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