hostlet 0.0.0-stage → 0.1.0-alpha.2

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 (512) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -2
  3. package/bin/hostlet.js +61 -0
  4. package/console/app/api.js +1223 -0
  5. package/console/app/boot.js +165 -0
  6. package/console/app/cards.js +222 -0
  7. package/console/app/compose-quote.js +127 -0
  8. package/console/app/config-form.js +727 -0
  9. package/console/app/document-drafts.js +62 -0
  10. package/console/app/document-tools.mjs +67 -0
  11. package/console/app/documents.js +106 -0
  12. package/console/app/pages.js +6483 -0
  13. package/console/app/plugins.js +509 -0
  14. package/console/app/preview-tools.js +172 -0
  15. package/console/app/reference-labels.js +118 -0
  16. package/console/app/selection.js +372 -0
  17. package/console/app/store.js +57 -0
  18. package/console/app/text-anchor.js +26 -0
  19. package/console/app/topic-local.js +322 -0
  20. package/console/app/topic-nav.js +414 -0
  21. package/console/app/topic-status.js +109 -0
  22. package/console/app/views.js +43 -0
  23. package/console/apple-touch-icon.png +0 -0
  24. package/console/avatars/agy.svg +34 -0
  25. package/console/avatars/alhena.svg +36 -0
  26. package/console/avatars/castor.svg +38 -0
  27. package/console/avatars/claude.svg +34 -0
  28. package/console/avatars/codex.svg +34 -0
  29. package/console/avatars/devin.svg +34 -0
  30. package/console/avatars/echo.svg +34 -0
  31. package/console/avatars/kimi.svg +33 -0
  32. package/console/avatars/opencode.svg +33 -0
  33. package/console/avatars/pinion.svg +34 -0
  34. package/console/avatars/sprocket.svg +34 -0
  35. package/console/avatars/vela.svg +44 -0
  36. package/console/avatars/wasat.svg +38 -0
  37. package/console/clients/agy.svg +1 -0
  38. package/console/clients/claude.svg +1 -0
  39. package/console/clients/codex.svg +1 -0
  40. package/console/clients/devin.svg +1 -0
  41. package/console/clients/kimi.svg +1 -0
  42. package/console/clients/opencode.svg +1 -0
  43. package/console/favicon.ico +0 -0
  44. package/console/favicon.svg +16 -0
  45. package/console/index.html +99 -0
  46. package/console/pdl/engine/README.md +13 -0
  47. package/console/pdl/engine/anchor.js +195 -0
  48. package/console/pdl/engine/core.js +1340 -0
  49. package/console/pdl/engine/frame.js +1252 -0
  50. package/console/pdl/engine/i18n.js +67 -0
  51. package/console/pdl/engine/pdl-check.js +102 -0
  52. package/console/pdl/engine/pdl-doc.js +353 -0
  53. package/console/pdl/engine/pdl-view.js +280 -0
  54. package/console/pdl/engine/pdl.js +1064 -0
  55. package/console/pdl/engine/platform.js +18 -0
  56. package/console/pdl/engine/proj.js +279 -0
  57. package/console/pdl/engine/theme.js +176 -0
  58. package/console/pdl/engine/tree.js +171 -0
  59. package/console/pdl/engine/units.js +546 -0
  60. package/console/pdl/library/README.md +28 -0
  61. package/console/pdl/library/blocks.js +1512 -0
  62. package/console/pdl/library/buttons.js +86 -0
  63. package/console/pdl/library/capsules.js +130 -0
  64. package/console/pdl/library/charts.js +287 -0
  65. package/console/pdl/library/code.js +98 -0
  66. package/console/pdl/library/css/base.css +12 -0
  67. package/console/pdl/library/css/blocks.css +98 -0
  68. package/console/pdl/library/css/capsules.css +42 -0
  69. package/console/pdl/library/css/catalog-page.css +24 -0
  70. package/console/pdl/library/css/chat.css +100 -0
  71. package/console/pdl/library/css/composer-top.css +145 -0
  72. package/console/pdl/library/css/controls.css +195 -0
  73. package/console/pdl/library/css/drag.css +29 -0
  74. package/console/pdl/library/css/edit-layout.css +93 -0
  75. package/console/pdl/library/css/floating-window.css +30 -0
  76. package/console/pdl/library/css/hover.css +50 -0
  77. package/console/pdl/library/css/label-search.css +37 -0
  78. package/console/pdl/library/css/layers.css +43 -0
  79. package/console/pdl/library/css/library-parts.css +33 -0
  80. package/console/pdl/library/css/library.css +117 -0
  81. package/console/pdl/library/css/member-select.css +34 -0
  82. package/console/pdl/library/css/message.css +72 -0
  83. package/console/pdl/library/css/page.css +104 -0
  84. package/console/pdl/library/css/parts.css +338 -0
  85. package/console/pdl/library/css/responsive.css +40 -0
  86. package/console/pdl/library/css/roles.css +28 -0
  87. package/console/pdl/library/css/rows.css +231 -0
  88. package/console/pdl/library/css/settings-rows.css +37 -0
  89. package/console/pdl/library/css/shell.css +59 -0
  90. package/console/pdl/library/css/stream.css +296 -0
  91. package/console/pdl/library/css/theme-calculator.css +18 -0
  92. package/console/pdl/library/css/thumb-choice.css +69 -0
  93. package/console/pdl/library/css/tweaks.css +16 -0
  94. package/console/pdl/library/css/widgets.css +211 -0
  95. package/console/pdl/library/css/workbench.css +59 -0
  96. package/console/pdl/library/feedback.js +83 -0
  97. package/console/pdl/library/floating-window.mjs +100 -0
  98. package/console/pdl/library/fold.js +238 -0
  99. package/console/pdl/library/format.js +53 -0
  100. package/console/pdl/library/frames.js +123 -0
  101. package/console/pdl/library/icons.js +165 -0
  102. package/console/pdl/library/identity.js +149 -0
  103. package/console/pdl/library/inputs.js +801 -0
  104. package/console/pdl/library/label-search.js +214 -0
  105. package/console/pdl/library/markdown-text.js +115 -0
  106. package/console/pdl/library/markdown.js +150 -0
  107. package/console/pdl/library/media-viewer.js +293 -0
  108. package/console/pdl/library/member-select.mjs +32 -0
  109. package/console/pdl/library/message.js +105 -0
  110. package/console/pdl/library/motion.js +56 -0
  111. package/console/pdl/library/overlays.js +165 -0
  112. package/console/pdl/library/page.js +142 -0
  113. package/console/pdl/library/plugin-form.js +154 -0
  114. package/console/pdl/library/registry.js +198 -0
  115. package/console/pdl/library/rows.js +523 -0
  116. package/console/pdl/library/shell.js +151 -0
  117. package/console/pdl/library/stream.js +58 -0
  118. package/console/pdl/library/tabs.js +259 -0
  119. package/console/pdl/library/theme-calculator.js +300 -0
  120. package/console/pdl/library/widgets.js +114 -0
  121. package/console/pdl/load-order.json +74 -0
  122. package/console/pdl/platform/README.md +3 -0
  123. package/console/pdl/platform/rich-markdown.mjs +17 -0
  124. package/console/pdl/platform/web-links.js +26 -0
  125. package/console/pdl/platform/web.js +80 -0
  126. package/console/sdk-browser/mentions.d.mts +16 -0
  127. package/console/sdk-browser/mentions.mjs +84 -0
  128. package/console/theme/assets.js +21 -0
  129. package/console/theme/theme.json +9417 -0
  130. package/console/theme/tokens.json +444 -0
  131. package/dist/core/a2a.d.ts +288 -0
  132. package/dist/core/a2a.js +2197 -0
  133. package/dist/core/address.d.ts +34 -0
  134. package/dist/core/address.js +33 -0
  135. package/dist/core/approval-inputs.d.ts +17 -0
  136. package/dist/core/approval-inputs.js +70 -0
  137. package/dist/core/archive.d.ts +19 -0
  138. package/dist/core/archive.js +135 -0
  139. package/dist/core/attachments.d.ts +17 -0
  140. package/dist/core/attachments.js +143 -0
  141. package/dist/core/blocked-handoffs.d.ts +132 -0
  142. package/dist/core/blocked-handoffs.js +349 -0
  143. package/dist/core/config-schema.d.ts +124 -0
  144. package/dist/core/config-schema.js +192 -0
  145. package/dist/core/config.d.ts +117 -0
  146. package/dist/core/config.js +638 -0
  147. package/dist/core/disk-usage.d.ts +26 -0
  148. package/dist/core/disk-usage.js +83 -0
  149. package/dist/core/documents.d.ts +9 -0
  150. package/dist/core/documents.js +48 -0
  151. package/dist/core/entry.d.ts +316 -0
  152. package/dist/core/entry.js +711 -0
  153. package/dist/core/home.d.ts +76 -0
  154. package/dist/core/home.js +449 -0
  155. package/dist/core/i18n.d.ts +36 -0
  156. package/dist/core/i18n.js +458 -0
  157. package/dist/core/instances.d.ts +224 -0
  158. package/dist/core/instances.js +1272 -0
  159. package/dist/core/members.d.ts +190 -0
  160. package/dist/core/members.js +358 -0
  161. package/dist/core/mentions.d.ts +12 -0
  162. package/dist/core/mentions.js +49 -0
  163. package/dist/core/messages.d.ts +876 -0
  164. package/dist/core/messages.js +916 -0
  165. package/dist/core/notices.d.ts +88 -0
  166. package/dist/core/notices.js +54 -0
  167. package/dist/core/ops.d.ts +117 -0
  168. package/dist/core/ops.js +146 -0
  169. package/dist/core/package.d.ts +2 -0
  170. package/dist/core/package.js +14 -0
  171. package/dist/core/parts.d.ts +25 -0
  172. package/dist/core/parts.js +119 -0
  173. package/dist/core/plugins/catalog.d.ts +14 -0
  174. package/dist/core/plugins/catalog.js +54 -0
  175. package/dist/core/plugins/external.d.ts +7 -0
  176. package/dist/core/plugins/external.js +921 -0
  177. package/dist/core/plugins/index.d.ts +5 -0
  178. package/dist/core/plugins/index.js +51 -0
  179. package/dist/core/plugins/npm.d.ts +12 -0
  180. package/dist/core/plugins/npm.js +99 -0
  181. package/dist/core/plugins/plugin-manifest.d.ts +12 -0
  182. package/dist/core/plugins/plugin-manifest.js +231 -0
  183. package/dist/core/push.d.ts +22 -0
  184. package/dist/core/push.js +63 -0
  185. package/dist/core/resource.d.ts +77 -0
  186. package/dist/core/resource.js +48 -0
  187. package/dist/core/spawn.d.ts +12 -0
  188. package/dist/core/spawn.js +30 -0
  189. package/dist/core/storage-inventory.d.ts +118 -0
  190. package/dist/core/storage-inventory.js +279 -0
  191. package/dist/core/storage.d.ts +45 -0
  192. package/dist/core/storage.js +602 -0
  193. package/dist/core/store.d.ts +15 -0
  194. package/dist/core/store.js +33 -0
  195. package/dist/core/topic-index.d.ts +19 -0
  196. package/dist/core/topic-index.js +70 -0
  197. package/dist/core/topic-ops.d.ts +139 -0
  198. package/dist/core/topic-ops.js +507 -0
  199. package/dist/core/topic-status.d.ts +32 -0
  200. package/dist/core/topic-status.js +105 -0
  201. package/dist/core/topics.d.ts +327 -0
  202. package/dist/core/topics.js +786 -0
  203. package/dist/core/turn-clients.d.ts +1 -0
  204. package/dist/core/turn-clients.js +5 -0
  205. package/dist/core/types.d.ts +2866 -0
  206. package/dist/core/types.js +166 -0
  207. package/dist/core/util.d.ts +10 -0
  208. package/dist/core/util.js +47 -0
  209. package/dist/main.d.ts +12 -0
  210. package/dist/main.js +82 -0
  211. package/dist/plugins/adapter-acp/index.d.ts +3 -0
  212. package/dist/plugins/adapter-acp/index.js +57 -0
  213. package/dist/plugins/adapter-acp/plugin.yaml +100 -0
  214. package/dist/plugins/adapter-agy/command.d.ts +9 -0
  215. package/dist/plugins/adapter-agy/command.js +34 -0
  216. package/dist/plugins/adapter-agy/index.d.ts +5 -0
  217. package/dist/plugins/adapter-agy/index.js +65 -0
  218. package/dist/plugins/adapter-agy/quota.d.ts +2 -0
  219. package/dist/plugins/adapter-agy/quota.js +155 -0
  220. package/dist/plugins/adapter-agy/terminal.d.ts +6 -0
  221. package/dist/plugins/adapter-agy/terminal.js +132 -0
  222. package/dist/plugins/adapter-agy/version.d.ts +9 -0
  223. package/dist/plugins/adapter-agy/version.js +17 -0
  224. package/dist/plugins/adapter-claude/index.d.ts +43 -0
  225. package/dist/plugins/adapter-claude/index.js +412 -0
  226. package/dist/plugins/adapter-claude/quota.d.ts +14 -0
  227. package/dist/plugins/adapter-claude/quota.js +103 -0
  228. package/dist/plugins/adapter-codex/index.d.ts +4 -0
  229. package/dist/plugins/adapter-codex/index.js +688 -0
  230. package/dist/plugins/adapter-codex/responses-model.d.ts +9 -0
  231. package/dist/plugins/adapter-codex/responses-model.js +82 -0
  232. package/dist/plugins/adapter-kimi/index.d.ts +4 -0
  233. package/dist/plugins/adapter-kimi/index.js +51 -0
  234. package/dist/plugins/adapter-kimi/quota.d.ts +3 -0
  235. package/dist/plugins/adapter-kimi/quota.js +171 -0
  236. package/dist/plugins/adapter-opencode/index.d.ts +12 -0
  237. package/dist/plugins/adapter-opencode/index.js +64 -0
  238. package/dist/plugins/annotations/console/cards.css +189 -0
  239. package/dist/plugins/annotations/console/cards.mjs +439 -0
  240. package/dist/plugins/annotations/console/pdl.json +52 -0
  241. package/dist/plugins/annotations/console/view.mjs +241 -0
  242. package/dist/plugins/annotations/console/window.mjs +219 -0
  243. package/dist/plugins/annotations/followups.d.ts +51 -0
  244. package/dist/plugins/annotations/followups.js +112 -0
  245. package/dist/plugins/annotations/index.d.ts +3 -0
  246. package/dist/plugins/annotations/index.js +298 -0
  247. package/dist/plugins/annotations/plugin.yaml +3 -0
  248. package/dist/plugins/ask-choice/index.d.ts +9 -0
  249. package/dist/plugins/ask-choice/index.js +24 -0
  250. package/dist/plugins/ask-choice/plugin.yaml +2 -0
  251. package/dist/plugins/background/index.d.ts +2 -0
  252. package/dist/plugins/background/index.js +398 -0
  253. package/dist/plugins/background/plugin.yaml +7 -0
  254. package/dist/plugins/builtin.json +37 -0
  255. package/dist/plugins/cards/console/pdl.json +516 -0
  256. package/dist/plugins/cards/console/view.mjs +67 -0
  257. package/dist/plugins/cards/index.d.ts +8 -0
  258. package/dist/plugins/cards/index.js +627 -0
  259. package/dist/plugins/cards/plugin.yaml +3 -0
  260. package/dist/plugins/console/browser.d.ts +2 -0
  261. package/dist/plugins/console/browser.js +115 -0
  262. package/dist/plugins/console/console/pdl.json +38 -0
  263. package/dist/plugins/console/console/view.mjs +26 -0
  264. package/dist/plugins/console/index.d.ts +4 -0
  265. package/dist/plugins/console/index.js +94 -0
  266. package/dist/plugins/console/picker.d.ts +2 -0
  267. package/dist/plugins/console/picker.js +48 -0
  268. package/dist/plugins/console/plugin.yaml +3 -0
  269. package/dist/plugins/console/topic-view.d.ts +3 -0
  270. package/dist/plugins/console/topic-view.js +388 -0
  271. package/dist/plugins/handoff/index.d.ts +2 -0
  272. package/dist/plugins/handoff/index.js +147 -0
  273. package/dist/plugins/handoff/plugin.yaml +8 -0
  274. package/dist/plugins/host-api/index.d.ts +7 -0
  275. package/dist/plugins/host-api/index.js +310 -0
  276. package/dist/plugins/host-api/plugin.yaml +2 -0
  277. package/dist/plugins/host-api/signing.d.ts +63 -0
  278. package/dist/plugins/host-api/signing.js +427 -0
  279. package/dist/plugins/host-api/skills/host-ops/SKILL.md +28 -0
  280. package/dist/plugins/host-api/skills/hostlet-plugin-dev/SKILL.md +38 -0
  281. package/dist/plugins/inbox/index.d.ts +15 -0
  282. package/dist/plugins/inbox/index.js +161 -0
  283. package/dist/plugins/inbox/plugin.yaml +2 -0
  284. package/dist/plugins/keys/account-directories.d.ts +18 -0
  285. package/dist/plugins/keys/account-directories.js +86 -0
  286. package/dist/plugins/keys/account-storage.d.ts +18 -0
  287. package/dist/plugins/keys/account-storage.js +112 -0
  288. package/dist/plugins/keys/console/pdl.json +710 -0
  289. package/dist/plugins/keys/console/view.mjs +619 -0
  290. package/dist/plugins/keys/index.d.ts +7 -0
  291. package/dist/plugins/keys/index.js +842 -0
  292. package/dist/plugins/keys/login-link.d.ts +2 -0
  293. package/dist/plugins/keys/login-link.js +15 -0
  294. package/dist/plugins/keys/plugin.yaml +3 -0
  295. package/dist/plugins/keys/quota-history.d.ts +91 -0
  296. package/dist/plugins/keys/quota-history.js +420 -0
  297. package/dist/plugins/mcp/console/pdl.json +412 -0
  298. package/dist/plugins/mcp/console/view.mjs +207 -0
  299. package/dist/plugins/mcp/index.d.ts +7 -0
  300. package/dist/plugins/mcp/index.js +494 -0
  301. package/dist/plugins/mcp/plugin.yaml +3 -0
  302. package/dist/plugins/member-health/index.d.ts +2 -0
  303. package/dist/plugins/member-health/index.js +478 -0
  304. package/dist/plugins/member-health/plugin.yaml +2 -0
  305. package/dist/plugins/memory/capabilities.d.ts +10 -0
  306. package/dist/plugins/memory/capabilities.js +70 -0
  307. package/dist/plugins/memory/console/pdl.json +459 -0
  308. package/dist/plugins/memory/console/view.mjs +254 -0
  309. package/dist/plugins/memory/corpus.d.ts +60 -0
  310. package/dist/plugins/memory/corpus.js +521 -0
  311. package/dist/plugins/memory/engines/fts-tree-diversity.d.ts +8 -0
  312. package/dist/plugins/memory/engines/fts-tree-diversity.js +49 -0
  313. package/dist/plugins/memory/engines/fts-tree-text.d.ts +12 -0
  314. package/dist/plugins/memory/engines/fts-tree-text.js +93 -0
  315. package/dist/plugins/memory/engines/fts-tree.d.ts +4 -0
  316. package/dist/plugins/memory/engines/fts-tree.js +387 -0
  317. package/dist/plugins/memory/engines/search.d.ts +9 -0
  318. package/dist/plugins/memory/engines/search.js +35 -0
  319. package/dist/plugins/memory/index.d.ts +3 -0
  320. package/dist/plugins/memory/index.js +465 -0
  321. package/dist/plugins/memory/notes.d.ts +22 -0
  322. package/dist/plugins/memory/notes.js +140 -0
  323. package/dist/plugins/memory/plugin.yaml +23 -0
  324. package/dist/plugins/model-profiles/index.d.ts +2 -0
  325. package/dist/plugins/model-profiles/index.js +919 -0
  326. package/dist/plugins/model-profiles/plugin.yaml +13 -0
  327. package/dist/plugins/model-profiles/review-source.d.ts +11 -0
  328. package/dist/plugins/model-profiles/review-source.js +640 -0
  329. package/dist/plugins/model-profiles/rules.d.ts +132 -0
  330. package/dist/plugins/model-profiles/rules.js +767 -0
  331. package/dist/plugins/model-profiles/skills/model-profile/SKILL.md +60 -0
  332. package/dist/plugins/model-profiles/sources.d.ts +61 -0
  333. package/dist/plugins/model-profiles/sources.js +375 -0
  334. package/dist/plugins/model-profiles/storage.d.ts +104 -0
  335. package/dist/plugins/model-profiles/storage.js +352 -0
  336. package/dist/plugins/model-profiles/types.d.ts +187 -0
  337. package/dist/plugins/model-profiles/types.js +12 -0
  338. package/dist/plugins/model-profiles/wakeup.d.ts +29 -0
  339. package/dist/plugins/model-profiles/wakeup.js +390 -0
  340. package/dist/plugins/models/index.d.ts +2 -0
  341. package/dist/plugins/models/index.js +63 -0
  342. package/dist/plugins/models/plugin.yaml +8 -0
  343. package/dist/plugins/ops/collector.d.ts +22 -0
  344. package/dist/plugins/ops/collector.js +48 -0
  345. package/dist/plugins/ops/config.d.ts +11 -0
  346. package/dist/plugins/ops/config.js +13 -0
  347. package/dist/plugins/ops/console/pdl.json +676 -0
  348. package/dist/plugins/ops/console/view.mjs +700 -0
  349. package/dist/plugins/ops/index.d.ts +3 -0
  350. package/dist/plugins/ops/index.js +20 -0
  351. package/dist/plugins/ops/journal.d.ts +7 -0
  352. package/dist/plugins/ops/journal.js +109 -0
  353. package/dist/plugins/ops/metrics.d.ts +3 -0
  354. package/dist/plugins/ops/metrics.js +81 -0
  355. package/dist/plugins/ops/plugin.yaml +63 -0
  356. package/dist/plugins/ops/samples.d.ts +54 -0
  357. package/dist/plugins/ops/samples.js +100 -0
  358. package/dist/plugins/ops/trace.d.ts +3 -0
  359. package/dist/plugins/ops/trace.js +104 -0
  360. package/dist/plugins/ops/usage.d.ts +2 -0
  361. package/dist/plugins/ops/usage.js +152 -0
  362. package/dist/plugins/plans/acceptance.d.ts +284 -0
  363. package/dist/plugins/plans/acceptance.js +247 -0
  364. package/dist/plugins/plans/blocked.d.ts +25 -0
  365. package/dist/plugins/plans/blocked.js +66 -0
  366. package/dist/plugins/plans/console/pdl.json +639 -0
  367. package/dist/plugins/plans/console/view.d.mts +2 -0
  368. package/dist/plugins/plans/console/view.mjs +855 -0
  369. package/dist/plugins/plans/dependencies.d.ts +5 -0
  370. package/dist/plugins/plans/dependencies.js +21 -0
  371. package/dist/plugins/plans/index.d.ts +72 -0
  372. package/dist/plugins/plans/index.js +2057 -0
  373. package/dist/plugins/plans/plugin.yaml +44 -0
  374. package/dist/plugins/plans/progress.d.ts +82 -0
  375. package/dist/plugins/plans/progress.js +516 -0
  376. package/dist/plugins/prompt/index.d.ts +8 -0
  377. package/dist/plugins/prompt/index.js +361 -0
  378. package/dist/plugins/prompt/plugin.yaml +2 -0
  379. package/dist/plugins/recovery/console/pdl.json +50 -0
  380. package/dist/plugins/recovery/console/view.mjs +46 -0
  381. package/dist/plugins/recovery/index.d.ts +9 -0
  382. package/dist/plugins/recovery/index.js +454 -0
  383. package/dist/plugins/recovery/plugin.yaml +9 -0
  384. package/dist/plugins/recovery/probe.d.ts +11 -0
  385. package/dist/plugins/recovery/probe.js +128 -0
  386. package/dist/plugins/restart/console/pdl.json +112 -0
  387. package/dist/plugins/restart/console/view.mjs +85 -0
  388. package/dist/plugins/restart/index.d.ts +10 -0
  389. package/dist/plugins/restart/index.js +669 -0
  390. package/dist/plugins/restart/plugin.yaml +9 -0
  391. package/dist/plugins/restart/scope.d.ts +6 -0
  392. package/dist/plugins/restart/scope.js +44 -0
  393. package/dist/plugins/schedule/console/pdl.json +696 -0
  394. package/dist/plugins/schedule/console/view.mjs +398 -0
  395. package/dist/plugins/schedule/events.d.ts +76 -0
  396. package/dist/plugins/schedule/events.js +158 -0
  397. package/dist/plugins/schedule/index.d.ts +32 -0
  398. package/dist/plugins/schedule/index.js +1199 -0
  399. package/dist/plugins/schedule/plugin.yaml +26 -0
  400. package/dist/plugins/schedule/when.d.ts +14 -0
  401. package/dist/plugins/schedule/when.js +83 -0
  402. package/dist/plugins/sessions/console/pdl.json +259 -0
  403. package/dist/plugins/sessions/console/view.mjs +355 -0
  404. package/dist/plugins/sessions/index.d.ts +3 -0
  405. package/dist/plugins/sessions/index.js +126 -0
  406. package/dist/plugins/sessions/participants.d.ts +28 -0
  407. package/dist/plugins/sessions/participants.js +83 -0
  408. package/dist/plugins/sessions/plugin.yaml +3 -0
  409. package/dist/plugins/signals/console/pdl.json +802 -0
  410. package/dist/plugins/signals/console/view.mjs +284 -0
  411. package/dist/plugins/signals/content.d.ts +31 -0
  412. package/dist/plugins/signals/content.js +151 -0
  413. package/dist/plugins/signals/index.d.ts +2 -0
  414. package/dist/plugins/signals/index.js +601 -0
  415. package/dist/plugins/signals/plugin.yaml +32 -0
  416. package/dist/plugins/signals/skills/signal-sources/SKILL.md +27 -0
  417. package/dist/plugins/skills/console/pdl.json +254 -0
  418. package/dist/plugins/skills/console/view.mjs +204 -0
  419. package/dist/plugins/skills/index.d.ts +11 -0
  420. package/dist/plugins/skills/index.js +567 -0
  421. package/dist/plugins/skills/install.d.ts +69 -0
  422. package/dist/plugins/skills/install.js +265 -0
  423. package/dist/plugins/skills/plugin.yaml +24 -0
  424. package/dist/plugins/skills/safety-scan.d.ts +17 -0
  425. package/dist/plugins/skills/safety-scan.js +78 -0
  426. package/dist/plugins/skills/skills/skill-ops/SKILL.md +29 -0
  427. package/dist/plugins/terminal/console/pdl.json +115 -0
  428. package/dist/plugins/terminal/console/view.mjs +178 -0
  429. package/dist/plugins/terminal/index.d.ts +3 -0
  430. package/dist/plugins/terminal/index.js +204 -0
  431. package/dist/plugins/terminal/plugin.yaml +2 -0
  432. package/dist/plugins/tools/index.d.ts +3 -0
  433. package/dist/plugins/tools/index.js +458 -0
  434. package/dist/plugins/tools/plugin.yaml +2 -0
  435. package/dist/plugins/tools/token.d.ts +61 -0
  436. package/dist/plugins/tools/token.js +179 -0
  437. package/dist/plugins/topic-tools/index.d.ts +9 -0
  438. package/dist/plugins/topic-tools/index.js +29 -0
  439. package/dist/plugins/topic-tools/plugin.yaml +2 -0
  440. package/dist/plugins/topic-tools/skills/topic-tidy/SKILL.md +108 -0
  441. package/dist/plugins/works/console/pdl.json +120 -0
  442. package/dist/plugins/works/console/view.mjs +91 -0
  443. package/dist/plugins/works/document-words.d.ts +50 -0
  444. package/dist/plugins/works/document-words.js +27 -0
  445. package/dist/plugins/works/editors.d.ts +3 -0
  446. package/dist/plugins/works/editors.js +162 -0
  447. package/dist/plugins/works/events.d.ts +58 -0
  448. package/dist/plugins/works/events.js +82 -0
  449. package/dist/plugins/works/files.d.ts +23 -0
  450. package/dist/plugins/works/files.js +53 -0
  451. package/dist/plugins/works/index.d.ts +9 -0
  452. package/dist/plugins/works/index.js +1088 -0
  453. package/dist/plugins/works/plugin.yaml +9 -0
  454. package/dist/plugins/works/preview.d.ts +10 -0
  455. package/dist/plugins/works/preview.js +30 -0
  456. package/dist/plugins/works/project.d.ts +3 -0
  457. package/dist/plugins/works/project.js +245 -0
  458. package/dist/plugins/works/resource.d.ts +28 -0
  459. package/dist/plugins/works/resource.js +71 -0
  460. package/dist/plugins/works/retention.d.ts +36 -0
  461. package/dist/plugins/works/retention.js +295 -0
  462. package/dist/plugins/works/skills/works-ops/SKILL.md +14 -0
  463. package/dist/plugins/works/viewers.d.ts +13 -0
  464. package/dist/plugins/works/viewers.js +87 -0
  465. package/dist/plugins/works/web/anchors.js +94 -0
  466. package/dist/plugins/works/web/document-edit.js +245 -0
  467. package/dist/plugins/works/web/preview-bridge.js +142 -0
  468. package/dist/plugins/works/web/reading-position.js +74 -0
  469. package/dist/plugins/works/web/view.html +1118 -0
  470. package/dist/runtime/runtime.d.ts +210 -0
  471. package/dist/runtime/runtime.js +338 -0
  472. package/dist/sdk/adapter-kit.d.ts +1 -0
  473. package/dist/sdk/adapter-kit.js +1 -0
  474. package/dist/sdk/client.d.ts +163 -0
  475. package/dist/sdk/client.js +43 -0
  476. package/dist/sdk/contracts.d.ts +1263 -0
  477. package/dist/sdk/contracts.js +1 -0
  478. package/dist/sdk/index.d.ts +57 -0
  479. package/dist/sdk/index.js +27 -0
  480. package/dist/sdk/source-choice.d.ts +40 -0
  481. package/dist/sdk/source-choice.js +217 -0
  482. package/dist/sdk/topic-text.d.ts +5 -0
  483. package/dist/sdk/topic-text.js +26 -0
  484. package/dist/sdk/transport.d.ts +12 -0
  485. package/dist/sdk/transport.js +34 -0
  486. package/node_modules/@hostlet/adapter-kit/dist/acp.d.ts +88 -0
  487. package/node_modules/@hostlet/adapter-kit/dist/acp.js +674 -0
  488. package/node_modules/@hostlet/adapter-kit/dist/command.d.ts +18 -0
  489. package/node_modules/@hostlet/adapter-kit/dist/command.js +39 -0
  490. package/node_modules/@hostlet/adapter-kit/dist/index.d.ts +8 -0
  491. package/node_modules/@hostlet/adapter-kit/dist/index.js +6 -0
  492. package/node_modules/@hostlet/adapter-kit/dist/models.d.ts +29 -0
  493. package/node_modules/@hostlet/adapter-kit/dist/models.js +108 -0
  494. package/node_modules/@hostlet/adapter-kit/dist/quota.d.ts +3 -0
  495. package/node_modules/@hostlet/adapter-kit/dist/quota.js +4 -0
  496. package/node_modules/@hostlet/adapter-kit/dist/rpc.d.ts +29 -0
  497. package/node_modules/@hostlet/adapter-kit/dist/rpc.js +84 -0
  498. package/node_modules/@hostlet/adapter-kit/dist/upstream-failure.d.ts +5 -0
  499. package/node_modules/@hostlet/adapter-kit/dist/upstream-failure.js +37 -0
  500. package/node_modules/@hostlet/adapter-kit/package.json +16 -0
  501. package/node_modules/@hostlet/platform/dist/desktop.d.ts +16 -0
  502. package/node_modules/@hostlet/platform/dist/desktop.js +276 -0
  503. package/node_modules/@hostlet/platform/dist/files.d.ts +24 -0
  504. package/node_modules/@hostlet/platform/dist/files.js +113 -0
  505. package/node_modules/@hostlet/platform/dist/index.d.ts +6 -0
  506. package/node_modules/@hostlet/platform/dist/index.js +4 -0
  507. package/node_modules/@hostlet/platform/dist/paths.d.ts +4 -0
  508. package/node_modules/@hostlet/platform/dist/paths.js +9 -0
  509. package/node_modules/@hostlet/platform/dist/process.d.ts +45 -0
  510. package/node_modules/@hostlet/platform/dist/process.js +297 -0
  511. package/node_modules/@hostlet/platform/package.json +14 -0
  512. package/package.json +60 -4
