wezard 2.8.8 → 3.0.1

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 (414) hide show
  1. package/.claude-plugin/plugin.json +0 -6
  2. package/CLAUDE.md +36 -16
  3. package/README.md +41 -54
  4. package/cli/wezard.sh +3 -0
  5. package/config.example.jsonc +6 -8
  6. package/dist/cli/codex-hook.js +20 -4
  7. package/dist/cli/codex-hook.js.map +1 -1
  8. package/dist/cli/init.js +45 -8
  9. package/dist/cli/init.js.map +1 -1
  10. package/dist/cli/skills.js +113 -0
  11. package/dist/cli/skills.js.map +1 -0
  12. package/dist/cli/sync.js +32 -112
  13. package/dist/cli/sync.js.map +1 -1
  14. package/dist/daemon/apprentice.js +75 -0
  15. package/dist/daemon/apprentice.js.map +1 -0
  16. package/dist/daemon/approval.js +78 -20
  17. package/dist/daemon/approval.js.map +1 -1
  18. package/dist/daemon/channel-context.js +69 -0
  19. package/dist/daemon/channel-context.js.map +1 -0
  20. package/dist/daemon/channel-posts.js +53 -0
  21. package/dist/daemon/channel-posts.js.map +1 -0
  22. package/dist/daemon/channel-store.js +96 -0
  23. package/dist/daemon/channel-store.js.map +1 -0
  24. package/dist/daemon/channel.js +805 -0
  25. package/dist/daemon/channel.js.map +1 -0
  26. package/dist/daemon/chat-name.js +24 -161
  27. package/dist/daemon/chat-name.js.map +1 -1
  28. package/dist/daemon/classes.js +418 -0
  29. package/dist/daemon/classes.js.map +1 -0
  30. package/dist/daemon/config-api.js +11 -3
  31. package/dist/daemon/config-api.js.map +1 -1
  32. package/dist/daemon/danger.js +24 -205
  33. package/dist/daemon/danger.js.map +1 -1
  34. package/dist/daemon/detail.js +14 -8
  35. package/dist/daemon/detail.js.map +1 -1
  36. package/dist/daemon/handoff.js +266 -50
  37. package/dist/daemon/handoff.js.map +1 -1
  38. package/dist/daemon/http.js +25 -18
  39. package/dist/daemon/http.js.map +1 -1
  40. package/dist/daemon/idle-reap.js +30 -0
  41. package/dist/daemon/idle-reap.js.map +1 -0
  42. package/dist/daemon/inbound.js +366 -143
  43. package/dist/daemon/inbound.js.map +1 -1
  44. package/dist/daemon/index.js +2232 -2616
  45. package/dist/daemon/index.js.map +1 -1
  46. package/dist/daemon/last-response.js +44 -9
  47. package/dist/daemon/last-response.js.map +1 -1
  48. package/dist/daemon/memory-steward.js +1 -1
  49. package/dist/daemon/memory-steward.js.map +1 -1
  50. package/dist/daemon/message-format.js +10 -2
  51. package/dist/daemon/message-format.js.map +1 -1
  52. package/dist/daemon/mirror-bridge.js +714 -485
  53. package/dist/daemon/mirror-bridge.js.map +1 -1
  54. package/dist/daemon/mirror-store.js +24 -0
  55. package/dist/daemon/mirror-store.js.map +1 -1
  56. package/dist/daemon/notices.js +2 -2
  57. package/dist/daemon/notices.js.map +1 -1
  58. package/dist/daemon/onboarding.js +384 -0
  59. package/dist/daemon/onboarding.js.map +1 -0
  60. package/dist/daemon/outbound.js +21 -11
  61. package/dist/daemon/outbound.js.map +1 -1
  62. package/dist/daemon/peers.js +38 -230
  63. package/dist/daemon/peers.js.map +1 -1
  64. package/dist/daemon/pending.js +7 -5
  65. package/dist/daemon/pending.js.map +1 -1
  66. package/dist/daemon/picker-policy.js +27 -12
  67. package/dist/daemon/picker-policy.js.map +1 -1
  68. package/dist/daemon/plans.js.map +1 -1
  69. package/dist/daemon/room-auto-adhoc.js +18 -0
  70. package/dist/daemon/room-auto-adhoc.js.map +1 -0
  71. package/dist/daemon/room-facts.js +35 -0
  72. package/dist/daemon/room-facts.js.map +1 -0
  73. package/dist/daemon/room-hub.js +430 -0
  74. package/dist/daemon/room-hub.js.map +1 -0
  75. package/dist/daemon/room-overdue.js +98 -0
  76. package/dist/daemon/room-overdue.js.map +1 -0
  77. package/dist/daemon/room-prune.js +74 -0
  78. package/dist/daemon/room-prune.js.map +1 -0
  79. package/dist/daemon/room-spawn.js +20 -0
  80. package/dist/daemon/room-spawn.js.map +1 -0
  81. package/dist/daemon/room-watchdog.js +153 -0
  82. package/dist/daemon/room-watchdog.js.map +1 -0
  83. package/dist/daemon/rooms.js +107 -0
  84. package/dist/daemon/rooms.js.map +1 -0
  85. package/dist/daemon/route.js +7 -18
  86. package/dist/daemon/route.js.map +1 -1
  87. package/dist/daemon/spawn-tmux.js +171 -55
  88. package/dist/daemon/spawn-tmux.js.map +1 -1
  89. package/dist/daemon/steward-guard.js +2 -2
  90. package/dist/daemon/steward.js +132 -0
  91. package/dist/daemon/steward.js.map +1 -0
  92. package/dist/daemon/tasks.js +4 -14
  93. package/dist/daemon/tasks.js.map +1 -1
  94. package/dist/daemon/turn-opening.js +25 -0
  95. package/dist/daemon/turn-opening.js.map +1 -0
  96. package/dist/daemon/wake-tail.js +55 -0
  97. package/dist/daemon/wake-tail.js.map +1 -0
  98. package/dist/daemon/weixin-cmd.js +10 -14
  99. package/dist/daemon/weixin-cmd.js.map +1 -1
  100. package/dist/daemon/wezard-session.js +7 -2
  101. package/dist/daemon/wezard-session.js.map +1 -1
  102. package/dist/daemon/wizard-names.js +0 -22
  103. package/dist/daemon/wizard-names.js.map +1 -1
  104. package/dist/daemon/wizard.js +589 -145
  105. package/dist/daemon/wizard.js.map +1 -1
  106. package/dist/mcp/output.js +6 -5
  107. package/dist/mcp/output.js.map +1 -1
  108. package/dist/mcp/tools.js +258 -236
  109. package/dist/mcp/tools.js.map +1 -1
  110. package/dist/shared/allow-rules.js +32 -8
  111. package/dist/shared/allow-rules.js.map +1 -1
  112. package/dist/shared/charter-rearm.js +179 -0
  113. package/dist/shared/charter-rearm.js.map +1 -0
  114. package/dist/shared/chat-http.js +374 -459
  115. package/dist/shared/chat-http.js.map +1 -1
  116. package/dist/shared/chat-record.js +55 -0
  117. package/dist/shared/chat-record.js.map +1 -0
  118. package/dist/shared/chat-render.js +7 -4
  119. package/dist/shared/chat-render.js.map +1 -1
  120. package/dist/shared/chat-view.js +2 -41
  121. package/dist/shared/chat-view.js.map +1 -1
  122. package/dist/shared/cli-backends.js +27 -5
  123. package/dist/shared/cli-backends.js.map +1 -1
  124. package/dist/shared/config.js +122 -38
  125. package/dist/shared/config.js.map +1 -1
  126. package/dist/shared/detail-render.js +104 -21
  127. package/dist/shared/detail-render.js.map +1 -1
  128. package/dist/shared/detail-store.js.map +1 -1
  129. package/dist/shared/group-members.js +35 -0
  130. package/dist/shared/group-members.js.map +1 -0
  131. package/dist/shared/inject-view.js +105 -0
  132. package/dist/shared/inject-view.js.map +1 -0
  133. package/dist/shared/json-map-store.js +23 -6
  134. package/dist/shared/json-map-store.js.map +1 -1
  135. package/dist/shared/legacy-routes.js +199 -0
  136. package/dist/shared/legacy-routes.js.map +1 -0
  137. package/dist/shared/mem-guard.js +32 -0
  138. package/dist/shared/mem-guard.js.map +1 -0
  139. package/dist/shared/message-footer.js +4 -3
  140. package/dist/shared/message-footer.js.map +1 -1
  141. package/dist/shared/pricing.js +5 -0
  142. package/dist/shared/pricing.js.map +1 -1
  143. package/dist/shared/reminder.js +30 -38
  144. package/dist/shared/reminder.js.map +1 -1
  145. package/dist/shared/repl-script.js +114 -26
  146. package/dist/shared/repl-script.js.map +1 -1
  147. package/dist/shared/role-render.js +209 -210
  148. package/dist/shared/role-render.js.map +1 -1
  149. package/dist/shared/role-view.js +61 -299
  150. package/dist/shared/role-view.js.map +1 -1
  151. package/dist/shared/room-label.js +13 -0
  152. package/dist/shared/room-label.js.map +1 -0
  153. package/dist/shared/room-migrate.js +404 -0
  154. package/dist/shared/room-migrate.js.map +1 -0
  155. package/dist/shared/room-overdue.js +81 -0
  156. package/dist/shared/room-overdue.js.map +1 -0
  157. package/dist/shared/room-search.js +102 -0
  158. package/dist/shared/room-search.js.map +1 -0
  159. package/dist/shared/room-view.js +261 -0
  160. package/dist/shared/room-view.js.map +1 -0
  161. package/dist/shared/room.js +610 -0
  162. package/dist/shared/room.js.map +1 -0
  163. package/dist/shared/session-hooks.js +58 -0
  164. package/dist/shared/session-hooks.js.map +1 -0
  165. package/dist/shared/session-label.js +80 -60
  166. package/dist/shared/session-label.js.map +1 -1
  167. package/dist/shared/session-mcp.js +77 -0
  168. package/dist/shared/session-mcp.js.map +1 -0
  169. package/dist/shared/session-skills.js +63 -0
  170. package/dist/shared/session-skills.js.map +1 -0
  171. package/dist/shared/skill-sync.js +229 -0
  172. package/dist/shared/skill-sync.js.map +1 -0
  173. package/dist/shared/smarts.js +39 -0
  174. package/dist/shared/smarts.js.map +1 -0
  175. package/dist/shared/stream-page.js +22 -0
  176. package/dist/shared/stream-page.js.map +1 -0
  177. package/dist/shared/task-file.js +0 -5
  178. package/dist/shared/task-file.js.map +1 -1
  179. package/dist/shared/task-template.js +1 -1
  180. package/dist/shared/task-template.js.map +1 -1
  181. package/dist/shared/tool-hints.js +76 -17
  182. package/dist/shared/tool-hints.js.map +1 -1
  183. package/dist/shared/workspace-trust.js +8 -0
  184. package/dist/shared/workspace-trust.js.map +1 -1
  185. package/dist/shared/world.js +101 -166
  186. package/dist/shared/world.js.map +1 -1
  187. package/dist/svr/facts-store.js +26 -0
  188. package/dist/svr/facts-store.js.map +1 -0
  189. package/dist/svr/index.js +62 -6
  190. package/dist/svr/index.js.map +1 -1
  191. package/hooks/pre-tool-use.sh +18 -0
  192. package/hooks/stop.sh +26 -0
  193. package/package.json +7 -3
  194. package/scripts/install.sh +11 -0
  195. package/skills/LICENSE.wecom-unified.txt +21 -0
  196. package/skills/wecom-unified/SKILL.md +151 -0
  197. package/skills/wecom-unified/assets/templates/broadside/DESIGN.preset.md +172 -0
  198. package/skills/wecom-unified/assets/templates/broadside/shell/content.jsx +31 -0
  199. package/skills/wecom-unified/assets/templates/broadside/slides/01_cover.slide +48 -0
  200. package/skills/wecom-unified/assets/templates/broadside/slides/02_section.slide +58 -0
  201. package/skills/wecom-unified/assets/templates/broadside/slides/03_cards.slide +53 -0
  202. package/skills/wecom-unified/assets/templates/broadside/slides/04_image.slide +64 -0
  203. package/skills/wecom-unified/assets/templates/cartesian/DESIGN.preset.md +139 -0
  204. package/skills/wecom-unified/assets/templates/cartesian/shell/content.jsx +28 -0
  205. package/skills/wecom-unified/assets/templates/cartesian/slides/01_cover.slide +44 -0
  206. package/skills/wecom-unified/assets/templates/cartesian/slides/02_compare.slide +79 -0
  207. package/skills/wecom-unified/assets/templates/cartesian/slides/03_table.slide +79 -0
  208. package/skills/wecom-unified/assets/templates/cobalt-grid/DESIGN.preset.md +118 -0
  209. package/skills/wecom-unified/assets/templates/cobalt-grid/shell/content.jsx +24 -0
  210. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/01_cover.slide +61 -0
  211. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/02_structure.slide +85 -0
  212. package/skills/wecom-unified/assets/templates/cobalt-grid/slides/03_data.slide +60 -0
  213. package/skills/wecom-unified/assets/templates/editorial-forest/DESIGN.preset.md +135 -0
  214. package/skills/wecom-unified/assets/templates/editorial-forest/shell/content.jsx +19 -0
  215. package/skills/wecom-unified/assets/templates/editorial-forest/slides/01_cover.slide +29 -0
  216. package/skills/wecom-unified/assets/templates/editorial-forest/slides/02_cards.slide +60 -0
  217. package/skills/wecom-unified/assets/templates/editorial-forest/slides/03_data.slide +49 -0
  218. package/skills/wecom-unified/assets/templates/editorial-forest/slides/04_image.slide +46 -0
  219. package/skills/wecom-unified/assets/templates/emerald-editorial/DESIGN.preset.md +119 -0
  220. package/skills/wecom-unified/assets/templates/emerald-editorial/shell/content.jsx +18 -0
  221. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/01_cover.slide +36 -0
  222. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/02_section.slide +39 -0
  223. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/03_data.slide +79 -0
  224. package/skills/wecom-unified/assets/templates/emerald-editorial/slides/04_steps.slide +53 -0
  225. package/skills/wecom-unified/assets/templates/grove/DESIGN.preset.md +159 -0
  226. package/skills/wecom-unified/assets/templates/grove/shell/content.jsx +18 -0
  227. package/skills/wecom-unified/assets/templates/grove/shell/content_light.jsx +18 -0
  228. package/skills/wecom-unified/assets/templates/grove/slides/01_cover.slide +26 -0
  229. package/skills/wecom-unified/assets/templates/grove/slides/02_compare.slide +92 -0
  230. package/skills/wecom-unified/assets/templates/grove/slides/03_table.slide +68 -0
  231. package/skills/wecom-unified/assets/templates/index.json +280 -0
  232. package/skills/wecom-unified/assets/templates/long-table/DESIGN.preset.md +135 -0
  233. package/skills/wecom-unified/assets/templates/long-table/shell/content.jsx +36 -0
  234. package/skills/wecom-unified/assets/templates/long-table/slides/01_cover.slide +71 -0
  235. package/skills/wecom-unified/assets/templates/long-table/slides/02_cards.slide +72 -0
  236. package/skills/wecom-unified/assets/templates/long-table/slides/03_timeline.slide +81 -0
  237. package/skills/wecom-unified/assets/templates/long-table/slides/04_image.slide +60 -0
  238. package/skills/wecom-unified/assets/templates/sakura-chroma/DESIGN.preset.md +121 -0
  239. package/skills/wecom-unified/assets/templates/sakura-chroma/shell/content.jsx +13 -0
  240. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/01_cover.slide +54 -0
  241. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/02_products.slide +134 -0
  242. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/03_section.slide +30 -0
  243. package/skills/wecom-unified/assets/templates/sakura-chroma/slides/04_schedule.slide +65 -0
  244. package/skills/wecom-unified/assets/templates/signal/DESIGN.preset.md +121 -0
  245. package/skills/wecom-unified/assets/templates/signal/shell/content.jsx +18 -0
  246. package/skills/wecom-unified/assets/templates/signal/shell/content_dark.jsx +23 -0
  247. package/skills/wecom-unified/assets/templates/signal/slides/01_cover.slide +48 -0
  248. package/skills/wecom-unified/assets/templates/signal/slides/02_cards.slide +67 -0
  249. package/skills/wecom-unified/assets/templates/signal/slides/03_data.slide +68 -0
  250. package/skills/wecom-unified/references/wecomcli-calendar-agenda.md +227 -0
  251. package/skills/wecom-unified/references/wecomcli-calendar-cancel.md +108 -0
  252. package/skills/wecom-unified/references/wecomcli-calendar-create.md +238 -0
  253. package/skills/wecom-unified/references/wecomcli-calendar-freebusy.md +207 -0
  254. package/skills/wecom-unified/references/wecomcli-calendar-meeting-room.md +170 -0
  255. package/skills/wecom-unified/references/wecomcli-calendar-search.md +209 -0
  256. package/skills/wecom-unified/references/wecomcli-calendar-update.md +272 -0
  257. package/skills/wecom-unified/references/wecomcli-calendar.md +296 -0
  258. package/skills/wecom-unified/references/wecomcli-contact.md +48 -0
  259. package/skills/wecom-unified/references/wecomcli-disk.md +380 -0
  260. package/skills/wecom-unified/references/wecomcli-doc-contents-append.md +20 -0
  261. package/skills/wecom-unified/references/wecomcli-doc-contents-overwrite.md +27 -0
  262. package/skills/wecom-unified/references/wecomcli-doc-create.md +162 -0
  263. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-members-update.md +24 -0
  264. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-names-update.md +20 -0
  265. package/skills/wecom-unified/references/wecomcli-doc-manage-doc-rules-update.md +22 -0
  266. package/skills/wecom-unified/references/wecomcli-doc-manage.md +127 -0
  267. package/skills/wecom-unified/references/wecomcli-doc.md +135 -0
  268. package/skills/wecom-unified/references/wecomcli-email-forward-mail.md +131 -0
  269. package/skills/wecom-unified/references/wecomcli-email-get-mail.md +187 -0
  270. package/skills/wecom-unified/references/wecomcli-email-reply-mail.md +138 -0
  271. package/skills/wecom-unified/references/wecomcli-email-search-mail.md +114 -0
  272. package/skills/wecom-unified/references/wecomcli-email-security.md +52 -0
  273. package/skills/wecom-unified/references/wecomcli-email-send-mail.md +186 -0
  274. package/skills/wecom-unified/references/wecomcli-email-send-schedule.md +83 -0
  275. package/skills/wecom-unified/references/wecomcli-email.md +206 -0
  276. package/skills/wecom-unified/references/wecomcli-media.md +89 -0
  277. package/skills/wecom-unified/references/wecomcli-meeting-cancel.md +113 -0
  278. package/skills/wecom-unified/references/wecomcli-meeting-create.md +167 -0
  279. package/skills/wecom-unified/references/wecomcli-meeting-list.md +228 -0
  280. package/skills/wecom-unified/references/wecomcli-meeting-original-get.md +101 -0
  281. package/skills/wecom-unified/references/wecomcli-meeting-search.md +176 -0
  282. package/skills/wecom-unified/references/wecomcli-meeting-update.md +217 -0
  283. package/skills/wecom-unified/references/wecomcli-meeting.md +366 -0
  284. package/skills/wecom-unified/references/wecomcli-message.md +190 -0
  285. package/skills/wecom-unified/references/wecomcli-pptx-component-animation.md +62 -0
  286. package/skills/wecom-unified/references/wecomcli-pptx-component-box.md +102 -0
  287. package/skills/wecom-unified/references/wecomcli-pptx-component-chart.md +261 -0
  288. package/skills/wecom-unified/references/wecomcli-pptx-component-codeblock.md +70 -0
  289. package/skills/wecom-unified/references/wecomcli-pptx-component-diagram.md +54 -0
  290. package/skills/wecom-unified/references/wecomcli-pptx-component-faicon.md +71 -0
  291. package/skills/wecom-unified/references/wecomcli-pptx-component-hyperlink.md +55 -0
  292. package/skills/wecom-unified/references/wecomcli-pptx-component-image.md +107 -0
  293. package/skills/wecom-unified/references/wecomcli-pptx-component-math.md +65 -0
  294. package/skills/wecom-unified/references/wecomcli-pptx-component-qrcode.md +22 -0
  295. package/skills/wecom-unified/references/wecomcli-pptx-component-slide.md +74 -0
  296. package/skills/wecom-unified/references/wecomcli-pptx-component-svg.md +95 -0
  297. package/skills/wecom-unified/references/wecomcli-pptx-component-table.md +72 -0
  298. package/skills/wecom-unified/references/wecomcli-pptx-component-text.md +96 -0
  299. package/skills/wecom-unified/references/wecomcli-pptx-content-contract.md +73 -0
  300. package/skills/wecom-unified/references/wecomcli-pptx-create-from-material.md +67 -0
  301. package/skills/wecom-unified/references/wecomcli-pptx-create-from-scratch.md +178 -0
  302. package/skills/wecom-unified/references/wecomcli-pptx-create-from-template.md +123 -0
  303. package/skills/wecom-unified/references/wecomcli-pptx-design-principle.md +65 -0
  304. package/skills/wecom-unified/references/wecomcli-pptx-government-contract.md +40 -0
  305. package/skills/wecom-unified/references/wecomcli-pptx-human-alignment.md +140 -0
  306. package/skills/wecom-unified/references/wecomcli-pptx-pptx-api.md +161 -0
  307. package/skills/wecom-unified/references/wecomcli-pptx-pptx-edit.md +37 -0
  308. package/skills/wecom-unified/references/wecomcli-pptx-story-principle.md +184 -0
  309. package/skills/wecom-unified/references/wecomcli-pptx-templates-README.md +165 -0
  310. package/skills/wecom-unified/references/wecomcli-pptx-templates-anti-ai-slop.md +52 -0
  311. package/skills/wecom-unified/references/wecomcli-pptx.md +158 -0
  312. package/skills/wecom-unified/references/wecomcli-sheet-conditional-formatting.md +203 -0
  313. package/skills/wecom-unified/references/wecomcli-sheet-filter.md +179 -0
  314. package/skills/wecom-unified/references/wecomcli-sheet-float-image.md +235 -0
  315. package/skills/wecom-unified/references/wecomcli-sheet-formulas.md +71 -0
  316. package/skills/wecom-unified/references/wecomcli-sheet-history.md +118 -0
  317. package/skills/wecom-unified/references/wecomcli-sheet-protection.md +170 -0
  318. package/skills/wecom-unified/references/wecomcli-sheet-range-operations.md +306 -0
  319. package/skills/wecom-unified/references/wecomcli-sheet-read-data.md +151 -0
  320. package/skills/wecom-unified/references/wecomcli-sheet-search-replace.md +121 -0
  321. package/skills/wecom-unified/references/wecomcli-sheet-structure-operations.md +394 -0
  322. package/skills/wecom-unified/references/wecomcli-sheet-style.md +246 -0
  323. package/skills/wecom-unified/references/wecomcli-sheet-table-style.md +199 -0
  324. package/skills/wecom-unified/references/wecomcli-sheet-validation.md +217 -0
  325. package/skills/wecom-unified/references/wecomcli-sheet-visual-standards.md +166 -0
  326. package/skills/wecom-unified/references/wecomcli-sheet-workbook.md +264 -0
  327. package/skills/wecom-unified/references/wecomcli-sheet-write-cells.md +320 -0
  328. package/skills/wecom-unified/references/wecomcli-sheet-xlsx-process.md +324 -0
  329. package/skills/wecom-unified/references/wecomcli-sheet.md +96 -0
  330. package/skills/wecom-unified/references/wecomcli-smartpage-data-driven-pages.md +50 -0
  331. package/skills/wecom-unified/references/wecomcli-smartpage-edit.md +526 -0
  332. package/skills/wecom-unified/references/wecomcli-smartpage-formula-arraylist.md +369 -0
  333. package/skills/wecom-unified/references/wecomcli-smartpage-formula-datetime.md +283 -0
  334. package/skills/wecom-unified/references/wecomcli-smartpage-formula-logic.md +247 -0
  335. package/skills/wecom-unified/references/wecomcli-smartpage-formula-math.md +362 -0
  336. package/skills/wecom-unified/references/wecomcli-smartpage-formula-operators.md +246 -0
  337. package/skills/wecom-unified/references/wecomcli-smartpage-formula-pageblock.md +76 -0
  338. package/skills/wecom-unified/references/wecomcli-smartpage-formula-reference.md +192 -0
  339. package/skills/wecom-unified/references/wecomcli-smartpage-formula-templates.md +410 -0
  340. package/skills/wecom-unified/references/wecomcli-smartpage-formula-text.md +377 -0
  341. package/skills/wecom-unified/references/wecomcli-smartpage-formula-user.md +22 -0
  342. package/skills/wecom-unified/references/wecomcli-smartpage-mdx-syntax.md +739 -0
  343. package/skills/wecom-unified/references/wecomcli-smartpage.md +179 -0
  344. package/skills/wecom-unified/references/wecomcli-smartsheet-chart-types.md +95 -0
  345. package/skills/wecom-unified/references/wecomcli-smartsheet-common.md +160 -0
  346. package/skills/wecom-unified/references/wecomcli-smartsheet-edit.md +609 -0
  347. package/skills/wecom-unified/references/wecomcli-smartsheet-field-types.md +438 -0
  348. package/skills/wecom-unified/references/wecomcli-smartsheet-formula.md +845 -0
  349. package/skills/wecom-unified/references/wecomcli-smartsheet-read.md +411 -0
  350. package/skills/wecom-unified/references/wecomcli-smartsheet-record-values.md +218 -0
  351. package/skills/wecom-unified/references/wecomcli-smartsheet-template-ai_efficiency.md +709 -0
  352. package/skills/wecom-unified/references/wecomcli-smartsheet-template-connect_to_app.md +380 -0
  353. package/skills/wecom-unified/references/wecomcli-smartsheet-template-financial_accounting.md +369 -0
  354. package/skills/wecom-unified/references/wecomcli-smartsheet-template-hr_and_administration.md +475 -0
  355. package/skills/wecom-unified/references/wecomcli-smartsheet-template-ledger_records.md +156 -0
  356. package/skills/wecom-unified/references/wecomcli-smartsheet-template-manufacturing.md +395 -0
  357. package/skills/wecom-unified/references/wecomcli-smartsheet-template-marketing.md +186 -0
  358. package/skills/wecom-unified/references/wecomcli-smartsheet-template-office_essentials.md +299 -0
  359. package/skills/wecom-unified/references/wecomcli-smartsheet-template-personal_efficiency.md +70 -0
  360. package/skills/wecom-unified/references/wecomcli-smartsheet-template-procurement_logistics.md +325 -0
  361. package/skills/wecom-unified/references/wecomcli-smartsheet-template-project_management.md +564 -0
  362. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_customer.md +222 -0
  363. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_ops.md +105 -0
  364. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_project.md +109 -0
  365. package/skills/wecom-unified/references/wecomcli-smartsheet-template-rd_process_research.md +92 -0
  366. package/skills/wecom-unified/references/wecomcli-smartsheet-template-sales_and_operations.md +446 -0
  367. package/skills/wecom-unified/references/wecomcli-smartsheet-template-store_management.md +431 -0
  368. package/skills/wecom-unified/references/wecomcli-smartsheet-template-team_tasks.md +274 -0
  369. package/skills/wecom-unified/references/wecomcli-smartsheet-template-wechat_customer.md +384 -0
  370. package/skills/wecom-unified/references/wecomcli-smartsheet-template-work_report.md +100 -0
  371. package/skills/wecom-unified/references/wecomcli-smartsheet-templates.md +53 -0
  372. package/skills/wecom-unified/references/wecomcli-smartsheet-view-types.md +373 -0
  373. package/skills/wecom-unified/references/wecomcli-smartsheet-webhook-examples.md +176 -0
  374. package/skills/wecom-unified/references/wecomcli-smartsheet-webhook.md +186 -0
  375. package/skills/wecom-unified/references/wecomcli-smartsheet.md +147 -0
  376. package/skills/wecom-unified/references/wecomcli-todo-create.md +137 -0
  377. package/skills/wecom-unified/references/wecomcli-todo-delete.md +63 -0
  378. package/skills/wecom-unified/references/wecomcli-todo-finish.md +72 -0
  379. package/skills/wecom-unified/references/wecomcli-todo-get.md +69 -0
  380. package/skills/wecom-unified/references/wecomcli-todo-list.md +136 -0
  381. package/skills/wecom-unified/references/wecomcli-todo-update.md +112 -0
  382. package/skills/wecom-unified/references/wecomcli-todo.md +68 -0
  383. package/skills/wecom-unified/scripts/build_docx.py +1274 -0
  384. package/skills/wecom-unified/scripts/build_page.py +2449 -0
  385. package/skills/wecom-unified/scripts/collect.py +868 -0
  386. package/skills/wecom-unified/scripts/doc_image_extractor.py +498 -0
  387. package/skills/wecom-unified/scripts/pptx2image.py +268 -0
  388. package/skills/wecom-unified/scripts/recalc.py +403 -0
  389. package/systemd/wezard.service.template +6 -0
  390. package/web/chat.css +70 -273
  391. package/web/chat.js +2228 -2190
  392. package/dist/daemon/chat-log.js +0 -130
  393. package/dist/daemon/chat-log.js.map +0 -1
  394. package/dist/daemon/dispatch.js +0 -6
  395. package/dist/daemon/dispatch.js.map +0 -1
  396. package/dist/daemon/idle-nudge.js +0 -69
  397. package/dist/daemon/idle-nudge.js.map +0 -1
  398. package/dist/daemon/message-events.js +0 -1083
  399. package/dist/daemon/message-events.js.map +0 -1
  400. package/dist/daemon/pending-items.js +0 -160
  401. package/dist/daemon/pending-items.js.map +0 -1
  402. package/dist/daemon/router.js +0 -742
  403. package/dist/daemon/router.js.map +0 -1
  404. package/dist/daemon/tips.js +0 -25
  405. package/dist/daemon/tips.js.map +0 -1
  406. package/dist/daemon/wedoc.js +0 -210
  407. package/dist/daemon/wedoc.js.map +0 -1
  408. package/dist/shared/role-search.js +0 -100
  409. package/dist/shared/role-search.js.map +0 -1
  410. package/dist/shared/startup-notice.js +0 -21
  411. package/dist/shared/startup-notice.js.map +0 -1
  412. package/dist/shared/turn-state.js +0 -27
  413. package/dist/shared/turn-state.js.map +0 -1
  414. package/hooks/hooks.json +0 -16
