weaver-work-cli 0.1.44 → 0.1.46

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 (241) hide show
  1. package/README.md +9 -5
  2. package/dist/chunks/{archive-P6TBQGKL.js → archive-ZQ4A4TV6.js} +388 -44
  3. package/dist/chunks/{archive-oa-7TQ2NXOH.js → archive-oa-BBDP7AKJ.js} +2 -2
  4. package/dist/chunks/{asset-3ELRG37G.js → asset-ZOJVBWZH.js} +2 -2
  5. package/dist/chunks/{asset-idle-WIGMUFMD.js → asset-idle-XGB5IPGT.js} +2 -2
  6. package/dist/chunks/{attachment-content-E3276UOV.js → attachment-content-MCXQBD6N.js} +3 -3
  7. package/dist/chunks/{blog-C5NMZAAC.js → blog-QSHLZSFW.js} +2 -2
  8. package/dist/chunks/caizhilian-KCQYFH72.js +204 -0
  9. package/dist/chunks/{calendar-FI2WNSBO.js → calendar-DLGMRJQA.js} +2 -2
  10. package/dist/chunks/{chunk-PUQS5MWL.js → chunk-3YV7PKRL.js} +1 -1
  11. package/dist/chunks/{chunk-FAZTGX7S.js → chunk-4RWS2YYL.js} +5 -5
  12. package/dist/chunks/{chunk-GM6J7Q4B.js → chunk-6AXKWFKG.js} +32 -12
  13. package/dist/chunks/{chunk-ETNJSKMM.js → chunk-6NXT4ICB.js} +148 -21
  14. package/dist/chunks/{chunk-QVSWRLLU.js → chunk-6V5ZPKHV.js} +56 -12
  15. package/dist/chunks/chunk-762M5XJS.js +215 -0
  16. package/dist/chunks/{chunk-PC7VKEB5.js → chunk-76H3IKH6.js} +178 -37
  17. package/dist/chunks/{chunk-FRZKBMSW.js → chunk-AD46OMQK.js} +239 -41
  18. package/dist/chunks/{chunk-WSF4NNMR.js → chunk-CZNZKOHR.js} +2 -2
  19. package/dist/chunks/{chunk-TA7FXXJD.js → chunk-DLY5GUXX.js} +1 -1
  20. package/dist/chunks/{chunk-BCVYBYYT.js → chunk-GR76ZDDX.js} +2 -2
  21. package/dist/chunks/{chunk-CWYGFU5B.js → chunk-GSZTA43P.js} +2 -2
  22. package/dist/chunks/{chunk-GRDRG6HP.js → chunk-HFXK54M4.js} +2 -2
  23. package/dist/chunks/{chunk-N4M2DDFE.js → chunk-IP4CWQCF.js} +11 -11
  24. package/dist/chunks/{chunk-GAMZLAG2.js → chunk-IRMIEDXN.js} +1 -1
  25. package/dist/chunks/{chunk-XNIK66I4.js → chunk-JB34OE7R.js} +790 -77
  26. package/dist/chunks/{chunk-HIT4Y6OI.js → chunk-JFAWZX53.js} +134 -13
  27. package/dist/chunks/{chunk-D4ADSZ7H.js → chunk-O6CMPO65.js} +24 -1
  28. package/dist/chunks/{chunk-Z7VYWPZV.js → chunk-OXHHJWNC.js} +1 -1
  29. package/dist/chunks/chunk-P5GQRWDC.js +60 -0
  30. package/dist/chunks/{caizhilian-5XSM2DFP.js → chunk-PGO4ILMQ.js} +41 -521
  31. package/dist/chunks/{chunk-OF4S23UB.js → chunk-PSOMGA3U.js} +4 -4
  32. package/dist/chunks/{chunk-F4E4EM35.js → chunk-TGAGQV4I.js} +2 -2
  33. package/dist/chunks/{chunk-UFIT2UU3.js → chunk-U6R6FZHD.js} +168 -14
  34. package/dist/chunks/{chunk-XHK4MDR5.js → chunk-UFIFZ4YC.js} +48 -14
  35. package/dist/chunks/chunk-VRPH24IC.js +76 -0
  36. package/dist/chunks/{chunk-3YBDYOC4.js → chunk-YIKSL36S.js} +2 -2
  37. package/dist/chunks/{chunk-IAZ3UPY6.js → chunk-Z6UUBY37.js} +2 -2
  38. package/dist/chunks/{conflict-ARLSZJ6V.js → conflict-H7EHQXYY.js} +2 -2
  39. package/dist/chunks/continuation-GW6PRWK3.js +12 -0
  40. package/dist/chunks/{contract-DNIIW5VJ.js → contract-3QLAGYQL.js} +5793 -4591
  41. package/dist/chunks/{cowork-GMLRGVIW.js → cowork-3ACICHDQ.js} +2 -2
  42. package/dist/chunks/{create-flow-J22BO65E.js → create-flow-VRVJEOBX.js} +6 -6
  43. package/dist/chunks/{ebuilder-form-ANV2FHYV.js → ebuilder-form-GWDTKEI2.js} +5 -5
  44. package/dist/chunks/{ehr-GSTGAIY3.js → ehr-SH2LM3NK.js} +648 -88
  45. package/dist/chunks/{employee-22BGJ3QS.js → employee-NOHNXC46.js} +1 -1
  46. package/dist/chunks/{env-BX3VRFS7.js → env-66FPSJDV.js} +2 -2
  47. package/dist/chunks/{esb-ATAIASX2.js → esb-4BQHNP5C.js} +4 -4
  48. package/dist/chunks/{factory-PETTFME6.js → factory-UH2TZBVA.js} +1 -1
  49. package/dist/chunks/{fna-YEKBSFSX.js → fna-ZVB2IILI.js} +2 -2
  50. package/dist/chunks/{group-chat-BFVXAYFX.js → group-chat-CAKMMV7K.js} +3 -3
  51. package/dist/chunks/{host-WIKN2EJ5.js → host-3TNBMDTR.js} +3 -3
  52. package/dist/chunks/host-7NTIBSPK.js +25 -0
  53. package/dist/chunks/{host-SZGV4UNT.js → host-7OWWPLM4.js} +3 -3
  54. package/dist/chunks/{host-HRBXEPDQ.js → host-G3VU7SDW.js} +3 -3
  55. package/dist/chunks/{host-LR55CTHP.js → host-M4XP5URR.js} +3 -3
  56. package/dist/chunks/{host-SUOY6VYQ.js → host-TUOIOEMC.js} +3 -3
  57. package/dist/chunks/{hrm-NRDO4W5G.js → hrm-UNKCCCGP.js} +5 -5
  58. package/dist/chunks/{im-IQ2HN23S.js → im-NJB7ZYMH.js} +3 -3
  59. package/dist/chunks/{invoice-MNRW76PP.js → invoice-OQP3TMKQ.js} +3 -3
  60. package/dist/chunks/{jiuchuanhui-DTRBAX4N.js → jiuchuanhui-ASFZBMPU.js} +2 -2
  61. package/dist/chunks/{lazy-dispatch-ZVWAI25B.js → lazy-dispatch-DD6ULZ3I.js} +4 -4
  62. package/dist/chunks/{mail-ZVAUXOJA.js → mail-M3HJF5ER.js} +2 -2
  63. package/dist/chunks/{meeting-FEVPZ67S.js → meeting-VTBFW4HI.js} +12 -12
  64. package/dist/chunks/{okr-SDH3E5RA.js → okr-EVX7FB5G.js} +2 -2
  65. package/dist/chunks/operations-J7PUIVWZ.js +15 -0
  66. package/dist/chunks/{plan-E35JFDI7.js → plan-2QJQEPBO.js} +2 -2
  67. package/dist/chunks/{project-73QXBAB2.js → project-XELELW2T.js} +2 -2
  68. package/dist/chunks/{reception-UWZVACBN.js → reception-5WITA44R.js} +2 -2
  69. package/dist/chunks/{recruit-stage-4MAOCKFY.js → recruit-stage-CAKZTUA7.js} +1343 -178
  70. package/dist/chunks/{registry-JDUS4E7D.js → registry-AQVGHUM6.js} +2 -2
  71. package/dist/chunks/{registry-IM5G23LS.js → registry-JVQBLFQ5.js} +10 -10
  72. package/dist/chunks/{registry-KNKSCJNT.js → registry-QJCZ2GVG.js} +4 -4
  73. package/dist/chunks/{registry-PO7SI256.js → registry-VWXWPVAG.js} +2 -2
  74. package/dist/chunks/{room-recommend-H7KLXA5R.js → room-recommend-5U55FMXZ.js} +6 -4
  75. package/dist/chunks/{schedule-ESZIBAUO.js → schedule-IDETODCA.js} +4 -4
  76. package/dist/chunks/{workflow-CWJFJLQU.js → workflow-BSYT5TGL.js} +6 -4
  77. package/dist/cmd/action.js +14 -10
  78. package/dist/index.js +30 -30
  79. package/dist/internal/e10/auth/commands.js +32 -0
  80. package/dist/internal/e10/auth/error-log.js +156 -26
  81. package/dist/internal/e10/auth/xiaoe.js +176 -13
  82. package/dist/internal/e10/context.js +12 -1
  83. package/dist/shortcuts/archive/operations/borrow-list.js +105 -14
  84. package/dist/shortcuts/archive/operations/flow-url.js +182 -22
  85. package/dist/shortcuts/archive/operations/getPageUrl.js +75 -0
  86. package/dist/shortcuts/archive/operations/prelib.js +33 -4
  87. package/dist/shortcuts/archive/operations/shared.js +52 -0
  88. package/dist/shortcuts/contract/host.js +111 -4
  89. package/dist/shortcuts/contract/index.js +19 -0
  90. package/dist/shortcuts/contract/manifest.js +125 -0
  91. package/dist/shortcuts/contract/ooxml/clause-insert.js +249 -0
  92. package/dist/shortcuts/contract/operations/clause-insert.js +56 -0
  93. package/dist/shortcuts/contract/operations/customer.js +192 -0
  94. package/dist/shortcuts/contract/operations/file-download.js +75 -0
  95. package/dist/shortcuts/contract/operations/flow.js +44 -2
  96. package/dist/shortcuts/contract/operations/form-info.js +162 -62
  97. package/dist/shortcuts/contract/operations/registry.js +8 -0
  98. package/dist/shortcuts/contract/operations/review.js +116 -1
  99. package/dist/shortcuts/contract/operations/summary.js +177 -0
  100. package/dist/shortcuts/contract/operations/upload.js +64 -4
  101. package/dist/shortcuts/contract/upload-cache.js +104 -0
  102. package/dist/shortcuts/ehr/host.js +2 -2
  103. package/dist/shortcuts/ehr/index.js +14 -3
  104. package/dist/shortcuts/ehr/manifest.js +5 -1
  105. package/dist/shortcuts/ehr/operations/recruit-candidate-import.js +44 -12
  106. package/dist/shortcuts/ehr/operations/recruit-interview-overview.js +258 -0
  107. package/dist/shortcuts/ehr/operations/recruit-position.js +146 -43
  108. package/dist/shortcuts/ehr/operations/recruit-stats.js +14 -1
  109. package/dist/shortcuts/ehr/operations/recruit-tag.js +173 -0
  110. package/dist/shortcuts/ehr/operations/recruit-write.js +154 -36
  111. package/dist/shortcuts/ehr/operations/recruit.js +196 -12
  112. package/dist/shortcuts/ehr/operations/registry.js +4 -0
  113. package/dist/shortcuts/ehr/operations.js +24 -0
  114. package/dist/shortcuts/ehr/recruit-stage/batch-store.js +78 -0
  115. package/dist/shortcuts/ehr/recruit-stage/context.js +231 -0
  116. package/dist/shortcuts/ehr/recruit-stage/continuation.js +74 -0
  117. package/dist/shortcuts/ehr/recruit-stage/errors.js +65 -0
  118. package/dist/shortcuts/ehr/recruit-stage/fs-scan.js +165 -0
  119. package/dist/shortcuts/ehr/recruit-stage/host.js +109 -0
  120. package/dist/shortcuts/ehr/recruit-stage/operations/interview-arrange.js +1049 -0
  121. package/dist/shortcuts/ehr/recruit-stage/operations/interview-feedback.js +295 -0
  122. package/dist/shortcuts/ehr/recruit-stage/operations/jd-create.js +961 -0
  123. package/dist/shortcuts/ehr/recruit-stage/operations/list.js +431 -0
  124. package/dist/shortcuts/ehr/recruit-stage/operations/registry.js +50 -0
  125. package/dist/shortcuts/ehr/recruit-stage/operations/resume-import.js +1647 -0
  126. package/dist/shortcuts/ehr/recruit-stage/operations/search.js +158 -0
  127. package/dist/shortcuts/ehr/recruit-stage/operations/types.js +34 -0
  128. package/dist/shortcuts/ehr/recruit-stage/runtime.js +31 -0
  129. package/dist/shortcuts/ehr/recruit-stage/school-tiers.json +318 -0
  130. package/dist/shortcuts/ehr/recruit-stage/shared.js +805 -0
  131. package/dist/shortcuts/hrm/operations/employee.js +29 -1
  132. package/dist/shortcuts/meeting/operations/eb/create-flow.js +274 -75
  133. package/dist/shortcuts/meeting/operations/eb/draft-memory.js +56 -0
  134. package/dist/shortcuts/meeting/operations/eb/factory.js +63 -11
  135. package/dist/shortcuts/meeting/operations/eb/person-cache.js +2 -2
  136. package/dist/shortcuts/meeting/operations/eb/room-recommend.js +38 -7
  137. package/dist/shortcuts/meeting/operations/invitation-publish.js +132 -0
  138. package/dist/shortcuts/meeting/operations/invitation.js +27 -4
  139. package/dist/shortcuts/meeting/operations/registry.js +2 -0
  140. package/dist/shortcuts/recruit-stage/batch-store.js +78 -0
  141. package/dist/shortcuts/recruit-stage/fs-scan.js +165 -0
  142. package/dist/shortcuts/recruit-stage/operations/interview-arrange.js +356 -29
  143. package/dist/shortcuts/recruit-stage/operations/interview-feedback.js +36 -10
  144. package/dist/shortcuts/recruit-stage/operations/jd-create.js +309 -67
  145. package/dist/shortcuts/recruit-stage/operations/registry.js +12 -0
  146. package/dist/shortcuts/recruit-stage/operations/resume-import.js +310 -17
  147. package/dist/shortcuts/recruit-stage/operations/types.js +9 -0
  148. package/dist/shortcuts/recruit-stage/shared.js +221 -24
  149. package/dist/shortcuts/workflow/index.js +2 -0
  150. package/dist/shortcuts/workflow/operations/read.js +8 -3
  151. package/dist/shortcuts/workflow/operations/todoSmartConvert/aigroupRules.js +92 -5
  152. package/dist/shortcuts/workflow/operations/todoSmartConvert/priorityExpr.js +509 -0
  153. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoListRows.js +22 -1
  154. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.collect.js +32 -6
  155. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.core.js +57 -11
  156. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.group.js +165 -52
  157. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.js +57 -14
  158. package/dist/shortcuts/workflow/operations/todoSmartConvert/todoSmartConvert.smartGroup.js +44 -18
  159. package/docs/contract.md +1 -0
  160. package/docs/e10-auth.md +4 -2
  161. package/docs/todo-smart-convert/data-contract.md +7 -0
  162. package/package.json +1 -1
  163. package/skill-template/domains/jinchengda.md +2 -0
  164. package/skills/weaver-e10-jinchengda/SKILL.md +198 -205
  165. package/skills/weaver-e10-jinchengda/references/contract-action-card.md +759 -0
  166. package/skills/weaver-e10-jinchengda/references/contract-action-engine.md +250 -0
  167. package/skills/weaver-e10-jinchengda/references/contract-ai-review.md +146 -7
  168. package/skills/weaver-e10-jinchengda/references/contract-clause-insert.md +178 -0
  169. package/skills/weaver-e10-jinchengda/references/contract-command-index.md +75 -0
  170. package/skills/weaver-e10-jinchengda/references/contract-compare-report-template.html +137 -0
  171. package/skills/weaver-e10-jinchengda/references/contract-compare-report.md +163 -0
  172. package/skills/weaver-e10-jinchengda/references/contract-credit-page.md +52 -3
  173. package/skills/weaver-e10-jinchengda/references/contract-doc-compare.md +92 -5
  174. package/skills/weaver-e10-jinchengda/references/contract-doc-triage.md +602 -0
  175. package/skills/weaver-e10-jinchengda/references/contract-element-extract.md +209 -0
  176. package/skills/weaver-e10-jinchengda/references/contract-execution-rules.md +126 -0
  177. package/skills/weaver-e10-jinchengda/references/contract-field-extract-new-customer.md +312 -0
  178. package/skills/weaver-e10-jinchengda/references/contract-field-extract-other-flows.md +555 -0
  179. package/skills/weaver-e10-jinchengda/references/contract-flow-launch.md +47 -12
  180. package/skills/weaver-e10-jinchengda/references/contract-object-detect.md +469 -0
  181. package/skills/weaver-e10-jinchengda/references/contract-quote-to-contract.md +154 -1
  182. package/skills/weaver-e10-jinchengda/references/contract-type-fingerprints.md +224 -0
  183. package/skills/weaver-e10-jinchengda/references/orchestration.md +355 -0
  184. package/skills/weaver-e10-jucailin/SKILL.md +12 -3
  185. package/skills/weaver-e10-jucailin/archive/LEGACY-README.md +18 -0
  186. package/skills/weaver-e10-jucailin/archive/LEGACY-SKILL.md +239 -0
  187. package/skills/weaver-e10-jucailin/archive/LEGACY-openai.yaml +131 -0
  188. package/skills/weaver-e10-jucailin/archive/LEGACY-position-templates.md +221 -0
  189. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-arrange-interview.md +334 -0
  190. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-capability-check.md +127 -0
  191. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-check-install.md +65 -0
  192. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-detail-process.md +63 -0
  193. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-edit-interview-feedback.md +142 -0
  194. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-jd-create.md +114 -0
  195. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-jd-template.md +56 -0
  196. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-list-candidate.md +101 -0
  197. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-list-interview.md +148 -0
  198. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-match-candidates.md +77 -0
  199. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-output-links.md +72 -0
  200. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-resolve-creator.md +69 -0
  201. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-resolve-metadata.md +241 -0
  202. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-resume-import.md +457 -0
  203. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-resume-parse.md +128 -0
  204. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-search-candidate.md +146 -0
  205. package/skills/weaver-e10-jucailin/archive/LEGACY-recruit-urge-feedback.md +69 -0
  206. package/skills/weaver-e10-jucailin/lib/recruit-xiaoe-file.mjs +192 -0
  207. package/skills/weaver-e10-jucailin/lib/xiaoe-session.mjs +66 -0
  208. package/skills/weaver-e10-jucailin/references/recruit-create.md +19 -91
  209. package/skills/weaver-e10-jucailin/references/recruit-interview-overview.md +64 -0
  210. package/skills/weaver-e10-jucailin/references/recruit-read.md +63 -1
  211. package/skills/weaver-e10-jucailin/references/recruit-screening-to-interview-sop.md +95 -0
  212. package/skills/weaver-e10-jucailin/references/recruit-stage-ops.md +89 -0
  213. package/skills/weaver-e10-jucailin/references/recruit-tag.md +81 -0
  214. package/skills/weaver-e10-jucailin/references/recruit-write.md +55 -11
  215. package/skills/weaver-e10-meeting/SKILL.md +103 -11
  216. package/skills/weaver-e10-meeting/references/meeting-eb.md +1 -1
  217. package/skills/weaver-e10-recruit-stage/SKILL.md +19 -11
  218. package/skills/weaver-e10-recruit-stage/agents/openai.yaml +26 -8
  219. package/skills/weaver-e10-recruit-stage/lib/recruit-xiaoe-file.mjs +5 -1
  220. package/skills/weaver-e10-recruit-stage/references/position-templates.md +23 -2
  221. package/skills/weaver-e10-recruit-stage/references/recruit-arrange-interview.md +13 -1
  222. package/skills/weaver-e10-recruit-stage/references/recruit-jd-create.md +40 -18
  223. package/skills/weaver-e10-recruit-stage/references/recruit-output-links.md +27 -14
  224. package/skills/weaver-e10-recruit-stage/references/recruit-resume-import.md +11 -1
  225. package/skills/weaver-e10-shared/references/e10-auth-and-session.md +4 -2
  226. package/skills/weaver-e10-wenshuding/SKILL.md +17 -7
  227. package/skills/weaver-e10-wenshuding/references/archive-borrow-list.md +28 -0
  228. package/skills/weaver-e10-wenshuding/references/archive-flow.md +24 -8
  229. package/skills/weaver-e10-wenshuding/references/archive-prelib-list.md +3 -0
  230. package/skills/weaver-e10-wenshuding/references/archive-prelib-open.md +4 -0
  231. package/skills/weaver-e10-wenshuding/references/archive-search.md +3 -1
  232. package/skills/weaver-e10-workflow/SKILL.md +19 -17
  233. package/skills/weaver-e10-workflow/aigroup/default.json +10 -6
  234. package/skills/weaver-e10-workflow/references/todo-smart-convert.md +36 -3
  235. package/skills/weaver-e10-workflow/references/workflow-memory.md +1 -1
  236. package/skills/weaver-e10-workflow/references/workflow-query.md +9 -6
  237. package/skills/weaver-e10-workflow/tools/todo-summary.cjs +152 -1
  238. package/skills/weaver-e10-yimiaoban/SKILL.md +17 -5
  239. package/skills/weaver-e10-yimiaoban/references/msg-write.md +30 -0
  240. package/skills/weaver-e10-yimiaoban/references/session-sysmsg.md +72 -0
  241. package/skills/weaver-e10-yimiaoban/references/source-manifest.json +7 -7