@@ -0,0 +1,2057 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import { address, array, errorText, HttpError, ltext, newId, object, OWNER_ID, visibleTo } from 'hostlet/sdk';
7
+ import { activityKinds, activityReasons, assigneeOf, assignmentContext, parseIsoTime, planNudge, planProgress, reminderPlace, requestTopic, sharedVisibility, topicAudience, watchPlanProgress } from "./progress.js";
8
+ import { blockedPlanWaits, receivedHandoff } from "./blocked.js";
9
+ import { planRefs, prerequisitePath, withPrerequisites } from "./dependencies.js";
10
+ import { acceptanceInput, acceptanceLine, acceptanceOutput, checkAcceptance, checkInput, CONSOLE_PLUGIN, consoleVersion, directoryDigest, effective, fetchConsoleAssetsDigest, guardOwnerItems, staleChecks, targetText, unmet, withAcceptance } from "./acceptance.js";
11
+ const stepKinds = ['noted', 'started', 'done', 'dropped', 'reopened', 'retitled', 'moved', 'mentioned', 'suspended', 'resumed', 'waiting', 'continued', 'reminded', 'checked', 'acceptanceAsked', 'sourceCorrected'];
12
+ /** Use the measured rate for the current window and the provider's live remaining balance. */
13
+ function runsOutBeforeReset(used, resetAt, burn, now) {
14
+ // Providers may round a reported reset time. A lower live percentage means the history is no longer comparable.
15
+ if (burn.resetsAt == null || Math.abs(burn.resetsAt - resetAt) > 60_000 || (burn.currentPercent ?? 0) > used)
16
+ return;
17
+ if (burn.predictionStatus === 'no_consumption')
18
+ return burn.currentPercent === used ? false : undefined;
19
+ if (burn.predictionStatus !== 'predicted' || !burn.rateBasis)
20
+ return;
21
+ const rate = burn[burn.rateBasis].ratePerHour;
22
+ if (rate == null || rate <= 0)
23
+ return;
24
+ return (100 - used) * 3_600_000 / rate < resetAt - now;
25
+ }
26
+ const LABEL = { later: '记着', doing: '在做', done: '做完', dropped: '不做了' };
27
+ const stringValue = { type: 'string' };
28
+ const numberValue = { type: 'number' };
29
+ const textDetails = ['description', 'trigger', 'when', 'dependencies'];
30
+ const detailFields = {
31
+ description: { type: 'string', description: '整理后的目标、交付内容和已知条件' },
32
+ trigger: { type: 'string', description: '触发条件' },
33
+ when: { type: 'string', description: '计划什么时候做(ISO 日期时间),空字符串清空' },
34
+ dependencies: { type: 'string', description: '依赖事项或规划地址' },
35
+ prerequisites: { ...array(stringValue), description: '前置规划编号列表。保存时替换依赖说明中的规划引用,保留其他文字。空列表清除规划引用' },
36
+ suspended: { type: 'boolean', description: '是否暂时挂起' },
37
+ resumeAt: { type: 'string', description: '暂挂后的预定恢复时间(ISO 日期时间),到点自动解除暂挂并按规则接续;空字符串清空' },
38
+ };
39
+ const dispatchField = {
40
+ ...object({
41
+ mode: { type: 'string', enum: ['new', 'existing'], description: '执行时新建子主题,或在已有主题继续' },
42
+ topic: { type: 'string', description: 'existing 时的承接主题编号' },
43
+ parent: { type: 'string', description: 'new 时的父主题编号,省略沿用规划归属' },
44
+ member: { type: 'string', member: true, description: '承接成员,省略沿用主题的分派规则' },
45
+ }, ['mode']),
46
+ description: '预设的执行安排。保存整份安排,执行时才创建主题和交办。',
47
+ };
48
+ const docField = {
49
+ ...object({
50
+ resource: { type: 'string', description: '主题文档的规范资源地址,如 res:topic/top_…/summary.md 或 res:topic/top_…/artifacts/rfc.md' },
51
+ section: { type: 'string', description: '可选的章节标题或定位文字' },
52
+ }, ['resource']),
53
+ description: '文档出处',
54
+ };
55
+ const waitingInput = {
56
+ ...object({
57
+ on: { type: 'string', member: true, description: '正在等的成员或机主(允许登记已停用或额度受限的成员)' },
58
+ why: { type: 'string', description: '一句话说明在等什么,例如待复核合入、等额度恢复或待机主验收' },
59
+ until: { type: 'string', description: '可选:预期恢复或到期时间(ISO 日期时间);省略且对方额度受限时,自动读取其额度重置时间' },
60
+ }, ['on', 'why']),
61
+ type: ['object', 'null'],
62
+ description: '声明当前承接的卡点。填 null 清除,等待起点由宿主记录。',
63
+ };
64
+ function editDetails(plan, input) {
65
+ for (const key of textDetails) {
66
+ if (input[key] === undefined)
67
+ continue;
68
+ const value = input[key].trim();
69
+ if (value)
70
+ plan[key] = value;
71
+ else
72
+ delete plan[key];
73
+ }
74
+ if (input.suspended)
75
+ plan.suspended = true;
76
+ else if (input.suspended === false)
77
+ delete plan.suspended;
78
+ if (input.resumeAt !== undefined) {
79
+ const value = input.resumeAt.trim();
80
+ if (!value)
81
+ delete plan.resumeAt;
82
+ else {
83
+ if (parseIsoTime(value) === undefined)
84
+ throw new HttpError(400, '恢复时间请填写有效的 ISO 日期时间');
85
+ plan.resumeAt = value;
86
+ }
87
+ }
88
+ if (!plan.suspended)
89
+ delete plan.resumeAt;
90
+ }
91
+ const planFields = {
92
+ ...detailFields, dispatch: dispatchField, sourceDeleted: { type: 'boolean' },
93
+ jump: object({ kind: { type: 'string', enum: ['acceptance', 'current', 'handoff', 'receipt', 'source', 'document', 'work', 'home'] }, url: stringValue }, ['kind', 'url']),
94
+ responsible: stringValue,
95
+ id: stringValue, title: stringValue, from: object({ message: stringValue, doc: docField }),
96
+ messageSource: object({ label: stringValue, url: stringValue }, ['label']),
97
+ documentSource: object({ label: stringValue, url: stringValue }, ['label']),
98
+ state: { type: 'string', enum: Object.keys(LABEL) },
99
+ at: stringValue, pinned: { type: 'boolean' },
100
+ trail: array(object({
101
+ at: numberValue, by: stringValue, where: stringValue, why: stringValue, assignee: stringValue, waitingOn: stringValue,
102
+ what: { type: 'string', enum: stepKinds },
103
+ }, ['at', 'by', 'what'])),
104
+ topicId: stringValue, topic: stringValue, source: stringValue,
105
+ waiting: object({ on: stringValue, why: stringValue, since: numberValue, until: numberValue }, ['on', 'why', 'since']),
106
+ reminder: { type: ['string', 'null'] },
107
+ acceptance: acceptanceOutput, statement: stringValue,
108
+ statementSource: object({ label: stringValue, url: stringValue }, ['label']),
109
+ assignee: stringValue, ready: { type: 'boolean' }, due: { type: 'boolean' }, lastWorkAt: numberValue, waitingOn: stringValue,
110
+ activity: object({
111
+ kind: { type: 'string', enum: activityKinds }, reason: { type: 'string', enum: activityReasons }, detail: stringValue,
112
+ }, ['kind', 'reason']),
113
+ place: object({ topicId: stringValue, title: stringValue, busy: { type: 'boolean' }, lastActiveAt: numberValue }, ['topicId', 'title', 'busy', 'lastActiveAt']),
114
+ };
115
+ const requiredPlan = ['id', 'title', 'from', 'state', 'trail', 'topicId', 'topic', 'source', 'jump', 'prerequisites'];
116
+ const planOutput = object(planFields, requiredPlan);
117
+ const OPEN = ['later', 'doing'];
118
+ const link = (label, to) => `[${label.replace(/\[/g, '[').replace(/\]/g, ']').replace(/\s+/g, ' ')}](#${to})`;
119
+ const planAddress = (plan) => address.item('plans', plan.id);
120
+ const planLink = (plan) => link(`「${plan.title}」`, planAddress(plan));
121
+ const ACCEPTANCE_CARD = 'approval.plan-acceptance';
122
+ const acceptancePlace = (plan) => plan.trail.findLast(({ what }) => what === 'acceptanceAsked')?.where;
123
+ const acceptancePart = (message) => message?.parts.find((part) => part.type === 'card' && part.kind === ACCEPTANCE_CARD);
124
+ const WHEN = '延后要做的事,以及机主在对话里提出、当轮接下的代码、界面、配置或文档改动,接手时用 plan_note 带原消息出处登记;当轮开工可传 state: "doing"。纯问答、闲聊、临时排查、已知限制、明说不做的和等人回答的问题不记。';
125
+ /**
126
+ * Plans: what the topics put off. A plan is kept in the folder of the topic that raised it (`plans.json`), noted
127
+ * by the members themselves; every topic's are listed together for whoever arranges the work. Starting one hands
128
+ * it to a topic (a new one under its own, or one there is); the topic that does it marks it done when it wraps
129
+ * up. Nothing is deleted: what was dropped stays, with where that was decided.
130
+ */
131
+ export const plansPlugin = (hostHome, ext) => ({
132
+ name: 'plans',
133
+ title: '规划',
134
+ about: '记录待做和当轮接下的改动,保留出处、承接主题与交付回执。各主题的规划可一起查看和安排。',
135
+ group: '给成员的工具',
136
+ needs: ['topics', 'members', 'messages', 'a2a', 'entry', 'i18n', 'notices', 'push', 'works'],
137
+ start(ctx) {
138
+ ctx.hook('topic.records', () => 'plans.json');
139
+ const { sender } = ctx.get('members').register(ctx, { name: '规划', handle: 'plans', icon: 'bookmark', color: { primary: '#3b7caf' } });
140
+ const topics = ctx.get('topics');
141
+ const members = ctx.get('members');
142
+ const messages = ctx.get('messages');
143
+ const a2a = ctx.get('a2a');
144
+ const entry = ctx.get('entry');
145
+ const works = ctx.get('works');
146
+ const i18n = ctx.get('i18n');
147
+ const attentionMs = Number(ext.config.get('stallMinutes')) * 60_000;
148
+ ctx.on('config.changed', ({ scope, key }) => { if (scope === 'plugin:plans' && key === 'stallMinutes')
149
+ ext.reload(); });
150
+ /** Where an acceptance check is made: this host, the code it started with, and this plugin's version. */
151
+ /**
152
+ * What runs on this host now, for acceptance targets: its address, its code's commit, and each started plugin's
153
+ * version. Read again whenever a plugin is installed, updated, reloaded or switched.
154
+ */
155
+ // The host's code is what the process started from, not what is checked out on disk now. A built-in plugin is the
156
+ // host's code; an external one has its own version. The console plugin serves static files directly from disk, so
157
+ // its version tracks the served console assets plus its loaded server plugin digest, independent of hostHome.codeCommit.
158
+ const repoDir = fileURLToPath(new URL('../../..', import.meta.url));
159
+ const hasGitRepo = existsSync(join(repoDir, '.git'));
160
+ const ancestryCache = new Map();
161
+ const isAncestor = (older, newer) => {
162
+ if (older === newer)
163
+ return true;
164
+ if (!hasGitRepo)
165
+ return false;
166
+ const key = `${older}..${newer}`;
167
+ const cached = ancestryCache.get(key);
168
+ if (cached !== undefined)
169
+ return cached;
170
+ let ancestor = false;
171
+ try {
172
+ execFileSync('git', ['--no-optional-locks', 'merge-base', '--is-ancestor', older, newer], { cwd: repoDir, stdio: 'ignore', timeout: 2_000 });
173
+ ancestor = true;
174
+ }
175
+ catch {
176
+ ancestor = false;
177
+ }
178
+ if (ancestryCache.size >= 512)
179
+ ancestryCache.clear();
180
+ ancestryCache.set(key, ancestor);
181
+ return ancestor;
182
+ };
183
+ const running = { host: entry.url, ...(hostHome.codeCommit ? { commit: hostHome.codeCommit } : {}), plugins: {}, isAncestor };
184
+ const localConsoleAssetsDir = fileURLToPath(new URL('../../../console', import.meta.url));
185
+ const localConsoleServerDir = fileURLToPath(new URL('../console', import.meta.url));
186
+ let consoleStarted = false;
187
+ let consoleServerHash;
188
+ const readLocalConsoleVersion = () => consoleVersion(directoryDigest(localConsoleAssetsDir, 12), consoleServerHash);
189
+ const readRunning = async (consoleReloaded = false) => {
190
+ if (cardsStopped)
191
+ return;
192
+ try {
193
+ const list = await entry.invoke('host.plugins', {});
194
+ // While plans itself is starting during a hot reload, runtime still reports its state as 'waiting' until start() settles.
195
+ const started = list.filter((one) => one.state === 'started' || (one.name === 'plans' && one.state === 'waiting'));
196
+ const consoleInfo = started.find((one) => one.name === CONSOLE_PLUGIN);
197
+ const becameStarted = !!consoleInfo && !consoleStarted;
198
+ consoleStarted = !!consoleInfo;
199
+ if (!consoleStarted)
200
+ consoleServerHash = undefined;
201
+ else if (becameStarted || consoleReloaded)
202
+ consoleServerHash = directoryDigest(localConsoleServerDir, 8);
203
+ // A built-in plugin is the host's code as it was last read (the start commit until it is reloaded); an external
204
+ // one has its own version; console tracks its live served assets independently of hostHome.codeCommit.
205
+ const plugins = {};
206
+ for (const one of started) {
207
+ if (one.name === CONSOLE_PLUGIN) {
208
+ const live = readLocalConsoleVersion() ?? consoleVersion(await fetchConsoleAssetsDigest(entry.url));
209
+ plugins[one.name] = live ?? (one.code ? `host@${one.code}` : undefined);
210
+ continue;
211
+ }
212
+ plugins[one.name] = one.external ? one.version ?? undefined : one.code ? `host@${one.code}` : undefined;
213
+ }
214
+ running.plugins = plugins;
215
+ }
216
+ catch (error) {
217
+ ctx.runtime.onError('plans running versions', error);
218
+ }
219
+ };
220
+ const hasConsoleTarget = (items) => !!items?.some((item) => item.target?.plugin === CONSOLE_PLUGIN);
221
+ const syncConsoleVersion = () => {
222
+ if (!consoleStarted)
223
+ return false;
224
+ const live = readLocalConsoleVersion();
225
+ if (!live || live === running.plugins[CONSOLE_PLUGIN])
226
+ return false;
227
+ running.plugins[CONSOLE_PLUGIN] = live;
228
+ resetStale();
229
+ queueAcceptanceCards((placesByBook ?? locateBooks()).keys());
230
+ return true;
231
+ };
232
+ const need = (id) => {
233
+ const topic = topics.get(String(id ?? ''));
234
+ if (!topic || topic.deletedAt)
235
+ throw new Error(`没有这个主题:${String(id ?? '')}`);
236
+ return topic;
237
+ };
238
+ const active = (topic) => {
239
+ if (topic.archivedAt !== null)
240
+ throw new HttpError(409, '主题已归档');
241
+ return topic;
242
+ };
243
+ const checkAssignee = (id, topic) => {
244
+ if (!id)
245
+ return;
246
+ const member = members.get(id);
247
+ if (!member || member.kind === 'person' || !member.enabled)
248
+ throw new Error(`没有可承接的成员:${id}`);
249
+ if (topic && !a2a.worksIn(topic.id, id))
250
+ throw new Error(`成员 ${member.name} 不在主题「${topic.title}」的成员里`);
251
+ };
252
+ const checkedDispatch = (dispatch) => {
253
+ if (dispatch.mode === 'existing') {
254
+ if (dispatch.parent || !dispatch.topic)
255
+ throw new Error('请选择执行时要继续的主题');
256
+ checkAssignee(dispatch.member, active(need(dispatch.topic)));
257
+ }
258
+ else {
259
+ if (dispatch.topic)
260
+ throw new Error('新开子主题时请填写父主题');
261
+ if (dispatch.parent)
262
+ active(need(dispatch.parent));
263
+ checkAssignee(dispatch.member);
264
+ }
265
+ return dispatch;
266
+ };
267
+ const file = (topic) => join(topic.dir, 'plans.json');
268
+ const bookOf = (topic) => (existsSync(file(topic)) ? JSON.parse(readFileSync(file(topic), 'utf8')).items : []);
269
+ // Only the locations are cached. Section text is always read from the contributing books.
270
+ let placesByBook;
271
+ function locateBook(id, items) {
272
+ if (!placesByBook)
273
+ return;
274
+ if (items.length)
275
+ placesByBook.set(id, new Set([id, ...items.flatMap((plan) => plan.at ? [plan.at] : [])]));
276
+ else
277
+ placesByBook.delete(id);
278
+ }
279
+ function locateBooks() {
280
+ placesByBook = new Map();
281
+ for (const topic of topics.list())
282
+ locateBook(topic.id, bookOf(topic));
283
+ return placesByBook;
284
+ }
285
+ ctx.on('topic.updated', ({ trashChanged }) => {
286
+ if (!placesByBook || !trashChanged)
287
+ return;
288
+ for (const id of trashChanged) {
289
+ const topic = topics.get(id);
290
+ locateBook(id, topic.deletedAt === null ? bookOf(topic) : []);
291
+ }
292
+ });
293
+ ctx.effect(ctx.get('push').forward('plans.changed'));
294
+ ctx.effect(ctx.get('push').forward('address.changed'));
295
+ const receiptsFile = hostHome.path('plugins', 'plans', 'starts.json');
296
+ const receipts = () => existsSync(receiptsFile) ? JSON.parse(readFileSync(receiptsFile, 'utf8')) : [];
297
+ const writeReceipts = (items) => {
298
+ if (!items.length && !existsSync(receiptsFile))
299
+ return;
300
+ mkdirSync(dirname(receiptsFile), { recursive: true });
301
+ writeFileSync(receiptsFile, `${JSON.stringify(items, null, 2)}\n`);
302
+ };
303
+ const receiptOf = (plan) => receipts().find((item) => item.plan === plan.id);
304
+ const dropReceipt = (id) => {
305
+ try {
306
+ writeReceipts(receipts().filter((item) => item.plan !== id));
307
+ }
308
+ catch (error) {
309
+ ctx.runtime.onError('plans start receipt ' + id, error);
310
+ }
311
+ };
312
+ /**
313
+ * The handoff an intent left: the start message for this plan in the topic it went to (or, for a new topic, in a topic
314
+ * created under the parent since), sent since the intent. Read from those topics only, so other talk about the plan
315
+ * cannot hide it.
316
+ */
317
+ const handoffSince = (plan, receipt) => {
318
+ const history = messages.forMember(OWNER_ID);
319
+ const places = receipt.topic ? [receipt.topic]
320
+ : receipt.parent ? topics.children(receipt.parent).filter((topic) => topic.createdAt >= receipt.since).map((topic) => topic.id) : [];
321
+ for (const place of places) {
322
+ for (const head of history.heads(place, receipt.since).toReversed()) {
323
+ if (!head.content.startsWith('开始做一条规划:「') || !head.content.includes(`(${plan.id})`))
324
+ continue;
325
+ const assignee = head.to.find((id) => members.get(id)?.kind === 'agent');
326
+ const step = { at: head.createdAt, by: head.from.id, what: 'started', where: address.message(place, head.id),
327
+ ...(assignee ? { assignee } : {}), ...receipt.stamp };
328
+ return { at: place, step };
329
+ }
330
+ }
331
+ return undefined;
332
+ };
333
+ /** A handoff that went out for this plan and is not in its record yet, from its receipt or found from its intent. */
334
+ const pendingStart = (plan) => {
335
+ const receipt = receiptOf(plan);
336
+ if (!receipt)
337
+ return undefined;
338
+ if (plan.trail.some((step) => step.what === 'started' && (receipt.step ? step.at === receipt.step.at && step.where === receipt.step.where : step.at >= receipt.since))) {
339
+ dropReceipt(plan.id);
340
+ return undefined;
341
+ }
342
+ const sent = receipt.step && receipt.at ? { at: receipt.at, step: receipt.step } : handoffSince(plan, receipt);
343
+ if (!sent)
344
+ dropReceipt(plan.id); // the intent was written, the handoff never went out
345
+ return sent;
346
+ };
347
+ /**
348
+ * Writes a handoff that went out into the plan. A decision taken after it (done, dropped, a later start or return to
349
+ * noted) stands: the handoff then only joins the record at its time.
350
+ */
351
+ const recordStart = (plan, sent) => {
352
+ const later = plan.trail.some((step) => step.at > sent.step.at && ['done', 'dropped', 'reopened', 'started', 'suspended'].includes(step.what));
353
+ if (later || plan.state === 'done' || plan.state === 'dropped') {
354
+ const index = plan.trail.findIndex((step) => step.at > sent.step.at);
355
+ plan.trail.splice(index < 0 ? plan.trail.length : index, 0, sent.step);
356
+ return false;
357
+ }
358
+ plan.state = 'doing';
359
+ plan.at = sent.at;
360
+ delete plan.waiting;
361
+ delete plan.reminder;
362
+ plan.trail.push(sent.step);
363
+ return true;
364
+ };
365
+ const save = (books, workTopics = []) => {
366
+ const affected = new Set(workTopics.filter((id) => !!id));
367
+ for (const [topic, items] of books) {
368
+ writeFileSync(file(topic), `${JSON.stringify({ items }, null, 2)}\n`);
369
+ locateBook(topic.id, items);
370
+ affected.add(topic.id);
371
+ }
372
+ const pending = receipts();
373
+ if (pending.length) {
374
+ const kept = pending.filter((item) => !item.step || !books.some(([, items]) => items.some((plan) => plan.id === item.plan
375
+ && plan.trail.some((step) => step.what === 'started' && step.at === item.step.at && step.where === item.step.where))));
376
+ if (kept.length !== pending.length)
377
+ writeReceipts(kept);
378
+ }
379
+ ctx.runtime.emit('plans.changed', { topicIds: [...affected] });
380
+ };
381
+ const replace = (home, before, next, target = home) => {
382
+ const items = bookOf(home);
383
+ const books = target.id === home.id
384
+ ? [[home, items.map((p) => p.id === next.id ? next : p)]]
385
+ : [[target, [...bookOf(target), next]], [home, items.filter((p) => p.id !== next.id)]];
386
+ save(books, [before.at, next.at]);
387
+ if (before.title !== next.title || before.at !== next.at) {
388
+ ctx.runtime.emit('address.changed', { addresses: [address.item('plans', next.id)] });
389
+ }
390
+ };
391
+ const everywhere = () => topics.list().flatMap((topic) => bookOf(topic).map((plan) => ({ topic, plan })));
392
+ function editPrerequisites(plan, args, before) {
393
+ if (args.dependencies === undefined && args.prerequisites === undefined)
394
+ return;
395
+ const text = plan.dependencies ?? '';
396
+ const refs = args.prerequisites ?? planRefs(text);
397
+ const current = new Set(planRefs(before?.dependencies ?? ''));
398
+ const added = [...new Set(refs)].filter((id) => !current.has(id));
399
+ if (added.length) {
400
+ const plans = new Map(everywhere().map(({ plan }) => [plan.id, plan]));
401
+ for (const id of added) {
402
+ const path = prerequisitePath(plans, id, plan.id);
403
+ if (path) {
404
+ const cycle = [plan.id, ...path].map((key) => key === plan.id ? plan.title : plans.get(key)?.title ?? key);
405
+ throw new HttpError(409, `规划不能互相等待:${cycle.join(' → ')}`);
406
+ }
407
+ if (args.prerequisites && !plans.has(id))
408
+ throw new HttpError(400, `没有这条前置规划:${id}`);
409
+ }
410
+ }
411
+ if (args.prerequisites === undefined)
412
+ return;
413
+ const dependencies = withPrerequisites(text, refs);
414
+ if (dependencies)
415
+ plan.dependencies = dependencies;
416
+ else
417
+ delete plan.dependencies;
418
+ }
419
+ ctx.provide('plans', {
420
+ source(id) {
421
+ const found = everywhere().find(({ plan }) => plan.id === id);
422
+ if (!found)
423
+ return;
424
+ const { plan } = found;
425
+ const assignment = plan.trail.findLast((step) => step.what === 'started' && step.where)?.where;
426
+ return { ...plan.from, ...(assignment ? { assignment } : {}) };
427
+ },
428
+ affectedWork(turn, reply) {
429
+ const history = messages.forMember(OWNER_ID);
430
+ const getMessage = (id) => history.get(id, { includeDeleted: true });
431
+ return [...(placesByBook ?? locateBooks())].flatMap(([id, places]) => {
432
+ const home = topics.get(id);
433
+ if (!places.has(turn.topicId) || !home || home.archivedAt !== null)
434
+ return [];
435
+ return bookOf(home).flatMap((plan) => {
436
+ if (plan.suspended || plan.at !== turn.topicId || assigneeOf(ctx.runtime, plan) !== turn.memberId)
437
+ return [];
438
+ const { since, related, unanchored } = assignmentContext(plan, turn.memberId, getMessage);
439
+ if (turn.endedAt === null || turn.endedAt < since || (!related(reply.id) && !related(reply.thread) && !related(reply.replyTo)
440
+ && !(turn.trace?.read ?? reply.read).some(related) && !unanchored(turn.startedAt, turn.memberId)))
441
+ return [];
442
+ const sourceMessageId = sourceId(plan.from);
443
+ return [{ id: plan.id, title: plan.title, ...(sourceMessageId ? { sourceMessageId } : {}) }];
444
+ });
445
+ });
446
+ },
447
+ });
448
+ ctx.hook('address.labels', ({ addresses }) => {
449
+ const prefix = address.page('plans') + '/';
450
+ if (![...addresses].some((href) => href.startsWith(prefix)))
451
+ return;
452
+ const labels = {};
453
+ for (const { plan } of everywhere()) {
454
+ const href = address.item('plans', plan.id);
455
+ if (addresses.has(href))
456
+ labels[href] = plan.title;
457
+ }
458
+ return labels;
459
+ });
460
+ const find = (id) => {
461
+ const found = everywhere().find(({ plan }) => plan.id === id);
462
+ if (!found)
463
+ throw new HttpError(404, `没有这条规划:${String(id)}`);
464
+ return found;
465
+ };
466
+ const who = (caller) => caller.member?.id ?? OWNER_ID;
467
+ const nameOf = (id) => members.get(id)?.name ?? id;
468
+ const pathText = (id) => topics.path(id).map((t) => t.title).join(' › ');
469
+ const messageAt = (id, memberId) => {
470
+ const message = (memberId ? messages.forMember(memberId) : messages).get(String(id));
471
+ if (!message)
472
+ throw new Error(`没有这条消息:${String(id)}`);
473
+ return address.message(message.topicId, message.id);
474
+ };
475
+ const liveOf = (caller) => (caller.member && caller.topicId ? a2a.live(caller.topicId).find((turn) => turn.memberId === caller.member.id) : undefined);
476
+ /** Where a plan comes from: what was given; else, for a member, the message its turn answers. */
477
+ const checkedDoc = ({ resource, section }) => {
478
+ if (works.parseResource(resource)?.kind !== 'topic')
479
+ throw new HttpError(400, '文档出处要填写规范的主题资源地址');
480
+ const text = section?.trim();
481
+ return { resource, ...(text ? { section: text } : {}) };
482
+ };
483
+ const checkedStatement = (resource) => {
484
+ let value = resource.trim();
485
+ // A path written as it reads (with spaces or Chinese) is taken in its canonical, encoded form.
486
+ if (!works.parseResource(value)) {
487
+ const [prefix, owner, ...rest] = value.split('/');
488
+ value = [prefix, owner, ...rest.map((part) => encodeURIComponent(part))].join('/');
489
+ }
490
+ if (works.parseResource(value)?.kind !== 'topic')
491
+ throw new HttpError(400, '验收声明要填写主题文件的资源地址,如 res:topic/top_…/tmp/验收声明.md');
492
+ return value;
493
+ };
494
+ const sourceOf = (args, caller) => {
495
+ const live = liveOf(caller);
496
+ const answered = args.message ?? (args.doc ? undefined : live?.replyTo ?? live?.read.at(-1));
497
+ if (!answered && !args.doc)
498
+ throw new Error('要说出处:message 填消息编号,或 doc 填文档资源地址和可选章节');
499
+ return { ...(answered ? { message: messageAt(answered) } : {}), ...(args.doc ? { doc: checkedDoc(args.doc) } : {}) };
500
+ };
501
+ /** Where something about a plan was decided: the message named; else the reply the member is writing. */
502
+ const decidedAt = (where, caller) => {
503
+ const live = liveOf(caller);
504
+ return where ? messageAt(where, who(caller)) : live ? address.message(live.topicId, live.messageId) : undefined;
505
+ };
506
+ const sourceId = (from) => from.message?.split('/')[1];
507
+ const sourceMessage = (from) => {
508
+ const id = sourceId(from);
509
+ return id ? messages.get(id, { includeDeleted: true }) : undefined;
510
+ };
511
+ const messageLabel = (message) => {
512
+ if (!message || message.deletedAt !== undefined)
513
+ return '(原消息已删除)';
514
+ const words = message.content.replace(/\s+/g, ' ').trim();
515
+ return `${message.from.kind === 'member' ? nameOf(message.from.id) : message.from.id}:「${words.length > 40 ? `${words.slice(0, 40)}…` : words}」`;
516
+ };
517
+ const documentSource = ({ resource, section }) => {
518
+ const ref = works.parseResource(resource);
519
+ const topic = ref?.kind === 'topic' ? topics.get(ref.topicId) : undefined;
520
+ const place = ref?.kind === 'topic' ? `${topic?.title ?? ref.topicId} › ${ref.path}` : resource;
521
+ const label = place + (section ? `「${section}」` : '');
522
+ const locator = section ? { text: section } : undefined;
523
+ if (topic?.deletedAt !== null || !works.open(topic, resource, locator))
524
+ return { label: `${label}(原件不可用)` };
525
+ const source = encodeURIComponent(JSON.stringify({ resource, locator })).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16));
526
+ return { label, url: `${address.topic(topic.id)}?source=${source}` };
527
+ };
528
+ const readerFor = (viewer) => viewer ? messages.forMember(viewer) : messages;
529
+ const admitted = (topicId, viewer) => viewer ? a2a.worksIn(topicId, viewer) : !topics.get(topicId)?.members?.length;
530
+ const availableMessage = (url, viewer) => {
531
+ if (!url)
532
+ return false;
533
+ const [chat, id] = url.split('/');
534
+ return topics.get(chat.slice(5))?.deletedAt === null && admitted(chat.slice(5), viewer) && !!readerFor(viewer).get(id);
535
+ };
536
+ /**
537
+ * Where the plan stands now: the latest message on it by whoever holds it (the assignee, or the one it waits for),
538
+ * the wait it declared, or the reminder about it; failing those, the handoff. The source stays in the source.
539
+ */
540
+ const currentPlace = (plan, working, assignee, viewer) => {
541
+ const since = plan.trail.findLast((s) => s.what === 'started')?.at ?? 0;
542
+ const waited = plan.waiting ? plan.trail.findLast((s) => s.what === 'waiting') : undefined;
543
+ // A declared wait points where it was asked, even in another topic; nothing said later in passing moves it.
544
+ if (waited?.where && availableMessage(waited.where, viewer))
545
+ return waited;
546
+ // Whoever declared the wait asked the question there: their word on it counts too.
547
+ const holders = new Set([assignee, plan.waiting?.on, waited?.by].filter(Boolean));
548
+ const here = address.topic(working.id) + '/';
549
+ const steps = plan.trail.filter((s) => s.at >= since && s.where?.startsWith(here) && (s.what === 'started' || s.what === 'continued' || s.what === 'reminded' || (s.what === 'mentioned' && holders.has(s.by))));
550
+ return steps.findLast((s) => availableMessage(s.where, viewer));
551
+ };
552
+ const jumpTo = (home, plan, working, source, document, assignee, viewer) => {
553
+ const floor = plan.trail.findLast((s) => s.what === 'started')?.where;
554
+ const card = acceptancePlace(plan);
555
+ const receipt = plan.state === 'done' && plan.trail.findLast((s) => s.what === 'done')?.where;
556
+ if (receipt && receipt === card && availableMessage(receipt, viewer))
557
+ return { kind: 'acceptance', url: receipt };
558
+ if (plan.state === 'doing' && working?.deletedAt === null) {
559
+ if (!plan.suspended && plan.waiting?.on === OWNER_ID && card?.startsWith(address.topic(working.id) + '/')
560
+ && availableMessage(card, viewer) && acceptancePart(readerFor(viewer).get(card.split('/')[1]))?.state === 'pending')
561
+ return { kind: 'acceptance', url: card };
562
+ const now = currentPlace(plan, working, assignee, viewer);
563
+ if (now && now.what !== 'started')
564
+ return { kind: now.where === card ? 'acceptance' : 'current', url: now.where };
565
+ }
566
+ if (working?.deletedAt === null && floor?.startsWith(address.topic(working.id) + '/') && availableMessage(floor, viewer))
567
+ return { kind: 'handoff', url: floor };
568
+ if (receipt && availableMessage(receipt, viewer))
569
+ return { kind: 'receipt', url: receipt };
570
+ if (source)
571
+ return { kind: 'source', url: source };
572
+ if (document)
573
+ return { kind: 'document', url: document };
574
+ return working?.deletedAt === null ? { kind: 'work', url: address.topic(working.id) } : { kind: 'home', url: address.topic(home.id) };
575
+ };
576
+ const noted = (plan) => plan.trail[0];
577
+ /** A plan as it is listed: with the topic it is kept in, its source in a few words, and how the topic that does it stands. */
578
+ const view = (topic, stored, signals, viewer) => {
579
+ // A shared plan may point at a smaller review audience. Its history and jump use that same audience.
580
+ const scopes = new Map();
581
+ const permits = (where) => {
582
+ if (!scopes.has(where)) {
583
+ const [chat, id] = where.split('/');
584
+ const routing = id ? messages.storedRouting(id) : undefined;
585
+ scopes.set(where, !!routing && admitted(chat.slice(5), viewer) && visibleTo(routing.visibility, viewer));
586
+ }
587
+ return scopes.get(where);
588
+ };
589
+ const plan = { ...stored, trail: stored.trail.map((step) => {
590
+ if (!step.where || permits(step.where))
591
+ return step;
592
+ const { where, why, waitingOn, ...publicStep } = step;
593
+ return publicStep;
594
+ }) };
595
+ if (stored.waiting && (!viewer || !reminderPlace(ctx.runtime, stored, viewer)))
596
+ delete plan.waiting;
597
+ if (plan.reminder && !permits(plan.reminder))
598
+ delete plan.reminder;
599
+ if (plan.from.message && !permits(plan.from.message))
600
+ plan.from = { doc: plan.from.doc };
601
+ const place = plan.at ? topics.get(plan.at) : undefined;
602
+ const source = sourceId(plan.from);
603
+ const message = source ? readerFor(viewer).get(source, { includeDeleted: true }) : undefined;
604
+ const label = plan.from.message && messageLabel(message);
605
+ const url = message && message.deletedAt === undefined && topics.get(message.topicId)?.deletedAt === null ? plan.from.message : undefined;
606
+ const doc = plan.from.doc && documentSource(plan.from.doc);
607
+ const assignee = signals ? signals.assignee : assigneeOf(ctx.runtime, plan);
608
+ const { waiting, acceptance, ...saved } = plan;
609
+ return {
610
+ ...saved, prerequisites: planRefs(plan.dependencies ?? ''),
611
+ // One judgment everywhere: the board, the handoff, the turn and done read the same effective state.
612
+ ...(acceptance ? { acceptance: acceptance.map((item) => ({ ...item, effective: effective(item, running) })) } : {}),
613
+ ...(waiting ? { waiting: { on: waiting.on, why: waiting.why, since: waiting.since, ...(waiting.until !== undefined ? { until: waiting.until } : {}) } } : {}),
614
+ topicId: topic.id, topic: pathText(topic.id), source: [label, doc?.label].filter(Boolean).join(' '), jump: jumpTo(topic, plan, place, url, doc?.url, assignee, viewer),
615
+ ...signals, ...(assignee ? { assignee } : {}),
616
+ // Who holds the plan now: the one it waits for, else whoever works on it.
617
+ ...(plan.state === 'doing' && !plan.suspended && (plan.waiting?.on ?? assignee) ? { responsible: plan.waiting?.on ?? assignee } : {}),
618
+ ...(label ? { messageSource: { label, ...(url ? { url } : {}) } } : {}),
619
+ ...(plan.from.message && (!message || message.deletedAt !== undefined) ? { sourceDeleted: true } : {}),
620
+ ...(doc ? { documentSource: doc } : {}),
621
+ ...(plan.statement ? { statementSource: documentSource({ resource: plan.statement }) } : {}),
622
+ ...(place ? { place: { topicId: place.id, title: place.title, busy: a2a.live(place.id).length > 0, lastActiveAt: place.lastActiveAt } } : {}),
623
+ };
624
+ };
625
+ const order = (a, b) => Number(!!b.pinned) - Number(!!a.pinned) || noted(a).at - noted(b).at;
626
+ // What this plugin says itself is not a mention of the plans it names.
627
+ let own = false;
628
+ const quietly = (fn) => {
629
+ const was = own;
630
+ own = true;
631
+ try {
632
+ return fn();
633
+ }
634
+ finally {
635
+ own = was;
636
+ }
637
+ };
638
+ // The channel card is the handoff and receipt. The plan only keeps its address and the results of its checks.
639
+ const acceptanceCard = (home, plan) => {
640
+ if (plan.state !== 'doing' || plan.suspended || plan.waiting?.on !== OWNER_ID || !plan.at)
641
+ return;
642
+ const work = topics.get(plan.at);
643
+ if (home.archivedAt !== null || home.deletedAt !== null || work?.archivedAt !== null || work.deletedAt !== null)
644
+ return;
645
+ const pending = unmet(plan.acceptance, running);
646
+ if (!pending.length || pending.some((item) => item.by !== 'owner'))
647
+ return;
648
+ const versions = pending.map(({ target }) => target?.plugin ? running.plugins[target.plugin] : target ? running.commit : null);
649
+ if (versions.includes(undefined))
650
+ return;
651
+ const statement = plan.statement && documentSource({ resource: plan.statement }).url;
652
+ return {
653
+ kind: ACCEPTANCE_CARD, title: `结项验收 · ${plan.title}`, by: assigneeOf(ctx.runtime, plan),
654
+ body: [planLink(plan), plan.waiting.why, statement && link('打开验收声明', statement)].filter(Boolean).join('\n\n'),
655
+ items: pending.map((item, index) => ({
656
+ id: item.id, title: item.result,
657
+ fields: [{ label: '入口', value: item.entry }, { label: '操作', value: item.action },
658
+ ...(item.target ? [{ label: '验收环境', value: `${targetText(item.target)} · ${versions[index]}` }] : [])],
659
+ })),
660
+ data: { plan: plan.id, since: plan.waiting.since, versions },
661
+ approve: '验收通过并结项', reject: '退回继续处理',
662
+ };
663
+ };
664
+ const fromPlans = (message) => message.from.kind === sender.kind && message.from.id === sender.id;
665
+ const sameAcceptanceCard = (card, next) => card.title === next.title && card.body === next.body && card.by === next.by
666
+ && isDeepStrictEqual(card.data, next.data) && isDeepStrictEqual(card.items, next.items);
667
+ const cardPlan = (card) => everywhere().find(({ plan }) => plan.id === card.data?.plan);
668
+ const acceptanceResult = (approved) => ({ ok: true, text: approved ? '验收通过,规划已结项' : '已退回,规划继续进行' });
669
+ const useAcceptanceAnswer = ({ message, answer }) => {
670
+ syncConsoleVersion();
671
+ const card = acceptancePart(message);
672
+ const located = cardPlan(card);
673
+ const where = address.message(message.topicId, message.id);
674
+ const applied = located?.plan.trail.some((step) => step.where === where && step.at === answer.at && step.by === answer.by
675
+ && step.what === (answer.approved ? 'done' : 'continued'));
676
+ if (applied)
677
+ return acceptanceResult(answer.approved);
678
+ const asked = located && acceptanceCard(located.topic, located.plan);
679
+ if (answer.by !== OWNER_ID || !located || !asked || acceptancePlace(located.plan) !== where || !sameAcceptanceCard(card, asked)) {
680
+ return { ok: false, text: '规划或验收环境已更新,请查看当前的结项验收' };
681
+ }
682
+ const { topic, plan } = located;
683
+ const next = { ...plan, trail: [...plan.trail] };
684
+ const step = { at: answer.at, by: answer.by, where };
685
+ for (const { id } of asked.items) {
686
+ const { items, item } = checkAcceptance(next.acceptance, { id: id, state: answer.approved ? 'passed' : 'failed', note: answer.text }, { id: answer.by, owner: true }, running, answer.at);
687
+ next.acceptance = items;
688
+ next.trail.push({ ...step, what: 'checked', why: acceptanceLine(item) });
689
+ }
690
+ if (answer.approved && unmet(next.acceptance, running).length)
691
+ return { ok: false, text: '还有待验收项,请查看当前的结项验收' };
692
+ delete next.waiting;
693
+ delete next.reminder;
694
+ if (answer.approved)
695
+ next.state = 'done';
696
+ next.trail.push({ ...step, what: answer.approved ? 'done' : 'continued', why: answer.approved ? '机主验收通过' : '机主退回验收' });
697
+ replace(topic, plan, next);
698
+ return acceptanceResult(answer.approved);
699
+ };
700
+ const syncAcceptanceCard = (home, plan) => {
701
+ if (!ctx.runtime.has('cards'))
702
+ return;
703
+ const cards = ctx.get('cards');
704
+ const wanted = acceptanceCard(home, plan);
705
+ const previous = cards.get(acceptancePlace(plan)?.split('/')[1] ?? '');
706
+ const card = previous && fromPlans(previous) ? acceptancePart(previous) : undefined;
707
+ // Finish an answer saved just before a reload interrupted delivery to the plan.
708
+ if (previous && card?.state === 'answered' && card.answer && !card.outcome && wanted && sameAcceptanceCard(card, wanted)) {
709
+ const outcome = useAcceptanceAnswer({ message: previous, card, answer: card.answer });
710
+ if (outcome.ok) {
711
+ cards.report(previous.id, { outcome, ...(card.by ? { tell: [card.by] } : {}) });
712
+ return;
713
+ }
714
+ }
715
+ if (card?.state === 'pending') {
716
+ if (wanted && previous.topicId === plan.at) {
717
+ if (!sameAcceptanceCard(card, wanted))
718
+ cards.update(previous.id, wanted);
719
+ return;
720
+ }
721
+ cards.close(previous.id, '规划已更新,当前无需在这张卡上验收');
722
+ }
723
+ if (!wanted)
724
+ return;
725
+ const work = plan.at;
726
+ const reply = plan.trail.findLast((step) => (step.what === 'waiting' || step.what === 'started')
727
+ && step.where?.startsWith(address.topic(work) + '/') && availableMessage(step.where))?.where?.split('/')[1];
728
+ const sent = cards.pending({ topicId: work, from: sender }).find((one) => acceptancePart(one)?.data?.plan === plan.id)
729
+ ?? quietly(() => cards.send({ topicId: work, from: sender, to: [OWNER_ID], card: wanted, ...(reply ? { replyTo: reply } : {}) }));
730
+ const where = address.message(work, sent.id);
731
+ replace(home, plan, { ...plan, trail: [...plan.trail, { what: 'acceptanceAsked', by: sender.id, at: sent.createdAt, where }] });
732
+ };
733
+ let reading = Promise.resolve();
734
+ ctx.hook('cards.refresh', async (message) => {
735
+ const card = acceptancePart(message);
736
+ if (!fromPlans(message) || !card)
737
+ return;
738
+ await reading;
739
+ syncConsoleVersion();
740
+ const cards = ctx.get('cards');
741
+ if (acceptancePart(cards.get(message.id))?.state !== 'pending')
742
+ return;
743
+ const located = cardPlan(card);
744
+ if (located && acceptancePlace(located.plan) === address.message(message.topicId, message.id))
745
+ syncAcceptanceCard(located.topic, located.plan);
746
+ else
747
+ cards.close(message.id, '这张卡已经不再对应当前验收');
748
+ });
749
+ ctx.on('card.answering', ({ message, accept }) => {
750
+ if (fromPlans(message) && acceptancePart(message))
751
+ accept(useAcceptanceAnswer);
752
+ });
753
+ const cardBooks = new Set();
754
+ let cardsQueued = false, cardsStopped = false, versionsRead = false;
755
+ const queueAcceptanceCards = (ids) => {
756
+ if (!versionsRead || cardsStopped || !ctx.runtime.has('cards'))
757
+ return;
758
+ for (const id of ids)
759
+ cardBooks.add(id);
760
+ if (cardsQueued)
761
+ return;
762
+ cardsQueued = true;
763
+ queueMicrotask(() => {
764
+ cardsQueued = false;
765
+ if (cardsStopped)
766
+ return;
767
+ const books = [...cardBooks];
768
+ cardBooks.clear();
769
+ for (const id of books) {
770
+ const home = topics.get(id);
771
+ if (!home)
772
+ continue;
773
+ for (const plan of bookOf(home)) {
774
+ if (!acceptancePlace(plan) && plan.waiting?.on !== OWNER_ID)
775
+ continue;
776
+ try {
777
+ syncAcceptanceCard(home, plan);
778
+ }
779
+ catch (error) {
780
+ ctx.runtime.onError('plans acceptance card ' + plan.id, error);
781
+ }
782
+ }
783
+ }
784
+ });
785
+ };
786
+ ctx.effect(() => { cardsStopped = true; });
787
+ ctx.on('plans.changed', ({ topicIds }) => queueAcceptanceCards(topicIds));
788
+ ctx.on('topic.updated', ({ topic, tree, trashChanged }) => {
789
+ if (!tree?.archiveDelta && !trashChanged?.length)
790
+ return;
791
+ const changed = trashChanged ?? [topic.id];
792
+ const related = [...(placesByBook ?? locateBooks())].filter(([, places]) => changed.some((id) => places.has(id))).map(([id]) => id);
793
+ queueAcceptanceCards([...changed, ...related]);
794
+ });
795
+ /** The topic that raised a plan knows what became of it: a change made from elsewhere leaves a line in its channel, which wakes nobody. */
796
+ const tell = (home, caller, text, where) => {
797
+ if (caller.member && caller.topicId === home.id)
798
+ return;
799
+ const history = readerFor(who(caller));
800
+ const id = where?.split('/')[1] ?? liveOf(caller)?.messageId;
801
+ const source = id ? history.get(id) : undefined;
802
+ if (id && !source)
803
+ return;
804
+ const floor = source?.thread ? history.get(source.thread) : source;
805
+ if (source && !floor)
806
+ return;
807
+ const visibility = sharedVisibility([source?.visibility, floor?.visibility,
808
+ source && source.topicId !== home.id ? topicAudience(ctx.runtime, source.topicId) : undefined]);
809
+ quietly(() => messages.publish({ topicId: home.id, from: sender, content: text, threadable: false, visibility }));
810
+ };
811
+ // A message that names a plan (its id) is part of what happened to it, unless the trail points at that message already.
812
+ ctx.on('message.appended', ({ message }) => {
813
+ if (own)
814
+ return;
815
+ const named = new Set(message.content.match(/plan_[a-z0-9]+/g) ?? []);
816
+ if (!named.size)
817
+ return;
818
+ const where = address.message(message.topicId, message.id);
819
+ const books = [];
820
+ const workTopics = [];
821
+ for (const topic of topics.list()) {
822
+ const items = bookOf(topic);
823
+ const hit = items.filter((plan) => named.has(plan.id) && !plan.trail.some((step) => step.where === where));
824
+ if (!hit.length)
825
+ continue;
826
+ for (const plan of hit)
827
+ plan.trail.push({ at: Date.now(), by: message.from.id, what: 'mentioned', where }); // now: a reply is made before it is written
828
+ books.push([topic, items]);
829
+ workTopics.push(...hit.map((plan) => plan.at));
830
+ }
831
+ if (books.length)
832
+ save(books, workTopics);
833
+ });
834
+ ctx.on('resource.changed', (change) => {
835
+ if (change.kind === 'updated')
836
+ return;
837
+ const books = [];
838
+ const affected = new Set();
839
+ for (const topic of topics.all()) {
840
+ const items = bookOf(topic);
841
+ let moved = false;
842
+ for (const plan of items) {
843
+ const doc = plan.from.doc;
844
+ if (!doc || !works.resourceWithin(doc.resource, change.resource))
845
+ continue;
846
+ affected.add(topic.id);
847
+ if (plan.at)
848
+ affected.add(plan.at);
849
+ if (change.kind === 'moved') {
850
+ doc.resource = change.nextResource + doc.resource.slice(change.resource.length);
851
+ moved = true;
852
+ }
853
+ }
854
+ if (moved)
855
+ books.push([topic, items]);
856
+ }
857
+ if (books.length)
858
+ save(books, [...affected]);
859
+ else if (affected.size)
860
+ ctx.runtime.emit('plans.changed', { topicIds: [...affected] });
861
+ });
862
+ function handoff(home, plan, caller, memberId, from = { kind: 'member', id: who(caller) }) {
863
+ const sources = [];
864
+ if (plan.from.message) {
865
+ const url = plan.from.message;
866
+ sources.push(`${link(messageLabel(sourceMessage(plan.from)), url)},消息编号 ${url.split('/')[1]},用 message_get 读全文`);
867
+ }
868
+ if (plan.from.doc) {
869
+ const doc = documentSource(plan.from.doc);
870
+ sources.push(`${doc.url ? link(doc.label, doc.url) : doc.label},资源地址 ${plan.from.doc.resource}`);
871
+ }
872
+ return {
873
+ from,
874
+ ...(memberId ? { targets: [memberId], requireRecipient: true } : {}),
875
+ ...(caller.member ? { fromTopic: caller.topicId } : {}),
876
+ content: [
877
+ `开始做一条规划:「${plan.title}」(${plan.id})`,
878
+ `- 它记在主题「${pathText(home.id)}」(${home.id})里。`,
879
+ ...(plan.description ? [`- 任务:${plan.description}`] : []),
880
+ ...(plan.trigger ? [`- 触发条件:${plan.trigger}`] : []),
881
+ ...(plan.dependencies ? [`- 依赖:${plan.dependencies}`] : []),
882
+ `- 出处:${sources.join(';')}`,
883
+ ...(plan.statement ? [`- 临时验收声明:${plan.statement}`] : []),
884
+ ...(unmet(plan.acceptance, running).length ? [`- 验收项(全部通过才能标 done,结果用 plan_set 的 check 记录):`, ...unmet(plan.acceptance, running).map((item) => ` - ${acceptanceLine(item, running)}`)] : []),
885
+ `- 交给别人等待复核、验收或答复时,用 plan_set 的 waiting: { on, why } 声明,恢复推进时填 waiting: null。`,
886
+ `- 合入或上线验收后,用 plan_set 回写同一条 ${plan.id} 为 done,where 填验收回执消息编号。暂缓就挂起或改回 later 并写原因;放弃用 dropped 写原因。`,
887
+ ].join('\n'),
888
+ };
889
+ }
890
+ function assign(plan, target, caller, delivery, stamp) {
891
+ active(target);
892
+ // A member can take it on in its current topic, or explicitly hand it to another member there.
893
+ const self = !!caller.member && target.id === caller.topicId && !delivery?.targets;
894
+ let sent;
895
+ try {
896
+ sent = delivery && !self ? quietly(() => a2a.send({ topicId: target.id, ...delivery })) : undefined;
897
+ }
898
+ catch (error) {
899
+ dropReceipt(plan.id);
900
+ throw error;
901
+ }
902
+ const where = sent ? address.message(target.id, sent.message.id) : self ? decidedAt(undefined, caller) : undefined;
903
+ const assignee = sent?.targets.find((id) => members.get(id)?.kind === 'agent') ?? (self ? caller.member.id : undefined);
904
+ plan.state = 'doing';
905
+ plan.at = target.id;
906
+ delete plan.waiting;
907
+ delete plan.reminder;
908
+ const step = { at: Date.now(), by: who(caller), what: 'started', ...(where ? { where } : {}), ...(assignee ? { assignee } : {}), ...stamp };
909
+ plan.trail.push(step);
910
+ if (sent) {
911
+ try {
912
+ writeReceipts([...receipts().filter((item) => item.plan !== plan.id), { plan: plan.id, since: step.at, at: target.id, step }]);
913
+ }
914
+ catch (error) {
915
+ ctx.runtime.onError('plans start receipt ' + plan.id, error); // the intent stays: the handoff is found from it
916
+ }
917
+ }
918
+ else
919
+ dropReceipt(plan.id);
920
+ return { where, woke: (sent?.targets ?? []).map(nameOf) };
921
+ }
922
+ function launch(home, plan, caller, options, from, stamp) {
923
+ // Already handed off, not yet recorded: record that handoff instead of sending another.
924
+ const sent = pendingStart(plan);
925
+ const recorded = sent && topics.get(sent.at);
926
+ if (sent && recorded) {
927
+ if (recordStart(plan, sent))
928
+ return { target: recorded, where: sent.step.where, woke: [] };
929
+ // A later decision outranks the old handoff: it joins the record, and this start goes ahead.
930
+ }
931
+ const preset = options.topic || options.title ? undefined : plan.dispatch;
932
+ const existing = options.topic || preset?.topic;
933
+ const memberId = options.member || preset?.member;
934
+ // The intent goes down before anything is created or sent: where it goes and why. If it cannot be written, nothing goes out.
935
+ writeReceipts([...receipts().filter((item) => item.plan !== plan.id), {
936
+ plan: plan.id, since: Date.now(), ...(existing ? { topic: existing } : { parent: preset?.parent ?? home.id }), ...(stamp ? { stamp } : {}),
937
+ }]);
938
+ if (existing) {
939
+ const target = need(existing);
940
+ checkAssignee(memberId, target);
941
+ return { target, ...assign(plan, target, caller, handoff(home, plan, caller, memberId, from), stamp) };
942
+ }
943
+ const parent = preset?.parent ? need(preset.parent) : home;
944
+ checkAssignee(memberId);
945
+ const lead = memberId || caller.member?.id || parent.defaultMember;
946
+ const delivery = handoff(home, plan, caller, memberId, from);
947
+ a2a.checkNewTopicSend(delivery, lead);
948
+ const target = topics.create({
949
+ title: options.title?.trim() || plan.title,
950
+ parentId: parent.id,
951
+ summary: `承接规划 ${planLink(plan)}。`,
952
+ ...(lead ? { defaultMember: lead } : {}),
953
+ }, caller.member?.id);
954
+ return { target, ...assign(plan, target, caller, delivery, stamp) };
955
+ }
956
+ // ── what can be asked ─────────────────────────────────────────────────
957
+ ctx.effect(entry.group('plans', '规划:各主题延后要做的事和当轮接下的明确改动,每条带出处、状态和承接主题'));
958
+ const op = (decl) => ctx.effect(entry.op(decl));
959
+ op({
960
+ name: 'plans.note',
961
+ about: `记一条规划,默认记在当前主题,出处取本轮所回消息。${WHEN}`,
962
+ input: object({
963
+ ...detailFields, dispatch: dispatchField,
964
+ state: { type: 'string', enum: ['later', 'doing'], description: '默认 later,当轮开工传 doing' },
965
+ at: { type: 'string', description: '直接开工时显式指定的承接主题,省略按执行安排或当前主题' },
966
+ topic: { type: 'string', description: '记在哪个主题里' },
967
+ title: { type: 'string', description: '一句话:要做的是什么' },
968
+ message: { type: 'string', description: '出处:提到这件事的那条消息的编号(msg_…)。成员不填就是这一轮在回的那条' },
969
+ doc: docField,
970
+ acceptance: { ...acceptanceInput, type: 'array' },
971
+ statement: { type: 'string', description: '临时验收声明的主题资源地址(如 res:topic/top_…/tmp/验收声明-xxx.md),写预期、步骤、每步应看到什么和验收环境;空字符串清除' },
972
+ }, ['topic', 'title']),
973
+ output: planOutput, sdk: true,
974
+ http: ['POST', '/api/topics/:topic/plans'], agent: true, topic: 'topic', tool: { server: 'plans', name: 'plan_note', plugin: 'plans' },
975
+ run(args, caller) {
976
+ const topic = need(args.topic);
977
+ const title = args.title.trim();
978
+ if (!title)
979
+ throw new Error('要有一句话的标题');
980
+ const plan = { id: newId('plan'), title, from: sourceOf(args, caller), state: 'later', trail: [{ at: Date.now(), by: who(caller), what: 'noted' }] };
981
+ if (hasConsoleTarget(args.acceptance))
982
+ syncConsoleVersion();
983
+ if (args.acceptance?.length)
984
+ plan.acceptance = withAcceptance([], args.acceptance, () => newId('acc'), running).items;
985
+ if (args.statement?.trim())
986
+ plan.statement = checkedStatement(args.statement);
987
+ editDetails(plan, args);
988
+ if (args.resumeAt?.trim() && !plan.suspended)
989
+ throw new HttpError(400, '恢复时间只能配合暂挂的未了结规划使用');
990
+ editPrerequisites(plan, args);
991
+ if (args.dispatch)
992
+ plan.dispatch = checkedDispatch(args.dispatch);
993
+ if (args.at && args.state !== 'doing')
994
+ throw new Error('只有在做的规划可以交办');
995
+ if (args.state === 'doing' && plan.dispatch) {
996
+ launch(topic, plan, caller, { topic: args.at, member: plan.dispatch.member });
997
+ }
998
+ else if (args.state === 'doing') {
999
+ const target = need(args.at ?? caller.topicId ?? topic.id);
1000
+ assign(plan, target, caller, target.id !== topic.id ? handoff(topic, plan, caller) : undefined);
1001
+ }
1002
+ if (plan.suspended)
1003
+ plan.trail.push({ at: Date.now(), by: who(caller), what: 'suspended' });
1004
+ save([[topic, [...bookOf(topic), plan]]], [plan.at]);
1005
+ return view(topic, plan, undefined, who(caller));
1006
+ },
1007
+ text: (plan) => `记下了:「${plan.title}」,编号 ${plan.id},在主题「${plan.topic}」里。`,
1008
+ });
1009
+ op({
1010
+ name: 'plans.list',
1011
+ about: '所有主题的规划:每条的标题、状态、记在哪个主题、出处、在哪做。不带参数是还没了结的(记着的和在做的)。',
1012
+ input: object({
1013
+ topic: { type: 'string', description: '只要这个主题提的和在这个主题里做的' },
1014
+ state: { type: 'string', enum: Object.keys(LABEL), description: 'later 记着 / doing 在做 / done 做完 / dropped 不做了' },
1015
+ closed: { type: 'boolean', description: 'true:做完的和不做了的也要' },
1016
+ }),
1017
+ output: array(planOutput), sdk: true,
1018
+ http: ['GET', '/api/plans'], agent: true, tool: { server: 'plans', name: 'plan_list', plugin: 'plans' },
1019
+ run({ topic, state, closed }, caller) {
1020
+ let all = everywhere();
1021
+ if (all.some(({ plan }) => OPEN.includes(plan.state) && hasConsoleTarget(plan.acceptance)) && syncConsoleVersion()) {
1022
+ all = everywhere();
1023
+ }
1024
+ const read = planProgress(ctx.runtime, all.map(({ plan }) => plan), attentionMs, Date.now(), who(caller));
1025
+ return all.filter(({ topic: home, plan }) => (!topic || home.id === topic || plan.at === topic) && (state ? plan.state === state : closed || OPEN.includes(plan.state)))
1026
+ .sort((a, b) => order(a.plan, b.plan))
1027
+ .map(({ topic: home, plan }) => view(home, plan, home.archivedAt === null ? read(plan).signals : undefined, who(caller)));
1028
+ },
1029
+ text(list) {
1030
+ const groups = new Map();
1031
+ for (const plan of list)
1032
+ groups.set(plan.topicId, [...(groups.get(plan.topicId) ?? []), plan]);
1033
+ const activity = { advancing: '推进中', recovering: '等待恢复', waiting: '等回应', stalled: '停滞', blocked: '受阻' };
1034
+ const describe = (plan) => {
1035
+ const status = plan.activity;
1036
+ return [
1037
+ `- [${LABEL[plan.state]}] ${plan.title}(${plan.id})`,
1038
+ plan.pinned ? '置顶' : '',
1039
+ plan.place ? `在「${plan.place.title}」(${plan.place.topicId})` : '',
1040
+ plan.assignee ? `${nameOf(plan.assignee)} 跟进` : '',
1041
+ plan.ready ? '依赖就绪' : '', plan.due ? '已到期' : '',
1042
+ plan.prerequisites.length ? '前置:' + plan.prerequisites.map((id) => '#plans/' + id).join('、') : '',
1043
+ status && status.kind !== 'waiting' && status.reason !== 'declared' ? activity[status.kind] + (status.detail ? `(${status.detail})` : '') : '',
1044
+ plan.waiting && !plan.suspended ? `等 ${nameOf(plan.waiting.on)}:${plan.waiting.why}${plan.waiting.until ? `(预计 ${new Date(plan.waiting.until).toLocaleString()})` : ''}` : '',
1045
+ plan.suspended && plan.resumeAt ? `暂挂至 ${new Date(Date.parse(plan.resumeAt)).toLocaleString()}` : '',
1046
+ status?.kind === 'stalled' && ['idle', 'unstarted', 'reply'].includes(status.reason) ? '无人推进' : '',
1047
+ plan.waitingOn ? `推断:等 ${nameOf(plan.waitingOn)} 回应` : '',
1048
+ status?.reason === 'unstarted' ? '登记在做后没有新的工作' : '',
1049
+ `出处:${plan.from.message ? `#${plan.from.message} ` : ''}${plan.source}${plan.from.doc ? `(${plan.from.doc.resource})` : ''}`,
1050
+ ].filter(Boolean).join(' · ');
1051
+ };
1052
+ return [...groups].map(([topicId, plans]) => [
1053
+ `「${plans[0].topic}」(${topicId})`,
1054
+ ...plans.map(describe),
1055
+ ].join('\n')).join('\n\n') || '(没有)';
1056
+ },
1057
+ });
1058
+ op({
1059
+ name: 'plans.set',
1060
+ about: '改规划状态或元信息。交给别人等结果时,跟进成员或在承接主题里工作的成员用 waiting 声明等谁和为什么,继续推进时填 waiting: null。改为 doing 时按显式 at 或执行安排开工。已在做可用 member 转派。合入或上线验收后用原编号标 done,where 指向验收回执。暂缓可挂起或回到 later,写明条件或原因。放弃标 dropped 并写原因。',
1061
+ input: object({
1062
+ id: { type: 'string', description: '规划的编号(plan_…)' },
1063
+ ...detailFields, dispatch: dispatchField, waiting: waitingInput, acceptance: acceptanceInput, check: checkInput,
1064
+ statement: { type: 'string', description: '临时验收声明的主题资源地址(如 res:topic/top_…/tmp/验收声明-xxx.md),写预期、步骤、每步应看到什么和验收环境;空字符串清除' },
1065
+ message: { type: 'string', description: '订正出处用现有消息编号,保留登记人、登记时间和原记录' },
1066
+ doc: { ...docField, type: ['object', 'null'], description: '订正文档出处;有消息出处时可传 null 清除文档' },
1067
+ state: { type: 'string', enum: Object.keys(LABEL) },
1068
+ at: { type: 'string', description: '显式指定承接主题;改为 doing 时可省略并采用执行安排' },
1069
+ member: { type: 'string', member: true, description: '给已在做且未挂起的规划换跟进成员,在承接主题按原编号重新交办' },
1070
+ why: { type: 'string', description: '为什么:标不做了时写原因' },
1071
+ where: { type: 'string', description: '在哪定的:那条消息的编号。成员不填就是这一轮的回复' },
1072
+ title: { type: 'string' },
1073
+ pinned: { type: 'boolean' },
1074
+ topic: { type: 'string', description: '挪到这个主题里记着' },
1075
+ }, ['id']),
1076
+ output: planOutput, sdk: true,
1077
+ http: ['PATCH', '/api/plans/:id'], agent: true, tool: { server: 'plans', name: 'plan_set', plugin: 'plans' },
1078
+ run(args, caller) {
1079
+ let found = find(args.id);
1080
+ if ((hasConsoleTarget(args.acceptance ?? undefined) || hasConsoleTarget(found.plan.acceptance)) && syncConsoleVersion()) {
1081
+ found = find(args.id);
1082
+ }
1083
+ const { topic: home, plan } = found;
1084
+ const step = { at: Date.now(), by: who(caller) };
1085
+ const next = { ...plan, trail: [...plan.trail] };
1086
+ const said = [];
1087
+ if (args.acceptance !== undefined) {
1088
+ if (plan.state === 'done' || plan.state === 'dropped')
1089
+ throw new HttpError(409, '规划已了结;要改验收清单,先改回记着或在做');
1090
+ const { items, changed } = args.acceptance ? withAcceptance(plan.acceptance, args.acceptance, () => newId('acc'), running) : { items: [], changed: [] };
1091
+ guardOwnerItems(plan.acceptance, items, step.by === OWNER_ID);
1092
+ if (items.length)
1093
+ next.acceptance = items;
1094
+ else
1095
+ delete next.acceptance;
1096
+ // A changed criterion is checked again: the trail says which and that it went back to pending.
1097
+ for (const item of changed)
1098
+ next.trail.push({ ...step, what: 'checked', why: `改了标准,退回待验:${acceptanceLine(item)}` });
1099
+ }
1100
+ if (args.statement !== undefined) {
1101
+ if (args.statement.trim())
1102
+ next.statement = checkedStatement(args.statement);
1103
+ else
1104
+ delete next.statement;
1105
+ }
1106
+ if (args.check) {
1107
+ if (plan.state === 'done' || plan.state === 'dropped')
1108
+ throw new HttpError(409, '规划已了结;要重新验收,先改回记着或在做');
1109
+ const { items, item } = checkAcceptance(next.acceptance ?? [], args.check, { id: step.by, owner: step.by === OWNER_ID, assignee: assigneeOf(ctx.runtime, plan) }, running);
1110
+ next.acceptance = items;
1111
+ const where = decidedAt(args.where, caller);
1112
+ next.trail.push({ ...step, what: 'checked', why: acceptanceLine(item) + (item.checked?.note ? `:${item.checked.note}` : ''), ...(where ? { where } : {}) });
1113
+ }
1114
+ editDetails(next, args);
1115
+ editPrerequisites(next, args, plan);
1116
+ if (args.dispatch)
1117
+ next.dispatch = checkedDispatch(args.dispatch);
1118
+ if (args.message !== undefined) {
1119
+ const message = messageAt(args.message);
1120
+ if (message !== plan.from.message) {
1121
+ if (plan.from.message && !noted(plan).where && !plan.trail.some((step) => step.what === 'sourceCorrected')) {
1122
+ next.trail[0] = { ...noted(plan), where: plan.from.message };
1123
+ }
1124
+ next.from = { ...plan.from, message };
1125
+ next.trail.push({ ...step, what: 'sourceCorrected', where: message });
1126
+ }
1127
+ }
1128
+ if (args.doc !== undefined) {
1129
+ next.from = { ...next.from };
1130
+ if (args.doc)
1131
+ next.from.doc = checkedDoc(args.doc);
1132
+ else
1133
+ delete next.from.doc;
1134
+ if (!next.from.message && !next.from.doc)
1135
+ throw new HttpError(400, '规划需要有消息或文档出处');
1136
+ }
1137
+ const title = args.title?.trim();
1138
+ if (title === '')
1139
+ throw new Error('要有一句话的标题');
1140
+ if (title && title !== plan.title) {
1141
+ next.title = title;
1142
+ said.push(`改名为「${title}」`);
1143
+ }
1144
+ if (args.pinned !== undefined) {
1145
+ if (args.pinned)
1146
+ next.pinned = true;
1147
+ else
1148
+ delete next.pinned;
1149
+ }
1150
+ const why = args.why?.trim();
1151
+ const target = args.topic && args.topic !== home.id ? need(args.topic) : home;
1152
+ const state = args.state ?? plan.state;
1153
+ if (!OPEN.includes(state)) {
1154
+ delete next.suspended;
1155
+ delete next.resumeAt;
1156
+ }
1157
+ if (args.resumeAt?.trim() && (!next.suspended || !OPEN.includes(state))) {
1158
+ throw new HttpError(400, '恢复时间只能配合暂挂的未了结规划使用');
1159
+ }
1160
+ if (args.at && state !== 'doing')
1161
+ throw new Error('只有在做的规划可以交办');
1162
+ if (args.member && (plan.state !== 'doing' || state !== 'doing' || next.suspended)) {
1163
+ throw new HttpError(409, '只有未挂起且在做的规划可以转派成员');
1164
+ }
1165
+ if (state === 'dropped' && state !== plan.state && !why)
1166
+ throw new Error('请写下不做这条规划的原因');
1167
+ const open = state === 'done' && state !== plan.state ? unmet(next.acceptance, running) : [];
1168
+ if (open.length && step.by !== OWNER_ID) {
1169
+ throw new HttpError(409, `还有验收项没在目标当前运行的版本上通过,不能标做完:\n${open.map((item) => acceptanceLine(item, running)).join('\n')}`);
1170
+ }
1171
+ const decision = decidedAt(args.where, caller);
1172
+ let where;
1173
+ let checkWaitQuota;
1174
+ const previousAssignee = assigneeOf(ctx.runtime, plan);
1175
+ const reassigned = (args.at && (args.at !== plan.at || next.dispatch?.member !== plan.dispatch?.member))
1176
+ || (args.member && args.member !== previousAssignee);
1177
+ if (args.waiting !== undefined) {
1178
+ const assignee = assigneeOf(ctx.runtime, plan);
1179
+ // The owner, the assignee, or a member working in the plan's topic (who sees where it stands) may say whom it waits for.
1180
+ if (step.by !== OWNER_ID && step.by !== assignee && !(caller.member && caller.topicId === plan.at)) {
1181
+ throw new HttpError(403, '由跟进成员或在承接主题里工作的成员声明或清除卡点');
1182
+ }
1183
+ if (args.waiting) {
1184
+ if (plan.state !== 'doing' || state !== 'doing' || reassigned)
1185
+ throw new HttpError(409, '请在承接规划后声明卡点');
1186
+ const { on } = args.waiting, why = args.waiting.why.trim();
1187
+ if (!why || on === assignee)
1188
+ throw new HttpError(400, '请填写正在等的其他成员与原因');
1189
+ const rawUntil = args.waiting.until?.trim();
1190
+ const until = rawUntil ? parseIsoTime(rawUntil) : undefined;
1191
+ if (rawUntil && until === undefined)
1192
+ throw new HttpError(400, '等待到期时间请填写有效的 ISO 日期时间');
1193
+ const work = active(need(plan.at));
1194
+ if (on !== OWNER_ID) {
1195
+ const targetMember = members.get(on);
1196
+ if (!targetMember)
1197
+ throw new Error(`成员已经不在了:${on}`);
1198
+ if (!members.acceptsDelivery(on))
1199
+ throw new Error(`成员 ${targetMember.name} 未声明接收消息`);
1200
+ if (!a2a.worksIn(work.id, on))
1201
+ throw new Error(`成员 ${targetMember.name} 不在这个主题的成员里`);
1202
+ }
1203
+ const sameWait = plan.waiting?.on === on && plan.waiting.why === why;
1204
+ if (!sameWait) {
1205
+ const askedIn = requestTopic(decision);
1206
+ next.waiting = { on, why, since: step.at, after: messages.lastSeq(work.id),
1207
+ ...(askedIn && askedIn !== work.id ? { requestAfter: messages.lastSeq(askedIn) } : {}),
1208
+ ...(until !== undefined ? { until } : {}) };
1209
+ next.trail.push({ ...step, what: 'waiting', waitingOn: on, why, ...(decision ? { where: decision } : {}) });
1210
+ delete next.reminder;
1211
+ }
1212
+ else if (until !== undefined && plan.waiting.until !== until) {
1213
+ next.waiting = { ...plan.waiting, until };
1214
+ delete next.reminder;
1215
+ }
1216
+ else if (args.waiting.until !== undefined && !rawUntil && plan.waiting.until !== undefined) {
1217
+ const { until: _cleared, ...rest } = plan.waiting;
1218
+ next.waiting = rest;
1219
+ delete next.reminder;
1220
+ }
1221
+ if (next.waiting && next.waiting.until === undefined && on !== OWNER_ID) {
1222
+ checkWaitQuota = { id: next.id, on, since: next.waiting.since };
1223
+ }
1224
+ }
1225
+ else if (plan.waiting) {
1226
+ delete next.waiting;
1227
+ delete next.reminder;
1228
+ next.trail.push({ ...step, what: 'continued', ...(decision ? { where: decision } : {}) });
1229
+ }
1230
+ }
1231
+ let closeWhy = why;
1232
+ if (state === 'doing' && (state !== plan.state || reassigned)) {
1233
+ const destination = args.at ?? (args.member ? plan.at : undefined);
1234
+ if (!destination && !next.dispatch)
1235
+ throw new Error('在做的规划要选择承接主题或执行安排');
1236
+ const assignment = launch(target, next, caller, { topic: destination, member: args.member ?? next.dispatch?.member });
1237
+ const work = assignment.target;
1238
+ where = assignment.where;
1239
+ said.push(`交给主题 ${link(work.title, where ?? address.topic(work.id))}`);
1240
+ }
1241
+ else if (state !== plan.state && state !== 'doing') {
1242
+ where = decision;
1243
+ next.state = state;
1244
+ delete next.waiting;
1245
+ delete next.reminder;
1246
+ if (state === 'later')
1247
+ delete next.at;
1248
+ else if (state === 'done' && !next.at && caller.member)
1249
+ next.at = caller.topicId;
1250
+ if (state === 'done' && step.by === OWNER_ID && open.length) {
1251
+ const note = `机主直接确认结项(放行 ${open.length} 项未通过验收项)`;
1252
+ closeWhy = why ? `${why};${note}` : note;
1253
+ }
1254
+ next.trail.push({ ...step, what: state === 'later' ? 'reopened' : state, ...(where ? { where } : {}), ...(closeWhy ? { why: closeWhy } : {}) });
1255
+ said.push(state === 'later' ? '改回了记着' : `标成了${LABEL[state]}`);
1256
+ }
1257
+ if (OPEN.includes(state) && !!next.suspended !== !!plan.suspended) {
1258
+ next.trail.push({ ...step, what: next.suspended ? 'suspended' : 'resumed', ...(decision || where ? { where: decision ?? where } : {}), ...(why ? { why } : {}) });
1259
+ }
1260
+ else if (args.state === plan.state && (next.suspended || state === 'done' || state === 'dropped') && (args.where || why)) {
1261
+ const index = next.trail.findLastIndex((record) => record.what === (next.suspended ? 'suspended' : state));
1262
+ next.trail[index] = { ...next.trail[index], ...(args.where ? { where: decision } : {}), ...(why ? { why } : {}) };
1263
+ }
1264
+ if (home.id === target.id && isDeepStrictEqual(next, plan)) {
1265
+ if (checkWaitQuota)
1266
+ syncWaitingReset(checkWaitQuota.id, checkWaitQuota.on, checkWaitQuota.since);
1267
+ return view(home, plan, undefined, who(caller));
1268
+ }
1269
+ replace(home, plan, next, target);
1270
+ if (reassigned && previousAssignee && plan.at && previousAssignee !== assigneeOf(ctx.runtime, next)
1271
+ && a2a.worksIn(plan.at, previousAssignee) && members.canReceive(previousAssignee)) {
1272
+ try {
1273
+ quietly(() => a2a.send({ topicId: plan.at, from: sender, targets: [previousAssignee], requireRecipient: true,
1274
+ content: `规划${planLink(next)}已转派。请交接这条规划的未完成工作,由${nameOf(assigneeOf(ctx.runtime, next) ?? OWNER_ID)}继续跟进。${where ? link('新的交办', where) : ''}` }));
1275
+ }
1276
+ catch (error) {
1277
+ ctx.runtime.onError('plans reassignment notice ' + plan.id, error);
1278
+ }
1279
+ }
1280
+ if (checkWaitQuota)
1281
+ syncWaitingReset(checkWaitQuota.id, checkWaitQuota.on, checkWaitQuota.since);
1282
+ const line = (actions) => `${nameOf(step.by)} 把规划${planLink(plan)}${actions.join(',')}${closeWhy ? `:${closeWhy}` : ''}。${where ? link('在这里定的', where) : ''}`;
1283
+ if (target.id !== home.id) {
1284
+ tell(home, caller, line([...said, `挪到了主题 ${link(target.title, address.topic(target.id))}`]), where ?? decision);
1285
+ tell(target, caller, line([...said, `从主题 ${link(home.title, address.topic(home.id))} 挪到了这里`]), where ?? decision);
1286
+ }
1287
+ else if (said.length) {
1288
+ tell(home, caller, line(said), where ?? decision);
1289
+ }
1290
+ return view(target, next, undefined, who(caller));
1291
+ },
1292
+ text: (plan) => `好:「${plan.title}」(${plan.id})现在是${LABEL[plan.state]},记在主题「${plan.topic}」里。${plan.waiting ? `等 ${nameOf(plan.waiting.on)}:${plan.waiting.why}${plan.waiting.until ? `(预计 ${new Date(plan.waiting.until).toLocaleString()})` : ''}。` : ''}${plan.suspended && plan.resumeAt ? `暂挂至 ${new Date(Date.parse(plan.resumeAt)).toLocaleString()}。` : ''}`,
1293
+ });
1294
+ op({
1295
+ name: 'plans.start',
1296
+ about: '开始做一条记着且未挂起的规划。默认按已存安排交办,没有安排则在归属主题下开子主题。可显式指定已有主题或新主题标题;只传 member 则在已选去向换接收成员。交办消息带任务、出处和收尾要求。',
1297
+ input: object({
1298
+ id: { type: 'string', description: '规划的编号(plan_…)' },
1299
+ topic: { type: 'string', description: '交给哪个已有的主题(主题编号)' },
1300
+ title: { type: 'string', description: '新开子主题时它的标题;不填用规划的标题' },
1301
+ member: { type: 'string', member: true, description: '叫谁来做;可覆盖安排中的成员' },
1302
+ }, ['id']),
1303
+ output: object({ ...planFields, woke: array(stringValue) }, [...requiredPlan, 'at', 'place', 'woke']), sdk: true,
1304
+ http: ['POST', '/api/plans/:id/start'], agent: true, tool: { server: 'plans', name: 'plan_start', plugin: 'plans' },
1305
+ run(args, caller) {
1306
+ let found = find(args.id);
1307
+ if (hasConsoleTarget(found.plan.acceptance) && syncConsoleVersion())
1308
+ found = find(args.id);
1309
+ const { topic: home, plan } = found;
1310
+ if (plan.state === 'doing')
1311
+ throw new Error(`已经在做了:在主题「${pathText(plan.at)}」(${plan.at})`);
1312
+ if (plan.state !== 'later')
1313
+ throw new Error(`这条已经${LABEL[plan.state]}。要重新做,先用 plans.set 把 state 改回 later`);
1314
+ if (plan.suspended)
1315
+ throw new Error('这条规划已暂挂,请先解除暂挂');
1316
+ const next = { ...plan, trail: [...plan.trail] };
1317
+ const { target, where, woke } = launch(home, next, caller, args);
1318
+ replace(home, plan, next);
1319
+ if (target.id !== home.id)
1320
+ tell(home, caller, `${nameOf(who(caller))} 开始做规划${planLink(plan)}:在主题 ${link(target.title, where ?? address.topic(target.id))}。`, where);
1321
+ return { ...view(home, next, undefined, who(caller)), woke };
1322
+ },
1323
+ text: (plan) => `开始了:「${plan.title}」(${plan.id})在主题「${plan.place.title}」(${plan.place.topicId})里做${plan.woke.length ? `,叫了 ${plan.woke.join('、')}` : ''}。`,
1324
+ });
1325
+ ctx.note('session.init', { title: '规划的基本原则:什么事要记、怎么流转和收口', when: '每段会话开头' });
1326
+ ctx.hook('session.init', () => [
1327
+ '延后要做的事,以及机主在对话里提出、当轮接下的代码、界面、配置或文档改动,接手时用规划工具带原消息出处登记;纯问答、闲聊、临时排查、已知限制、明说不做的和等人回答的问题不记。',
1328
+ '跨主题交办、等待复核或验收、暂缓、放弃与合入验收结项始终沿用原规划编号,具体参数与验收卡用法见各规划工具说明。',
1329
+ ].join('\n'));
1330
+ // Each turn of a member on a plan it follows here lists the acceptance items not passed yet.
1331
+ ctx.hook('turn.init', ({ topicId, member, append }) => {
1332
+ if (append)
1333
+ return undefined;
1334
+ const activePlans = () => [...(placesByBook ?? locateBooks())].flatMap(([id, places]) => {
1335
+ const home = places.has(topicId) ? topics.get(id) : undefined;
1336
+ if (!home || home.archivedAt !== null)
1337
+ return [];
1338
+ return bookOf(home).filter((plan) => plan.state === 'doing' && plan.at === topicId && !plan.suspended && assigneeOf(ctx.runtime, plan) === member.id);
1339
+ });
1340
+ let mine = activePlans();
1341
+ if (mine.some((plan) => hasConsoleTarget(plan.acceptance)) && syncConsoleVersion())
1342
+ mine = activePlans();
1343
+ const lines = mine.flatMap((plan) => {
1344
+ const open = unmet(plan.acceptance, running);
1345
+ return open.length ? [`「${plan.title}」(${plan.id})还有验收项没通过:`, ...open.map((item) => `- ${acceptanceLine(item, running)}`)] : [];
1346
+ });
1347
+ return lines.length ? lines.join('\n') : undefined;
1348
+ });
1349
+ // ── for topic context and memory ───────────────────────────────────────
1350
+ const entriesFor = (topicId, viewer, includeClosed = true) => {
1351
+ const topic = topics.get(topicId);
1352
+ if (!topic)
1353
+ return undefined;
1354
+ const entry = ({ topic: home, plan }) => {
1355
+ const seen = view(home, plan, undefined, viewer);
1356
+ const why = OPEN.includes(plan.state) ? undefined : seen.trail.findLast((step) => step.what === plan.state)?.why;
1357
+ return {
1358
+ id: plan.id, title: plan.title, address: planAddress(plan), sourceMessageId: sourceId(seen.from),
1359
+ sub: [
1360
+ `${LABEL[plan.state]}${why ? `(${why})` : ''}`, home.id !== topicId ? `记在「${home.title}」` : '', seen.place && seen.place.topicId !== topicId ? `在「${seen.place.title}」做` : '',
1361
+ `出处:${seen.source}`, `${nameOf(noted(plan).by)} 记的`, new Date(noted(plan).at).toLocaleString(),
1362
+ ].filter(Boolean).join(' · '),
1363
+ fallbackText: seen.messageSource?.url || seen.documentSource?.url ? '' : (seen.documentSource?.label ?? ''),
1364
+ };
1365
+ };
1366
+ const mine = [...(placesByBook ?? locateBooks())].flatMap(([id, places]) => {
1367
+ if (!places.has(topicId))
1368
+ return [];
1369
+ const home = topics.get(id);
1370
+ return bookOf(home).filter((plan) => id === topicId || plan.at === topicId).map((plan) => ({ topic: home, plan }));
1371
+ }).sort((a, b) => order(a.plan, b.plan));
1372
+ const open = mine.filter(({ plan }) => OPEN.includes(plan.state));
1373
+ const closed = mine.filter(({ plan }) => !OPEN.includes(plan.state));
1374
+ return {
1375
+ open: open.map(entry),
1376
+ closed: includeClosed ? closed.map(entry) : [],
1377
+ closedCount: closed.length,
1378
+ };
1379
+ };
1380
+ ctx.note('topic.context', { title: '当前未了结的规划清单,及已了结规划的数量提示', when: '成员查看主题说明或进入主题首轮时(已了结规划明细按需用 plan_list(closed: true) 查)' });
1381
+ ctx.hook('topic.context', ({ topicId, member }) => {
1382
+ const entries = entriesFor(topicId, member?.id, false);
1383
+ if (!entries)
1384
+ return undefined;
1385
+ const format = (title, rows) => `${title}:${rows.length ? `\n${rows.map((r) => `- ${r.title}(${r.id}):${r.sub}`).join('\n')}` : '(还没有)'}`;
1386
+ return [
1387
+ format('规划', entries.open),
1388
+ ...(entries.closedCount ? [`已了结的规划:${entries.closedCount} 条(需要时用 plan_list(topic: "${topicId}", closed: true) 查看)`] : []),
1389
+ ].join('\n');
1390
+ });
1391
+ ctx.hook('memory.sources', () => ({
1392
+ event: 'plans.changed',
1393
+ topics: () => new Set([...locateBooks().values()].flatMap((ids) => [...ids])),
1394
+ docs(topicId) {
1395
+ const entries = entriesFor(topicId);
1396
+ if (!entries)
1397
+ return [];
1398
+ const toDoc = (id, title, rows) => ({
1399
+ id, title,
1400
+ text: rows.map((row) => [row.title, row.sub, row.fallbackText].filter(Boolean).join(':')).join('\n'),
1401
+ rowIds: rows.map((row) => row.id),
1402
+ rowAddresses: Object.fromEntries(rows.map((row) => [row.id, row.address])),
1403
+ rowMessages: rows.flatMap((row) => row.sourceMessageId ? [row.sourceMessageId] : []),
1404
+ });
1405
+ return [
1406
+ ...(entries.open.length ? [toDoc('plans', '规划', entries.open)] : []),
1407
+ ...(entries.closed.length ? [toDoc('plans-closed', `了结的规划(${entries.closed.length} 条)`, entries.closed)] : []),
1408
+ ];
1409
+ },
1410
+ }));
1411
+ /**
1412
+ * A plan whose turn has come starts by itself, the way its arrangement says: noted, not held, every prerequisite done
1413
+ * and its time reached (at least one of the two given). It goes to the member its arrangement names, else the default
1414
+ * member of the topic it goes to; it waits for a free slot and enough quota to reach the reset. Everything is
1415
+ * checked again right before the handoff, against what is current then.
1416
+ */
1417
+ const autoStart = () => ({
1418
+ on: ext.config.get('autoStart') !== false,
1419
+ perMember: Number(ext.config.get('autoStartPerMember') ?? 3),
1420
+ quotaPercent: Number(ext.config.get('autoStartQuotaPercent') ?? 90),
1421
+ });
1422
+ const autoRules = { ready: '自动开工:前置规划都已完成', due: '自动开工:到了约定时间' };
1423
+ const autoBackoffMs = 60 * 60_000;
1424
+ const autoFailed = new Map(); // a start that failed waits an hour before it is tried again
1425
+ const autoQuotaWait = new Map(); // plans deferred to a quota recheck
1426
+ /** Wake for the earliest retry or quota reset, or soon while a receipt waits to be recorded. */
1427
+ const autoWake = () => {
1428
+ clearTimeout(autoClock);
1429
+ // Only plans still waiting for their turn keep a retry: a plan held, started, closed or gone leaves the queue.
1430
+ const waiting = new Set(everywhere().filter(({ topic, plan }) => topic.archivedAt === null && plan.state === 'later' && !plan.suspended && plan.dispatch).map(({ plan }) => plan.id));
1431
+ for (const id of autoFailed.keys())
1432
+ if (!waiting.has(id))
1433
+ autoFailed.delete(id);
1434
+ for (const id of autoQuotaWait.keys())
1435
+ if (!waiting.has(id))
1436
+ autoQuotaWait.delete(id);
1437
+ const due = [...autoFailed.values()].map((at) => at + autoBackoffMs).concat([...autoQuotaWait.values()].map((w) => w.until));
1438
+ if (receipts().length)
1439
+ due.push(Date.now() + 60_000);
1440
+ if (due.length)
1441
+ autoClock = setTimeout(() => void startReady(), Math.min(2 ** 31 - 1, Math.max(0, Math.min(...due) - Date.now()) + 1000)).unref();
1442
+ };
1443
+ /** Any change to a member or a credential since a quota read makes that read stale for the handoff. */
1444
+ let credentials = 0;
1445
+ const enabledAgents = new Set(members.list().filter((member) => member.kind === 'agent' && member.enabled).map((member) => member.id));
1446
+ ctx.on('members.changed', ({ id, removed }) => {
1447
+ credentials++;
1448
+ autoQuotaWait.clear();
1449
+ const member = removed ? undefined : members.get(id);
1450
+ const nowEnabled = !!member && member.kind === 'agent' && member.enabled;
1451
+ const reenabled = nowEnabled && !enabledAgents.has(id);
1452
+ if (nowEnabled)
1453
+ enabledAgents.add(id);
1454
+ else
1455
+ enabledAgents.delete(id);
1456
+ if (!hostHome.checkOnly && reenabled) {
1457
+ for (const { topic, plan } of everywhere()) {
1458
+ if (topic.archivedAt !== null || plan.state !== 'doing' || plan.suspended || plan.waiting?.on !== id || plan.reminder !== undefined)
1459
+ continue;
1460
+ void handleWaitingWake(plan.id, 'enabled');
1461
+ }
1462
+ void startReady();
1463
+ }
1464
+ });
1465
+ ctx.on('key.changed', () => {
1466
+ credentials++;
1467
+ autoQuotaWait.clear();
1468
+ if (!hostHome.checkOnly)
1469
+ void startReady();
1470
+ });
1471
+ let autoRunning = false, autoAgain = false, autoStopped = false, autoClock;
1472
+ ctx.effect(() => { autoStopped = true; clearTimeout(autoClock); });
1473
+ const autoMember = (home, dispatch) => dispatch.member
1474
+ ?? (dispatch.mode === 'existing' ? topics.get(dispatch.topic ?? '')?.defaultMember : topics.get(dispatch.parent ?? home.id)?.defaultMember)
1475
+ ?? undefined;
1476
+ /** The plan's turn, judged on what is current now: undefined when it should not start (yet). */
1477
+ const autoTurn = (id) => {
1478
+ const rules = autoStart();
1479
+ if (autoStopped || !rules.on)
1480
+ return undefined;
1481
+ const all = everywhere();
1482
+ const found = all.find(({ plan }) => plan.id === id);
1483
+ if (!found)
1484
+ return undefined;
1485
+ const { topic: home, plan } = found;
1486
+ if (home.archivedAt !== null || plan.state !== 'later' || plan.suspended || !plan.dispatch)
1487
+ return undefined;
1488
+ const failed = autoFailed.get(plan.id);
1489
+ if (failed !== undefined) {
1490
+ if (failed > Date.now() - autoBackoffMs)
1491
+ return undefined;
1492
+ autoFailed.delete(plan.id); // its hour is up and the scheduler has looked at it
1493
+ }
1494
+ if (receiptOf(plan))
1495
+ return undefined;
1496
+ const refs = planRefs(plan.dependencies ?? '');
1497
+ const done = new Set(all.filter((item) => item.plan.state === 'done').map((item) => item.plan.id));
1498
+ if (refs.some((ref) => !done.has(ref)))
1499
+ return undefined;
1500
+ const at = parseIsoTime(plan.when);
1501
+ if (at !== undefined && at > Date.now())
1502
+ return undefined;
1503
+ if (!refs.length && at === undefined)
1504
+ return undefined;
1505
+ const memberId = autoMember(home, plan.dispatch);
1506
+ const member = memberId ? members.get(memberId) : undefined;
1507
+ if (!member || member.kind !== 'agent' || !member.enabled)
1508
+ return undefined;
1509
+ if (ctx.runtime.has('memberHealth') && ctx.runtime.get('memberHealth').memberIssue(member.id, OWNER_ID))
1510
+ return undefined;
1511
+ // Work already handed to the member counts, recorded or still in a receipt.
1512
+ const working = all.filter((item) => item.plan.state === 'doing' && !item.plan.suspended && assigneeOf(ctx.runtime, item.plan) === member.id).length
1513
+ + receipts().filter((item) => item.step?.assignee === member.id && all.some(({ plan: p }) => p.id === item.plan && p.state !== 'doing')).length;
1514
+ if (working >= rules.perMember)
1515
+ return undefined;
1516
+ return { home, plan, memberId: member.id, rule: refs.length ? 'ready' : 'due', quotaPercent: rules.quotaPercent };
1517
+ };
1518
+ /** An automatic start supplies measured burn history. A declared wait uses the provider's reset directly. */
1519
+ async function quotaStatus(memberId, percent, readBurn) {
1520
+ const member = members.get(memberId);
1521
+ if (!member || member.kind !== 'agent')
1522
+ return { limited: false };
1523
+ try {
1524
+ const windows = await Promise.race([
1525
+ entry.invoke('members.adapter_quota', { name: member.adapter, member: member.id }),
1526
+ new Promise((_, reject) => setTimeout(() => reject(new Error('quota timeout')), 15_000).unref()),
1527
+ ]);
1528
+ if (!Array.isArray(windows))
1529
+ return { limited: false };
1530
+ const burn = readBurn && windows.some((w) => w.label && w.resetsAt && w.usedPercent !== undefined && w.usedPercent < 100)
1531
+ ? (await readBurn())?.accounts.find((account) => account.adapter === member.adapter && account.members.includes(member.id))?.windows
1532
+ : undefined;
1533
+ const now = Date.now();
1534
+ let limited = false;
1535
+ let retryAt;
1536
+ for (const window of windows) {
1537
+ const used = window.usedPercent;
1538
+ if (used === undefined)
1539
+ continue;
1540
+ const resetAt = window.resetsAt && Number.isFinite(window.resetsAt) && window.resetsAt > now ? window.resetsAt : undefined;
1541
+ const history = burn?.[window.label];
1542
+ const forecast = used < 100 && resetAt && history ? runsOutBeforeReset(used, resetAt, history, now) : undefined;
1543
+ if (!(forecast ?? (used >= (readBurn ? Math.min(100, percent) : percent))))
1544
+ continue;
1545
+ limited = true;
1546
+ if (resetAt) {
1547
+ const recheck = forecast === true ? Math.min(resetAt, now + autoBackoffMs) : resetAt;
1548
+ retryAt = Math.max(retryAt ?? 0, recheck);
1549
+ }
1550
+ }
1551
+ return { limited, retryAt };
1552
+ }
1553
+ catch (error) {
1554
+ // An adapter with no quota feature can still receive work. A failed provider probe is inconclusive.
1555
+ if (error instanceof HttpError && error.status === 404 && members.get(memberId)?.enabled)
1556
+ return { limited: false };
1557
+ return { limited: false, unknown: true };
1558
+ }
1559
+ }
1560
+ const pendingWaitQuota = new Set();
1561
+ function syncWaitingReset(planId, memberId, since) {
1562
+ if (hostHome.checkOnly || memberId === OWNER_ID)
1563
+ return;
1564
+ const member = members.get(memberId);
1565
+ if (!member || member.kind !== 'agent')
1566
+ return;
1567
+ const token = `${planId}:${since}`;
1568
+ if (pendingWaitQuota.has(token))
1569
+ return;
1570
+ pendingWaitQuota.add(token);
1571
+ void quotaStatus(memberId, autoStart().quotaPercent).then((status) => {
1572
+ if (autoStopped || !status.limited || !status.retryAt)
1573
+ return;
1574
+ const found = everywhere().find(({ plan }) => plan.id === planId);
1575
+ if (!found)
1576
+ return;
1577
+ const { topic: home, plan } = found;
1578
+ if (plan.state !== 'doing' || plan.suspended || !plan.waiting)
1579
+ return;
1580
+ if (plan.waiting.on !== memberId || plan.waiting.since !== since || plan.waiting.until !== undefined)
1581
+ return;
1582
+ replace(home, plan, { ...plan, waiting: { ...plan.waiting, until: status.retryAt } });
1583
+ }).catch((error) => {
1584
+ ctx.runtime.onError('plans waiting quota ' + planId, error);
1585
+ }).finally(() => {
1586
+ pendingWaitQuota.delete(token);
1587
+ });
1588
+ }
1589
+ const deliveryPlace = (plan, memberId) => {
1590
+ if (!members.get(memberId)?.enabled || !members.acceptsDelivery(memberId))
1591
+ return;
1592
+ const health = ctx.runtime.has('memberHealth') ? ctx.runtime.get('memberHealth') : undefined;
1593
+ if (!health?.memberIssue(memberId, OWNER_ID))
1594
+ return reminderPlace(ctx.runtime, plan, memberId);
1595
+ };
1596
+ const blockedWaits = blockedPlanWaits(ctx, everywhere);
1597
+ function returnUndelivered(planId, { fact, step }) {
1598
+ const receipt = a2a.returnBlockedHandoff(fact.id, step.by);
1599
+ if (!receipt)
1600
+ return;
1601
+ const current = everywhere().find(({ plan }) => plan.id === planId);
1602
+ if (!current || current.plan.suspended || current.plan.waiting?.since !== step.at || current.plan.waiting.on !== step.waitingOn)
1603
+ return;
1604
+ const assignee = assigneeOf(ctx.runtime, current.plan);
1605
+ const returned = assignee && messages.forMember(assignee).get(receipt.messageId);
1606
+ if (!assignee || !returned || returned.topicId !== receipt.topicId || !returned.to.includes(assignee))
1607
+ return;
1608
+ const { waiting, reminder, ...next } = current.plan;
1609
+ replace(current.topic, current.plan, { ...next, trail: [...next.trail, {
1610
+ what: 'continued', by: sender.id, at: Date.now(), where: address.message(returned.topicId, returned.id),
1611
+ why: '原交办尚未确认送达,已交还原跟进成员处理',
1612
+ }] });
1613
+ }
1614
+ function sendReminder(home, plan, input) {
1615
+ const step = { what: 'reminded', at: Date.now(), by: sender.id };
1616
+ const blocked = blockedWaits.forWait(plan);
1617
+ if (blocked) {
1618
+ const { fact, step: declared } = blocked, recipient = declared.waitingOn;
1619
+ let where = !fact.remaining.includes(recipient) ? receivedHandoff(ctx, fact, recipient) : undefined;
1620
+ if (!where) {
1621
+ if (fact.state !== 'pending' || !fact.remaining.includes(recipient) || blockedWaits.forEvent(fact)?.plan.id !== plan.id)
1622
+ return;
1623
+ if (!fact.canResume || fact.contacts?.[recipient]) {
1624
+ returnUndelivered(plan.id, blocked);
1625
+ return;
1626
+ }
1627
+ const request = { from: sender, viewerId: declared.by, memberId: recipient, content: input.content, visibility: input.visibility };
1628
+ const receipt = quietly(() => a2a.claimBlockedHandoff(fact.id, request));
1629
+ where = receipt && receivedHandoff(ctx, fact, recipient, receipt);
1630
+ if (!where) {
1631
+ returnUndelivered(plan.id, blocked);
1632
+ return;
1633
+ }
1634
+ }
1635
+ if (plan.reminder === where)
1636
+ return;
1637
+ step.where = where;
1638
+ const delivered = messages.forMember(recipient).get(where.split('/')[1]);
1639
+ step.by = delivered.from.id;
1640
+ step.at = delivered.createdAt;
1641
+ }
1642
+ else {
1643
+ try {
1644
+ const { message } = quietly(() => a2a.send({ ...input, from: sender, requireRecipient: true }));
1645
+ step.where = address.message(message.topicId, message.id);
1646
+ }
1647
+ catch (error) {
1648
+ step.why = errorText(error);
1649
+ ctx.runtime.onError('plans reminder ' + plan.id, error);
1650
+ }
1651
+ }
1652
+ const recorded = step.where && plan.trail.some((s) => s.what === 'reminded' && s.where === step.where);
1653
+ const trail = recorded ? plan.trail : [...plan.trail, step];
1654
+ if (!recorded && step.at < plan.trail.at(-1).at)
1655
+ trail.sort((a, b) => a.at - b.at);
1656
+ replace(home, plan, { ...plan, trail, reminder: step.where ?? null });
1657
+ }
1658
+ const handlingWait = new Set();
1659
+ async function handleWaitingWake(planId, mode) {
1660
+ if (autoStopped || handlingWait.has(planId))
1661
+ return;
1662
+ handlingWait.add(planId);
1663
+ try {
1664
+ const initial = everywhere().find(({ plan }) => plan.id === planId);
1665
+ if (!initial)
1666
+ return;
1667
+ const { plan: snap } = initial;
1668
+ if (snap.state !== 'doing' || snap.suspended || !snap.waiting || !snap.at)
1669
+ return;
1670
+ const { on, since, until } = snap.waiting;
1671
+ if (on === OWNER_ID || mode === 'blocked' && until !== undefined && until > Date.now())
1672
+ return;
1673
+ if (deliveryPlace(snap, on)) {
1674
+ const status = await quotaStatus(on, autoStart().quotaPercent);
1675
+ if (autoStopped)
1676
+ return;
1677
+ const fresh = everywhere().find(({ plan }) => plan.id === planId);
1678
+ if (!fresh)
1679
+ return;
1680
+ const { topic: home, plan } = fresh;
1681
+ if (plan.state !== 'doing' || plan.suspended || !plan.waiting || plan.waiting.on !== on || plan.waiting.since !== since || plan.waiting.until !== until || !plan.at)
1682
+ return;
1683
+ const evidence = blockedWaits.forWait(plan);
1684
+ if (mode === 'blocked' && !evidence)
1685
+ return;
1686
+ if (evidence && status.unknown) {
1687
+ returnUndelivered(plan.id, evidence);
1688
+ return;
1689
+ }
1690
+ const lastReminder = plan.reminder !== undefined ? plan.trail.findLast(({ what }) => what === 'reminded') : undefined;
1691
+ if (mode === 'due' && until !== undefined && lastReminder && lastReminder.at >= until)
1692
+ return;
1693
+ if (mode === 'enabled' && plan.reminder !== undefined)
1694
+ return;
1695
+ if (status.limited) {
1696
+ if (status.retryAt && status.retryAt > Date.now() + 5_000) {
1697
+ replace(home, plan, { ...plan, waiting: { ...plan.waiting, until: status.retryAt } });
1698
+ return;
1699
+ }
1700
+ if (mode === 'enabled')
1701
+ return;
1702
+ }
1703
+ else {
1704
+ const place = deliveryPlace(plan, on);
1705
+ if (place) {
1706
+ if (evidence && planProgress(ctx.runtime, [plan], attentionMs, Date.now(), on)(plan).answered) {
1707
+ blockedWaits.resolve(evidence);
1708
+ return;
1709
+ }
1710
+ const recipient = members.get(on);
1711
+ sendReminder(home, plan, planNudge(ctx.runtime, plan, recipient, plan.waiting.why, place));
1712
+ return;
1713
+ }
1714
+ }
1715
+ }
1716
+ if (mode === 'enabled')
1717
+ return;
1718
+ const fresh = everywhere().find(({ plan }) => plan.id === planId);
1719
+ if (!fresh)
1720
+ return;
1721
+ const { topic: home, plan } = fresh;
1722
+ if (plan.state !== 'doing' || plan.suspended || !plan.waiting || plan.waiting.on !== on || plan.waiting.since !== since || plan.waiting.until !== until || !plan.at)
1723
+ return;
1724
+ const blocked = blockedWaits.forWait(plan);
1725
+ if (blocked) {
1726
+ returnUndelivered(plan.id, blocked);
1727
+ return;
1728
+ }
1729
+ if (mode === 'blocked')
1730
+ return;
1731
+ const lastReminder = plan.reminder !== undefined ? plan.trail.findLast(({ what }) => what === 'reminded') : undefined;
1732
+ if (until !== undefined && lastReminder && lastReminder.at >= until)
1733
+ return;
1734
+ const assignee = assigneeOf(ctx.runtime, plan);
1735
+ const place = assignee && assignee !== on ? deliveryPlace(plan, assignee) : undefined;
1736
+ if (assignee && place) {
1737
+ const assigneeMember = members.get(assignee);
1738
+ const waitWhy = plan.waiting.why;
1739
+ const reason = `等 ${nameOf(on)} 已到期,对方当前仍不可用,交还 ${assigneeMember.name} 接续`;
1740
+ try {
1741
+ const { message } = quietly(() => a2a.send({
1742
+ ...place, from: sender, targets: [assignee], requireRecipient: true,
1743
+ content: i18n.render(ltext('plansAttention.waitReturn', {
1744
+ handle: assigneeMember.handle, name: nameOf(on), plan: '#' + planAddress(plan), why: waitWhy,
1745
+ })),
1746
+ }));
1747
+ const next = {
1748
+ ...plan,
1749
+ trail: [...plan.trail, { what: 'continued', at: Date.now(), by: sender.id, where: address.message(message.topicId, message.id), why: reason }],
1750
+ };
1751
+ delete next.waiting;
1752
+ delete next.reminder;
1753
+ replace(home, plan, next);
1754
+ return;
1755
+ }
1756
+ catch (error) {
1757
+ ctx.runtime.onError('plans waiting return ' + plan.id, error);
1758
+ }
1759
+ }
1760
+ const step = { what: 'reminded', at: Date.now(), by: sender.id, why: `等 ${nameOf(on)} 已到期,但对方与原跟进人均不可投递` };
1761
+ replace(home, plan, { ...plan, trail: [...plan.trail, step], reminder: null });
1762
+ }
1763
+ finally {
1764
+ handlingWait.delete(planId);
1765
+ }
1766
+ }
1767
+ const resumeHeld = (planId) => {
1768
+ const fresh = everywhere().find(({ plan }) => plan.id === planId);
1769
+ if (!fresh)
1770
+ return;
1771
+ const { topic: home, plan } = fresh;
1772
+ if (!plan.suspended || !plan.resumeAt)
1773
+ return;
1774
+ const at = parseIsoTime(plan.resumeAt);
1775
+ if (at === undefined || at > Date.now())
1776
+ return;
1777
+ const next = { ...plan, trail: [...plan.trail] };
1778
+ delete next.suspended;
1779
+ delete next.resumeAt;
1780
+ if (next.state === 'later' && parseIsoTime(next.when) === undefined)
1781
+ next.when = plan.resumeAt;
1782
+ const step = { what: 'resumed', at: Date.now(), by: sender.id, why: '到达预定恢复时间,自动解除暂挂' };
1783
+ if (next.state === 'doing' && !next.waiting && next.at) {
1784
+ const work = topics.get(next.at);
1785
+ const assignee = assigneeOf(ctx.runtime, next);
1786
+ const place = assignee ? deliveryPlace(next, assignee) : undefined;
1787
+ if (work && assignee && place) {
1788
+ try {
1789
+ const recipient = members.get(assignee);
1790
+ const { message } = quietly(() => a2a.send({
1791
+ ...place, from: sender, targets: [assignee], requireRecipient: true,
1792
+ content: i18n.render(ltext('plansAttention.resumeDue', { handle: recipient.handle, plan: '#' + planAddress(next) })),
1793
+ }));
1794
+ step.where = address.message(message.topicId, message.id);
1795
+ }
1796
+ catch (error) {
1797
+ ctx.runtime.onError('plans auto resume ' + next.id, error);
1798
+ }
1799
+ }
1800
+ }
1801
+ next.trail.push(step);
1802
+ replace(home, plan, next);
1803
+ };
1804
+ /** One pass over the noted plans with an arrangement. A change that comes during a pass is read in one more pass after it. */
1805
+ async function startReady() {
1806
+ if (autoRunning) {
1807
+ autoAgain = true;
1808
+ return;
1809
+ }
1810
+ autoRunning = true;
1811
+ try {
1812
+ do {
1813
+ autoAgain = false;
1814
+ let burn;
1815
+ const readBurn = () => {
1816
+ if (burn?.atCredentials !== credentials) {
1817
+ const result = entry.invoke('keys.quota_burn', { includeUsage: false }).catch(() => undefined);
1818
+ burn = { atCredentials: credentials, result };
1819
+ }
1820
+ return burn.result;
1821
+ };
1822
+ const ids = everywhere().filter(({ plan }) => plan.state === 'later' && plan.dispatch && !plan.suspended)
1823
+ .sort((a, b) => a.plan.trail[0].at - b.plan.trail[0].at).map(({ plan }) => plan.id);
1824
+ // Handoffs that went out but were not recorded: record them first, whoever started them.
1825
+ for (const receipt of receipts()) {
1826
+ const current = everywhere().find(({ plan }) => plan.id === receipt.plan);
1827
+ if (!current) {
1828
+ dropReceipt(receipt.plan);
1829
+ continue;
1830
+ }
1831
+ try {
1832
+ const sent = pendingStart(current.plan);
1833
+ if (!sent || !topics.get(sent.at))
1834
+ continue;
1835
+ const next = { ...current.plan, trail: [...current.plan.trail] };
1836
+ recordStart(next, sent);
1837
+ replace(current.topic, current.plan, next);
1838
+ }
1839
+ catch (error) {
1840
+ ctx.runtime.onError('plans auto start record ' + receipt.plan, error);
1841
+ }
1842
+ }
1843
+ for (const id of ids) {
1844
+ const turn = autoTurn(id);
1845
+ if (!turn)
1846
+ continue;
1847
+ const quotaWait = autoQuotaWait.get(id);
1848
+ if (quotaWait && quotaWait.memberId === turn.memberId && quotaWait.until > Date.now())
1849
+ continue;
1850
+ const read = credentials;
1851
+ // A credential that does not resolve now (a client account signed out) keeps this plan queued; others go on.
1852
+ const key = members.get(turn.memberId)?.key;
1853
+ if (key) {
1854
+ try {
1855
+ await ctx.runtime.serial('key.resolve', { id: key });
1856
+ }
1857
+ catch {
1858
+ continue;
1859
+ }
1860
+ }
1861
+ const quota = await quotaStatus(turn.memberId, turn.quotaPercent, readBurn);
1862
+ // A changed credential invalidates a queue decision as well as permission to hand off.
1863
+ if (credentials !== read) {
1864
+ autoAgain = true;
1865
+ continue;
1866
+ }
1867
+ if (quota.limited) {
1868
+ autoQuotaWait.set(id, { until: quota.retryAt ?? Date.now() + autoBackoffMs, memberId: turn.memberId });
1869
+ autoWake();
1870
+ continue;
1871
+ }
1872
+ autoQuotaWait.delete(id);
1873
+ // Nothing is awaited from here to the handoff: judge on what is current now, and hand off that version.
1874
+ const now = autoTurn(id);
1875
+ if (!now || now.memberId !== turn.memberId)
1876
+ continue;
1877
+ let next;
1878
+ let handed;
1879
+ try {
1880
+ next = { ...now.plan, trail: [...now.plan.trail] };
1881
+ handed = launch(now.home, next, {}, { member: now.memberId }, sender, { by: sender.id, why: autoRules[now.rule] });
1882
+ }
1883
+ catch (error) {
1884
+ autoFailed.set(id, Date.now());
1885
+ autoWake();
1886
+ ctx.runtime.onError('plans auto start ' + id, error);
1887
+ continue;
1888
+ }
1889
+ try {
1890
+ replace(now.home, now.plan, next);
1891
+ }
1892
+ catch (error) {
1893
+ // Sent, not recorded: the receipt stays, and the next pass (or any start) records it.
1894
+ autoWake();
1895
+ ctx.runtime.onError('plans auto start record ' + id, error);
1896
+ continue;
1897
+ }
1898
+ const { target, where } = handed;
1899
+ if (target.id !== now.home.id) {
1900
+ quietly(() => messages.publish({ topicId: now.home.id, from: sender, threadable: false,
1901
+ content: `${autoRules[now.rule]},规划${planLink(now.plan)}交给主题 ${link(target.title, where ?? address.topic(target.id))}。` }));
1902
+ }
1903
+ }
1904
+ } while (autoAgain && !autoStopped);
1905
+ }
1906
+ finally {
1907
+ autoRunning = false;
1908
+ if (!autoStopped)
1909
+ autoWake();
1910
+ }
1911
+ }
1912
+ // A deployment item passed on another version than its target runs now does not hold for a plan still open: it goes
1913
+ // back to pending. Checked once the running versions are read, and again whenever a plugin changes.
1914
+ function resetStale() {
1915
+ const books = [];
1916
+ for (const topic of topics.list()) {
1917
+ let changed = false;
1918
+ const items = bookOf(topic).map((plan) => {
1919
+ if (plan.state === 'done' || plan.state === 'dropped')
1920
+ return plan;
1921
+ const stale = staleChecks(plan.acceptance, running);
1922
+ if (!stale.length)
1923
+ return plan;
1924
+ changed = true;
1925
+ const ids = new Set(stale.map((item) => item.id));
1926
+ return {
1927
+ ...plan,
1928
+ acceptance: plan.acceptance.map((item) => ids.has(item.id) ? { ...item, state: 'pending' } : item),
1929
+ trail: [...plan.trail, ...stale.map((item) => ({ at: Date.now(), by: sender.id, what: 'checked',
1930
+ why: `${targetText(item.target)} 现在运行的版本是 ${(item.target.plugin ? running.plugins[item.target.plugin] : running.commit) ?? '未知'},与验收时(${item.checked?.plugin ?? item.checked?.commit ?? '未知'})不同,退回待验:${acceptanceLine({ ...item, state: 'pending' })}` }))],
1931
+ };
1932
+ });
1933
+ if (changed)
1934
+ books.push([topic, items]);
1935
+ }
1936
+ if (books.length) {
1937
+ try {
1938
+ save(books);
1939
+ }
1940
+ catch (error) {
1941
+ ctx.runtime.onError('plans acceptance reset', error);
1942
+ }
1943
+ }
1944
+ }
1945
+ if (!hostHome.checkOnly) {
1946
+ const refresh = (event) => {
1947
+ const consoleReloaded = event?.name === CONSOLE_PLUGIN && event.kind !== 'configured';
1948
+ reading = reading.then(() => readRunning(consoleReloaded)).then(() => {
1949
+ if (cardsStopped)
1950
+ return;
1951
+ resetStale();
1952
+ versionsRead = true;
1953
+ queueAcceptanceCards((placesByBook ?? locateBooks()).keys());
1954
+ });
1955
+ return reading;
1956
+ };
1957
+ if (ctx.runtime.ready)
1958
+ refresh();
1959
+ else
1960
+ ctx.hook('host.ready', () => refresh());
1961
+ ctx.on('plugin.changed', (event) => refresh(event));
1962
+ }
1963
+ if (!hostHome.checkOnly && receipts().length)
1964
+ setTimeout(() => void startReady(), 0).unref();
1965
+ // Holds belong to the durable transport record. Only the active observations are kept here for changes to a plan.
1966
+ const heldHandoffs = new Map();
1967
+ const observeBlocked = (event) => {
1968
+ const match = blockedWaits.forEvent(event);
1969
+ if (!match)
1970
+ return false;
1971
+ const { plan, step, fact } = match, on = step.waitingOn;
1972
+ if (fact.state !== 'pending' || !fact.remaining.includes(on))
1973
+ return false;
1974
+ const active = plan.state === 'doing' && plan.waiting?.since === step.at && plan.waiting.on === on;
1975
+ if (!active) {
1976
+ // An old approval, assignment or completed job cannot be revived by replaying its event.
1977
+ blockedWaits.resolve(match);
1978
+ return false;
1979
+ }
1980
+ heldHandoffs.set(fact.id, { id: fact.id, sourceTopicId: fact.sourceTopicId, viewer: step.by });
1981
+ if (plan.suspended || on === OWNER_ID || plan.waiting.until !== undefined && plan.waiting.until > Date.now()) {
1982
+ return true;
1983
+ }
1984
+ if (!fact.canResume || fact.contacts?.[on] || !deliveryPlace(plan, on)) {
1985
+ returnUndelivered(plan.id, match);
1986
+ return false;
1987
+ }
1988
+ const prior = plan.reminder && receivedHandoff(ctx, fact, on, {
1989
+ topicId: requestTopic(plan.reminder), messageId: plan.reminder.split('/')[1],
1990
+ });
1991
+ if (prior) {
1992
+ const original = messages.forMember(on).get(prior.split('/')[1]);
1993
+ if (original?.from.id === sender.id && original.content.includes('#' + step.where)) {
1994
+ blockedWaits.resolve(match);
1995
+ return false;
1996
+ }
1997
+ }
1998
+ if (planProgress(ctx.runtime, [plan], attentionMs, Date.now(), on)(plan).answered) {
1999
+ blockedWaits.resolve(match);
2000
+ return false;
2001
+ }
2002
+ void handleWaitingWake(plan.id, 'blocked').catch((error) => {
2003
+ ctx.runtime.onError('plans blocked handoff ' + plan.id, error);
2004
+ returnUndelivered(plan.id, match);
2005
+ });
2006
+ return true;
2007
+ };
2008
+ if (!hostHome.checkOnly) {
2009
+ ctx.on('a2a.handoffBlocked', (event) => {
2010
+ if (observeBlocked(event))
2011
+ event.hold();
2012
+ else
2013
+ heldHandoffs.delete(event.id);
2014
+ });
2015
+ ctx.on('plans.changed', () => {
2016
+ for (const held of heldHandoffs.values()) {
2017
+ if (observeBlocked(held))
2018
+ continue;
2019
+ heldHandoffs.delete(held.id);
2020
+ const pending = a2a.blockedHandoffs(held.sourceTopicId, held.viewer).some((h) => h.id === held.id && h.state === 'pending');
2021
+ if (pending)
2022
+ a2a.returnBlockedHandoff(held.id, held.viewer);
2023
+ }
2024
+ });
2025
+ }
2026
+ if (!hostHome.checkOnly)
2027
+ watchPlanProgress(ctx, sender, everywhere, planLink, attentionMs, {
2028
+ ready() { void startReady(); },
2029
+ resume(_home, plan) { resumeHeld(plan.id); },
2030
+ waitDue(_home, plan) { void handleWaitingWake(plan.id, 'due'); },
2031
+ hasSeparateNotice(plan) {
2032
+ if (acceptancePart(messages.get(acceptancePlace(plan)?.split('/')[1] ?? ''))?.state === 'pending')
2033
+ return true;
2034
+ const state = blockedWaits.forWait(plan)?.fact.state;
2035
+ return state === 'escalated' || state === 'returned';
2036
+ },
2037
+ remind(home, plan, input) {
2038
+ if (blockedWaits.forWait(plan))
2039
+ void handleWaitingWake(plan.id, 'blocked');
2040
+ else
2041
+ sendReminder(home, plan, input);
2042
+ },
2043
+ answered(home, plan, reply) {
2044
+ const blocked = blockedWaits.forWait(plan);
2045
+ if (blocked)
2046
+ blockedWaits.resolve(blocked);
2047
+ const next = { ...plan, trail: [...plan.trail, {
2048
+ what: 'continued', at: reply.createdAt, by: reply.from.id, where: address.message(reply.topicId, reply.id),
2049
+ }] };
2050
+ delete next.waiting;
2051
+ delete next.reminder;
2052
+ replace(home, plan, next);
2053
+ },
2054
+ });
2055
+ },
2056
+ });
2057
+ export default plansPlugin;