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,492 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, extname } from 'node:path';
|
|
4
|
+
import { inflateRawSync } from 'node:zlib';
|
|
5
|
+
import { DEFAULT_RESULT_THRESHOLD_BYTES } from '../../../core/output.js';
|
|
6
|
+
import { DATA_SOURCE, MAX_ATTACHMENTS, MAX_ATTACHMENT_BYTES, MAX_REQUEST_ID_LENGTH, PATHS, TEXT_PREVIEW_CHARS, sessionPath, } from '../constants.js';
|
|
7
|
+
import { smartExtractBusinessError, smartExtractPartialError, smartExtractValidationError, SmartExtractCliError, } from '../errors.js';
|
|
8
|
+
import { record } from '../host.js';
|
|
9
|
+
import { downloadAttachments } from './attachment.js';
|
|
10
|
+
import { fetchWfNodeStructure, resolveStartNode } from './structure.js';
|
|
11
|
+
import { normalizeResult, validateExtraction } from './validate.js';
|
|
12
|
+
import { queryByRequestId } from './save.js';
|
|
13
|
+
import { optionalId, optionalString, parseIdList, readObjectInput, } from './shared.js';
|
|
14
|
+
import { schemaOf, SCHEMA_ID, smartExtractSuccess } from './types.js';
|
|
15
|
+
/** 结果 JSON 契约:一句话给模型,别让它去别处找格式。 */
|
|
16
|
+
const RESULT_CONTRACT = '{"isSuccess":true,"mainTable":{"rows":[{"mainDataId":1,"fieldResults":[{"fieldInfo":"字段ID#字段名称","value":"值","reason":"依据","origin":["附件ID#原文片段"]}]}]}'
|
|
17
|
+
+ ',"subTables":[{"subFormId":"明细表ID","fields":["字段ID#字段名称"],"rows":[{"subDataId":1,"mainDataId":1,"values":["值"],"reasons":["依据"],"origins":[["附件ID#原文片段"]]}]}]}';
|
|
18
|
+
/** 生成会话 ID:`sf` + 24 位十六进制。`fill.save` 的 requestId 由它派生(`se` + 同一串十六进制)。 */
|
|
19
|
+
function shortId(prefix) {
|
|
20
|
+
return `${prefix}${randomBytes(12).toString('hex')}`;
|
|
21
|
+
}
|
|
22
|
+
/** stdout 预算里留给附件正文的比例,其余归结构、规则、envelope 与 warnings。 */
|
|
23
|
+
const INLINE_BUDGET_RATIO = 0.95;
|
|
24
|
+
/** envelope 与 warnings 的固定余量(字节)。 */
|
|
25
|
+
const ENVELOPE_RESERVE_BYTES = 400;
|
|
26
|
+
/** 单个附件至少能内联这么多字节才内联,否则整份落文件——把正文切一半没有意义。 */
|
|
27
|
+
const MIN_INLINE_BYTES_PER_ATTACHMENT = 2_400;
|
|
28
|
+
/** fill 的回执提示:只写「拿到这份结果后怎么抽、怎么存」。 */
|
|
29
|
+
function fillNextHint(sessionFile) {
|
|
30
|
+
return '按 fields 抽取,origin 用「附件ID#原文片段」,只填有值的字段。'
|
|
31
|
+
+ '正文:有 text 的直接用;只有 textFile 的用 read_file 读一次(全文在里面);PDF/图片/Excel 读 path。'
|
|
32
|
+
+ '不要用 --input-ref / --pick-as,不要重新下载附件,不要自己解析 docx。'
|
|
33
|
+
+ `抽完调 smart-extract.fill.save --input-json '{"sessionFile":"${sessionFile}","result":{...}}',拿到 aiExtraId 即结束。`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 取识别规则(后台「智能填单配置」)。
|
|
37
|
+
*
|
|
38
|
+
* 先按启用过滤取一次;一条都没有时再放宽一次(有些环境配置了但 enabled 字段不干净)。
|
|
39
|
+
*/
|
|
40
|
+
async function fetchRules(host, workflowId, nodeId) {
|
|
41
|
+
const query = async (withEnabled) => {
|
|
42
|
+
const page = record(await host.requestData({
|
|
43
|
+
operation: 'smart-extract.fill',
|
|
44
|
+
method: 'POST',
|
|
45
|
+
path: PATHS.configList,
|
|
46
|
+
body: {
|
|
47
|
+
current: 1,
|
|
48
|
+
pageSize: 50,
|
|
49
|
+
modeType: 'wf',
|
|
50
|
+
sourceId: workflowId,
|
|
51
|
+
wfNodeId: nodeId,
|
|
52
|
+
...(withEnabled ? { enabled: 1 } : {}),
|
|
53
|
+
},
|
|
54
|
+
}));
|
|
55
|
+
return (Array.isArray(page.records) ? page.records : []).map((item) => record(item));
|
|
56
|
+
};
|
|
57
|
+
const warnings = [];
|
|
58
|
+
let configs = await query(true);
|
|
59
|
+
if (configs.length === 0)
|
|
60
|
+
configs = await query(false);
|
|
61
|
+
if (configs.length === 0) {
|
|
62
|
+
warnings.push('该流程没有配置识别规则;按字段名/类型自行判断即可');
|
|
63
|
+
}
|
|
64
|
+
if (configs.length > 1) {
|
|
65
|
+
warnings.push(`命中 ${configs.length} 条配置,已合并其规则(同一字段以先出现的为准)`);
|
|
66
|
+
}
|
|
67
|
+
const fieldRules = [];
|
|
68
|
+
const parseFields = [];
|
|
69
|
+
const seenField = new Set();
|
|
70
|
+
for (const config of configs) {
|
|
71
|
+
for (const ruleRaw of Array.isArray(config.fieldRules) ? config.fieldRules : []) {
|
|
72
|
+
const rule = record(ruleRaw);
|
|
73
|
+
const fieldId = rule.fieldId === undefined || rule.fieldId === null ? '' : String(rule.fieldId);
|
|
74
|
+
const fieldName = String(record(rule.fieldInfo).fieldName ?? rule.fieldAlias ?? '');
|
|
75
|
+
const key = fieldId || fieldName;
|
|
76
|
+
const text = String(rule.fieldRule ?? '').trim();
|
|
77
|
+
if (!key || !text || seenField.has(key))
|
|
78
|
+
continue;
|
|
79
|
+
seenField.add(key);
|
|
80
|
+
fieldRules.push(`${fieldName || fieldId}#${text}`);
|
|
81
|
+
}
|
|
82
|
+
for (const item of String(config.parseFields ?? '').split(/[,;,;]/u).map((part) => part.trim())) {
|
|
83
|
+
if (item && !parseFields.includes(item))
|
|
84
|
+
parseFields.push(item);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
globalRule: configs.map((config) => String(config.globalRule ?? '').trim()).filter(Boolean).join('\n'),
|
|
89
|
+
fieldRules,
|
|
90
|
+
parseFields,
|
|
91
|
+
warnings,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 从 docx 抽纯文本。
|
|
96
|
+
*
|
|
97
|
+
* docx 是 zip,正文在 `word/document.xml`;用 Node 自带 `zlib` 解压,不引第三方依赖。
|
|
98
|
+
* 只处理 wf 场景最常见的 docx 与纯文本,PDF/图片/Excel 交给宿主读 `path`。
|
|
99
|
+
*/
|
|
100
|
+
function unzipEntry(buffer, entryName) {
|
|
101
|
+
let eocd = -1;
|
|
102
|
+
for (let index = buffer.length - 22; index >= Math.max(0, buffer.length - 66_000); index -= 1) {
|
|
103
|
+
if (buffer.readUInt32LE(index) === 0x06054b50) {
|
|
104
|
+
eocd = index;
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (eocd < 0)
|
|
109
|
+
return null;
|
|
110
|
+
const total = buffer.readUInt16LE(eocd + 10);
|
|
111
|
+
let offset = buffer.readUInt32LE(eocd + 16);
|
|
112
|
+
for (let index = 0; index < total; index += 1) {
|
|
113
|
+
if (offset + 46 > buffer.length || buffer.readUInt32LE(offset) !== 0x02014b50)
|
|
114
|
+
return null;
|
|
115
|
+
const method = buffer.readUInt16LE(offset + 10);
|
|
116
|
+
const compressedSize = buffer.readUInt32LE(offset + 20);
|
|
117
|
+
const nameLength = buffer.readUInt16LE(offset + 28);
|
|
118
|
+
const extraLength = buffer.readUInt16LE(offset + 30);
|
|
119
|
+
const commentLength = buffer.readUInt16LE(offset + 32);
|
|
120
|
+
const localOffset = buffer.readUInt32LE(offset + 42);
|
|
121
|
+
const name = buffer.toString('utf8', offset + 46, offset + 46 + nameLength);
|
|
122
|
+
if (name === entryName && localOffset + 30 <= buffer.length) {
|
|
123
|
+
const localNameLength = buffer.readUInt16LE(localOffset + 26);
|
|
124
|
+
const localExtraLength = buffer.readUInt16LE(localOffset + 28);
|
|
125
|
+
const start = localOffset + 30 + localNameLength + localExtraLength;
|
|
126
|
+
const data = buffer.subarray(start, start + compressedSize);
|
|
127
|
+
return method === 0 ? Buffer.from(data) : inflateRawSync(data);
|
|
128
|
+
}
|
|
129
|
+
offset += 46 + nameLength + extraLength + commentLength;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
function xmlToText(xml) {
|
|
134
|
+
return xml
|
|
135
|
+
.replace(/<w:tab[^>]*\/>/gu, '\t')
|
|
136
|
+
.replace(/<w:br[^>]*\/>/gu, '\n')
|
|
137
|
+
.replace(/<\/w:p>/gu, '\n')
|
|
138
|
+
.replace(/<[^>]+>/gu, '')
|
|
139
|
+
.replace(/</gu, '<')
|
|
140
|
+
.replace(/>/gu, '>')
|
|
141
|
+
.replace(/"/gu, '"')
|
|
142
|
+
.replace(/'/gu, "'")
|
|
143
|
+
.replace(/&/gu, '&')
|
|
144
|
+
.replace(/[ \t]+\n/gu, '\n')
|
|
145
|
+
.replace(/\n{3,}/gu, '\n\n')
|
|
146
|
+
.trim();
|
|
147
|
+
}
|
|
148
|
+
function stripHtml(html) {
|
|
149
|
+
return html
|
|
150
|
+
.replace(/<script[\s\S]*?<\/script>/giu, '')
|
|
151
|
+
.replace(/<style[\s\S]*?<\/style>/giu, '')
|
|
152
|
+
.replace(/<[^>]+>/gu, '\n')
|
|
153
|
+
.replace(/ /gu, ' ')
|
|
154
|
+
.replace(/&/gu, '&')
|
|
155
|
+
.replace(/\n{3,}/gu, '\n\n')
|
|
156
|
+
.trim();
|
|
157
|
+
}
|
|
158
|
+
/** 识别规则是富文本(<p>/<br/>):块级标签转换行、行内标签直接去掉,转成紧凑纯文本。 */
|
|
159
|
+
function ruleToPlainText(rule) {
|
|
160
|
+
return rule
|
|
161
|
+
.replace(/<br\s*\/?>/giu, '\n')
|
|
162
|
+
.replace(/<\/(?:p|div|li|h[1-6])>/giu, '\n')
|
|
163
|
+
.replace(/<[^>]+>/gu, '')
|
|
164
|
+
.replace(/ /gu, ' ')
|
|
165
|
+
.replace(/</gu, '<')
|
|
166
|
+
.replace(/>/gu, '>')
|
|
167
|
+
.replace(/"/gu, '"')
|
|
168
|
+
.replace(/&/gu, '&')
|
|
169
|
+
.replace(/[ \t]+\n/gu, '\n')
|
|
170
|
+
.replace(/\n{2,}/gu, '\n')
|
|
171
|
+
.trim();
|
|
172
|
+
}
|
|
173
|
+
/** 本地抽正文:只覆盖 docx 与纯文本类;PDF/图片/Excel 交给宿主原生能力读 path。 */ async function extractText(item) {
|
|
174
|
+
if (!item.downloaded || !item.path)
|
|
175
|
+
return {};
|
|
176
|
+
const ext = extname(item.name ?? item.path).toLowerCase();
|
|
177
|
+
try {
|
|
178
|
+
if (ext === '.docx') {
|
|
179
|
+
const buffer = await readFile(item.path);
|
|
180
|
+
const xml = unzipEntry(buffer, 'word/document.xml')?.toString('utf8');
|
|
181
|
+
if (!xml)
|
|
182
|
+
return {};
|
|
183
|
+
const text = xmlToText(xml);
|
|
184
|
+
return text ? { text, chars: text.length } : {};
|
|
185
|
+
}
|
|
186
|
+
if (['.txt', '.md', '.csv', '.json', '.xml', '.html', '.htm'].includes(ext)) {
|
|
187
|
+
const raw = await readFile(item.path, 'utf8');
|
|
188
|
+
const text = ext === '.html' || ext === '.htm' ? stripHtml(raw) : raw.trim();
|
|
189
|
+
return text ? { text, chars: text.length } : {};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return {};
|
|
194
|
+
}
|
|
195
|
+
return {};
|
|
196
|
+
}
|
|
197
|
+
const fill = {
|
|
198
|
+
name: 'smart-extract.fill',
|
|
199
|
+
risk: 'read',
|
|
200
|
+
summary: '一次调用取齐抽取所需的全部入参:流程节点表单结构(压缩串)、识别规则、附件正文(docx 本地抽文本)。返回精简后只含模型需要的内容 + sessionFile;模型据此直接抽取,再调 smart-extract.fill.save 一步落库。',
|
|
201
|
+
inputSchema: schemaOf({
|
|
202
|
+
workflowId: { ...SCHEMA_ID, description: '流程模板 ID(必填)' },
|
|
203
|
+
nodeId: { ...SCHEMA_ID, description: '流程节点 ID;不传自动取发起节点' },
|
|
204
|
+
attachmentIds: {
|
|
205
|
+
oneOf: [
|
|
206
|
+
{ type: 'string', description: '附件 ID,多个用逗号分隔' },
|
|
207
|
+
{ type: 'array', items: { type: 'string' }, description: '附件 ID 数组' },
|
|
208
|
+
],
|
|
209
|
+
description: '待抽取的附件 ID(用户给了就带上;没有就靠 userInput 或表单已有内容)',
|
|
210
|
+
},
|
|
211
|
+
userInput: { type: 'string', description: '用户原始输入(没有附件时的唯一来源,也用于追溯)' },
|
|
212
|
+
targetFieldIdList: {
|
|
213
|
+
type: 'array',
|
|
214
|
+
items: { type: 'string' },
|
|
215
|
+
description: '只抽这些字段 ID(可选,不传就是该节点全部可填字段)',
|
|
216
|
+
},
|
|
217
|
+
}, { required: ['workflowId'] }),
|
|
218
|
+
handler: async (args, env) => {
|
|
219
|
+
const workflowId = optionalId(args.workflowId, 'workflowId');
|
|
220
|
+
if (!workflowId)
|
|
221
|
+
throw smartExtractValidationError('workflow_id_required', 'workflowId 必填');
|
|
222
|
+
const nodeIdInput = optionalId(args.nodeId, 'nodeId');
|
|
223
|
+
const userInput = optionalString(args.userInput, 'userInput');
|
|
224
|
+
const keep = parseIdList(args.targetFieldIdList, 'targetFieldIdList');
|
|
225
|
+
const attachmentIds = parseIdList(args.attachmentIds, 'attachmentIds');
|
|
226
|
+
if (attachmentIds.length > MAX_ATTACHMENTS) {
|
|
227
|
+
throw smartExtractValidationError('too_many_attachments', `一次最多处理 ${MAX_ATTACHMENTS} 个附件,当前 ${attachmentIds.length} 个`);
|
|
228
|
+
}
|
|
229
|
+
const warnings = [];
|
|
230
|
+
let nodeId = nodeIdInput;
|
|
231
|
+
let nodeName;
|
|
232
|
+
if (!nodeId) {
|
|
233
|
+
const start = await resolveStartNode(env.host, workflowId);
|
|
234
|
+
nodeId = start.nodeId;
|
|
235
|
+
nodeName = start.nodeName;
|
|
236
|
+
warnings.push(...start.warnings);
|
|
237
|
+
}
|
|
238
|
+
// 规则 / 结构 / 附件三路并行:彼此无依赖。
|
|
239
|
+
const outDir = env.outDir;
|
|
240
|
+
await mkdir(outDir, { recursive: true });
|
|
241
|
+
const [rules, loaded, downloaded] = await Promise.all([
|
|
242
|
+
fetchRules(env.host, workflowId, nodeId).catch((error) => ({
|
|
243
|
+
globalRule: '',
|
|
244
|
+
fieldRules: [],
|
|
245
|
+
parseFields: [],
|
|
246
|
+
warnings: [`识别规则查询失败(按表单结构自行判断):${error.message.slice(0, 120)}`],
|
|
247
|
+
})),
|
|
248
|
+
fetchWfNodeStructure(env.host, workflowId, nodeId, { keep, ...(nodeName ? { nodeName } : {}) }),
|
|
249
|
+
attachmentIds.length > 0
|
|
250
|
+
? downloadAttachments(env, attachmentIds, outDir, MAX_ATTACHMENT_BYTES)
|
|
251
|
+
: Promise.resolve({ items: [], warnings: [] }),
|
|
252
|
+
]);
|
|
253
|
+
warnings.push(...rules.warnings, ...loaded.warnings, ...downloaded.warnings);
|
|
254
|
+
const structure = loaded.structure;
|
|
255
|
+
const sessionId = shortId('sf');
|
|
256
|
+
const sessionFile = sessionPath(env.stateDir, sessionId);
|
|
257
|
+
// 只回模型用得上的东西:结构用压缩串(ID#名称#标记#单值#类型#选项),
|
|
258
|
+
// 不回 fieldDbName/optionId/appId 这类服务端字段,省上下文也少干扰。
|
|
259
|
+
const basePayload = {
|
|
260
|
+
sessionFile,
|
|
261
|
+
sessionId,
|
|
262
|
+
workflowId,
|
|
263
|
+
nodeId,
|
|
264
|
+
...(nodeName ? { nodeName } : {}),
|
|
265
|
+
mainFormName: structure.mainFormName ?? null,
|
|
266
|
+
fields: {
|
|
267
|
+
main: structure.mainFieldsStr,
|
|
268
|
+
subTables: structure.subTables.map((table) => ({
|
|
269
|
+
subFormId: table.subFormId,
|
|
270
|
+
subFormName: table.subFormName,
|
|
271
|
+
fields: table.subFieldsStr,
|
|
272
|
+
})),
|
|
273
|
+
},
|
|
274
|
+
rules: {
|
|
275
|
+
globalRule: rules.globalRule ? ruleToPlainText(rules.globalRule) : null,
|
|
276
|
+
fieldRules: rules.fieldRules.map(ruleToPlainText),
|
|
277
|
+
parseFields: rules.parseFields,
|
|
278
|
+
},
|
|
279
|
+
resultContract: RESULT_CONTRACT,
|
|
280
|
+
next: fillNextHint(sessionFile),
|
|
281
|
+
};
|
|
282
|
+
// 正文内联额度 = stdout 预算 − 结构/规则/固定说明的实际字节。
|
|
283
|
+
// 简单表单额度富余,整份合同一次进上下文;只有真装不下才落文件让模型读一次。
|
|
284
|
+
const inlineBudgetBytes = Math.floor(DEFAULT_RESULT_THRESHOLD_BYTES * INLINE_BUDGET_RATIO)
|
|
285
|
+
- Buffer.byteLength(JSON.stringify({ ...basePayload, attachments: [] }), 'utf8')
|
|
286
|
+
- ENVELOPE_RESERVE_BYTES;
|
|
287
|
+
const perAttachmentBytes = Math.floor(inlineBudgetBytes / Math.max(1, downloaded.items.length));
|
|
288
|
+
const inlineAllowed = perAttachmentBytes > MIN_INLINE_BYTES_PER_ATTACHMENT;
|
|
289
|
+
const extractedItems = await Promise.all(downloaded.items.map(async (item) => ({
|
|
290
|
+
item,
|
|
291
|
+
...(await extractText(item)),
|
|
292
|
+
})));
|
|
293
|
+
const totalTextBytes = extractedItems.reduce((sum, entry) => sum + Buffer.byteLength(entry.text ?? '', 'utf8'), 0);
|
|
294
|
+
// 全部正文一次装得下就全内联;装不下才按附件均分额度,装不进的那份落文件。
|
|
295
|
+
const allInline = totalTextBytes <= inlineBudgetBytes;
|
|
296
|
+
const attachments = await Promise.all(extractedItems.map(async ({ item, text: extractedText, chars }) => {
|
|
297
|
+
const text = extractedText ?? '';
|
|
298
|
+
const oversized = allInline
|
|
299
|
+
? false
|
|
300
|
+
: !inlineAllowed || Buffer.byteLength(text, 'utf8') > perAttachmentBytes;
|
|
301
|
+
let textFile;
|
|
302
|
+
if (oversized && item.path) {
|
|
303
|
+
textFile = `${item.path}.txt`;
|
|
304
|
+
await mkdir(dirname(textFile), { recursive: true });
|
|
305
|
+
await writeFile(textFile, text, { encoding: 'utf8', mode: 0o600 });
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
fileId: item.fileId,
|
|
309
|
+
name: item.name,
|
|
310
|
+
kind: item.kind ?? null,
|
|
311
|
+
path: item.path ?? null,
|
|
312
|
+
downloaded: item.downloaded,
|
|
313
|
+
...(item.reason ? { reason: item.reason } : {}),
|
|
314
|
+
...(oversized
|
|
315
|
+
? {
|
|
316
|
+
chars,
|
|
317
|
+
textFile,
|
|
318
|
+
textPreview: `${text.slice(0, TEXT_PREVIEW_CHARS)}…`,
|
|
319
|
+
}
|
|
320
|
+
: text
|
|
321
|
+
? { chars, text }
|
|
322
|
+
: {}),
|
|
323
|
+
};
|
|
324
|
+
}));
|
|
325
|
+
const session = {
|
|
326
|
+
sessionId,
|
|
327
|
+
createdAt: new Date().toISOString(),
|
|
328
|
+
workflowId,
|
|
329
|
+
nodeId,
|
|
330
|
+
...(nodeName ? { nodeName } : {}),
|
|
331
|
+
attachmentIds,
|
|
332
|
+
...(userInput ? { userInput } : {}),
|
|
333
|
+
structure,
|
|
334
|
+
rules: { globalRule: rules.globalRule, fieldRules: rules.fieldRules, parseFields: rules.parseFields },
|
|
335
|
+
};
|
|
336
|
+
await mkdir(dirname(sessionFile), { recursive: true, mode: 0o700 });
|
|
337
|
+
await writeFile(sessionFile, JSON.stringify(session), { encoding: 'utf8', mode: 0o600 });
|
|
338
|
+
const noText = attachments.filter((item) => item.downloaded && !item.text && !item.textFile);
|
|
339
|
+
if (noText.length > 0) {
|
|
340
|
+
warnings.push(`以下附件未能本地抽文本,需要读 path(PDF/图片/Excel):${noText.map((item) => item.fileId).join(',')}`);
|
|
341
|
+
}
|
|
342
|
+
return smartExtractSuccess('smart-extract.fill', { ...basePayload, attachments }, { warnings });
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
const fillSave = {
|
|
346
|
+
name: 'smart-extract.fill.save',
|
|
347
|
+
risk: 'high-risk-write',
|
|
348
|
+
summary: '一步收尾:按 sessionFile 取回结构与规则 → 自动整理结果(主表剔除空值并按 fields.main 排序、明细删全空行)→ 确定性校验(不通过直接拒写并回错误清单)→ 写批次记录 → 回查验证,返回 aiExtraId。每次都新建一条记录,不判断是否已存在;不需要预览与人工确认。',
|
|
349
|
+
inputSchema: schemaOf({
|
|
350
|
+
sessionFile: { type: 'string', description: 'smart-extract.fill 返回的 sessionFile 路径' },
|
|
351
|
+
result: { type: 'object', description: '抽取结果(内联)' },
|
|
352
|
+
resultPath: { type: 'string', description: '抽取结果 JSON 文件路径(与 result 二选一)' },
|
|
353
|
+
requestId: { type: 'string', description: `可选:自定义 requestId(≤${MAX_REQUEST_ID_LENGTH} 字符)。默认按 sessionFile 派生,同一次 fill 重试时不会重复入库` },
|
|
354
|
+
dataSource: { type: 'string', description: 'wf-pre / wf-manual / eb-manual,默认 wf-manual' },
|
|
355
|
+
sceneFlag: { type: 'string', description: '场景标识' },
|
|
356
|
+
agentId: { ...SCHEMA_ID, description: '智能体 ID' },
|
|
357
|
+
chatId: { type: 'string', description: '会话 ID' },
|
|
358
|
+
messageId: { type: 'string', description: '消息 ID' },
|
|
359
|
+
}, { required: ['sessionFile'] }),
|
|
360
|
+
handler: async (args, env) => {
|
|
361
|
+
const sessionFile = optionalString(args.sessionFile, 'sessionFile');
|
|
362
|
+
if (!sessionFile)
|
|
363
|
+
throw smartExtractValidationError('session_file_required', 'sessionFile 必填');
|
|
364
|
+
let session;
|
|
365
|
+
try {
|
|
366
|
+
session = JSON.parse(await readFile(sessionFile, 'utf8'));
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
throw smartExtractValidationError('session_unreadable', `无法读取会话文件:${sessionFile}`, {
|
|
370
|
+
details: { reason: error instanceof Error ? error.message : String(error) },
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
if (!session.workflowId || !session.structure) {
|
|
374
|
+
throw smartExtractValidationError('session_invalid', '会话文件缺少 workflowId 或 structure,请重新调 smart-extract.fill');
|
|
375
|
+
}
|
|
376
|
+
const result = await readObjectInput(args, 'result', 'resultPath', { required: true });
|
|
377
|
+
if (!result)
|
|
378
|
+
throw smartExtractValidationError('result_required', '必须提供 result 或 resultPath');
|
|
379
|
+
// 先把结果整理成服务端期望的形态(主表剔除空值并按 fields.main 排序、明细删全空行),
|
|
380
|
+
// 再校验、再落库:服务端不该收到的乱序/空值在这里就消失,不依赖模型自觉。
|
|
381
|
+
const normalized = normalizeResult(result, session.structure);
|
|
382
|
+
// 校验先行:错误结果一律不写库,把错误清单原样回给调用方改。
|
|
383
|
+
const report = validateExtraction(normalized, session.structure, {
|
|
384
|
+
knownAttachmentIds: session.attachmentIds,
|
|
385
|
+
});
|
|
386
|
+
if (!report.ok) {
|
|
387
|
+
throw smartExtractValidationError('result_invalid', `抽取结果校验未通过(${report.stats.errorCount} 个错误),未写库;按 errors 修正后重新调用本命令`, { errors: report.errors, stats: report.stats });
|
|
388
|
+
}
|
|
389
|
+
const { workflowId, nodeId } = session;
|
|
390
|
+
const attachmentIds = session.attachmentIds.join(',');
|
|
391
|
+
const customRequestId = optionalString(args.requestId, 'requestId');
|
|
392
|
+
if (customRequestId && customRequestId.length > MAX_REQUEST_ID_LENGTH) {
|
|
393
|
+
throw smartExtractValidationError('request_id_too_long', `requestId 最多 ${MAX_REQUEST_ID_LENGTH} 个字符(服务端 request_id 列放不下,会直接 500)`, { expected: MAX_REQUEST_ID_LENGTH, actual: customRequestId.length });
|
|
394
|
+
}
|
|
395
|
+
// 不判断「这条记录是否已存在」:每次抽取都新建一条,同样的附件再抽一次就是新记录。
|
|
396
|
+
// requestId 按 sessionFile 派生(sf… → se…):只有「同一次 fill 的重试」才会撞同一个值,
|
|
397
|
+
// 用来兜住「写库成功但响应丢失、模型重跑一次」这一种情况,不影响正常的新建。
|
|
398
|
+
const requestId = customRequestId ?? `se${session.sessionId.replace(/^sf/, '')}`;
|
|
399
|
+
const existingId = await queryByRequestId(env, requestId);
|
|
400
|
+
if (existingId) {
|
|
401
|
+
return smartExtractSuccess('smart-extract.fill.save', {
|
|
402
|
+
aiExtraId: existingId,
|
|
403
|
+
requestId,
|
|
404
|
+
workflowId,
|
|
405
|
+
nodeId,
|
|
406
|
+
retried: true,
|
|
407
|
+
message: '同一次抽取的重试:服务端已有该 requestId 的记录(上次写库实际已成功),本次未重复入库',
|
|
408
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
409
|
+
}
|
|
410
|
+
const dataSource = (() => {
|
|
411
|
+
const text = optionalString(args.dataSource, 'dataSource');
|
|
412
|
+
if (!text)
|
|
413
|
+
return DATA_SOURCE['wf-manual'];
|
|
414
|
+
if (text in DATA_SOURCE)
|
|
415
|
+
return DATA_SOURCE[text];
|
|
416
|
+
if (['0', '1', '2'].includes(text))
|
|
417
|
+
return text;
|
|
418
|
+
throw smartExtractValidationError('data_source_invalid', 'dataSource 只能是 wf-pre / wf-manual / eb-manual 或 0/1/2');
|
|
419
|
+
})();
|
|
420
|
+
const payload = {
|
|
421
|
+
workflowId,
|
|
422
|
+
...(nodeId ? { nodeId } : {}),
|
|
423
|
+
formModeType: 'wf',
|
|
424
|
+
requestId,
|
|
425
|
+
recognizeResult: JSON.stringify(normalized),
|
|
426
|
+
dataSource,
|
|
427
|
+
fillStatus: '0',
|
|
428
|
+
...(attachmentIds ? { attachmentIds } : {}),
|
|
429
|
+
...(session.userInput ? { userInput: session.userInput } : {}),
|
|
430
|
+
...(optionalString(args.sceneFlag, 'sceneFlag') ? { sceneFlag: optionalString(args.sceneFlag, 'sceneFlag') } : {}),
|
|
431
|
+
...(optionalId(args.agentId, 'agentId') ? { agentId: optionalId(args.agentId, 'agentId') } : {}),
|
|
432
|
+
...(optionalString(args.chatId, 'chatId') ? { chatId: optionalString(args.chatId, 'chatId') } : {}),
|
|
433
|
+
...(optionalString(args.messageId, 'messageId') ? { messageId: optionalString(args.messageId, 'messageId') } : {}),
|
|
434
|
+
};
|
|
435
|
+
let saved;
|
|
436
|
+
try {
|
|
437
|
+
saved = await env.host.requestData({
|
|
438
|
+
operation: 'smart-extract.fill.save',
|
|
439
|
+
method: 'POST',
|
|
440
|
+
path: PATHS.saveRecognizeRecord,
|
|
441
|
+
body: payload,
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
if (error instanceof SmartExtractCliError && error.type === 'network') {
|
|
446
|
+
throw smartExtractPartialError('保存请求结果未知(网络中断/超时)。直接重跑本命令即可:同一次 fill 的 requestId 相同,会命中已写入的那条,不会重复入库', { requestId, sessionFile, hint: '重跑同样入参;若返回 retried:true 且带 aiExtraId,就是上一轮已写成功' });
|
|
447
|
+
}
|
|
448
|
+
throw error;
|
|
449
|
+
}
|
|
450
|
+
const root = record(saved);
|
|
451
|
+
const rawId = root.id ?? root.aiExtraId ?? root.batchId;
|
|
452
|
+
if (rawId === undefined || rawId === null) {
|
|
453
|
+
throw smartExtractBusinessError('save_response_invalid', '保存接口未返回 aiExtraId', { details: { result: saved } });
|
|
454
|
+
}
|
|
455
|
+
const aiExtraId = String(rawId);
|
|
456
|
+
// 写完立刻只读回查一次:回给用户的 ID 必须是「库里真能查到」的那条。
|
|
457
|
+
let verified = false;
|
|
458
|
+
try {
|
|
459
|
+
const check = record(await env.host.requestData({
|
|
460
|
+
operation: 'smart-extract.fill.save',
|
|
461
|
+
method: 'GET',
|
|
462
|
+
path: PATHS.batchInfoById,
|
|
463
|
+
query: { id: aiExtraId },
|
|
464
|
+
}));
|
|
465
|
+
verified = Object.keys(check).length > 0;
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
verified = false;
|
|
469
|
+
}
|
|
470
|
+
const mainRows = Array.isArray(record(normalized.mainTable).rows) ? record(normalized.mainTable).rows.length : 0;
|
|
471
|
+
const subRows = Array.isArray(normalized.subTables)
|
|
472
|
+
? normalized.subTables.reduce((total, table) => total + (Array.isArray(table?.rows) ? table.rows.length : 0), 0)
|
|
473
|
+
: 0;
|
|
474
|
+
return smartExtractSuccess('smart-extract.fill.save', {
|
|
475
|
+
aiExtraId,
|
|
476
|
+
verified,
|
|
477
|
+
workflowId,
|
|
478
|
+
nodeId,
|
|
479
|
+
requestId,
|
|
480
|
+
mainRows,
|
|
481
|
+
subRows,
|
|
482
|
+
fills: report.stats.mainFieldsFilled,
|
|
483
|
+
}, {
|
|
484
|
+
meta: { state: verified ? 'COMPLETE' : 'WRITTEN_UNVERIFIED' },
|
|
485
|
+
warnings: [
|
|
486
|
+
...report.warnings.slice(0, 20).map((issue) => issue.message),
|
|
487
|
+
...(verified ? [] : [`已写入但回查未确认(aiExtraId=${aiExtraId}),可稍后用 smart-extract.batch.get 再查一次`]),
|
|
488
|
+
],
|
|
489
|
+
});
|
|
490
|
+
},
|
|
491
|
+
};
|
|
492
|
+
export const fillOperations = [fill, fillSave];
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { smartExtractValidationError } from '../errors.js';
|
|
2
|
+
import { readObjectInput, truncate } from './shared.js';
|
|
3
|
+
import { coerceStructure, valuesOf } from './validate.js';
|
|
4
|
+
import { smartExtractSuccess, schemaOf } from './types.js';
|
|
5
|
+
/**
|
|
6
|
+
* 结果预览(纯本地,排障命令)。
|
|
7
|
+
*
|
|
8
|
+
* 输出「字段 → 值 → 来源」的可读文本,选项字段显示选项名而不是 optionValue。
|
|
9
|
+
*/
|
|
10
|
+
function renderValue(value, options) {
|
|
11
|
+
const values = valuesOf(value);
|
|
12
|
+
if (values.length === 0)
|
|
13
|
+
return '(空)';
|
|
14
|
+
// 选项字段存的是 optionValue("2"),但用户只认选项名(「二审」)——确认表必须显示人话。
|
|
15
|
+
const label = (raw) => {
|
|
16
|
+
if (!options?.length)
|
|
17
|
+
return raw;
|
|
18
|
+
const hit = options.find((option) => option.optionValue === raw.trim());
|
|
19
|
+
return hit ? hit.optionName : raw;
|
|
20
|
+
};
|
|
21
|
+
return truncate(values.map(label).join('、'), 120);
|
|
22
|
+
}
|
|
23
|
+
function renderOrigins(origin, nameOf) {
|
|
24
|
+
if (!Array.isArray(origin) || origin.length === 0)
|
|
25
|
+
return '—';
|
|
26
|
+
const parts = [];
|
|
27
|
+
for (const item of origin) {
|
|
28
|
+
if (typeof item !== 'string')
|
|
29
|
+
continue;
|
|
30
|
+
const hash = item.indexOf('#');
|
|
31
|
+
if (hash <= 0) {
|
|
32
|
+
parts.push(truncate(item, 80));
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const sourceId = item.slice(0, hash);
|
|
36
|
+
const snippet = item.slice(hash + 1);
|
|
37
|
+
const label = sourceId === 'userInput' ? '用户输入' : nameOf(sourceId);
|
|
38
|
+
parts.push(`${label}:${truncate(snippet, 80)}`);
|
|
39
|
+
}
|
|
40
|
+
return parts.join(';') || '—';
|
|
41
|
+
}
|
|
42
|
+
const resultPreview = {
|
|
43
|
+
name: 'smart-extract.result.preview',
|
|
44
|
+
risk: 'read',
|
|
45
|
+
summary: '把抽取结果渲染成人可确认的表格文本(字段→值→来源),并列出未取到值的标记字段。用户确认这份预览后才允许 save.prepare。',
|
|
46
|
+
inputSchema: schemaOf({
|
|
47
|
+
result: { type: 'object', description: '抽取结果(内联)' },
|
|
48
|
+
resultPath: { type: 'string', description: '抽取结果 JSON 文件路径(与 result 二选一)' },
|
|
49
|
+
structure: { type: 'object', description: 'smart-extract.form.structure 的 data(内联)' },
|
|
50
|
+
structurePath: { type: 'string', description: '表单结构 JSON 文件路径(与 structure 二选一)' },
|
|
51
|
+
attachments: {
|
|
52
|
+
type: 'array',
|
|
53
|
+
items: {
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: {
|
|
56
|
+
fileId: { type: 'string' },
|
|
57
|
+
name: { type: 'string' },
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
description: '附件清单(fileId → 名称),用于把来源显示成文件名',
|
|
61
|
+
},
|
|
62
|
+
}, { required: ['structure'] }),
|
|
63
|
+
handler: async (args) => {
|
|
64
|
+
const result = await readObjectInput(args, 'result', 'resultPath', { required: true });
|
|
65
|
+
const structureRaw = await readObjectInput(args, 'structure', 'structurePath', { required: true });
|
|
66
|
+
if (!result || !structureRaw) {
|
|
67
|
+
throw smartExtractValidationError('result_required', '必须提供 result 与 structure');
|
|
68
|
+
}
|
|
69
|
+
const structure = coerceStructure(structureRaw);
|
|
70
|
+
const nameMap = new Map();
|
|
71
|
+
if (Array.isArray(args.attachments)) {
|
|
72
|
+
for (const item of args.attachments) {
|
|
73
|
+
if (!item || typeof item !== 'object')
|
|
74
|
+
continue;
|
|
75
|
+
const fileId = String(item.fileId ?? item.id ?? '').trim();
|
|
76
|
+
const name = String(item.name ?? '').trim();
|
|
77
|
+
if (fileId && name)
|
|
78
|
+
nameMap.set(fileId, name);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const nameOf = (id) => nameMap.get(id) || `附件 ${id}`;
|
|
82
|
+
const mainFields = new Map(structure.mainFields.map((field) => [field.fieldId, field]));
|
|
83
|
+
const subTables = new Map(structure.subTables.map((table) => [table.subFormId, table]));
|
|
84
|
+
const lines = [];
|
|
85
|
+
const filledFieldIds = new Set();
|
|
86
|
+
let mainRowCount = 0;
|
|
87
|
+
let subRowCount = 0;
|
|
88
|
+
const formLabel = structure.mainFormName || `表单 ${structure.mainFormId}`;
|
|
89
|
+
lines.push(`### 抽取结果预览:${formLabel}`);
|
|
90
|
+
const mainRows = result.mainTable && Array.isArray(result.mainTable.rows)
|
|
91
|
+
? result.mainTable.rows
|
|
92
|
+
: [];
|
|
93
|
+
mainRowCount = mainRows.length;
|
|
94
|
+
if (mainRows.length === 0) {
|
|
95
|
+
lines.push('', '_主表没有任何识别结果。_');
|
|
96
|
+
}
|
|
97
|
+
for (const [rowIndex, rowRaw] of mainRows.entries()) {
|
|
98
|
+
const row = rowRaw;
|
|
99
|
+
const label = mainRows.length > 1 ? `主表第 ${row.mainDataId ?? rowIndex + 1} 条` : '主表';
|
|
100
|
+
lines.push('', `**${label}**`, '');
|
|
101
|
+
lines.push('| 字段 | 值 | 依据 | 来源 |');
|
|
102
|
+
lines.push('| --- | --- | --- | --- |');
|
|
103
|
+
for (const fieldRaw of Array.isArray(row.fieldResults) ? row.fieldResults : []) {
|
|
104
|
+
const fieldResult = fieldRaw;
|
|
105
|
+
const fieldInfo = String(fieldResult.fieldInfo ?? '');
|
|
106
|
+
const hash = fieldInfo.indexOf('#');
|
|
107
|
+
const fieldId = hash > 0 ? fieldInfo.slice(0, hash) : fieldInfo;
|
|
108
|
+
const fieldName = hash > 0 ? fieldInfo.slice(hash + 1) : (mainFields.get(fieldId)?.fieldName ?? fieldId);
|
|
109
|
+
filledFieldIds.add(fieldId);
|
|
110
|
+
lines.push(`| ${fieldName} | ${renderValue(fieldResult.value, mainFields.get(fieldId)?.options)} | ${truncate(String(fieldResult.reason ?? '—'), 80)} | ${renderOrigins(fieldResult.origin, nameOf)} |`);
|
|
111
|
+
}
|
|
112
|
+
if (!Array.isArray(row.fieldResults) || row.fieldResults.length === 0) {
|
|
113
|
+
lines.push('| (无字段) | | | |');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const tables = Array.isArray(result.subTables) ? result.subTables : [];
|
|
117
|
+
for (const tableRaw of tables) {
|
|
118
|
+
const table = tableRaw;
|
|
119
|
+
const subFormId = String(table.subFormId ?? '');
|
|
120
|
+
const definition = subTables.get(subFormId);
|
|
121
|
+
const tableName = definition?.subFormName || String(table.subFormName ?? subFormId);
|
|
122
|
+
const fields = Array.isArray(table.fields) ? table.fields.map((item) => String(item)) : [];
|
|
123
|
+
const rows = Array.isArray(table.rows) ? table.rows : [];
|
|
124
|
+
subRowCount += rows.length;
|
|
125
|
+
lines.push('', `**明细表:${tableName}(${rows.length} 行)**`);
|
|
126
|
+
if (rows.length === 0) {
|
|
127
|
+
lines.push('', '_无明细数据。_');
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
for (const [rowIndex, subRowRaw] of rows.entries()) {
|
|
131
|
+
const subRow = subRowRaw;
|
|
132
|
+
lines.push('', `第 ${subRow.subDataId ?? rowIndex + 1} 行(主表 ${subRow.mainDataId ?? '-'})`);
|
|
133
|
+
const values = Array.isArray(subRow.values) ? subRow.values : [];
|
|
134
|
+
const reasons = Array.isArray(subRow.reasons) ? subRow.reasons : [];
|
|
135
|
+
const origins = Array.isArray(subRow.origins) ? subRow.origins : [];
|
|
136
|
+
for (const [fieldIndex, fieldInfo] of fields.entries()) {
|
|
137
|
+
const hash = fieldInfo.indexOf('#');
|
|
138
|
+
const fieldId = hash > 0 ? fieldInfo.slice(0, hash) : fieldInfo;
|
|
139
|
+
const definitionField = definition?.fields.find((field) => field.fieldId === fieldId);
|
|
140
|
+
const fieldName = hash > 0 ? fieldInfo.slice(hash + 1) : (definitionField?.fieldName ?? fieldId);
|
|
141
|
+
filledFieldIds.add(fieldId);
|
|
142
|
+
const value = renderValue(values[fieldIndex], definitionField?.options);
|
|
143
|
+
const reason = reasons[fieldIndex] ? `(${truncate(String(reasons[fieldIndex]), 60)})` : '';
|
|
144
|
+
lines.push(`- ${fieldName}:${value}${reason}${origins[fieldIndex] ? ` ← ${renderOrigins(origins[fieldIndex], nameOf)}` : ''}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const missingMarked = structure.mainFields
|
|
149
|
+
.filter((field) => field.marked && !filledFieldIds.has(field.fieldId))
|
|
150
|
+
.map((field) => ({ fieldId: field.fieldId, fieldName: field.fieldName }));
|
|
151
|
+
if (missingMarked.length > 0) {
|
|
152
|
+
lines.push('', '**未取到值的标记字段(可能需要向用户追问)**');
|
|
153
|
+
for (const field of missingMarked)
|
|
154
|
+
lines.push(`- ${field.fieldName}`);
|
|
155
|
+
}
|
|
156
|
+
const emptyFieldCount = structure.mainFields.length - filledFieldIds.size;
|
|
157
|
+
lines.push('', '---', '以上为本次抽取结果。**确认无误后才会保存**;如需修改请直接说改哪个字段。');
|
|
158
|
+
return smartExtractSuccess('smart-extract.result.preview', {
|
|
159
|
+
previewText: lines.join('\n'),
|
|
160
|
+
mainRowCount,
|
|
161
|
+
subRowCount,
|
|
162
|
+
subTableCount: tables.length,
|
|
163
|
+
structureFieldCount: structure.mainFields.length,
|
|
164
|
+
missingMarkedFields: missingMarked,
|
|
165
|
+
untouchedFieldCount: Math.max(0, emptyFieldCount),
|
|
166
|
+
confirmationHint: '把 previewText 原样贴给用户并要求明确确认(是/可以/保存);用户确认后才调 smart-extract.save.prepare',
|
|
167
|
+
}, {
|
|
168
|
+
warnings: missingMarked.length > 0
|
|
169
|
+
? [`有 ${missingMarked.length} 个标记字段没抽到值,确认时应主动提示用户`]
|
|
170
|
+
: [],
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
export const previewOperations = [resultPreview];
|