Add compact approval run queries
This commit is contained in:
1 parent
97c89351e6
commit
c29ff37a49
7 files changed
+488
-29
No files matched your search
@@ -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 <recordId> --fields metadata`, `seal-home approval-runs attachments <recordId>`, or `seal-home approval-runs result <recordId> --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 <corpId> --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:
|
||||
|
||||
@@ -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 <corpId>]`.
|
||||
- For an unredacted Hose provisional auth link: use `seal-home auth hose-link --corp <corpId> --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 <recordId> --fields metadata`, `seal-home approval-runs attachments <recordId>`, or `seal-home approval-runs result <recordId> --summary`.
|
||||
- For Hose enterprise assist links: use `seal-home approval-runs url`; add `<recordId>` 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 <batchId>`.
|
||||
@@ -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 <recordId> --fields metadata,document.fields,result.summary
|
||||
seal-home approval-runs attachments <recordId>
|
||||
seal-home approval-runs result <recordId> --summary
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url --sourceDocumentSN B26001887
|
||||
seal-home approval-runs bridge --sourceDocumentSN B26001887
|
||||
|
||||
@@ -25,10 +25,14 @@ seal-home corps current
|
||||
seal-home corps switch <corpId>
|
||||
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
|
||||
seal-home auth diagnose [--corp <corpId>]
|
||||
seal-home auth hose-link [--corp <corpId>] [--expire 7200]
|
||||
seal-home source config [--corp <corpId>]
|
||||
seal-home tool <toolName> [--corp <corpId>] [--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 <recordId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
|
||||
seal-home approval-runs attachments <recordId>
|
||||
seal-home approval-runs result <recordId> [--summary]
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url <recordId>
|
||||
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 <recordId> --fields metadata`
|
||||
- `seal-home approval-runs get <recordId> --fields document.fields,result.summary`
|
||||
- `seal-home approval-runs attachments <recordId>`
|
||||
- `seal-home approval-runs result <recordId> --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`
|
||||
|
||||
+81
-20
@@ -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 <versionId|versionNumber|latest>");
|
||||
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 <toolName> [--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 <recordId>");
|
||||
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 <recordId> [--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<ReturnType<typeof createSealClient>>,
|
||||
corp: CorpConfig,
|
||||
params: Record<string, unknown>
|
||||
params: Record<string, unknown>,
|
||||
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<string, string | boolean>): 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 <corpId>
|
||||
seal-home corps add-hose --json '{"name":"企业名称","domain":"https://app.ekuaibao.com","appKey":"...","appSecurity":"...","proxyStaffBizId":"corpId:staffId"}'
|
||||
seal-home auth diagnose [--corp <corpId>]
|
||||
seal-home auth hose-link [--corp <corpId>] [--expire 7200]
|
||||
seal-home source config [--corp <corpId>]
|
||||
seal-home tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
|
||||
seal-home rules count [--corp <corpId>]
|
||||
@@ -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 <documentSN-or-query> [--limit 20]
|
||||
seal-home approval-runs get <recordId>
|
||||
seal-home approval-runs get <recordId> [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json]
|
||||
seal-home approval-runs attachments <recordId>
|
||||
seal-home approval-runs result <recordId> [--summary]
|
||||
seal-home approval-runs url
|
||||
seal-home approval-runs url <recordId>
|
||||
seal-home approval-runs url --sourceDocumentSN B26022501
|
||||
|
||||
+31
-3
@@ -128,7 +128,8 @@ async function ensureHoseOpenapiToken(corp: CorpConfig): Promise<string> {
|
||||
|
||||
async function fetchHoseCloseApiToken(
|
||||
source: HoseSealSource,
|
||||
openapiToken: string
|
||||
openapiToken: string,
|
||||
expiresIn = 7200
|
||||
): Promise<TokenEntry> {
|
||||
const client = hoseClient(source);
|
||||
const uid = hoseUid(source);
|
||||
@@ -141,7 +142,7 @@ async function fetchHoseCloseApiToken(
|
||||
json: {
|
||||
uid,
|
||||
pageType: "home",
|
||||
expireDate: 7200
|
||||
expireDate: expiresIn
|
||||
}
|
||||
})
|
||||
.json<HoseProvisionalResponse>();
|
||||
@@ -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<string> {
|
||||
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<SealSession> {
|
||||
if (corp.source.type !== "hose") {
|
||||
throw new Error(`Unsupported Seal source: ${corp.source.type}`);
|
||||
|
||||
@@ -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<Record<string, unknown>> };
|
||||
|
||||
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"
|
||||
|
||||
+253
-4
@@ -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<string, unknown>, fields: readonly string[]) {
|
||||
const output: Record<string, unknown> = {};
|
||||
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<Record<string, unknown>> = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
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<Record<string, unknown>>,
|
||||
seen: Set<string>
|
||||
) {
|
||||
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<string, unknown>, 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<string, unknown>) {
|
||||
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<string, unknown> | 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<string, unknown> | 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<unknown>((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<string, unknown>)[segment];
|
||||
}
|
||||
return undefined;
|
||||
}, value);
|
||||
}
|
||||
|
||||
function setPath(target: Record<string, unknown>, 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<string, unknown>;
|
||||
}
|
||||
current[segments[segments.length - 1] ?? path] = value;
|
||||
}
|
||||
|
||||
function compactObject(object: Record<string, unknown>) {
|
||||
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function summarizeRunBridge(records: ApprovalRun[]) {
|
||||
return records.map((record) => {
|
||||
const summary = summarizeApprovalRun(record);
|
||||
|
||||
Reference in new issue
Block a user