weaver-work-cli 0.1.49 → 0.1.52
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-MU2LPI5P.js → attachment-content-MBYYSQIX.js} +3 -3
- package/dist/chunks/{chunk-ZKEUGS2U.js → chunk-7UOXOGFL.js} +4 -4
- package/dist/chunks/{chunk-72MI3MBX.js → chunk-ATEXBEPD.js} +55 -15
- package/dist/chunks/{chunk-3NV2ETZR.js → chunk-D3TDNRFE.js} +8 -8
- package/dist/chunks/{chunk-6GWU63YF.js → chunk-DZOC77ZD.js} +1 -1
- package/dist/chunks/{chunk-K3BT54CU.js → chunk-IRMA3GVP.js} +1 -1
- package/dist/chunks/{chunk-3X7VOSBA.js → chunk-KLZ3ULQQ.js} +1 -1
- package/dist/chunks/{chunk-YLCYX7LE.js → chunk-KMRT7NAT.js} +18 -5
- package/dist/chunks/{chunk-NBEWUR7L.js → chunk-LALWNK6M.js} +167 -44
- package/dist/chunks/{chunk-BRRW7CWA.js → chunk-LM2H7SZI.js} +26 -26
- package/dist/chunks/{chunk-KV5SOWMS.js → chunk-LTRLF6MM.js} +4 -4
- package/dist/chunks/{chunk-D2QRZUW4.js → chunk-RPRFIG6I.js} +35 -28
- package/dist/chunks/{chunk-GEOMANP7.js → chunk-RWFRZSIP.js} +2 -2
- package/dist/chunks/{chunk-EJVA5ZVB.js → chunk-ZRHKGQRQ.js} +2 -2
- package/dist/chunks/{conflict-6347A7YK.js → conflict-D2HYKBMH.js} +2 -2
- package/dist/chunks/{contract-N6P2HIIE.js → contract-MFOFMM2J.js} +4284 -254
- package/dist/chunks/{create-flow-7WG7LVX5.js → create-flow-7ZATJVTM.js} +6 -6
- package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
- package/dist/chunks/{env-LHRKSLG6.js → env-5DO4YENS.js} +2 -2
- package/dist/chunks/{factory-2H7Z4RWJ.js → factory-3M7D7WJC.js} +1 -1
- package/dist/chunks/{fna-ZVB2IILI.js → fna-ECOYBQYL.js} +328 -5
- package/dist/chunks/{group-chat-EW6PNDDT.js → group-chat-B2HT5NEO.js} +3 -3
- package/dist/chunks/{im-3RCNL5GT.js → im-TN2JYVGJ.js} +2 -2
- package/dist/chunks/{invoice-FXWH5GPO.js → invoice-V7ZTITUO.js} +726 -206
- package/dist/chunks/{meeting-N2FQBHXI.js → meeting-HZOX3CBB.js} +10 -10
- package/dist/chunks/{msg-parse-4GSQ2WTO.js → msg-parse-FPFVPMYI.js} +5 -1
- package/dist/chunks/{reception-MYOKJULO.js → reception-QGPNTGHG.js} +98 -82
- package/dist/chunks/{recruit-stage-FKWS5UQF.js → recruit-stage-XCMVEQA2.js} +718 -131
- package/dist/chunks/{registry-BUTEDK3C.js → registry-E5RQJVWN.js} +2 -2
- package/dist/chunks/{registry-7VZ6YJUF.js → registry-KYPFFQIH.js} +1 -1
- package/dist/chunks/{registry-CKUVBS53.js → registry-SJHSBO5G.js} +10 -10
- package/dist/chunks/{room-recommend-MBCYENQ2.js → room-recommend-5AHR4YQV.js} +4 -4
- package/dist/chunks/{schedule-5IFMCXME.js → schedule-KZPJUPC2.js} +4 -4
- package/dist/chunks/smart-extract-IXHCZE4R.js +2846 -0
- package/dist/chunks/{workflow-2TRU2ZSP.js → workflow-UHKCZJMY.js} +1 -1
- package/dist/index.js +14 -9
- package/dist/shortcuts/contract/host.js +11 -0
- package/dist/shortcuts/contract/index.js +13 -0
- package/dist/shortcuts/contract/manifest.js +204 -0
- package/dist/shortcuts/contract/operations/card-action.js +585 -0
- package/dist/shortcuts/contract/operations/card-ebdf-list.js +315 -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/elements-build.js +714 -0
- package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
- package/dist/shortcuts/contract/operations/first-screen.js +563 -0
- package/dist/shortcuts/contract/operations/flow.js +81 -25
- 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 +58 -7
- package/dist/shortcuts/contract/operations/quote.js +410 -22
- package/dist/shortcuts/contract/operations/registry.js +22 -0
- package/dist/shortcuts/contract/operations/review.js +73 -58
- package/dist/shortcuts/contract/operations/save-recognize.js +151 -0
- package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
- package/dist/shortcuts/contract/operations/summary.js +4 -2
- 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/fna/host.js +4 -2
- package/dist/shortcuts/fna/manifest.js +14 -5
- package/dist/shortcuts/fna/operations/audit.js +334 -0
- package/dist/shortcuts/fna/operations/registry.js +2 -0
- package/dist/shortcuts/im/operations/at-mention.js +6 -3
- package/dist/shortcuts/im/operations/msg-parse.js +35 -5
- package/dist/shortcuts/im/operations/msg-sync.js +3 -1
- package/dist/shortcuts/im/operations/msg-write.js +57 -9
- package/dist/shortcuts/index.js +5 -0
- package/dist/shortcuts/invoice/index.js +0 -12
- package/dist/shortcuts/invoice/manifest.js +201 -50
- 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/meeting/operations/from-group-chat.js +16 -2
- package/dist/shortcuts/reception/constants.js +3 -7
- package/dist/shortcuts/reception/operations/leads.js +30 -6
- package/dist/shortcuts/reception/operations/panels.js +3 -2
- 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 +489 -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 +408 -0
- package/dist/shortcuts/workflow/operations/read.js +77 -15
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +140 -24
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +42 -14
- package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +4 -6
- package/docs/SKILL.md +1 -1
- package/docs/_catalog.md +4 -1
- package/docs/agent-invoice.md +5 -7
- package/docs/data.md +5 -1
- package/docs/fna.md +24 -4
- package/docs/invoice.md +7 -5
- package/docs/smart-extract.md +156 -0
- package/package.json +1 -1
- package/skill-template/business-info.json +21 -1
- package/skill-template/domains/qiyecheng.md +6 -2
- 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 +159 -11
- package/skills/weaver-e10-jinchengda/references/contract-action-card.md +13 -8
- package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +5 -4
- package/skills/weaver-e10-jinchengda/references/contract-clause-library-crud.md +44 -2
- package/skills/weaver-e10-jinchengda/references/contract-command-index.md +2 -2
- package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +220 -0
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +68 -33
- package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +26 -15
- package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +1 -1
- package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
- package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +90 -0
- package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +96 -2
- package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +167 -5
- package/skills/weaver-e10-jinchengda/scripts/contract_first_screen.py +200 -0
- package/skills/weaver-e10-jinchengda/scripts/fill_contract_from_quote.py +572 -0
- package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +997 -0
- package/skills/weaver-e10-jinchengda/scripts/quote_screen.py +560 -0
- package/skills/weaver-e10-jinchengda/scripts/triage_contract.py +894 -0
- package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +93 -0
- package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +118 -0
- package/skills/weaver-e10-qiyecheng/SKILL.md +58 -7
- package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +118 -0
- package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
- package/skills/weaver-e10-qiyecheng/references/catalog.md +42 -3
- 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 +153 -40
- package/skills/weaver-e10-reception-flow/SKILL.md +43 -6
- package/skills/weaver-e10-reception-flow/references/guide.md +1 -1
- 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 -40
- 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 +169 -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 +105 -0
- package/skills/weaver-e10-workflow/SKILL.md +2 -1
- package/skills/weaver-e10-workflow/references/todo-smart-convert.md +29 -6
- 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-workflow/tools/todo-summary.cjs +162 -10
- package/skills/weaver-e10-yepiaotong/SKILL.md +53 -35
- 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-issuing-workflow.md +19 -32
- 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 +18 -53
- package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
- package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +96 -7
- package/skills/weaver-e10-yepiaotong/references/reim-examples.md +5 -38
- package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +14 -14
- package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
- package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +139 -94
- package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +131 -58
- package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
- package/skills/weaver-e10-yimiaoban/SKILL.md +8 -6
- package/skills/weaver-e10-yimiaoban/references/msg-read.md +20 -0
- package/skills/weaver-e10-yimiaoban/references/msg-write.md +7 -0
- package/skills/weaver-e10-yimiaoban/references/source-manifest.json +18 -15
- 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_risk_report.py +0 -358
- package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { PATHS } from '../constants.js';
|
|
2
|
+
import { smartExtractBusinessError } from '../errors.js';
|
|
3
|
+
import { record } from '../host.js';
|
|
4
|
+
import { requiredId } from './shared.js';
|
|
5
|
+
import { smartExtractSuccess, schemaOf, SCHEMA_ID } from './types.js';
|
|
6
|
+
/**
|
|
7
|
+
* 批次回查(只读)。
|
|
8
|
+
*
|
|
9
|
+
* 两个用途:
|
|
10
|
+
* 1. 保存后验证真的落库了(而不是只信 apply 的返回);
|
|
11
|
+
* 2. apply 出现 `write_uncertain` 时,**唯一允许的下一步**——查到了就说明已成功,
|
|
12
|
+
* 查不到才允许重新 prepare,绝不能直接重试写请求。
|
|
13
|
+
*/
|
|
14
|
+
const batchGet = {
|
|
15
|
+
name: 'smart-extract.batch.get',
|
|
16
|
+
risk: 'read',
|
|
17
|
+
summary: '按 aiExtraId 回查已保存的抽取记录(只读)。用于保存后校验,以及 write_uncertain 时判定到底有没有落库。',
|
|
18
|
+
inputSchema: schemaOf({
|
|
19
|
+
id: { ...SCHEMA_ID, description: '抽取记录 ID aiExtraId(save.apply 返回的 aiExtraId)' },
|
|
20
|
+
includeResult: { type: 'boolean', description: '是否返回完整 recognizeResult,默认 true' },
|
|
21
|
+
}, { required: ['id'] }),
|
|
22
|
+
handler: async (args, env) => {
|
|
23
|
+
const id = requiredId(args.id, 'id');
|
|
24
|
+
const includeResult = args.includeResult !== false;
|
|
25
|
+
const data = await env.host.requestData({
|
|
26
|
+
operation: 'smart-extract.batch.get',
|
|
27
|
+
method: 'GET',
|
|
28
|
+
path: PATHS.batchInfoById,
|
|
29
|
+
query: { id },
|
|
30
|
+
});
|
|
31
|
+
const batch = record(data);
|
|
32
|
+
if (!batch.id) {
|
|
33
|
+
throw smartExtractBusinessError('batch_not_found', `批次 ${id} 不存在或无权查看`, { details: { id } });
|
|
34
|
+
}
|
|
35
|
+
let recognizeResult;
|
|
36
|
+
if (includeResult && typeof batch.recognizeResult === 'string' && batch.recognizeResult.trim()) {
|
|
37
|
+
try {
|
|
38
|
+
recognizeResult = JSON.parse(batch.recognizeResult);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
recognizeResult = batch.recognizeResult;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const mainRows = (() => {
|
|
45
|
+
const parsed = record(recognizeResult);
|
|
46
|
+
const rows = parsed.mainTable && Array.isArray(parsed.mainTable.rows) ? parsed.mainTable.rows : [];
|
|
47
|
+
return rows.length;
|
|
48
|
+
})();
|
|
49
|
+
return smartExtractSuccess('smart-extract.batch.get', {
|
|
50
|
+
exists: true,
|
|
51
|
+
aiExtraId: String(batch.id),
|
|
52
|
+
workflowId: batch.workflowId ?? null,
|
|
53
|
+
nodeId: batch.nodeId ?? null,
|
|
54
|
+
requestId: batch.requestId ?? null,
|
|
55
|
+
formModeType: batch.formModeType ?? null,
|
|
56
|
+
fillStatus: batch.fillStatus ?? null,
|
|
57
|
+
dataSource: batch.dataSource ?? null,
|
|
58
|
+
attachmentIds: batch.attachmentIds ?? null,
|
|
59
|
+
createTime: batch.createTime ?? null,
|
|
60
|
+
creator: batch.creator ?? null,
|
|
61
|
+
mainRowCount: mainRows,
|
|
62
|
+
hasTableStructure: Boolean(batch.tableStructure),
|
|
63
|
+
...(includeResult ? { recognizeResult: recognizeResult ?? null } : {}),
|
|
64
|
+
});
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
export const batchOperations = [batchGet];
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { PATHS } from '../constants.js';
|
|
2
|
+
import { smartExtractValidationError } from '../errors.js';
|
|
3
|
+
import { record } from '../host.js';
|
|
4
|
+
import { smartExtractSuccess, schemaOf } from './types.js';
|
|
5
|
+
import { optionalId, optionalString } from './shared.js';
|
|
6
|
+
/**
|
|
7
|
+
* 识别规则:E10 后台「智能填单配置」里配的那套东西。
|
|
8
|
+
*
|
|
9
|
+
* 它决定三件事:
|
|
10
|
+
* 1. 这次只解析哪些字段(parseFields);
|
|
11
|
+
* 2. 全局补充规则 + 每字段补充规则(globalRule / fieldRules);
|
|
12
|
+
* 3. 附件放在哪个字段(attachmentFieldId)。
|
|
13
|
+
*
|
|
14
|
+
* CLI 只负责取出来并整理成模型好读的形状,不做任何规则解释。
|
|
15
|
+
*/
|
|
16
|
+
function splitCsv(value) {
|
|
17
|
+
if (!value)
|
|
18
|
+
return [];
|
|
19
|
+
return String(value)
|
|
20
|
+
.split(/[,;,;]/u)
|
|
21
|
+
.map((item) => item.trim())
|
|
22
|
+
.filter(Boolean);
|
|
23
|
+
}
|
|
24
|
+
const configList = {
|
|
25
|
+
name: 'smart-extract.config.list',
|
|
26
|
+
risk: 'read',
|
|
27
|
+
summary: '取该流程/表单配置的识别规则(全局补充规则、每字段补充规则、需解析字段、附件字段)。分页接口,默认只取启用中的配置。',
|
|
28
|
+
inputSchema: schemaOf({
|
|
29
|
+
modeType: { type: 'string', enum: ['wf', 'eb'], description: '数据源类型;与 sourceId 一起用' },
|
|
30
|
+
sourceId: { ...{ oneOf: [{ type: 'integer' }, { type: 'string', pattern: '^\\d+$' }] },
|
|
31
|
+
description: '流程 ID(wf)或 EB 表单 ID(eb)' },
|
|
32
|
+
wfNodeId: { ...{ oneOf: [{ type: 'integer' }, { type: 'string', pattern: '^\\d+$' }] },
|
|
33
|
+
description: '流程节点 ID:查该节点上的配置(可选)' },
|
|
34
|
+
enabled: { type: 'integer', enum: [0, 1], description: '只看启用(1)/停用(0);不传返回全部' },
|
|
35
|
+
pageSize: { type: 'integer', description: '每页条数,默认 50,最大 200' },
|
|
36
|
+
}),
|
|
37
|
+
handler: async (args, env) => {
|
|
38
|
+
const modeType = optionalString(args.modeType, 'modeType');
|
|
39
|
+
if (modeType && modeType !== 'wf' && modeType !== 'eb') {
|
|
40
|
+
throw smartExtractValidationError('mode_type_invalid', 'modeType 只能是 wf 或 eb');
|
|
41
|
+
}
|
|
42
|
+
const sourceId = optionalId(args.sourceId, 'sourceId');
|
|
43
|
+
const wfNodeId = optionalId(args.wfNodeId, 'wfNodeId');
|
|
44
|
+
const enabled = args.enabled === undefined || args.enabled === null ? undefined : Number(args.enabled);
|
|
45
|
+
if (enabled !== undefined && enabled !== 0 && enabled !== 1) {
|
|
46
|
+
throw smartExtractValidationError('enabled_invalid', 'enabled 只能是 0 或 1');
|
|
47
|
+
}
|
|
48
|
+
const pageSize = Math.max(1, Math.min(200, Number(args.pageSize ?? 50) || 50));
|
|
49
|
+
const body = { current: 1, pageSize };
|
|
50
|
+
if (modeType)
|
|
51
|
+
body.modeType = modeType;
|
|
52
|
+
if (sourceId)
|
|
53
|
+
body.sourceId = sourceId;
|
|
54
|
+
if (wfNodeId)
|
|
55
|
+
body.wfNodeId = wfNodeId;
|
|
56
|
+
if (enabled !== undefined)
|
|
57
|
+
body.enabled = enabled;
|
|
58
|
+
const page = record(await env.host.requestData({
|
|
59
|
+
operation: 'smart-extract.config.list',
|
|
60
|
+
method: 'POST',
|
|
61
|
+
path: PATHS.configList,
|
|
62
|
+
body,
|
|
63
|
+
}));
|
|
64
|
+
const records = Array.isArray(page.records) ? page.records : [];
|
|
65
|
+
const configs = records.map((item) => {
|
|
66
|
+
const config = record(item);
|
|
67
|
+
const rules = (Array.isArray(config.fieldRules) ? config.fieldRules : []).map((rule) => {
|
|
68
|
+
const entry = record(rule);
|
|
69
|
+
return {
|
|
70
|
+
fieldId: entry.fieldId ?? null,
|
|
71
|
+
fieldName: entry.fieldInfo?.fieldName ?? null,
|
|
72
|
+
fieldAlias: entry.fieldAlias ?? null,
|
|
73
|
+
fieldRule: entry.fieldRule ?? null,
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
id: config.id ?? null,
|
|
78
|
+
enabled: config.enabled ?? null,
|
|
79
|
+
modeType: config.modeType ?? null,
|
|
80
|
+
sourceId: config.sourceId ?? null,
|
|
81
|
+
wfNodeIds: splitCsv(config.wfNodeIds),
|
|
82
|
+
layoutId: config.layoutId ?? null,
|
|
83
|
+
listId: config.listId ?? null,
|
|
84
|
+
parseFields: splitCsv(config.parseFields),
|
|
85
|
+
attachmentFieldId: config.attachmentFieldId ?? null,
|
|
86
|
+
needSourceReason: config.needSourceReason ?? null,
|
|
87
|
+
filterField: config.filterField ?? null,
|
|
88
|
+
agentId: config.agentId ?? null,
|
|
89
|
+
globalRule: config.globalRule ?? '',
|
|
90
|
+
fieldRules: rules,
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
const enabledConfigs = configs.filter((config) => config.enabled === 1);
|
|
94
|
+
const effective = enabledConfigs.length > 0 ? enabledConfigs : configs;
|
|
95
|
+
const warnings = [];
|
|
96
|
+
if (configs.length === 0) {
|
|
97
|
+
warnings.push('该目标没有配置识别规则;仍可抽取,但只能按表单结构本身的字段名/类型判断');
|
|
98
|
+
}
|
|
99
|
+
if (configs.length > 1) {
|
|
100
|
+
warnings.push(`命中 ${configs.length} 条配置,请按 wfNodeIds/layoutId 选与本次目标一致的那条,不要混用规则`);
|
|
101
|
+
}
|
|
102
|
+
return smartExtractSuccess('smart-extract.config.list', {
|
|
103
|
+
total: Number(page.total ?? configs.length),
|
|
104
|
+
count: configs.length,
|
|
105
|
+
configs,
|
|
106
|
+
effective: effective.map((config) => config.id),
|
|
107
|
+
/** 供直接塞进提示词的两段文本(为空则整段忽略)。 */
|
|
108
|
+
promptFragments: {
|
|
109
|
+
globalRule: effective.map((config) => config.globalRule).filter(Boolean).join('\n'),
|
|
110
|
+
fieldRules: effective.flatMap((config) => config.fieldRules
|
|
111
|
+
.filter((rule) => rule.fieldRule && (rule.fieldName || rule.fieldId))
|
|
112
|
+
.map((rule) => `${rule.fieldName || rule.fieldId}#${rule.fieldRule}`)),
|
|
113
|
+
parseFields: effective.flatMap((config) => config.parseFields),
|
|
114
|
+
},
|
|
115
|
+
}, { warnings });
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
export const configOperations = [configList];
|
|
@@ -0,0 +1,489 @@
|
|
|
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 { 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 取回结构与规则 → 确定性校验抽取结果(不通过直接拒写并回错误清单)→ 写批次记录 → 回查验证,返回 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
|
+
// 校验先行:错误结果一律不写库,把错误清单原样回给调用方改。
|
|
380
|
+
const report = validateExtraction(result, session.structure, {
|
|
381
|
+
knownAttachmentIds: session.attachmentIds,
|
|
382
|
+
});
|
|
383
|
+
if (!report.ok) {
|
|
384
|
+
throw smartExtractValidationError('result_invalid', `抽取结果校验未通过(${report.stats.errorCount} 个错误),未写库;按 errors 修正后重新调用本命令`, { errors: report.errors, stats: report.stats });
|
|
385
|
+
}
|
|
386
|
+
const { workflowId, nodeId } = session;
|
|
387
|
+
const attachmentIds = session.attachmentIds.join(',');
|
|
388
|
+
const customRequestId = optionalString(args.requestId, 'requestId');
|
|
389
|
+
if (customRequestId && customRequestId.length > MAX_REQUEST_ID_LENGTH) {
|
|
390
|
+
throw smartExtractValidationError('request_id_too_long', `requestId 最多 ${MAX_REQUEST_ID_LENGTH} 个字符(服务端 request_id 列放不下,会直接 500)`, { expected: MAX_REQUEST_ID_LENGTH, actual: customRequestId.length });
|
|
391
|
+
}
|
|
392
|
+
// 不判断「这条记录是否已存在」:每次抽取都新建一条,同样的附件再抽一次就是新记录。
|
|
393
|
+
// requestId 按 sessionFile 派生(sf… → se…):只有「同一次 fill 的重试」才会撞同一个值,
|
|
394
|
+
// 用来兜住「写库成功但响应丢失、模型重跑一次」这一种情况,不影响正常的新建。
|
|
395
|
+
const requestId = customRequestId ?? `se${session.sessionId.replace(/^sf/, '')}`;
|
|
396
|
+
const existingId = await queryByRequestId(env, requestId);
|
|
397
|
+
if (existingId) {
|
|
398
|
+
return smartExtractSuccess('smart-extract.fill.save', {
|
|
399
|
+
aiExtraId: existingId,
|
|
400
|
+
requestId,
|
|
401
|
+
workflowId,
|
|
402
|
+
nodeId,
|
|
403
|
+
retried: true,
|
|
404
|
+
message: '同一次抽取的重试:服务端已有该 requestId 的记录(上次写库实际已成功),本次未重复入库',
|
|
405
|
+
}, { meta: { state: 'ALREADY_SAVED' } });
|
|
406
|
+
}
|
|
407
|
+
const dataSource = (() => {
|
|
408
|
+
const text = optionalString(args.dataSource, 'dataSource');
|
|
409
|
+
if (!text)
|
|
410
|
+
return DATA_SOURCE['wf-manual'];
|
|
411
|
+
if (text in DATA_SOURCE)
|
|
412
|
+
return DATA_SOURCE[text];
|
|
413
|
+
if (['0', '1', '2'].includes(text))
|
|
414
|
+
return text;
|
|
415
|
+
throw smartExtractValidationError('data_source_invalid', 'dataSource 只能是 wf-pre / wf-manual / eb-manual 或 0/1/2');
|
|
416
|
+
})();
|
|
417
|
+
const payload = {
|
|
418
|
+
workflowId,
|
|
419
|
+
...(nodeId ? { nodeId } : {}),
|
|
420
|
+
formModeType: 'wf',
|
|
421
|
+
requestId,
|
|
422
|
+
recognizeResult: JSON.stringify(result),
|
|
423
|
+
dataSource,
|
|
424
|
+
fillStatus: '0',
|
|
425
|
+
...(attachmentIds ? { attachmentIds } : {}),
|
|
426
|
+
...(session.userInput ? { userInput: session.userInput } : {}),
|
|
427
|
+
...(optionalString(args.sceneFlag, 'sceneFlag') ? { sceneFlag: optionalString(args.sceneFlag, 'sceneFlag') } : {}),
|
|
428
|
+
...(optionalId(args.agentId, 'agentId') ? { agentId: optionalId(args.agentId, 'agentId') } : {}),
|
|
429
|
+
...(optionalString(args.chatId, 'chatId') ? { chatId: optionalString(args.chatId, 'chatId') } : {}),
|
|
430
|
+
...(optionalString(args.messageId, 'messageId') ? { messageId: optionalString(args.messageId, 'messageId') } : {}),
|
|
431
|
+
};
|
|
432
|
+
let saved;
|
|
433
|
+
try {
|
|
434
|
+
saved = await env.host.requestData({
|
|
435
|
+
operation: 'smart-extract.fill.save',
|
|
436
|
+
method: 'POST',
|
|
437
|
+
path: PATHS.saveRecognizeRecord,
|
|
438
|
+
body: payload,
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
catch (error) {
|
|
442
|
+
if (error instanceof SmartExtractCliError && error.type === 'network') {
|
|
443
|
+
throw smartExtractPartialError('保存请求结果未知(网络中断/超时)。直接重跑本命令即可:同一次 fill 的 requestId 相同,会命中已写入的那条,不会重复入库', { requestId, sessionFile, hint: '重跑同样入参;若返回 retried:true 且带 aiExtraId,就是上一轮已写成功' });
|
|
444
|
+
}
|
|
445
|
+
throw error;
|
|
446
|
+
}
|
|
447
|
+
const root = record(saved);
|
|
448
|
+
const rawId = root.id ?? root.aiExtraId ?? root.batchId;
|
|
449
|
+
if (rawId === undefined || rawId === null) {
|
|
450
|
+
throw smartExtractBusinessError('save_response_invalid', '保存接口未返回 aiExtraId', { details: { result: saved } });
|
|
451
|
+
}
|
|
452
|
+
const aiExtraId = String(rawId);
|
|
453
|
+
// 写完立刻只读回查一次:回给用户的 ID 必须是「库里真能查到」的那条。
|
|
454
|
+
let verified = false;
|
|
455
|
+
try {
|
|
456
|
+
const check = record(await env.host.requestData({
|
|
457
|
+
operation: 'smart-extract.fill.save',
|
|
458
|
+
method: 'GET',
|
|
459
|
+
path: PATHS.batchInfoById,
|
|
460
|
+
query: { id: aiExtraId },
|
|
461
|
+
}));
|
|
462
|
+
verified = Object.keys(check).length > 0;
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
verified = false;
|
|
466
|
+
}
|
|
467
|
+
const mainRows = Array.isArray(record(result.mainTable).rows) ? record(result.mainTable).rows.length : 0;
|
|
468
|
+
const subRows = Array.isArray(result.subTables)
|
|
469
|
+
? result.subTables.reduce((total, table) => total + (Array.isArray(table?.rows) ? table.rows.length : 0), 0)
|
|
470
|
+
: 0;
|
|
471
|
+
return smartExtractSuccess('smart-extract.fill.save', {
|
|
472
|
+
aiExtraId,
|
|
473
|
+
verified,
|
|
474
|
+
workflowId,
|
|
475
|
+
nodeId,
|
|
476
|
+
requestId,
|
|
477
|
+
mainRows,
|
|
478
|
+
subRows,
|
|
479
|
+
fills: report.stats.mainFieldsFilled,
|
|
480
|
+
}, {
|
|
481
|
+
meta: { state: verified ? 'COMPLETE' : 'WRITTEN_UNVERIFIED' },
|
|
482
|
+
warnings: [
|
|
483
|
+
...report.warnings.slice(0, 20).map((issue) => issue.message),
|
|
484
|
+
...(verified ? [] : [`已写入但回查未确认(aiExtraId=${aiExtraId}),可稍后用 smart-extract.batch.get 再查一次`]),
|
|
485
|
+
],
|
|
486
|
+
});
|
|
487
|
+
},
|
|
488
|
+
};
|
|
489
|
+
export const fillOperations = [fill, fillSave];
|