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.
Files changed (191) hide show
  1. package/README.md +1 -1
  2. package/dist/chunks/{attachment-content-EJYIOJPH.js → attachment-content-W3TSJC3Y.js} +3 -3
  3. package/dist/chunks/{chunk-BFKLQLBK.js → chunk-2J3XY4ED.js} +7 -7
  4. package/dist/chunks/{chunk-K67FODVC.js → chunk-6GCXWKG6.js} +1 -1
  5. package/dist/chunks/{chunk-WNJUGI2F.js → chunk-76PRVYH4.js} +1 -1
  6. package/dist/chunks/{chunk-RYFRGTUV.js → chunk-DEHJ7PMA.js} +4 -4
  7. package/dist/chunks/{chunk-3NCFFHB2.js → chunk-IF33CG4V.js} +1 -1
  8. package/dist/chunks/{chunk-YB3AJYPY.js → chunk-PE334WL3.js} +4 -4
  9. package/dist/chunks/{chunk-MCZG6HPM.js → chunk-QQXMHM3J.js} +2 -2
  10. package/dist/chunks/{chunk-7ECB22G3.js → chunk-U7ROML5E.js} +23 -23
  11. package/dist/chunks/{chunk-7AYQJSFY.js → chunk-WTLQGS6D.js} +2 -2
  12. package/dist/chunks/{chunk-6T53BSWZ.js → chunk-XPQN4E5O.js} +50 -19
  13. package/dist/chunks/{chunk-HARQF5IP.js → chunk-Z4G7LLDD.js} +25 -25
  14. package/dist/chunks/{conflict-C4UDHCWV.js → conflict-57WDJWL7.js} +2 -2
  15. package/dist/chunks/{contract-VUC6JOPG.js → contract-LJRAXVZU.js} +8587 -1421
  16. package/dist/chunks/{create-flow-6OG2LYBD.js → create-flow-3FMMZBCA.js} +6 -6
  17. package/dist/chunks/{data-QO7QWOIV.js → data-WK5CQXNF.js} +17 -32
  18. package/dist/chunks/{env-WP57TF2S.js → env-JYZE3BZB.js} +2 -2
  19. package/dist/chunks/{factory-VUXI7N5C.js → factory-66SCIKW3.js} +1 -1
  20. package/dist/chunks/{group-chat-UQRGXILK.js → group-chat-MNRYMLNG.js} +3 -3
  21. package/dist/chunks/{invoice-E7GOITEU.js → invoice-V7ZTITUO.js} +725 -205
  22. package/dist/chunks/{meeting-4BBLVAWM.js → meeting-IIY4UAJL.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-CJOVECZD.js} +1 -1
  25. package/dist/chunks/{registry-5CRCN2TV.js → registry-METZ2LWE.js} +10 -10
  26. package/dist/chunks/{room-recommend-AYR3UG7R.js → room-recommend-YFY7HTOF.js} +4 -4
  27. package/dist/chunks/{schedule-JZEFIXUS.js → schedule-6I63TERA.js} +4 -4
  28. package/dist/chunks/smart-extract-FOUYNIG3.js +2882 -0
  29. package/dist/chunks/{workflow-3ZAF2J5E.js → workflow-YHXFIU63.js} +1 -1
  30. package/dist/index.js +11 -6
  31. package/dist/shortcuts/contract/manifest.js +251 -0
  32. package/dist/shortcuts/contract/ooxml/docx-table.js +233 -0
  33. package/dist/shortcuts/contract/operations/card-action.js +1165 -0
  34. package/dist/shortcuts/contract/operations/card-ebdf-list.js +571 -0
  35. package/dist/shortcuts/contract/operations/card-plan.js +327 -0
  36. package/dist/shortcuts/contract/operations/card-risk-report.js +565 -0
  37. package/dist/shortcuts/contract/operations/card.js +6 -5
  38. package/dist/shortcuts/contract/operations/docx-fillfromquote.js +532 -0
  39. package/dist/shortcuts/contract/operations/docx-verify.js +258 -0
  40. package/dist/shortcuts/contract/operations/elements-build.js +761 -0
  41. package/dist/shortcuts/contract/operations/elements-spec.js +216 -0
  42. package/dist/shortcuts/contract/operations/first-screen.js +588 -0
  43. package/dist/shortcuts/contract/operations/flow.js +81 -25
  44. package/dist/shortcuts/contract/operations/ledger.js +438 -0
  45. package/dist/shortcuts/contract/operations/modeltext.js +132 -0
  46. package/dist/shortcuts/contract/operations/op-resolver.js +22 -0
  47. package/dist/shortcuts/contract/operations/performance.js +104 -3
  48. package/dist/shortcuts/contract/operations/quote.js +131 -25
  49. package/dist/shortcuts/contract/operations/quotescreen.js +529 -0
  50. package/dist/shortcuts/contract/operations/registry.js +30 -0
  51. package/dist/shortcuts/contract/operations/review.js +73 -58
  52. package/dist/shortcuts/contract/operations/summary-validate.js +293 -0
  53. package/dist/shortcuts/contract/operations/summary.js +4 -2
  54. package/dist/shortcuts/contract/operations/triage.js +1100 -0
  55. package/dist/shortcuts/contract/operations/upload.js +48 -7
  56. package/dist/shortcuts/contract/prewarm-cache.js +90 -0
  57. package/dist/shortcuts/contract/prewarm.js +88 -0
  58. package/dist/shortcuts/contract/upload-cache.js +49 -4
  59. package/dist/shortcuts/data/index.js +1 -6
  60. package/dist/shortcuts/data/manifest.js +2 -2
  61. package/dist/shortcuts/data/operations/index.js +1 -1
  62. package/dist/shortcuts/data/operations/query.js +23 -46
  63. package/dist/shortcuts/index.js +5 -0
  64. package/dist/shortcuts/invoice/index.js +0 -12
  65. package/dist/shortcuts/invoice/manifest.js +200 -49
  66. package/dist/shortcuts/invoice/operations/registry.js +4 -2
  67. package/dist/shortcuts/invoice/operations/reim-relation.js +438 -0
  68. package/dist/shortcuts/invoice/operations/shared.js +3 -19
  69. package/dist/shortcuts/invoice/operations/upload-and-validate.js +109 -73
  70. package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +4 -2
  71. package/dist/shortcuts/recruit-stage/operations/jd-create.js +6 -2
  72. package/dist/shortcuts/recruit-stage/operations/list.js +217 -1
  73. package/dist/shortcuts/recruit-stage/operations/resume-import.js +144 -158
  74. package/dist/shortcuts/recruit-stage/operations/search.js +348 -0
  75. package/dist/shortcuts/recruit-stage/shared.js +5 -0
  76. package/dist/shortcuts/recruit-stage/tag-lookup.js +136 -0
  77. package/dist/shortcuts/smart-extract/constants.js +79 -0
  78. package/dist/shortcuts/smart-extract/continuation.js +71 -0
  79. package/dist/shortcuts/smart-extract/errors.js +68 -0
  80. package/dist/shortcuts/smart-extract/host.js +191 -0
  81. package/dist/shortcuts/smart-extract/index.js +105 -0
  82. package/dist/shortcuts/smart-extract/ledger.js +70 -0
  83. package/dist/shortcuts/smart-extract/manifest.js +35 -0
  84. package/dist/shortcuts/smart-extract/operations/attachment.js +212 -0
  85. package/dist/shortcuts/smart-extract/operations/batch.js +67 -0
  86. package/dist/shortcuts/smart-extract/operations/config.js +118 -0
  87. package/dist/shortcuts/smart-extract/operations/fill.js +492 -0
  88. package/dist/shortcuts/smart-extract/operations/preview.js +174 -0
  89. package/dist/shortcuts/smart-extract/operations/registry.js +34 -0
  90. package/dist/shortcuts/smart-extract/operations/save.js +355 -0
  91. package/dist/shortcuts/smart-extract/operations/shared.js +191 -0
  92. package/dist/shortcuts/smart-extract/operations/structure.js +401 -0
  93. package/dist/shortcuts/smart-extract/operations/target.js +167 -0
  94. package/dist/shortcuts/smart-extract/operations/types.js +22 -0
  95. package/dist/shortcuts/smart-extract/operations/validate.js +454 -0
  96. package/dist/shortcuts/workflow/operations/form.js +68 -33
  97. package/dist/shortcuts/workflow/operations/read.js +19 -1
  98. package/docs/SKILL.md +1 -1
  99. package/docs/_catalog.md +3 -0
  100. package/docs/agent-invoice.md +5 -7
  101. package/docs/data.md +5 -1
  102. package/docs/fna.md +14 -1
  103. package/docs/invoice.md +7 -5
  104. package/docs/smart-extract.md +156 -0
  105. package/package.json +1 -1
  106. package/skill-template/business-info.json +16 -1
  107. package/skill-template/domains/qiyecheng.md +2 -0
  108. package/skill-template/domains/smart-extract.md +16 -0
  109. package/skill-template/domains/yepiaotong.md +2 -2
  110. package/skills/weaver-e10-data/references/scene-and-misc.md +4 -3
  111. package/skills/weaver-e10-jinchengda/SKILL.md +223 -35
  112. package/skills/weaver-e10-jinchengda/references/contract-action-card.md +47 -481
  113. package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +11 -11
  114. package/skills/weaver-e10-jinchengda/references/contract-agent-entry.md +3 -3
  115. package/skills/weaver-e10-jinchengda/references/contract-ai-assistant.md +1 -1
  116. package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +32 -16
  117. package/skills/weaver-e10-jinchengda/references/contract-card-render-internals.md +478 -0
  118. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +4 -4
  119. package/skills/weaver-e10-jinchengda/references/contract-disabled-capabilities.md +2 -2
  120. package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +39 -61
  121. package/skills/weaver-e10-jinchengda/references/contract-element-save-record.md +18 -13
  122. package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +2 -2
  123. package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +21 -6
  124. package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +6 -4
  125. package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +3 -3
  126. package/skills/weaver-e10-jinchengda/references/contract-ledger-catalog.md +263 -0
  127. package/skills/weaver-e10-jinchengda/references/contract-ledger-query-playbook.md +525 -0
  128. package/skills/weaver-e10-jinchengda/references/contract-ledger-rules.md +36 -0
  129. package/skills/weaver-e10-jinchengda/references/contract-modeltext-library.md +128 -0
  130. package/skills/weaver-e10-jinchengda/references/contract-multi-file.md +87 -0
  131. package/skills/weaver-e10-jinchengda/references/contract-performance-query.md +80 -54
  132. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +110 -14
  133. package/skills/weaver-e10-jinchengda/references/contract-template-selector.md +19 -21
  134. package/skills/weaver-e10-jinchengda/references/orchestration.md +12 -12
  135. package/skills/weaver-e10-jinchengda/references/source-manifest.json +1 -6
  136. package/skills/weaver-e10-jinchengda/scripts/fill_plan.py +2 -1
  137. package/skills/weaver-e10-qiyecheng/SKILL.md +37 -0
  138. package/skills/weaver-e10-qiyecheng/references/ai-check-audit.md +14 -0
  139. package/skills/weaver-e10-qiyecheng/references/budget.md +14 -0
  140. package/skills/weaver-e10-qiyecheng/references/catalog.md +25 -0
  141. package/skills/weaver-e10-qiyecheng/references/expense-center.md +8 -0
  142. package/skills/weaver-e10-qiyecheng/references/expense-chart.md +9 -0
  143. package/skills/weaver-e10-qiyecheng/references/invoice-writeoff.md +13 -0
  144. package/skills/weaver-e10-qiyecheng/references/loan-management.md +14 -0
  145. package/skills/weaver-e10-qiyecheng/references/self-hosted-mode.md +239 -0
  146. package/skills/weaver-e10-qiyecheng/references/source-manifest.json +34 -27
  147. package/skills/weaver-e10-recruit-stage/SKILL.md +62 -4
  148. package/skills/weaver-e10-recruit-stage/agents/openai.yaml +42 -8
  149. package/skills/weaver-e10-recruit-stage/references/env-ziyong.md +79 -0
  150. package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +11 -3
  151. package/skills/weaver-e10-recruit-stage/references/recruit-edit-interview-feedback.md +3 -2
  152. package/skills/weaver-e10-recruit-stage/references/recruit-interview-not-attended.md +153 -0
  153. package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +7 -4
  154. package/skills/weaver-e10-recruit-stage/references/recruit-match-candidates.md +1 -1
  155. package/skills/weaver-e10-recruit-stage/references/recruit-my-positions.md +66 -0
  156. package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +156 -42
  157. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import-batch.md +122 -0
  158. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +36 -8
  159. package/skills/weaver-e10-recruit-stage/references/recruit-search-by-tag.md +157 -0
  160. package/skills/weaver-e10-recruit-stage/references/recruit-utterance-glossary.md +35 -0
  161. package/skills/weaver-e10-smart-extract/SKILL.md +180 -0
  162. package/skills/weaver-e10-smart-extract/references/api-contract.md +71 -0
  163. package/skills/weaver-e10-smart-extract/references/result-format.md +102 -0
  164. package/skills/weaver-e10-smart-extract/references/troubleshooting.md +106 -0
  165. package/skills/weaver-e10-workflow/references/workflow-create.md +6 -5
  166. package/skills/weaver-e10-workflow/references/workflow-edit.md +1 -1
  167. package/skills/weaver-e10-workflow/references/workflow-query.md +1 -1
  168. package/skills/weaver-e10-workflow/references/workflow-view.md +1 -1
  169. package/skills/weaver-e10-yepiaotong/SKILL.md +46 -33
  170. package/skills/weaver-e10-yepiaotong/references/invoice-add.md +2 -0
  171. package/skills/weaver-e10-yepiaotong/references/invoice-file-upload.md +1 -1
  172. package/skills/weaver-e10-yepiaotong/references/invoice-import.md +19 -2
  173. package/skills/weaver-e10-yepiaotong/references/invoice-ocr-preview.md +8 -2
  174. package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +407 -0
  175. package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +12 -8
  176. package/skills/weaver-e10-yepiaotong/references/invoice-upload-and-validate.md +97 -39
  177. package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +91 -2
  178. package/skills/weaver-e10-yepiaotong/references/reim-examples.md +1 -1
  179. package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +12 -12
  180. package/skills/weaver-e10-yepiaotong/references/reim-matching-rules.md +8 -4
  181. package/skills/weaver-e10-yepiaotong/references/reim-phone-subsidy-rules.md +136 -91
  182. package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +109 -23
  183. package/skills/weaver-e10-yepiaotong/references/source-manifest.json +110 -43
  184. package/dist/shortcuts/invoice/operations/validate-preview.js +0 -40
  185. package/skills/weaver-e10-jinchengda/scripts/plan_actions.py +0 -279
  186. package/skills/weaver-e10-jinchengda/scripts/render_action_card.py +0 -450
  187. package/skills/weaver-e10-jinchengda/scripts/render_ebdf_list_card.py +0 -265
  188. package/skills/weaver-e10-jinchengda/scripts/render_risk_report.py +0 -358
  189. package/skills/weaver-e10-jinchengda/scripts/validate_action_card.py +0 -588
  190. package/skills/weaver-e10-jinchengda/scripts/verify_docx_placeholders.py +0 -118
  191. package/skills/weaver-e10-yepiaotong/references/invoice-validation-preview.md +0 -40