@@ -1,5 +1,5 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { basename } from 'node:path';
1
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { basename, dirname } from 'node:path';
3
3
  import { E10_SESSION_EXPIRED_MESSAGE } from '../../internal/e10/auth/messages.js';
4
4
  import { isE10SessionExpiredResponse, } from '../../internal/e10/auth-recovery.js';
5
5
  import { requireE10Session } from '../../internal/e10/context.js';
@@ -7,6 +7,10 @@ import { getActiveProfile } from '../../internal/e10/auth/session.js';
7
7
  import { E10ApiError, createE10RequestRuntime, } from '../../internal/e10/request-runtime.js';
8
8
  import { ContractCliError, contractAuthError, contractNetworkError, contractValidationError, } from './errors.js';
9
9
  const DEFAULT_TIMEOUT_MS = 30_000;
10
+ /** 文件下载超时:普通接口 30s 不够,大文件按 120s 走。 */
11
+ const DEFAULT_DOWNLOAD_TIMEOUT_MS = 120_000;
12
+ /** 单文件下载上限 200MB,与采知连附件下载口径一致。 */
13
+ const DEFAULT_MAX_DOWNLOAD_BYTES = 200 * 1024 * 1024;
10
14
  function assertPath(requestPath) {
11
15
  if (typeof requestPath !== 'string' || !requestPath.startsWith('/') || requestPath.startsWith('//')) {
12
16
  throw contractValidationError('path_invalid', '请求路径必须是相对绝对路径');
@@ -32,6 +36,8 @@ function textOf(value, keys) {
32
36
  * 因此 0 与 200 均视为成功,并辅以 status/fail 判定
33
37
  * - /api/ebuilder/form/obj/getObjsByTag、/api/bs/ebuilder/app/tags/getAppIds、
34
38
  * /api/ebuilder/common/ds/fields、/api/ebuilder/common/ds/options:顶层 code = 200 且 status 不为 false
39
+ * - /api/ebuilder/form/common/browser/**(表单浏览补全):同样是顶层 code = 0/200 且 status 不为 false,
40
+ * 但没有 message 节点也没有 errcode——不单独分组就会被末尾兜底判成失败
35
41
  * - /api/ebuilder/form/dataset/v2/**:message.code = "0"
36
42
  * - /api/workflow/**:message.errcode = "0"(getFieldOption 上游文档示例为 200,同样视为成功)
37
43
  * - /api/workflow/core/flowPage/**、/api/workflow/core/form/**、/api/ebuilder/flow/form/**
@@ -64,6 +70,15 @@ export function contractBusinessStatus(path, value) {
64
70
  const ok = (code === 0 || code === '0' || code === 200 || code === '200') && root.status !== false && root.fail !== true;
65
71
  return { ok, code: code === undefined ? undefined : String(code), message: textOf(root, ['msg', 'message']) ?? textOf(messageNode, ['errmsg', 'msg']) };
66
72
  }
73
+ // 表单浏览补全 browser/complete:与 getObjsByTag 同一族形状——顶层 code=200、无 message 节点、
74
+ // 也没有 errcode。落到末尾兜底分支会因 errcode === undefined 被判成失败,必须在这里拦下来。
75
+ if (path.startsWith('/api/ebuilder/form/common/browser/')) {
76
+ const code = root.code ?? messageNode.code ?? messageNode.errcode;
77
+ const ok = (code === 0 || code === '0' || code === 200 || code === '200')
78
+ && root.status !== false
79
+ && root.fail !== true;
80
+ return { ok, code: code === undefined ? undefined : String(code), message: textOf(root, ['msg', 'message']) ?? textOf(messageNode, ['errmsg', 'msg']) };
81
+ }
67
82
  if (path === '/api/ebuilder/form/obj/getObjsByTag'
68
83
  || path === '/api/bs/ebuilder/app/tags/getAppIds'
69
84
  || path === '/api/ebuilder/common/ds/fields'
@@ -121,7 +136,7 @@ export function createContractHost(ctx, dependencies = {}) {
121
136
  return sessionContext;
122
137
  }
123
138
  async function contractRequest(request) {
124
- const { method = 'POST', path, query = {}, body, form, file, headers: extraHeaders, userIdField, timeoutMs = DEFAULT_TIMEOUT_MS, } = request;
139
+ const { method = 'POST', path, query = {}, body, form, file, headers: extraHeaders, userIdField, timeoutMs = DEFAULT_TIMEOUT_MS, okOnHttpSuccess = false, } = request;
125
140
  assertPath(path);
126
141
  const session = await ensureSession();
127
142
  const context = await getSession();
@@ -197,6 +212,10 @@ export function createContractHost(ctx, dependencies = {}) {
197
212
  exitCode: 1,
198
213
  });
199
214
  }
215
+ // 触发型接口:HTTP 2xx 即成功,空响应体也是正确结果,不再走业务码判定。
216
+ if (okOnHttpSuccess) {
217
+ return value;
218
+ }
200
219
  const status = contractBusinessStatus(path, value);
201
220
  if (!status.ok) {
202
221
  const rawPreview = typeof text === 'string' ? text.slice(0, 500) : '';
@@ -208,5 +227,93 @@ export function createContractHost(ctx, dependencies = {}) {
208
227
  }
209
228
  return value;
210
229
  }
211
- return { contractRequest, getSession };
230
+ /**
231
+ * 二进制下载通道。
232
+ *
233
+ * 刻意与 `contractRequest` 分离,原因有三:
234
+ * 1. `contractRequest` 强制 `response.text()` + `JSON.parse`,文件字节流过不去;
235
+ * 2. 它的成功判据走 `contractBusinessStatus`,而文件服务没有统一业务码,硬套会把成功判成失败;
236
+ * 3. 下载要跟重定向(302 → 登录页 / CDN),`contractRequest` 对 302 直接抛 session_expired。
237
+ *
238
+ * 认证与重定向**完全复用** `createE10RequestRuntime().requestBinary()`:同一套 auth 头、
239
+ * 超时控制,以及下载重定向跟随(同源带 Cookie/eteamsid、跨域对象存储不带任何会话凭证),
240
+ * 不另读凭证、也不复写一遍低层 fetch 逻辑。
241
+ */
242
+ async function contractDownloadToFile(request) {
243
+ const { path, query = {}, headers: extraHeaders, savePath, maxBytes = DEFAULT_MAX_DOWNLOAD_BYTES, timeoutMs = DEFAULT_DOWNLOAD_TIMEOUT_MS, } = request;
244
+ assertPath(path);
245
+ if (!savePath || typeof savePath !== 'string') {
246
+ throw contractValidationError('save_path_required', '下载必须提供本地保存路径');
247
+ }
248
+ const session = await ensureSession();
249
+ const runtime = createE10RequestRuntime(ctx, session, {
250
+ interceptors: dependencies.interceptors,
251
+ fetch: dependencies.fetch,
252
+ recoverAuthentication: dependencies.recoverAuthentication,
253
+ });
254
+ let response;
255
+ try {
256
+ response = await runtime.requestBinary({
257
+ module: 'contract',
258
+ method: 'GET',
259
+ path,
260
+ query,
261
+ headers: extraHeaders,
262
+ timeoutMs,
263
+ });
264
+ }
265
+ catch (error) {
266
+ if (error instanceof E10ApiError && error.type === 'network') {
267
+ throw contractNetworkError(error.subtype, error.message, {
268
+ retryable: error.retryable,
269
+ details: error.details,
270
+ });
271
+ }
272
+ throw error;
273
+ }
274
+ // requestBinary 内部已跟随下载重定向(302 → 文件服务/CDN)。这里还残留的
275
+ // 302 只可能是登录跳转(运行时判定为 login 不跟随),按登录失效处理。
276
+ if (response.status === 302) {
277
+ throw contractAuthError('session_expired', '下载接口跳转到登录页,登录态未被接受;请先完成 E10 登录后重试', { httpStatus: response.status, path });
278
+ }
279
+ if (response.status === 401 || response.status === 403) {
280
+ throw contractAuthError('session_expired', 'E10 登录态不可用于文件下载,或当前账号对该文件没有下载权限', { httpStatus: response.status, path });
281
+ }
282
+ if (response.status < 200 || response.status >= 300) {
283
+ throw new ContractCliError('api', 'http_error', `文件下载失败,HTTP ${response.status}`, {
284
+ code: response.status,
285
+ details: { path, status: response.status },
286
+ exitCode: 1,
287
+ });
288
+ }
289
+ const contentType = response.contentType;
290
+ // 服务端把登录页/错误页当 200 返回时,content-type 是 html,不能当文件落盘。
291
+ if (contentType && /text\/html/i.test(contentType)) {
292
+ const preview = response.content.subarray(0, 200).toString('utf8').replace(/\s+/g, ' ');
293
+ throw new ContractCliError('api', 'not_a_file', '返回的是 HTML 页面而不是文件,登录态或下载权限不足', {
294
+ details: { path, contentType, preview },
295
+ exitCode: 1,
296
+ });
297
+ }
298
+ const declared = Number(response.headers.get('content-length') ?? '');
299
+ if (Number.isFinite(declared) && declared > maxBytes) {
300
+ throw contractValidationError('file_too_large', `文件超过下载上限 ${Math.round(maxBytes / 1024 / 1024)}MB`);
301
+ }
302
+ const buffer = response.content;
303
+ if (buffer.length === 0) {
304
+ throw new ContractCliError('api', 'empty_file', '下载结果为空文件', {
305
+ details: { path, contentType },
306
+ exitCode: 1,
307
+ });
308
+ }
309
+ if (buffer.length > maxBytes) {
310
+ throw contractValidationError('file_too_large', `文件超过下载上限 ${Math.round(maxBytes / 1024 / 1024)}MB`);
311
+ }
312
+ const directory = dirname(savePath);
313
+ if (directory)
314
+ await mkdir(directory, { recursive: true });
315
+ await writeFile(savePath, buffer);
316
+ return { filePath: savePath, fileSize: buffer.length, contentType: contentType ?? null };
317
+ }
318
+ return { contractRequest, getSession, contractDownloadToFile };
212
319
  }
@@ -187,6 +187,7 @@ export const contractShortcut = {
187
187
  { flag: '--page-no <n>', description: 'page number', key: 'pageNo', kind: 'int' },
188
188
  { flag: '--page-size <n>', description: 'page size', key: 'pageSize', kind: 'int' },
189
189
  ]);
190
+ registerCommand(clause, 'insert', 'Insert clauses into a contract docx (locate by chapter, dedupe)', 'contract.clause.insert');
190
191
  registerCommand(clause, 'search', 'Search clauses', 'contract.clause.search', [
191
192
  { flag: '--title <title>', description: 'clause title keyword', key: 'title' },
192
193
  { flag: '--tag-id <id>', description: 'clause tag id', key: 'tagId' },
@@ -351,6 +352,12 @@ export const contractShortcut = {
351
352
  const review = contract.command('review').description('Contract AI review commands');
352
353
  // paths 是数组,子命令只提供 JSON 输入入口,避免把路径拆成多个位置参数。
353
354
  registerCommand(review, 'upload', 'Upload contracts and get the AI review page url', 'contract.review.upload');
355
+ registerCommand(review, 'prewarm', 'Trigger contract review prewarm for one fileId', 'contract.review.prewarm', [
356
+ { flag: '--file-id <id>', description: 'uploaded file id', key: 'fileId' },
357
+ ]);
358
+ registerCommand(review, 'prewarm-batch', 'Trigger review prewarm for multiple fileIds (parallel)', 'contract.review.prewarm.batch', [
359
+ { flag: '--file-ids <json>', description: 'JSON array of file ids', key: 'fileIds' },
360
+ ]);
354
361
  registerCommand(review, 'export', 'Export AI review records', 'contract.review.export', [
355
362
  { flag: '--file-id <id>', description: 'contract file id', key: 'fileId' },
356
363
  { flag: '--sclx <types>', description: '1 risk, 2 legal, 3 proofreading', key: 'sclx' },
@@ -442,6 +449,18 @@ export const contractShortcut = {
442
449
  { flag: '--contract-numbers <json>', description: 'contract numbers JSON array', key: 'contractNumbers' },
443
450
  { flag: '--page-size <n>', description: 'page size', key: 'pageSize', kind: 'int' },
444
451
  ]);
452
+ const summary = contract.command('summary').description('Contract summary rendering commands (local)');
453
+ registerCommand(summary, 'render', 'Render summary data JSON into an HTML file (local)', 'contract.summary.render', [
454
+ { flag: '--data <file>', description: 'summary data JSON path', key: 'data' },
455
+ { flag: '--out <file>', description: 'output HTML path', key: 'out' },
456
+ ]);
457
+ const file = contract.command('file').description('Contract file download commands (binary)');
458
+ registerCommand(file, 'download', 'Download an E10 file to a local path', 'contract.file.download', [
459
+ { flag: '--file-id <id>', description: 'E10 file id (template / attachment / review file)', key: 'fileId' },
460
+ { flag: '--module <name>', description: 'ebContract / workflow / docCompared / ebuilderform', key: 'module' },
461
+ { flag: '--save-path <path>', description: 'local absolute save path', key: 'savePath' },
462
+ { flag: '--max-bytes <n>', description: 'max file size in bytes, default 200MB', key: 'maxBytes', kind: 'int' },
463
+ ]);
445
464
  const quote = contract.command('quote').description('Quote-to-contract commands (local xlsx/docx)');
446
465
  registerCommand(quote, 'rmb', 'Convert a number to RMB uppercase (local)', 'contract.quote.rmb', [
447
466
  { flag: '--num <value>', description: 'number', key: 'num' },
@@ -434,6 +434,31 @@ const quoteContracts = [
434
434
  fixed: { local: true, kind: 'rmb-upper' },
435
435
  inputSchema: readSchema({ num: { type: 'string', minLength: 1 } }, ['num']),
436
436
  },
437
+ {
438
+ name: 'contract.summary.render',
439
+ risk: 'local-file-write',
440
+ fixed: { local: true, kind: 'summary-render' },
441
+ inputSchema: readSchema({
442
+ data: { type: 'string', minLength: 1, maxLength: 4096, description: '摘要数据 JSON 文件路径' },
443
+ out: { type: 'string', minLength: 1, maxLength: 4096, description: '输出 HTML 绝对路径' },
444
+ }, ['data', 'out']),
445
+ },
446
+ {
447
+ name: 'contract.file.download',
448
+ risk: 'local-file-write',
449
+ auth: AUTH,
450
+ fixed: { local: true, kind: 'file-download', method: 'GET' },
451
+ inputSchema: readSchema({
452
+ fileId: { ...idString, description: 'E10 文件 ID(模板 fileId、附件 id、审查 fileId)' },
453
+ module: {
454
+ type: 'string',
455
+ enum: ['ebContract', 'workflow', 'docCompared', 'ebuilderform'],
456
+ description: '文件所属模块,合同模板用 ebContract',
457
+ },
458
+ savePath: { type: 'string', minLength: 1, maxLength: 4096, description: '本地保存绝对路径' },
459
+ maxBytes: { type: 'integer', minimum: 1, maximum: 209715200, description: '单文件大小上限,默认 200MB' },
460
+ }, ['fileId', 'savePath']),
461
+ },
437
462
  {
438
463
  name: 'contract.quote.sheets',
439
464
  risk: 'read-with-upload',
@@ -464,6 +489,27 @@ const quoteContracts = [
464
489
  }, ['template', 'data', 'out']),
465
490
  },
466
491
  ];
492
+ // ---------------------------------------------------------------- 客户主数据查询(按全称)
493
+ //
494
+ // 编排层 S2(对象识别)的取数入口:把「最终用户」全称丢进来,判断有没有匹配到客户主数据。
495
+ // 走表单浏览补全接口而非 subject.query —— 客户主数据的 objId/appId 是环境值,只能由服务端
496
+ // 从 fieldId 现场解析,不能硬编码,也不能靠 getObjsByTag 发现(它挂在别的应用下)。
497
+ // 只接受全称:空关键词在这条接口上是"按顺序返回前若干条",会把任意主体当命中。
498
+ const contractCustomerOperationContracts = [
499
+ {
500
+ name: 'contract.customer.browser',
501
+ risk: 'read',
502
+ auth: AUTH,
503
+ fixed: { method: 'POST', path: '/api/ebuilder/form/common/browser/complete/ebuilder' },
504
+ inputSchema: readSchema({
505
+ searchValue: { type: 'string', minLength: 1, maxLength: 100, description: '客户全称(必填、不可为空)。只做全称查询:空关键词会返回无关的前若干条,会把新老客户判错' },
506
+ workflowId: idString,
507
+ fieldName: { type: 'string', maxLength: 50, description: '客户字段名;缺省按「客户名称 / 最终用户名称 / 最终用户 / 客户」依次匹配' },
508
+ fieldId: idString,
509
+ pageSize: { type: 'integer', minimum: 1, maximum: 50 },
510
+ }, ['searchValue', 'workflowId']),
511
+ },
512
+ ];
467
513
  export const contractOperations = [
468
514
  {
469
515
  name: 'contract.type.tree',
@@ -1020,6 +1066,8 @@ export const contractOperations = [
1020
1066
  module: 'ebContract',
1021
1067
  createDoc: true,
1022
1068
  pagePath: '/sp/contract/business/ai-contract',
1069
+ prewarmPath: '/api/ebd/contract/ai/saveInternalRecord',
1070
+ prewarmFlowId: '1269716062340284522',
1023
1071
  },
1024
1072
  inputSchema: readSchema({
1025
1073
  paths: {
@@ -1028,8 +1076,46 @@ export const contractOperations = [
1028
1076
  maxItems: 10,
1029
1077
  items: { type: 'string', minLength: 1, maxLength: 1000 },
1030
1078
  },
1079
+ prewarm: {
1080
+ type: 'boolean',
1081
+ description: '默认 true:上传成功即触发预审预热;传 false 可关闭',
1082
+ },
1031
1083
  }, ['paths']),
1032
1084
  },
1085
+ {
1086
+ name: 'contract.review.prewarm',
1087
+ risk: 'write',
1088
+ auth: AUTH,
1089
+ fixed: {
1090
+ method: 'POST',
1091
+ path: '/api/ebd/contract/ai/saveInternalRecord',
1092
+ flowId: '1269716062340284522',
1093
+ purpose: '合同预审预处理:提前启动预审,打开审查页时结果已就绪',
1094
+ },
1095
+ inputSchema: readSchema({
1096
+ fileId: { ...idString, description: '上传返回的 fileId' },
1097
+ }, ['fileId']),
1098
+ },
1099
+ {
1100
+ name: 'contract.review.prewarm.batch',
1101
+ risk: 'write',
1102
+ auth: AUTH,
1103
+ fixed: {
1104
+ method: 'POST',
1105
+ path: '/api/ebd/contract/ai/saveInternalRecord',
1106
+ flowId: '1269716062340284522',
1107
+ parallel: true,
1108
+ },
1109
+ inputSchema: readSchema({
1110
+ fileIds: {
1111
+ type: 'array',
1112
+ minItems: 1,
1113
+ maxItems: 10,
1114
+ items: idString,
1115
+ description: '批量预热的 fileId 列表',
1116
+ },
1117
+ }, ['fileIds']),
1118
+ },
1033
1119
  {
1034
1120
  name: 'contract.review.export',
1035
1121
  risk: 'read',
@@ -1054,6 +1140,19 @@ export const contractOperations = [
1054
1140
  flow: { type: 'string', enum: ['契约锁', '新客户', '老客户增值', '常规二次销售'] },
1055
1141
  }, ['flow']),
1056
1142
  },
1143
+ {
1144
+ name: 'contract.flow.upload-field',
1145
+ risk: 'read',
1146
+ auth: AUTH,
1147
+ fixed: {
1148
+ method: 'POST',
1149
+ path: '/api/workflow/core/flowPage/loadBaseParam',
1150
+ note: '诊断用:三段式读布局后解析主表附件字段(loadBaseParam -> loadFrameParam -> getFormLayout)',
1151
+ },
1152
+ inputSchema: readSchema({
1153
+ flow: { type: 'string', enum: ['契约锁', '新客户', '老客户增值', '常规二次销售'] },
1154
+ }, ['flow']),
1155
+ },
1057
1156
  {
1058
1157
  name: 'contract.flow.launch',
1059
1158
  risk: 'read-with-upload',
@@ -1293,6 +1392,31 @@ export const contractOperations = [
1293
1392
  confirm: { type: 'boolean', enum: [true] },
1294
1393
  }, ['id', 'continuation', 'confirm']),
1295
1394
  },
1395
+ {
1396
+ name: 'contract.clause.insert',
1397
+ risk: 'local-file-write',
1398
+ fixed: { local: true, kind: 'clause-insert', dedupe: true, locateByChapter: true },
1399
+ inputSchema: readSchema({
1400
+ path: { type: 'string', minLength: 1, maxLength: 4096, description: '合同 docx 绝对路径' },
1401
+ out: { type: 'string', maxLength: 4096, description: '输出路径;缺省与 path 相同(原地覆盖)' },
1402
+ dryRun: { type: 'boolean', description: 'true 时只分析插入位置与去重,不写文件' },
1403
+ clauses: {
1404
+ type: 'array',
1405
+ minItems: 1,
1406
+ maxItems: 30,
1407
+ items: {
1408
+ type: 'object',
1409
+ additionalProperties: false,
1410
+ properties: {
1411
+ name: { type: 'string', minLength: 1, maxLength: 200 },
1412
+ content: { type: 'string', minLength: 1, maxLength: 20000 },
1413
+ anchor: { type: 'string', maxLength: 200, description: '锚点章节关键词,如「保密条款」' },
1414
+ },
1415
+ required: ['name', 'content'],
1416
+ },
1417
+ },
1418
+ }, ['path', 'clauses']),
1419
+ },
1296
1420
  {
1297
1421
  name: 'contract.clause.create.prepare',
1298
1422
  risk: 'read-before-write',
@@ -1487,6 +1611,7 @@ export const contractOperations = [
1487
1611
  confirm: { type: 'boolean', enum: [true] },
1488
1612
  }, ['id', 'continuation', 'confirm']),
1489
1613
  },
1614
+ ...contractCustomerOperationContracts,
1490
1615
  ...contractAssistantOperationContracts,
1491
1616
  ...performanceContracts,
1492
1617
  ...quoteContracts,
@@ -0,0 +1,249 @@
1
+ /**
2
+ * docx 条款插入引擎(零依赖,与 docx.ts 同一套正则分段扫描风格)。
3
+ *
4
+ * 职责:把「条款库推荐来的条款」插进一份真实合同 docx 的指定章节之后。
5
+ *
6
+ * 三个硬要求(业务侧明确提出):
7
+ * 1. **定位**:必须判断插入位置是哪个章节之后,不能一律追加到文末;
8
+ * 2. **去重**:合同里已有同名或实质相同的条款,不得重复插入;
9
+ * 3. **可选**:支持 dryRun 只出位置判断不落盘,便于先给用户确认。
10
+ *
11
+ * 只处理 word/document.xml;表格、页眉页脚、批注一概不碰。
12
+ */
13
+ import { readFileSync } from 'node:fs';
14
+ import { readZipEntry, rewriteZip } from './zip.js';
15
+ import { decodeXml, encodeXml } from './xlsx.js';
16
+ const CHAPTER_RE = /^\s*(第[一二三四五六七八九十百零〇\d]+[章节篇部分]|附件\s*[一二三四五六七八九十\d]+|\d+[、..]\s*\S)/u;
17
+ /**
18
+ * 读 styles.xml,构建 styleId → 样式名 映射。
19
+ *
20
+ * 必需原因(2026-11-03 实测):段落里 `<w:pStyle w:val="16">` 存的是**数字 styleId**,
21
+ * 不是可读样式名;而「一级」(正文标题)与「toc 1」「WPSOffice手动目录 1」(目录)
22
+ * 的区别**只体现在名称上**。不查这张表就无法把正文标题与目录区分开。
23
+ *
24
+ * 读不到 styles.xml 时返回空表,调用方退回文本判据。
25
+ */
26
+ function readStyleNameMap(buffer) {
27
+ const map = new Map();
28
+ let stylesXml = '';
29
+ try {
30
+ stylesXml = readZipEntry(buffer, 'word/styles.xml');
31
+ }
32
+ catch {
33
+ return map;
34
+ }
35
+ for (const m of stylesXml.matchAll(/<w:style\b[^>]*w:styleId="([^"]*)"[^>]*>([\s\S]*?)<\/w:style>/gu)) {
36
+ const id = m[1];
37
+ const nameMatch = /<w:name\s+w:val="([^"]*)"/u.exec(m[2]);
38
+ if (nameMatch)
39
+ map.set(id, nameMatch[1]);
40
+ }
41
+ return map;
42
+ }
43
+ function collectTopParagraphs(xml, styleMap = new Map()) {
44
+ // 先求出所有 w:tbl 的顶层范围,段落若落在表格内则跳过(表格内容不参与章节结构)。
45
+ const tables = [];
46
+ const tOpen = [...xml.matchAll(/<w:tbl(?:\s[^>]*)?>/gu)];
47
+ const tClose = [...xml.matchAll(/<\/w:tbl>/gu)];
48
+ const events = [
49
+ ...tOpen.map((m) => ({ pos: m.index ?? 0, open: true })),
50
+ ...tClose.map((m) => ({ pos: m.index ?? 0, open: false })),
51
+ ].sort((a, b) => a.pos - b.pos || (a.open ? -1 : 1));
52
+ let depth = 0;
53
+ let cur = -1;
54
+ for (const e of events) {
55
+ if (e.open) {
56
+ if (depth === 0)
57
+ cur = e.pos;
58
+ depth++;
59
+ }
60
+ else {
61
+ depth--;
62
+ if (depth === 0 && cur >= 0) {
63
+ tables.push({ start: cur, end: e.pos + '</w:tbl>'.length });
64
+ cur = -1;
65
+ }
66
+ }
67
+ }
68
+ const inTable = (pos) => tables.some((t) => pos >= t.start && pos < t.end);
69
+ const out = [];
70
+ const pOpen = [...xml.matchAll(/<w:p(?:\s[^>]*)?>/gu)];
71
+ for (const m of pOpen) {
72
+ const start = m.index ?? 0;
73
+ if (inTable(start))
74
+ continue;
75
+ const endIdx = xml.indexOf('</w:p>', start);
76
+ if (endIdx < 0)
77
+ continue;
78
+ const end = endIdx + '</w:p>'.length;
79
+ const pXml = xml.slice(start, end);
80
+ let text = '';
81
+ for (const t of pXml.matchAll(/<w:t(?:\s[^>]*)?>([\s\S]*?)<\/w:t>/gu))
82
+ text += decodeXml(t[1]);
83
+ const trimmed = text.trim();
84
+ // 标题判据以**段落样式**为主、文本为辅(2026-11-03 实测修正):
85
+ // 真实合同的正文章节标题样式是「一级」,文本只有「保密条款」「付款方式」,
86
+ // **不含「第X章」**;而「第八章 保密条款8」那种带章号和页码的,只存在于目录。
87
+ // 只靠文本判「第X章」会同时漏掉正文标题、错认目录项。
88
+ // w:val 是数字 styleId,须经 styles.xml 映射成名称再判类型。
89
+ const styleMatch = /<w:pStyle\s+w:val="([^"]*)"/u.exec(pXml);
90
+ const styleVal = styleMatch ? styleMatch[1].trim() : '';
91
+ const styleName = (styleMap.get(styleVal) ?? styleVal).trim();
92
+ // 目录:名称含 toc / 目录(如「toc 1」「WPSOffice手动目录 1」)。
93
+ const isTocByStyle = /(?:^|[^a-z])toc|目录/iu.test(styleName);
94
+ // 正文标题:「一级/二级/三级」「标题N」「Heading N」。
95
+ const headingByStyle = /^(?:一|二|三|四|五|六)级$|^标题\s*\d*$|^Heading\s*\d*$/iu.test(styleName);
96
+ // 文本兜底:无样式信息时按「第X章」判,但排除「章号 + 结尾页码」的目录形态。
97
+ const hasStyle = styleMap.size > 0 || styleVal !== '';
98
+ const headingByText = !hasStyle && CHAPTER_RE.test(trimmed);
99
+ const tocByText = CHAPTER_RE.test(trimmed)
100
+ && /[\d0-9]+\s*$/u.test(trimmed)
101
+ && !/第[一二三四五六七八九十百零〇\d]+[章节篇]\s*$/u.test(trimmed);
102
+ const isToc = isTocByStyle || tocByText;
103
+ const heading = !isToc && (headingByStyle || headingByText);
104
+ out.push({ start, end, text: trimmed, heading, isToc });
105
+ }
106
+ return out;
107
+ }
108
+ /** 归一化用于去重比对:去空白与标点,只留有效字符。 */
109
+ function normalize(text) {
110
+ return text.replace(/[\s\u3000]/gu, '').replace(/[,,。.;;::、"'"'()()【】\[\]《》]/gu, '');
111
+ }
112
+ function similarityHit(a, b) {
113
+ const na = normalize(a);
114
+ const nb = normalize(b);
115
+ if (!na || !nb)
116
+ return false;
117
+ if (na === nb)
118
+ return true;
119
+ const probe = Math.min(40, na.length, nb.length);
120
+ if (probe < 16)
121
+ return false;
122
+ return na.slice(0, probe) === nb.slice(0, probe);
123
+ }
124
+ /** 取一个普通正文段落的 pPr / rPr 作为插入段落的格式模板。 */
125
+ function pickBodyFormat(xml, paras) {
126
+ for (const p of paras) {
127
+ if (!p.text || p.heading)
128
+ continue;
129
+ const pXml = xml.slice(p.start, p.end);
130
+ const pPrMatch = /<w:pPr>[\s\S]*?<\/w:pPr>/u.exec(pXml);
131
+ const rPrMatch = /<w:rPr>[\s\S]*?<\/w:rPr>/u.exec(pXml);
132
+ if (pPrMatch || rPrMatch) {
133
+ return { pPr: pPrMatch?.[0] ?? '', rPr: rPrMatch?.[0] ?? '' };
134
+ }
135
+ }
136
+ return { pPr: '', rPr: '' };
137
+ }
138
+ function buildClauseParagraphs(name, content, fmt) {
139
+ const escape = (s) => encodeXml(s);
140
+ const title = `<w:p>${fmt.pPr ? `<w:pPr>${fmt.pPr.replace(/<\/?w:pPr>/gu, '')}</w:pPr>` : ''}`
141
+ + `<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">${escape(name)}</w:t></w:r></w:p>`;
142
+ const body = `<w:p>${fmt.pPr ? `<w:pPr>${fmt.pPr.replace(/<\/?w:pPr>/gu, '')}</w:pPr>` : ''}`
143
+ + `<w:r>${fmt.rPr ? `<w:rPr>${fmt.rPr.replace(/<\/?w:rPr>/gu, '')}</w:rPr>` : ''}`
144
+ + `<w:t xml:space="preserve">${escape(content)}</w:t></w:r></w:p>`;
145
+ return title + body;
146
+ }
147
+ /**
148
+ * 在 docx 中插入条款。
149
+ *
150
+ * @param path 合同 docx 绝对路径
151
+ * @param clauses 待插入条款
152
+ * @param outPath 输出路径;与 path 相同则原地覆盖,`dryRun` 时不写盘
153
+ * @param dryRun 只分析不落盘
154
+ */
155
+ export function insertClausesIntoDocx(path, clauses, outPath, dryRun = false) {
156
+ const buffer = readFileSync(path);
157
+ let xml = readZipEntry(buffer, 'word/document.xml');
158
+ const styleMap = readStyleNameMap(buffer);
159
+ const paras = collectTopParagraphs(xml, styleMap);
160
+ // 章节清单只取正文标题,目录项不算(否则给用户看的章节列表也是目录)。
161
+ const chapters = paras.filter((p) => p.heading && !p.isToc).map((p) => p.text);
162
+ const fmt = pickBodyFormat(xml, paras);
163
+ const outcomes = [];
164
+ // 逐条计算插入点,最后按位置从后往前统一插入,避免偏移。
165
+ const pending = [];
166
+ for (const clause of clauses) {
167
+ // ---- 去重:先看条款名,再看正文首段
168
+ const dupName = paras.find((p) => p.text && normalize(p.text) === normalize(clause.name));
169
+ if (dupName) {
170
+ outcomes.push({
171
+ name: clause.name,
172
+ status: 'duplicate',
173
+ reason: `合同已存在同名条款:${dupName.text.slice(0, 40)}`,
174
+ });
175
+ continue;
176
+ }
177
+ const dupBody = paras.find((p) => p.text && similarityHit(p.text, clause.content));
178
+ if (dupBody) {
179
+ outcomes.push({
180
+ name: clause.name,
181
+ status: 'duplicate',
182
+ reason: `合同已有实质相同条款:${dupBody.text.slice(0, 40)}…`,
183
+ });
184
+ continue;
185
+ }
186
+ // ---- 定位:按 anchor 命中章节标题,退化按条款名/正文关键词
187
+ const anchor = (clause.anchor ?? '').trim();
188
+ let chapterIdx = -1;
189
+ if (anchor) {
190
+ chapterIdx = paras.findIndex((p) => p.heading && !p.isToc && normalize(p.text).includes(normalize(anchor)));
191
+ }
192
+ if (chapterIdx < 0) {
193
+ const key = normalize(clause.name).slice(0, 6);
194
+ if (key.length >= 2) {
195
+ chapterIdx = paras.findIndex((p) => p.heading && !p.isToc && normalize(p.text).includes(key));
196
+ }
197
+ }
198
+ if (chapterIdx < 0) {
199
+ outcomes.push({
200
+ name: clause.name,
201
+ status: 'anchor_not_found',
202
+ reason: anchor ? `未找到章节「${anchor}」` : '未给出锚点且条款名无法匹配章节',
203
+ });
204
+ continue;
205
+ }
206
+ // ---- 插入点:该章节之后的下一个章节标题之前;最后一章则取正文末尾
207
+ const nextHeading = paras.findIndex((p, i) => i > chapterIdx && p.heading && !p.isToc);
208
+ const insertAt = nextHeading >= 0 ? paras[nextHeading].start : lastBodyInsertPos(xml);
209
+ const chapterText = paras[chapterIdx].text;
210
+ pending.push({
211
+ at: insertAt,
212
+ xml: buildClauseParagraphs(clause.name, clause.content, fmt),
213
+ name: clause.name,
214
+ });
215
+ outcomes.push({
216
+ name: clause.name,
217
+ status: 'inserted',
218
+ chapter: chapterText,
219
+ position: `${chapterText} 之后`,
220
+ paragraphIndex: chapterIdx,
221
+ });
222
+ }
223
+ // 从后往前插入
224
+ pending.sort((a, b) => b.at - a.at);
225
+ for (const item of pending) {
226
+ xml = xml.slice(0, item.at) + item.xml + xml.slice(item.at);
227
+ }
228
+ const result = {
229
+ outcomes,
230
+ chapters,
231
+ insertedCount: outcomes.filter((o) => o.status === 'inserted').length,
232
+ skippedCount: outcomes.filter((o) => o.status !== 'inserted').length,
233
+ };
234
+ if (dryRun)
235
+ return { buffer: null, result };
236
+ const out = rewriteZip(path, { 'word/document.xml': xml });
237
+ if (outPath !== path) {
238
+ // 由调用方负责写文件;这里只回传 buffer 以保持函数纯粹。
239
+ }
240
+ return { buffer: out, result };
241
+ }
242
+ function lastBodyInsertPos(xml) {
243
+ const sectPr = xml.lastIndexOf('<w:sectPr');
244
+ if (sectPr >= 0)
245
+ return sectPr;
246
+ const bodyClose = xml.lastIndexOf('</w:body>');
247
+ return bodyClose >= 0 ? bodyClose : xml.length;
248
+ }
249
+ export { collectTopParagraphs };