import { z } from "zod"; import type { KyInstance } from "ky"; import { readFileSync } from "node:fs"; import * as api from "../api.js"; import { type SimulationBatch } from "../types.js"; import * as helpers from "./helpers.js"; const { parseDurationMs, buildSimulationBatchParams, summarizeSimulationBatch, summarizeApprovalRun, findReusableSimulationBatch, simulationBatchCreatedAtMs, summarizeRunBridge, filterRuns } = helpers; export const simulationCapabilities = [ { name: "seal_simulation_feishu_approval_definitions_list", description: "列出飞书模拟测试可用的审批定义,便于选择 approvalCode", parameters: z.object({}), handler: async (client: KyInstance) => { const approvalDefinitions = await api.listFeishuSimulationApprovalDefinitions(client); return { count: approvalDefinitions.length, approvalDefinitions }; } }, { name: "seal_simulation_batch_records_get", description: "获取某一次 Seal 模拟批次的运行记录,并整理对应 Langfuse trace/session 桥接字段", parameters: z.object({ batchId: z.string().describe("simulation batch ID"), query: z.string().optional().describe("在 id、sourceDocumentSN、sourceDocumentId、documentId、Langfuse traceId 中做本地包含匹配") }), handler: async ( client: KyInstance, params: { batchId: string; query?: string } ) => { const records = filterRuns( await api.listSimulationBatchRecords(client, params.batchId), params.query ); return { batchId: params.batchId, count: records.length, records: records.map(summarizeApprovalRun), bridge: summarizeRunBridge(records) }; } }, { name: "seal_simulation_batch_create", description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;默认幂等:复用窗口内同 flow-ids/packageIds 的既有批次直接返回不重复扣费(--force 跳过);其他取数模式通过 rawParams 预留透传。", parameters: z.object({ mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"), flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"), rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"), thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"), skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"), skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"), disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"), signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"), packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"), templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1; 缺省取 schemaConfig.id"), schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"), noWait: z.boolean().optional().describe("创建后立即返回异步票据,不等待批次完成"), force: z.boolean().optional().describe("跳过同单幂等复用检查, 强制创建新批次"), reuseWindow: z.string().optional().describe("幂等复用检查时间窗(如 5m/10m), 默认 5m, 设为 0 关闭复用检查"), rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果") }), handler: async ( client: KyInstance, params: { mode?: "hosecloud" | "material_pack"; flowIds?: string[]; rejectNodeName?: string | null; thinkingDepthOverride?: "default" | "medium" | "high"; skipInvoiceGeneration?: boolean; skipExpenseExtraction?: boolean; disableAttachmentCache?: boolean; signKey?: string; packageIds?: string[]; templateId?: string; schemaConfig?: Record; noWait?: boolean; force?: boolean; reuseWindow?: string; rawParams?: Record; } ) => { const mode = params.mode ?? "hosecloud"; let signKey = params.signKey; if (mode === "hosecloud" && !signKey) { const integrations = await api.listSimulationHosecloudIntegrations(client); signKey = integrations.find((item) => item.signKey)?.signKey; if (!signKey) { throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供"); } } const payload = buildSimulationBatchParams({ mode, flowIds: params.flowIds, rejectNodeName: params.rejectNodeName, thinkingDepthOverride: params.thinkingDepthOverride, skipInvoiceGeneration: params.skipInvoiceGeneration, skipExpenseExtraction: params.skipExpenseExtraction, disableAttachmentCache: params.disableAttachmentCache, signKey, packageIds: params.packageIds, templateId: params.templateId, schemaConfig: params.schemaConfig, rawParams: params.rawParams }); // 幂等复用: 打断/重试场景下避免同一组单号重复创建批次导致重复扣费 const reuseWindowMs = params.force ? 0 : parseDurationMs(params.reuseWindow ?? "5m"); if (reuseWindowMs > 0 && (params.flowIds?.length || params.packageIds?.length)) { let reusable: SimulationBatch | null = null; try { reusable = findReusableSimulationBatch( await api.listSimulationBatches(client, { limit: 50 }), { flowIds: params.flowIds, packageIds: params.packageIds, signKey }, reuseWindowMs ); } catch (error) { console.error( `⚠️ [Simulation] 幂等复用检查失败, 将按原计划创建新批次: ${error instanceof Error ? error.message : String(error)}` ); } if (reusable) { const createdAtMs = simulationBatchCreatedAtMs(reusable); const ageSeconds = createdAtMs === null ? undefined : Math.max(0, Math.round((Date.now() - createdAtMs) / 1000)); console.error( `♻️ [Simulation] 检测到 ${ageSeconds ?? "?"}s 前已创建同单批次 ${reusable.id}(status=${reusable.status ?? "unknown"}),复用该批次, 不重复创建以避免重复扣费;确需重跑请加 --force` ); return { batchId: reusable.id, created: false, reused: true, reuseWindow: params.reuseWindow ?? "5m", message: "已存在同单批次, 已复用既有批次, 未创建新批次(不重复扣费)", matchedBatch: { id: reusable.id, status: reusable.status, createdAt: reusable.createdAt, ageSeconds, flowIds: reusable.params?.flowIds, packageIds: reusable.params?.packageIds }, noWait: params.noWait ?? true, asyncTicket: reusable.id, next: { status: `seal-use simulation status ${reusable.id}`, wait: `seal-use simulation wait ${reusable.id}`, getBatch: `seal-use simulation get ${reusable.id}`, getRecords: `seal-use simulation batch-records ${reusable.id}`, listBatches: "seal-use simulation list" } }; } } const result = mode === "material_pack" ? await api.createMaterialPackBatch(client, payload) : await api.createSimulationBatch(client, payload); return { ...result, created: true, noWait: params.noWait ?? true, asyncTicket: result.batchId, next: { status: `seal-use simulation status ${result.batchId}`, wait: `seal-use simulation wait ${result.batchId}`, getBatch: `seal-use simulation get ${result.batchId}`, getRecords: `seal-use simulation batch-records ${result.batchId}`, listBatches: "seal-use simulation list" } }; } }, { name: "seal_simulation_batches_list", description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)", parameters: z.object({ limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50") }), handler: async (client: KyInstance, params: { limit?: number }) => { const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 }); return { count: batches.length, batches: batches.map(summarizeSimulationBatch), next: { getBatch: "seal-use simulation get ", getRecords: "seal-use simulation batch-records " } }; } }, { name: "seal_simulation_batch_get", description: "获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计", parameters: z.object({ batchId: z.string().describe("simulation batch ID") }), handler: async (client: KyInstance, params: { batchId: string }) => { const batch = await api.getSimulationBatch(client, params.batchId); return { batch, next: { getRecords: "seal-use simulation batch-records " } }; } }, { name: "seal_simulation_batch_status", description: "单次读取 Seal 模拟批次状态,不阻塞等待;适合根据异步票据轮询", parameters: z.object({ batchId: z.string().describe("simulation batch ID") }), handler: async (client: KyInstance, params: { batchId: string }) => { const batch = await api.getSimulationBatch(client, params.batchId); const status = String(batch.status ?? "UNKNOWN").toUpperCase(); const terminal = ["COMPLETED", "FAILED", "CANCELLED", "CANCELED"].includes(status); return { batchId: params.batchId, status, terminal, totalCount: batch.totalCount, processedCount: batch.processedCount, successCount: batch.successCount, failedCount: batch.failedCount, createdAt: batch.createdAt, updatedAt: batch.updatedAt, next: terminal ? { getRecords: `seal-use simulation batch-records ${params.batchId}` } : { status: `seal-use simulation status ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` } }; } }, { name: "seal_simulation_templates_get", description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)", parameters: z.object({}), handler: async (client: KyInstance) => { const templates = await api.listSimulationTemplates(client); return { count: templates.length, templates: templates.map((template) => ({ id: template.id, name: template.name, description: template.description, approvalSystem: template.approvalSystem, hosecloudConfig: template.hosecloudConfig, updatedAt: template.updatedAt })), next: { createBatch: "seal-use simulation create --mode hosecloud --flow-ids ..." } }; } }, { name: "seal_simulation_integrations_get", description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)", parameters: z.object({}), handler: async (client: KyInstance) => { const [status, hosecloudIntegrations] = await Promise.all([ api.getSimulationIntegrationStatus(client), api.listSimulationHosecloudIntegrations(client) ]); return { status, hosecloudIntegrations }; } }, { name: "seal_simulation_material_package_upload", description: "上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)", parameters: z.object({ filePath: z.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)") }), handler: async (client: KyInstance, params: { filePath?: string }) => { if (!params.filePath) { throw new Error("filePath is required"); } const fileBuffer = readFileSync(params.filePath); const fileName = params.filePath.split(/[\\/]/).pop() ?? "material-pack.zip"; const materialPackage = await api.uploadMaterialPackage(client, { fileName, fileBuffer }); return { materialPackage, next: { createBatch: `seal-use simulation create --mode material_pack --package-ids ${materialPackage.id} --schema-config schema.json` } }; } }, { name: "seal_simulation_batch_wait", description: "等待 Seal 模拟测试批次完成(轮询状态直到 completed/failed/canceled 或超时)", parameters: z.object({ batchId: z.string().describe("模拟批次 ID"), timeout: z.string().default("10m").describe("最长等待时间, 默认 10m"), pollInterval: z.string().default("2s").describe("轮询间隔, 默认 2s") }), handler: async (client: KyInstance, params: { batchId: string; timeout?: string; pollInterval?: string }) => { const timeoutMs = parseDurationMs(params.timeout ?? "10m"); const pollIntervalMs = parseDurationMs(params.pollInterval ?? "2s"); const startedAt = Date.now(); console.error( `⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...` ); while (true) { const batch = await api.getSimulationBatch(client, params.batchId); const status = (batch.status ?? "").toLowerCase(); if (["completed", "failed", "cancelled", "canceled"].includes(status)) { return { batch, completed: true, status, elapsedMs: Date.now() - startedAt, next: { getRecords: `seal-use simulation batch-records ${params.batchId}` } }; } if (Date.now() - startedAt >= timeoutMs) { throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`); } await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); } } }, { name: "seal_simulation_batch_clean", description: "删除模拟测试批次产生的测试数据", parameters: z.object({ batchId: z.string().describe("模拟批次 ID") }), handler: async (client: KyInstance, params: { batchId: string }) => { const result = await api.cleanSimulationBatch(client, params.batchId); return { batchId: params.batchId, cleaned: true, result }; } }, { name: "seal_simulation_specifications_list", description: "列出指定合思集成可用的单据模板列表", parameters: z.object({ signKey: z.string().optional().describe("合思集成 sign-key") }), handler: async (client: KyInstance, params: { signKey?: string }) => { const specifications = await api.listSimulationSpecifications(client, params.signKey); return { count: specifications.length, specifications }; } } ];