weaver-work-cli 0.1.50 → 0.1.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/chunks/{attachment-content-EJYIOJPH.js → attachment-content-W3TSJC3Y.js} +3 -3
- package/dist/chunks/{chunk-BFKLQLBK.js → chunk-2J3XY4ED.js} +7 -7
- package/dist/chunks/{chunk-K67FODVC.js → chunk-6GCXWKG6.js} +1 -1
- package/dist/chunks/{chunk-WNJUGI2F.js → chunk-76PRVYH4.js} +1 -1
- package/dist/chunks/{chunk-RYFRGTUV.js → chunk-DEHJ7PMA.js} +4 -4
- package/dist/chunks/{chunk-3NCFFHB2.js → chunk-IF33CG4V.js} +1 -1
- package/dist/chunks/{chunk-YB3AJYPY.js → chunk-PE334WL3.js} +4 -4
- package/dist/chunks/{chunk-MCZG6HPM.js → chunk-QQXMHM3J.js} +2 -2
- package/dist/chunks/{chunk-7ECB22G3.js → chunk-U7ROML5E.js} +23 -23
- package/dist/chunks/{chunk-7AYQJSFY.js → chunk-WTLQGS6D.js} +2 -2
- package/dist/chunks/{chunk-6T53BSWZ.js → chunk-XPQN4E5O.js} +50 -19
- package/dist/chunks/{chunk-HARQF5IP.js → chunk-Z4G7LLDD.js} +25 -25
- package/dist/chunks/{conflict-C4UDHCWV.js → conflict-57WDJWL7.js} +2 -2
- package/dist/chunks/{contract-VUC6JOPG.js → contract-LJRAXVZU.js} +8587 -1421
- package/dist/chunks/{create-flow-6OG2LYBD.js → create-flow-3FMMZBCA.js} +6 -6
- package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
- package/dist/chunks/{env-WP57TF2S.js → env-JYZE3BZB.js} +2 -2
- package/dist/chunks/{factory-VUXI7N5C.js → factory-66SCIKW3.js} +1 -1
- package/dist/chunks/{group-chat-UQRGXILK.js → group-chat-MNRYMLNG.js} +3 -3
- package/dist/chunks/{invoice-E7GOITEU.js → invoice-V7ZTITUO.js} +725 -205
- package/dist/chunks/{meeting-4BBLVAWM.js → meeting-IIY4UAJL.js} +10 -10
- package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
- package/dist/chunks/{registry-V4CHRQDI.js → registry-CJOVECZD.js} +1 -1
- package/dist/chunks/{registry-5CRCN2TV.js → registry-METZ2LWE.js} +10 -10
- package/dist/chunks/{room-recommend-AYR3UG7R.js → room-recommend-YFY7HTOF.js} +4 -4
- package/dist/chunks/{schedule-JZEFIXUS.js → schedule-6I63TERA.js} +4 -4
- package/dist/chunks/smart-extract-FOUYNIG3.js +2882 -0
- package/dist/chunks/{workflow-3ZAF2J5E.js → workflow-YHXFIU63.js} +1 -1
- package/dist/index.js +11 -6
- package/dist/shortcuts/contract/manifest.js +251 -0
- package/dist/shortcuts/contract/ooxml/docx-table.js +233 -0
- package/dist/shortcuts/contract/operations/card-action.js +1165 -0
- package/dist/shortcuts/contract/operations/card-ebdf-list.js +571 -0
- package/dist/shortcuts/contract/operations/card-plan.js +327 -0
- package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
- package/dist/shortcuts/contract/operations/card.js +6 -5
- package/dist/shortcuts/contract/operations/docx-fillfromquote.js +532 -0
- package/dist/shortcuts/contract/operations/docx-verify.js +258 -0
- package/dist/shortcuts/contract/operations/elements-build.js +761 -0
- package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
- package/dist/shortcuts/contract/operations/first-screen.js +588 -0
- package/dist/shortcuts/contract/operations/flow.js +81 -25
- package/dist/shortcuts/contract/operations/ledger.js +438 -0
- package/dist/shortcuts/contract/operations/modeltext.js +132 -0
- package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
- package/dist/shortcuts/contract/operations/performance.js +104 -3
- package/dist/shortcuts/contract/operations/quote.js +131 -25
- package/dist/shortcuts/contract/operations/quotescreen.js +529 -0
- package/dist/shortcuts/contract/operations/registry.js +30 -0
- package/dist/shortcuts/contract/operations/review.js +73 -58
- package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
- package/dist/shortcuts/contract/operations/summary.js +4 -2
- package/dist/shortcuts/contract/operations/triage.js +1100 -0
- package/dist/shortcuts/contract/operations/upload.js +48 -7
- package/dist/shortcuts/contract/prewarm-cache.js +90 -0
- package/dist/shortcuts/contract/prewarm.js +88 -0
- package/dist/shortcuts/contract/upload-cache.js +49 -4
- package/dist/shortcuts/data/index.js +1 -6
- package/dist/shortcuts/data/manifest.js +2 -2
- package/dist/shortcuts/data/operations/index.js +1 -1
- package/dist/shortcuts/data/operations/query.js +23 -46
- package/dist/shortcuts/index.js +5 -0
- package/dist/shortcuts/invoice/index.js +0 -12
- package/dist/shortcuts/invoice/manifest.js +200 -49
- package/dist/shortcuts/invoice/operations/registry.js +4 -2
- package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
- package/dist/shortcuts/invoice/operations/shared.js +3 -19
- package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
- package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
- package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
- package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
- package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
- package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
- package/dist/shortcuts/recruit-stage/shared.js +5 -0
- package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
- package/dist/shortcuts/smart-extract/constants.js +79 -0
- package/dist/shortcuts/smart-extract/continuation.js +71 -0
- package/dist/shortcuts/smart-extract/errors.js +68 -0
- package/dist/shortcuts/smart-extract/host.js +191 -0
- package/dist/shortcuts/smart-extract/index.js +105 -0
- package/dist/shortcuts/smart-extract/ledger.js +70 -0
- package/dist/shortcuts/smart-extract/manifest.js +35 -0
- package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
- package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
- package/dist/shortcuts/smart-extract/operations/config.js +118 -0
- package/dist/shortcuts/smart-extract/operations/fill.js +492 -0
- package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
- package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
- package/dist/shortcuts/smart-extract/operations/save.js +355 -0
- package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
- package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
- package/dist/shortcuts/smart-extract/operations/target.js +167 -0
- package/dist/shortcuts/smart-extract/operations/types.js +22 -0
- package/dist/shortcuts/smart-extract/operations/validate.js +454 -0
- package/dist/shortcuts/workflow/operations/form.js +68 -33
- package/dist/shortcuts/workflow/operations/read.js +19 -1
- package/docs/SKILL.md +1 -1
- package/docs/_catalog.md +3 -0
- package/docs/agent-invoice.md +5 -7
- package/docs/data.md +5 -1
- package/docs/fna.md +14 -1
- package/docs/invoice.md +7 -5
- package/docs/smart-extract.md +156 -0
- package/package.json +1 -1
- package/skill-template/business-info.json +16 -1
- package/skill-template/domains/qiyecheng.md +2 -0
- package/skill-template/domains/smart-extract.md +16 -0
- package/skill-template/domains/yepiaotong.md +2 -2
- package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
- package/skills/weaver-e10-jinchengda/SKILL.md +223 -35
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +47 -481
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +11 -11
- package/skills/weaver-e10-jinchengda/references/contract-agent-entry.md +3 -3
- package/skills/weaver-e10-jinchengda/references/contract-ai-assistant.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +32 -16
- package/skills/weaver-e10-jinchengda/references/contract-card-render-internals.md +478 -0
- package/skills/weaver-e10-jinchengda/references/contract-command-index.md +4 -4
- package/skills/weaver-e10-jinchengda/references/contract-disabled-capabilities.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +39 -61
- package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +18 -13
- package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +21 -6
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +6 -4
- package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +3 -3
- package/skills/weaver-e10-jinchengda/references/contract-ledger-catalog.md +263 -0
- package/skills/weaver-e10-jinchengda/references/contract-ledger-query-playbook.md +525 -0
- package/skills/weaver-e10-jinchengda/references/contract-ledger-rules.md +36 -0
- package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
- package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +87 -0
- package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +80 -54
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +110 -14
- package/skills/weaver-e10-jinchengda/references/contract-template-selector.md +19 -21
- package/skills/weaver-e10-jinchengda/references/orchestration.md +12 -12
- package/skills/weaver-e10-jinchengda/references/source-manifest.json +1 -6
- package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +2 -1
- package/skills/weaver-e10-qiyecheng/SKILL.md +37 -0
- package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/catalog.md +25 -0
- package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
- package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
- package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
- package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
- package/skills/weaver-e10-qiyecheng/references/source-manifest.json +34 -27
- package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
- package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
- package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
- package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
- package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
- package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
- package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -42
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
- package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
- package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
- package/skills/weaver-e10-smart-extract/SKILL.md +180 -0
- package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
- package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
- package/skills/weaver-e10-smart-extract/references/troubleshooting.md +106 -0
- package/skills/weaver-e10-workflow/references/workflow-create.md +6 -5
- package/skills/weaver-e10-workflow/references/workflow-edit.md +1 -1
- package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
- package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
- package/skills/weaver-e10-yepiaotong/SKILL.md +46 -33
- package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
- package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
- package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +12 -8
- package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
- package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +91 -2
- package/skills/weaver-e10-yepiaotong/references/reim-examples.md +1 -1
- package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +12 -12
- package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
- package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +136 -91
- package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +109 -23
- package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
- package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
- package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
- package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
- package/skills/weaver-e10-jinchengda/scripts/render_ebdf_list_card.py +0 -265
- package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +0 -588
- package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +0 -118
- package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { attachmentOperations } from './attachment.js';
|
|
2
|
+
import { batchOperations } from './batch.js';
|
|
3
|
+
import { configOperations } from './config.js';
|
|
4
|
+
import { fillOperations } from './fill.js';
|
|
5
|
+
import { previewOperations } from './preview.js';
|
|
6
|
+
import { saveOperations } from './save.js';
|
|
7
|
+
import { structureOperations } from './structure.js';
|
|
8
|
+
import { targetOperations } from './target.js';
|
|
9
|
+
import { validateOperations } from './validate.js';
|
|
10
|
+
/**
|
|
11
|
+
* operation 注册表。顺序即 `smart-extract schema` 的输出顺序。
|
|
12
|
+
*
|
|
13
|
+
* 主链路只有 `fill` → 模型抽取 → `fill.save`;其余是排障用的细粒度命令,不要串着用。
|
|
14
|
+
*/
|
|
15
|
+
export const smartExtractOperationDefinitions = [
|
|
16
|
+
...fillOperations,
|
|
17
|
+
...targetOperations,
|
|
18
|
+
...configOperations,
|
|
19
|
+
...structureOperations,
|
|
20
|
+
...attachmentOperations,
|
|
21
|
+
...validateOperations,
|
|
22
|
+
...previewOperations,
|
|
23
|
+
...saveOperations,
|
|
24
|
+
...batchOperations,
|
|
25
|
+
];
|
|
26
|
+
const REGISTRY = new Map(smartExtractOperationDefinitions.map((definition) => [definition.name, definition]));
|
|
27
|
+
export function getSmartExtractOperation(name) {
|
|
28
|
+
const hit = REGISTRY.get(name);
|
|
29
|
+
if (!hit) {
|
|
30
|
+
throw new Error(`未知 operation: ${name}(可用:${[...REGISTRY.keys()].join(' / ')})`);
|
|
31
|
+
}
|
|
32
|
+
return hit;
|
|
33
|
+
}
|
|
34
|
+
export const smartExtractOperationNames = [...REGISTRY.keys()];
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { CONTINUATION_TTL_SECONDS } from '../../../core/continuation-ttl.js';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { DATA_SOURCE, MAX_INLINE_TICKET_CHARS, MAX_REQUEST_ID_LENGTH, PATHS, ticketPath, } from '../constants.js';
|
|
6
|
+
import { smartExtractBusinessError, smartExtractConfirmationError, smartExtractPartialError, smartExtractValidationError, SmartExtractCliError, } from '../errors.js';
|
|
7
|
+
import { record } from '../host.js';
|
|
8
|
+
import { findSavedByFingerprint, findSavedByTargetAttachment, rememberSaved } from '../ledger.js';
|
|
9
|
+
import { optionalId, optionalString, readObjectInput, requiredId, sha256, stableStringify, } from './shared.js';
|
|
10
|
+
import { smartExtractSuccess, schemaOf, SCHEMA_ID } from './types.js';
|
|
11
|
+
/**
|
|
12
|
+
* 落库:prepare → apply 两段式(排障命令;主链路用 `fill.save`)。
|
|
13
|
+
*
|
|
14
|
+
* 防重复三级:
|
|
15
|
+
* L1 本地内容指纹:同一 workflowId+nodeId+同一份结果 → 返回原 aiExtraId,不签票据不发写请求;
|
|
16
|
+
* L2 本地附件键:同一 workflowId+nodeId+同一组附件(内容有差异)→ 拒绝,forceNew 才放行;
|
|
17
|
+
* L3 服务端 requestId:apply 发写请求前用 queryBatchInfo?requestId= 查一次,
|
|
18
|
+
* 命中说明上次写库已成功、只是响应没回来,不再重发。
|
|
19
|
+
*
|
|
20
|
+
* requestId 缺失时 L3 失效,「写结果未知后重试」会写两条,所以由 CLI 自动生成
|
|
21
|
+
* (`se` + 30 位十六进制,32 字符,等于列宽);调用方显式传了则尊重调用方的。
|
|
22
|
+
*
|
|
23
|
+
* `saveRecognizeRecord` 只写「批次抽取记录」,不写流程表单、不提交审批。
|
|
24
|
+
* EB 模式的批次保存服务端没有对应 HTTP 接口(`saveBatchInfo` 是内部方法),EB 目标在这里直接拒绝。
|
|
25
|
+
*/
|
|
26
|
+
/** 自动生成 32 字符内的请求 ID(服务端 request_id 列宽 32)。 */
|
|
27
|
+
function autoRequestId() {
|
|
28
|
+
return `se${randomBytes(15).toString('hex')}`;
|
|
29
|
+
}
|
|
30
|
+
function mapDataSource(value) {
|
|
31
|
+
const text = optionalString(value, 'dataSource');
|
|
32
|
+
if (!text)
|
|
33
|
+
return DATA_SOURCE['wf-manual'];
|
|
34
|
+
if (text in DATA_SOURCE)
|
|
35
|
+
return DATA_SOURCE[text];
|
|
36
|
+
if (['0', '1', '2'].includes(text))
|
|
37
|
+
return text;
|
|
38
|
+
throw smartExtractValidationError('data_source_invalid', 'dataSource 只能是 wf-pre / wf-manual / eb-manual 或 0/1/2');
|
|
39
|
+
}
|
|
40
|
+
function requireSuccessResult(result) {
|
|
41
|
+
if (result.isSuccess === false) {
|
|
42
|
+
throw smartExtractValidationError('result_not_success', `抽取结果标记为失败,不能保存:${String(result.errorMsg ?? '未给 errorMsg')}`);
|
|
43
|
+
}
|
|
44
|
+
if (result.isSuccess !== true) {
|
|
45
|
+
throw smartExtractValidationError('is_success_missing', '抽取结果缺少 isSuccess=true,禁止保存');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const savePrepare = {
|
|
49
|
+
name: 'smart-extract.save.prepare',
|
|
50
|
+
risk: 'read-before-write',
|
|
51
|
+
summary: '组装落库请求并签发确认票据:先按内容指纹与附件键查本地台账(命中返回 duplicate 与已有 aiExtraId,不签票据),再自动生成 requestId(防「写结果未知后重试」双插)。本身不发写请求。',
|
|
52
|
+
inputSchema: schemaOf({
|
|
53
|
+
workflowId: { ...SCHEMA_ID, description: '流程模板 ID(必填,服务端要求)' },
|
|
54
|
+
nodeId: { ...SCHEMA_ID, description: '流程节点 ID' },
|
|
55
|
+
objFormId: { ...SCHEMA_ID, description: 'EB 表单 ID(仅记录用,EB 模式不支持本接口落库)' },
|
|
56
|
+
layoutId: { ...SCHEMA_ID, description: 'EB 布局 ID(仅记录用)' },
|
|
57
|
+
listId: { ...SCHEMA_ID, description: 'EB 列表 ID(仅记录用)' },
|
|
58
|
+
formModeType: { type: 'string', enum: ['wf', 'eb'], description: '默认 wf;eb 会被拒绝' },
|
|
59
|
+
result: { type: 'object', description: '已通过 validate 的抽取结果(内联)' },
|
|
60
|
+
resultPath: { type: 'string', description: '抽取结果 JSON 文件路径(与 result 二选一)' },
|
|
61
|
+
structure: { type: 'object', description: '表单结构快照(可选,留空由服务端按 workflowId 重新计算)' },
|
|
62
|
+
structurePath: { type: 'string', description: '表单结构 JSON 文件路径(可选)' },
|
|
63
|
+
attachmentIds: {
|
|
64
|
+
oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],
|
|
65
|
+
description: '本次附件 ID(逗号分隔或数组);服务端会据此生成附件元数据',
|
|
66
|
+
},
|
|
67
|
+
userInput: { type: 'string', description: '用户原始输入(无附件时的唯一来源,也用于追溯)' },
|
|
68
|
+
requestId: { type: 'string', description: '可选:自定义请求 ID(≤32 字符)。默认由 CLI 自动生成并用于服务端查重' },
|
|
69
|
+
dataSource: { type: 'string', description: 'wf-pre / wf-manual / eb-manual,默认 wf-manual' },
|
|
70
|
+
sceneFlag: { type: 'string', description: '场景标识' },
|
|
71
|
+
agentId: { ...SCHEMA_ID, description: '智能体 ID' },
|
|
72
|
+
chatId: { type: 'string', description: '会话 ID' },
|
|
73
|
+
messageId: { type: 'string', description: '消息 ID' },
|
|
74
|
+
forceNew: { type: 'boolean', description: '跳过查重强制新建(仅在用户明确要求重存时使用)' },
|
|
75
|
+
}, { required: ['workflowId'] }),
|
|
76
|
+
handler: async (args, env) => {
|
|
77
|
+
const workflowId = requiredId(args.workflowId, 'workflowId');
|
|
78
|
+
const nodeId = optionalId(args.nodeId, 'nodeId');
|
|
79
|
+
const formModeType = optionalString(args.formModeType, 'formModeType') || 'wf';
|
|
80
|
+
if (formModeType === 'eb') {
|
|
81
|
+
throw smartExtractBusinessError('eb_save_unsupported', 'saveRecognizeRecord 只支持流程(wf)批次;EB 模式的批次保存没有对外 HTTP 接口,请在前端/建模数据接口侧落库', { details: { formModeType } });
|
|
82
|
+
}
|
|
83
|
+
if (formModeType !== 'wf') {
|
|
84
|
+
throw smartExtractValidationError('form_mode_invalid', 'formModeType 只能是 wf 或 eb');
|
|
85
|
+
}
|
|
86
|
+
const result = await readObjectInput(args, 'result', 'resultPath', { required: true });
|
|
87
|
+
if (!result)
|
|
88
|
+
throw smartExtractValidationError('result_required', '必须提供 result 或 resultPath');
|
|
89
|
+
requireSuccessResult(result);
|
|
90
|
+
const structure = await readObjectInput(args, 'structure', 'structurePath');
|
|
91
|
+
const forceNew = args.forceNew === true;
|
|
92
|
+
const attachmentIds = Array.isArray(args.attachmentIds)
|
|
93
|
+
? args.attachmentIds.map((item) => String(item).trim()).filter(Boolean).join(',')
|
|
94
|
+
: optionalString(args.attachmentIds, 'attachmentIds');
|
|
95
|
+
const fingerprint = sha256(`${workflowId}|${nodeId ?? ''}|${stableStringify(result)}`);
|
|
96
|
+
const customRequestId = optionalString(args.requestId, 'requestId');
|
|
97
|
+
if (customRequestId && customRequestId.length > MAX_REQUEST_ID_LENGTH) {
|
|
98
|
+
throw smartExtractValidationError('request_id_too_long', `requestId 最多 ${MAX_REQUEST_ID_LENGTH} 个字符(服务端 request_id 列放不下,会直接 500)`, { expected: MAX_REQUEST_ID_LENGTH, actual: customRequestId.length });
|
|
99
|
+
}
|
|
100
|
+
// requestId 必须有:服务端只认它做查重(queryBatchInfo?requestId=),缺了就无法判断「上次是否已写入」。
|
|
101
|
+
const requestId = customRequestId ?? autoRequestId();
|
|
102
|
+
if (!forceNew) {
|
|
103
|
+
const saved = await findSavedByFingerprint(env.stateDir, fingerprint);
|
|
104
|
+
if (saved) {
|
|
105
|
+
return smartExtractSuccess('smart-extract.save.prepare', {
|
|
106
|
+
duplicate: true,
|
|
107
|
+
applied: false,
|
|
108
|
+
aiExtraId: saved.aiExtraId,
|
|
109
|
+
savedAt: saved.savedAt,
|
|
110
|
+
fingerprint,
|
|
111
|
+
requestId: saved.requestId ?? requestId,
|
|
112
|
+
message: '同一目标 + 同一份抽取结果已在本地台账记录为已保存,不再重复落库',
|
|
113
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
114
|
+
}
|
|
115
|
+
if (attachmentIds) {
|
|
116
|
+
const byAttachment = await findSavedByTargetAttachment(env.stateDir, workflowId, nodeId, attachmentIds);
|
|
117
|
+
if (byAttachment) {
|
|
118
|
+
return smartExtractSuccess('smart-extract.save.prepare', {
|
|
119
|
+
duplicate: true,
|
|
120
|
+
applied: false,
|
|
121
|
+
aiExtraId: byAttachment.aiExtraId,
|
|
122
|
+
savedAt: byAttachment.savedAt,
|
|
123
|
+
fingerprint,
|
|
124
|
+
requestId: byAttachment.requestId ?? requestId,
|
|
125
|
+
alreadySavedForAttachment: true,
|
|
126
|
+
message: '同一流程同一附件已保存过抽取记录(本次抽取内容与上次略有差异,视为同一次业务保存)。确需重存请带 forceNew:true',
|
|
127
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const existingId = await queryByRequestId(env, requestId);
|
|
131
|
+
if (existingId) {
|
|
132
|
+
await rememberSaved(env.stateDir, fingerprint, {
|
|
133
|
+
aiExtraId: existingId,
|
|
134
|
+
savedAt: new Date().toISOString(),
|
|
135
|
+
workflowId,
|
|
136
|
+
nodeId,
|
|
137
|
+
requestId,
|
|
138
|
+
...(attachmentIds ? { attachmentIds } : {}),
|
|
139
|
+
});
|
|
140
|
+
return smartExtractSuccess('smart-extract.save.prepare', {
|
|
141
|
+
duplicate: true,
|
|
142
|
+
applied: false,
|
|
143
|
+
aiExtraId: existingId,
|
|
144
|
+
fingerprint,
|
|
145
|
+
requestId,
|
|
146
|
+
message: '服务端已存在同一 requestId 的记录,视为已保存',
|
|
147
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const payload = {
|
|
151
|
+
workflowId,
|
|
152
|
+
...(nodeId ? { nodeId } : {}),
|
|
153
|
+
formModeType: 'wf',
|
|
154
|
+
...(requestId ? { requestId } : {}),
|
|
155
|
+
recognizeResult: JSON.stringify(result),
|
|
156
|
+
dataSource: mapDataSource(args.dataSource),
|
|
157
|
+
fillStatus: '0',
|
|
158
|
+
...(optionalId(args.objFormId, 'objFormId') ? { objFormId: optionalId(args.objFormId, 'objFormId') } : {}),
|
|
159
|
+
...(optionalId(args.layoutId, 'layoutId') ? { layoutId: optionalId(args.layoutId, 'layoutId') } : {}),
|
|
160
|
+
...(optionalId(args.listId, 'listId') ? { listId: optionalId(args.listId, 'listId') } : {}),
|
|
161
|
+
...(attachmentIds ? { attachmentIds } : {}),
|
|
162
|
+
...(optionalString(args.userInput, 'userInput') ? { userInput: optionalString(args.userInput, 'userInput') } : {}),
|
|
163
|
+
...(optionalString(args.sceneFlag, 'sceneFlag') ? { sceneFlag: optionalString(args.sceneFlag, 'sceneFlag') } : {}),
|
|
164
|
+
...(optionalId(args.agentId, 'agentId') ? { agentId: optionalId(args.agentId, 'agentId') } : {}),
|
|
165
|
+
...(optionalString(args.chatId, 'chatId') ? { chatId: optionalString(args.chatId, 'chatId') } : {}),
|
|
166
|
+
...(optionalString(args.messageId, 'messageId') ? { messageId: optionalString(args.messageId, 'messageId') } : {}),
|
|
167
|
+
};
|
|
168
|
+
const session = await env.host.getSession();
|
|
169
|
+
const continuation = await env.continuation.issue({
|
|
170
|
+
operation: 'smart-extract.save.apply',
|
|
171
|
+
actor: { userId: session.userId, baseUrl: session.baseUrl, profile: session.profile },
|
|
172
|
+
workflowId,
|
|
173
|
+
nodeId: nodeId ?? null,
|
|
174
|
+
fingerprint,
|
|
175
|
+
requestId,
|
|
176
|
+
payload,
|
|
177
|
+
});
|
|
178
|
+
const mainRows = result.mainTable && Array.isArray(result.mainTable.rows)
|
|
179
|
+
? result.mainTable.rows.length
|
|
180
|
+
: 0;
|
|
181
|
+
const subRows = Array.isArray(result.subTables)
|
|
182
|
+
? result.subTables.reduce((total, table) => total + (Array.isArray(table?.rows) ? table.rows.length : 0), 0)
|
|
183
|
+
: 0;
|
|
184
|
+
// 票据必须落盘:它封了完整请求体,长度通常几 KB,直接打到 stdout 会被输出层
|
|
185
|
+
// 按预算截断成「前 200 字…」,截过的票据签名必然对不上,等于把保存链路堵死。
|
|
186
|
+
const ticketFile = ticketPath(env.stateDir, requestId);
|
|
187
|
+
await mkdir(dirname(ticketFile), { recursive: true, mode: 0o700 });
|
|
188
|
+
await writeFile(ticketFile, continuation, { encoding: 'utf8', mode: 0o600 });
|
|
189
|
+
return smartExtractSuccess('smart-extract.save.prepare', {
|
|
190
|
+
duplicate: false,
|
|
191
|
+
applied: false,
|
|
192
|
+
requestId: requestId ?? null,
|
|
193
|
+
fingerprint,
|
|
194
|
+
ticketFile,
|
|
195
|
+
// 只有短票据才把明文放进来;长票据一律走 ticketFile,避免调用方拿到半截字符串
|
|
196
|
+
...(continuation.length <= MAX_INLINE_TICKET_CHARS ? { continuation } : {}),
|
|
197
|
+
expiresInSeconds: CONTINUATION_TTL_SECONDS,
|
|
198
|
+
requestPreview: {
|
|
199
|
+
workflowId,
|
|
200
|
+
nodeId: nodeId ?? null,
|
|
201
|
+
formModeType: 'wf',
|
|
202
|
+
requestId,
|
|
203
|
+
dataSource: payload.dataSource,
|
|
204
|
+
attachmentIds: attachmentIds ?? null,
|
|
205
|
+
mainRows,
|
|
206
|
+
subRows,
|
|
207
|
+
recognizeResultBytes: String(payload.recognizeResult).length,
|
|
208
|
+
},
|
|
209
|
+
next: `把 requestPreview 与预览一起给用户确认;用户明确同意后调 smart-extract.save.apply(confirm=true, ticketFile=${ticketFile})。票据已落盘,不要回传 stdout 里的票据明文(可能被截断)`,
|
|
210
|
+
}, { meta: { state: 'PREPARED' } });
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
export async function queryByRequestId(env, requestId) {
|
|
214
|
+
try {
|
|
215
|
+
const data = await env.host.requestData({
|
|
216
|
+
operation: 'smart-extract.save.prepare',
|
|
217
|
+
method: 'GET',
|
|
218
|
+
path: PATHS.queryBatchInfo,
|
|
219
|
+
query: { requestId },
|
|
220
|
+
});
|
|
221
|
+
const list = Array.isArray(data) ? data : [];
|
|
222
|
+
const first = record(list[0]);
|
|
223
|
+
const id = first.id ?? first.aiExtraId ?? first.batchId;
|
|
224
|
+
return id === undefined || id === null ? undefined : String(id);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// 查重失败不阻塞 prepare:真正的兜底在 apply 发写请求前的服务端复查。
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* 取票据明文:ticketFile 优先,其次 continuation。
|
|
233
|
+
*
|
|
234
|
+
* 票据被截断时签名校验只会报「签名校验失败」,看起来像密钥问题;这里直接指出真实原因
|
|
235
|
+
* (CLI 输出层会给超预算的长字符串加 `…`,照 stdout 原样回传就会截断)。
|
|
236
|
+
*/
|
|
237
|
+
async function resolveContinuation(args, stateDir) {
|
|
238
|
+
const file = optionalString(args.ticketFile, 'ticketFile');
|
|
239
|
+
if (file) {
|
|
240
|
+
try {
|
|
241
|
+
return (await readFile(file, 'utf8')).trim();
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
throw smartExtractValidationError('ticket_unreadable', `无法读取票据文件:${file}`, { details: { reason: error instanceof Error ? error.message : String(error) } });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const inline = String(args.continuation ?? '').trim();
|
|
248
|
+
if (!inline) {
|
|
249
|
+
throw smartExtractValidationError('continuation_required', `必须提供 ticketFile(推荐)或 continuation;prepare 会把票据写到 ${stateDir}/tickets/ 下`);
|
|
250
|
+
}
|
|
251
|
+
if (inline.includes('…')) {
|
|
252
|
+
throw smartExtractValidationError('continuation_truncated', 'continuation 被 CLI 输出层截断(含省略号),无法用于签名校验;请改用 save.prepare 返回的 ticketFile');
|
|
253
|
+
}
|
|
254
|
+
return inline;
|
|
255
|
+
}
|
|
256
|
+
const saveApply = {
|
|
257
|
+
name: 'smart-extract.save.apply',
|
|
258
|
+
risk: 'high-risk-write',
|
|
259
|
+
summary: '确认后真正写入批次记录:必须 confirm=true 且带 prepare 返回的 ticketFile。发写请求前先按 requestId/内容指纹/附件键三层查重,重复一律返回已有 aiExtraId,不再入库。',
|
|
260
|
+
inputSchema: schemaOf({
|
|
261
|
+
confirm: { type: 'boolean', description: '必须为 true;表示用户已明确确认保存' },
|
|
262
|
+
ticketFile: { type: 'string', description: 'save.prepare 返回的 ticketFile 路径(首选,票据完整)' },
|
|
263
|
+
continuation: { type: 'string', description: 'save.prepare 返回的票据明文(仅短票据会返回;长票据被输出层截断,必须用 ticketFile)' },
|
|
264
|
+
}, { required: ['confirm'] }),
|
|
265
|
+
handler: async (args, env) => {
|
|
266
|
+
if (args.confirm !== true) {
|
|
267
|
+
throw smartExtractConfirmationError('smart-extract.save.apply', {
|
|
268
|
+
hint: '先向用户展示预览并取得明确同意,再把 confirm 设为 true',
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
const continuation = await resolveContinuation(args, env.stateDir);
|
|
272
|
+
const recordValue = await env.continuation.verify(continuation, 'smart-extract.save.apply');
|
|
273
|
+
const session = await env.host.getSession();
|
|
274
|
+
const actor = record(recordValue.actor);
|
|
275
|
+
if (actor.userId !== session.userId || actor.baseUrl !== session.baseUrl) {
|
|
276
|
+
throw smartExtractValidationError('continuation_actor_changed', 'continuation 签发时的登录用户/环境与当前不一致,请重新 prepare');
|
|
277
|
+
}
|
|
278
|
+
const fingerprint = String(recordValue.fingerprint ?? '');
|
|
279
|
+
if (!fingerprint) {
|
|
280
|
+
throw smartExtractValidationError('continuation_invalid', 'continuation 缺少内容指纹');
|
|
281
|
+
}
|
|
282
|
+
const payload = record(recordValue.payload);
|
|
283
|
+
const requestId = recordValue.requestId === undefined || recordValue.requestId === null
|
|
284
|
+
? undefined
|
|
285
|
+
: String(recordValue.requestId);
|
|
286
|
+
const saved = await findSavedByFingerprint(env.stateDir, fingerprint);
|
|
287
|
+
if (saved) {
|
|
288
|
+
return smartExtractSuccess('smart-extract.save.apply', {
|
|
289
|
+
duplicate: true,
|
|
290
|
+
aiExtraId: saved.aiExtraId,
|
|
291
|
+
savedAt: saved.savedAt,
|
|
292
|
+
message: '本地台账显示该结果已保存,未再发写请求',
|
|
293
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
294
|
+
}
|
|
295
|
+
// 上次写库可能已成功、只是响应没回来(超时/断网后重试 apply)。本地台账此时还没有那条记录,
|
|
296
|
+
// 必须先拿 requestId 问一次服务端,命中就不再重发。
|
|
297
|
+
if (requestId) {
|
|
298
|
+
const existingId = await queryByRequestId(env, requestId);
|
|
299
|
+
if (existingId) {
|
|
300
|
+
await rememberSaved(env.stateDir, fingerprint, {
|
|
301
|
+
aiExtraId: existingId,
|
|
302
|
+
savedAt: new Date().toISOString(),
|
|
303
|
+
workflowId: String(recordValue.workflowId ?? payload.workflowId ?? ''),
|
|
304
|
+
nodeId: recordValue.nodeId === null || recordValue.nodeId === undefined ? undefined : String(recordValue.nodeId),
|
|
305
|
+
requestId,
|
|
306
|
+
...(payload.attachmentIds ? { attachmentIds: String(payload.attachmentIds) } : {}),
|
|
307
|
+
});
|
|
308
|
+
return smartExtractSuccess('smart-extract.save.apply', {
|
|
309
|
+
duplicate: true,
|
|
310
|
+
aiExtraId: existingId,
|
|
311
|
+
requestId,
|
|
312
|
+
message: '服务端已存在同一 requestId 的记录(上次写库实际已成功),未重复入库',
|
|
313
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
let data;
|
|
317
|
+
try {
|
|
318
|
+
data = await env.host.requestData({
|
|
319
|
+
operation: 'smart-extract.save.apply',
|
|
320
|
+
method: 'POST',
|
|
321
|
+
path: PATHS.saveRecognizeRecord,
|
|
322
|
+
body: payload,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
if (error instanceof SmartExtractCliError && error.type === 'network') {
|
|
327
|
+
throw smartExtractPartialError('保存请求结果未知(网络中断/超时)。禁止直接重试本命令:重试是安全的(requestId 查重会兜底),但应先调 smart-extract.batch.get 或重新 apply 确认', { requestId, hint: '重新执行 apply 会先用 requestId 查服务端,命中则返回已有 aiExtraId 而不会重复入库' });
|
|
328
|
+
}
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
const result = record(data);
|
|
332
|
+
const savedId = result.id ?? result.aiExtraId ?? result.batchId;
|
|
333
|
+
if (savedId === undefined || savedId === null) {
|
|
334
|
+
throw smartExtractBusinessError('save_response_invalid', '保存接口未返回 aiExtraId', {
|
|
335
|
+
details: { result: data },
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
const aiExtraId = String(savedId);
|
|
339
|
+
await rememberSaved(env.stateDir, fingerprint, {
|
|
340
|
+
aiExtraId,
|
|
341
|
+
savedAt: new Date().toISOString(),
|
|
342
|
+
workflowId: String(recordValue.workflowId ?? payload.workflowId ?? ''),
|
|
343
|
+
nodeId: recordValue.nodeId === null || recordValue.nodeId === undefined ? undefined : String(recordValue.nodeId),
|
|
344
|
+
requestId,
|
|
345
|
+
...(payload.attachmentIds ? { attachmentIds: String(payload.attachmentIds) } : {}),
|
|
346
|
+
});
|
|
347
|
+
return smartExtractSuccess('smart-extract.save.apply', {
|
|
348
|
+
duplicate: false,
|
|
349
|
+
aiExtraId,
|
|
350
|
+
requestId: requestId ?? null,
|
|
351
|
+
verifyHint: `已保存。可用 smart-extract.batch.get --input-json '{"id":"${aiExtraId}"}' 回查;前端组件用 getBatchInfoById 读同一条`,
|
|
352
|
+
}, { meta: { state: 'COMPLETE' } });
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
export const saveOperations = [savePrepare, saveApply];
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { smartExtractValidationError } from '../errors.js';
|
|
4
|
+
/** operation 入参的通用取值/校验工具:宁可在入口拒绝,也不要把脏数据带到请求里。 */
|
|
5
|
+
export function record(value) {
|
|
6
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
7
|
+
}
|
|
8
|
+
export function asObject(value, field) {
|
|
9
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
10
|
+
throw smartExtractValidationError('field_invalid', `${field} 必须是对象`);
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
export function optionalString(value, field) {
|
|
15
|
+
if (value === undefined || value === null || value === '')
|
|
16
|
+
return undefined;
|
|
17
|
+
if (typeof value !== 'string' && typeof value !== 'number') {
|
|
18
|
+
throw smartExtractValidationError('field_invalid', `${field} 必须是字符串`);
|
|
19
|
+
}
|
|
20
|
+
const text = String(value).trim();
|
|
21
|
+
return text === '' ? undefined : text;
|
|
22
|
+
}
|
|
23
|
+
export function requiredString(value, field) {
|
|
24
|
+
const text = optionalString(value, field);
|
|
25
|
+
if (!text)
|
|
26
|
+
throw smartExtractValidationError(`${field}_required`, `${field} 必填`);
|
|
27
|
+
return text;
|
|
28
|
+
}
|
|
29
|
+
/** E10 长 ID 统一按字符串处理,避免 Number 精度丢失。 */
|
|
30
|
+
export function requiredId(value, field) {
|
|
31
|
+
const text = requiredString(value, field);
|
|
32
|
+
if (!/^\d+$/u.test(text)) {
|
|
33
|
+
throw smartExtractValidationError(`${field}_invalid`, `${field} 必须是纯数字 ID`);
|
|
34
|
+
}
|
|
35
|
+
return text;
|
|
36
|
+
}
|
|
37
|
+
export function optionalId(value, field) {
|
|
38
|
+
const text = optionalString(value, field);
|
|
39
|
+
if (!text)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (!/^\d+$/u.test(text)) {
|
|
42
|
+
throw smartExtractValidationError(`${field}_invalid`, `${field} 必须是纯数字 ID`);
|
|
43
|
+
}
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
export function optionalArray(value, field) {
|
|
47
|
+
if (value === undefined || value === null || value === '')
|
|
48
|
+
return undefined;
|
|
49
|
+
if (!Array.isArray(value)) {
|
|
50
|
+
throw smartExtractValidationError('field_invalid', `${field} 必须是数组`);
|
|
51
|
+
}
|
|
52
|
+
return value;
|
|
53
|
+
}
|
|
54
|
+
export function requiredArray(value, field) {
|
|
55
|
+
const list = optionalArray(value, field);
|
|
56
|
+
if (!list || list.length === 0) {
|
|
57
|
+
throw smartExtractValidationError(`${field}_required`, `${field} 不能为空`);
|
|
58
|
+
}
|
|
59
|
+
return list;
|
|
60
|
+
}
|
|
61
|
+
/** 逗号/分号/空格分隔的 ID 串 → 去重数组,兼容数组与 JSON 数组字符串。 */
|
|
62
|
+
export function parseIdList(value, field) {
|
|
63
|
+
if (value === undefined || value === null || value === '')
|
|
64
|
+
return [];
|
|
65
|
+
if (Array.isArray(value)) {
|
|
66
|
+
return dedupe(value.map((item) => {
|
|
67
|
+
if (item && typeof item === 'object')
|
|
68
|
+
return String(item.fileId ?? item.id ?? '').trim();
|
|
69
|
+
return String(item ?? '').trim();
|
|
70
|
+
}).filter(Boolean));
|
|
71
|
+
}
|
|
72
|
+
const text = String(value).trim();
|
|
73
|
+
if (text.startsWith('[')) {
|
|
74
|
+
try {
|
|
75
|
+
return parseIdList(JSON.parse(text), field);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// 不是合法 JSON,按分隔符继续
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const items = text.split(/[,;,;\s]+/u).map((item) => item.trim()).filter(Boolean);
|
|
82
|
+
for (const item of items) {
|
|
83
|
+
if (!/^\d+$/u.test(item)) {
|
|
84
|
+
throw smartExtractValidationError('field_invalid', `${field} 中包含非数字 ID:${item}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return dedupe(items);
|
|
88
|
+
}
|
|
89
|
+
export function dedupe(values) {
|
|
90
|
+
return [...new Set(values.filter(Boolean))];
|
|
91
|
+
}
|
|
92
|
+
/** 只允许声明过的入参字段;写错字段立刻失败,而不是被静默忽略。 */
|
|
93
|
+
export function assertKnownKeys(input, allowed, action) {
|
|
94
|
+
const unknown = Object.keys(input).filter((key) => !allowed.includes(key));
|
|
95
|
+
if (unknown.length > 0) {
|
|
96
|
+
throw smartExtractValidationError('input_unknown_field', `${action} 不支持入参:${unknown.join(', ')}`, {
|
|
97
|
+
allowed,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 读取「内联对象或 JSON 文件」二选一的入参。
|
|
103
|
+
*
|
|
104
|
+
* 模型经常需要传很大的结构/结果,内联 JSON 容易被 shell 吃掉引号,
|
|
105
|
+
* 所以所有大对象入参都支持 `xxx` 与 `xxxPath` 两种形态。
|
|
106
|
+
*/
|
|
107
|
+
export async function readObjectInput(input, inlineKey, pathKey, options = {}) {
|
|
108
|
+
const inline = input[inlineKey];
|
|
109
|
+
const path = optionalString(input[pathKey], pathKey);
|
|
110
|
+
if (inline !== undefined && inline !== null && path) {
|
|
111
|
+
throw smartExtractValidationError('input_conflict', `${inlineKey} 与 ${pathKey} 只能传一个`);
|
|
112
|
+
}
|
|
113
|
+
if (path) {
|
|
114
|
+
let raw;
|
|
115
|
+
try {
|
|
116
|
+
raw = await readFile(path, 'utf8');
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
throw smartExtractValidationError('input_unreadable', `无法读取 ${pathKey}:${path}`);
|
|
120
|
+
}
|
|
121
|
+
return unwrapDataEnvelope(parseJsonObject(stripBom(raw), pathKey));
|
|
122
|
+
}
|
|
123
|
+
if (typeof inline === 'string') {
|
|
124
|
+
return unwrapDataEnvelope(parseJsonObject(stripBom(inline), inlineKey));
|
|
125
|
+
}
|
|
126
|
+
if (inline && typeof inline === 'object' && !Array.isArray(inline)) {
|
|
127
|
+
return unwrapDataEnvelope(inline);
|
|
128
|
+
}
|
|
129
|
+
if (options.required) {
|
|
130
|
+
throw smartExtractValidationError(`${inlineKey}_required`, `必须提供 ${inlineKey} 或 ${pathKey}`);
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
export function parseJsonObject(raw, label) {
|
|
135
|
+
let parsed;
|
|
136
|
+
try {
|
|
137
|
+
parsed = JSON.parse(raw);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
throw smartExtractValidationError('json_invalid', `${label} 不是合法 JSON`);
|
|
141
|
+
}
|
|
142
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
143
|
+
throw smartExtractValidationError('json_invalid', `${label} 必须是 JSON 对象`);
|
|
144
|
+
}
|
|
145
|
+
return parsed;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* 允许直接把上一条命令的 stdout 存成文件再传回来。
|
|
149
|
+
*
|
|
150
|
+
* CLI 统一输出 `{schemaVersion, ok, operation, data}` 信封;如果用户把整个 stdout 重定向成
|
|
151
|
+
* `structure.json`,这里自动取 `data`,不用模型手工剥一层。
|
|
152
|
+
*/
|
|
153
|
+
export function unwrapDataEnvelope(value) {
|
|
154
|
+
const looksLikeEnvelope = (value.ok === true || value.ok === false)
|
|
155
|
+
&& typeof value.operation === 'string'
|
|
156
|
+
&& value.data !== undefined;
|
|
157
|
+
if (!looksLikeEnvelope)
|
|
158
|
+
return value;
|
|
159
|
+
if (value.ok === false) {
|
|
160
|
+
throw smartExtractValidationError('input_envelope_failed', `输入文件来自一次失败的调用:${value.operation}`);
|
|
161
|
+
}
|
|
162
|
+
const data = value.data;
|
|
163
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
164
|
+
throw smartExtractValidationError('input_envelope_invalid', `${value.operation} 的 data 不是对象`);
|
|
165
|
+
}
|
|
166
|
+
return data;
|
|
167
|
+
}
|
|
168
|
+
export function stripBom(value) {
|
|
169
|
+
return value.replace(/^\uFEFF+/u, '');
|
|
170
|
+
}
|
|
171
|
+
/** 稳定序列化:对象键排序,保证同一份内容得到同一个指纹。 */
|
|
172
|
+
export function stableStringify(value) {
|
|
173
|
+
if (value === null || typeof value !== 'object')
|
|
174
|
+
return JSON.stringify(value);
|
|
175
|
+
if (Array.isArray(value))
|
|
176
|
+
return `[${value.map(stableStringify).join(',')}]`;
|
|
177
|
+
const entries = Object.entries(value)
|
|
178
|
+
.filter(([, item]) => item !== undefined)
|
|
179
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
180
|
+
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(',')}}`;
|
|
181
|
+
}
|
|
182
|
+
export function sha256(value) {
|
|
183
|
+
return createHash('sha256').update(value).digest('hex');
|
|
184
|
+
}
|
|
185
|
+
export function truncate(value, max) {
|
|
186
|
+
return value.length <= max ? value : `${value.slice(0, max)}…`;
|
|
187
|
+
}
|
|
188
|
+
/** 金额/数字比较前的清洗:去千分位、货币符号、首尾空格。 */
|
|
189
|
+
export function normalizeNumberText(value) {
|
|
190
|
+
return value.replace(/[,,\s]/gu, '').replace(/^[¥$¥]/u, '');
|
|
191
|
+
}
|