diff --git a/README.md b/README.md index a6c4f8c..9d5e27c 100644 --- a/README.md +++ b/README.md @@ -189,12 +189,17 @@ These tools remain available to the CLI: - `seal_approval_documents_list`, `seal_approval_document_get`, `seal_approval_document_create`, `seal_approval_document_update`: maintain approval documents. - `seal_approval_style_preferences_get`, `seal_approval_style_preferences_update`: read and update approval style preferences. - `seal_approval_runs_summary`: summarize approval runs by local date and timezone. Use this for daily questions such as "what approval records did Tawen have today"; it returns status/task-mode counts and compact records. +- `seal_approval_run_get`: fetch one approval run. Pass `fields` such as `"metadata"` or `"document.fields,result.summary"` to avoid returning full document, pipeline, and AI output payloads. +- `seal_approval_run_attachments_get`: return attachment and invoice file metadata for one run without the full document or rule result. +- `seal_approval_run_result_get`: return one run result, with `{"summary":true}` for decision, summary, risk point count, matched rule count, trace ID, and record ID only. - `seal_approval_run_url_get`: return the Hose enterprise assist URL, optionally with the original document URL for an approval run by `recordId`, `sourceDocumentSN`, or `sourceDocumentId`. - `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`. - `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback. For rule list commands, prefer `seal-home rules count` or `seal-home rules list --summary` before requesting full rule descriptions. `seal-home rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large. +For approval run detail commands, prefer `seal-home approval-runs get --fields metadata`, `seal-home approval-runs attachments `, or `seal-home approval-runs result --summary` before requesting the full record. CLI JSON output is protected by a 200KB default limit; use `--output-file` for large payloads or `--full` only when the full response is intentional. Hose provisional auth links are available with `seal-home auth hose-link --corp --expire 7200`, which returns the unredacted `getProvisionalAuth` URL. + ## Approval Run To Langfuse Bridge Seal approval runs and simulation batch records are treated as two views over the same run data: diff --git a/skills/seal-home/SKILL.md b/skills/seal-home/SKILL.md index 0f6a94b..c7e52a2 100644 --- a/skills/seal-home/SKILL.md +++ b/skills/seal-home/SKILL.md @@ -38,9 +38,11 @@ Use `seal-home update` after pulling new versions; it restarts the service if it - For current identity or tenant: use `seal-home tool seal_whoami`. - For configured enterprises: use `seal-home corps list`. - For Hose login, SSO, or "Unable to connect" authentication failures: use `seal-home auth diagnose [--corp ]`. +- For an unredacted Hose provisional auth link: use `seal-home auth hose-link --corp --expire 7200`. - For source-derived enterprise config: use `seal-home source config`. - For daily approval run questions: use `seal-home approval-runs summary --date YYYY-MM-DD --timezone Asia/Shanghai`. - For approval run lookup by document SN, ID, status, mode, or trace: use `seal-home approval-runs search`. +- For compact approval run detail: use `seal-home approval-runs get --fields metadata`, `seal-home approval-runs attachments `, or `seal-home approval-runs result --summary`. - For Hose enterprise assist links: use `seal-home approval-runs url`; add `` or `--sourceDocumentSN B26001887` when a document link is also needed. - For Langfuse lookup hints: use `seal-home approval-runs bridge`. - For one simulation batch: use `seal-home simulation batch-records `. @@ -171,6 +173,9 @@ Preferred command forms: ```bash seal-home approval-runs summary --date 2026-06-09 --timezone Asia/Shanghai seal-home approval-runs search --query B26001887 --limit 20 --includeBridge true +seal-home approval-runs get --fields metadata,document.fields,result.summary +seal-home approval-runs attachments +seal-home approval-runs result --summary seal-home approval-runs url seal-home approval-runs url --sourceDocumentSN B26001887 seal-home approval-runs bridge --sourceDocumentSN B26001887 diff --git a/skills/seal-home/references/cli.md b/skills/seal-home/references/cli.md index d224d45..fa38e30 100644 --- a/skills/seal-home/references/cli.md +++ b/skills/seal-home/references/cli.md @@ -25,10 +25,14 @@ seal-home corps current seal-home corps switch seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home auth diagnose [--corp ] +seal-home auth hose-link [--corp ] [--expire 7200] seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] seal-home approval-runs search [--query text] [--limit 20] [--includeBridge true] +seal-home approval-runs get [--fields metadata|document.fields,result.summary] [--output-file file.json] +seal-home approval-runs attachments +seal-home approval-runs result [--summary] seal-home approval-runs url seal-home approval-runs url seal-home approval-runs url --sourceDocumentSN B26001887 @@ -68,6 +72,16 @@ Approval rule maintenance: - `seal_approval_rule_versions_list` - `seal_approval_rule_version_publish` +Approval run lightweight queries: + +- `seal-home approval-runs get --fields metadata` +- `seal-home approval-runs get --fields document.fields,result.summary` +- `seal-home approval-runs attachments ` +- `seal-home approval-runs result --summary` +- `seal_approval_run_get` with `fields` +- `seal_approval_run_attachments_get` +- `seal_approval_run_result_get` with `{"summary":true}` + Approval knowledge documents: - `seal_approval_documents_list` diff --git a/src/cli.ts b/src/cli.ts index 13acb9a..96f559d 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -12,6 +12,7 @@ import { getMe } from "./domains/seal/api.js"; import { sealTools, type SealTool } from "./domains/seal/tools.js"; import { CorpConfig } from "./core/config/types.js"; import { clearCorpTokenCache } from "./core/auth/token-store.js"; +import { getHoseProvisionalAuthLink } from "./core/auth/hose.js"; const VERSION = "0.3.0"; const APP_ROOT = dirname(dirname(fileURLToPath(import.meta.url))); @@ -22,6 +23,7 @@ const CURRENT_CORP_FILE = join(STATE_DIR, "current-corp"); const RULE_LIST_FULL_COUNT_LIMIT = 100; const RULE_LIST_FULL_BYTES_LIMIT = 120_000; const RULE_SUMMARY_FIELDS = ["id", "status", "strictness", "scope", "createdAt", "updatedAt"]; +const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000; type ParsedArgs = { command: string[]; @@ -29,6 +31,11 @@ type ParsedArgs = { json?: unknown; }; +type OutputOptions = { + allowFull?: boolean; + outputFile?: string; +}; + async function main() { const args = parseArgs(Bun.argv.slice(2)); const [area, action, maybeName] = args.command; @@ -122,24 +129,30 @@ async function main() { return; } + if (area === "auth" && action === "hose-link") { + const expiresIn = numberOption(args.options.expire) ?? 7200; + printJson(await getHoseProvisionalAuthLink(corp, expiresIn)); + return; + } + const client = await createSealClient(corp); if (area === "context") { await runTool("seal_approval_context_get", client, corp, { documentLimit: numberOption(args.options.documentLimit), ...ruleVersionContextOptions(stringOption(args.options.ruleVersion)) - }); + }, outputOptions(args.options)); return; } if (area === "rules" && action === "count") { - await runTool("seal_approval_rules_list", client, corp, { countOnly: true }); + await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); return; } if (area === "rules" && action === "list") { if (booleanOption(args.options.count)) { - await runTool("seal_approval_rules_list", client, corp, { countOnly: true }); + await runTool("seal_approval_rules_list", client, corp, { countOnly: true }, outputOptions(args.options)); return; } @@ -150,7 +163,7 @@ async function main() { fields: RULE_SUMMARY_FIELDS, limit, offset - }); + }, outputOptions(args.options)); return; } @@ -161,14 +174,14 @@ async function main() { } if (area === "rules" && action === "versions") { - await runTool("seal_approval_rule_versions_list", client, corp, {}); + await runTool("seal_approval_rule_versions_list", client, corp, {}, outputOptions(args.options)); return; } if (area === "rules" && action === "version") { const version = maybeName ?? stringOption(args.options.version); if (!version) throw new Error("Usage: seal-home rules version "); - await runTool("seal_approval_rule_version_get", client, corp, parseRuleVersionSelector(version)); + await runTool("seal_approval_rule_version_get", client, corp, parseRuleVersionSelector(version), outputOptions(args.options)); return; } @@ -182,13 +195,13 @@ async function main() { contextLines: numberOption(args.options.contextLines), refresh: booleanOption(args.options.refresh), ...ruleVersionSearchOptions(stringOption(args.options.version)) - }); + }, outputOptions(args.options)); return; } if (area === "tool") { if (!action) throw new Error("Usage: seal-home tool [--json '{...}']"); - await runTool(action, client, corp, jsonObject(args.json)); + await runTool(action, client, corp, jsonObject(args.json), outputOptions(args.options)); return; } @@ -206,7 +219,7 @@ async function main() { sourceDocumentId: stringOption(args.options.sourceDocumentId), humanResult: stringOption(args.options.humanResult), query: stringOption(args.options.query) - }); + }, outputOptions(args.options)); return; } @@ -224,7 +237,7 @@ async function main() { humanResult: stringOption(args.options.humanResult), query: stringOption(args.options.query), includeBridge: booleanOption(args.options.includeBridge) - }); + }, outputOptions(args.options)); return; } @@ -235,7 +248,7 @@ async function main() { sourceDocumentId: stringOption(args.options.sourceDocumentId), simulationBatchId: stringOption(args.options.simulationBatchId), limit: numberOption(args.options.limit) - }); + }, outputOptions(args.options)); return; } @@ -246,14 +259,34 @@ async function main() { query, limit: numberOption(args.options.limit), includeBridge: booleanOption(args.options.includeBridge) - }); + }, outputOptions(args.options)); return; } if (area === "approval-runs" && action === "get") { const recordId = args.command[2]; if (!recordId) throw new Error("Missing approval run recordId"); - await runTool("seal_approval_run_get", client, corp, { recordId }); + await runTool("seal_approval_run_get", client, corp, { + recordId, + fields: stringOption(args.options.fields) + }, outputOptions(args.options)); + return; + } + + if (area === "approval-runs" && action === "attachments") { + const recordId = args.command[2]; + if (!recordId) throw new Error("Usage: seal-home approval-runs attachments "); + await runTool("seal_approval_run_attachments_get", client, corp, { recordId }, outputOptions(args.options)); + return; + } + + if (area === "approval-runs" && action === "result") { + const recordId = args.command[2]; + if (!recordId) throw new Error("Usage: seal-home approval-runs result [--summary]"); + await runTool("seal_approval_run_result_get", client, corp, { + recordId, + summary: booleanOption(args.options.summary) + }, outputOptions(args.options)); return; } @@ -262,7 +295,7 @@ async function main() { recordId: maybeName, sourceDocumentSN: stringOption(args.options.sourceDocumentSN), sourceDocumentId: stringOption(args.options.sourceDocumentId) - }); + }, outputOptions(args.options)); return; } @@ -272,7 +305,7 @@ async function main() { await runTool("seal_simulation_batch_records_get", client, corp, { batchId, query: stringOption(args.options.query) - }); + }, outputOptions(args.options)); return; } @@ -417,9 +450,10 @@ async function runTool( name: string, client: Awaited>, corp: CorpConfig, - params: Record + params: Record, + options: OutputOptions = {} ) { - printJson(await runToolResult(name, client, corp, params)); + printJson(await runToolResult(name, client, corp, params), options); } async function runToolResult( @@ -457,6 +491,23 @@ function protectLargeRuleListOutput(result: unknown, allowFull: boolean) { } } +function protectLargeOutput(result: unknown, options: OutputOptions = {}) { + if (options.allowFull || options.outputFile) return; + const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8"); + if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) { + throw new Error( + `Output is large (${bodyBytes} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.` + ); + } +} + +function outputOptions(options: Record): OutputOptions { + return { + allowFull: booleanOption(options.full) === true, + outputFile: stringOption(options.outputFile) ?? stringOption(options["output-file"]) + }; +} + function selectCorp(corpId: string): CorpConfig { const corps = loadCorpConfigs(); const selectedCorpId = corpId || readCurrentCorpId() || ""; @@ -996,8 +1047,15 @@ function appendLog(message: string) { writeFileSync(SERVICE_LOG_FILE, `${new Date().toISOString()} ${message}\n`, { flag: "a" }); } -function printJson(value: unknown) { - console.log(JSON.stringify(value, null, 2)); +function printJson(value: unknown, options: OutputOptions = {}) { + protectLargeOutput(value, options); + const json = `${JSON.stringify(value, null, 2)}\n`; + if (options.outputFile) { + writeFileSync(options.outputFile, json); + console.log(JSON.stringify({ outputFile: options.outputFile, bytes: Buffer.byteLength(json, "utf-8") }, null, 2)); + return; + } + console.log(json.trimEnd()); } function printHelp() { @@ -1014,6 +1072,7 @@ Usage: seal-home corps switch seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}' seal-home auth diagnose [--corp ] + seal-home auth hose-link [--corp ] [--expire 7200] seal-home source config [--corp ] seal-home tool [--corp ] [--json '{"key":"value"}'] seal-home rules count [--corp ] @@ -1025,7 +1084,9 @@ Usage: seal-home approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] seal-home approval-runs search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] seal-home approval-runs pick [--limit 20] - seal-home approval-runs get + seal-home approval-runs get [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] + seal-home approval-runs attachments + seal-home approval-runs result [--summary] seal-home approval-runs url seal-home approval-runs url seal-home approval-runs url --sourceDocumentSN B26022501 diff --git a/src/core/auth/hose.ts b/src/core/auth/hose.ts index be3b396..75113c7 100644 --- a/src/core/auth/hose.ts +++ b/src/core/auth/hose.ts @@ -128,7 +128,8 @@ async function ensureHoseOpenapiToken(corp: CorpConfig): Promise { async function fetchHoseCloseApiToken( source: HoseSealSource, - openapiToken: string + openapiToken: string, + expiresIn = 7200 ): Promise { const client = hoseClient(source); const uid = hoseUid(source); @@ -141,7 +142,7 @@ async function fetchHoseCloseApiToken( json: { uid, pageType: "home", - expireDate: 7200 + expireDate: expiresIn } }) .json(); @@ -159,7 +160,7 @@ async function fetchHoseCloseApiToken( return { token: closeapiToken, url, - expiresAt: Date.now() + 7200 * 1000 + expiresAt: Date.now() + expiresIn * 1000 }; } @@ -194,6 +195,33 @@ export async function getHoseEnterpriseUrl(corp: CorpConfig): Promise { return url; } +export async function getHoseProvisionalAuthLink( + corp: CorpConfig, + expiresIn = 7200 +): Promise<{ + corpId: string; + staffId: string; + url: string; + expiresIn: number; +}> { + if (corp.source.type !== "hose") { + throw new Error(`Unsupported Seal source: ${corp.source.type}`); + } + + const openapiToken = await ensureHoseOpenapiToken(corp); + const provisional = await fetchHoseCloseApiToken(corp.source, openapiToken, expiresIn); + if (!provisional.url) { + throw new Error("Hose provisional auth URL was not available"); + } + + return { + corpId: corp.source.corpId, + staffId: corp.source.staffId, + url: provisional.url, + expiresIn + }; +} + export async function getHoseSealSession(corp: CorpConfig): Promise { if (corp.source.type !== "hose") { throw new Error(`Unsupported Seal source: ${corp.source.type}`); diff --git a/src/domains/seal/tools.test.ts b/src/domains/seal/tools.test.ts index a28acbe..7901443 100644 --- a/src/domains/seal/tools.test.ts +++ b/src/domains/seal/tools.test.ts @@ -255,6 +255,81 @@ describe("sealTools", () => { }); }); + test("approval run get can return selected fields only", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1", fields: "metadata,document.fields,result.summary" }, + fakeContext() + ) as { + metadata?: { recordId?: string }; + document?: { fields?: unknown[] }; + result?: { summary?: string; manualApproval?: unknown }; + pipelineData?: unknown; + }; + + expect(result.metadata?.recordId).toBe("run-1"); + expect(result.document?.fields).toHaveLength(1); + expect(result.result?.summary).toBe("费用存在风险"); + expect(result.result?.manualApproval).toBeUndefined(); + expect(result.pipelineData).toBeUndefined(); + }); + + test("approval run attachments extracts compact attachment metadata", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_attachments_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1" }, + fakeContext() + ) as { count: number; attachments: Array> }; + + expect(result.count).toBe(2); + expect(result.attachments).toContainEqual(expect.objectContaining({ + kind: "attachment", + fileName: "receipt.pdf", + fileId: "file-1", + mimeType: "application/pdf", + ossPath: "oss://bucket/receipt.pdf" + })); + expect(result.attachments).toContainEqual(expect.objectContaining({ + kind: "invoice", + fileName: "invoice.png", + url: "https://signed.example/invoice.png" + })); + }); + + test("approval run result can return summary only", async () => { + const tool = sealTools.find((item) => item.name === "seal_approval_run_result_get"); + expect(tool).toBeDefined(); + + const handler = tool!.handler as ToolHandler; + const result = await handler( + fakeApprovalRunsClient(), + { recordId: "run-1", summary: true }, + fakeContext() + ) as { + decision?: string; + summary?: string; + riskPointCount?: number; + matchedRuleCount?: number; + traceId?: string; + }; + + expect(result).toMatchObject({ + decision: "驳回", + summary: "费用存在风险", + riskPointCount: 2, + matchedRuleCount: 1, + traceId: "trace-1" + }); + }); + test("approval run url returns Hose enterprise and document links by recordId", async () => { const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get"); expect(tool).toBeDefined(); @@ -371,12 +446,34 @@ function fakeApprovalRunsClient(requests: string[] = []): KyInstance { id: "normalized-doc-1", sourceDocumentSN: "B26001965", sourceDocumentId: "doc-source-1", - fields: [] + fields: [ + { + label: "附件", + attachments: [ + { + fileName: "receipt.pdf", + fileId: "file-1", + mimeType: "application/pdf", + ossPath: "oss://bucket/receipt.pdf" + } + ] + } + ] }, result: { + summary: "费用存在风险", + riskPoints: ["金额异常", "附件缺失"], + matchedRules: [{ id: "rule-1" }], manualApproval: { result: "驳回" - } + }, + invoices: [ + { + fileName: "invoice.png", + mimeType: "image/png", + signedUrl: "https://signed.example/invoice.png" + } + ] }, pipelineData: { logs: "audit logs" diff --git a/src/domains/seal/tools.ts b/src/domains/seal/tools.ts index 72ee033..bf0b5ff 100644 --- a/src/domains/seal/tools.ts +++ b/src/domains/seal/tools.ts @@ -461,7 +461,28 @@ export const sealTools = [ }, { name: "seal_approval_run_get", - description: "获取 Seal 单条审批/审核运行记录详情,用于查看 result、pipelineData 等列表接口省略的字段", + description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段", + parameters: z.object({ + recordId: z.string().describe("Seal approval run record ID"), + fields: z.union([z.string(), z.array(z.string())]).optional().describe("逗号分隔或数组形式的字段路径,如 metadata、document.fields、result.summary") + }), + handler: async ( + client: KyInstance, + params: { recordId: string; fields?: string | string[] } + ) => { + const record = await api.getApprovalRun(client, params.recordId); + const full = { + ...record, + aliases: approvalRunAliases(record), + humanResult: extractHumanResult(record) + }; + const fields = parseFieldPaths(params.fields); + return fields.length > 0 ? pickRunFields(full, fields) : full; + } + }, + { + name: "seal_approval_run_attachments_get", + description: "从审批运行记录中抽取附件、发票附件和字段位置,不返回完整单据正文和规则结果", parameters: z.object({ recordId: z.string().describe("Seal approval run record ID") }), @@ -470,10 +491,25 @@ export const sealTools = [ params: { recordId: string } ) => { const record = await api.getApprovalRun(client, params.recordId); + return extractApprovalRunAttachments(record); + } + }, + { + name: "seal_approval_run_result_get", + description: "返回审批运行结果摘要;summary=true 时只返回 decision、summary、风险点数量、命中规则数量、traceId 等", + parameters: z.object({ + recordId: z.string().describe("Seal approval run record ID"), + summary: z.boolean().optional() + }), + handler: async ( + client: KyInstance, + params: { recordId: string; summary?: boolean } + ) => { + const record = await api.getApprovalRun(client, params.recordId); + if (params.summary) return summarizeApprovalRunResult(record); return { - ...record, - aliases: approvalRunAliases(record), - humanResult: extractHumanResult(record) + recordId: record.id, + result: record.result }; } }, @@ -907,6 +943,219 @@ function summarizeApprovalRuns(records: ApprovalRun[], options: ApprovalRunsSumm }; } +function parseFieldPaths(fields: string | string[] | undefined): string[] { + if (!fields) return []; + const raw = Array.isArray(fields) ? fields : fields.split(","); + return raw.map((field) => field.trim()).filter(Boolean); +} + +function pickRunFields(record: Record, fields: readonly string[]) { + const output: Record = {}; + for (const field of fields) { + if (field === "metadata") { + output.metadata = approvalRunMetadata(record as ApprovalRun); + continue; + } + const value = getPath(record, field); + if (value !== undefined) setPath(output, field, value); + } + return output; +} + +function approvalRunMetadata(record: ApprovalRun) { + const summary = summarizeApprovalRun(record); + return { + recordId: summary.id, + tenantId: summary.tenantId, + agentId: summary.agentId, + sourceSystem: summary.sourceSystem, + sourceDocumentSN: summary.sourceDocumentSN, + sourceDocumentId: summary.sourceDocumentId, + documentId: summary.documentId, + status: summary.status, + taskMode: summary.taskMode, + finalExecutionMode: summary.finalExecutionMode, + simulationBatchId: summary.simulationBatchId, + langfuseTraceId: summary.langfuseTraceId, + langfuseSessionFallback: summary.langfuseSessionFallback, + ruleSetVersionNumber: summary.ruleSetVersionNumber, + ruleSetPublishedAt: summary.ruleSetPublishedAt, + ruleSetPublishedByName: summary.ruleSetPublishedByName, + createdAt: summary.createdAt, + updatedAt: summary.updatedAt + }; +} + +function summarizeApprovalRunResult(record: ApprovalRun) { + const result = asRecord(record.result); + return { + recordId: record.id, + sourceDocumentSN: record.sourceDocumentSN, + sourceDocumentId: record.sourceDocumentId, + traceId: record.sourceExtendData?._langfuseTraceId, + langfuseTraceId: record.sourceExtendData?._langfuseTraceId, + decision: firstPath(result, [ + "decision", + "manualApproval.decision", + "manualApproval.result", + "review.decision", + "finalDecision" + ]), + summary: firstPath(result, [ + "summary", + "result.summary", + "review.summary", + "conclusion" + ]), + riskPointCount: countPathCandidates(result, [ + "riskPoints", + "risks", + "risk_points", + "review.riskPoints" + ]), + matchedRuleCount: countPathCandidates(result, [ + "matchedRules", + "hitRules", + "ruleResults", + "rules", + "review.matchedRules" + ]) + }; +} + +function extractApprovalRunAttachments(record: ApprovalRun) { + const roots: Array<[string, unknown]> = [ + ["document", record.document], + ["result", record.result], + ["pipelineData", record.pipelineData], + ["sourceExtendData", record.sourceExtendData] + ]; + const attachments: Array> = []; + const seen = new Set(); + + for (const [path, value] of roots) { + collectAttachments(value, path, attachments, seen); + } + + return { + recordId: record.id, + sourceDocumentSN: record.sourceDocumentSN, + sourceDocumentId: record.sourceDocumentId, + count: attachments.length, + attachments + }; +} + +function collectAttachments( + value: unknown, + path: string, + output: Array>, + seen: Set +) { + if (Array.isArray(value)) { + value.forEach((item, index) => collectAttachments(item, `${path}.${index}`, output, seen)); + return; + } + + const object = asRecord(value); + if (!object) return; + + if (looksLikeAttachment(object, path)) { + const attachment = compactObject({ + path, + fieldPath: path, + kind: inferAttachmentKind(path, object), + fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.originalName), + mimeType: stringFromUnknown(object.mimeType) ?? stringFromUnknown(object.mimetype) ?? stringFromUnknown(object.contentType), + fileId: stringFromUnknown(object.fileId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.attachmentId), + ossPath: stringFromUnknown(object.ossPath) ?? stringFromUnknown(object.ossKey) ?? stringFromUnknown(object.key), + url: stringFromUnknown(object.url) ?? stringFromUnknown(object.signedUrl) ?? stringFromUnknown(object.downloadUrl) ?? stringFromUnknown(object.previewUrl), + invoiceId: stringFromUnknown(object.invoiceId), + sourceField: stringFromUnknown(object.fieldName) ?? stringFromUnknown(object.label) + }); + const key = JSON.stringify(attachment); + if (!seen.has(key)) { + seen.add(key); + output.push(attachment); + } + } + + for (const [key, child] of Object.entries(object)) { + collectAttachments(child, `${path}.${key}`, output, seen); + } +} + +function looksLikeAttachment(object: Record, path: string) { + const keys = Object.keys(object).map((key) => key.toLowerCase()); + const pathHint = /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(path); + const fileHints = ["filename", "fileName", "mimeType", "mimetype", "contentType", "fileId", "ossPath", "signedUrl", "downloadUrl", "previewUrl", "attachmentId"]; + return pathHint && fileHints.some((key) => keys.includes(key.toLowerCase())); +} + +function inferAttachmentKind(path: string, object: Record) { + const normalized = `${path} ${stringFromUnknown(object.type) ?? ""}`.toLowerCase(); + if (normalized.includes("invoice") || normalized.includes("发票")) return "invoice"; + if (normalized.includes("receipt")) return "receipt"; + return "attachment"; +} + +function firstPath(object: Record | undefined, paths: readonly string[]) { + if (!object) return undefined; + for (const path of paths) { + const value = getPath(object, path); + if (value !== undefined) return value; + } + return undefined; +} + +function countPathCandidates(object: Record | undefined, paths: readonly string[]) { + if (!object) return 0; + for (const path of paths) { + const value = getPath(object, path); + if (Array.isArray(value)) return value.length; + if (value && typeof value === "object") return Object.keys(value).length; + if (typeof value === "number") return value; + } + return 0; +} + +function getPath(value: unknown, path: string): unknown { + return path.split(".").reduce((current, segment) => { + if (current === undefined || current === null) return undefined; + if (Array.isArray(current)) { + const index = Number(segment); + return Number.isInteger(index) ? current[index] : undefined; + } + if (typeof current === "object") { + return (current as Record)[segment]; + } + return undefined; + }, value); +} + +function setPath(target: Record, path: string, value: unknown) { + const segments = path.split("."); + let current = target; + for (const segment of segments.slice(0, -1)) { + const existing = current[segment]; + if (!existing || typeof existing !== "object" || Array.isArray(existing)) { + current[segment] = {}; + } + current = current[segment] as Record; + } + current[segments[segments.length - 1] ?? path] = value; +} + +function compactObject(object: Record) { + return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined)); +} + +function asRecord(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : undefined; +} + function summarizeRunBridge(records: ApprovalRun[]) { return records.map((record) => { const summary = summarizeApprovalRun(record);