@@ -0,0 +1,2882 @@
1
+ import { createRequire as __esbuildCreateRequire } from 'node:module';
2
+ const require = __esbuildCreateRequire(import.meta.url);
3
+ import {
4
+ DEFAULT_RESULT_THRESHOLD_BYTES
5
+ } from "./chunk-2IGZUMNG.js";
6
+ import {
7
+ stateRoot
8
+ } from "./chunk-AJ62BGAW.js";
9
+ import {
10
+ CONTINUATION_TTL_MS,
11
+ CONTINUATION_TTL_SECONDS
12
+ } from "./chunk-7BDPM5ST.js";
13
+ import {
14
+ E10ApiError,
15
+ createE10RequestRuntime,
16
+ isE10SessionExpiredResponse,
17
+ requireE10Session
18
+ } from "./chunk-6NXT4ICB.js";
19
+ import {
20
+ getActiveProfile
21
+ } from "./chunk-U6R6FZHD.js";
22
+ import {
23
+ CliError,
24
+ isCliError,
25
+ toErrorEnvelope
26
+ } from "./chunk-UG5G54VL.js";
27
+ import "./chunk-BUSC6UAE.js";
28
+
29
+ // src/shortcuts/smart-extract/index.ts
30
+ import { readFile as readFile6 } from "node:fs/promises";
31
+ import { join as join4 } from "node:path";
32
+
33
+ // src/shortcuts/smart-extract/constants.ts
34
+ import { join } from "node:path";
35
+ var STATE_SUBDIR = "smart-extract";
36
+ var DEFAULT_TIMEOUT_MS = 3e4;
37
+ var DOWNLOAD_TIMEOUT_MS = 18e4;
38
+ var MAX_ATTACHMENTS = 20;
39
+ var MAX_ATTACHMENT_BYTES = 200 * 1024 * 1024;
40
+ var FILE_DOWNLOAD_PATH = (fileId) => `/api/file/remotedownload/${encodeURIComponent(fileId)}/meeting/true`;
41
+ var PATHS = {
42
+ configList: "/api/ai/application/smartfill/config/list",
43
+ creatableFlows: "/api/ai/application/smartfill/config/listCreatableFlows",
44
+ creatableFormIds: "/api/ai/application/smartfill/config/listCreatableFormIds",
45
+ flowStartNode: "/api/ai/application/smartfill/config/getFlowStartNode",
46
+ attachmentInfo: "/api/ai/application/smartfill/data/queryAttachmentInfo",
47
+ saveRecognizeRecord: "/api/ai/application/smartfill/data/saveRecognizeRecord",
48
+ batchInfoById: "/api/ai/application/smartfill/data/getBatchInfoById",
49
+ queryBatchInfo: "/api/ai/application/smartfill/data/queryBatchInfo",
50
+ /** 监管模块:EB / 指定节点的流程表单结构 */
51
+ governFormSimple: "/api/government/formStructure/getSimple",
52
+ governObjId: "/api/government/formStructure/getObjId",
53
+ governFormId: "/api/government/formStructure/getFormId"
54
+ };
55
+ var DATA_SOURCE = {
56
+ "wf-pre": "0",
57
+ "wf-manual": "1",
58
+ "eb-manual": "2"
59
+ };
60
+ var MAX_REQUEST_ID_LENGTH = 32;
61
+ var TICKETS_SUBDIR = "tickets";
62
+ var MAX_INLINE_TICKET_CHARS = 512;
63
+ function ticketPath(stateDir, requestId) {
64
+ const safe = requestId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64) || "ticket";
65
+ return join(stateDir, TICKETS_SUBDIR, `${safe}.ticket`);
66
+ }
67
+ var SESSIONS_SUBDIR = "sessions";
68
+ function sessionPath(stateDir, sessionId) {
69
+ const safe = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64) || "session";
70
+ return join(stateDir, SESSIONS_SUBDIR, `${safe}.json`);
71
+ }
72
+ var TEXT_PREVIEW_CHARS = 400;
73
+
74
+ // src/shortcuts/smart-extract/continuation.ts
75
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
76
+ import { existsSync } from "node:fs";
77
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
78
+ import { homedir } from "node:os";
79
+ import { resolve } from "node:path";
80
+
81
+ // src/shortcuts/smart-extract/errors.ts
82
+ var SmartExtractCliError = class extends CliError {
83
+ type;
84
+ subtype;
85
+ code;
86
+ retryable;
87
+ stage;
88
+ details;
89
+ constructor(type, subtype, message, options = {}) {
90
+ super(message, options.exitCode ?? 5 /* InternalError */);
91
+ this.name = "SmartExtractCliError";
92
+ this.type = type;
93
+ this.subtype = subtype;
94
+ this.code = options.code;
95
+ this.retryable = options.retryable ?? false;
96
+ this.stage = options.stage;
97
+ this.details = options.details;
98
+ }
99
+ };
100
+ function smartExtractValidationError(subtype, message, details) {
101
+ return new SmartExtractCliError("validation", subtype, message, {
102
+ details,
103
+ exitCode: 2 /* UsageError */
104
+ });
105
+ }
106
+ function smartExtractAuthError(subtype, message, details) {
107
+ return new SmartExtractCliError("authentication", subtype, message, {
108
+ details,
109
+ exitCode: 3 /* AuthError */
110
+ });
111
+ }
112
+ function smartExtractBusinessError(subtype, message, options = {}) {
113
+ return new SmartExtractCliError("business", subtype, message, {
114
+ ...options,
115
+ exitCode: 1 /* GeneralError */
116
+ });
117
+ }
118
+ function smartExtractNetworkError(subtype, message, options = {}) {
119
+ return new SmartExtractCliError("network", subtype, message, {
120
+ ...options,
121
+ retryable: options.retryable ?? true,
122
+ exitCode: 4 /* NetworkError */
123
+ });
124
+ }
125
+ function smartExtractConfirmationError(action, details) {
126
+ return new SmartExtractCliError("confirmation", "required", "\u8BE5\u64CD\u4F5C\u9700\u8981\u7528\u6237\u660E\u786E\u786E\u8BA4\u540E\u624D\u80FD\u6267\u884C", {
127
+ details: { action, ...details },
128
+ exitCode: 10 /* ConfirmationRequired */
129
+ });
130
+ }
131
+ function smartExtractPartialError(message, details) {
132
+ return new SmartExtractCliError("partial", "write_uncertain", message, {
133
+ details,
134
+ exitCode: 11 /* Partial */
135
+ });
136
+ }
137
+
138
+ // src/shortcuts/smart-extract/continuation.ts
139
+ function stateRoot2(ctx) {
140
+ const configured = ctx?.config?.path();
141
+ if (configured) return resolve(configured, "..");
142
+ return process.env.WEAVER_WORK_CLI_HOME || process.env.WORK_CLI_HOME || resolve(homedir(), ".weaver-work-cli");
143
+ }
144
+ async function loadKey(ctx) {
145
+ const keysDir = resolve(stateRoot2(ctx), "keys");
146
+ const filename = resolve(keysDir, "smart-extract-continuation.key");
147
+ await mkdir(keysDir, { recursive: true, mode: 448 });
148
+ if (existsSync(filename)) return readFile(filename);
149
+ const key = randomBytes(32);
150
+ try {
151
+ await writeFile(filename, key, { flag: "wx", mode: 384 });
152
+ if (process.platform !== "win32") await chmod(filename, 384).catch(() => void 0);
153
+ return key;
154
+ } catch {
155
+ return readFile(filename);
156
+ }
157
+ }
158
+ function encode(value) {
159
+ return Buffer.from(JSON.stringify(value)).toString("base64url");
160
+ }
161
+ function signature(payload, key) {
162
+ return createHmac("sha256", key).update(payload).digest("base64url");
163
+ }
164
+ function createSmartExtractContinuationSigner(ctx) {
165
+ return {
166
+ async issue(payload, ttlMs = CONTINUATION_TTL_MS) {
167
+ const issuedAt = Date.now();
168
+ const body = encode({ ...payload, issuedAt, expiresAt: issuedAt + ttlMs });
169
+ const sig = signature(body, await loadKey(ctx));
170
+ return `${body}.${sig}`;
171
+ },
172
+ async verify(token, expectedOperation) {
173
+ if (typeof token !== "string" || !token.includes(".")) {
174
+ throw smartExtractValidationError("continuation_invalid", "continuation \u65E0\u6548");
175
+ }
176
+ const [body, provided] = token.split(".");
177
+ const expected = signature(body, await loadKey(ctx));
178
+ const valid = provided.length === expected.length && timingSafeEqual(Buffer.from(provided), Buffer.from(expected));
179
+ if (!valid) throw smartExtractValidationError("continuation_invalid", "continuation \u7B7E\u540D\u6821\u9A8C\u5931\u8D25");
180
+ let value;
181
+ try {
182
+ value = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
183
+ } catch {
184
+ throw smartExtractValidationError("continuation_invalid", "continuation \u5185\u5BB9\u65E0\u6CD5\u89E3\u6790");
185
+ }
186
+ if (value.operation !== expectedOperation) {
187
+ throw smartExtractValidationError("continuation_mismatch", "continuation \u4E0D\u5C5E\u4E8E\u5F53\u524D\u64CD\u4F5C");
188
+ }
189
+ if (!Number.isSafeInteger(value.expiresAt) || value.expiresAt < Date.now()) {
190
+ throw smartExtractValidationError("continuation_expired", "continuation \u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u6267\u884C save.prepare");
191
+ }
192
+ return value;
193
+ }
194
+ };
195
+ }
196
+
197
+ // src/shortcuts/smart-extract/host.ts
198
+ var ALLOWED_PREFIXES = ["/api/ai/application/", "/api/government/", "/api/file/", "/api/ebuilder/"];
199
+ function assertApiPath(path) {
200
+ if (!path.startsWith("/api/") || path.startsWith("//") || path.includes("/../") || /^https?:/iu.test(path)) {
201
+ throw smartExtractValidationError("path_invalid", "E10 API \u53EA\u80FD\u8C03\u7528 /api/ \u540C\u6E90\u76F8\u5BF9\u8DEF\u5F84");
202
+ }
203
+ if (!ALLOWED_PREFIXES.some((prefix) => path.startsWith(prefix))) {
204
+ throw smartExtractValidationError("path_forbidden", `smart-extract \u4E0D\u5141\u8BB8\u8C03\u7528\u8BE5\u63A5\u53E3\uFF1A${path}`);
205
+ }
206
+ }
207
+ function createSmartExtractHost(ctx) {
208
+ let cached = null;
209
+ async function resolve3() {
210
+ if (cached) return cached;
211
+ const e10 = await requireE10Session(ctx).catch(() => null);
212
+ if (!e10) {
213
+ cached = {
214
+ e10: null,
215
+ info: {
216
+ available: false,
217
+ baseUrl: "",
218
+ userId: "",
219
+ profile: getActiveProfile(),
220
+ reason: "\u672A\u53D6\u5F97 E10 \u4F1A\u8BDD\uFF0C\u8BF7\u5148\u6267\u884C weaver-work-cli auth login"
221
+ }
222
+ };
223
+ return cached;
224
+ }
225
+ cached = {
226
+ e10,
227
+ info: {
228
+ available: true,
229
+ baseUrl: e10.getBaseUrl(),
230
+ userId: e10.userId,
231
+ profile: ctx.getGlobalOptions().profile || getActiveProfile()
232
+ }
233
+ };
234
+ return cached;
235
+ }
236
+ async function getSession() {
237
+ return (await resolve3()).info;
238
+ }
239
+ async function runtime() {
240
+ const { e10, info } = await resolve3();
241
+ if (!e10) throw smartExtractAuthError("no_session", info.reason || "\u672A\u53D6\u5F97 E10 \u4F1A\u8BDD", { available: false });
242
+ return { runtime: createE10RequestRuntime(ctx, e10), info };
243
+ }
244
+ async function request(options) {
245
+ assertApiPath(options.path);
246
+ const { runtime: rt } = await runtime();
247
+ let response;
248
+ try {
249
+ response = await rt.requestJson({
250
+ module: "smart-extract",
251
+ operation: options.operation,
252
+ method: options.method || "POST",
253
+ path: options.path,
254
+ query: options.query,
255
+ body: options.body,
256
+ headers: { langtype: "zh_CN" },
257
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS
258
+ });
259
+ } catch (error) {
260
+ if (error instanceof E10ApiError) {
261
+ throw smartExtractNetworkError("request_failed", `\u8BF7\u6C42\u5931\u8D25\uFF1A${error.message}`, {
262
+ retryable: error.retryable,
263
+ stage: options.operation
264
+ });
265
+ }
266
+ throw smartExtractNetworkError("request_failed", `\u8BF7\u6C42\u5F02\u5E38\uFF1A${error.message}`, {
267
+ stage: options.operation
268
+ });
269
+ }
270
+ if (isE10SessionExpiredResponse(response)) {
271
+ throw smartExtractAuthError("session_expired", "E10 \u767B\u5F55\u6001\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55", {
272
+ httpStatus: response.status
273
+ });
274
+ }
275
+ if (response.parseError) {
276
+ throw smartExtractNetworkError("protocol", `\u63A5\u53E3\u8FD4\u56DE\u4E0D\u662F\u5408\u6CD5 JSON\uFF08HTTP ${response.status}\uFF09`, {
277
+ retryable: false,
278
+ stage: options.operation
279
+ });
280
+ }
281
+ if (response.status < 200 || response.status >= 300) {
282
+ throw smartExtractBusinessError("http_error", `\u63A5\u53E3 HTTP ${response.status}`, {
283
+ code: response.status,
284
+ stage: options.operation
285
+ });
286
+ }
287
+ return response.value;
288
+ }
289
+ async function requestData(options) {
290
+ return unwrapWeaResult(await request(options), options.operation);
291
+ }
292
+ async function download(path, operation, timeoutMs = DOWNLOAD_TIMEOUT_MS) {
293
+ assertApiPath(path);
294
+ const { runtime: rt } = await runtime();
295
+ let response;
296
+ try {
297
+ response = await rt.requestBinary({
298
+ module: "smart-extract",
299
+ operation,
300
+ method: "GET",
301
+ path,
302
+ headers: { accept: "*/*" },
303
+ timeoutMs,
304
+ followRedirects: true
305
+ });
306
+ } catch (error) {
307
+ if (error instanceof E10ApiError) {
308
+ throw smartExtractNetworkError("download_failed", `\u4E0B\u8F7D\u5931\u8D25\uFF1A${error.message}`, {
309
+ retryable: error.retryable,
310
+ stage: operation
311
+ });
312
+ }
313
+ throw smartExtractNetworkError("download_failed", `\u4E0B\u8F7D\u5F02\u5E38\uFF1A${error.message}`, {
314
+ stage: operation
315
+ });
316
+ }
317
+ if (isE10SessionExpiredResponse(response)) {
318
+ throw smartExtractAuthError("session_expired", "\u4E0B\u8F7D\u65F6\u767B\u5F55\u6001\u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55", {
319
+ httpStatus: response.status
320
+ });
321
+ }
322
+ if (response.status !== 200) {
323
+ throw smartExtractBusinessError("download_failed", `\u4E0B\u8F7D\u5931\u8D25 HTTP ${response.status}`, {
324
+ code: response.status,
325
+ stage: operation
326
+ });
327
+ }
328
+ return {
329
+ buffer: response.content,
330
+ contentType: response.contentType || "",
331
+ contentDisposition: response.headers.get("content-disposition") || "",
332
+ httpStatus: response.status
333
+ };
334
+ }
335
+ return { getSession, request, requestData, download };
336
+ }
337
+ function unwrapWeaResult(payload, operation) {
338
+ const root = record(payload);
339
+ if (Object.keys(root).length === 0) {
340
+ throw smartExtractBusinessError("response_invalid", `${operation} \u8FD4\u56DE\u4E3A\u7A7A`, { stage: operation });
341
+ }
342
+ const code = root.code;
343
+ const failed = root.status === false || root.fail === true || code !== void 0 && code !== null && String(code) !== "200" && String(code) !== "0";
344
+ if (failed) {
345
+ throw smartExtractBusinessError("business_error", responseMessage(payload) || `${operation} \u4E1A\u52A1\u5931\u8D25`, {
346
+ code: code === void 0 || code === null ? void 0 : String(code),
347
+ details: { result: payload },
348
+ stage: operation
349
+ });
350
+ }
351
+ if (!("data" in root)) {
352
+ throw smartExtractBusinessError("response_invalid", `${operation} \u54CD\u5E94\u7F3A\u5C11 data`, {
353
+ details: { result: payload },
354
+ stage: operation
355
+ });
356
+ }
357
+ return root.data;
358
+ }
359
+ function record(value) {
360
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
361
+ }
362
+ function responseMessage(payload) {
363
+ const root = record(payload);
364
+ const message = record(root.message);
365
+ for (const value of [root.msg, root.message, message.msg, message.message, root.errmsg]) {
366
+ if (typeof value === "string" && value.trim()) return value.trim().slice(0, 500);
367
+ }
368
+ return "";
369
+ }
370
+
371
+ // src/shortcuts/smart-extract/operations/attachment.ts
372
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
373
+ import { extname, join as join2, resolve as resolve2 } from "node:path";
374
+
375
+ // src/shortcuts/smart-extract/operations/types.ts
376
+ function smartExtractSuccess(action, data, options = {}) {
377
+ const envelope = { ok: true, action, data };
378
+ if (options.meta && Object.keys(options.meta).length > 0) envelope.meta = options.meta;
379
+ if (options.warnings && options.warnings.length > 0) envelope.warnings = options.warnings;
380
+ return envelope;
381
+ }
382
+ function schemaOf(properties, options = {}) {
383
+ return {
384
+ type: "object",
385
+ additionalProperties: false,
386
+ properties,
387
+ ...options.required?.length ? { required: options.required } : {},
388
+ ...options.description ? { description: options.description } : {}
389
+ };
390
+ }
391
+ var SCHEMA_ID = {
392
+ oneOf: [{ type: "integer" }, { type: "string", pattern: "^\\d+$" }]
393
+ };
394
+
395
+ // src/shortcuts/smart-extract/operations/shared.ts
396
+ import { readFile as readFile2 } from "node:fs/promises";
397
+ import { createHash } from "node:crypto";
398
+ function optionalString(value, field) {
399
+ if (value === void 0 || value === null || value === "") return void 0;
400
+ if (typeof value !== "string" && typeof value !== "number") {
401
+ throw smartExtractValidationError("field_invalid", `${field} \u5FC5\u987B\u662F\u5B57\u7B26\u4E32`);
402
+ }
403
+ const text = String(value).trim();
404
+ return text === "" ? void 0 : text;
405
+ }
406
+ function requiredString(value, field) {
407
+ const text = optionalString(value, field);
408
+ if (!text) throw smartExtractValidationError(`${field}_required`, `${field} \u5FC5\u586B`);
409
+ return text;
410
+ }
411
+ function requiredId(value, field) {
412
+ const text = requiredString(value, field);
413
+ if (!/^\d+$/u.test(text)) {
414
+ throw smartExtractValidationError(`${field}_invalid`, `${field} \u5FC5\u987B\u662F\u7EAF\u6570\u5B57 ID`);
415
+ }
416
+ return text;
417
+ }
418
+ function optionalId(value, field) {
419
+ const text = optionalString(value, field);
420
+ if (!text) return void 0;
421
+ if (!/^\d+$/u.test(text)) {
422
+ throw smartExtractValidationError(`${field}_invalid`, `${field} \u5FC5\u987B\u662F\u7EAF\u6570\u5B57 ID`);
423
+ }
424
+ return text;
425
+ }
426
+ function parseIdList(value, field) {
427
+ if (value === void 0 || value === null || value === "") return [];
428
+ if (Array.isArray(value)) {
429
+ return dedupe(value.map((item) => {
430
+ if (item && typeof item === "object") return String(item.fileId ?? item.id ?? "").trim();
431
+ return String(item ?? "").trim();
432
+ }).filter(Boolean));
433
+ }
434
+ const text = String(value).trim();
435
+ if (text.startsWith("[")) {
436
+ try {
437
+ return parseIdList(JSON.parse(text), field);
438
+ } catch {
439
+ }
440
+ }
441
+ const items = text.split(/[,;,;\s]+/u).map((item) => item.trim()).filter(Boolean);
442
+ for (const item of items) {
443
+ if (!/^\d+$/u.test(item)) {
444
+ throw smartExtractValidationError("field_invalid", `${field} \u4E2D\u5305\u542B\u975E\u6570\u5B57 ID\uFF1A${item}`);
445
+ }
446
+ }
447
+ return dedupe(items);
448
+ }
449
+ function dedupe(values) {
450
+ return [...new Set(values.filter(Boolean))];
451
+ }
452
+ async function readObjectInput(input, inlineKey, pathKey, options = {}) {
453
+ const inline = input[inlineKey];
454
+ const path = optionalString(input[pathKey], pathKey);
455
+ if (inline !== void 0 && inline !== null && path) {
456
+ throw smartExtractValidationError("input_conflict", `${inlineKey} \u4E0E ${pathKey} \u53EA\u80FD\u4F20\u4E00\u4E2A`);
457
+ }
458
+ if (path) {
459
+ let raw;
460
+ try {
461
+ raw = await readFile2(path, "utf8");
462
+ } catch {
463
+ throw smartExtractValidationError("input_unreadable", `\u65E0\u6CD5\u8BFB\u53D6 ${pathKey}\uFF1A${path}`);
464
+ }
465
+ return unwrapDataEnvelope(parseJsonObject(stripBom(raw), pathKey));
466
+ }
467
+ if (typeof inline === "string") {
468
+ return unwrapDataEnvelope(parseJsonObject(stripBom(inline), inlineKey));
469
+ }
470
+ if (inline && typeof inline === "object" && !Array.isArray(inline)) {
471
+ return unwrapDataEnvelope(inline);
472
+ }
473
+ if (options.required) {
474
+ throw smartExtractValidationError(`${inlineKey}_required`, `\u5FC5\u987B\u63D0\u4F9B ${inlineKey} \u6216 ${pathKey}`);
475
+ }
476
+ return void 0;
477
+ }
478
+ function parseJsonObject(raw, label) {
479
+ let parsed;
480
+ try {
481
+ parsed = JSON.parse(raw);
482
+ } catch {
483
+ throw smartExtractValidationError("json_invalid", `${label} \u4E0D\u662F\u5408\u6CD5 JSON`);
484
+ }
485
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
486
+ throw smartExtractValidationError("json_invalid", `${label} \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);
487
+ }
488
+ return parsed;
489
+ }
490
+ function unwrapDataEnvelope(value) {
491
+ const looksLikeEnvelope = (value.ok === true || value.ok === false) && typeof value.operation === "string" && value.data !== void 0;
492
+ if (!looksLikeEnvelope) return value;
493
+ if (value.ok === false) {
494
+ throw smartExtractValidationError("input_envelope_failed", `\u8F93\u5165\u6587\u4EF6\u6765\u81EA\u4E00\u6B21\u5931\u8D25\u7684\u8C03\u7528\uFF1A${value.operation}`);
495
+ }
496
+ const data = value.data;
497
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
498
+ throw smartExtractValidationError("input_envelope_invalid", `${value.operation} \u7684 data \u4E0D\u662F\u5BF9\u8C61`);
499
+ }
500
+ return data;
501
+ }
502
+ function stripBom(value) {
503
+ return value.replace(/^\uFEFF+/u, "");
504
+ }
505
+ function stableStringify(value) {
506
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
507
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
508
+ const entries = Object.entries(value).filter(([, item]) => item !== void 0).sort(([left], [right]) => left.localeCompare(right));
509
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
510
+ }
511
+ function sha256(value) {
512
+ return createHash("sha256").update(value).digest("hex");
513
+ }
514
+ function truncate(value, max) {
515
+ return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
516
+ }
517
+ function normalizeNumberText(value) {
518
+ return value.replace(/[,,\s]/gu, "").replace(/^[¥$¥]/u, "");
519
+ }
520
+
521
+ // src/shortcuts/smart-extract/operations/attachment.ts
522
+ var KIND_BY_EXT = {
523
+ ".pdf": "pdf",
524
+ ".doc": "word",
525
+ ".docx": "word",
526
+ ".xls": "excel",
527
+ ".xlsx": "excel",
528
+ ".csv": "excel",
529
+ ".ppt": "ppt",
530
+ ".pptx": "ppt",
531
+ ".txt": "text",
532
+ ".md": "text",
533
+ ".json": "text",
534
+ ".xml": "text",
535
+ ".html": "text",
536
+ ".htm": "text",
537
+ ".png": "image",
538
+ ".jpg": "image",
539
+ ".jpeg": "image",
540
+ ".webp": "image",
541
+ ".gif": "image",
542
+ ".bmp": "image",
543
+ ".zip": "archive",
544
+ ".rar": "archive",
545
+ ".7z": "archive"
546
+ };
547
+ function kindOf(name, contentType) {
548
+ const ext = extname(name).toLowerCase();
549
+ if (KIND_BY_EXT[ext]) return KIND_BY_EXT[ext];
550
+ if (contentType.includes("pdf")) return "pdf";
551
+ if (contentType.includes("word")) return "word";
552
+ if (contentType.includes("sheet") || contentType.includes("excel")) return "excel";
553
+ if (contentType.startsWith("image/")) return "image";
554
+ if (contentType.startsWith("text/")) return "text";
555
+ return "other";
556
+ }
557
+ function safeFileName(name, fileId) {
558
+ const base = name.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_").trim();
559
+ return base || fileId;
560
+ }
561
+ function extFromContentType(contentType) {
562
+ const text = contentType.toLowerCase();
563
+ if (text.includes("wordprocessingml")) return ".docx";
564
+ if (text.includes("spreadsheetml")) return ".xlsx";
565
+ if (text.includes("presentationml")) return ".pptx";
566
+ if (text.includes("pdf")) return ".pdf";
567
+ if (text.includes("png")) return ".png";
568
+ if (text.includes("jpeg") || text.includes("jpg")) return ".jpg";
569
+ if (text.includes("plain")) return ".txt";
570
+ return "";
571
+ }
572
+ function fileNameFromDisposition(disposition) {
573
+ const encoded = /filename\*=UTF-8''([^;]+)/iu.exec(disposition);
574
+ if (encoded) {
575
+ try {
576
+ return decodeURIComponent(encoded[1]).trim();
577
+ } catch {
578
+ }
579
+ }
580
+ const plain = /filename="?([^";]+)"?/iu.exec(disposition);
581
+ return plain ? plain[1].trim() : "";
582
+ }
583
+ async function loadMeta(env, ids) {
584
+ const metas = /* @__PURE__ */ new Map();
585
+ const warnings = [];
586
+ try {
587
+ const data = await env.host.requestData({
588
+ operation: "smart-extract.attachment.fetch",
589
+ method: "GET",
590
+ path: PATHS.attachmentInfo,
591
+ query: { attachmentIds: ids.join(",") }
592
+ });
593
+ const list = Array.isArray(data) ? data : [];
594
+ for (const item of list) {
595
+ const entry = record(item);
596
+ const fileId = String(entry.fileid ?? entry.fileId ?? entry.id ?? "").trim();
597
+ if (!fileId) continue;
598
+ metas.set(fileId, {
599
+ fileId,
600
+ ...entry.name ? { name: String(entry.name) } : {},
601
+ ...entry.extName ? { extName: String(entry.extName) } : {},
602
+ ...entry.size === void 0 || entry.size === null ? {} : { size: Number(entry.size) }
603
+ });
604
+ }
605
+ } catch (error) {
606
+ warnings.push(`\u9644\u4EF6\u5143\u6570\u636E\u67E5\u8BE2\u5931\u8D25\uFF08\u7EE7\u7EED\u6309 ID \u4E0B\u8F7D\uFF09\uFF1A${error.message.slice(0, 120)}`);
607
+ }
608
+ return { metas, warnings };
609
+ }
610
+ async function downloadAttachments(env, ids, outDir, maxBytes) {
611
+ const { metas, warnings } = await loadMeta(env, ids);
612
+ const session = await env.host.getSession();
613
+ const items = [];
614
+ for (const fileId of ids) {
615
+ const meta = metas.get(fileId);
616
+ try {
617
+ const response = await env.host.download(FILE_DOWNLOAD_PATH(fileId), "smart-extract.attachment.fetch");
618
+ if (response.buffer.length > maxBytes) {
619
+ warnings.push(`\u9644\u4EF6 ${fileId} \u5927\u5C0F ${response.buffer.length} \u8D85\u8FC7\u4E0A\u9650 ${maxBytes}\uFF0C\u5DF2\u8DF3\u8FC7\u843D\u5730`);
620
+ items.push({ fileId, name: meta?.name ?? null, bytes: response.buffer.length, downloaded: false, reason: "too_large" });
621
+ continue;
622
+ }
623
+ const dispositionName = fileNameFromDisposition(response.contentDisposition);
624
+ const ext = meta?.extName ? `.${meta.extName.replace(/^\./u, "")}` : "";
625
+ const metaName = meta?.name ? ext && !meta.name.toLowerCase().endsWith(ext.toLowerCase()) ? `${meta.name}${ext}` : meta.name : "";
626
+ const fallbackExt = extFromContentType(response.contentType);
627
+ const name = safeFileName(metaName || dispositionName || `${fileId}${fallbackExt}`, `${fileId}${fallbackExt}`);
628
+ const target = join2(outDir, name);
629
+ await writeFile2(target, response.buffer);
630
+ const resolvedName = name || `${fileId}${fallbackExt}`;
631
+ items.push({
632
+ fileId,
633
+ name: resolvedName,
634
+ path: target,
635
+ bytes: response.buffer.length,
636
+ contentType: response.contentType,
637
+ kind: kindOf(resolvedName, response.contentType),
638
+ downloaded: true,
639
+ ...session.baseUrl ? { previewUrl: `${session.baseUrl.replace(/\/+$/u, "")}/sp/file/filePreview/${fileId}` } : {}
640
+ });
641
+ } catch (error) {
642
+ warnings.push(`\u9644\u4EF6 ${fileId} \u4E0B\u8F7D\u5931\u8D25\uFF1A${error.message.slice(0, 160)}`);
643
+ items.push({
644
+ fileId,
645
+ name: meta?.name ?? null,
646
+ downloaded: false,
647
+ reason: "download_failed",
648
+ error: error.message.slice(0, 300)
649
+ });
650
+ }
651
+ }
652
+ return { items, warnings };
653
+ }
654
+ var attachmentFetch = {
655
+ name: "smart-extract.attachment.fetch",
656
+ risk: "read",
657
+ summary: "\u628A E10 \u9644\u4EF6\uFF08fileId/attachmentId\uFF09\u4E0B\u8F7D\u5230\u672C\u5730\u4E34\u65F6\u76EE\u5F55\uFF0C\u8FD4\u56DE\u7EDD\u5BF9\u8DEF\u5F84\u4E0E\u6587\u4EF6\u7C7B\u578B\u3002\u53EA\u843D\u5730\u4E0D\u89E3\u89E3\u6790\uFF1A\u62FF\u5230 path \u540E\u7531\u5BBF\u4E3B\u6A21\u578B\u81EA\u5DF1\u8BFB\uFF08PDF/Word/Excel/\u56FE\u7247\u90FD\u884C\uFF09\u3002",
658
+ inputSchema: schemaOf({
659
+ attachmentIds: {
660
+ oneOf: [
661
+ { type: "string", description: "\u9644\u4EF6 ID\uFF0C\u591A\u4E2A\u7528\u9017\u53F7\u5206\u9694" },
662
+ { type: "array", items: { type: "string" }, description: "\u9644\u4EF6 ID \u6570\u7EC4" }
663
+ ],
664
+ description: "\u8981\u4E0B\u8F7D\u7684\u9644\u4EF6 ID\uFF08E10 \u6587\u4EF6\u670D\u52A1 fileId\uFF09"
665
+ },
666
+ outDir: { type: "string", description: "\u843D\u5730\u76EE\u5F55\uFF1B\u9ED8\u8BA4 <state>/smart-extract/attachments" },
667
+ maxBytes: { type: "integer", description: "\u5355\u6587\u4EF6\u5927\u5C0F\u4E0A\u9650\uFF08\u5B57\u8282\uFF09\uFF0C\u9ED8\u8BA4 200MB" }
668
+ }, { required: ["attachmentIds"] }),
669
+ handler: async (args, env) => {
670
+ const ids = parseIdList(args.attachmentIds, "attachmentIds");
671
+ if (ids.length === 0) {
672
+ throw smartExtractValidationError("attachment_ids_required", "attachmentIds \u4E0D\u80FD\u4E3A\u7A7A");
673
+ }
674
+ if (ids.length > MAX_ATTACHMENTS) {
675
+ throw smartExtractValidationError(
676
+ "too_many_attachments",
677
+ `\u4E00\u6B21\u6700\u591A\u4E0B\u8F7D ${MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6\uFF0C\u5F53\u524D ${ids.length} \u4E2A`
678
+ );
679
+ }
680
+ const maxBytes = Number(args.maxBytes ?? MAX_ATTACHMENT_BYTES) || MAX_ATTACHMENT_BYTES;
681
+ const outDirArg = optionalString(args.outDir, "outDir");
682
+ const outDir = outDirArg ? resolve2(outDirArg) : join2(env.stateDir, "attachments");
683
+ await mkdir2(outDir, { recursive: true });
684
+ const { items, warnings } = await downloadAttachments(env, ids, outDir, maxBytes);
685
+ const downloaded = items.filter((item) => item.downloaded === true);
686
+ if (downloaded.length === 0) {
687
+ warnings.push("\u6CA1\u6709\u4EFB\u4F55\u9644\u4EF6\u843D\u5730\u6210\u529F\uFF1B\u5982\u679C\u786E\u8BA4\u9644\u4EF6 ID \u6B63\u786E\uFF0C\u68C0\u67E5\u767B\u5F55\u6001\u4E0E\u8BE5\u9644\u4EF6\u7684\u8BBF\u95EE\u6743\u9650");
688
+ }
689
+ return smartExtractSuccess(
690
+ "smart-extract.attachment.fetch",
691
+ {
692
+ outDir,
693
+ count: downloaded.length,
694
+ requested: ids.length,
695
+ items,
696
+ /** 给模型的下一步:直接读 path,不要再去服务端要「解析文本」。 */
697
+ next: downloaded.length > 0 ? "\u7528\u5BBF\u4E3B\u6587\u4EF6\u8BFB\u53D6\u80FD\u529B\u6253\u5F00 items[].path\uFF1B\u56FE\u7247/PDF \u8D70\u539F\u751F\u89C6\u89C9\u6216 pdf \u6280\u80FD\uFF0C\u4E0D\u8981\u5047\u8BBE CLI \u5DF2\u62BD\u6587\u672C" : null
698
+ },
699
+ { warnings }
700
+ );
701
+ }
702
+ };
703
+ var attachmentOperations = [attachmentFetch];
704
+
705
+ // src/shortcuts/smart-extract/operations/batch.ts
706
+ var batchGet = {
707
+ name: "smart-extract.batch.get",
708
+ risk: "read",
709
+ summary: "\u6309 aiExtraId \u56DE\u67E5\u5DF2\u4FDD\u5B58\u7684\u62BD\u53D6\u8BB0\u5F55\uFF08\u53EA\u8BFB\uFF09\u3002\u7528\u4E8E\u4FDD\u5B58\u540E\u6821\u9A8C\uFF0C\u4EE5\u53CA write_uncertain \u65F6\u5224\u5B9A\u5230\u5E95\u6709\u6CA1\u6709\u843D\u5E93\u3002",
710
+ inputSchema: schemaOf({
711
+ id: { ...SCHEMA_ID, description: "\u62BD\u53D6\u8BB0\u5F55 ID aiExtraId\uFF08save.apply \u8FD4\u56DE\u7684 aiExtraId\uFF09" },
712
+ includeResult: { type: "boolean", description: "\u662F\u5426\u8FD4\u56DE\u5B8C\u6574 recognizeResult\uFF0C\u9ED8\u8BA4 true" }
713
+ }, { required: ["id"] }),
714
+ handler: async (args, env) => {
715
+ const id = requiredId(args.id, "id");
716
+ const includeResult = args.includeResult !== false;
717
+ const data = await env.host.requestData({
718
+ operation: "smart-extract.batch.get",
719
+ method: "GET",
720
+ path: PATHS.batchInfoById,
721
+ query: { id }
722
+ });
723
+ const batch = record(data);
724
+ if (!batch.id) {
725
+ throw smartExtractBusinessError("batch_not_found", `\u6279\u6B21 ${id} \u4E0D\u5B58\u5728\u6216\u65E0\u6743\u67E5\u770B`, { details: { id } });
726
+ }
727
+ let recognizeResult;
728
+ if (includeResult && typeof batch.recognizeResult === "string" && batch.recognizeResult.trim()) {
729
+ try {
730
+ recognizeResult = JSON.parse(batch.recognizeResult);
731
+ } catch {
732
+ recognizeResult = batch.recognizeResult;
733
+ }
734
+ }
735
+ const mainRows = (() => {
736
+ const parsed = record(recognizeResult);
737
+ const rows = parsed.mainTable && Array.isArray(parsed.mainTable.rows) ? parsed.mainTable.rows : [];
738
+ return rows.length;
739
+ })();
740
+ return smartExtractSuccess("smart-extract.batch.get", {
741
+ exists: true,
742
+ aiExtraId: String(batch.id),
743
+ workflowId: batch.workflowId ?? null,
744
+ nodeId: batch.nodeId ?? null,
745
+ requestId: batch.requestId ?? null,
746
+ formModeType: batch.formModeType ?? null,
747
+ fillStatus: batch.fillStatus ?? null,
748
+ dataSource: batch.dataSource ?? null,
749
+ attachmentIds: batch.attachmentIds ?? null,
750
+ createTime: batch.createTime ?? null,
751
+ creator: batch.creator ?? null,
752
+ mainRowCount: mainRows,
753
+ hasTableStructure: Boolean(batch.tableStructure),
754
+ ...includeResult ? { recognizeResult: recognizeResult ?? null } : {}
755
+ });
756
+ }
757
+ };
758
+ var batchOperations = [batchGet];
759
+
760
+ // src/shortcuts/smart-extract/operations/config.ts
761
+ function splitCsv(value) {
762
+ if (!value) return [];
763
+ return String(value).split(/[,;,;]/u).map((item) => item.trim()).filter(Boolean);
764
+ }
765
+ var configList = {
766
+ name: "smart-extract.config.list",
767
+ risk: "read",
768
+ summary: "\u53D6\u8BE5\u6D41\u7A0B/\u8868\u5355\u914D\u7F6E\u7684\u8BC6\u522B\u89C4\u5219\uFF08\u5168\u5C40\u8865\u5145\u89C4\u5219\u3001\u6BCF\u5B57\u6BB5\u8865\u5145\u89C4\u5219\u3001\u9700\u89E3\u6790\u5B57\u6BB5\u3001\u9644\u4EF6\u5B57\u6BB5\uFF09\u3002\u5206\u9875\u63A5\u53E3\uFF0C\u9ED8\u8BA4\u53EA\u53D6\u542F\u7528\u4E2D\u7684\u914D\u7F6E\u3002",
769
+ inputSchema: schemaOf({
770
+ modeType: { type: "string", enum: ["wf", "eb"], description: "\u6570\u636E\u6E90\u7C7B\u578B\uFF1B\u4E0E sourceId \u4E00\u8D77\u7528" },
771
+ sourceId: {
772
+ ...{ oneOf: [{ type: "integer" }, { type: "string", pattern: "^\\d+$" }] },
773
+ description: "\u6D41\u7A0B ID\uFF08wf\uFF09\u6216 EB \u8868\u5355 ID\uFF08eb\uFF09"
774
+ },
775
+ wfNodeId: {
776
+ ...{ oneOf: [{ type: "integer" }, { type: "string", pattern: "^\\d+$" }] },
777
+ description: "\u6D41\u7A0B\u8282\u70B9 ID\uFF1A\u67E5\u8BE5\u8282\u70B9\u4E0A\u7684\u914D\u7F6E\uFF08\u53EF\u9009\uFF09"
778
+ },
779
+ enabled: { type: "integer", enum: [0, 1], description: "\u53EA\u770B\u542F\u7528(1)/\u505C\u7528(0)\uFF1B\u4E0D\u4F20\u8FD4\u56DE\u5168\u90E8" },
780
+ pageSize: { type: "integer", description: "\u6BCF\u9875\u6761\u6570\uFF0C\u9ED8\u8BA4 50\uFF0C\u6700\u5927 200" }
781
+ }),
782
+ handler: async (args, env) => {
783
+ const modeType = optionalString(args.modeType, "modeType");
784
+ if (modeType && modeType !== "wf" && modeType !== "eb") {
785
+ throw smartExtractValidationError("mode_type_invalid", "modeType \u53EA\u80FD\u662F wf \u6216 eb");
786
+ }
787
+ const sourceId = optionalId(args.sourceId, "sourceId");
788
+ const wfNodeId = optionalId(args.wfNodeId, "wfNodeId");
789
+ const enabled = args.enabled === void 0 || args.enabled === null ? void 0 : Number(args.enabled);
790
+ if (enabled !== void 0 && enabled !== 0 && enabled !== 1) {
791
+ throw smartExtractValidationError("enabled_invalid", "enabled \u53EA\u80FD\u662F 0 \u6216 1");
792
+ }
793
+ const pageSize = Math.max(1, Math.min(200, Number(args.pageSize ?? 50) || 50));
794
+ const body = { current: 1, pageSize };
795
+ if (modeType) body.modeType = modeType;
796
+ if (sourceId) body.sourceId = sourceId;
797
+ if (wfNodeId) body.wfNodeId = wfNodeId;
798
+ if (enabled !== void 0) body.enabled = enabled;
799
+ const page = record(await env.host.requestData({
800
+ operation: "smart-extract.config.list",
801
+ method: "POST",
802
+ path: PATHS.configList,
803
+ body
804
+ }));
805
+ const records = Array.isArray(page.records) ? page.records : [];
806
+ const configs = records.map((item) => {
807
+ const config = record(item);
808
+ const rules = (Array.isArray(config.fieldRules) ? config.fieldRules : []).map((rule) => {
809
+ const entry = record(rule);
810
+ return {
811
+ fieldId: entry.fieldId ?? null,
812
+ fieldName: entry.fieldInfo?.fieldName ?? null,
813
+ fieldAlias: entry.fieldAlias ?? null,
814
+ fieldRule: entry.fieldRule ?? null
815
+ };
816
+ });
817
+ return {
818
+ id: config.id ?? null,
819
+ enabled: config.enabled ?? null,
820
+ modeType: config.modeType ?? null,
821
+ sourceId: config.sourceId ?? null,
822
+ wfNodeIds: splitCsv(config.wfNodeIds),
823
+ layoutId: config.layoutId ?? null,
824
+ listId: config.listId ?? null,
825
+ parseFields: splitCsv(config.parseFields),
826
+ attachmentFieldId: config.attachmentFieldId ?? null,
827
+ needSourceReason: config.needSourceReason ?? null,
828
+ filterField: config.filterField ?? null,
829
+ agentId: config.agentId ?? null,
830
+ globalRule: config.globalRule ?? "",
831
+ fieldRules: rules
832
+ };
833
+ });
834
+ const enabledConfigs = configs.filter((config) => config.enabled === 1);
835
+ const effective = enabledConfigs.length > 0 ? enabledConfigs : configs;
836
+ const warnings = [];
837
+ if (configs.length === 0) {
838
+ warnings.push("\u8BE5\u76EE\u6807\u6CA1\u6709\u914D\u7F6E\u8BC6\u522B\u89C4\u5219\uFF1B\u4ECD\u53EF\u62BD\u53D6\uFF0C\u4F46\u53EA\u80FD\u6309\u8868\u5355\u7ED3\u6784\u672C\u8EAB\u7684\u5B57\u6BB5\u540D/\u7C7B\u578B\u5224\u65AD");
839
+ }
840
+ if (configs.length > 1) {
841
+ warnings.push(`\u547D\u4E2D ${configs.length} \u6761\u914D\u7F6E\uFF0C\u8BF7\u6309 wfNodeIds/layoutId \u9009\u4E0E\u672C\u6B21\u76EE\u6807\u4E00\u81F4\u7684\u90A3\u6761\uFF0C\u4E0D\u8981\u6DF7\u7528\u89C4\u5219`);
842
+ }
843
+ return smartExtractSuccess(
844
+ "smart-extract.config.list",
845
+ {
846
+ total: Number(page.total ?? configs.length),
847
+ count: configs.length,
848
+ configs,
849
+ effective: effective.map((config) => config.id),
850
+ /** 供直接塞进提示词的两段文本(为空则整段忽略)。 */
851
+ promptFragments: {
852
+ globalRule: effective.map((config) => config.globalRule).filter(Boolean).join("\n"),
853
+ fieldRules: effective.flatMap((config) => config.fieldRules.filter((rule) => rule.fieldRule && (rule.fieldName || rule.fieldId)).map((rule) => `${rule.fieldName || rule.fieldId}#${rule.fieldRule}`)),
854
+ parseFields: effective.flatMap((config) => config.parseFields)
855
+ }
856
+ },
857
+ { warnings }
858
+ );
859
+ }
860
+ };
861
+ var configOperations = [configList];
862
+
863
+ // src/shortcuts/smart-extract/operations/fill.ts
864
+ import { randomBytes as randomBytes3 } from "node:crypto";
865
+ import { mkdir as mkdir5, readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
866
+ import { dirname as dirname2, extname as extname2 } from "node:path";
867
+ import { inflateRawSync } from "node:zlib";
868
+
869
+ // src/shortcuts/smart-extract/operations/structure.ts
870
+ var OPTION_TYPES = /* @__PURE__ */ new Set(["Select", "SelectMultiple", "RadioBox", "CheckBox", "Cascader"]);
871
+ var ALWAYS_SINGLE_TYPES = /* @__PURE__ */ new Set([
872
+ "Text",
873
+ "TextArea",
874
+ "RichText",
875
+ "Number",
876
+ "Money",
877
+ "Amount",
878
+ "Percent",
879
+ "Score",
880
+ "DateComponent",
881
+ "TimeComponent"
882
+ ]);
883
+ function isOptionType(fieldType) {
884
+ return OPTION_TYPES.has(fieldType);
885
+ }
886
+ function boolOf(value, fallback) {
887
+ if (typeof value === "boolean") return value;
888
+ if (typeof value === "number") return value !== 0;
889
+ if (typeof value === "string") {
890
+ const text = value.trim().toLowerCase();
891
+ if (text === "true" || text === "1") return true;
892
+ if (text === "false" || text === "0") return false;
893
+ }
894
+ return fallback;
895
+ }
896
+ function textOf(value) {
897
+ if (value === void 0 || value === null) return "";
898
+ return String(value).trim();
899
+ }
900
+ function normalizeOptions(raw) {
901
+ if (!Array.isArray(raw)) return [];
902
+ return raw.map((item) => {
903
+ const option = record(item);
904
+ const optionName = textOf(option.optionName ?? option.name ?? option.label);
905
+ const optionValue = textOf(option.optionValue ?? option.value ?? option.id ?? option.optionId);
906
+ if (!optionName && !optionValue) return null;
907
+ return {
908
+ ...option.optionId === void 0 || option.optionId === null ? {} : { optionId: textOf(option.optionId) },
909
+ optionName,
910
+ optionValue: optionValue || optionName
911
+ };
912
+ }).filter((item) => item !== null);
913
+ }
914
+ function compactOf(field) {
915
+ const head = [
916
+ field.fieldId,
917
+ field.fieldName,
918
+ field.marked ? "isMarked" : "notMarked",
919
+ field.single ? "single" : "multiple",
920
+ field.fieldType || "Text"
921
+ ].join("#");
922
+ const options = field.options?.length ? `#${field.options.map((option) => `[optionName:${option.optionName},optionValue:${option.optionValue}]`).join("\u3001")}` : "";
923
+ return `${head}${options}`;
924
+ }
925
+ function normalizeField(raw) {
926
+ const field = record(raw);
927
+ const fieldId = textOf(field.fieldId ?? field.id);
928
+ if (!fieldId) return null;
929
+ const fieldType = textOf(field.fieldType ?? field.type) || "Text";
930
+ const options = isOptionType(fieldType) ? normalizeOptions(field.options) : [];
931
+ const normalized = {
932
+ fieldId,
933
+ fieldName: textOf(field.fieldName ?? field.name) || fieldId,
934
+ fieldType,
935
+ // 照抄服务端;wf 模式会丢值,由 correctSingleFromEb / applyTypeBasedSingle 事后校正。
936
+ single: boolOf(field.single ?? field.isSingle, false),
937
+ marked: boolOf(field.marked ?? field.isMarked, false),
938
+ ...textOf(field.fieldDbName) ? { fieldDbName: textOf(field.fieldDbName) } : {},
939
+ ...textOf(field.browserModule) ? { browserModule: textOf(field.browserModule) } : {},
940
+ ...textOf(field.browserType) ? { browserType: textOf(field.browserType) } : {},
941
+ ...textOf(field.fieldAlias) ? { fieldAlias: textOf(field.fieldAlias) } : {},
942
+ ...textOf(field.parentFieldId) ? { parentFieldId: textOf(field.parentFieldId) } : {},
943
+ ...options.length > 0 ? { options } : {},
944
+ compact: ""
945
+ };
946
+ normalized.compact = compactOf(normalized);
947
+ return normalized;
948
+ }
949
+ function normalizeStructure(raw, mode, source) {
950
+ if (!raw || typeof raw !== "object") {
951
+ throw smartExtractValidationError("structure_invalid", "\u8868\u5355\u7ED3\u6784\u54CD\u5E94\u4E0D\u662F\u5BF9\u8C61");
952
+ }
953
+ const main = record(raw);
954
+ const layoutFields = [];
955
+ const mainFields = [];
956
+ for (const item of Array.isArray(main.mainFields) ? main.mainFields : []) {
957
+ const field = normalizeField(item);
958
+ if (!field) continue;
959
+ if (field.fieldType === "Fold") {
960
+ layoutFields.push({ fieldId: field.fieldId, fieldName: field.fieldName });
961
+ continue;
962
+ }
963
+ mainFields.push(field);
964
+ }
965
+ const subTables = [];
966
+ for (const item of Array.isArray(main.subTables) ? main.subTables : []) {
967
+ const sub = record(item);
968
+ const subFormId = textOf(sub.subFormId ?? sub.id);
969
+ if (!subFormId) continue;
970
+ const fields = [];
971
+ for (const subField of Array.isArray(sub.subFields) ? sub.subFields : []) {
972
+ const field = normalizeField(subField);
973
+ if (!field || field.fieldType === "Fold") continue;
974
+ fields.push(field);
975
+ }
976
+ subTables.push({
977
+ subFormId,
978
+ subFormName: textOf(sub.subFormName ?? sub.name) || subFormId,
979
+ ...textOf(sub.subDbTableName) ? { subDbTableName: textOf(sub.subDbTableName) } : {},
980
+ fields,
981
+ subFieldsStr: fields.map((field) => field.compact)
982
+ });
983
+ }
984
+ const mainFormId = textOf(main.mainFormId ?? main.formId);
985
+ if (!mainFormId) {
986
+ throw smartExtractValidationError("structure_invalid", "\u8868\u5355\u7ED3\u6784\u7F3A\u5C11 mainFormId");
987
+ }
988
+ return {
989
+ mode,
990
+ source,
991
+ mainFormId,
992
+ ...textOf(main.mainFormName) ? { mainFormName: textOf(main.mainFormName) } : {},
993
+ ...textOf(main.mainFormDesc) ? { mainFormDesc: textOf(main.mainFormDesc) } : {},
994
+ ...textOf(main.mainDbTableName) ? { mainDbTableName: textOf(main.mainDbTableName) } : {},
995
+ ...main.appId === void 0 || main.appId === null ? {} : { appId: textOf(main.appId) },
996
+ mainFields,
997
+ mainFieldsStr: mainFields.map((field) => field.compact),
998
+ subTables,
999
+ layoutFields,
1000
+ stats: {
1001
+ mainFieldCount: mainFields.length,
1002
+ subTableCount: subTables.length,
1003
+ subFieldCount: subTables.reduce((total, table) => total + table.fields.length, 0),
1004
+ layoutFieldCount: layoutFields.length,
1005
+ optionFieldCount: mainFields.filter((field) => (field.options?.length ?? 0) > 0).length
1006
+ }
1007
+ };
1008
+ }
1009
+ function rewriteCompact(structure, touched) {
1010
+ if (!touched) return;
1011
+ structure.mainFieldsStr = structure.mainFields.map((field) => field.compact);
1012
+ for (const table of structure.subTables) {
1013
+ table.subFieldsStr = table.fields.map((field) => field.compact);
1014
+ }
1015
+ }
1016
+ function eachField(structure) {
1017
+ return [...structure.mainFields, ...structure.subTables.flatMap((table) => table.fields)];
1018
+ }
1019
+ async function correctSingleFromEb(host, structure) {
1020
+ if (!structure.mainFormId) return 0;
1021
+ const raw = await host.requestData({
1022
+ operation: "smart-extract.form.structure",
1023
+ method: "GET",
1024
+ path: PATHS.governFormSimple,
1025
+ query: { formId: structure.mainFormId, formModeType: "eb" }
1026
+ });
1027
+ const truth = /* @__PURE__ */ new Map();
1028
+ const collect = (list) => {
1029
+ for (const entry of list) {
1030
+ const item = record(entry);
1031
+ const fieldId = textOf(item.fieldId ?? item.id);
1032
+ if (!fieldId) continue;
1033
+ if (item.single === void 0 && item.isSingle === void 0) continue;
1034
+ truth.set(fieldId, boolOf(item.single ?? item.isSingle, false));
1035
+ }
1036
+ };
1037
+ const data = record(raw);
1038
+ collect(Array.isArray(data.mainFields) ? data.mainFields : []);
1039
+ for (const entry of Array.isArray(data.subTables) ? data.subTables : []) {
1040
+ const sub = record(entry);
1041
+ collect(Array.isArray(sub.subFields) ? sub.subFields : []);
1042
+ }
1043
+ let corrected = 0;
1044
+ for (const field of eachField(structure)) {
1045
+ const expected = truth.get(field.fieldId);
1046
+ if (expected === void 0 || expected === field.single) continue;
1047
+ field.single = expected;
1048
+ field.compact = compactOf(field);
1049
+ corrected += 1;
1050
+ }
1051
+ rewriteCompact(structure, corrected > 0);
1052
+ return corrected;
1053
+ }
1054
+ function applyTypeBasedSingle(structure) {
1055
+ let corrected = 0;
1056
+ for (const field of eachField(structure)) {
1057
+ if (field.single || !ALWAYS_SINGLE_TYPES.has(field.fieldType)) continue;
1058
+ field.single = true;
1059
+ field.compact = compactOf(field);
1060
+ corrected += 1;
1061
+ }
1062
+ rewriteCompact(structure, corrected > 0);
1063
+ return corrected;
1064
+ }
1065
+ function filterByFieldIds(structure, keep) {
1066
+ if (keep.length === 0) return structure;
1067
+ const wanted = new Set(keep);
1068
+ const mainFields = structure.mainFields.filter((field) => wanted.has(field.fieldId));
1069
+ const subTables = structure.subTables.map((table) => {
1070
+ const fields = table.fields.filter((field) => wanted.has(field.fieldId));
1071
+ return { ...table, fields, subFieldsStr: fields.map((field) => field.compact) };
1072
+ });
1073
+ return {
1074
+ ...structure,
1075
+ mainFields,
1076
+ mainFieldsStr: mainFields.map((field) => field.compact),
1077
+ subTables,
1078
+ stats: {
1079
+ ...structure.stats,
1080
+ mainFieldCount: mainFields.length,
1081
+ subFieldCount: subTables.reduce((total, table) => total + table.fields.length, 0)
1082
+ }
1083
+ };
1084
+ }
1085
+ async function resolveStartNode(host, workflowId) {
1086
+ const data = record(await host.requestData({
1087
+ operation: "smart-extract.form.structure",
1088
+ method: "GET",
1089
+ path: PATHS.flowStartNode,
1090
+ query: { workflowId }
1091
+ }));
1092
+ const node = record(data.node);
1093
+ const resolved = node.id ?? node.nodeId;
1094
+ if (data.success === false || !resolved) {
1095
+ throw smartExtractValidationError(
1096
+ "node_id_required",
1097
+ "\u672A\u6307\u5B9A nodeId \u4E14\u81EA\u52A8\u53D6\u53D1\u8D77\u8282\u70B9\u5931\u8D25\uFF1B\u8BF7\u663E\u5F0F\u4F20 nodeId",
1098
+ { workflowId, result: data }
1099
+ );
1100
+ }
1101
+ const nodeName = textOf(node.nodeName) || void 0;
1102
+ return {
1103
+ nodeId: String(resolved),
1104
+ ...nodeName ? { nodeName } : {},
1105
+ warnings: [`\u672A\u6307\u5B9A\u8282\u70B9\uFF0C\u5DF2\u4F7F\u7528\u6D41\u7A0B\u53D1\u8D77\u8282\u70B9${nodeName ? `\u300C${nodeName}\u300D` : ""}\uFF08nodeId=${resolved}\uFF09`]
1106
+ };
1107
+ }
1108
+ async function fetchWfNodeStructure(host, workflowId, nodeId, options = {}) {
1109
+ const keep = options.keep ?? [];
1110
+ const warnings = [];
1111
+ const raw = await host.requestData({
1112
+ operation: "smart-extract.form.structure",
1113
+ method: "GET",
1114
+ path: PATHS.governFormSimple,
1115
+ query: {
1116
+ workflowId,
1117
+ nodeId,
1118
+ formModeType: "wf",
1119
+ ...keep.length > 0 ? { targetFieldIdList: keep.join(",") } : {}
1120
+ }
1121
+ });
1122
+ const structure = normalizeStructure(raw, "wf-node", {
1123
+ workflowId,
1124
+ nodeId,
1125
+ ...options.nodeName ? { nodeName: options.nodeName } : {}
1126
+ });
1127
+ try {
1128
+ const corrected = await correctSingleFromEb(host, structure);
1129
+ if (corrected > 0) {
1130
+ warnings.push(`\u5DF2\u6309 EB \u8868\u5355\u5B9A\u4E49\u6821\u6B63 ${corrected} \u4E2A\u5B57\u6BB5\u7684\u5355\u503C/\u591A\u503C\u6807\u8BB0\uFF08wf \u63A5\u53E3\u4F1A\u4E22\u8BE5\u6807\u8BB0\uFF09`);
1131
+ }
1132
+ } catch {
1133
+ const corrected = applyTypeBasedSingle(structure);
1134
+ if (corrected > 0) {
1135
+ warnings.push(
1136
+ `\u672A\u80FD\u53D6\u5230 EB \u8868\u5355\u5B9A\u4E49\uFF0C\u5DF2\u6309\u5B57\u6BB5\u7C7B\u578B\u63A8\u65AD ${corrected} \u4E2A\u5B57\u6BB5\u4E3A\u5355\u503C\uFF1B\u4EBA\u5458/\u6D4F\u89C8\u6846/\u591A\u9009\u7C7B\u4ECD\u4EE5\u670D\u52A1\u7AEF\u4E3A\u51C6`
1137
+ );
1138
+ }
1139
+ }
1140
+ return { structure, warnings };
1141
+ }
1142
+ var formStructure = {
1143
+ name: "smart-extract.form.structure",
1144
+ risk: "read",
1145
+ summary: "\u53D6\u8868\u5355\u7ED3\u6784\u5E76\u5F52\u4E00\u5316\uFF1A\u4F20 workflowId(+nodeId\uFF0C\u7F3A\u7701\u81EA\u52A8\u53D6\u53D1\u8D77\u8282\u70B9) \u8D70\u6D41\u7A0B\u8282\u70B9\u5B57\u6BB5\uFF0C\u4F20 formId \u8D70 EB \u8868\u5355\u3002\u8F93\u51FA mainFieldsStr/subFieldsStr \u538B\u7F29\u4E32\uFF0C\u53EF\u76F4\u63A5\u8FDB\u63D0\u793A\u8BCD\u3002",
1146
+ inputSchema: schemaOf({
1147
+ workflowId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u6A21\u677F ID\uFF08wf\uFF09" },
1148
+ nodeId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u8282\u70B9 ID\uFF1B\u4E0D\u4F20\u65F6\u81EA\u52A8\u53D6\u53D1\u8D77\u8282\u70B9" },
1149
+ formId: { ...SCHEMA_ID, description: "EB \u8868\u5355 ID\uFF08\u4E0E workflowId \u4E8C\u9009\u4E00\uFF09" },
1150
+ targetFieldIdList: {
1151
+ type: "array",
1152
+ items: { type: "string" },
1153
+ description: "\u53EA\u8F93\u51FA\u8FD9\u4E9B\u5B57\u6BB5 ID\uFF08\u53EF\u9009\uFF09"
1154
+ }
1155
+ }),
1156
+ handler: async (args, env) => {
1157
+ const workflowId = optionalId(args.workflowId, "workflowId");
1158
+ const formId = optionalId(args.formId, "formId");
1159
+ const nodeIdInput = optionalId(args.nodeId, "nodeId");
1160
+ if (workflowId && formId) {
1161
+ throw smartExtractValidationError("target_conflict", "workflowId \u4E0E formId \u53EA\u80FD\u4F20\u4E00\u4E2A");
1162
+ }
1163
+ if (!workflowId && !formId) {
1164
+ throw smartExtractValidationError("target_required", "\u5FC5\u987B\u63D0\u4F9B workflowId \u6216 formId");
1165
+ }
1166
+ const keep = parseIdList(args.targetFieldIdList, "targetFieldIdList");
1167
+ const warnings = [];
1168
+ let structure;
1169
+ if (formId) {
1170
+ const raw = await env.host.requestData({
1171
+ operation: "smart-extract.form.structure",
1172
+ method: "GET",
1173
+ path: PATHS.governFormSimple,
1174
+ query: {
1175
+ formId,
1176
+ formModeType: "eb",
1177
+ ...keep.length > 0 ? { targetFieldIdList: keep.join(",") } : {}
1178
+ }
1179
+ });
1180
+ structure = normalizeStructure(raw, "eb", { formId });
1181
+ if (nodeIdInput) warnings.push("EB \u6A21\u5F0F\u4E0D\u652F\u6301 nodeId\uFF0C\u5DF2\u5FFD\u7565");
1182
+ } else {
1183
+ if (!workflowId) {
1184
+ throw smartExtractValidationError("target_required", "\u6D41\u7A0B\u6A21\u5F0F\u5FC5\u987B\u63D0\u4F9B workflowId");
1185
+ }
1186
+ let nodeId = nodeIdInput;
1187
+ let nodeName;
1188
+ if (!nodeId) {
1189
+ const start = await resolveStartNode(env.host, workflowId);
1190
+ nodeId = start.nodeId;
1191
+ nodeName = start.nodeName;
1192
+ warnings.push(...start.warnings);
1193
+ }
1194
+ const loaded = await fetchWfNodeStructure(env.host, workflowId, nodeId, {
1195
+ keep,
1196
+ ...nodeName ? { nodeName } : {}
1197
+ });
1198
+ structure = loaded.structure;
1199
+ warnings.push(...loaded.warnings);
1200
+ warnings.push("\u6D41\u7A0B\u8282\u70B9\u6A21\u5F0F\u53EA\u8FD4\u56DE\u8BE5\u8282\u70B9\u300C\u53EF\u7F16\u8F91\u6216\u5FC5\u586B\u300D\u7684\u5B57\u6BB5\uFF1B\u53EA\u8BFB\u5B57\u6BB5\u5DF2\u88AB\u670D\u52A1\u7AEF\u8FC7\u6EE4");
1201
+ }
1202
+ const filtered = keep.length > 0 ? filterByFieldIds(structure, keep) : structure;
1203
+ if (keep.length > 0) {
1204
+ const present = /* @__PURE__ */ new Set([
1205
+ ...filtered.mainFields.map((field) => field.fieldId),
1206
+ ...filtered.subTables.flatMap((table) => table.fields.map((field) => field.fieldId))
1207
+ ]);
1208
+ const missing = keep.filter((id) => !present.has(id));
1209
+ if (missing.length > 0) {
1210
+ warnings.push(`\u4EE5\u4E0B\u5B57\u6BB5\u4E0D\u5728\u5F53\u524D\u7ED3\u6784/\u8282\u70B9\u53EF\u586B\u8303\u56F4\u5185\uFF0C\u5DF2\u5FFD\u7565\uFF1A${missing.join(",")}`);
1211
+ }
1212
+ }
1213
+ if (filtered.mainFields.length === 0) {
1214
+ warnings.push("\u4E3B\u8868\u6CA1\u6709\u53EF\u586B\u5B57\u6BB5\uFF1A\u8BE5\u8282\u70B9\u53EF\u80FD\u5168\u90E8\u53EA\u8BFB\uFF0C\u6216 targetFieldIdList \u8FC7\u6EE4\u540E\u4E3A\u7A7A");
1215
+ }
1216
+ return smartExtractSuccess("smart-extract.form.structure", filtered, { warnings });
1217
+ }
1218
+ };
1219
+ var structureOperations = [formStructure];
1220
+
1221
+ // src/shortcuts/smart-extract/operations/validate.ts
1222
+ function coerceStructure(raw) {
1223
+ const looksNormalized = Array.isArray(raw.mainFields) && Array.isArray(raw.mainFieldsStr) && raw.stats && typeof raw.stats === "object";
1224
+ if (looksNormalized) return raw;
1225
+ return normalizeStructure(raw, "wf-node", {});
1226
+ }
1227
+ function valuesOf(value) {
1228
+ if (value === void 0 || value === null) return [];
1229
+ if (Array.isArray(value)) {
1230
+ return value.filter((item) => item !== void 0 && item !== null).map((item) => typeof item === "object" ? JSON.stringify(item) : String(item)).filter((item) => item.trim() !== "");
1231
+ }
1232
+ if (typeof value === "object") return [JSON.stringify(value)];
1233
+ const text = String(value).trim();
1234
+ return text === "" ? [] : [text];
1235
+ }
1236
+ function isDateField(fieldType) {
1237
+ return fieldType === "DateComponent" || fieldType === "Date";
1238
+ }
1239
+ function isNumberField(fieldType) {
1240
+ return fieldType === "Money" || fieldType === "NumberComponent" || fieldType === "Number";
1241
+ }
1242
+ var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
1243
+ var NUMBER_PATTERN = /^-?\d+(\.\d+)?$/u;
1244
+ function checkFieldValue(field, values, path, strict, errors, warnings, options = {}) {
1245
+ if (values.length === 0) {
1246
+ if (!options.allowEmpty) {
1247
+ warnings.push({ path, code: "empty_value", message: "\u7A7A\u503C\u5B57\u6BB5\u4E0D\u5E94\u51FA\u73B0\u5728\u7ED3\u679C\u91CC\uFF08fieldResults \u53EA\u653E\u6709\u6548\u503C\uFF09" });
1248
+ }
1249
+ return;
1250
+ }
1251
+ if (field.single && values.length > 1) {
1252
+ errors.push({
1253
+ path,
1254
+ code: "single_field_multiple_values",
1255
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u662F\u5355\u503C\u5B57\u6BB5\uFF08single\uFF09\uFF0C\u5374\u7ED9\u4E86 ${values.length} \u4E2A\u503C`
1256
+ });
1257
+ }
1258
+ if (field.options && field.options.length > 0) {
1259
+ const optionValues = new Set(field.options.map((option) => option.optionValue));
1260
+ const optionNames = new Set(field.options.map((option) => option.optionName));
1261
+ for (const value of values) {
1262
+ for (const part of field.single ? [value] : value.split(/[,,、;;]/u).map((item) => item.trim()).filter(Boolean)) {
1263
+ if (optionValues.has(part)) continue;
1264
+ if (optionNames.has(part)) {
1265
+ const hit = field.options.find((option) => option.optionName === part);
1266
+ errors.push({
1267
+ path,
1268
+ code: "option_name_used",
1269
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u5199\u7684\u662F\u9009\u9879\u540D\u300C${part}\u300D\uFF0C\u5FC5\u987B\u5199 optionValue\u300C${hit?.optionValue}\u300D`
1270
+ });
1271
+ continue;
1272
+ }
1273
+ const issue = {
1274
+ path,
1275
+ code: "option_not_found",
1276
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u7684\u503C\u300C${part}\u300D\u4E0D\u5728\u5019\u9009\u9879\u4E2D\uFF08\u53EF\u7528\uFF1A${[...optionValues].slice(0, 10).join(" / ")}\uFF09`
1277
+ };
1278
+ if (strict) errors.push(issue);
1279
+ else warnings.push(issue);
1280
+ }
1281
+ }
1282
+ }
1283
+ if (isDateField(field.fieldType)) {
1284
+ for (const value of values) {
1285
+ if (!DATE_PATTERN.test(value)) {
1286
+ errors.push({
1287
+ path,
1288
+ code: "date_format",
1289
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u65E5\u671F\u5FC5\u987B\u662F YYYY-MM-DD\uFF0C\u5F53\u524D\u4E3A\u300C${value}\u300D`
1290
+ });
1291
+ }
1292
+ }
1293
+ }
1294
+ if (isNumberField(field.fieldType)) {
1295
+ for (const value of values) {
1296
+ if (!NUMBER_PATTERN.test(normalizeNumberText(value))) {
1297
+ errors.push({
1298
+ path,
1299
+ code: "number_format",
1300
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u5FC5\u987B\u662F\u7EAF\u6570\u5B57\uFF08\u53BB\u6389\u5343\u5206\u4F4D/\u8D27\u5E01\u7B26\u53F7\uFF09\uFF0C\u5F53\u524D\u4E3A\u300C${value}\u300D`
1301
+ });
1302
+ }
1303
+ }
1304
+ }
1305
+ if (field.marked) {
1306
+ for (const value of values) {
1307
+ if (value.length > 40) {
1308
+ warnings.push({
1309
+ path,
1310
+ code: "marked_value_too_long",
1311
+ message: `\u5B57\u6BB5\u300C${field.fieldName}\u300D\u662F\u6807\u8BB0\u5B57\u6BB5\uFF08isMarked\uFF09\uFF0C\u5E94\u8FD4\u56DE\u7B80\u77ED\u5173\u952E\u8BCD\u7528\u4E8E\u6A21\u7CCA\u641C\u7D22\uFF0C\u5F53\u524D ${value.length} \u5B57`
1312
+ });
1313
+ }
1314
+ }
1315
+ }
1316
+ }
1317
+ function checkOrigins(origin, path, knownIds, errors, warnings) {
1318
+ if (origin === null || origin === void 0) return;
1319
+ if (!Array.isArray(origin)) {
1320
+ errors.push({
1321
+ path,
1322
+ code: "origin_not_array",
1323
+ message: 'origin \u5FC5\u987B\u662F\u6570\u7EC4\uFF08["attachmentId#\u539F\u6587"]\uFF09\uFF0C\u65E0\u6765\u6E90\u624D\u7528 null'
1324
+ });
1325
+ return;
1326
+ }
1327
+ for (const [index, item] of origin.entries()) {
1328
+ if (item === null || item === void 0) continue;
1329
+ if (typeof item !== "string") {
1330
+ errors.push({ path: `${path}[${index}]`, code: "origin_item_invalid", message: "origin \u5143\u7D20\u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1331
+ continue;
1332
+ }
1333
+ const hashIndex = item.indexOf("#");
1334
+ if (hashIndex <= 0) {
1335
+ errors.push({
1336
+ path: `${path}[${index}]`,
1337
+ code: "origin_format",
1338
+ message: "origin \u5FC5\u987B\u662F attachmentId#\u539F\u6587\u7247\u6BB5\uFF08\u7528\u6237\u8F93\u5165\u7528 userInput#\u539F\u6587\uFF09"
1339
+ });
1340
+ continue;
1341
+ }
1342
+ const sourceId = item.slice(0, hashIndex);
1343
+ const snippet = item.slice(hashIndex + 1);
1344
+ if (snippet.trim() === "") {
1345
+ warnings.push({ path: `${path}[${index}]`, code: "origin_empty_snippet", message: "origin \u7684\u539F\u6587\u7247\u6BB5\u4E3A\u7A7A" });
1346
+ }
1347
+ if (sourceId === "attachmentId") {
1348
+ warnings.push({
1349
+ path: `${path}[${index}]`,
1350
+ code: "origin_placeholder_id",
1351
+ message: "origin \u91CC\u5199\u7684\u662F\u5360\u4F4D\u7B26 attachmentId\uFF0C\u5FC5\u987B\u6362\u6210\u771F\u5B9E\u9644\u4EF6 ID"
1352
+ });
1353
+ } else if (sourceId !== "userInput" && knownIds.size > 0 && !knownIds.has(sourceId)) {
1354
+ warnings.push({
1355
+ path: `${path}[${index}]`,
1356
+ code: "origin_unknown_attachment",
1357
+ message: `origin \u7684\u6765\u6E90 ID\u300C${sourceId}\u300D\u4E0D\u5728\u672C\u6B21\u9644\u4EF6\u5217\u8868\u91CC`
1358
+ });
1359
+ }
1360
+ }
1361
+ }
1362
+ function normalizeResult(result, structureRaw) {
1363
+ const structure = coerceStructure(structureRaw);
1364
+ const normalized = JSON.parse(JSON.stringify(result ?? {}));
1365
+ const order = new Map(structure.mainFields.map((field, index) => [field.fieldId, index]));
1366
+ const rows = Array.isArray(normalized.mainTable?.rows) ? normalized.mainTable.rows : [];
1367
+ for (const rowRaw of rows) {
1368
+ const row = rowRaw && typeof rowRaw === "object" && !Array.isArray(rowRaw) ? rowRaw : null;
1369
+ if (!row || !Array.isArray(row.fieldResults)) continue;
1370
+ const kept = row.fieldResults.filter(
1371
+ (item) => item && typeof item === "object" && !Array.isArray(item) && valuesOf(item.value).length > 0
1372
+ );
1373
+ kept.sort((left, right) => {
1374
+ const leftIndex = order.get(String(left.fieldInfo ?? "").split("#")[0].trim()) ?? Number.MAX_SAFE_INTEGER;
1375
+ const rightIndex = order.get(String(right.fieldInfo ?? "").split("#")[0].trim()) ?? Number.MAX_SAFE_INTEGER;
1376
+ return leftIndex - rightIndex;
1377
+ });
1378
+ row.fieldResults = kept;
1379
+ }
1380
+ if (Array.isArray(normalized.subTables)) {
1381
+ for (const table of normalized.subTables) {
1382
+ if (!table || typeof table !== "object") continue;
1383
+ const subTable = table;
1384
+ if (!Array.isArray(subTable.rows)) continue;
1385
+ subTable.rows = subTable.rows.filter((rowRaw) => {
1386
+ const row = rowRaw && typeof rowRaw === "object" ? rowRaw : null;
1387
+ if (!row) return true;
1388
+ if (!Array.isArray(row.values)) return true;
1389
+ return row.values.some((value) => valuesOf(value).length > 0);
1390
+ });
1391
+ }
1392
+ }
1393
+ return normalized;
1394
+ }
1395
+ function validateExtraction(result, structureRaw, options = {}) {
1396
+ const structure = coerceStructure(structureRaw);
1397
+ const strict = options.strict !== false;
1398
+ const maxErrors = Math.max(1, Math.min(200, Number(options.maxErrors ?? 50) || 50));
1399
+ const knownIds = new Set((options.knownAttachmentIds ?? []).map((item) => String(item).trim()).filter(Boolean));
1400
+ {
1401
+ const errors = [];
1402
+ const warnings = [];
1403
+ const mainFieldMap = new Map(structure.mainFields.map((field) => [field.fieldId, field]));
1404
+ const fieldOrder = structure.mainFields.map((field) => field.fieldId);
1405
+ const subTableMap = new Map(structure.subTables.map((table) => [table.subFormId, table]));
1406
+ if (result.isSuccess === false) {
1407
+ errors.push({
1408
+ path: "isSuccess",
1409
+ code: "result_not_success",
1410
+ message: `\u62BD\u53D6\u7ED3\u679C\u6807\u8BB0\u4E3A\u5931\u8D25\uFF1A${String(result.errorMsg ?? "\u672A\u7ED9 errorMsg")}`
1411
+ });
1412
+ } else if (result.isSuccess !== true) {
1413
+ errors.push({ path: "isSuccess", code: "is_success_missing", message: "isSuccess \u5FC5\u586B\uFF0C\u4E14\u5FC5\u987B\u662F true/false" });
1414
+ }
1415
+ const mainTable = result.mainTable;
1416
+ if (!mainTable || typeof mainTable !== "object" || !Array.isArray(mainTable.rows)) {
1417
+ errors.push({ path: "mainTable.rows", code: "main_rows_missing", message: "mainTable.rows \u5FC5\u987B\u662F\u6570\u7EC4" });
1418
+ }
1419
+ const mainRows = mainTable && Array.isArray(mainTable.rows) ? mainTable.rows : [];
1420
+ const mainDataIds = /* @__PURE__ */ new Set();
1421
+ let mainFieldsFilled = 0;
1422
+ for (const [rowIndex, rowRaw] of mainRows.entries()) {
1423
+ if (!rowRaw || typeof rowRaw !== "object" || Array.isArray(rowRaw)) {
1424
+ errors.push({ path: `mainTable.rows[${rowIndex}]`, code: "main_row_invalid", message: "\u4E3B\u8868\u884C\u5FC5\u987B\u662F\u5BF9\u8C61" });
1425
+ continue;
1426
+ }
1427
+ const row = rowRaw;
1428
+ const mainDataId = row.mainDataId;
1429
+ if (mainDataId === void 0 || mainDataId === null || String(mainDataId).trim() === "") {
1430
+ errors.push({ path: `mainTable.rows[${rowIndex}].mainDataId`, code: "main_data_id_missing", message: "mainDataId \u5FC5\u586B" });
1431
+ } else {
1432
+ mainDataIds.add(String(mainDataId));
1433
+ }
1434
+ if (!Array.isArray(row.fieldResults)) {
1435
+ errors.push({
1436
+ path: `mainTable.rows[${rowIndex}].fieldResults`,
1437
+ code: "field_results_missing",
1438
+ message: "fieldResults \u5FC5\u987B\u662F\u6570\u7EC4"
1439
+ });
1440
+ continue;
1441
+ }
1442
+ const seen = /* @__PURE__ */ new Set();
1443
+ for (const [fieldIndex, fieldRaw] of row.fieldResults.entries()) {
1444
+ const path = `mainTable.rows[${rowIndex}].fieldResults[${fieldIndex}]`;
1445
+ if (!fieldRaw || typeof fieldRaw !== "object") {
1446
+ errors.push({ path, code: "field_result_invalid", message: "fieldResults \u5143\u7D20\u5FC5\u987B\u662F\u5BF9\u8C61" });
1447
+ continue;
1448
+ }
1449
+ const fieldResult = fieldRaw;
1450
+ const fieldInfo = String(fieldResult.fieldInfo ?? "");
1451
+ const hash = fieldInfo.indexOf("#");
1452
+ if (hash <= 0) {
1453
+ errors.push({ path: `${path}.fieldInfo`, code: "field_info_format", message: "fieldInfo \u5FC5\u987B\u662F \u5B57\u6BB5ID#\u5B57\u6BB5\u540D\u79F0" });
1454
+ continue;
1455
+ }
1456
+ const fieldId = fieldInfo.slice(0, hash).trim();
1457
+ const fieldName = fieldInfo.slice(hash + 1).trim();
1458
+ const field = mainFieldMap.get(fieldId);
1459
+ if (!field) {
1460
+ errors.push({
1461
+ path: `${path}.fieldInfo`,
1462
+ code: "unknown_field",
1463
+ message: `\u4E3B\u8868\u6CA1\u6709\u5B57\u6BB5 ID\u300C${fieldId}\u300D\uFF08${fieldName}\uFF09`
1464
+ });
1465
+ continue;
1466
+ }
1467
+ if (field.fieldName && fieldName && field.fieldName !== fieldName) {
1468
+ warnings.push({
1469
+ path: `${path}.fieldInfo`,
1470
+ code: "field_name_mismatch",
1471
+ message: `\u5B57\u6BB5 ID ${fieldId} \u7684\u540D\u79F0\u5E94\u4E3A\u300C${field.fieldName}\u300D\uFF0C\u7ED3\u679C\u5199\u7684\u662F\u300C${fieldName}\u300D`
1472
+ });
1473
+ }
1474
+ if (seen.has(fieldId)) {
1475
+ errors.push({ path, code: "duplicate_field", message: `\u540C\u4E00\u884C\u91CD\u590D\u51FA\u73B0\u5B57\u6BB5\u300C${field.fieldName}\u300D` });
1476
+ }
1477
+ seen.add(fieldId);
1478
+ const values = valuesOf(fieldResult.value);
1479
+ mainFieldsFilled += values.length > 0 ? 1 : 0;
1480
+ checkFieldValue(field, values, `${path}.value`, strict, errors, warnings);
1481
+ checkOrigins(fieldResult.origin, `${path}.origin`, knownIds, errors, warnings);
1482
+ }
1483
+ const orderIndexes = row.fieldResults.map((item) => fieldOrder.indexOf(String(item?.fieldInfo ?? "").split("#")[0])).filter((index) => index >= 0);
1484
+ const sorted = [...orderIndexes].sort((left, right) => left - right);
1485
+ if (orderIndexes.join(",") !== sorted.join(",")) {
1486
+ warnings.push({
1487
+ path: `mainTable.rows[${rowIndex}].fieldResults`,
1488
+ code: "field_order_diff",
1489
+ message: "fieldResults \u987A\u5E8F\u4E0E mainFieldsStr \u5B57\u6BB5\u987A\u5E8F\u4E0D\u4E00\u81F4"
1490
+ });
1491
+ }
1492
+ }
1493
+ const subTables = Array.isArray(result.subTables) ? result.subTables : [];
1494
+ if (result.subTables === void 0 || result.subTables === null) {
1495
+ errors.push({ path: "subTables", code: "sub_tables_missing", message: "subTables \u5FC5\u987B\u662F\u6570\u7EC4\uFF08\u65E0\u660E\u7EC6\u7ED9 []\uFF09" });
1496
+ }
1497
+ let subRows = 0;
1498
+ for (const [tableIndex, tableRaw] of subTables.entries()) {
1499
+ const tablePath = `subTables[${tableIndex}]`;
1500
+ if (!tableRaw || typeof tableRaw !== "object") {
1501
+ errors.push({ path: tablePath, code: "sub_table_invalid", message: "\u660E\u7EC6\u8868\u5FC5\u987B\u662F\u5BF9\u8C61" });
1502
+ continue;
1503
+ }
1504
+ const table = tableRaw;
1505
+ const subFormId = String(table.subFormId ?? "").trim();
1506
+ const expected = subTableMap.get(subFormId);
1507
+ if (!expected) {
1508
+ errors.push({
1509
+ path: `${tablePath}.subFormId`,
1510
+ code: "unknown_sub_table",
1511
+ message: `\u7ED3\u6784\u91CC\u6CA1\u6709\u660E\u7EC6\u8868 ID\u300C${subFormId}\u300D`
1512
+ });
1513
+ }
1514
+ const fields = Array.isArray(table.fields) ? table.fields.map((item) => String(item)) : [];
1515
+ if (expected) {
1516
+ const expectedFields = expected.fields.map((field) => `${field.fieldId}#${field.fieldName}`);
1517
+ if (fields.join("|") !== expectedFields.join("|")) {
1518
+ errors.push({
1519
+ path: `${tablePath}.fields`,
1520
+ code: "sub_fields_mismatch",
1521
+ message: `\u660E\u7EC6\u8868\u300C${expected.subFormName}\u300D\u7684 fields \u4E0E\u7ED3\u6784\u4E0D\u4E00\u81F4`,
1522
+ expected: expectedFields,
1523
+ actual: fields
1524
+ });
1525
+ }
1526
+ }
1527
+ const rows = Array.isArray(table.rows) ? table.rows : [];
1528
+ for (const [rowIndex, subRowRaw] of rows.entries()) {
1529
+ const rowPath = `${tablePath}.rows[${rowIndex}]`;
1530
+ if (!subRowRaw || typeof subRowRaw !== "object") {
1531
+ errors.push({ path: rowPath, code: "sub_row_invalid", message: "\u660E\u7EC6\u884C\u5FC5\u987B\u662F\u5BF9\u8C61" });
1532
+ continue;
1533
+ }
1534
+ subRows += 1;
1535
+ const subRow = subRowRaw;
1536
+ for (const key of ["reasons", "values", "origins"]) {
1537
+ if (!Array.isArray(subRow[key])) {
1538
+ errors.push({ path: `${rowPath}.${key}`, code: "sub_row_array_missing", message: `${key} \u5FC5\u987B\u662F\u6570\u7EC4` });
1539
+ } else if (subRow[key].length !== fields.length) {
1540
+ errors.push({
1541
+ path: `${rowPath}.${key}`,
1542
+ code: "sub_row_length_mismatch",
1543
+ message: `${key} \u957F\u5EA6 ${subRow[key].length} \u4E0E fields \u957F\u5EA6 ${fields.length} \u4E0D\u4E00\u81F4`
1544
+ });
1545
+ }
1546
+ }
1547
+ if (subRow.mainDataId !== void 0 && subRow.mainDataId !== null && mainDataIds.size > 0 && !mainDataIds.has(String(subRow.mainDataId))) {
1548
+ warnings.push({
1549
+ path: `${rowPath}.mainDataId`,
1550
+ code: "sub_main_data_id_unknown",
1551
+ message: `mainDataId=${subRow.mainDataId} \u5728\u4E3B\u8868\u91CC\u627E\u4E0D\u5230`
1552
+ });
1553
+ }
1554
+ if (expected && Array.isArray(subRow.values)) {
1555
+ for (const [fieldIndex, field] of expected.fields.entries()) {
1556
+ const values = valuesOf(subRow.values[fieldIndex]);
1557
+ checkFieldValue(field, values, `${rowPath}.values[${fieldIndex}]`, strict, errors, warnings, { allowEmpty: true });
1558
+ }
1559
+ }
1560
+ if (Array.isArray(subRow.origins)) {
1561
+ for (const [originIndex, origin] of subRow.origins.entries()) {
1562
+ checkOrigins(origin, `${rowPath}.origins[${originIndex}]`, knownIds, errors, warnings);
1563
+ }
1564
+ }
1565
+ }
1566
+ }
1567
+ const cappedErrors = errors.slice(0, maxErrors);
1568
+ const report = {
1569
+ ok: errors.length === 0,
1570
+ errors: cappedErrors,
1571
+ warnings: warnings.slice(0, 100),
1572
+ stats: {
1573
+ mainRows: mainRows.length,
1574
+ mainFieldsFilled,
1575
+ subTableCount: subTables.length,
1576
+ subRows,
1577
+ errorCount: errors.length,
1578
+ warningCount: warnings.length
1579
+ }
1580
+ };
1581
+ return report;
1582
+ }
1583
+ }
1584
+ var resultValidate = {
1585
+ name: "smart-extract.result.validate",
1586
+ risk: "read",
1587
+ summary: "\u6309\u8868\u5355\u7ED3\u6784\u6821\u9A8C\u62BD\u53D6\u7ED3\u679C\uFF1A\u5B57\u6BB5 ID \u662F\u5426\u5B58\u5728\u3001\u9009\u9879\u503C\u662F\u5426\u5408\u6CD5\u3001\u5355\u503C\u5B57\u6BB5\u662F\u5426\u591A\u503C\u3001\u65E5\u671F/\u6570\u5B57\u683C\u5F0F\u3001\u660E\u7EC6\u4E09\u6570\u7EC4\u957F\u5EA6\u662F\u5426\u5BF9\u9F50\u3001origin \u683C\u5F0F\u3002\u8FD4\u56DE errors/warnings\uFF0Cok=true \u624D\u5141\u8BB8\u4FDD\u5B58\u3002fill.save \u5DF2\u5185\u7F6E\u540C\u4E00\u5957\u6821\u9A8C\uFF0C\u5355\u72EC\u8C03\u8BD5\u65F6\u7528\u672C\u547D\u4EE4\u3002",
1588
+ inputSchema: schemaOf({
1589
+ result: { type: "object", description: "\u62BD\u53D6\u7ED3\u679C\uFF08\u5185\u8054\uFF09" },
1590
+ resultPath: { type: "string", description: "\u62BD\u53D6\u7ED3\u679C JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E result \u4E8C\u9009\u4E00\uFF09" },
1591
+ structure: { type: "object", description: "smart-extract.form.structure \u7684 data\uFF08\u5185\u8054\uFF09" },
1592
+ structurePath: { type: "string", description: "\u8868\u5355\u7ED3\u6784 JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E structure \u4E8C\u9009\u4E00\uFF09" },
1593
+ attachmentIds: {
1594
+ oneOf: [
1595
+ { type: "string" },
1596
+ { type: "array", items: { type: "string" } }
1597
+ ],
1598
+ description: "\u672C\u6B21\u9644\u4EF6 ID\uFF1B\u7528\u4E8E\u6821\u9A8C origin \u91CC\u7684\u6765\u6E90 ID"
1599
+ },
1600
+ strict: { type: "boolean", description: "\u9009\u9879\u503C\u4E0D\u5B58\u5728\u65F6\u662F\u5426\u7B97\u9519\u8BEF\uFF08\u9ED8\u8BA4 true\uFF1Bfalse \u964D\u7EA7\u4E3A\u8B66\u544A\uFF09" },
1601
+ maxErrors: { type: "integer", description: "\u6700\u591A\u8FD4\u56DE\u591A\u5C11\u6761\u9519\u8BEF\uFF0C\u9ED8\u8BA4 50" }
1602
+ }, { required: ["structure"] }),
1603
+ handler: async (args) => {
1604
+ const result = await readObjectInput(args, "result", "resultPath", { required: true });
1605
+ const structureRaw = await readObjectInput(args, "structure", "structurePath", { required: true });
1606
+ if (!result || !structureRaw) {
1607
+ throw smartExtractValidationError("result_required", "\u5FC5\u987B\u63D0\u4F9B result \u4E0E structure");
1608
+ }
1609
+ const rawIds = args.attachmentIds;
1610
+ const knownAttachmentIds = typeof rawIds === "string" || Array.isArray(rawIds) ? (Array.isArray(rawIds) ? rawIds : String(rawIds).split(",")).map((item) => String(item ?? "").trim()).filter(Boolean) : [];
1611
+ const report = validateExtraction(result, structureRaw, {
1612
+ knownAttachmentIds,
1613
+ strict: args.strict !== false,
1614
+ maxErrors: args.maxErrors
1615
+ });
1616
+ const nextSteps = [];
1617
+ if (!report.ok) {
1618
+ nextSteps.push("\u6309 errors \u9010\u6761\u4FEE\u6B63 result \u540E\u91CD\u65B0\u6821\u9A8C\uFF1B\u4E0D\u8981\u76F4\u63A5\u4FDD\u5B58\u5E26\u9519\u8BEF\u7684\u7ED3\u679C");
1619
+ } else {
1620
+ nextSteps.push("\u6821\u9A8C\u901A\u8FC7 \u2192 \u8C03 smart-extract.fill.save \u76F4\u63A5\u843D\u5E93\u5E76\u62FF aiExtraId");
1621
+ }
1622
+ if (report.warnings.length > 0) {
1623
+ nextSteps.push("warnings \u4E0D\u963B\u585E\u4FDD\u5B58\uFF0C\u4F46\u56DE\u7ED9\u7528\u6237\u65F6\u8981\u63D0\u4E00\u53E5\uFF08\u5C24\u5176\u662F origin \u6765\u6E90\u7F3A\u5931\uFF09");
1624
+ }
1625
+ return smartExtractSuccess(
1626
+ "smart-extract.result.validate",
1627
+ { ...report, next: nextSteps },
1628
+ {
1629
+ meta: { ok: report.ok },
1630
+ warnings: report.ok ? [] : [`\u5B58\u5728 ${report.stats.errorCount} \u4E2A\u9519\u8BEF\uFF0C\u7981\u6B62\u76F4\u63A5\u4FDD\u5B58`]
1631
+ }
1632
+ );
1633
+ }
1634
+ };
1635
+ var validateOperations = [resultValidate];
1636
+
1637
+ // src/shortcuts/smart-extract/operations/save.ts
1638
+ import { randomBytes as randomBytes2 } from "node:crypto";
1639
+ import { mkdir as mkdir4, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
1640
+ import { dirname } from "node:path";
1641
+
1642
+ // src/shortcuts/smart-extract/ledger.ts
1643
+ import { mkdir as mkdir3, readFile as readFile3, rename, writeFile as writeFile3 } from "node:fs/promises";
1644
+ import { join as join3 } from "node:path";
1645
+ var MAX_ENTRIES = 300;
1646
+ var LEDGER_FILE = "saved-ledger.json";
1647
+ function ledgerPath(stateDir) {
1648
+ return join3(stateDir, LEDGER_FILE);
1649
+ }
1650
+ async function readLedger(stateDir) {
1651
+ try {
1652
+ const raw = await readFile3(ledgerPath(stateDir), "utf8");
1653
+ const parsed = JSON.parse(raw);
1654
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
1655
+ const ledger = parsed;
1656
+ for (const entry of Object.values(ledger)) {
1657
+ if (!entry.aiExtraId && typeof entry.batchId === "string") {
1658
+ entry.aiExtraId = entry.batchId;
1659
+ }
1660
+ delete entry.batchId;
1661
+ }
1662
+ return ledger;
1663
+ } catch {
1664
+ return {};
1665
+ }
1666
+ }
1667
+ async function findSavedByFingerprint(stateDir, fingerprint) {
1668
+ const ledger = await readLedger(stateDir);
1669
+ return ledger[fingerprint];
1670
+ }
1671
+ async function findSavedByTargetAttachment(stateDir, workflowId, nodeId, attachmentIds) {
1672
+ const ledger = await readLedger(stateDir);
1673
+ for (const entry of Object.values(ledger)) {
1674
+ if (entry.workflowId !== workflowId) continue;
1675
+ if ((entry.nodeId ?? "") !== (nodeId ?? "")) continue;
1676
+ if (!entry.attachmentIds) continue;
1677
+ if (entry.attachmentIds !== attachmentIds) continue;
1678
+ return entry;
1679
+ }
1680
+ return void 0;
1681
+ }
1682
+ async function rememberSaved(stateDir, fingerprint, entry) {
1683
+ const ledger = await readLedger(stateDir);
1684
+ ledger[fingerprint] = entry;
1685
+ const keys = Object.keys(ledger);
1686
+ if (keys.length > MAX_ENTRIES) {
1687
+ const kept = keys.sort((left, right) => String(ledger[right]?.savedAt ?? "").localeCompare(String(ledger[left]?.savedAt ?? ""))).slice(0, MAX_ENTRIES);
1688
+ for (const key of keys) {
1689
+ if (!kept.includes(key)) delete ledger[key];
1690
+ }
1691
+ }
1692
+ await mkdir3(stateDir, { recursive: true });
1693
+ const target = ledgerPath(stateDir);
1694
+ const temp = `${target}.${process.pid}.tmp`;
1695
+ await writeFile3(temp, JSON.stringify(ledger, null, 2), "utf8");
1696
+ await rename(temp, target);
1697
+ }
1698
+
1699
+ // src/shortcuts/smart-extract/operations/save.ts
1700
+ function autoRequestId() {
1701
+ return `se${randomBytes2(15).toString("hex")}`;
1702
+ }
1703
+ function mapDataSource(value) {
1704
+ const text = optionalString(value, "dataSource");
1705
+ if (!text) return DATA_SOURCE["wf-manual"];
1706
+ if (text in DATA_SOURCE) return DATA_SOURCE[text];
1707
+ if (["0", "1", "2"].includes(text)) return text;
1708
+ throw smartExtractValidationError("data_source_invalid", "dataSource \u53EA\u80FD\u662F wf-pre / wf-manual / eb-manual \u6216 0/1/2");
1709
+ }
1710
+ function requireSuccessResult(result) {
1711
+ if (result.isSuccess === false) {
1712
+ throw smartExtractValidationError(
1713
+ "result_not_success",
1714
+ `\u62BD\u53D6\u7ED3\u679C\u6807\u8BB0\u4E3A\u5931\u8D25\uFF0C\u4E0D\u80FD\u4FDD\u5B58\uFF1A${String(result.errorMsg ?? "\u672A\u7ED9 errorMsg")}`
1715
+ );
1716
+ }
1717
+ if (result.isSuccess !== true) {
1718
+ throw smartExtractValidationError("is_success_missing", "\u62BD\u53D6\u7ED3\u679C\u7F3A\u5C11 isSuccess=true\uFF0C\u7981\u6B62\u4FDD\u5B58");
1719
+ }
1720
+ }
1721
+ var savePrepare = {
1722
+ name: "smart-extract.save.prepare",
1723
+ risk: "read-before-write",
1724
+ summary: "\u7EC4\u88C5\u843D\u5E93\u8BF7\u6C42\u5E76\u7B7E\u53D1\u786E\u8BA4\u7968\u636E\uFF1A\u5148\u6309\u5185\u5BB9\u6307\u7EB9\u4E0E\u9644\u4EF6\u952E\u67E5\u672C\u5730\u53F0\u8D26\uFF08\u547D\u4E2D\u8FD4\u56DE duplicate \u4E0E\u5DF2\u6709 aiExtraId\uFF0C\u4E0D\u7B7E\u7968\u636E\uFF09\uFF0C\u518D\u81EA\u52A8\u751F\u6210 requestId\uFF08\u9632\u300C\u5199\u7ED3\u679C\u672A\u77E5\u540E\u91CD\u8BD5\u300D\u53CC\u63D2\uFF09\u3002\u672C\u8EAB\u4E0D\u53D1\u5199\u8BF7\u6C42\u3002",
1725
+ inputSchema: schemaOf({
1726
+ workflowId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u6A21\u677F ID\uFF08\u5FC5\u586B\uFF0C\u670D\u52A1\u7AEF\u8981\u6C42\uFF09" },
1727
+ nodeId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u8282\u70B9 ID" },
1728
+ objFormId: { ...SCHEMA_ID, description: "EB \u8868\u5355 ID\uFF08\u4EC5\u8BB0\u5F55\u7528\uFF0CEB \u6A21\u5F0F\u4E0D\u652F\u6301\u672C\u63A5\u53E3\u843D\u5E93\uFF09" },
1729
+ layoutId: { ...SCHEMA_ID, description: "EB \u5E03\u5C40 ID\uFF08\u4EC5\u8BB0\u5F55\u7528\uFF09" },
1730
+ listId: { ...SCHEMA_ID, description: "EB \u5217\u8868 ID\uFF08\u4EC5\u8BB0\u5F55\u7528\uFF09" },
1731
+ formModeType: { type: "string", enum: ["wf", "eb"], description: "\u9ED8\u8BA4 wf\uFF1Beb \u4F1A\u88AB\u62D2\u7EDD" },
1732
+ result: { type: "object", description: "\u5DF2\u901A\u8FC7 validate \u7684\u62BD\u53D6\u7ED3\u679C\uFF08\u5185\u8054\uFF09" },
1733
+ resultPath: { type: "string", description: "\u62BD\u53D6\u7ED3\u679C JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E result \u4E8C\u9009\u4E00\uFF09" },
1734
+ structure: { type: "object", description: "\u8868\u5355\u7ED3\u6784\u5FEB\u7167\uFF08\u53EF\u9009\uFF0C\u7559\u7A7A\u7531\u670D\u52A1\u7AEF\u6309 workflowId \u91CD\u65B0\u8BA1\u7B97\uFF09" },
1735
+ structurePath: { type: "string", description: "\u8868\u5355\u7ED3\u6784 JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u53EF\u9009\uFF09" },
1736
+ attachmentIds: {
1737
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }],
1738
+ description: "\u672C\u6B21\u9644\u4EF6 ID\uFF08\u9017\u53F7\u5206\u9694\u6216\u6570\u7EC4\uFF09\uFF1B\u670D\u52A1\u7AEF\u4F1A\u636E\u6B64\u751F\u6210\u9644\u4EF6\u5143\u6570\u636E"
1739
+ },
1740
+ userInput: { type: "string", description: "\u7528\u6237\u539F\u59CB\u8F93\u5165\uFF08\u65E0\u9644\u4EF6\u65F6\u7684\u552F\u4E00\u6765\u6E90\uFF0C\u4E5F\u7528\u4E8E\u8FFD\u6EAF\uFF09" },
1741
+ requestId: { type: "string", description: "\u53EF\u9009\uFF1A\u81EA\u5B9A\u4E49\u8BF7\u6C42 ID\uFF08\u226432 \u5B57\u7B26\uFF09\u3002\u9ED8\u8BA4\u7531 CLI \u81EA\u52A8\u751F\u6210\u5E76\u7528\u4E8E\u670D\u52A1\u7AEF\u67E5\u91CD" },
1742
+ dataSource: { type: "string", description: "wf-pre / wf-manual / eb-manual\uFF0C\u9ED8\u8BA4 wf-manual" },
1743
+ sceneFlag: { type: "string", description: "\u573A\u666F\u6807\u8BC6" },
1744
+ agentId: { ...SCHEMA_ID, description: "\u667A\u80FD\u4F53 ID" },
1745
+ chatId: { type: "string", description: "\u4F1A\u8BDD ID" },
1746
+ messageId: { type: "string", description: "\u6D88\u606F ID" },
1747
+ forceNew: { type: "boolean", description: "\u8DF3\u8FC7\u67E5\u91CD\u5F3A\u5236\u65B0\u5EFA\uFF08\u4EC5\u5728\u7528\u6237\u660E\u786E\u8981\u6C42\u91CD\u5B58\u65F6\u4F7F\u7528\uFF09" }
1748
+ }, { required: ["workflowId"] }),
1749
+ handler: async (args, env) => {
1750
+ const workflowId = requiredId(args.workflowId, "workflowId");
1751
+ const nodeId = optionalId(args.nodeId, "nodeId");
1752
+ const formModeType = optionalString(args.formModeType, "formModeType") || "wf";
1753
+ if (formModeType === "eb") {
1754
+ throw smartExtractBusinessError(
1755
+ "eb_save_unsupported",
1756
+ "saveRecognizeRecord \u53EA\u652F\u6301\u6D41\u7A0B(wf)\u6279\u6B21\uFF1BEB \u6A21\u5F0F\u7684\u6279\u6B21\u4FDD\u5B58\u6CA1\u6709\u5BF9\u5916 HTTP \u63A5\u53E3\uFF0C\u8BF7\u5728\u524D\u7AEF/\u5EFA\u6A21\u6570\u636E\u63A5\u53E3\u4FA7\u843D\u5E93",
1757
+ { details: { formModeType } }
1758
+ );
1759
+ }
1760
+ if (formModeType !== "wf") {
1761
+ throw smartExtractValidationError("form_mode_invalid", "formModeType \u53EA\u80FD\u662F wf \u6216 eb");
1762
+ }
1763
+ const result = await readObjectInput(args, "result", "resultPath", { required: true });
1764
+ if (!result) throw smartExtractValidationError("result_required", "\u5FC5\u987B\u63D0\u4F9B result \u6216 resultPath");
1765
+ requireSuccessResult(result);
1766
+ const structure = await readObjectInput(args, "structure", "structurePath");
1767
+ const forceNew = args.forceNew === true;
1768
+ const attachmentIds = Array.isArray(args.attachmentIds) ? args.attachmentIds.map((item) => String(item).trim()).filter(Boolean).join(",") : optionalString(args.attachmentIds, "attachmentIds");
1769
+ const fingerprint = sha256(`${workflowId}|${nodeId ?? ""}|${stableStringify(result)}`);
1770
+ const customRequestId = optionalString(args.requestId, "requestId");
1771
+ if (customRequestId && customRequestId.length > MAX_REQUEST_ID_LENGTH) {
1772
+ throw smartExtractValidationError(
1773
+ "request_id_too_long",
1774
+ `requestId \u6700\u591A ${MAX_REQUEST_ID_LENGTH} \u4E2A\u5B57\u7B26\uFF08\u670D\u52A1\u7AEF request_id \u5217\u653E\u4E0D\u4E0B\uFF0C\u4F1A\u76F4\u63A5 500\uFF09`,
1775
+ { expected: MAX_REQUEST_ID_LENGTH, actual: customRequestId.length }
1776
+ );
1777
+ }
1778
+ const requestId = customRequestId ?? autoRequestId();
1779
+ if (!forceNew) {
1780
+ const saved = await findSavedByFingerprint(env.stateDir, fingerprint);
1781
+ if (saved) {
1782
+ return smartExtractSuccess("smart-extract.save.prepare", {
1783
+ duplicate: true,
1784
+ applied: false,
1785
+ aiExtraId: saved.aiExtraId,
1786
+ savedAt: saved.savedAt,
1787
+ fingerprint,
1788
+ requestId: saved.requestId ?? requestId,
1789
+ message: "\u540C\u4E00\u76EE\u6807 + \u540C\u4E00\u4EFD\u62BD\u53D6\u7ED3\u679C\u5DF2\u5728\u672C\u5730\u53F0\u8D26\u8BB0\u5F55\u4E3A\u5DF2\u4FDD\u5B58\uFF0C\u4E0D\u518D\u91CD\u590D\u843D\u5E93"
1790
+ }, { meta: { state: "ALREADY_SAVED" } });
1791
+ }
1792
+ if (attachmentIds) {
1793
+ const byAttachment = await findSavedByTargetAttachment(env.stateDir, workflowId, nodeId, attachmentIds);
1794
+ if (byAttachment) {
1795
+ return smartExtractSuccess("smart-extract.save.prepare", {
1796
+ duplicate: true,
1797
+ applied: false,
1798
+ aiExtraId: byAttachment.aiExtraId,
1799
+ savedAt: byAttachment.savedAt,
1800
+ fingerprint,
1801
+ requestId: byAttachment.requestId ?? requestId,
1802
+ alreadySavedForAttachment: true,
1803
+ message: "\u540C\u4E00\u6D41\u7A0B\u540C\u4E00\u9644\u4EF6\u5DF2\u4FDD\u5B58\u8FC7\u62BD\u53D6\u8BB0\u5F55\uFF08\u672C\u6B21\u62BD\u53D6\u5185\u5BB9\u4E0E\u4E0A\u6B21\u7565\u6709\u5DEE\u5F02\uFF0C\u89C6\u4E3A\u540C\u4E00\u6B21\u4E1A\u52A1\u4FDD\u5B58\uFF09\u3002\u786E\u9700\u91CD\u5B58\u8BF7\u5E26 forceNew:true"
1804
+ }, { meta: { state: "ALREADY_SAVED" } });
1805
+ }
1806
+ }
1807
+ const existingId = await queryByRequestId(env, requestId);
1808
+ if (existingId) {
1809
+ await rememberSaved(env.stateDir, fingerprint, {
1810
+ aiExtraId: existingId,
1811
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1812
+ workflowId,
1813
+ nodeId,
1814
+ requestId,
1815
+ ...attachmentIds ? { attachmentIds } : {}
1816
+ });
1817
+ return smartExtractSuccess("smart-extract.save.prepare", {
1818
+ duplicate: true,
1819
+ applied: false,
1820
+ aiExtraId: existingId,
1821
+ fingerprint,
1822
+ requestId,
1823
+ message: "\u670D\u52A1\u7AEF\u5DF2\u5B58\u5728\u540C\u4E00 requestId \u7684\u8BB0\u5F55\uFF0C\u89C6\u4E3A\u5DF2\u4FDD\u5B58"
1824
+ }, { meta: { state: "ALREADY_SAVED" } });
1825
+ }
1826
+ }
1827
+ const payload = {
1828
+ workflowId,
1829
+ ...nodeId ? { nodeId } : {},
1830
+ formModeType: "wf",
1831
+ ...requestId ? { requestId } : {},
1832
+ recognizeResult: JSON.stringify(result),
1833
+ dataSource: mapDataSource(args.dataSource),
1834
+ fillStatus: "0",
1835
+ ...optionalId(args.objFormId, "objFormId") ? { objFormId: optionalId(args.objFormId, "objFormId") } : {},
1836
+ ...optionalId(args.layoutId, "layoutId") ? { layoutId: optionalId(args.layoutId, "layoutId") } : {},
1837
+ ...optionalId(args.listId, "listId") ? { listId: optionalId(args.listId, "listId") } : {},
1838
+ ...attachmentIds ? { attachmentIds } : {},
1839
+ ...optionalString(args.userInput, "userInput") ? { userInput: optionalString(args.userInput, "userInput") } : {},
1840
+ ...optionalString(args.sceneFlag, "sceneFlag") ? { sceneFlag: optionalString(args.sceneFlag, "sceneFlag") } : {},
1841
+ ...optionalId(args.agentId, "agentId") ? { agentId: optionalId(args.agentId, "agentId") } : {},
1842
+ ...optionalString(args.chatId, "chatId") ? { chatId: optionalString(args.chatId, "chatId") } : {},
1843
+ ...optionalString(args.messageId, "messageId") ? { messageId: optionalString(args.messageId, "messageId") } : {}
1844
+ };
1845
+ const session = await env.host.getSession();
1846
+ const continuation = await env.continuation.issue({
1847
+ operation: "smart-extract.save.apply",
1848
+ actor: { userId: session.userId, baseUrl: session.baseUrl, profile: session.profile },
1849
+ workflowId,
1850
+ nodeId: nodeId ?? null,
1851
+ fingerprint,
1852
+ requestId,
1853
+ payload
1854
+ });
1855
+ const mainRows = result.mainTable && Array.isArray(result.mainTable.rows) ? result.mainTable.rows.length : 0;
1856
+ const subRows = Array.isArray(result.subTables) ? result.subTables.reduce((total, table) => total + (Array.isArray(table?.rows) ? table.rows.length : 0), 0) : 0;
1857
+ const ticketFile = ticketPath(env.stateDir, requestId);
1858
+ await mkdir4(dirname(ticketFile), { recursive: true, mode: 448 });
1859
+ await writeFile4(ticketFile, continuation, { encoding: "utf8", mode: 384 });
1860
+ return smartExtractSuccess("smart-extract.save.prepare", {
1861
+ duplicate: false,
1862
+ applied: false,
1863
+ requestId: requestId ?? null,
1864
+ fingerprint,
1865
+ ticketFile,
1866
+ // 只有短票据才把明文放进来;长票据一律走 ticketFile,避免调用方拿到半截字符串
1867
+ ...continuation.length <= MAX_INLINE_TICKET_CHARS ? { continuation } : {},
1868
+ expiresInSeconds: CONTINUATION_TTL_SECONDS,
1869
+ requestPreview: {
1870
+ workflowId,
1871
+ nodeId: nodeId ?? null,
1872
+ formModeType: "wf",
1873
+ requestId,
1874
+ dataSource: payload.dataSource,
1875
+ attachmentIds: attachmentIds ?? null,
1876
+ mainRows,
1877
+ subRows,
1878
+ recognizeResultBytes: String(payload.recognizeResult).length
1879
+ },
1880
+ next: `\u628A requestPreview \u4E0E\u9884\u89C8\u4E00\u8D77\u7ED9\u7528\u6237\u786E\u8BA4\uFF1B\u7528\u6237\u660E\u786E\u540C\u610F\u540E\u8C03 smart-extract.save.apply\uFF08confirm=true, ticketFile=${ticketFile}\uFF09\u3002\u7968\u636E\u5DF2\u843D\u76D8\uFF0C\u4E0D\u8981\u56DE\u4F20 stdout \u91CC\u7684\u7968\u636E\u660E\u6587\uFF08\u53EF\u80FD\u88AB\u622A\u65AD\uFF09`
1881
+ }, { meta: { state: "PREPARED" } });
1882
+ }
1883
+ };
1884
+ async function queryByRequestId(env, requestId) {
1885
+ try {
1886
+ const data = await env.host.requestData({
1887
+ operation: "smart-extract.save.prepare",
1888
+ method: "GET",
1889
+ path: PATHS.queryBatchInfo,
1890
+ query: { requestId }
1891
+ });
1892
+ const list = Array.isArray(data) ? data : [];
1893
+ const first = record(list[0]);
1894
+ const id = first.id ?? first.aiExtraId ?? first.batchId;
1895
+ return id === void 0 || id === null ? void 0 : String(id);
1896
+ } catch {
1897
+ return void 0;
1898
+ }
1899
+ }
1900
+ async function resolveContinuation(args, stateDir) {
1901
+ const file = optionalString(args.ticketFile, "ticketFile");
1902
+ if (file) {
1903
+ try {
1904
+ return (await readFile4(file, "utf8")).trim();
1905
+ } catch (error) {
1906
+ throw smartExtractValidationError(
1907
+ "ticket_unreadable",
1908
+ `\u65E0\u6CD5\u8BFB\u53D6\u7968\u636E\u6587\u4EF6\uFF1A${file}`,
1909
+ { details: { reason: error instanceof Error ? error.message : String(error) } }
1910
+ );
1911
+ }
1912
+ }
1913
+ const inline = String(args.continuation ?? "").trim();
1914
+ if (!inline) {
1915
+ throw smartExtractValidationError(
1916
+ "continuation_required",
1917
+ `\u5FC5\u987B\u63D0\u4F9B ticketFile\uFF08\u63A8\u8350\uFF09\u6216 continuation\uFF1Bprepare \u4F1A\u628A\u7968\u636E\u5199\u5230 ${stateDir}/tickets/ \u4E0B`
1918
+ );
1919
+ }
1920
+ if (inline.includes("\u2026")) {
1921
+ throw smartExtractValidationError(
1922
+ "continuation_truncated",
1923
+ "continuation \u88AB CLI \u8F93\u51FA\u5C42\u622A\u65AD\uFF08\u542B\u7701\u7565\u53F7\uFF09\uFF0C\u65E0\u6CD5\u7528\u4E8E\u7B7E\u540D\u6821\u9A8C\uFF1B\u8BF7\u6539\u7528 save.prepare \u8FD4\u56DE\u7684 ticketFile"
1924
+ );
1925
+ }
1926
+ return inline;
1927
+ }
1928
+ var saveApply = {
1929
+ name: "smart-extract.save.apply",
1930
+ risk: "high-risk-write",
1931
+ summary: "\u786E\u8BA4\u540E\u771F\u6B63\u5199\u5165\u6279\u6B21\u8BB0\u5F55\uFF1A\u5FC5\u987B confirm=true \u4E14\u5E26 prepare \u8FD4\u56DE\u7684 ticketFile\u3002\u53D1\u5199\u8BF7\u6C42\u524D\u5148\u6309 requestId/\u5185\u5BB9\u6307\u7EB9/\u9644\u4EF6\u952E\u4E09\u5C42\u67E5\u91CD\uFF0C\u91CD\u590D\u4E00\u5F8B\u8FD4\u56DE\u5DF2\u6709 aiExtraId\uFF0C\u4E0D\u518D\u5165\u5E93\u3002",
1932
+ inputSchema: schemaOf({
1933
+ confirm: { type: "boolean", description: "\u5FC5\u987B\u4E3A true\uFF1B\u8868\u793A\u7528\u6237\u5DF2\u660E\u786E\u786E\u8BA4\u4FDD\u5B58" },
1934
+ ticketFile: { type: "string", description: "save.prepare \u8FD4\u56DE\u7684 ticketFile \u8DEF\u5F84\uFF08\u9996\u9009\uFF0C\u7968\u636E\u5B8C\u6574\uFF09" },
1935
+ continuation: { type: "string", description: "save.prepare \u8FD4\u56DE\u7684\u7968\u636E\u660E\u6587\uFF08\u4EC5\u77ED\u7968\u636E\u4F1A\u8FD4\u56DE\uFF1B\u957F\u7968\u636E\u88AB\u8F93\u51FA\u5C42\u622A\u65AD\uFF0C\u5FC5\u987B\u7528 ticketFile\uFF09" }
1936
+ }, { required: ["confirm"] }),
1937
+ handler: async (args, env) => {
1938
+ if (args.confirm !== true) {
1939
+ throw smartExtractConfirmationError("smart-extract.save.apply", {
1940
+ hint: "\u5148\u5411\u7528\u6237\u5C55\u793A\u9884\u89C8\u5E76\u53D6\u5F97\u660E\u786E\u540C\u610F\uFF0C\u518D\u628A confirm \u8BBE\u4E3A true"
1941
+ });
1942
+ }
1943
+ const continuation = await resolveContinuation(args, env.stateDir);
1944
+ const recordValue = await env.continuation.verify(continuation, "smart-extract.save.apply");
1945
+ const session = await env.host.getSession();
1946
+ const actor = record(recordValue.actor);
1947
+ if (actor.userId !== session.userId || actor.baseUrl !== session.baseUrl) {
1948
+ throw smartExtractValidationError(
1949
+ "continuation_actor_changed",
1950
+ "continuation \u7B7E\u53D1\u65F6\u7684\u767B\u5F55\u7528\u6237/\u73AF\u5883\u4E0E\u5F53\u524D\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u91CD\u65B0 prepare"
1951
+ );
1952
+ }
1953
+ const fingerprint = String(recordValue.fingerprint ?? "");
1954
+ if (!fingerprint) {
1955
+ throw smartExtractValidationError("continuation_invalid", "continuation \u7F3A\u5C11\u5185\u5BB9\u6307\u7EB9");
1956
+ }
1957
+ const payload = record(recordValue.payload);
1958
+ const requestId = recordValue.requestId === void 0 || recordValue.requestId === null ? void 0 : String(recordValue.requestId);
1959
+ const saved = await findSavedByFingerprint(env.stateDir, fingerprint);
1960
+ if (saved) {
1961
+ return smartExtractSuccess("smart-extract.save.apply", {
1962
+ duplicate: true,
1963
+ aiExtraId: saved.aiExtraId,
1964
+ savedAt: saved.savedAt,
1965
+ message: "\u672C\u5730\u53F0\u8D26\u663E\u793A\u8BE5\u7ED3\u679C\u5DF2\u4FDD\u5B58\uFF0C\u672A\u518D\u53D1\u5199\u8BF7\u6C42"
1966
+ }, { meta: { state: "ALREADY_SAVED" } });
1967
+ }
1968
+ if (requestId) {
1969
+ const existingId = await queryByRequestId(env, requestId);
1970
+ if (existingId) {
1971
+ await rememberSaved(env.stateDir, fingerprint, {
1972
+ aiExtraId: existingId,
1973
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1974
+ workflowId: String(recordValue.workflowId ?? payload.workflowId ?? ""),
1975
+ nodeId: recordValue.nodeId === null || recordValue.nodeId === void 0 ? void 0 : String(recordValue.nodeId),
1976
+ requestId,
1977
+ ...payload.attachmentIds ? { attachmentIds: String(payload.attachmentIds) } : {}
1978
+ });
1979
+ return smartExtractSuccess("smart-extract.save.apply", {
1980
+ duplicate: true,
1981
+ aiExtraId: existingId,
1982
+ requestId,
1983
+ message: "\u670D\u52A1\u7AEF\u5DF2\u5B58\u5728\u540C\u4E00 requestId \u7684\u8BB0\u5F55\uFF08\u4E0A\u6B21\u5199\u5E93\u5B9E\u9645\u5DF2\u6210\u529F\uFF09\uFF0C\u672A\u91CD\u590D\u5165\u5E93"
1984
+ }, { meta: { state: "ALREADY_SAVED" } });
1985
+ }
1986
+ }
1987
+ let data;
1988
+ try {
1989
+ data = await env.host.requestData({
1990
+ operation: "smart-extract.save.apply",
1991
+ method: "POST",
1992
+ path: PATHS.saveRecognizeRecord,
1993
+ body: payload
1994
+ });
1995
+ } catch (error) {
1996
+ if (error instanceof SmartExtractCliError && error.type === "network") {
1997
+ throw smartExtractPartialError(
1998
+ "\u4FDD\u5B58\u8BF7\u6C42\u7ED3\u679C\u672A\u77E5\uFF08\u7F51\u7EDC\u4E2D\u65AD/\u8D85\u65F6\uFF09\u3002\u7981\u6B62\u76F4\u63A5\u91CD\u8BD5\u672C\u547D\u4EE4\uFF1A\u91CD\u8BD5\u662F\u5B89\u5168\u7684\uFF08requestId \u67E5\u91CD\u4F1A\u515C\u5E95\uFF09\uFF0C\u4F46\u5E94\u5148\u8C03 smart-extract.batch.get \u6216\u91CD\u65B0 apply \u786E\u8BA4",
1999
+ { requestId, hint: "\u91CD\u65B0\u6267\u884C apply \u4F1A\u5148\u7528 requestId \u67E5\u670D\u52A1\u7AEF\uFF0C\u547D\u4E2D\u5219\u8FD4\u56DE\u5DF2\u6709 aiExtraId \u800C\u4E0D\u4F1A\u91CD\u590D\u5165\u5E93" }
2000
+ );
2001
+ }
2002
+ throw error;
2003
+ }
2004
+ const result = record(data);
2005
+ const savedId = result.id ?? result.aiExtraId ?? result.batchId;
2006
+ if (savedId === void 0 || savedId === null) {
2007
+ throw smartExtractBusinessError("save_response_invalid", "\u4FDD\u5B58\u63A5\u53E3\u672A\u8FD4\u56DE aiExtraId", {
2008
+ details: { result: data }
2009
+ });
2010
+ }
2011
+ const aiExtraId = String(savedId);
2012
+ await rememberSaved(env.stateDir, fingerprint, {
2013
+ aiExtraId,
2014
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
2015
+ workflowId: String(recordValue.workflowId ?? payload.workflowId ?? ""),
2016
+ nodeId: recordValue.nodeId === null || recordValue.nodeId === void 0 ? void 0 : String(recordValue.nodeId),
2017
+ requestId,
2018
+ ...payload.attachmentIds ? { attachmentIds: String(payload.attachmentIds) } : {}
2019
+ });
2020
+ return smartExtractSuccess("smart-extract.save.apply", {
2021
+ duplicate: false,
2022
+ aiExtraId,
2023
+ requestId: requestId ?? null,
2024
+ verifyHint: `\u5DF2\u4FDD\u5B58\u3002\u53EF\u7528 smart-extract.batch.get --input-json '{"id":"${aiExtraId}"}' \u56DE\u67E5\uFF1B\u524D\u7AEF\u7EC4\u4EF6\u7528 getBatchInfoById \u8BFB\u540C\u4E00\u6761`
2025
+ }, { meta: { state: "COMPLETE" } });
2026
+ }
2027
+ };
2028
+ var saveOperations = [savePrepare, saveApply];
2029
+
2030
+ // src/shortcuts/smart-extract/operations/fill.ts
2031
+ var RESULT_CONTRACT = '{"isSuccess":true,"mainTable":{"rows":[{"mainDataId":1,"fieldResults":[{"fieldInfo":"\u5B57\u6BB5ID#\u5B57\u6BB5\u540D\u79F0","value":"\u503C","reason":"\u4F9D\u636E","origin":["\u9644\u4EF6ID#\u539F\u6587\u7247\u6BB5"]}]}]},"subTables":[{"subFormId":"\u660E\u7EC6\u8868ID","fields":["\u5B57\u6BB5ID#\u5B57\u6BB5\u540D\u79F0"],"rows":[{"subDataId":1,"mainDataId":1,"values":["\u503C"],"reasons":["\u4F9D\u636E"],"origins":[["\u9644\u4EF6ID#\u539F\u6587\u7247\u6BB5"]]}]}]}';
2032
+ function shortId(prefix) {
2033
+ return `${prefix}${randomBytes3(12).toString("hex")}`;
2034
+ }
2035
+ var INLINE_BUDGET_RATIO = 0.95;
2036
+ var ENVELOPE_RESERVE_BYTES = 400;
2037
+ var MIN_INLINE_BYTES_PER_ATTACHMENT = 2400;
2038
+ function fillNextHint(sessionFile) {
2039
+ return `\u6309 fields \u62BD\u53D6\uFF0Corigin \u7528\u300C\u9644\u4EF6ID#\u539F\u6587\u7247\u6BB5\u300D\uFF0C\u53EA\u586B\u6709\u503C\u7684\u5B57\u6BB5\u3002\u6B63\u6587\uFF1A\u6709 text \u7684\u76F4\u63A5\u7528\uFF1B\u53EA\u6709 textFile \u7684\u7528 read_file \u8BFB\u4E00\u6B21\uFF08\u5168\u6587\u5728\u91CC\u9762\uFF09\uFF1BPDF/\u56FE\u7247/Excel \u8BFB path\u3002\u4E0D\u8981\u7528 --input-ref / --pick-as\uFF0C\u4E0D\u8981\u91CD\u65B0\u4E0B\u8F7D\u9644\u4EF6\uFF0C\u4E0D\u8981\u81EA\u5DF1\u89E3\u6790 docx\u3002\u62BD\u5B8C\u8C03 smart-extract.fill.save --input-json '{"sessionFile":"${sessionFile}","result":{...}}'\uFF0C\u62FF\u5230 aiExtraId \u5373\u7ED3\u675F\u3002`;
2040
+ }
2041
+ async function fetchRules(host, workflowId, nodeId) {
2042
+ const query = async (withEnabled) => {
2043
+ const page = record(await host.requestData({
2044
+ operation: "smart-extract.fill",
2045
+ method: "POST",
2046
+ path: PATHS.configList,
2047
+ body: {
2048
+ current: 1,
2049
+ pageSize: 50,
2050
+ modeType: "wf",
2051
+ sourceId: workflowId,
2052
+ wfNodeId: nodeId,
2053
+ ...withEnabled ? { enabled: 1 } : {}
2054
+ }
2055
+ }));
2056
+ return (Array.isArray(page.records) ? page.records : []).map((item) => record(item));
2057
+ };
2058
+ const warnings = [];
2059
+ let configs = await query(true);
2060
+ if (configs.length === 0) configs = await query(false);
2061
+ if (configs.length === 0) {
2062
+ warnings.push("\u8BE5\u6D41\u7A0B\u6CA1\u6709\u914D\u7F6E\u8BC6\u522B\u89C4\u5219\uFF1B\u6309\u5B57\u6BB5\u540D/\u7C7B\u578B\u81EA\u884C\u5224\u65AD\u5373\u53EF");
2063
+ }
2064
+ if (configs.length > 1) {
2065
+ warnings.push(`\u547D\u4E2D ${configs.length} \u6761\u914D\u7F6E\uFF0C\u5DF2\u5408\u5E76\u5176\u89C4\u5219\uFF08\u540C\u4E00\u5B57\u6BB5\u4EE5\u5148\u51FA\u73B0\u7684\u4E3A\u51C6\uFF09`);
2066
+ }
2067
+ const fieldRules = [];
2068
+ const parseFields = [];
2069
+ const seenField = /* @__PURE__ */ new Set();
2070
+ for (const config of configs) {
2071
+ for (const ruleRaw of Array.isArray(config.fieldRules) ? config.fieldRules : []) {
2072
+ const rule = record(ruleRaw);
2073
+ const fieldId = rule.fieldId === void 0 || rule.fieldId === null ? "" : String(rule.fieldId);
2074
+ const fieldName = String(record(rule.fieldInfo).fieldName ?? rule.fieldAlias ?? "");
2075
+ const key = fieldId || fieldName;
2076
+ const text = String(rule.fieldRule ?? "").trim();
2077
+ if (!key || !text || seenField.has(key)) continue;
2078
+ seenField.add(key);
2079
+ fieldRules.push(`${fieldName || fieldId}#${text}`);
2080
+ }
2081
+ for (const item of String(config.parseFields ?? "").split(/[,;,;]/u).map((part) => part.trim())) {
2082
+ if (item && !parseFields.includes(item)) parseFields.push(item);
2083
+ }
2084
+ }
2085
+ return {
2086
+ globalRule: configs.map((config) => String(config.globalRule ?? "").trim()).filter(Boolean).join("\n"),
2087
+ fieldRules,
2088
+ parseFields,
2089
+ warnings
2090
+ };
2091
+ }
2092
+ function unzipEntry(buffer, entryName) {
2093
+ let eocd = -1;
2094
+ for (let index = buffer.length - 22; index >= Math.max(0, buffer.length - 66e3); index -= 1) {
2095
+ if (buffer.readUInt32LE(index) === 101010256) {
2096
+ eocd = index;
2097
+ break;
2098
+ }
2099
+ }
2100
+ if (eocd < 0) return null;
2101
+ const total = buffer.readUInt16LE(eocd + 10);
2102
+ let offset = buffer.readUInt32LE(eocd + 16);
2103
+ for (let index = 0; index < total; index += 1) {
2104
+ if (offset + 46 > buffer.length || buffer.readUInt32LE(offset) !== 33639248) return null;
2105
+ const method = buffer.readUInt16LE(offset + 10);
2106
+ const compressedSize = buffer.readUInt32LE(offset + 20);
2107
+ const nameLength = buffer.readUInt16LE(offset + 28);
2108
+ const extraLength = buffer.readUInt16LE(offset + 30);
2109
+ const commentLength = buffer.readUInt16LE(offset + 32);
2110
+ const localOffset = buffer.readUInt32LE(offset + 42);
2111
+ const name = buffer.toString("utf8", offset + 46, offset + 46 + nameLength);
2112
+ if (name === entryName && localOffset + 30 <= buffer.length) {
2113
+ const localNameLength = buffer.readUInt16LE(localOffset + 26);
2114
+ const localExtraLength = buffer.readUInt16LE(localOffset + 28);
2115
+ const start = localOffset + 30 + localNameLength + localExtraLength;
2116
+ const data = buffer.subarray(start, start + compressedSize);
2117
+ return method === 0 ? Buffer.from(data) : inflateRawSync(data);
2118
+ }
2119
+ offset += 46 + nameLength + extraLength + commentLength;
2120
+ }
2121
+ return null;
2122
+ }
2123
+ function xmlToText(xml) {
2124
+ return xml.replace(/<w:tab[^>]*\/>/gu, " ").replace(/<w:br[^>]*\/>/gu, "\n").replace(/<\/w:p>/gu, "\n").replace(/<[^>]+>/gu, "").replace(/&lt;/gu, "<").replace(/&gt;/gu, ">").replace(/&quot;/gu, '"').replace(/&apos;/gu, "'").replace(/&amp;/gu, "&").replace(/[ \t]+\n/gu, "\n").replace(/\n{3,}/gu, "\n\n").trim();
2125
+ }
2126
+ function stripHtml(html) {
2127
+ return html.replace(/<script[\s\S]*?<\/script>/giu, "").replace(/<style[\s\S]*?<\/style>/giu, "").replace(/<[^>]+>/gu, "\n").replace(/&nbsp;/gu, " ").replace(/&amp;/gu, "&").replace(/\n{3,}/gu, "\n\n").trim();
2128
+ }
2129
+ function ruleToPlainText(rule) {
2130
+ return rule.replace(/<br\s*\/?>/giu, "\n").replace(/<\/(?:p|div|li|h[1-6])>/giu, "\n").replace(/<[^>]+>/gu, "").replace(/&nbsp;/gu, " ").replace(/&lt;/gu, "<").replace(/&gt;/gu, ">").replace(/&quot;/gu, '"').replace(/&amp;/gu, "&").replace(/[ \t]+\n/gu, "\n").replace(/\n{2,}/gu, "\n").trim();
2131
+ }
2132
+ async function extractText(item) {
2133
+ if (!item.downloaded || !item.path) return {};
2134
+ const ext = extname2(item.name ?? item.path).toLowerCase();
2135
+ try {
2136
+ if (ext === ".docx") {
2137
+ const buffer = await readFile5(item.path);
2138
+ const xml = unzipEntry(buffer, "word/document.xml")?.toString("utf8");
2139
+ if (!xml) return {};
2140
+ const text = xmlToText(xml);
2141
+ return text ? { text, chars: text.length } : {};
2142
+ }
2143
+ if ([".txt", ".md", ".csv", ".json", ".xml", ".html", ".htm"].includes(ext)) {
2144
+ const raw = await readFile5(item.path, "utf8");
2145
+ const text = ext === ".html" || ext === ".htm" ? stripHtml(raw) : raw.trim();
2146
+ return text ? { text, chars: text.length } : {};
2147
+ }
2148
+ } catch {
2149
+ return {};
2150
+ }
2151
+ return {};
2152
+ }
2153
+ var fill = {
2154
+ name: "smart-extract.fill",
2155
+ risk: "read",
2156
+ summary: "\u4E00\u6B21\u8C03\u7528\u53D6\u9F50\u62BD\u53D6\u6240\u9700\u7684\u5168\u90E8\u5165\u53C2\uFF1A\u6D41\u7A0B\u8282\u70B9\u8868\u5355\u7ED3\u6784\uFF08\u538B\u7F29\u4E32\uFF09\u3001\u8BC6\u522B\u89C4\u5219\u3001\u9644\u4EF6\u6B63\u6587\uFF08docx \u672C\u5730\u62BD\u6587\u672C\uFF09\u3002\u8FD4\u56DE\u7CBE\u7B80\u540E\u53EA\u542B\u6A21\u578B\u9700\u8981\u7684\u5185\u5BB9 + sessionFile\uFF1B\u6A21\u578B\u636E\u6B64\u76F4\u63A5\u62BD\u53D6\uFF0C\u518D\u8C03 smart-extract.fill.save \u4E00\u6B65\u843D\u5E93\u3002",
2157
+ inputSchema: schemaOf({
2158
+ workflowId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u6A21\u677F ID\uFF08\u5FC5\u586B\uFF09" },
2159
+ nodeId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u8282\u70B9 ID\uFF1B\u4E0D\u4F20\u81EA\u52A8\u53D6\u53D1\u8D77\u8282\u70B9" },
2160
+ attachmentIds: {
2161
+ oneOf: [
2162
+ { type: "string", description: "\u9644\u4EF6 ID\uFF0C\u591A\u4E2A\u7528\u9017\u53F7\u5206\u9694" },
2163
+ { type: "array", items: { type: "string" }, description: "\u9644\u4EF6 ID \u6570\u7EC4" }
2164
+ ],
2165
+ description: "\u5F85\u62BD\u53D6\u7684\u9644\u4EF6 ID\uFF08\u7528\u6237\u7ED9\u4E86\u5C31\u5E26\u4E0A\uFF1B\u6CA1\u6709\u5C31\u9760 userInput \u6216\u8868\u5355\u5DF2\u6709\u5185\u5BB9\uFF09"
2166
+ },
2167
+ userInput: { type: "string", description: "\u7528\u6237\u539F\u59CB\u8F93\u5165\uFF08\u6CA1\u6709\u9644\u4EF6\u65F6\u7684\u552F\u4E00\u6765\u6E90\uFF0C\u4E5F\u7528\u4E8E\u8FFD\u6EAF\uFF09" },
2168
+ targetFieldIdList: {
2169
+ type: "array",
2170
+ items: { type: "string" },
2171
+ description: "\u53EA\u62BD\u8FD9\u4E9B\u5B57\u6BB5 ID\uFF08\u53EF\u9009\uFF0C\u4E0D\u4F20\u5C31\u662F\u8BE5\u8282\u70B9\u5168\u90E8\u53EF\u586B\u5B57\u6BB5\uFF09"
2172
+ }
2173
+ }, { required: ["workflowId"] }),
2174
+ handler: async (args, env) => {
2175
+ const workflowId = optionalId(args.workflowId, "workflowId");
2176
+ if (!workflowId) throw smartExtractValidationError("workflow_id_required", "workflowId \u5FC5\u586B");
2177
+ const nodeIdInput = optionalId(args.nodeId, "nodeId");
2178
+ const userInput = optionalString(args.userInput, "userInput");
2179
+ const keep = parseIdList(args.targetFieldIdList, "targetFieldIdList");
2180
+ const attachmentIds = parseIdList(args.attachmentIds, "attachmentIds");
2181
+ if (attachmentIds.length > MAX_ATTACHMENTS) {
2182
+ throw smartExtractValidationError(
2183
+ "too_many_attachments",
2184
+ `\u4E00\u6B21\u6700\u591A\u5904\u7406 ${MAX_ATTACHMENTS} \u4E2A\u9644\u4EF6\uFF0C\u5F53\u524D ${attachmentIds.length} \u4E2A`
2185
+ );
2186
+ }
2187
+ const warnings = [];
2188
+ let nodeId = nodeIdInput;
2189
+ let nodeName;
2190
+ if (!nodeId) {
2191
+ const start = await resolveStartNode(env.host, workflowId);
2192
+ nodeId = start.nodeId;
2193
+ nodeName = start.nodeName;
2194
+ warnings.push(...start.warnings);
2195
+ }
2196
+ const outDir = env.outDir;
2197
+ await mkdir5(outDir, { recursive: true });
2198
+ const [rules, loaded, downloaded] = await Promise.all([
2199
+ fetchRules(env.host, workflowId, nodeId).catch((error) => ({
2200
+ globalRule: "",
2201
+ fieldRules: [],
2202
+ parseFields: [],
2203
+ warnings: [`\u8BC6\u522B\u89C4\u5219\u67E5\u8BE2\u5931\u8D25\uFF08\u6309\u8868\u5355\u7ED3\u6784\u81EA\u884C\u5224\u65AD\uFF09\uFF1A${error.message.slice(0, 120)}`]
2204
+ })),
2205
+ fetchWfNodeStructure(env.host, workflowId, nodeId, { keep, ...nodeName ? { nodeName } : {} }),
2206
+ attachmentIds.length > 0 ? downloadAttachments(env, attachmentIds, outDir, MAX_ATTACHMENT_BYTES) : Promise.resolve({ items: [], warnings: [] })
2207
+ ]);
2208
+ warnings.push(...rules.warnings, ...loaded.warnings, ...downloaded.warnings);
2209
+ const structure = loaded.structure;
2210
+ const sessionId = shortId("sf");
2211
+ const sessionFile = sessionPath(env.stateDir, sessionId);
2212
+ const basePayload = {
2213
+ sessionFile,
2214
+ sessionId,
2215
+ workflowId,
2216
+ nodeId,
2217
+ ...nodeName ? { nodeName } : {},
2218
+ mainFormName: structure.mainFormName ?? null,
2219
+ fields: {
2220
+ main: structure.mainFieldsStr,
2221
+ subTables: structure.subTables.map((table) => ({
2222
+ subFormId: table.subFormId,
2223
+ subFormName: table.subFormName,
2224
+ fields: table.subFieldsStr
2225
+ }))
2226
+ },
2227
+ rules: {
2228
+ globalRule: rules.globalRule ? ruleToPlainText(rules.globalRule) : null,
2229
+ fieldRules: rules.fieldRules.map(ruleToPlainText),
2230
+ parseFields: rules.parseFields
2231
+ },
2232
+ resultContract: RESULT_CONTRACT,
2233
+ next: fillNextHint(sessionFile)
2234
+ };
2235
+ const inlineBudgetBytes = Math.floor(DEFAULT_RESULT_THRESHOLD_BYTES * INLINE_BUDGET_RATIO) - Buffer.byteLength(JSON.stringify({ ...basePayload, attachments: [] }), "utf8") - ENVELOPE_RESERVE_BYTES;
2236
+ const perAttachmentBytes = Math.floor(inlineBudgetBytes / Math.max(1, downloaded.items.length));
2237
+ const inlineAllowed = perAttachmentBytes > MIN_INLINE_BYTES_PER_ATTACHMENT;
2238
+ const extractedItems = await Promise.all(downloaded.items.map(async (item) => ({
2239
+ item,
2240
+ ...await extractText(item)
2241
+ })));
2242
+ const totalTextBytes = extractedItems.reduce(
2243
+ (sum, entry) => sum + Buffer.byteLength(entry.text ?? "", "utf8"),
2244
+ 0
2245
+ );
2246
+ const allInline = totalTextBytes <= inlineBudgetBytes;
2247
+ const attachments = await Promise.all(extractedItems.map(async ({ item, text: extractedText, chars }) => {
2248
+ const text = extractedText ?? "";
2249
+ const oversized = allInline ? false : !inlineAllowed || Buffer.byteLength(text, "utf8") > perAttachmentBytes;
2250
+ let textFile;
2251
+ if (oversized && item.path) {
2252
+ textFile = `${item.path}.txt`;
2253
+ await mkdir5(dirname2(textFile), { recursive: true });
2254
+ await writeFile5(textFile, text, { encoding: "utf8", mode: 384 });
2255
+ }
2256
+ return {
2257
+ fileId: item.fileId,
2258
+ name: item.name,
2259
+ kind: item.kind ?? null,
2260
+ path: item.path ?? null,
2261
+ downloaded: item.downloaded,
2262
+ ...item.reason ? { reason: item.reason } : {},
2263
+ ...oversized ? {
2264
+ chars,
2265
+ textFile,
2266
+ textPreview: `${text.slice(0, TEXT_PREVIEW_CHARS)}\u2026`
2267
+ } : text ? { chars, text } : {}
2268
+ };
2269
+ }));
2270
+ const session = {
2271
+ sessionId,
2272
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2273
+ workflowId,
2274
+ nodeId,
2275
+ ...nodeName ? { nodeName } : {},
2276
+ attachmentIds,
2277
+ ...userInput ? { userInput } : {},
2278
+ structure,
2279
+ rules: { globalRule: rules.globalRule, fieldRules: rules.fieldRules, parseFields: rules.parseFields }
2280
+ };
2281
+ await mkdir5(dirname2(sessionFile), { recursive: true, mode: 448 });
2282
+ await writeFile5(sessionFile, JSON.stringify(session), { encoding: "utf8", mode: 384 });
2283
+ const noText = attachments.filter((item) => item.downloaded && !item.text && !item.textFile);
2284
+ if (noText.length > 0) {
2285
+ warnings.push(
2286
+ `\u4EE5\u4E0B\u9644\u4EF6\u672A\u80FD\u672C\u5730\u62BD\u6587\u672C\uFF0C\u9700\u8981\u8BFB path\uFF08PDF/\u56FE\u7247/Excel\uFF09\uFF1A${noText.map((item) => item.fileId).join(",")}`
2287
+ );
2288
+ }
2289
+ return smartExtractSuccess("smart-extract.fill", { ...basePayload, attachments }, { warnings });
2290
+ }
2291
+ };
2292
+ var fillSave = {
2293
+ name: "smart-extract.fill.save",
2294
+ risk: "high-risk-write",
2295
+ summary: "\u4E00\u6B65\u6536\u5C3E\uFF1A\u6309 sessionFile \u53D6\u56DE\u7ED3\u6784\u4E0E\u89C4\u5219 \u2192 \u81EA\u52A8\u6574\u7406\u7ED3\u679C\uFF08\u4E3B\u8868\u5254\u9664\u7A7A\u503C\u5E76\u6309 fields.main \u6392\u5E8F\u3001\u660E\u7EC6\u5220\u5168\u7A7A\u884C\uFF09\u2192 \u786E\u5B9A\u6027\u6821\u9A8C\uFF08\u4E0D\u901A\u8FC7\u76F4\u63A5\u62D2\u5199\u5E76\u56DE\u9519\u8BEF\u6E05\u5355\uFF09\u2192 \u5199\u6279\u6B21\u8BB0\u5F55 \u2192 \u56DE\u67E5\u9A8C\u8BC1\uFF0C\u8FD4\u56DE aiExtraId\u3002\u6BCF\u6B21\u90FD\u65B0\u5EFA\u4E00\u6761\u8BB0\u5F55\uFF0C\u4E0D\u5224\u65AD\u662F\u5426\u5DF2\u5B58\u5728\uFF1B\u4E0D\u9700\u8981\u9884\u89C8\u4E0E\u4EBA\u5DE5\u786E\u8BA4\u3002",
2296
+ inputSchema: schemaOf({
2297
+ sessionFile: { type: "string", description: "smart-extract.fill \u8FD4\u56DE\u7684 sessionFile \u8DEF\u5F84" },
2298
+ result: { type: "object", description: "\u62BD\u53D6\u7ED3\u679C\uFF08\u5185\u8054\uFF09" },
2299
+ resultPath: { type: "string", description: "\u62BD\u53D6\u7ED3\u679C JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E result \u4E8C\u9009\u4E00\uFF09" },
2300
+ requestId: { type: "string", description: `\u53EF\u9009\uFF1A\u81EA\u5B9A\u4E49 requestId\uFF08\u2264${MAX_REQUEST_ID_LENGTH} \u5B57\u7B26\uFF09\u3002\u9ED8\u8BA4\u6309 sessionFile \u6D3E\u751F\uFF0C\u540C\u4E00\u6B21 fill \u91CD\u8BD5\u65F6\u4E0D\u4F1A\u91CD\u590D\u5165\u5E93` },
2301
+ dataSource: { type: "string", description: "wf-pre / wf-manual / eb-manual\uFF0C\u9ED8\u8BA4 wf-manual" },
2302
+ sceneFlag: { type: "string", description: "\u573A\u666F\u6807\u8BC6" },
2303
+ agentId: { ...SCHEMA_ID, description: "\u667A\u80FD\u4F53 ID" },
2304
+ chatId: { type: "string", description: "\u4F1A\u8BDD ID" },
2305
+ messageId: { type: "string", description: "\u6D88\u606F ID" }
2306
+ }, { required: ["sessionFile"] }),
2307
+ handler: async (args, env) => {
2308
+ const sessionFile = optionalString(args.sessionFile, "sessionFile");
2309
+ if (!sessionFile) throw smartExtractValidationError("session_file_required", "sessionFile \u5FC5\u586B");
2310
+ let session;
2311
+ try {
2312
+ session = JSON.parse(await readFile5(sessionFile, "utf8"));
2313
+ } catch (error) {
2314
+ throw smartExtractValidationError("session_unreadable", `\u65E0\u6CD5\u8BFB\u53D6\u4F1A\u8BDD\u6587\u4EF6\uFF1A${sessionFile}`, {
2315
+ details: { reason: error instanceof Error ? error.message : String(error) }
2316
+ });
2317
+ }
2318
+ if (!session.workflowId || !session.structure) {
2319
+ throw smartExtractValidationError("session_invalid", "\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 workflowId \u6216 structure\uFF0C\u8BF7\u91CD\u65B0\u8C03 smart-extract.fill");
2320
+ }
2321
+ const result = await readObjectInput(args, "result", "resultPath", { required: true });
2322
+ if (!result) throw smartExtractValidationError("result_required", "\u5FC5\u987B\u63D0\u4F9B result \u6216 resultPath");
2323
+ const normalized = normalizeResult(result, session.structure);
2324
+ const report = validateExtraction(normalized, session.structure, {
2325
+ knownAttachmentIds: session.attachmentIds
2326
+ });
2327
+ if (!report.ok) {
2328
+ throw smartExtractValidationError(
2329
+ "result_invalid",
2330
+ `\u62BD\u53D6\u7ED3\u679C\u6821\u9A8C\u672A\u901A\u8FC7\uFF08${report.stats.errorCount} \u4E2A\u9519\u8BEF\uFF09\uFF0C\u672A\u5199\u5E93\uFF1B\u6309 errors \u4FEE\u6B63\u540E\u91CD\u65B0\u8C03\u7528\u672C\u547D\u4EE4`,
2331
+ { errors: report.errors, stats: report.stats }
2332
+ );
2333
+ }
2334
+ const { workflowId, nodeId } = session;
2335
+ const attachmentIds = session.attachmentIds.join(",");
2336
+ const customRequestId = optionalString(args.requestId, "requestId");
2337
+ if (customRequestId && customRequestId.length > MAX_REQUEST_ID_LENGTH) {
2338
+ throw smartExtractValidationError(
2339
+ "request_id_too_long",
2340
+ `requestId \u6700\u591A ${MAX_REQUEST_ID_LENGTH} \u4E2A\u5B57\u7B26\uFF08\u670D\u52A1\u7AEF request_id \u5217\u653E\u4E0D\u4E0B\uFF0C\u4F1A\u76F4\u63A5 500\uFF09`,
2341
+ { expected: MAX_REQUEST_ID_LENGTH, actual: customRequestId.length }
2342
+ );
2343
+ }
2344
+ const requestId = customRequestId ?? `se${session.sessionId.replace(/^sf/, "")}`;
2345
+ const existingId = await queryByRequestId(env, requestId);
2346
+ if (existingId) {
2347
+ return smartExtractSuccess("smart-extract.fill.save", {
2348
+ aiExtraId: existingId,
2349
+ requestId,
2350
+ workflowId,
2351
+ nodeId,
2352
+ retried: true,
2353
+ message: "\u540C\u4E00\u6B21\u62BD\u53D6\u7684\u91CD\u8BD5\uFF1A\u670D\u52A1\u7AEF\u5DF2\u6709\u8BE5 requestId \u7684\u8BB0\u5F55\uFF08\u4E0A\u6B21\u5199\u5E93\u5B9E\u9645\u5DF2\u6210\u529F\uFF09\uFF0C\u672C\u6B21\u672A\u91CD\u590D\u5165\u5E93"
2354
+ }, { meta: { state: "ALREADY_SAVED" } });
2355
+ }
2356
+ const dataSource = (() => {
2357
+ const text = optionalString(args.dataSource, "dataSource");
2358
+ if (!text) return DATA_SOURCE["wf-manual"];
2359
+ if (text in DATA_SOURCE) return DATA_SOURCE[text];
2360
+ if (["0", "1", "2"].includes(text)) return text;
2361
+ throw smartExtractValidationError("data_source_invalid", "dataSource \u53EA\u80FD\u662F wf-pre / wf-manual / eb-manual \u6216 0/1/2");
2362
+ })();
2363
+ const payload = {
2364
+ workflowId,
2365
+ ...nodeId ? { nodeId } : {},
2366
+ formModeType: "wf",
2367
+ requestId,
2368
+ recognizeResult: JSON.stringify(normalized),
2369
+ dataSource,
2370
+ fillStatus: "0",
2371
+ ...attachmentIds ? { attachmentIds } : {},
2372
+ ...session.userInput ? { userInput: session.userInput } : {},
2373
+ ...optionalString(args.sceneFlag, "sceneFlag") ? { sceneFlag: optionalString(args.sceneFlag, "sceneFlag") } : {},
2374
+ ...optionalId(args.agentId, "agentId") ? { agentId: optionalId(args.agentId, "agentId") } : {},
2375
+ ...optionalString(args.chatId, "chatId") ? { chatId: optionalString(args.chatId, "chatId") } : {},
2376
+ ...optionalString(args.messageId, "messageId") ? { messageId: optionalString(args.messageId, "messageId") } : {}
2377
+ };
2378
+ let saved;
2379
+ try {
2380
+ saved = await env.host.requestData({
2381
+ operation: "smart-extract.fill.save",
2382
+ method: "POST",
2383
+ path: PATHS.saveRecognizeRecord,
2384
+ body: payload
2385
+ });
2386
+ } catch (error) {
2387
+ if (error instanceof SmartExtractCliError && error.type === "network") {
2388
+ throw smartExtractPartialError(
2389
+ "\u4FDD\u5B58\u8BF7\u6C42\u7ED3\u679C\u672A\u77E5\uFF08\u7F51\u7EDC\u4E2D\u65AD/\u8D85\u65F6\uFF09\u3002\u76F4\u63A5\u91CD\u8DD1\u672C\u547D\u4EE4\u5373\u53EF\uFF1A\u540C\u4E00\u6B21 fill \u7684 requestId \u76F8\u540C\uFF0C\u4F1A\u547D\u4E2D\u5DF2\u5199\u5165\u7684\u90A3\u6761\uFF0C\u4E0D\u4F1A\u91CD\u590D\u5165\u5E93",
2390
+ { requestId, sessionFile, hint: "\u91CD\u8DD1\u540C\u6837\u5165\u53C2\uFF1B\u82E5\u8FD4\u56DE retried:true \u4E14\u5E26 aiExtraId\uFF0C\u5C31\u662F\u4E0A\u4E00\u8F6E\u5DF2\u5199\u6210\u529F" }
2391
+ );
2392
+ }
2393
+ throw error;
2394
+ }
2395
+ const root = record(saved);
2396
+ const rawId = root.id ?? root.aiExtraId ?? root.batchId;
2397
+ if (rawId === void 0 || rawId === null) {
2398
+ throw smartExtractBusinessError("save_response_invalid", "\u4FDD\u5B58\u63A5\u53E3\u672A\u8FD4\u56DE aiExtraId", { details: { result: saved } });
2399
+ }
2400
+ const aiExtraId = String(rawId);
2401
+ let verified = false;
2402
+ try {
2403
+ const check = record(await env.host.requestData({
2404
+ operation: "smart-extract.fill.save",
2405
+ method: "GET",
2406
+ path: PATHS.batchInfoById,
2407
+ query: { id: aiExtraId }
2408
+ }));
2409
+ verified = Object.keys(check).length > 0;
2410
+ } catch {
2411
+ verified = false;
2412
+ }
2413
+ const mainRows = Array.isArray(record(normalized.mainTable).rows) ? record(normalized.mainTable).rows.length : 0;
2414
+ const subRows = Array.isArray(normalized.subTables) ? normalized.subTables.reduce((total, table) => total + (Array.isArray(table?.rows) ? table.rows.length : 0), 0) : 0;
2415
+ return smartExtractSuccess("smart-extract.fill.save", {
2416
+ aiExtraId,
2417
+ verified,
2418
+ workflowId,
2419
+ nodeId,
2420
+ requestId,
2421
+ mainRows,
2422
+ subRows,
2423
+ fills: report.stats.mainFieldsFilled
2424
+ }, {
2425
+ meta: { state: verified ? "COMPLETE" : "WRITTEN_UNVERIFIED" },
2426
+ warnings: [
2427
+ ...report.warnings.slice(0, 20).map((issue) => issue.message),
2428
+ ...verified ? [] : [`\u5DF2\u5199\u5165\u4F46\u56DE\u67E5\u672A\u786E\u8BA4\uFF08aiExtraId=${aiExtraId}\uFF09\uFF0C\u53EF\u7A0D\u540E\u7528 smart-extract.batch.get \u518D\u67E5\u4E00\u6B21`]
2429
+ ]
2430
+ });
2431
+ }
2432
+ };
2433
+ var fillOperations = [fill, fillSave];
2434
+
2435
+ // src/shortcuts/smart-extract/operations/preview.ts
2436
+ function renderValue(value, options) {
2437
+ const values = valuesOf(value);
2438
+ if (values.length === 0) return "\uFF08\u7A7A\uFF09";
2439
+ const label = (raw) => {
2440
+ if (!options?.length) return raw;
2441
+ const hit = options.find((option) => option.optionValue === raw.trim());
2442
+ return hit ? hit.optionName : raw;
2443
+ };
2444
+ return truncate(values.map(label).join("\u3001"), 120);
2445
+ }
2446
+ function renderOrigins(origin, nameOf) {
2447
+ if (!Array.isArray(origin) || origin.length === 0) return "\u2014";
2448
+ const parts = [];
2449
+ for (const item of origin) {
2450
+ if (typeof item !== "string") continue;
2451
+ const hash = item.indexOf("#");
2452
+ if (hash <= 0) {
2453
+ parts.push(truncate(item, 80));
2454
+ continue;
2455
+ }
2456
+ const sourceId = item.slice(0, hash);
2457
+ const snippet = item.slice(hash + 1);
2458
+ const label = sourceId === "userInput" ? "\u7528\u6237\u8F93\u5165" : nameOf(sourceId);
2459
+ parts.push(`${label}\uFF1A${truncate(snippet, 80)}`);
2460
+ }
2461
+ return parts.join("\uFF1B") || "\u2014";
2462
+ }
2463
+ var resultPreview = {
2464
+ name: "smart-extract.result.preview",
2465
+ risk: "read",
2466
+ summary: "\u628A\u62BD\u53D6\u7ED3\u679C\u6E32\u67D3\u6210\u4EBA\u53EF\u786E\u8BA4\u7684\u8868\u683C\u6587\u672C\uFF08\u5B57\u6BB5\u2192\u503C\u2192\u6765\u6E90\uFF09\uFF0C\u5E76\u5217\u51FA\u672A\u53D6\u5230\u503C\u7684\u6807\u8BB0\u5B57\u6BB5\u3002\u7528\u6237\u786E\u8BA4\u8FD9\u4EFD\u9884\u89C8\u540E\u624D\u5141\u8BB8 save.prepare\u3002",
2467
+ inputSchema: schemaOf({
2468
+ result: { type: "object", description: "\u62BD\u53D6\u7ED3\u679C\uFF08\u5185\u8054\uFF09" },
2469
+ resultPath: { type: "string", description: "\u62BD\u53D6\u7ED3\u679C JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E result \u4E8C\u9009\u4E00\uFF09" },
2470
+ structure: { type: "object", description: "smart-extract.form.structure \u7684 data\uFF08\u5185\u8054\uFF09" },
2471
+ structurePath: { type: "string", description: "\u8868\u5355\u7ED3\u6784 JSON \u6587\u4EF6\u8DEF\u5F84\uFF08\u4E0E structure \u4E8C\u9009\u4E00\uFF09" },
2472
+ attachments: {
2473
+ type: "array",
2474
+ items: {
2475
+ type: "object",
2476
+ properties: {
2477
+ fileId: { type: "string" },
2478
+ name: { type: "string" }
2479
+ }
2480
+ },
2481
+ description: "\u9644\u4EF6\u6E05\u5355\uFF08fileId \u2192 \u540D\u79F0\uFF09\uFF0C\u7528\u4E8E\u628A\u6765\u6E90\u663E\u793A\u6210\u6587\u4EF6\u540D"
2482
+ }
2483
+ }, { required: ["structure"] }),
2484
+ handler: async (args) => {
2485
+ const result = await readObjectInput(args, "result", "resultPath", { required: true });
2486
+ const structureRaw = await readObjectInput(args, "structure", "structurePath", { required: true });
2487
+ if (!result || !structureRaw) {
2488
+ throw smartExtractValidationError("result_required", "\u5FC5\u987B\u63D0\u4F9B result \u4E0E structure");
2489
+ }
2490
+ const structure = coerceStructure(structureRaw);
2491
+ const nameMap = /* @__PURE__ */ new Map();
2492
+ if (Array.isArray(args.attachments)) {
2493
+ for (const item of args.attachments) {
2494
+ if (!item || typeof item !== "object") continue;
2495
+ const fileId = String(item.fileId ?? item.id ?? "").trim();
2496
+ const name = String(item.name ?? "").trim();
2497
+ if (fileId && name) nameMap.set(fileId, name);
2498
+ }
2499
+ }
2500
+ const nameOf = (id) => nameMap.get(id) || `\u9644\u4EF6 ${id}`;
2501
+ const mainFields = new Map(structure.mainFields.map((field) => [field.fieldId, field]));
2502
+ const subTables = new Map(structure.subTables.map((table) => [table.subFormId, table]));
2503
+ const lines = [];
2504
+ const filledFieldIds = /* @__PURE__ */ new Set();
2505
+ let mainRowCount = 0;
2506
+ let subRowCount = 0;
2507
+ const formLabel = structure.mainFormName || `\u8868\u5355 ${structure.mainFormId}`;
2508
+ lines.push(`### \u62BD\u53D6\u7ED3\u679C\u9884\u89C8\uFF1A${formLabel}`);
2509
+ const mainRows = result.mainTable && Array.isArray(result.mainTable.rows) ? result.mainTable.rows : [];
2510
+ mainRowCount = mainRows.length;
2511
+ if (mainRows.length === 0) {
2512
+ lines.push("", "_\u4E3B\u8868\u6CA1\u6709\u4EFB\u4F55\u8BC6\u522B\u7ED3\u679C\u3002_");
2513
+ }
2514
+ for (const [rowIndex, rowRaw] of mainRows.entries()) {
2515
+ const row = rowRaw;
2516
+ const label = mainRows.length > 1 ? `\u4E3B\u8868\u7B2C ${row.mainDataId ?? rowIndex + 1} \u6761` : "\u4E3B\u8868";
2517
+ lines.push("", `**${label}**`, "");
2518
+ lines.push("| \u5B57\u6BB5 | \u503C | \u4F9D\u636E | \u6765\u6E90 |");
2519
+ lines.push("| --- | --- | --- | --- |");
2520
+ for (const fieldRaw of Array.isArray(row.fieldResults) ? row.fieldResults : []) {
2521
+ const fieldResult = fieldRaw;
2522
+ const fieldInfo = String(fieldResult.fieldInfo ?? "");
2523
+ const hash = fieldInfo.indexOf("#");
2524
+ const fieldId = hash > 0 ? fieldInfo.slice(0, hash) : fieldInfo;
2525
+ const fieldName = hash > 0 ? fieldInfo.slice(hash + 1) : mainFields.get(fieldId)?.fieldName ?? fieldId;
2526
+ filledFieldIds.add(fieldId);
2527
+ lines.push(
2528
+ `| ${fieldName} | ${renderValue(fieldResult.value, mainFields.get(fieldId)?.options)} | ${truncate(String(fieldResult.reason ?? "\u2014"), 80)} | ${renderOrigins(fieldResult.origin, nameOf)} |`
2529
+ );
2530
+ }
2531
+ if (!Array.isArray(row.fieldResults) || row.fieldResults.length === 0) {
2532
+ lines.push("| \uFF08\u65E0\u5B57\u6BB5\uFF09 | | | |");
2533
+ }
2534
+ }
2535
+ const tables = Array.isArray(result.subTables) ? result.subTables : [];
2536
+ for (const tableRaw of tables) {
2537
+ const table = tableRaw;
2538
+ const subFormId = String(table.subFormId ?? "");
2539
+ const definition = subTables.get(subFormId);
2540
+ const tableName = definition?.subFormName || String(table.subFormName ?? subFormId);
2541
+ const fields = Array.isArray(table.fields) ? table.fields.map((item) => String(item)) : [];
2542
+ const rows = Array.isArray(table.rows) ? table.rows : [];
2543
+ subRowCount += rows.length;
2544
+ lines.push("", `**\u660E\u7EC6\u8868\uFF1A${tableName}\uFF08${rows.length} \u884C\uFF09**`);
2545
+ if (rows.length === 0) {
2546
+ lines.push("", "_\u65E0\u660E\u7EC6\u6570\u636E\u3002_");
2547
+ continue;
2548
+ }
2549
+ for (const [rowIndex, subRowRaw] of rows.entries()) {
2550
+ const subRow = subRowRaw;
2551
+ lines.push("", `\u7B2C ${subRow.subDataId ?? rowIndex + 1} \u884C\uFF08\u4E3B\u8868 ${subRow.mainDataId ?? "-"}\uFF09`);
2552
+ const values = Array.isArray(subRow.values) ? subRow.values : [];
2553
+ const reasons = Array.isArray(subRow.reasons) ? subRow.reasons : [];
2554
+ const origins = Array.isArray(subRow.origins) ? subRow.origins : [];
2555
+ for (const [fieldIndex, fieldInfo] of fields.entries()) {
2556
+ const hash = fieldInfo.indexOf("#");
2557
+ const fieldId = hash > 0 ? fieldInfo.slice(0, hash) : fieldInfo;
2558
+ const definitionField = definition?.fields.find((field) => field.fieldId === fieldId);
2559
+ const fieldName = hash > 0 ? fieldInfo.slice(hash + 1) : definitionField?.fieldName ?? fieldId;
2560
+ filledFieldIds.add(fieldId);
2561
+ const value = renderValue(values[fieldIndex], definitionField?.options);
2562
+ const reason = reasons[fieldIndex] ? `\uFF08${truncate(String(reasons[fieldIndex]), 60)}\uFF09` : "";
2563
+ lines.push(`- ${fieldName}\uFF1A${value}${reason}${origins[fieldIndex] ? ` \u2190 ${renderOrigins(origins[fieldIndex], nameOf)}` : ""}`);
2564
+ }
2565
+ }
2566
+ }
2567
+ const missingMarked = structure.mainFields.filter((field) => field.marked && !filledFieldIds.has(field.fieldId)).map((field) => ({ fieldId: field.fieldId, fieldName: field.fieldName }));
2568
+ if (missingMarked.length > 0) {
2569
+ lines.push("", "**\u672A\u53D6\u5230\u503C\u7684\u6807\u8BB0\u5B57\u6BB5\uFF08\u53EF\u80FD\u9700\u8981\u5411\u7528\u6237\u8FFD\u95EE\uFF09**");
2570
+ for (const field of missingMarked) lines.push(`- ${field.fieldName}`);
2571
+ }
2572
+ const emptyFieldCount = structure.mainFields.length - filledFieldIds.size;
2573
+ lines.push("", "---", "\u4EE5\u4E0A\u4E3A\u672C\u6B21\u62BD\u53D6\u7ED3\u679C\u3002**\u786E\u8BA4\u65E0\u8BEF\u540E\u624D\u4F1A\u4FDD\u5B58**\uFF1B\u5982\u9700\u4FEE\u6539\u8BF7\u76F4\u63A5\u8BF4\u6539\u54EA\u4E2A\u5B57\u6BB5\u3002");
2574
+ return smartExtractSuccess("smart-extract.result.preview", {
2575
+ previewText: lines.join("\n"),
2576
+ mainRowCount,
2577
+ subRowCount,
2578
+ subTableCount: tables.length,
2579
+ structureFieldCount: structure.mainFields.length,
2580
+ missingMarkedFields: missingMarked,
2581
+ untouchedFieldCount: Math.max(0, emptyFieldCount),
2582
+ confirmationHint: "\u628A previewText \u539F\u6837\u8D34\u7ED9\u7528\u6237\u5E76\u8981\u6C42\u660E\u786E\u786E\u8BA4\uFF08\u662F/\u53EF\u4EE5/\u4FDD\u5B58\uFF09\uFF1B\u7528\u6237\u786E\u8BA4\u540E\u624D\u8C03 smart-extract.save.prepare"
2583
+ }, {
2584
+ warnings: missingMarked.length > 0 ? [`\u6709 ${missingMarked.length} \u4E2A\u6807\u8BB0\u5B57\u6BB5\u6CA1\u62BD\u5230\u503C\uFF0C\u786E\u8BA4\u65F6\u5E94\u4E3B\u52A8\u63D0\u793A\u7528\u6237`] : []
2585
+ });
2586
+ }
2587
+ };
2588
+ var previewOperations = [resultPreview];
2589
+
2590
+ // src/shortcuts/smart-extract/operations/target.ts
2591
+ function flowSummary(flow) {
2592
+ return {
2593
+ workflowId: flow.workflowid ?? flow.workflowId ?? null,
2594
+ workflowName: flow.workflowname ?? flow.workflowName ?? null,
2595
+ workflowDesc: flow.workflowdesc ?? null,
2596
+ typeName: flow.typeName ?? null,
2597
+ pcUrl: flow.pcUrl ?? null
2598
+ };
2599
+ }
2600
+ var targetResolve = {
2601
+ name: "smart-extract.target.resolve",
2602
+ risk: "read",
2603
+ summary: "\u628A\u76EE\u6807\u6536\u655B\u6210 ID\uFF1AworkflowId/formId/objId \u76F4\u63A5\u56DE\u663E\u6821\u9A8C\uFF1B\u7ED9 workflowKeyword \u65F6\u5217\u51FA\u5F53\u524D\u7528\u6237\u53EF\u53D1\u8D77\u7684\u6D41\u7A0B\u5E76\u505A\u540D\u79F0\u5339\u914D\u3002\u8FD4\u56DE modeType \u4E0E\u547D\u4E2D\u9879\u3002",
2604
+ inputSchema: schemaOf({
2605
+ workflowId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u6A21\u677F ID" },
2606
+ formId: { ...SCHEMA_ID, description: "EB \u8868\u5355 ID" },
2607
+ objId: { ...SCHEMA_ID, description: "EB \u5EFA\u6A21\u5BF9\u8C61 ID\uFF08\u4F1A\u81EA\u52A8\u8F6C\u6362\u6210 formId\uFF09" },
2608
+ workflowKeyword: { type: "string", description: "\u6D41\u7A0B\u540D\u79F0\u5173\u952E\u5B57\uFF08\u53EA\u5728\u53EF\u53D1\u8D77\u6D41\u7A0B\u91CC\u505A\u5305\u542B\u5339\u914D\uFF09" },
2609
+ limit: { type: "integer", description: "\u5173\u952E\u5B57\u5339\u914D\u8FD4\u56DE\u6761\u6570\u4E0A\u9650\uFF0C\u9ED8\u8BA4 10" }
2610
+ }),
2611
+ handler: async (args, env) => {
2612
+ const workflowId = optionalId(args.workflowId, "workflowId");
2613
+ const formId = optionalId(args.formId, "formId");
2614
+ const objId = optionalId(args.objId, "objId");
2615
+ const keyword = optionalString(args.workflowKeyword, "workflowKeyword");
2616
+ const limit = Math.max(1, Math.min(50, Number(args.limit ?? 10) || 10));
2617
+ if (workflowId) {
2618
+ return smartExtractSuccess("smart-extract.target.resolve", {
2619
+ modeType: "wf",
2620
+ resolved: true,
2621
+ workflowId,
2622
+ hint: "\u9700\u8981\u6309\u8282\u70B9\u5B57\u6BB5\u62BD\u53D6\u65F6\uFF0C\u518D\u8C03 smart-extract.flow.start-node \u53D6\u9996\u8282\u70B9 nodeId"
2623
+ });
2624
+ }
2625
+ if (formId) {
2626
+ let resolvedObjId = null;
2627
+ try {
2628
+ const data = record(await env.host.requestData({
2629
+ operation: "smart-extract.target.resolve",
2630
+ method: "GET",
2631
+ path: PATHS.governObjId,
2632
+ query: { formId }
2633
+ }));
2634
+ resolvedObjId = data.value ?? data.objId ?? null;
2635
+ } catch {
2636
+ resolvedObjId = null;
2637
+ }
2638
+ return smartExtractSuccess("smart-extract.target.resolve", {
2639
+ modeType: "eb",
2640
+ resolved: true,
2641
+ formId,
2642
+ objId: resolvedObjId
2643
+ });
2644
+ }
2645
+ if (objId) {
2646
+ const data = await env.host.requestData({
2647
+ operation: "smart-extract.target.resolve",
2648
+ method: "GET",
2649
+ path: PATHS.governFormId,
2650
+ query: { objId }
2651
+ });
2652
+ const resolvedFormId = typeof data === "string" ? data : record(data).value;
2653
+ if (!resolvedFormId) {
2654
+ throw smartExtractBusinessError("form_id_not_found", `objId=${objId} \u6CA1\u6709\u5BF9\u5E94\u7684\u8868\u5355 ID`, {
2655
+ details: { objId }
2656
+ });
2657
+ }
2658
+ return smartExtractSuccess("smart-extract.target.resolve", {
2659
+ modeType: "eb",
2660
+ resolved: true,
2661
+ objId,
2662
+ formId: String(resolvedFormId)
2663
+ });
2664
+ }
2665
+ if (!keyword) {
2666
+ throw smartExtractValidationError(
2667
+ "target_required",
2668
+ "\u5FC5\u987B\u63D0\u4F9B workflowId\u3001formId\u3001objId \u6216 workflowKeyword \u4E4B\u4E00"
2669
+ );
2670
+ }
2671
+ let payload;
2672
+ try {
2673
+ payload = record(await env.host.requestData({
2674
+ operation: "smart-extract.target.resolve",
2675
+ method: "GET",
2676
+ path: PATHS.creatableFlows,
2677
+ query: { onlyLoadListData: 1, identityTypes: "0", loadOfsFlow: 0, wfpBelongTypeCode: 1 }
2678
+ }));
2679
+ } catch (error) {
2680
+ const message = error?.message || "\u83B7\u53D6\u53EF\u53D1\u8D77\u6D41\u7A0B\u5931\u8D25";
2681
+ return smartExtractSuccess("smart-extract.target.resolve", {
2682
+ modeType: "wf",
2683
+ resolved: false,
2684
+ keyword,
2685
+ candidateCount: 0,
2686
+ candidates: [],
2687
+ flowListAvailable: false,
2688
+ flowListError: message,
2689
+ hint: `\u53EF\u53D1\u8D77\u6D41\u7A0B\u5217\u8868\u63A5\u53E3\u4E0D\u53EF\u7528\uFF08${message}\uFF09\u3002\u4E0D\u8981\u636E\u6B64\u5224\u65AD\u300C\u6CA1\u6709\u8FD9\u4E2A\u6D41\u7A0B\u300D\uFF1A\u8BF7\u8BA9\u7528\u6237\u76F4\u63A5\u7ED9\u51FA\u6D41\u7A0B ID\uFF08workflowId\uFF09\uFF0C\u6216\u7ED9\u51FA\u7CBE\u786E\u6D41\u7A0B\u540D\u7531\u7528\u6237\u786E\u8BA4\u540E\u53D6 ID`
2690
+ }, { warnings: ["\u53EF\u53D1\u8D77\u6D41\u7A0B\u5217\u8868\u63A5\u53E3\u62A5\u9519\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u300C\u6309\u5173\u952E\u5B57\u65E0\u6CD5\u81EA\u52A8\u5339\u914D\u300D\uFF0C\u8BF7\u6539\u7528 workflowId \u76F4\u63A5\u5B9A\u4F4D"] });
2691
+ }
2692
+ if (payload.success === false) {
2693
+ throw smartExtractBusinessError("creatable_flows_failed", String(payload.message || "\u83B7\u53D6\u53EF\u53D1\u8D77\u6D41\u7A0B\u5931\u8D25"));
2694
+ }
2695
+ const flows = Array.isArray(payload.list) ? payload.list : [];
2696
+ const needle = keyword.toLowerCase();
2697
+ const matched = flows.map((flow) => flowSummary(flow)).filter((flow) => String(flow.workflowName ?? "").toLowerCase().includes(needle) || String(flow.workflowDesc ?? "").toLowerCase().includes(needle));
2698
+ const candidates = matched.slice(0, limit);
2699
+ return smartExtractSuccess("smart-extract.target.resolve", {
2700
+ modeType: "wf",
2701
+ resolved: candidates.length === 1,
2702
+ keyword,
2703
+ candidateCount: matched.length,
2704
+ candidates,
2705
+ totalCreatableFlows: flows.length,
2706
+ hint: candidates.length === 1 ? "\u547D\u4E2D\u552F\u4E00\u6D41\u7A0B\uFF0C\u53EF\u76F4\u63A5\u7528\u5176 workflowId" : "\u547D\u4E2D\u591A\u4E2A/\u96F6\u4E2A\u6D41\u7A0B\uFF1A\u8BF7\u628A\u5019\u9009\u5217\u8868\u7ED9\u7528\u6237\u9009\uFF0C\u6216\u8BA9\u7528\u6237\u7ED9\u51FA\u66F4\u7CBE\u786E\u7684\u540D\u79F0/\u6D41\u7A0B ID"
2707
+ });
2708
+ }
2709
+ };
2710
+ var flowStartNode = {
2711
+ name: "smart-extract.flow.start-node",
2712
+ risk: "read",
2713
+ summary: "\u6309 workflowId \u53D6\u6D41\u7A0B\u53D1\u8D77\u8282\u70B9\uFF08nodeId/nodeName\uFF09\u3002\u7528\u6237\u6CA1\u63D0\u5177\u4F53\u8282\u70B9\u65F6\uFF0C\u7528\u5B83\u51B3\u5B9A getSimple(wf) \u7684 nodeId\u3002",
2714
+ inputSchema: schemaOf({ workflowId: { ...SCHEMA_ID, description: "\u6D41\u7A0B\u6A21\u677F ID" } }, {
2715
+ required: ["workflowId"]
2716
+ }),
2717
+ handler: async (args, env) => {
2718
+ const workflowId = requiredId(args.workflowId, "workflowId");
2719
+ const data = record(await env.host.requestData({
2720
+ operation: "smart-extract.flow.start-node",
2721
+ method: "GET",
2722
+ path: PATHS.flowStartNode,
2723
+ query: { workflowId }
2724
+ }));
2725
+ if (data.success === false) {
2726
+ throw smartExtractBusinessError("start_node_not_found", String(data.message || "\u672A\u53D6\u5230\u6D41\u7A0B\u53D1\u8D77\u8282\u70B9"), {
2727
+ details: { workflowId }
2728
+ });
2729
+ }
2730
+ const node = record(data.node);
2731
+ const nodeId = node.id ?? node.nodeId;
2732
+ if (!nodeId) {
2733
+ throw smartExtractBusinessError("start_node_invalid", "\u53D1\u8D77\u8282\u70B9\u7F3A\u5C11 id", { details: { result: data } });
2734
+ }
2735
+ return smartExtractSuccess("smart-extract.flow.start-node", {
2736
+ workflowId,
2737
+ nodeId: String(nodeId),
2738
+ nodeName: node.nodeName ?? null,
2739
+ nodeType: node.nodeType ?? null,
2740
+ nodeTypeCode: node.nodeTypeCode ?? null
2741
+ });
2742
+ }
2743
+ };
2744
+ var targetOperations = [targetResolve, flowStartNode];
2745
+
2746
+ // src/shortcuts/smart-extract/operations/registry.ts
2747
+ var smartExtractOperationDefinitions = [
2748
+ ...fillOperations,
2749
+ ...targetOperations,
2750
+ ...configOperations,
2751
+ ...structureOperations,
2752
+ ...attachmentOperations,
2753
+ ...validateOperations,
2754
+ ...previewOperations,
2755
+ ...saveOperations,
2756
+ ...batchOperations
2757
+ ];
2758
+ var REGISTRY = new Map(
2759
+ smartExtractOperationDefinitions.map((definition) => [definition.name, definition])
2760
+ );
2761
+ function getSmartExtractOperation(name) {
2762
+ const hit = REGISTRY.get(name);
2763
+ if (!hit) {
2764
+ throw new Error(`\u672A\u77E5 operation: ${name}\uFF08\u53EF\u7528\uFF1A${[...REGISTRY.keys()].join(" / ")}\uFF09`);
2765
+ }
2766
+ return hit;
2767
+ }
2768
+ var smartExtractOperationNames = [...REGISTRY.keys()];
2769
+
2770
+ // src/shortcuts/smart-extract/manifest.ts
2771
+ var smartExtractOperations = smartExtractOperationDefinitions.map((definition) => ({
2772
+ name: definition.name,
2773
+ risk: definition.risk,
2774
+ summary: definition.summary,
2775
+ inputSchema: definition.inputSchema
2776
+ }));
2777
+ var smartExtractManifest = {
2778
+ schemaVersion: 1,
2779
+ module: "smart-extract",
2780
+ name: "smart-extract",
2781
+ title: "E10 \u667A\u80FD\u62BD\u53D6\uFF08\u8868\u5355\u7ED3\u6784\u5316\u6570\u636E\u62BD\u53D6\uFF09",
2782
+ version: 1,
2783
+ host: "e10-smart-extract",
2784
+ status: "builtin",
2785
+ sourceSkill: "weaver-e10-smart-extract",
2786
+ capabilities: ["smart-extract"],
2787
+ /** 主链路两步:fill 只读、fill.save 校验通过即写(不再要人工确认)。 */
2788
+ writePolicy: "auto-after-validate",
2789
+ /** 推荐调用顺序,给模型当路标,不参与校验。 */
2790
+ flow: [
2791
+ "smart-extract.fill",
2792
+ "smart-extract.fill.save"
2793
+ ],
2794
+ operations: smartExtractOperations,
2795
+ operationNames: smartExtractOperationNames
2796
+ };
2797
+ function assertManifestMatchesRegistry() {
2798
+ const declared = smartExtractOperations.map((operation) => operation.name).sort();
2799
+ const registered = [...smartExtractOperationNames].sort();
2800
+ if (declared.join(",") !== registered.join(",")) {
2801
+ throw new Error(`manifest \u4E0E registry \u4E0D\u4E00\u81F4\uFF1A
2802
+ manifest=${declared.join(",")}
2803
+ registry=${registered.join(",")}`);
2804
+ }
2805
+ }
2806
+
2807
+ // src/shortcuts/smart-extract/index.ts
2808
+ function asOptions(value) {
2809
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
2810
+ }
2811
+ async function readStdin() {
2812
+ const chunks = [];
2813
+ for await (const chunk of process.stdin) {
2814
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
2815
+ }
2816
+ return Buffer.concat(chunks).toString("utf8");
2817
+ }
2818
+ async function inputFrom(options) {
2819
+ const inline = typeof options.inputJson === "string" ? options.inputJson.trim() : "";
2820
+ const file = typeof options.input === "string" ? options.input.trim() : "";
2821
+ if (inline && file) {
2822
+ throw smartExtractValidationError("input_conflict", "\u4E0D\u80FD\u540C\u65F6\u4F20 --input \u548C --input-json");
2823
+ }
2824
+ if (inline) return parseJsonObject(stripBom(inline), "--input-json");
2825
+ if (file) {
2826
+ let raw;
2827
+ try {
2828
+ raw = file === "-" ? await readStdin() : await readFile6(file, "utf8");
2829
+ } catch {
2830
+ throw smartExtractValidationError("input_unreadable", `\u65E0\u6CD5\u8BFB\u53D6 --input\uFF1A${file}`);
2831
+ }
2832
+ return parseJsonObject(stripBom(raw), "--input");
2833
+ }
2834
+ return {};
2835
+ }
2836
+ function contextOf(ctx) {
2837
+ const stateDir = join4(stateRoot(ctx), STATE_SUBDIR);
2838
+ return {
2839
+ ctx,
2840
+ host: createSmartExtractHost(ctx),
2841
+ continuation: createSmartExtractContinuationSigner(ctx),
2842
+ stateDir,
2843
+ outDir: join4(stateDir, "attachments")
2844
+ };
2845
+ }
2846
+ async function executeAndPrint(ctx, operation, input) {
2847
+ try {
2848
+ const definition = getSmartExtractOperation(operation);
2849
+ const result = await definition.handler(input, contextOf(ctx));
2850
+ ctx.output.write({
2851
+ schemaVersion: 1,
2852
+ ok: true,
2853
+ operation,
2854
+ risk: definition.risk,
2855
+ data: result.data === void 0 ? null : result.data,
2856
+ ...result.meta ? { meta: result.meta } : {},
2857
+ warnings: result.warnings ?? []
2858
+ }, { json: true });
2859
+ } catch (error) {
2860
+ ctx.output.write({ schemaVersion: 1, ok: false, operation, error: toErrorEnvelope(error) }, { json: true });
2861
+ process.exitCode = isCliError(error) ? error.exitCode : 1 /* GeneralError */;
2862
+ }
2863
+ }
2864
+ var smartExtractShortcut = {
2865
+ name: "smart-extract",
2866
+ description: "E10 \u667A\u80FD\u62BD\u53D6 CLI\uFF08fill \u4E00\u6B21\u53D6\u9F50\u5165\u53C2 \u2192 fill.save \u6821\u9A8C+\u843D\u5E93+\u56DE\u67E5\uFF0C\u8FD4\u56DE aiExtraId\uFF09",
2867
+ category: "shortcut",
2868
+ register({ program, action }) {
2869
+ assertManifestMatchesRegistry();
2870
+ const command = program.command("smart-extract").description("E10 \u667A\u80FD\u62BD\u53D6\uFF1Afill \u4E00\u6B21\u53D6\u9F50\u7ED3\u6784\u4E0E\u9644\u4EF6\u6B63\u6587\uFF0Cfill.save \u6821\u9A8C+\u843D\u5E93+\u56DE\u67E5\uFF1B\u5176\u4F59\u4E3A\u6392\u969C\u547D\u4EE4");
2871
+ command.command("schema").description("\u8F93\u51FA operation \u5408\u7EA6\uFF08Agent \u81EA\u67E5\u5165\u53E3\uFF09").action(action((ctx) => {
2872
+ ctx.output.write(smartExtractManifest, { json: true });
2873
+ }));
2874
+ command.command("run").description("\u6309 operation \u540D\u6267\u884C\uFF0C\u4F8B\u5982 smart-extract.form.structure").argument("<operation>", "operation \u540D\uFF0C\u89C1 schema \u8F93\u51FA").option("--input <path>", "JSON \u5165\u53C2\u6587\u4EF6\uFF0C- \u8868\u793A stdin").option("--input-json <json>", "\u5185\u8054 JSON \u5165\u53C2").action(action(async (ctx, operation, options) => {
2875
+ const opts = asOptions(options);
2876
+ await executeAndPrint(ctx, String(operation), await inputFrom(opts));
2877
+ }));
2878
+ }
2879
+ };
2880
+ export {
2881
+ smartExtractShortcut
2882
+ };