import { validationError } from "../../../core/errors.js"; import { z } from "zod"; import type { KyInstance } from "ky"; import { readFileSync } from "node:fs"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import * as api from "../api.js"; import { type SimulationBatch } from "../types.js"; import * as helpers from "./helpers.js"; import { parseDurationMs } from "../../../core/duration.js"; import { batchTimestampMs, collectSimulationBatches, DEFAULT_SIMULATION_MAX_SCAN, DEFAULT_SIMULATION_SCAN_LIMIT, filterSimulationBatches, MAX_SIMULATION_SCAN, parseSimulationTimeBound } from "../simulation/batch-search.js"; const { buildSimulationBatchParams, summarizeSimulationBatch, summarizeApprovalRun, findReusableSimulationBatch, simulationBatchCreatedAtMs, summarizeRunBridge, filterRuns } = helpers; /** * 列表/检索的统一展示: 时间统一成北京时间秒级(附 epoch 毫秒便于精确比较), * 并带上单号/材料包标识, 让检索结果无需二次 get 就能对上界面里的任务。 */ function presentSimulationBatch(batch: SimulationBatch) { const createdAtMs = batchTimestampMs(batch.createdAt); const updatedAtMs = batchTimestampMs(batch.updatedAt); return { ...summarizeSimulationBatch(batch), createdAt: createdAtMs === null ? (batch.createdAt ?? null) : formatBeijingIso(createdAtMs), createdAtMs, updatedAt: updatedAtMs === null ? (batch.updatedAt ?? null) : formatBeijingIso(updatedAtMs), flowIds: batch.params?.flowIds ?? [], packageIds: batch.params?.packageIds ?? [], packageLabel: batch.params?.packageLabel ?? null, templateId: batch.params?.templateId ?? null }; } export const simulationCapabilities = [ { name: "sealSimulationFeishuApprovalDefinitionsList", description: "列出飞书模拟测试可用的审批定义,便于选择 approvalCode", parameters: z.object({}), handler: async (client: KyInstance) => { const approvalDefinitions = await api.listFeishuSimulationApprovalDefinitions(client); return { count: approvalDefinitions.length, approvalDefinitions }; } }, { name: "sealSimulationBatchRecordsGet", 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: "sealSimulationBatchCreate", 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 validationError("未找到合思集成 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: "sealSimulationBatchesList", description: "【本地聚合检索, 非云端原生能力】列出或检索 Seal 模拟测试批次摘要。服务端 /simulation/batches 只支持 limit/offset, 没有名称/关键词检索, 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是 UUID 末 8 位)。CLI 先把批次拉到本地再按关键词与时间窗过滤, 结果完整度取决于 scanned 范围: 默认扫描最近 50 个批次, all=true 分页扫到底。返回体带 retrieval.mode=local_scan / serverSideSearch=false 标记, 不要把它当成服务端搜索。", parameters: z.object({ limit: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional() .describe(`本地扫描的最近批次数量(不是返回条数上限), 默认 ${DEFAULT_SIMULATION_SCAN_LIMIT}`), all: z.boolean().optional() .describe(`分页扫描到底(仍受 maxScan 保护), 用于检索较早批次`), maxScan: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional() .describe(`all=true 时的扫描上限, 默认 ${DEFAULT_SIMULATION_MAX_SCAN}`), query: z.string().optional() .describe("本地关键词检索(CLI 端过滤, 非服务端): 空格/逗号分隔的多个关键词同时命中(AND); 匹配批次 ID(含无连字符形式)、界面「任务」后缀、单号、材料包/模板、条件摘要等"), since: z.string().optional() .describe("创建时间下界(含): ISO、YYYY-MM-DD、毫秒, 或相对时长如 7d"), until: z.string().optional() .describe("创建时间上界(含): 格式同 since") }), handler: async ( client: KyInstance, params: { limit?: number; all?: boolean; maxScan?: number; query?: string; since?: string; until?: string; } ) => { const sinceMs = parseSimulationTimeBound(params.since, { endOfDay: false }); const untilMs = parseSimulationTimeBound(params.until, { endOfDay: true }); const scanLimit = params.all ? (params.maxScan ?? DEFAULT_SIMULATION_MAX_SCAN) : (params.limit ?? DEFAULT_SIMULATION_SCAN_LIMIT); const { batches, capped } = await collectSimulationBatches(client, scanLimit); const matched = filterSimulationBatches(batches, { query: params.query, sinceMs, untilMs }); const searching = Boolean(params.query?.trim()) || sinceMs !== undefined || untilMs !== undefined; if (searching) { console.error( `ℹ️ [Simulation] 本地聚合检索(非云端原生): 服务端无关键词/名称检索, 已拉取最近 ${batches.length} 个批次并在本地过滤。` ); } if (capped) { console.error( `🔎 [Simulation] 已扫描 ${batches.length} 个批次(达到扫描上限), 更早的批次未参与检索; 可用 --all 或调大 --max-scan。` ); } return { retrieval: { mode: "local_scan", serverSideSearch: false, scanned: batches.length, note: searching ? "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次结果是 CLI 本地拉取后过滤, 命中范围以 scanned 为准, 不代表服务端全量。" : "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次仅列出最近 scanned 个批次, 不代表服务端全量。" }, scanned: batches.length, scanLimit, truncated: capped, filters: { query: params.query ?? null, since: sinceMs === undefined ? null : formatBeijingIso(sinceMs), until: untilMs === undefined ? null : formatBeijingIso(untilMs) }, count: matched.length, batches: matched.map(presentSimulationBatch), next: { getBatch: "seal-use simulation get ", getRecords: "seal-use simulation batch-records ", search: "seal-use simulation search <关键词> [--since 7d] [--all] (本地检索)" } }; } }, { name: "sealSimulationBatchGet", 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: "sealSimulationBatchStatus", 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: "sealSimulationTemplatesGet", 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: "sealSimulationIntegrationsGet", 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: "sealSimulationMaterialPackageUpload", 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: "sealSimulationBatchWait", 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} 查看进度)...` ); let retryCount = 0; while (true) { let batch; try { batch = await api.getSimulationBatch(client, params.batchId); } catch (err: unknown) { const isInitialPhase = Date.now() - startedAt < 15000; const statusStr = String( (err && typeof err === "object" && "status" in err ? (err as { status: unknown }).status : "") ?? (err instanceof Error ? err.message : "") ); const isNotFoundOrForbidden = statusStr.includes("403") || statusStr.includes("404") || statusStr.toLowerCase().includes("not found"); if (isInitialPhase && isNotFoundOrForbidden && retryCount < 4) { retryCount++; console.error( `⏳ [Simulation] 批次 ${params.batchId} 刚创建,等待服务端落库就绪 (重试 ${retryCount}/4)...` ); await new Promise((resolve) => setTimeout(resolve, 2000)); continue; } throw err; } 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) { console.error( `⏳ [Simulation] 批次 ${params.batchId} 等待超时(已等待 ${(Date.now() - startedAt) / 1000}s)。批次仍在服务端执行中。` ); return { batchId: params.batchId, completed: false, timedOut: true, status: status || "running", elapsedMs: Date.now() - startedAt, message: `等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。任务仍在后台执行。`, next: { status: `seal-use simulation status ${params.batchId}`, getRecords: `seal-use simulation batch-records ${params.batchId}`, wait: `seal-use simulation wait ${params.batchId}` } }; } await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); } } }, { name: "sealSimulationBatchClean", description: "删除模拟测试批次产生的测试数据", parameters: z.object({ batchId: z.string().describe("模拟批次 ID"), dryRun: z.boolean().optional().describe("仅预览批次当前状态与将被清理的数据,不执行删除") }), handler: async (client: KyInstance, params: { batchId: string; dryRun?: boolean }) => { if (params.dryRun) { const before = await api.getSimulationBatch(client, params.batchId).catch(() => undefined); return { preview: true, dryRun: true, mutation: "sealSimulationBatchClean", batchId: params.batchId, cleaned: 0, before }; } const result = await api.cleanSimulationBatch(client, params.batchId); return { batchId: params.batchId, cleaned: true, result }; } }, { name: "sealSimulationSpecificationsList", 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 }; } } ];