@@ -0,0 +1,1274 @@
1
+ """build_docx.py — Generate a .docx file from a JSONL spec.
2
+
3
+ Each line of the input file is a single command::
4
+
5
+ {"action": "<function_name>", "params": {...}}
6
+
7
+ Workflow::
8
+
9
+ 1. 读 JSONL → 一次性按 ``references/doc-create.md`` 做参数校验
10
+ (action 取值 / params 字段名 / 类型 / 取值范围)。
11
+ 任何偏差立即抛 ``TypeError``("类型错误,无法执行")。
12
+ 2. 校验通过后,再创建 docx 并按 action 派发到 ``DocxBuilder``。
13
+ 3. 通过本地文件系统写出 ``.docx``,默认输出到 JSONL 文件所在目录的
14
+ ``docx/`` 子目录;同名文件会追加时间戳与进程号后缀避免覆盖。
15
+
16
+ Usage::
17
+
18
+ python build_docx.py <spec.jsonl>
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import io
25
+ import json
26
+ import os
27
+ import re
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+ from typing import Any, Iterator, NamedTuple
32
+
33
+ from docx import Document
34
+ from docx.enum.table import WD_TABLE_ALIGNMENT
35
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
36
+ from docx.oxml import OxmlElement, parse_xml
37
+ from docx.oxml.ns import nsdecls, qn
38
+ from docx.shared import Cm, Emu, Pt, RGBColor
39
+
40
+ # ===========================================================================
41
+ # Constants & lookups
42
+ # ===========================================================================
43
+
44
+ _PARAGRAPH_ALIGN = {
45
+ "left": WD_ALIGN_PARAGRAPH.LEFT,
46
+ "center": WD_ALIGN_PARAGRAPH.CENTER,
47
+ "right": WD_ALIGN_PARAGRAPH.RIGHT,
48
+ "justify": WD_ALIGN_PARAGRAPH.JUSTIFY,
49
+ }
50
+
51
+ _TABLE_ALIGN = {
52
+ "left": WD_TABLE_ALIGNMENT.LEFT,
53
+ "center": WD_TABLE_ALIGNMENT.CENTER,
54
+ "right": WD_TABLE_ALIGNMENT.RIGHT,
55
+ }
56
+
57
+ EMU_PER_DXA = 635 # 1 dxa = 1/20 pt = 635 EMU
58
+ DEFAULT_TABLE_TOTAL_DXA = 9072 # ~6.30 in, A4 content-area width
59
+ DEFAULT_LINE_DXA_NORMAL = 312
60
+ DEFAULT_LINE_DXA_HEADING = 408
61
+
62
+ # Table-level frame uses a thin theme-default line; per-cell borders
63
+ # use a soft gray, applied to every cell so the grid stays consistent
64
+ # on renderers that ignore table-level borders.
65
+ DEFAULT_TABLE_BORDER_COLOR_HEX = "auto"
66
+ DEFAULT_TABLE_BORDER_SIZE = 4
67
+ DEFAULT_CELL_BORDER_COLOR_HEX = "CBCDD1"
68
+ DEFAULT_CELL_BORDER_SIZE = 6
69
+
70
+ # --- XSD ordering anchors --------------------------------------------------
71
+ # Each tuple lists the children that the new element must appear *before*,
72
+ # per the OOXML schema. ``_set_unique_child`` inserts the new element ahead
73
+ # of the first sibling found.
74
+
75
+
76
+ def _anchors_after(tag: str, order: tuple) -> tuple:
77
+ """Return the slice of ``order`` strictly after ``tag``."""
78
+ return order[order.index(tag) + 1:]
79
+
80
+
81
+ # CT_PPrBase: shared by snapToGrid (pos 21) and spacing (pos 22) —
82
+ # every sibling listed comes after both.
83
+ _PPR_SPACING_ANCHORS = (
84
+ qn("w:contextualSpacing"),
85
+ qn("w:jc"),
86
+ qn("w:outlineLvl"),
87
+ )
88
+
89
+ # CT_TblPr order (relevant prefix).
90
+ _TBL_PR_ORDER = (
91
+ qn("w:tblW"),
92
+ qn("w:jc"),
93
+ qn("w:tblCellSpacing"),
94
+ qn("w:tblInd"),
95
+ qn("w:tblBorders"),
96
+ qn("w:shd"),
97
+ qn("w:tblLayout"),
98
+ qn("w:tblLook"),
99
+ )
100
+ _TBL_PR_TBLW_ANCHORS = _anchors_after(qn("w:tblW"), _TBL_PR_ORDER)
101
+ _TBL_PR_BORDERS_ANCHORS = _anchors_after(qn("w:tblBorders"), _TBL_PR_ORDER)
102
+ _TBL_PR_LAYOUT_ANCHORS = _anchors_after(qn("w:tblLayout"), _TBL_PR_ORDER)
103
+
104
+ # CT_TcPrInner order (relevant prefix).
105
+ _TC_PR_ORDER = (
106
+ qn("w:tcBorders"),
107
+ qn("w:shd"),
108
+ qn("w:noWrap"),
109
+ qn("w:tcMar"),
110
+ qn("w:textDirection"),
111
+ qn("w:tcFitText"),
112
+ qn("w:vAlign"),
113
+ qn("w:hideMark"),
114
+ qn("w:headers"),
115
+ )
116
+ _TC_PR_BORDERS_ANCHORS = _anchors_after(qn("w:tcBorders"), _TC_PR_ORDER)
117
+ _TC_PR_SHD_ANCHORS = _anchors_after(qn("w:shd"), _TC_PR_ORDER)
118
+ _TC_PR_MAR_ANCHORS = _anchors_after(qn("w:tcMar"), _TC_PR_ORDER)
119
+ _TC_PR_VALIGN_ANCHORS = _anchors_after(qn("w:vAlign"), _TC_PR_ORDER)
120
+
121
+
122
+ class _HeadingPreset(NamedTuple):
123
+ style_name: str
124
+ size_pt: int
125
+ color_hex: str
126
+ alignment: str | None
127
+
128
+
129
+ # Title 24pt → H1 18pt → H2 16pt → H3 14pt → H4 12pt → H5/H6 11pt.
130
+ _DEFAULT_HEADINGS: tuple[_HeadingPreset, ...] = (
131
+ _HeadingPreset("Title", 24, "1A1A1A", "center"),
132
+ _HeadingPreset("Subtitle", 18, "5C5C5C", "center"),
133
+ _HeadingPreset("Heading 1", 18, "1A1A1A", None),
134
+ _HeadingPreset("Heading 2", 16, "1A1A1A", None),
135
+ _HeadingPreset("Heading 3", 14, "1A1A1A", None),
136
+ _HeadingPreset("Heading 4", 12, "1A1A1A", None),
137
+ _HeadingPreset("Heading 5", 11, "1A1A1A", None),
138
+ _HeadingPreset("Heading 6", 11, "1A1A1A", None),
139
+ )
140
+
141
+ # 6 位十六进制颜色字符串,可选前缀 '#'。供 _hex_to_rgb / 上游校验复用。
142
+ _HEX_COLOR_RE = re.compile(r"^#?[0-9A-Fa-f]{6}$")
143
+
144
+
145
+ # ===========================================================================
146
+ # Exceptions
147
+ # ===========================================================================
148
+
149
+
150
+ class SpecTypeError(TypeError):
151
+ """JSONL 参数校验失败抛出,等同 ``TypeError``,附带行号上下文。"""
152
+
153
+
154
+ # Backwards-compatible alias for any existing caller that imports SpecError.
155
+ SpecError = SpecTypeError
156
+
157
+
158
+ # ===========================================================================
159
+ # JSONL spec validation — 上游一次性校验(基于 references/doc-create.md)
160
+ # ===========================================================================
161
+ #
162
+ # 校验范围严格对齐 doc-create.md 中描述的 4 个 action 及其 params。
163
+ # 任何偏差均抛出 ``SpecTypeError``(继承自 ``TypeError``),由 main()
164
+ # 统一捕获并转成 "类型错误,无法执行" 提示。
165
+
166
+ # 段落 style 仅支持以下内置样式(doc-create.md:列表样式 + Subtitle)。
167
+ ALLOWED_PARAGRAPH_STYLES: frozenset[str] = frozenset({
168
+ "List Bullet", "List Bullet 2", "List Bullet 3",
169
+ "List Number", "List Number 2", "List Number 3",
170
+ "Subtitle",
171
+ })
172
+
173
+ # 段落级对齐枚举。
174
+ ALLOWED_ALIGNMENTS: frozenset[str] = frozenset({
175
+ "left", "center", "right", "justify",
176
+ })
177
+
178
+ # run / cell 对象支持的字段及类型(与 doc-create.md 中表格一致)。
179
+ # (int, float) 元组用于 "数字" 类(运行时显式排除 bool)。
180
+ RUN_FIELD_TYPES: dict[str, Any] = {
181
+ "text": str,
182
+ "bold": bool,
183
+ "italic": bool,
184
+ "underline": bool,
185
+ "color_hex": str,
186
+ "size_pt": (int, float),
187
+ "font": str,
188
+ "east_asia_font": str,
189
+ }
190
+
191
+ # add_heading.level 取值范围(doc-create.md:0=Title,1~4=章节标题)。
192
+ HEADING_LEVEL_MIN: int = 0
193
+ HEADING_LEVEL_MAX: int = 4
194
+
195
+ # 结构化输入上限:在校验阶段尽早拒绝异常输入,避免下游构建 / 序列化
196
+ MAX_COMMANDS: int = 5000 # 单份 JSONL 的命令条数上限
197
+ MAX_TEXT_CHARS: int = 20000 # 段落 text / run.text 单字段长度上限
198
+ MAX_RUNS_PER_PARAGRAPH: int = 200 # 单段 runs 数组长度上限
199
+ MAX_TABLE_ROWS: int = 10000 # 单表行数上限
200
+ MAX_TABLE_COLS: int = 50 # 单行列数上限
201
+ MAX_CELL_TEXT_CHARS: int = 5000 # 表格 cell(字符串或 run.text)长度上限
202
+
203
+
204
+ def _spec_raise(ctx: str, msg: str) -> None:
205
+ raise SpecTypeError(f"{ctx}: {msg}")
206
+
207
+
208
+ def _spec_type_name(expected: Any) -> str:
209
+ if isinstance(expected, type):
210
+ return expected.__name__
211
+ if isinstance(expected, tuple):
212
+ return " | ".join(t.__name__ for t in expected if isinstance(t, type))
213
+ return str(expected)
214
+
215
+
216
+ def _spec_check_type(value: Any, expected: Any, ctx: str, name: str) -> None:
217
+ """对值做基础类型检查;显式拒绝 bool 充当 int/float。"""
218
+ if expected is int:
219
+ if isinstance(value, bool) or not isinstance(value, int):
220
+ _spec_raise(ctx, f"参数 '{name}' 类型错误,期望 int,实际 {type(value).__name__}")
221
+ return
222
+ if expected is bool:
223
+ if not isinstance(value, bool):
224
+ _spec_raise(ctx, f"参数 '{name}' 类型错误,期望 bool,实际 {type(value).__name__}")
225
+ return
226
+ if isinstance(expected, tuple) and int in expected and float in expected:
227
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
228
+ _spec_raise(ctx, f"参数 '{name}' 类型错误,期望 number,实际 {type(value).__name__}")
229
+ return
230
+ if not isinstance(value, expected):
231
+ _spec_raise(
232
+ ctx,
233
+ f"参数 '{name}' 类型错误,期望 {_spec_type_name(expected)},"
234
+ f"实际 {type(value).__name__}",
235
+ )
236
+
237
+
238
+ def _spec_check_hex_color(value: Any, ctx: str, name: str) -> None:
239
+ if not (isinstance(value, str) and _HEX_COLOR_RE.match(value)):
240
+ _spec_raise(
241
+ ctx,
242
+ f"参数 '{name}' 必须是 6 位十六进制颜色字符串"
243
+ f"(如 'FF0000' 或 '#FF0000'),实际为 {value!r}",
244
+ )
245
+
246
+
247
+ def _spec_validate_run_object(
248
+ obj: Any,
249
+ ctx: str,
250
+ max_text_chars: int = MAX_TEXT_CHARS,
251
+ ) -> None:
252
+ """校验一个 run / table-cell 对象(字段集合相同)。
253
+
254
+ ``max_text_chars`` 控制 ``text`` 字段的长度上限:段落里的 run 沿用
255
+ ``MAX_TEXT_CHARS``;表格 cell 上下文则收窄到 ``MAX_CELL_TEXT_CHARS``。
256
+ """
257
+ if not isinstance(obj, dict):
258
+ _spec_raise(ctx, f"必须是 JSON 对象(dict),实际 {type(obj).__name__}")
259
+
260
+ unknown = set(obj) - set(RUN_FIELD_TYPES)
261
+ if unknown:
262
+ _spec_raise(
263
+ ctx,
264
+ f"包含未知字段 {sorted(unknown)};允许字段: {sorted(RUN_FIELD_TYPES)}",
265
+ )
266
+
267
+ for fname, expected in RUN_FIELD_TYPES.items():
268
+ if fname not in obj:
269
+ continue
270
+ _spec_check_type(obj[fname], expected, ctx, fname)
271
+
272
+ if "text" in obj and len(obj["text"]) > max_text_chars:
273
+ _spec_raise(
274
+ ctx,
275
+ f"参数 'text' 长度 {len(obj['text'])} 超过上限 {max_text_chars} 字符",
276
+ )
277
+
278
+ if "color_hex" in obj:
279
+ _spec_check_hex_color(obj["color_hex"], ctx, "color_hex")
280
+
281
+ if "size_pt" in obj:
282
+ size = obj["size_pt"]
283
+ if size < 1 or size > 819:
284
+ _spec_raise(ctx, f"参数 'size_pt' 必须在 [1, 819] 范围内,实际为 {size}")
285
+
286
+
287
+ def _spec_validate_add_paragraph(params: dict, ctx: str) -> None:
288
+ allowed = {"text", "runs", "style", "alignment"}
289
+ unknown = set(params) - allowed
290
+ if unknown:
291
+ _spec_raise(
292
+ ctx,
293
+ f"add_paragraph 含未知参数 {sorted(unknown)};允许参数: {sorted(allowed)}",
294
+ )
295
+
296
+ if "text" in params:
297
+ _spec_check_type(params["text"], str, ctx, "text")
298
+ if len(params["text"]) > MAX_TEXT_CHARS:
299
+ _spec_raise(
300
+ ctx,
301
+ f"参数 'text' 长度 {len(params['text'])} 超过上限 "
302
+ f"{MAX_TEXT_CHARS} 字符",
303
+ )
304
+
305
+ if "runs" in params:
306
+ runs = params["runs"]
307
+ if not isinstance(runs, list):
308
+ _spec_raise(ctx, f"参数 'runs' 必须是数组,实际 {type(runs).__name__}")
309
+ if len(runs) > MAX_RUNS_PER_PARAGRAPH:
310
+ _spec_raise(
311
+ ctx,
312
+ f"参数 'runs' 数量 {len(runs)} 超过上限 "
313
+ f"{MAX_RUNS_PER_PARAGRAPH}",
314
+ )
315
+ for i, r in enumerate(runs):
316
+ _spec_validate_run_object(r, f"{ctx}.runs[{i}]")
317
+
318
+ if "style" in params:
319
+ style = params["style"]
320
+ if not isinstance(style, str) or style not in ALLOWED_PARAGRAPH_STYLES:
321
+ _spec_raise(
322
+ ctx,
323
+ f"参数 'style' 必须是 {sorted(ALLOWED_PARAGRAPH_STYLES)} 之一,"
324
+ f"实际为 {style!r}",
325
+ )
326
+
327
+ if "alignment" in params:
328
+ align = params["alignment"]
329
+ if not isinstance(align, str) or align not in ALLOWED_ALIGNMENTS:
330
+ _spec_raise(
331
+ ctx,
332
+ f"参数 'alignment' 必须是 {sorted(ALLOWED_ALIGNMENTS)} 之一,"
333
+ f"实际为 {align!r}",
334
+ )
335
+
336
+
337
+ def _spec_validate_add_heading(params: dict, ctx: str) -> None:
338
+ allowed = {"text", "level"}
339
+ unknown = set(params) - allowed
340
+ if unknown:
341
+ _spec_raise(
342
+ ctx,
343
+ f"add_heading 含未知参数 {sorted(unknown)};允许参数: {sorted(allowed)}",
344
+ )
345
+
346
+ if "text" in params:
347
+ _spec_check_type(params["text"], str, ctx, "text")
348
+
349
+ if "level" in params:
350
+ level = params["level"]
351
+ if isinstance(level, bool) or not isinstance(level, int):
352
+ _spec_raise(ctx, f"参数 'level' 必须是整数,实际为 {type(level).__name__}")
353
+ if not (HEADING_LEVEL_MIN <= level <= HEADING_LEVEL_MAX):
354
+ _spec_raise(
355
+ ctx,
356
+ f"参数 'level' 必须在 [{HEADING_LEVEL_MIN}, {HEADING_LEVEL_MAX}] 之间"
357
+ f"(0=封面主标题 Title,1~4=一~四级章节标题),实际为 {level}",
358
+ )
359
+
360
+
361
+ def _spec_validate_add_table(params: dict, ctx: str) -> None:
362
+ allowed = {"data"}
363
+ unknown = set(params) - allowed
364
+ if unknown:
365
+ _spec_raise(
366
+ ctx,
367
+ f"add_table 含未知参数 {sorted(unknown)};仅支持参数: {sorted(allowed)}",
368
+ )
369
+
370
+ if "data" not in params:
371
+ _spec_raise(ctx, "add_table 缺少必填参数 'data'")
372
+
373
+ data = params["data"]
374
+ if not isinstance(data, list):
375
+ _spec_raise(ctx, f"参数 'data' 必须是二维数组,实际 {type(data).__name__}")
376
+ if not data:
377
+ _spec_raise(ctx, "参数 'data' 不能为空数组")
378
+ if len(data) > MAX_TABLE_ROWS:
379
+ _spec_raise(
380
+ ctx,
381
+ f"参数 'data' 行数 {len(data)} 超过上限 {MAX_TABLE_ROWS}",
382
+ )
383
+
384
+ for ri, row in enumerate(data):
385
+ if not isinstance(row, list):
386
+ _spec_raise(
387
+ ctx,
388
+ f"参数 'data[{ri}]' 必须是数组(一行 cells),实际 {type(row).__name__}",
389
+ )
390
+ if len(row) > MAX_TABLE_COLS:
391
+ _spec_raise(
392
+ ctx,
393
+ f"参数 'data[{ri}]' 列数 {len(row)} 超过上限 {MAX_TABLE_COLS}",
394
+ )
395
+ for ci, cell in enumerate(row):
396
+ cell_ctx = f"{ctx}.data[{ri}][{ci}]"
397
+ if isinstance(cell, str):
398
+ if len(cell) > MAX_CELL_TEXT_CHARS:
399
+ _spec_raise(
400
+ cell_ctx,
401
+ f"cell 文本长度 {len(cell)} 超过上限 "
402
+ f"{MAX_CELL_TEXT_CHARS} 字符",
403
+ )
404
+ continue
405
+ if isinstance(cell, dict):
406
+ _spec_validate_run_object(
407
+ cell, cell_ctx, max_text_chars=MAX_CELL_TEXT_CHARS,
408
+ )
409
+ continue
410
+ _spec_raise(
411
+ cell_ctx,
412
+ f"cell 必须是字符串或 dict(单 run 对象),实际 {type(cell).__name__}",
413
+ )
414
+
415
+
416
+ def _spec_validate_add_page_break(params: dict, ctx: str) -> None:
417
+ if params:
418
+ _spec_raise(ctx, f"add_page_break 不接受任何参数,实际为 {params!r}")
419
+
420
+
421
+ # action 名称 → 校验函数;同时充当 "合法 action 集合"。
422
+ _SPEC_ACTION_VALIDATORS: dict[str, Any] = {
423
+ "add_paragraph": _spec_validate_add_paragraph,
424
+ "add_heading": _spec_validate_add_heading,
425
+ "add_table": _spec_validate_add_table,
426
+ "add_page_break": _spec_validate_add_page_break,
427
+ }
428
+
429
+
430
+ def _spec_validate_command(cmd: Any, line_no: int) -> tuple[str, dict]:
431
+ """校验单条 JSONL 命令,返回 ``(action, params)`` 便于派发器复用。"""
432
+ ctx = f"Line {line_no}"
433
+
434
+ if not isinstance(cmd, dict):
435
+ _spec_raise(ctx, f"每行必须是 JSON 对象,实际 {type(cmd).__name__}")
436
+
437
+ extra = set(cmd) - {"action", "params"}
438
+ if extra:
439
+ _spec_raise(ctx, f"命令仅允许 'action' / 'params' 字段,多余字段: {sorted(extra)}")
440
+
441
+ if "action" not in cmd:
442
+ _spec_raise(ctx, "缺少必填字段 'action'")
443
+
444
+ action = cmd["action"]
445
+ if not isinstance(action, str):
446
+ _spec_raise(ctx, f"'action' 必须是字符串,实际 {type(action).__name__}")
447
+ if action not in _SPEC_ACTION_VALIDATORS:
448
+ _spec_raise(
449
+ ctx,
450
+ f"未知的 action {action!r},允许的 action: {sorted(_SPEC_ACTION_VALIDATORS)}",
451
+ )
452
+
453
+ params = cmd.get("params", {})
454
+ if not isinstance(params, dict):
455
+ _spec_raise(ctx, f"'params' 必须是 JSON 对象,实际 {type(params).__name__}")
456
+
457
+ _SPEC_ACTION_VALIDATORS[action](params, f"{ctx} action='{action}'")
458
+ return action, params
459
+
460
+
461
+ # ===========================================================================
462
+ # Local IO helpers
463
+ # ===========================================================================
464
+
465
+ # 读入 / 写出文件的大小硬上限:30 MiB。
466
+ # - 读入:避免一次性把巨型 JSONL 拉进内存撑爆进程;
467
+ # - 写出:避免生成过大的 .docx 写入磁盘。
468
+ MAX_FILE_SIZE_BYTES = 30 * 1024 * 1024
469
+
470
+
471
+ def _read_text(path: str) -> str:
472
+ """Read a UTF-8 text file without applying directory restrictions.
473
+
474
+ 最多读取 ``MAX_FILE_SIZE_BYTES + 1`` 字节,以便在不把超大文件
475
+ 整体载入内存的前提下判断是否超限。
476
+ """
477
+ with open(path, "rb") as f:
478
+ data = f.read(MAX_FILE_SIZE_BYTES + 1)
479
+ if len(data) > MAX_FILE_SIZE_BYTES:
480
+ raise ValueError(
481
+ f"输入文件过大:{path!r} "
482
+ f"超过上限 {MAX_FILE_SIZE_BYTES} 字节(30 MiB)"
483
+ )
484
+ return data.decode("utf-8")
485
+
486
+
487
+ def _write_bytes(path: str, data: bytes) -> None:
488
+ """Write binary data without applying directory restrictions."""
489
+ if len(data) > MAX_FILE_SIZE_BYTES:
490
+ raise ValueError(
491
+ f"输出文件过大:{len(data)} 字节,"
492
+ f"超过上限 {MAX_FILE_SIZE_BYTES} 字节(30 MiB)"
493
+ )
494
+
495
+ parent = os.path.dirname(os.path.abspath(path))
496
+ os.makedirs(parent, exist_ok=True)
497
+ with open(path, "xb") as f:
498
+ f.write(data)
499
+
500
+
501
+ # ===========================================================================
502
+ # Generic OOXML helpers
503
+ # ===========================================================================
504
+ #
505
+ # 注:颜色 / 数值 / 取值合法性已在上游 _spec_validate_command 阶段校验,
506
+ # 此处不再重复检查;下游 helpers 仅负责生成 OOXML 元素。
507
+
508
+
509
+ def _hex_to_rgb(color_hex: str) -> RGBColor:
510
+ s = color_hex.lstrip("#")
511
+ return RGBColor(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
512
+
513
+
514
+ def _set_unique_child(parent, tag, new_el, insert_before=()) -> None:
515
+ """Replace any existing ``tag`` children of ``parent`` with ``new_el``,
516
+ inserting ahead of the first sibling listed in ``insert_before`` (the
517
+ XSD ordering constraint). Falls back to append."""
518
+ for existing in parent.findall(tag):
519
+ parent.remove(existing)
520
+ for sibling_tag in insert_before:
521
+ sibling = parent.find(sibling_tag)
522
+ if sibling is not None:
523
+ sibling.addprevious(new_el)
524
+ return
525
+ parent.append(new_el)
526
+
527
+
528
+ def _set_east_asia_font(rPr, font_name: str) -> None:
529
+ """Set ``w:eastAsia`` on the rFonts child of ``rPr`` (creating it if needed)."""
530
+ rFonts = rPr.find(qn("w:rFonts"))
531
+ if rFonts is None:
532
+ rFonts = OxmlElement("w:rFonts")
533
+ rPr.insert(0, rFonts)
534
+ rFonts.set(qn("w:eastAsia"), font_name)
535
+
536
+
537
+ def _strip_theme_color(element) -> None:
538
+ """Remove ``themeColor``/``themeTint``/``themeShade`` from every
539
+ ``w:color`` under ``element``.
540
+
541
+ Built-in heading styles ship with theme-tinted colors that many
542
+ renderers prefer over the explicit ``w:val``, leaking the accent
543
+ color (typically blue) instead of the requested RGB.
544
+ """
545
+ color_tag = qn("w:color")
546
+ color_attrs = (qn("w:themeColor"), qn("w:themeTint"), qn("w:themeShade"))
547
+ for color_el in element.iter(color_tag):
548
+ for key in color_attrs:
549
+ if key in color_el.attrib:
550
+ del color_el.attrib[key]
551
+
552
+
553
+ def _force_color_on_rpr(rPr, color_hex: str) -> None:
554
+ """Replace any ``<w:color>`` under ``rPr`` with a plain ``w:val`` one
555
+ (no theme attributes)."""
556
+ for existing in rPr.findall(qn("w:color")):
557
+ rPr.remove(existing)
558
+ color_el = OxmlElement("w:color")
559
+ color_el.set(qn("w:val"), color_hex.lstrip("#").upper())
560
+ rFonts = rPr.find(qn("w:rFonts"))
561
+ if rFonts is not None:
562
+ rFonts.addnext(color_el)
563
+ else:
564
+ rPr.insert(0, color_el)
565
+
566
+
567
+ def _apply_run_format(run, spec: dict) -> None:
568
+ """Apply formatting from a run-spec dict to a python-docx Run."""
569
+ if spec.get("bold"):
570
+ run.bold = True
571
+ if spec.get("italic"):
572
+ run.italic = True
573
+ if spec.get("underline"):
574
+ run.underline = True
575
+ if "color_hex" in spec:
576
+ run.font.color.rgb = _hex_to_rgb(spec["color_hex"])
577
+ if "size_pt" in spec:
578
+ run.font.size = Pt(spec["size_pt"])
579
+ if "font" in spec:
580
+ run.font.name = spec["font"]
581
+ if "east_asia_font" in spec:
582
+ _set_east_asia_font(run._element.get_or_add_rPr(), spec["east_asia_font"])
583
+
584
+
585
+ def _make_borders_el(wrapper_tag: str, sides: tuple, color_hex: str, size: int):
586
+ """Build a ``<w:tblBorders>`` / ``<w:tcBorders>`` element with all
587
+ sides sharing the same single-line style, size and color."""
588
+ inner = "".join(
589
+ f'<w:{s} w:val="single" w:sz="{size}" w:color="{color_hex}"/>'
590
+ for s in sides
591
+ )
592
+ return parse_xml(f'<w:{wrapper_tag} {nsdecls("w")}>{inner}</w:{wrapper_tag}>')
593
+
594
+
595
+ # ===========================================================================
596
+ # DocxBuilder — every public method (no leading underscore) is a JSONL action
597
+ # ===========================================================================
598
+
599
+
600
+ class DocxBuilder:
601
+ """Each public method (no leading underscore) is callable as an `action`.
602
+
603
+ 所有方法不再做内部参数校验,调用方(``_dispatch``)保证传入的参数
604
+ 已通过上游 ``_spec_validate_command`` 检查。
605
+ """
606
+
607
+ def __init__(self) -> None:
608
+ self.doc: Any = None # python-docx Document
609
+
610
+ # -- 0. Default initialization -----------------------------------------
611
+
612
+ def _init_defaults(self) -> None:
613
+ """Run document + page + Normal + heading defaults. Called once by
614
+ ``run_jsonl`` before any user action; spec-level setup_* overrides win."""
615
+ self._create_document()
616
+ self.setup_page()
617
+ self.setup_normal_style()
618
+ for preset in _DEFAULT_HEADINGS:
619
+ self.setup_heading_style(
620
+ style_name=preset.style_name,
621
+ size_pt=preset.size_pt,
622
+ color_hex=preset.color_hex,
623
+ alignment=preset.alignment,
624
+ )
625
+
626
+ # -- 1. Document lifecycle --------------------------------------------
627
+
628
+ def _create_document(self) -> None:
629
+ # Underscore-prefixed: not exposed as a JSONL action — calling it
630
+ # twice would replace ``self.doc`` and drop everything written so far.
631
+ self.doc = Document()
632
+ settings = self.doc.settings.element
633
+ zoom = settings.find(qn("w:zoom"))
634
+ if zoom is not None and zoom.get(qn("w:percent")) is None:
635
+ zoom.set(qn("w:percent"), "100")
636
+
637
+ def save(self, path: str) -> None:
638
+ """Persist the document to the local filesystem.
639
+
640
+ Exclusive-create mode enforces the "never clobber an existing .docx"
641
+ guarantee that ``_pick_output_path`` makes when picking the filename.
642
+
643
+ 在写入之前校验序列化后的 docx 体积不得超过
644
+ ``MAX_FILE_SIZE_BYTES``;超限直接抛 ``ValueError`` 中止保存。
645
+ """
646
+ buf = io.BytesIO()
647
+ self.doc.save(buf)
648
+ size = buf.tell()
649
+ if size > MAX_FILE_SIZE_BYTES:
650
+ raise ValueError(
651
+ f"输出文件过大:序列化后 {size} 字节,"
652
+ f"超过上限 {MAX_FILE_SIZE_BYTES} 字节(30 MiB)"
653
+ )
654
+ _write_bytes(path, buf.getvalue())
655
+
656
+ # -- 2. Page setup ----------------------------------------------------
657
+
658
+ def setup_page(
659
+ self,
660
+ width_cm: float = 21,
661
+ height_cm: float = 29.7,
662
+ top_cm: float = 2.4,
663
+ bottom_cm: float = 2.4,
664
+ left_cm: float = 2.5,
665
+ right_cm: float = 2.5,
666
+ header_cm: float = 1.27,
667
+ footer_cm: float = 1.27,
668
+ ) -> None:
669
+ section = self.doc.sections[0]
670
+ section.page_width = Cm(width_cm)
671
+ section.page_height = Cm(height_cm)
672
+ section.top_margin = Cm(top_cm)
673
+ section.bottom_margin = Cm(bottom_cm)
674
+ section.left_margin = Cm(left_cm)
675
+ section.right_margin = Cm(right_cm)
676
+ section.header_distance = Cm(header_cm)
677
+ section.footer_distance = Cm(footer_cm)
678
+
679
+ # -- 3. Style setup ---------------------------------------------------
680
+
681
+ def setup_normal_style(
682
+ self,
683
+ font: str = "Arial",
684
+ east_asia_font: str = "微软雅黑",
685
+ size_pt: float = 11,
686
+ color_hex: str = "333333",
687
+ before_dxa: int = 60,
688
+ after_dxa: int = 60,
689
+ line_dxa: int = DEFAULT_LINE_DXA_NORMAL,
690
+ widow_control: bool = False,
691
+ snap_to_grid: bool = False,
692
+ ) -> None:
693
+ style = self.doc.styles["Normal"]
694
+ style.font.name = font
695
+ style.font.size = Pt(size_pt)
696
+ style.font.color.rgb = _hex_to_rgb(color_hex)
697
+
698
+ rPr = style.element.get_or_add_rPr()
699
+ _set_east_asia_font(rPr, east_asia_font)
700
+
701
+ style.paragraph_format.widow_control = widow_control
702
+
703
+ pPr = style.element.get_or_add_pPr()
704
+
705
+ snap = OxmlElement("w:snapToGrid")
706
+ snap.set(qn("w:val"), "1" if snap_to_grid else "0")
707
+ _set_unique_child(pPr, qn("w:snapToGrid"), snap, _PPR_SPACING_ANCHORS)
708
+
709
+ sp = self._make_spacing_el(before_dxa, after_dxa, line_dxa)
710
+ _set_unique_child(pPr, qn("w:spacing"), sp, _PPR_SPACING_ANCHORS)
711
+
712
+ def setup_heading_style(
713
+ self,
714
+ style_name: str,
715
+ size_pt: float,
716
+ color_hex: str = "1A1A1A",
717
+ bold: bool = True,
718
+ font: str = "Arial",
719
+ line_dxa: int = DEFAULT_LINE_DXA_HEADING,
720
+ before_dxa: int = 0,
721
+ after_dxa: int = 0,
722
+ alignment: str | None = None,
723
+ keep_with_next: bool = True,
724
+ keep_together: bool = True,
725
+ ) -> None:
726
+ """Configure Title / Subtitle / Heading 1..N styles.
727
+
728
+ 仅由 ``_init_defaults`` 内部调用,传入的参数来自 ``_DEFAULT_HEADINGS``
729
+ 预置常量,已知合法;不再做单独校验。
730
+ """
731
+ style = self.doc.styles[style_name]
732
+ style.font.name = font
733
+ style.font.size = Pt(size_pt)
734
+ style.font.bold = bold
735
+ style.font.color.rgb = _hex_to_rgb(color_hex)
736
+ style.paragraph_format.space_before = Pt(0)
737
+ style.paragraph_format.space_after = Pt(0)
738
+ style.paragraph_format.keep_with_next = keep_with_next
739
+ style.paragraph_format.keep_together = keep_together
740
+ if alignment is not None:
741
+ style.paragraph_format.alignment = _PARAGRAPH_ALIGN[alignment]
742
+
743
+ pPr = style.element.get_or_add_pPr()
744
+ sp = self._make_spacing_el(before_dxa, after_dxa, line_dxa)
745
+ _set_unique_child(pPr, qn("w:spacing"), sp, _PPR_SPACING_ANCHORS)
746
+
747
+ # Drop the decorative theme-accent bottom border that built-in
748
+ # Title (and a few headings) ship with.
749
+ for pBdr in pPr.findall(qn("w:pBdr")):
750
+ pPr.remove(pBdr)
751
+
752
+ # Strip themeColor/Tint/Shade everywhere in the style element so
753
+ # the requested RGB actually wins on renderers that prefer theme.
754
+ _strip_theme_color(style.element)
755
+
756
+ # Mirror the color onto the paired *character* style (Title↔TitleChar,
757
+ # Heading 1↔Heading1Char, …): some renderers (WPS, Word for Mac /
758
+ # Online, the WeCom doc preview) apply the linked char style's rPr
759
+ # to runs in preference to the paragraph style's rPr.
760
+ self._sync_linked_char_style_color(style, color_hex)
761
+
762
+ # Strip leaked python-docx template defaults and add bCs/szCs that
763
+ # the high-level setters skip; do the same on the linked char style.
764
+ self._normalize_heading_style_element(style.element, bold)
765
+ linked_char = self._resolve_linked_char_style_element(style)
766
+ if linked_char is not None:
767
+ self._normalize_heading_style_element(linked_char, bold)
768
+
769
+ @staticmethod
770
+ def _make_spacing_el(before_dxa: int, after_dxa: int, line_dxa: int):
771
+ sp = OxmlElement("w:spacing")
772
+ sp.set(qn("w:before"), str(before_dxa))
773
+ sp.set(qn("w:after"), str(after_dxa))
774
+ sp.set(qn("w:line"), str(line_dxa))
775
+ sp.set(qn("w:lineRule"), "auto")
776
+ return sp
777
+
778
+ def _sync_linked_char_style_color(self, paragraph_style, color_hex: str) -> None:
779
+ """Mirror ``color_hex`` onto the paragraph style's linked char style
780
+ (silent no-op if there is no link or it cannot be resolved)."""
781
+ target = self._resolve_linked_char_style_element(paragraph_style)
782
+ if target is None:
783
+ return
784
+ rPr = target.find(qn("w:rPr"))
785
+ if rPr is None:
786
+ rPr = OxmlElement("w:rPr")
787
+ target.append(rPr)
788
+ _force_color_on_rpr(rPr, color_hex)
789
+
790
+ def _resolve_linked_char_style_element(self, paragraph_style):
791
+ """Return the ``<w:style>`` element of the linked char style, or None."""
792
+ link_el = paragraph_style.element.find(qn("w:link"))
793
+ if link_el is None:
794
+ return None
795
+ char_style_id = link_el.get(qn("w:val"))
796
+ if not char_style_id:
797
+ return None
798
+ for s in self.doc.styles.element.findall(qn("w:style")):
799
+ if s.get(qn("w:styleId")) == char_style_id:
800
+ return s
801
+ return None
802
+
803
+ @staticmethod
804
+ def _normalize_heading_style_element(style_element, bold: bool) -> None:
805
+ """Strip python-docx template defaults on built-in heading styles
806
+ and add the bCs / szCs siblings that high-level setters skip.
807
+
808
+ Removed: pPr/contextualSpacing (Title), pPr/numPr (Subtitle),
809
+ rPr/i, rPr/iCs, rPr/spacing, rPr/kern, and theme-bound rFonts
810
+ attributes (asciiTheme/hAnsiTheme/eastAsiaTheme/cstheme).
811
+ Added: rPr/bCs (paired with rPr/b) for CJK / complex-script bold;
812
+ rPr/szCs synced to rPr/sz so font.size actually applies.
813
+ """
814
+ pPr = style_element.find(qn("w:pPr"))
815
+ if pPr is not None:
816
+ for tag in ("w:contextualSpacing", "w:numPr"):
817
+ for child in pPr.findall(qn(tag)):
818
+ pPr.remove(child)
819
+
820
+ rPr = style_element.find(qn("w:rPr"))
821
+ if rPr is None:
822
+ return
823
+
824
+ for tag in ("w:i", "w:iCs", "w:spacing", "w:kern"):
825
+ for child in rPr.findall(qn(tag)):
826
+ rPr.remove(child)
827
+
828
+ rFonts = rPr.find(qn("w:rFonts"))
829
+ if rFonts is not None:
830
+ for attr in (
831
+ "w:asciiTheme",
832
+ "w:hAnsiTheme",
833
+ "w:eastAsiaTheme",
834
+ "w:cstheme",
835
+ ):
836
+ key = qn(attr)
837
+ if key in rFonts.attrib:
838
+ del rFonts.attrib[key]
839
+
840
+ if bold:
841
+ b = rPr.find(qn("w:b"))
842
+ if b is not None and rPr.find(qn("w:bCs")) is None:
843
+ bCs = OxmlElement("w:bCs")
844
+ b.addnext(bCs)
845
+
846
+ sz = rPr.find(qn("w:sz"))
847
+ if sz is not None:
848
+ sz_val = sz.get(qn("w:val"))
849
+ if sz_val:
850
+ szCs = rPr.find(qn("w:szCs"))
851
+ if szCs is None:
852
+ szCs = OxmlElement("w:szCs")
853
+ sz.addnext(szCs)
854
+ szCs.set(qn("w:val"), sz_val)
855
+
856
+ # -- 4. Content blocks ------------------------------------------------
857
+
858
+ def add_heading(self, text: str = "", level: int = 1) -> None:
859
+ self.doc.add_heading(text, level=level)
860
+
861
+ def add_paragraph(
862
+ self,
863
+ text: str | None = None,
864
+ runs: list[dict] | None = None,
865
+ style: str | None = None,
866
+ alignment: str | None = None,
867
+ ) -> None:
868
+ """Add a paragraph.
869
+
870
+ - ``text`` : single-run plain text.
871
+ - ``runs`` : list of run-specs (bold/italic/color/size...). If both
872
+ ``text`` and ``runs`` are given, ``runs`` wins.
873
+ - ``style`` : built-in style name, e.g. 'List Bullet', 'List Number',
874
+ 'Subtitle'.
875
+ """
876
+ p = self.doc.add_paragraph(style=style) if style else self.doc.add_paragraph()
877
+ if alignment:
878
+ p.alignment = _PARAGRAPH_ALIGN[alignment]
879
+ if runs:
880
+ for r in runs:
881
+ run = p.add_run(r.get("text", ""))
882
+ _apply_run_format(run, r)
883
+ elif text is not None:
884
+ p.add_run(text)
885
+
886
+ def add_page_break(self) -> None:
887
+ self.doc.add_page_break()
888
+
889
+ # -- 5. Table ---------------------------------------------------------
890
+
891
+ def add_table(
892
+ self,
893
+ data: list,
894
+ col_widths_dxa: list[int] | None = None,
895
+ total_width_dxa: int = DEFAULT_TABLE_TOTAL_DXA,
896
+ border_color_hex: str = DEFAULT_CELL_BORDER_COLOR_HEX,
897
+ border_size: int = DEFAULT_CELL_BORDER_SIZE,
898
+ cell_margin_dxa: tuple | list = (0, 108, 0, 108), # top, left, bottom, right
899
+ header_shading_hex: str | None = None,
900
+ alignment: str = "center",
901
+ cell_v_align: str = "center",
902
+ ) -> None:
903
+ """Add a fixed-layout table.
904
+
905
+ ``data`` is a list of rows. Each row is a list of cells. A cell can
906
+ be a plain string OR a dict like
907
+ ``{"text": "...", "bold": true, "color_hex": "FF0000"}``.
908
+
909
+ The first row is auto-tagged with ``<w:tblHeader/>`` so it repeats
910
+ on page breaks. Header shading is OFF by default — pass
911
+ ``header_shading_hex="2972F4"`` to opt in.
912
+ """
913
+ if not data:
914
+ return
915
+
916
+ rows = len(data)
917
+ cols = max(len(r) for r in data)
918
+ col_widths = self._resolve_col_widths(cols, col_widths_dxa, total_width_dxa)
919
+
920
+ table = self._create_blank_table(rows, cols, alignment)
921
+ self._apply_table_width(table)
922
+ self._apply_table_borders(
923
+ table,
924
+ DEFAULT_TABLE_BORDER_COLOR_HEX,
925
+ DEFAULT_TABLE_BORDER_SIZE,
926
+ )
927
+ self._apply_table_fixed_layout(table)
928
+ self._strip_table_look(table)
929
+ self._apply_table_grid(table, col_widths)
930
+ self._mark_header_row(table)
931
+ self._fill_table_cells(
932
+ table, data, col_widths,
933
+ cell_margin_dxa, header_shading_hex, cell_v_align,
934
+ border_color_hex, border_size,
935
+ )
936
+
937
+ # -- 5.1 Table internals ---------------------------------------------
938
+
939
+ @staticmethod
940
+ def _resolve_col_widths(
941
+ cols: int,
942
+ col_widths_dxa: list[int] | None,
943
+ total_width_dxa: int,
944
+ ) -> list[int]:
945
+ if col_widths_dxa:
946
+ return list(col_widths_dxa)
947
+ base = total_width_dxa // cols
948
+ widths = [base] * cols
949
+ widths[-1] += total_width_dxa - base * cols # absorb rounding
950
+ return widths
951
+
952
+ def _create_blank_table(self, rows: int, cols: int, alignment: str):
953
+ # Intentionally no ``table.style = "Table Grid"`` — we provide all
954
+ # visual properties explicitly, and a built-in style would leak its
955
+ # own border / shading defaults.
956
+ table = self.doc.add_table(rows=rows, cols=cols)
957
+ table.alignment = _TABLE_ALIGN.get(alignment, WD_TABLE_ALIGNMENT.CENTER)
958
+ return table
959
+
960
+ @staticmethod
961
+ def _apply_table_width(table) -> None:
962
+ # ``tblW`` declares ``auto``; the actual width is dictated by
963
+ # ``tblLayout=fixed`` plus the explicit ``<w:gridCol>`` widths.
964
+ tblPr = table._tbl.tblPr
965
+ tblW = OxmlElement("w:tblW")
966
+ tblW.set(qn("w:w"), "0")
967
+ tblW.set(qn("w:type"), "auto")
968
+ _set_unique_child(tblPr, qn("w:tblW"), tblW, _TBL_PR_TBLW_ANCHORS)
969
+
970
+ @staticmethod
971
+ def _apply_table_borders(table, color_hex: str, size: int) -> None:
972
+ # Table-level frame only; per-cell borders are added separately so
973
+ # the grid stays visible on renderers that ignore <w:tblBorders>.
974
+ tblPr = table._tbl.tblPr
975
+ el = _make_borders_el(
976
+ "tblBorders",
977
+ ("top", "left", "bottom", "right", "insideH", "insideV"),
978
+ color_hex,
979
+ size,
980
+ )
981
+ _set_unique_child(tblPr, qn("w:tblBorders"), el, _TBL_PR_BORDERS_ANCHORS)
982
+
983
+ @staticmethod
984
+ def _apply_table_fixed_layout(table) -> None:
985
+ tblPr = table._tbl.tblPr
986
+ el = OxmlElement("w:tblLayout")
987
+ el.set(qn("w:type"), "fixed")
988
+ _set_unique_child(tblPr, qn("w:tblLayout"), el, _TBL_PR_LAYOUT_ANCHORS)
989
+
990
+ @staticmethod
991
+ def _strip_table_look(table) -> None:
992
+ # We don't attach a table style, so <w:tblLook> (firstRow / banding /
993
+ # ... toggles) is inert noise relative to the target docx.
994
+ tblPr = table._tbl.tblPr
995
+ for el in tblPr.findall(qn("w:tblLook")):
996
+ tblPr.remove(el)
997
+
998
+ @staticmethod
999
+ def _apply_table_grid(table, col_widths_dxa: list[int]) -> None:
1000
+ grid = table._tbl.find(qn("w:tblGrid"))
1001
+ if grid is None:
1002
+ return
1003
+ for col in list(grid.findall(qn("w:gridCol"))):
1004
+ grid.remove(col)
1005
+ for w in col_widths_dxa:
1006
+ gc = OxmlElement("w:gridCol")
1007
+ gc.set(qn("w:w"), str(w))
1008
+ grid.append(gc)
1009
+
1010
+ @staticmethod
1011
+ def _mark_header_row(table) -> None:
1012
+ # Tag the first row with <w:tblHeader/> so it repeats on page breaks.
1013
+ if not table.rows:
1014
+ return
1015
+ tr = table.rows[0]._tr
1016
+ trPr = tr.find(qn("w:trPr"))
1017
+ if trPr is None:
1018
+ trPr = OxmlElement("w:trPr")
1019
+ tr.insert(0, trPr) # trPr precedes <w:tc> per the OOXML schema
1020
+ if trPr.find(qn("w:tblHeader")) is None:
1021
+ trPr.append(OxmlElement("w:tblHeader"))
1022
+
1023
+ def _fill_table_cells(
1024
+ self,
1025
+ table,
1026
+ data: list,
1027
+ col_widths_dxa: list[int],
1028
+ cell_margin_dxa: tuple | list,
1029
+ header_shading_hex: str | None,
1030
+ cell_v_align: str,
1031
+ cell_border_color_hex: str,
1032
+ cell_border_size: int,
1033
+ ) -> None:
1034
+ cols = len(col_widths_dxa)
1035
+ for ri, row_data in enumerate(data):
1036
+ for ci in range(cols):
1037
+ cell = table.rows[ri].cells[ci]
1038
+ value = row_data[ci] if ci < len(row_data) else None
1039
+
1040
+ self._set_cell_width(cell, col_widths_dxa[ci])
1041
+ self._write_cell_content(cell, value)
1042
+
1043
+ # Apply tcBorders → shd → tcMar → vAlign in this order so
1044
+ # the anchor lookups in ``_set_unique_child`` resolve.
1045
+ self._apply_cell_borders(
1046
+ cell, cell_border_color_hex, cell_border_size,
1047
+ )
1048
+ if ri == 0 and header_shading_hex:
1049
+ self._apply_cell_shading(cell, header_shading_hex)
1050
+ self._apply_cell_margin(cell, cell_margin_dxa)
1051
+ self._apply_cell_v_align(cell, cell_v_align)
1052
+
1053
+ @staticmethod
1054
+ def _set_cell_width(cell, width_dxa: int) -> None:
1055
+ # cell.width takes EMU-typed Length; convert dxa → EMU.
1056
+ cell.width = Emu(width_dxa * EMU_PER_DXA)
1057
+
1058
+ @staticmethod
1059
+ def _write_cell_content(cell, value) -> None:
1060
+ # ``cell.text = ""`` leaves an empty <w:r/> placeholder that renders
1061
+ # as a stray empty run; clear runs on the first paragraph instead.
1062
+ p = cell.paragraphs[0]
1063
+ for run in list(p.runs):
1064
+ run._element.getparent().remove(run._element)
1065
+ if value is None:
1066
+ return
1067
+ if isinstance(value, dict):
1068
+ run = p.add_run(value.get("text", ""))
1069
+ _apply_run_format(run, value)
1070
+ else:
1071
+ p.add_run(str(value))
1072
+
1073
+ @staticmethod
1074
+ def _apply_cell_borders(cell, color_hex: str, size: int) -> None:
1075
+ # Per-cell <w:tcBorders> in addition to the table-level frame so
1076
+ # the grid stays intact on renderers that disagree on which level
1077
+ # of border is authoritative.
1078
+ tcPr = cell._tc.get_or_add_tcPr()
1079
+ el = _make_borders_el(
1080
+ "tcBorders",
1081
+ ("top", "left", "bottom", "right"),
1082
+ color_hex,
1083
+ size,
1084
+ )
1085
+ _set_unique_child(tcPr, qn("w:tcBorders"), el, _TC_PR_BORDERS_ANCHORS)
1086
+
1087
+ @staticmethod
1088
+ def _apply_cell_shading(cell, fill_hex: str) -> None:
1089
+ tcPr = cell._tc.get_or_add_tcPr()
1090
+ shd = parse_xml(
1091
+ f'<w:shd {nsdecls("w")} w:val="clear" '
1092
+ f'w:color="auto" w:fill="{fill_hex}"/>'
1093
+ )
1094
+ _set_unique_child(tcPr, qn("w:shd"), shd, _TC_PR_SHD_ANCHORS)
1095
+
1096
+ @staticmethod
1097
+ def _apply_cell_margin(cell, margin_dxa: tuple | list) -> None:
1098
+ # margin_dxa = (top, left, bottom, right).
1099
+ top, left, bottom, right = margin_dxa
1100
+ tcPr = cell._tc.get_or_add_tcPr()
1101
+ el = parse_xml(
1102
+ f'<w:tcMar {nsdecls("w")}>'
1103
+ f' <w:top w:w="{top}" w:type="dxa"/>'
1104
+ f' <w:left w:w="{left}" w:type="dxa"/>'
1105
+ f' <w:bottom w:w="{bottom}" w:type="dxa"/>'
1106
+ f' <w:right w:w="{right}" w:type="dxa"/>'
1107
+ f'</w:tcMar>'
1108
+ )
1109
+ _set_unique_child(tcPr, qn("w:tcMar"), el, _TC_PR_MAR_ANCHORS)
1110
+
1111
+ @staticmethod
1112
+ def _apply_cell_v_align(cell, val: str) -> None:
1113
+ tcPr = cell._tc.get_or_add_tcPr()
1114
+ el = parse_xml(f'<w:vAlign {nsdecls("w")} w:val="{val}"/>')
1115
+ _set_unique_child(tcPr, qn("w:vAlign"), el, _TC_PR_VALIGN_ANCHORS)
1116
+
1117
+
1118
+ # ===========================================================================
1119
+ # JSONL spec parsing
1120
+ # ===========================================================================
1121
+
1122
+
1123
+ def _iter_spec_commands(spec_path: str) -> Iterator[tuple[int, Any]]:
1124
+ """Yield ``(line_no, cmd)`` from a JSONL spec file.
1125
+
1126
+ Tolerates blank lines, leading UTF-8 BOM, ``//`` / ``#`` comment lines,
1127
+ and JSON objects pretty-printed across multiple lines (uses
1128
+ ``raw_decode`` to consume one object at a time). ``line_no`` is the
1129
+ 1-based line where each object *starts*.
1130
+ """
1131
+ text = _read_text(spec_path)
1132
+
1133
+ if text.startswith("\ufeff"):
1134
+ text = text[1:]
1135
+
1136
+ decoder = json.JSONDecoder()
1137
+ idx = 0
1138
+ n = len(text)
1139
+
1140
+ # Incremental newline counter: scans only the disjoint segment
1141
+ # text[line_cursor:idx] each iteration → O(N) total.
1142
+ line_cursor = 0
1143
+ line_no = 1
1144
+
1145
+ while idx < n:
1146
+ ch = text[idx]
1147
+
1148
+ if ch.isspace():
1149
+ idx += 1
1150
+ continue
1151
+
1152
+ if ch == "#" or text.startswith("//", idx):
1153
+ nl = text.find("\n", idx)
1154
+ if nl == -1:
1155
+ break
1156
+ idx = nl + 1
1157
+ continue
1158
+
1159
+ line_no += text.count("\n", line_cursor, idx)
1160
+ line_cursor = idx
1161
+ start_line = line_no
1162
+
1163
+ try:
1164
+ cmd, end = decoder.raw_decode(text, idx)
1165
+ except json.JSONDecodeError as e:
1166
+ raise SpecTypeError(f"Line {start_line}: invalid JSON: {e}") from e
1167
+
1168
+ yield start_line, cmd
1169
+ idx = end
1170
+
1171
+
1172
+ # ===========================================================================
1173
+ # Dispatcher & runner
1174
+ # ===========================================================================
1175
+
1176
+
1177
+ def _dispatch(builder: DocxBuilder, action: str, params: dict) -> None:
1178
+ """执行单条已通过校验的命令。
1179
+
1180
+ 上游 ``_spec_validate_command`` 已确保 ``action`` 合法且 ``params``
1181
+ 形态正确,这里直接派发到对应方法即可。
1182
+ """
1183
+ method = getattr(builder, action)
1184
+ method(**params)
1185
+
1186
+
1187
+ def run_jsonl(spec_path: str, output: str) -> str:
1188
+ if not output:
1189
+ raise SpecTypeError("An output path must be provided.")
1190
+
1191
+ # 1) 一次性把整份 JSONL 读出来,全部走完上游校验,再开始写文档。
1192
+ # 任何参数问题都会以 SpecTypeError("类型错误,无法执行") 抛出。
1193
+ # 命令总数受 MAX_COMMANDS 限制,超限立即中止以避免下游构建阶段
1194
+ # 因海量命令而 OOM / 卡死。
1195
+ commands: list[tuple[str, dict]] = []
1196
+ for line_no, cmd in _iter_spec_commands(spec_path):
1197
+ if len(commands) >= MAX_COMMANDS:
1198
+ raise SpecTypeError(
1199
+ f"Line {line_no}: 命令总数超过上限 {MAX_COMMANDS}"
1200
+ )
1201
+ action, params = _spec_validate_command(cmd, line_no)
1202
+ commands.append((action, params))
1203
+
1204
+ # 2) 校验通过 → 实际生成文档并保存。
1205
+ builder = DocxBuilder()
1206
+ builder._init_defaults()
1207
+ for action, params in commands:
1208
+ _dispatch(builder, action, params)
1209
+ builder.save(output)
1210
+
1211
+ return output
1212
+
1213
+
1214
+ # ===========================================================================
1215
+ # CLI
1216
+ # ===========================================================================
1217
+
1218
+
1219
+ def _pick_output_path(spec_path: str) -> str:
1220
+ """Pick a non-conflicting path beside the JSONL file.
1221
+
1222
+ The document is written to a ``docx/`` subdirectory of the JSONL file's
1223
+ directory. Its filename derives from the spec's stem
1224
+ (``report.jsonl`` → ``report.docx``); on conflict a timestamp suffix is
1225
+ appended to avoid overwriting.
1226
+ """
1227
+ spec = Path(spec_path).expanduser().resolve()
1228
+ target_dir = str(spec.parent / "docx")
1229
+ stem = spec.stem or "document"
1230
+ if not re.fullmatch(r"[A-Za-z0-9_.\-]{1,128}", stem):
1231
+ stem = "document"
1232
+
1233
+ candidate = os.path.join(target_dir, f"{stem}.docx")
1234
+ if not os.path.lexists(candidate):
1235
+ return candidate
1236
+ # Multi-user host: combine millisecond timestamp with PID to avoid
1237
+ # collisions between concurrent processes within the same millisecond.
1238
+ suffix = f"{int(time.time_ns() // 1_000_000)}_{os.getpid()}"
1239
+ candidate = os.path.join(target_dir, f"{stem}_{suffix}.docx")
1240
+ if not os.path.lexists(candidate):
1241
+ return candidate
1242
+ # 时间戳 + PID 仍然冲突属于极端异常情况,直接报错而非覆盖既有文件。
1243
+ raise FileExistsError(f"无法生成唯一的输出路径:{candidate} 已存在")
1244
+
1245
+
1246
+ def main() -> None:
1247
+ parser = argparse.ArgumentParser(
1248
+ description="Build a .docx file from a JSONL spec."
1249
+ )
1250
+ parser.add_argument("spec", help="Path to the JSONL spec file")
1251
+ args = parser.parse_args()
1252
+
1253
+ try:
1254
+ output = _pick_output_path(args.spec)
1255
+ except Exception:
1256
+ print("Error: failed to pick output path")
1257
+ sys.exit(2)
1258
+
1259
+ try:
1260
+ saved = run_jsonl(args.spec, output=output)
1261
+ except TypeError as e:
1262
+ # 上游 JSONL 校验抛出的 SpecTypeError(继承 TypeError),统一
1263
+ # 转译成 "类型错误,无法执行" 提示。
1264
+ print(f"Error: 类型错误,无法执行: {e}", file=sys.stderr)
1265
+ sys.exit(2)
1266
+ except Exception:
1267
+ print("Error: 执行失败,请检查输入文件格式或稍后重试", file=sys.stderr)
1268
+ sys.exit(2)
1269
+
1270
+ print(f"Successfully built {saved}")
1271
+
1272
+
1273
+ if __name__ == "__main__":
1274
+ main()