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,2197 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { rmSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { address } from "./address.js";
5
+ import { MAX_ATTACHMENT_BYTES } from "./attachments.js";
6
+ import { blockedHandoffs } from "./blocked-handoffs.js";
7
+ import { configOwnership } from "./config.js";
8
+ import { ArgsError, HttpError } from "./entry.js";
9
+ import { ljoin, ltext } from "./i18n.js";
10
+ import { OWNER_ID } from "./members.js";
11
+ import { findMentions, stripMentionMarks } from "./mentions.js";
12
+ import { deletedReferences, messageOutput, messagePreview, messagesOut, relayBrief, visibleInTurn, visibleTo, withDeletedRefs } from "./messages.js";
13
+ import { array, object } from "./ops.js";
14
+ import { cleanExternalText, cleanIncomingParts, foldEvent, stepSummary, textOf, withExcerpts } from "./parts.js";
15
+ import { draftSchema, requireTopic } from "./topics.js";
16
+ import { turnClientsSchema } from "./turn-clients.js";
17
+ import { TurnFailureError, partsSchema, senderSchema, usageSchema } from "./types.js";
18
+ import { errorText, log, newId } from "./util.js";
19
+ const stringValue = { type: 'string' };
20
+ const numberValue = { type: 'number' };
21
+ const booleanValue = { type: 'boolean' };
22
+ const strings = array(stringValue);
23
+ const channelStateOutput = object({
24
+ live: array(object({
25
+ turnId: stringValue, topicId: stringValue, memberId: stringValue, messageId: stringValue,
26
+ origin: { type: 'string', enum: ['host', 'self'] }, depth: numberValue, parts: partsSchema, startedAt: numberValue,
27
+ replyTo: stringValue, thread: stringValue, seq: numberValue, priorParts: numberValue, ...deletedReferences,
28
+ read: strings, dispatchedAt: numberValue, model: stringValue, stopping: booleanValue,
29
+ usage: usageSchema,
30
+ }, ['turnId', 'topicId', 'memberId', 'messageId', 'origin', 'depth', 'parts', 'startedAt', 'read'])),
31
+ unread: array(object({ messageId: stringValue, memberId: stringValue, from: senderSchema, deferred: booleanValue }, ['messageId', 'memberId', 'from'])),
32
+ queuedRetries: array(object({
33
+ topicId: stringValue, memberId: stringValue, replyId: stringValue, turnId: stringValue,
34
+ waitingOnTurnId: { type: ['string', 'null'] }, queuedAt: numberValue,
35
+ }, ['topicId', 'memberId', 'replyId', 'turnId', 'waitingOnTurnId', 'queuedAt'])),
36
+ messages: array(messageOutput), through: numberValue, turns: array({ type: 'object' }),
37
+ }, ['live', 'unread', 'queuedRetries']);
38
+ function turnPreview({ inputText, trace, silent, ...turn }, detail = false) {
39
+ const output = silent || trace;
40
+ return {
41
+ ...turn,
42
+ inputPreview: inputText.slice(0, 240),
43
+ ...(detail ? { trace, silent } : output ? {
44
+ preview: { content: textOf(output.parts).slice(0, 120), steps: stepSummary(output.parts), silent: !!silent },
45
+ } : {}),
46
+ };
47
+ }
48
+ const NO_REPLY = 'NO_REPLY';
49
+ function sameVisibility(a, b) {
50
+ return (a ?? 'all') === (b ?? 'all') || (Array.isArray(a) && Array.isArray(b)
51
+ && a.every((id) => b.includes(id)) && b.every((id) => a.includes(id)));
52
+ }
53
+ const opensFloor = (message) => message.threadable ?? message.from.kind === 'member';
54
+ const floorOf = (message) => message.thread ?? (opensFloor(message) ? message.id : undefined);
55
+ /** How much room, in Unicode characters, the bystander background of one turn may take. */
56
+ const BACKGROUND_BUDGET = 6000;
57
+ function paragraphEnd(text, from) {
58
+ let end = text.lastIndexOf('\n');
59
+ while (end >= from && end > 0) {
60
+ const previous = text.lastIndexOf('\n', end - 1);
61
+ if (previous < 0)
62
+ break;
63
+ if (!text.slice(previous + 1, end).trim())
64
+ return end + 1;
65
+ end = previous;
66
+ }
67
+ return 0;
68
+ }
69
+ export const a2aPlugin = {
70
+ name: 'a2a',
71
+ core: true,
72
+ needs: ['store', 'config', 'members', 'topics', 'messages', 'instances', 'notices', 'push', 'entry'],
73
+ start(ctx) {
74
+ const store = ctx.get('store');
75
+ const { db } = store;
76
+ const config = configOwnership(ctx.get('config'));
77
+ const members = ctx.get('members');
78
+ const topics = ctx.get('topics');
79
+ const messages = ctx.get('messages');
80
+ const instances = ctx.get('instances');
81
+ const notices = ctx.get('notices');
82
+ const push = ctx.get('push');
83
+ db.exec(`
84
+ CREATE TABLE IF NOT EXISTS a2a_sent (message_id TEXT PRIMARY KEY, depth INTEGER NOT NULL);
85
+ CREATE TABLE IF NOT EXISTS a2a_turns (
86
+ id TEXT PRIMARY KEY, topic_id TEXT NOT NULL, member_id TEXT NOT NULL, status TEXT NOT NULL, origin TEXT NOT NULL,
87
+ reply_id TEXT NOT NULL, input_text TEXT NOT NULL DEFAULT '', usage TEXT, error TEXT, depth INTEGER NOT NULL DEFAULT 0,
88
+ started_at INTEGER NOT NULL, ended_at INTEGER, dispatched_at INTEGER, session_id TEXT, model TEXT, trace TEXT
89
+ );
90
+ CREATE INDEX IF NOT EXISTS a2a_turns_topic ON a2a_turns (topic_id, started_at);
91
+ CREATE INDEX IF NOT EXISTS a2a_turns_ended ON a2a_turns (ended_at) WHERE ended_at IS NOT NULL;
92
+ ${turnClientsSchema}
93
+ CREATE TABLE IF NOT EXISTS a2a_cursors (
94
+ topic_id TEXT NOT NULL, member_id TEXT NOT NULL, seq INTEGER NOT NULL, PRIMARY KEY (topic_id, member_id)
95
+ );
96
+ CREATE TABLE IF NOT EXISTS a2a_addressed (
97
+ topic_id TEXT NOT NULL, message_id TEXT NOT NULL, member_id TEXT NOT NULL, seq INTEGER NOT NULL, read_at INTEGER,
98
+ PRIMARY KEY (message_id, member_id)
99
+ );
100
+ CREATE INDEX IF NOT EXISTS a2a_addressed_unread ON a2a_addressed (member_id, topic_id) WHERE read_at IS NULL;
101
+ CREATE TABLE IF NOT EXISTS a2a_delivery_grants (
102
+ credential TEXT PRIMARY KEY, topic_id TEXT NOT NULL, message_id TEXT NOT NULL,
103
+ member_id TEXT NOT NULL, reply_id TEXT NOT NULL, UNIQUE (message_id, member_id)
104
+ );
105
+ `);
106
+ const saveTurnModel = db.prepare('UPDATE a2a_turns SET model = ? WHERE id = ?');
107
+ const saveTurnClient = db.prepare('INSERT INTO a2a_turn_clients (turn_id, client) VALUES (?, ?)');
108
+ for (const declaration of [
109
+ { key: 'chat.floorFoldAt', kind: 'number', default: 6, minimum: 2, maximum: 100, unit: 'items', presets: [3, 4, 6, 8, 10, 15, 20], section: 'general', label: { default: '楼内回复折叠条数', translations: { zh: '楼内回复折叠条数', en: 'Fold floors at' } }, description: { default: '打开主题时,一栋楼的回复达到这个条数就折叠中间部分。看着主题时新来的回复不会让楼折叠。', translations: { zh: '打开主题时,一栋楼的回复达到这个条数就折叠中间部分。看着主题时新来的回复不会让楼折叠。', en: 'When a topic opens, a floor with at least this many replies folds its middle. Replies that arrive while you are reading never fold it.' } } },
110
+ { key: 'chat.floorTail', kind: 'number', default: 3, minimum: 1, maximum: 50, unit: 'items', presets: [1, 2, 3, 5, 8], section: 'general', label: { default: '折叠后保留最新回复', translations: { zh: '折叠后保留最新回复', en: 'Replies kept when folded' } }, description: { default: '楼折叠后,楼主下面仍然显示的最新回复条数。', translations: { zh: '楼折叠后,楼主下面仍然显示的最新回复条数。', en: 'How many of the newest replies stay visible under a folded floor head.' } } },
111
+ { key: 'a2a.recent', kind: 'number', default: 20, minimum: 0, maximum: 200, unit: 'items', presets: [0, 5, 10, 20, 30, 50, 100], section: 'runtime', label: { default: '新会话附带消息', translations: { zh: '新会话附带消息', en: 'Recent context messages' } }, description: { default: '新进主题或交接后重开会话时,默认带给成员的最近消息条数。', translations: { zh: '新进主题或交接后重开会话时,默认带给成员的最近消息条数。', en: 'Number of recent messages included in the first turn of a new session.' } } },
112
+ { key: 'a2a.maxDepth', kind: 'number', default: 10, minimum: 0, maximum: 50, unit: 'levels', presets: [0, 3, 5, 10, 15, 20, 30], section: 'runtime', label: { default: '成员接力上限', translations: { zh: '成员接力上限', en: 'Max member relay depth' } }, description: { default: '成员之间连续 @ 接力的最大深度;找人不受此限制。', translations: { zh: '成员之间连续 @ 接力的最大深度;找人不受此限制。', en: 'Maximum relay depth between members; mentioning the owner is not limited.' } } },
113
+ { key: 'a2a.defaultMember', kind: 'member', default: '', section: 'members', label: { default: '默认回复成员', translations: { zh: '默认回复成员', en: 'Default member' } }, description: { default: '新主题里没有指定成员时默认回复的成员。', translations: { zh: '新主题里没有指定成员时默认回复的成员。', en: 'Default member that replies when a new topic does not mention anyone.' } } },
114
+ ])
115
+ ctx.effect(config.declare({ scope: 'settings', owner: 'core', fields: [declaration] }));
116
+ const independent = Symbol('independent replies');
117
+ const textMessage = Symbol('current client text message');
118
+ const configuredModel = Symbol('configured model');
119
+ const replyVisibility = Symbol('reply visibility');
120
+ const priorReply = Symbol('prior reply');
121
+ const revisedReply = Symbol('revised reply');
122
+ const sources = Symbol('input sources');
123
+ const deferred = Symbol('deferred messages');
124
+ const deliveredFloor = Symbol('delivered floor seq');
125
+ const running = new Map();
126
+ const preparedFloorDelivery = new WeakMap();
127
+ const idleWaiters = new Map();
128
+ const waking = new Set();
129
+ const dirty = new Set();
130
+ const key = (topicId, memberId) => `${topicId}:${memberId}`;
131
+ const interrupted = new Map();
132
+ const retryQueue = new Map();
133
+ /** How many hand-overs from member to member led to a message (0 for what a person or a plugin said). */
134
+ const depthOf = (messageId) => db.prepare('SELECT depth FROM a2a_sent WHERE message_id = ?').get(messageId)?.depth ?? 0;
135
+ const setDepth = (messageId, depth) => {
136
+ if (depth > 0)
137
+ db.prepare('INSERT OR REPLACE INTO a2a_sent (message_id, depth) VALUES (?, ?)').run(messageId, depth);
138
+ };
139
+ const selectCursor = db.prepare('SELECT seq FROM a2a_cursors WHERE topic_id = ? AND member_id = ?');
140
+ const selectCursors = db.prepare('SELECT topic_id, seq FROM a2a_cursors WHERE member_id = ?');
141
+ const cursorOf = (topicId, memberId) => selectCursor.get(topicId, memberId)?.seq ?? 0;
142
+ const positions = (rows) => new Map(rows.map(({ topic_id, seq }) => [topic_id, seq]));
143
+ const selectSomeCursors = db.prepare('SELECT topic_id, seq FROM a2a_cursors WHERE member_id = ? AND topic_id IN (SELECT value FROM json_each(?))');
144
+ const cursorsOf = (memberId, ids) => positions((ids ? selectSomeCursors.all(memberId, JSON.stringify([...ids])) : selectCursors.all(memberId)));
145
+ const unreadCounts = (memberId, ids) => messages.countsAfter(cursorsOf(memberId, ids), memberId, ids);
146
+ const seedCursor = db.prepare('INSERT INTO a2a_cursors (topic_id, member_id, seq) VALUES (?, ?, ?) ON CONFLICT DO NOTHING');
147
+ const advanceCursor = db.prepare(`INSERT INTO a2a_cursors (topic_id, member_id, seq) VALUES (?, ?, ?)
148
+ ON CONFLICT(topic_id, member_id) DO UPDATE SET seq = MAX(a2a_cursors.seq, excluded.seq)`);
149
+ const setCursor = (topicId, memberId, seq) => {
150
+ advanceCursor.run(topicId, memberId, seq);
151
+ };
152
+ const unreadCount = (topicId, memberId) => messages.countAfter(topicId, cursorOf(topicId, memberId), memberId);
153
+ ctx.effect(push.forward('channel.updated'));
154
+ const channelUpdated = (topicId) => {
155
+ const ownerUnread = unreadCount(topicId, OWNER_ID);
156
+ ctx.runtime.emit('channel.updated', { topicId, ownerUnread });
157
+ topics.status.set('unread', topicId, ownerUnread);
158
+ };
159
+ const queuedRetry = (request, viewerId) => {
160
+ const active = running.get(key(request.topicId, request.memberId));
161
+ return { ...request, waitingOnTurnId: active && visibleTo(active[replyVisibility], viewerId) ? active.turnId : null };
162
+ };
163
+ const removeQueuedRetries = (discard) => {
164
+ const changed = new Set();
165
+ for (const [pair, queue] of retryQueue) {
166
+ const remaining = queue.filter((request) => !discard(request));
167
+ if (remaining.length === queue.length)
168
+ continue;
169
+ changed.add(queue[0].topicId);
170
+ if (remaining.length)
171
+ retryQueue.set(pair, remaining);
172
+ else
173
+ retryQueue.delete(pair);
174
+ }
175
+ return changed;
176
+ };
177
+ const readTurnSummary = (row) => ({
178
+ id: row.id,
179
+ status: row.status === 'interrupted' ? 'failed' : row.status,
180
+ replyId: row.reply_id,
181
+ error: row.error,
182
+ startedAt: row.started_at,
183
+ endedAt: row.ended_at,
184
+ sessionId: row.session_id,
185
+ });
186
+ const readUsage = (row) => {
187
+ const saved = row.usage ? JSON.parse(row.usage) : null;
188
+ if (!saved)
189
+ return null;
190
+ const { _inputFormat, ...usage } = saved;
191
+ return usage;
192
+ };
193
+ const settledBills = db.prepare(`SELECT t.id, t.topic_id, t.member_id, t.session_id,
194
+ COALESCE(t.model, json_extract(t.usage, '$.model')) AS model,
195
+ t.status, t.reply_id, t.started_at, t.ended_at, t.usage,
196
+ json_extract(t.trace, '$.failure') AS trace_failure,
197
+ json_extract(t.trace, '$.modelMismatch') AS trace_model_mismatch,
198
+ c.client
199
+ FROM a2a_turns t LEFT JOIN a2a_turn_clients c ON c.turn_id = t.id
200
+ WHERE t.ended_at >= ? AND t.ended_at < ?`);
201
+ const latestMemberModel = db.prepare(`SELECT id, COALESCE(model, json_extract(usage, '$.model')) AS model,
202
+ COALESCE(ended_at, started_at) AS at
203
+ FROM a2a_turns
204
+ WHERE member_id = ? AND COALESCE(model, json_extract(usage, '$.model')) IS NOT NULL
205
+ AND COALESCE(model, json_extract(usage, '$.model')) != ''
206
+ ORDER BY started_at DESC, rowid DESC LIMIT 1`);
207
+ const modelOfTurn = db.prepare(`SELECT COALESCE(model, json_extract(usage, '$.model')) AS model FROM a2a_turns WHERE id = ?`);
208
+ const readTrace = (row) => JSON.parse(row.trace);
209
+ const saveTrace = db.prepare('UPDATE a2a_turns SET trace = ? WHERE id = ?');
210
+ const turnById = db.prepare('SELECT * FROM a2a_turns WHERE id = ?');
211
+ const turnInput = db.prepare('SELECT input_text FROM a2a_turns WHERE topic_id = ? AND id = ?');
212
+ const latestTurn = db.prepare('SELECT id FROM a2a_turns WHERE topic_id = ? AND member_id = ? ORDER BY started_at DESC, rowid DESC LIMIT 1');
213
+ const replyModels = db.prepare(`
214
+ SELECT t.id, t.reply_id, COALESCE(t.model, json_extract(t.usage, '$.model')) AS model,
215
+ json_extract(t.trace, '$.modelMismatch') AS model_mismatch
216
+ FROM json_each(?) AS wanted JOIN a2a_turns AS t ON t.id = wanted.value
217
+ `);
218
+ const withReplyModels = (items) => {
219
+ const ids = items.flatMap(({ turnId }) => turnId ? [turnId] : []);
220
+ if (!ids.length)
221
+ return items;
222
+ const rows = replyModels.all(JSON.stringify([...new Set(ids)]));
223
+ const byTurn = new Map(rows.map((row) => [row.id, row]));
224
+ return items.map((message) => {
225
+ const row = byTurn.get(message.turnId ?? '');
226
+ if (!row || row.reply_id !== message.id || typeof row.model !== 'string' || !row.model)
227
+ return message;
228
+ return { ...message, model: row.model, ...(row.model_mismatch ? { modelMismatch: row.model_mismatch } : {}) };
229
+ });
230
+ };
231
+ const pendingText = { type: 'text', text: '' };
232
+ const pendingFrom = (live) => {
233
+ const message = live[textMessage];
234
+ return message?.prefix === undefined ? undefined : message.start;
235
+ };
236
+ const publishedParts = (live, parts = live.parts) => {
237
+ const from = pendingFrom(live);
238
+ // Keep the same part positions in snapshots and the stream, even when tools split a candidate.
239
+ return from === undefined ? parts : parts.map((part, i) => i >= from && part.type === 'text' ? pendingText : part);
240
+ };
241
+ const readTurnTrace = (row, saved) => {
242
+ const { failure, modelMismatch, delivered: _delivered, ...trace } = saved;
243
+ const live = row.status === 'running' ? running.get(key(row.topic_id, row.member_id)) : undefined;
244
+ if (live?.turnId === row.id)
245
+ trace.parts = publishedParts(live, trace.parts);
246
+ const reply = messages.storedRouting(row.reply_id);
247
+ return {
248
+ ...readTurnSummary(row),
249
+ ...(failure ? { failure } : {}),
250
+ ...(modelMismatch ? { modelMismatch } : {}),
251
+ topicId: row.topic_id,
252
+ memberId: row.member_id,
253
+ origin: row.origin,
254
+ inputText: row.input_text,
255
+ model: row.model,
256
+ usage: readUsage(row),
257
+ depth: row.depth,
258
+ dispatchedAt: row.dispatched_at,
259
+ ...(reply ? { trace } : { silent: trace }),
260
+ };
261
+ };
262
+ const readTurn = (row) => readTurnTrace(row, readTrace(row));
263
+ const readTurnPreview = (row) => readTurnTrace(row, {
264
+ parts: JSON.parse(row.preview_parts),
265
+ read: JSON.parse(row.trace_read),
266
+ ...(row.trace_failure ? { failure: row.trace_failure } : {}),
267
+ ...(row.trace_model_mismatch ? { modelMismatch: row.trace_model_mismatch } : {}),
268
+ });
269
+ const traceOf = (live, parts = live.parts) => ({ parts, read: [...live[sources]] });
270
+ const savedTraceOf = (live, parts = live.parts, extra = {}) => ({
271
+ ...traceOf(live, parts),
272
+ ...(live[deliveredFloor] ? { delivered: live[deliveredFloor] } : {}),
273
+ ...extra,
274
+ });
275
+ const replyParts = (live, parts = live.parts) => live[priorReply] ? [...live[priorReply].parts, ...parts] : parts;
276
+ // Save the accumulated public reply together with the raw output of this attempt.
277
+ const checkpoint = (live, parts = live.parts) => {
278
+ store.tx(() => {
279
+ messages.checkpointReply(live.messageId, replyParts(live, publishedParts(live, parts)));
280
+ saveTrace.run(JSON.stringify(savedTraceOf(live, parts)), live.turnId);
281
+ });
282
+ };
283
+ const settleParts = (parts, completed, quietFrom = parts.length) => parts.filter((part, i) => i < quietFrom || part.type !== 'text').map((part) => part.type === 'tool' && part.status === 'running' ? { ...part, status: completed ? 'done' : 'failed' } : part);
284
+ const turnFilters = `
285
+ FROM a2a_turns AS t LEFT JOIN json_each(?) AS preparing ON preparing.key = t.id
286
+ WHERE t.topic_id = ? AND (? IS NULL OR t.member_id = ?)
287
+ AND (? IS NULL OR t.id = ?)
288
+ AND (? IS NULL OR COALESCE(NULLIF(t.session_id, ''), preparing.value) = ?)
289
+ AND (? = 0 OR COALESCE(NULLIF(t.session_id, ''), preparing.value) IS NULL)
290
+ ORDER BY t.started_at DESC, t.rowid DESC LIMIT ?
291
+ `;
292
+ const filteredTurns = db.prepare(`SELECT t.* ${turnFilters}`);
293
+ const filteredTurnPreviews = db.prepare(`
294
+ SELECT t.id, t.topic_id, t.member_id, t.status, t.origin, t.reply_id,
295
+ substr(t.input_text, 1, 240) AS input_text, t.usage, t.error, t.depth,
296
+ t.started_at, t.ended_at, t.dispatched_at, t.session_id, t.model,
297
+ json_extract(t.trace, '$.failure') AS trace_failure,
298
+ json_extract(t.trace, '$.modelMismatch') AS trace_model_mismatch,
299
+ json_extract(t.trace, '$.read') AS trace_read,
300
+ (SELECT json_group_array(json_object(
301
+ 'type', json_extract(part.value, '$.type'),
302
+ 'text', json_extract(part.value, '$.text'),
303
+ 'status', json_extract(part.value, '$.status')))
304
+ FROM json_each(t.trace, '$.parts') AS part
305
+ WHERE json_extract(part.value, '$.type') IN ('text', 'thinking', 'tool')) AS preview_parts
306
+ ${turnFilters}
307
+ `);
308
+ const logFailed = (turn) => log('a2a', `turn failed: topic=${turn.topicId} member=${members.get(turn.memberId)?.name ?? turn.memberId} reply=${turn.replyId} dispatched=${turn.dispatchedAt !== null} reason=${turn.error ?? 'unknown'}`);
309
+ // Close replies left open by the previous host. Other startup handlers can claim their turns before catch-up.
310
+ const interruptedReason = '宿主停止时这一轮还在进行';
311
+ const failInterrupted = db.prepare("UPDATE a2a_turns SET status = 'interrupted', error = ?, ended_at = ?, trace = ? WHERE id = ?");
312
+ for (const open of messages.openReplies()) {
313
+ const row = open.turnId ? turnById.get(open.turnId) : undefined;
314
+ const saved = row?.status === 'running' ? readTrace(row) : undefined;
315
+ // The public checkpoint keeps one placeholder per hidden part, so the raw trace replaces its attempt suffix.
316
+ const priorCount = Math.max(0, open.parts.length - (saved?.parts.length ?? 0));
317
+ const parts = settleParts(saved ? [...open.parts.slice(0, priorCount), ...saved.parts] : open.parts, false);
318
+ messages.closeReply(open.id, {
319
+ content: textOf(parts), parts, status: 'failed', reason: interruptedReason, read: open.read,
320
+ }, () => {
321
+ if (!saved)
322
+ return;
323
+ const trace = { parts: parts.slice(priorCount), read: saved.read, ...(saved.delivered ? { delivered: saved.delivered } : {}) };
324
+ failInterrupted.run(interruptedReason, Date.now(), JSON.stringify(trace), open.turnId);
325
+ });
326
+ if (row?.status === 'running')
327
+ logFailed({ ...readTurn(row), error: interruptedReason });
328
+ }
329
+ db.prepare("UPDATE a2a_turns SET status = 'failed', error = ?, ended_at = ? WHERE status = 'running'").run(interruptedReason, Date.now());
330
+ const recoverable = db.prepare("SELECT * FROM a2a_turns WHERE status = 'interrupted' ORDER BY started_at DESC, rowid DESC");
331
+ for (const row of recoverable.all()) {
332
+ if (messages.stored(row.reply_id)?.turnId !== row.id)
333
+ continue;
334
+ const turn = readTurn(row);
335
+ const pair = key(turn.topicId, turn.memberId);
336
+ if (!interrupted.has(pair))
337
+ interrupted.set(pair, { turn });
338
+ }
339
+ // Upgrade existing topics without marking the whole history unread. Keep what was already waiting for the owner.
340
+ const ownerPositions = cursorsOf(OWNER_ID);
341
+ const firstWaiting = positions(db.prepare(`
342
+ SELECT topic_id, MIN(seq) AS seq FROM a2a_addressed WHERE member_id = ? AND read_at IS NULL GROUP BY topic_id
343
+ `).all(OWNER_ID));
344
+ store.tx(() => {
345
+ for (const topic of topics.list()) {
346
+ if (ownerPositions.has(topic.id))
347
+ continue;
348
+ const first = firstWaiting.get(topic.id);
349
+ seedCursor.run(topic.id, OWNER_ID, first === undefined ? messages.lastSeq(topic.id) : first - 1);
350
+ }
351
+ });
352
+ /** A topic can say who works in it: then only those are woken there. A person is never kept out; a topic that names nobody keeps nobody out. */
353
+ const admittedTo = (topic) => {
354
+ const only = topic?.members;
355
+ return (id) => !only?.length || only.includes(id) || isPerson(id);
356
+ };
357
+ const worksIn = (topicId) => admittedTo(topics.get(topicId));
358
+ const canWake = (topicId) => {
359
+ const topic = topics.get(topicId);
360
+ return !!topic && !topic.deletedAt && topic.archivedAt === null;
361
+ };
362
+ const isPerson = (id) => members.get(id)?.kind === 'person';
363
+ const usable = (id) => !!id && members.canReceive(id);
364
+ const reconcileGlobalDefault = () => {
365
+ const id = config.get('settings', 'a2a.defaultMember');
366
+ if (!id)
367
+ return '';
368
+ const previous = members.get(id);
369
+ if (usable(id) || (previous && !previous.adapter && members.acceptsDelivery(id)))
370
+ return id;
371
+ const order = members.list();
372
+ const start = order.findIndex((member) => member.id === id) + 1;
373
+ const next = [...order.slice(start), ...order.slice(0, start)].find((member) => usable(member.id));
374
+ const nextId = next?.id ?? '';
375
+ config.set('settings', 'a2a.defaultMember', nextId);
376
+ const reason = previous ? `原全局默认成员「${previous.name}」已停用。` : '原全局默认成员已移除。';
377
+ const change = next ? `已切换为「${next.name}」。` : '当前没有启用的成员,已清空全局默认。';
378
+ const i18n = ljoin([
379
+ previous ? ltext('host.notice.defaultMember.disabled', { name: previous.name }) : ltext('host.notice.defaultMember.removed'),
380
+ next ? ltext('host.notice.defaultMember.changedTo', { name: next.name }) : ltext('host.notice.defaultMember.cleared'),
381
+ ], ltext('host.sep.sentence'));
382
+ notices.add({ from: { kind: 'system', id: 'a2a' }, text: reason + change, i18n, open: 'members', key: 'a2a:default-member' });
383
+ return nextId;
384
+ };
385
+ /** A hand-over adds one to the depth of the message it answers or, without a reply, the turn that sent it. */
386
+ const handOver = (turn, to, replyTo) => {
387
+ const base = replyTo ? depthOf(replyTo) : (turn?.depth ?? 0);
388
+ const depth = base + 1;
389
+ return { depth, tooDeep: depth > config.get('settings', 'a2a.maxDepth') && to.some((id) => !isPerson(id)) };
390
+ };
391
+ const depthError = (id) => new Error('接力深度已达上限,没有发出。' +
392
+ (id ? '未送达交办已记录(' + id + ')。请接回这项工作,或说明还需要谁作决定。' : '成员之间连续交接的次数到了上限。'));
393
+ // The turn's actual first input establishes its authority. Quoting a different old message changes depth, never authority.
394
+ const authorityFor = (live, from, answered) => {
395
+ const input = live?.[sources].values().next().value ?? (answered?.to.includes(from) ? answered.id : undefined);
396
+ return handoffs.originOf(input);
397
+ };
398
+ const outgoingTurn = (from, fromTopic, targetId) => {
399
+ const agent = from.kind === 'member' && !!members.get(from.id)?.adapter;
400
+ const speaker = agent || (from.kind === 'member' && isPerson(from.id));
401
+ const source = speaker && fromTopic && fromTopic !== targetId ? topics.get(fromTopic) : undefined;
402
+ if (source?.archivedAt != null)
403
+ throw new HttpError(409, '主题已归档');
404
+ const room = fromTopic ?? targetId;
405
+ const live = agent && room ? running.get(key(room, from.id)) : undefined;
406
+ return { agent, source, live };
407
+ };
408
+ /** A running turn has read these too. Its unquoted hand-overs count from the deepest of all the messages it read. */
409
+ const alsoRead = (live, ids) => {
410
+ if (!ids.length)
411
+ return;
412
+ live.read.push(...ids);
413
+ for (const id of ids)
414
+ live[sources].add(id);
415
+ live.depth = Math.max(live.depth, ...ids.map(depthOf));
416
+ messages.setReplyRead(live.messageId, live.read);
417
+ db.prepare("UPDATE a2a_turns SET depth = ?, trace = json_set(trace, '$.read', json(?)) WHERE id = ?")
418
+ .run(live.depth, JSON.stringify([...live[sources]]), live.turnId);
419
+ };
420
+ /** Marked owner drafts and member hand-offs still name their recipients in the message. */
421
+ const namedIn = (content, by, include) => {
422
+ const person = by.kind === 'member' && isPerson(by.id);
423
+ const handles = [...members.list(), ...members.people()]
424
+ .filter((m) => !include || include(m.id))
425
+ .map((m) => ({ memberId: m.id, handle: m.handle.toLowerCase() }));
426
+ return findMentions(content, handles, { markedOnly: person });
427
+ };
428
+ function* recentContacts(topicId) {
429
+ const addressed = db.prepare(`
430
+ SELECT member_id FROM a2a_turns WHERE topic_id = ? AND origin = 'host' AND depth = 0
431
+ GROUP BY member_id ORDER BY MAX(started_at) DESC
432
+ `).all(topicId);
433
+ for (const row of addressed)
434
+ yield row.member_id;
435
+ yield* messages.repliers(topicId);
436
+ }
437
+ /** Resolve a participant's mentions, reply and fallback in that order. An incoming connector cannot answer itself. */
438
+ const conversationTargets = (topic, from, content, answered) => {
439
+ const here = admittedTo(topic);
440
+ const connector = isPerson(from.id) ? undefined : from.id;
441
+ const available = (id) => id !== connector && usable(id) && here(id);
442
+ const unavailable = (id) => {
443
+ const member = members.get(id);
444
+ if (!member)
445
+ return `成员 ${id} 已移除`;
446
+ if (!member.enabled)
447
+ return `${member.name} 已停用`;
448
+ if (!members.acceptsDelivery(id))
449
+ return `${member.name} 未声明接收消息`;
450
+ return `${member.name} 不在这个主题的成员名单里`;
451
+ };
452
+ const mentioned = connector === undefined ? namedIn(content, from, (id) => id !== from.id) : [];
453
+ let specified = mentioned;
454
+ if (!specified.length && answered?.from.kind === 'member'
455
+ && (members.get(answered.from.id)?.kind !== 'plugin' || members.acceptsDelivery(answered.from.id))) {
456
+ specified = answered.from.id === from.id ? answered.to.filter((id) => id !== connector) : [answered.from.id];
457
+ }
458
+ if (specified.length) {
459
+ const to = specified.filter(available);
460
+ if (to.length === specified.length || (!mentioned.length && to.length))
461
+ return { to };
462
+ const reasons = specified.filter((id) => !to.includes(id)).map(unavailable).join('、');
463
+ const note = to.length ? `${reasons},没有投递给它。` : `${reasons},没有投递,请从 @ 菜单选择其他成员。`;
464
+ return { to, note };
465
+ }
466
+ let previous;
467
+ for (const id of recentContacts(topic.id)) {
468
+ if (id === connector)
469
+ continue;
470
+ if (available(id))
471
+ return { to: [id] };
472
+ if (!members.get(id)?.enabled)
473
+ continue;
474
+ previous ??= id;
475
+ }
476
+ const other = (id) => id === connector ? undefined : id;
477
+ const topicDefault = topic.defaultMember && members.get(topic.defaultMember)?.enabled ? other(topic.defaultMember) : undefined;
478
+ const configured = topicDefault || (previous ? undefined : other(reconcileGlobalDefault()));
479
+ if (configured && available(configured))
480
+ return { to: [configured] };
481
+ if (previous)
482
+ return { to: [], note: `这个主题里之前交谈的 ${unavailable(previous)},没有投递,请从 @ 菜单选择成员。` };
483
+ if (configured)
484
+ return { to: [], note: `默认成员 ${unavailable(configured)},没有投递,请从 @ 菜单选择成员或更换默认成员。` };
485
+ const avail = members.list().filter((m) => available(m.id));
486
+ if (avail.length === 1)
487
+ return { to: [avail[0].id] };
488
+ const note = avail.length ? '没有设置默认成员,请从 @ 菜单选择成员,或在「成员」页设置默认成员。' : '没有可投递的成员。请先添加或启用成员。';
489
+ return { to: [], note };
490
+ };
491
+ const sendRecipients = (topic, { from, content, targets, requireRecipient }, visibility, handedOver, personRoute) => {
492
+ const here = admittedTo(topic);
493
+ const sender = from.kind === 'member' ? from.id : undefined;
494
+ const available = (id) => usable(id) && here(id);
495
+ const eligible = (id) => available(id) && (visibility === 'shadow' ? !isPerson(id) : visibleTo(visibility, id));
496
+ const route = visibility === 'shadow'
497
+ ? { to: targets ?? [] }
498
+ : personRoute?.() ?? { to: targets ?? namedIn(content, from, handedOver ? undefined : (id) => id !== sender && available(id)) };
499
+ const to = [...new Set(route.to)].filter(eligible);
500
+ // A forward supplies the names from its new note, even when that list is empty.
501
+ if (handedOver && !route.to.length && visibility !== 'shadow') {
502
+ const candidates = [topic.defaultMember, config.get('settings', 'a2a.defaultMember'), sender];
503
+ const handler = candidates.find((id) => !!id && !isPerson(id) && eligible(id));
504
+ if (handler)
505
+ to.push(handler);
506
+ }
507
+ if (!to.length && (handedOver || requireRecipient))
508
+ throw new HttpError(409, '没有可见且能接收此消息的成员。请指定可在该主题接手的成员。');
509
+ return { ...route, to };
510
+ };
511
+ const compose = async (init) => {
512
+ const pieces = await ctx.runtime.serial('turn.init', init);
513
+ if (pieces.length)
514
+ return pieces.join('\n\n');
515
+ return [init.note, ...init.messages.map((m) => withExcerpts(m, m.content))].filter(Boolean).join('\n\n');
516
+ };
517
+ let deletionVersion = 0;
518
+ /** A prompt assembled before a deletion may still be waiting for a hook or for the client to start. */
519
+ const prepareInput = (init, addressed) => {
520
+ const ids = new Set(addressed.map((m) => m.id));
521
+ for (const m of [...init.messages, ...(init.recent ?? [])]) {
522
+ ids.add(m.id);
523
+ if (m.replyTo)
524
+ ids.add(m.replyTo);
525
+ if (m.thread)
526
+ ids.add(m.thread);
527
+ }
528
+ if (init.reply?.thread)
529
+ ids.add(init.reply.thread);
530
+ let version = -1, deletedCount = -1;
531
+ let text;
532
+ return async () => {
533
+ while (version !== deletionVersion) {
534
+ version = deletionVersion;
535
+ const deleted = messages.deletedIds(ids);
536
+ if (deleted.size === deletedCount && init.recent === undefined)
537
+ continue;
538
+ deletedCount = deleted.size;
539
+ const visible = (m) => !deleted.has(m.id);
540
+ const trigger = addressed.findLast(visible);
541
+ if (!trigger && !init.note) {
542
+ text = undefined;
543
+ break;
544
+ }
545
+ text = await compose({ ...init, trigger, messages: init.messages.filter(visible), addressed: addressed.filter(visible).map((m) => m.id), ...(init.recent ? { recent: init.recent.filter(visible) } : {}) });
546
+ }
547
+ return text;
548
+ };
549
+ };
550
+ // The addressed receipts and the read position are independent. The position also marks what the owner
551
+ // has seen in the console, including messages addressed to nobody.
552
+ ctx.on('message.appended', ({ message }) => {
553
+ const { topicId, from } = message;
554
+ const add = db.prepare('INSERT OR IGNORE INTO a2a_addressed (topic_id, message_id, member_id, seq) VALUES (?, ?, ?, ?)');
555
+ for (const memberId of message.to)
556
+ add.run(topicId, message.id, memberId, message.seq);
557
+ if (from.kind === 'member' && isPerson(from.id) && message.replyTo)
558
+ read(from.id, [message.replyTo]);
559
+ if (from.kind === 'member' && from.id === OWNER_ID)
560
+ setCursor(topicId, OWNER_ID, message.seq);
561
+ else
562
+ seedCursor.run(topicId, OWNER_ID, 0); // The first message in a new topic establishes its unread baseline.
563
+ if (canWake(topicId))
564
+ topics.touch(topicId);
565
+ channelUpdated(topicId);
566
+ });
567
+ // A message already in the channel that is handed to someone because it changed (a card that was answered goes
568
+ // back to whoever sent it) waits for them unread, as if it had just been said to them. That is a person's or a
569
+ // plugin's doing, so no hand-over from member to member led to it.
570
+ const handAgain = db.prepare('INSERT INTO a2a_addressed (topic_id, message_id, member_id, seq) VALUES (?, ?, ?, ?) ON CONFLICT (message_id, member_id) DO UPDATE SET read_at = NULL');
571
+ const redeliver = (message, to) => {
572
+ for (const memberId of to)
573
+ handAgain.run(message.topicId, message.id, memberId, message.seq ?? 0);
574
+ };
575
+ ctx.on('message.changed', ({ message, tell }) => {
576
+ if (!tell.length)
577
+ return;
578
+ redeliver(message, tell);
579
+ db.prepare('DELETE FROM a2a_sent WHERE message_id = ?').run(message.id);
580
+ void wake(message.topicId);
581
+ });
582
+ ctx.on('message.deleted', ({ topicId, id }) => {
583
+ deletionVersion++;
584
+ db.prepare('DELETE FROM a2a_addressed WHERE message_id = ?').run(id);
585
+ db.prepare('DELETE FROM a2a_sent WHERE message_id = ?').run(id);
586
+ db.prepare('DELETE FROM a2a_delivery_grants WHERE message_id = ?').run(id);
587
+ removeQueuedRetries((request) => request.replyId === id);
588
+ channelUpdated(topicId);
589
+ });
590
+ ctx.on('topic.purged', ({ topicIds }) => {
591
+ db.prepare('DELETE FROM a2a_delivery_grants WHERE topic_id IN (SELECT value FROM json_each(?))').run(JSON.stringify(topicIds));
592
+ });
593
+ const pending = ({ topicId, memberId }) => {
594
+ const columns = ['read_at IS NULL', topicId !== undefined && 'topic_id = ?', memberId !== undefined && 'member_id = ?'].filter(Boolean);
595
+ const args = [topicId, memberId].filter((id) => id !== undefined);
596
+ return db.prepare(`SELECT message_id AS messageId, member_id AS memberId FROM a2a_addressed
597
+ WHERE ${columns.join(' AND ')} ORDER BY seq`).all(...args);
598
+ };
599
+ const waiting = (topicId, memberId) => pending({ topicId, memberId })
600
+ .map(({ messageId }) => messages.stored(messageId)).filter((m) => !!m);
601
+ /** Marks them read; gives back the ones that were unread until now. */
602
+ const read = (memberId, ids) => {
603
+ const mark = db.prepare('UPDATE a2a_addressed SET read_at = ? WHERE member_id = ? AND message_id = ? AND read_at IS NULL');
604
+ return ids.filter((id) => mark.run(Date.now(), memberId, id).changes > 0);
605
+ };
606
+ const isUnreadAddressed = db.prepare('SELECT 1 FROM a2a_addressed WHERE topic_id = ? AND member_id = ? AND message_id = ? AND read_at IS NULL');
607
+ const isReadAddressed = db.prepare('SELECT 1 FROM a2a_addressed WHERE topic_id = ? AND member_id = ? AND message_id = ? AND read_at IS NOT NULL');
608
+ const grantFields = 'credential, topic_id AS topicId, message_id AS messageId, member_id AS memberId, reply_id AS replyId';
609
+ const findGrant = db.prepare(`SELECT ${grantFields} FROM a2a_delivery_grants WHERE message_id = ? AND member_id = ?`);
610
+ const redeemGrant = db.prepare(`SELECT ${grantFields} FROM a2a_delivery_grants WHERE credential = ? AND member_id = ?`);
611
+ const saveGrant = db.prepare('INSERT INTO a2a_delivery_grants (credential, topic_id, message_id, member_id, reply_id) VALUES (?, ?, ?, ?, ?)');
612
+ const credentialFor = ({ topicId, id }, memberId) => {
613
+ const previous = findGrant.get(id, memberId);
614
+ if (previous)
615
+ return previous.credential;
616
+ const credential = randomBytes(32).toString('base64url');
617
+ saveGrant.run(credential, topicId, id, memberId, newId('msg'));
618
+ return credential;
619
+ };
620
+ const deliveryVisible = (message, memberId) => message.visibility === 'shadow' ? message.to.includes(memberId) : visibleTo(message.visibility, memberId);
621
+ const markDelivered = (message, memberId) => {
622
+ if (!read(memberId, [message.id]).length)
623
+ return;
624
+ setCursor(message.topicId, memberId, message.seq);
625
+ channelUpdated(message.topicId);
626
+ };
627
+ /** Notices from the system or a non-conversational plugin are operational noise for anyone but their recipients. */
628
+ const isOperationalNotice = (m) => {
629
+ if (m.from.kind === 'system')
630
+ return true;
631
+ if (m.from.kind !== 'member')
632
+ return false;
633
+ const sender = members.get(m.from.id);
634
+ return sender?.kind === 'plugin' && !sender.persona && !members.canReceive(m.from.id);
635
+ };
636
+ /** An empty message whose only payload is outgoing cross-topic references. */
637
+ const isPureOutgoingReceipt = (m) => !m.content.trim() && !m.attachments.length
638
+ && m.parts.some((part) => part.type === 'reference' && part.dir === 'out')
639
+ && !m.parts.some((part) => part.type === 'card' || part.type === 'excerpt'
640
+ || (part.type === 'reference' && part.dir !== 'out') || (part.type === 'text' && part.text.trim()));
641
+ const isFilteredBystander = (m, memberId) => !m.to.includes(memberId) && ((isOperationalNotice(m) && m.to.length > 0) || isPureOutgoingReceipt(m));
642
+ const backgroundChars = (m) => [...withExcerpts(m, m.content)].length;
643
+ const highestFloorSeq = (floor, given) => given.reduce((highest, m) => m.seq !== null && (m.id === floor || m.thread === floor) ? Math.max(highest, m.seq) : highest, 0);
644
+ /**
645
+ * How far `shown` carries a member's progress in one floor: walk the floor messages the member can see after
646
+ * `progress` through the highest shown one. What was neither shown nor left out with an omission notice (`omitted`)
647
+ * stops the walk — unless it is filtered bystander noise, or an addressed message with its own read receipt.
648
+ */
649
+ const coveredThrough = (topicId, memberId, floor, progress, shown, omitted = []) => {
650
+ const top = highestFloorSeq(floor, shown);
651
+ if (top <= progress)
652
+ return progress;
653
+ const ids = new Set(shown.map((m) => m.id));
654
+ for (const m of omitted)
655
+ ids.add(m.id);
656
+ for (const m of messages.after(topicId, progress, memberId, top, { floor, visibility: [memberId] })) {
657
+ if (ids.has(m.id) || isFilteredBystander(m, memberId))
658
+ continue;
659
+ // A receipt covers this message once the preceding gap has been accounted for.
660
+ if (m.to.includes(memberId) && isReadAddressed.get(topicId, memberId, m.id))
661
+ continue;
662
+ return m.seq - 1;
663
+ }
664
+ return top;
665
+ };
666
+ const completedFloorDelivery = db.prepare(`SELECT MAX(CAST(json_extract(trace, '$.delivered.seq') AS INTEGER)) AS seq
667
+ FROM a2a_turns WHERE topic_id = ? AND member_id = ? AND status = 'completed' AND dispatched_at IS NOT NULL
668
+ AND json_extract(trace, '$.delivered.floor') = ?`);
669
+ /**
670
+ * How far this member has got in one floor, from verifiable delivery evidence only: what a dispatched turn input
671
+ * or append handed it (`delivered` in the turn trace), or a continuous in-turn `topic_read` page of the floor
672
+ * that reached back past the standing progress. Reading one addressed message or writing in the floor proves
673
+ * neither. Without evidence this returns 0 and the first-visit path fills recent background instead.
674
+ */
675
+ const floorProgress = (topicId, memberId, floor) => {
676
+ const live = running.get(key(topicId, memberId));
677
+ const liveDelivered = live?.dispatchedAt !== undefined && live[deliveredFloor]?.floor === floor ? live[deliveredFloor].seq : 0;
678
+ const completed = completedFloorDelivery.get(topicId, memberId, floor);
679
+ return Math.max(liveDelivered, completed.seq ?? 0);
680
+ };
681
+ const selectDirectTargets = (topicId, memberId, visibility, batch, floor, progressSeq, mode) => {
682
+ const batchIds = new Set(batch.map((m) => m.id));
683
+ const directTargets = [];
684
+ const directIds = new Set();
685
+ for (const m of batch) {
686
+ if (!m.replyTo || batchIds.has(m.replyTo) || directIds.has(m.replyTo))
687
+ continue;
688
+ const target = messages.stored(m.replyTo);
689
+ if (!target || target.topicId !== topicId || target.seq === null || !visibleInTurn(target.visibility, memberId, visibility))
690
+ continue;
691
+ if (mode.firstVisitFloor || mode.opening || mode.replay || (target.id !== floor && target.thread !== floor) || target.seq > progressSeq) {
692
+ directTargets.push(target);
693
+ directIds.add(target.id);
694
+ }
695
+ }
696
+ return { batchIds, directTargets, directIds };
697
+ };
698
+ const selectFloorHead = (topicId, memberId, visibility, floor, batchIds, directIds, mode) => {
699
+ if (floor === null || !(mode.firstVisitFloor || mode.opening))
700
+ return undefined;
701
+ const head = messages.stored(floor);
702
+ return head && head.topicId === topicId && head.seq !== null && visibleInTurn(head.visibility, memberId, visibility)
703
+ && !batchIds.has(head.id) && !directIds.has(head.id) ? head : undefined;
704
+ };
705
+ /**
706
+ * What is handed to a member now: its addressed batch, the originals it directly answers, and the last few
707
+ * bystander messages of the same floor through the cutoff, within `a2a.recent` slots and the character budget.
708
+ * The floor head reserves background room before any general background; on an opening it is placed above the line.
709
+ */
710
+ const windowFor = (topicId, memberId, batch, cutoff, progressSeq, opening, before) => {
711
+ const floor = batch[0].thread;
712
+ const visibility = batch[0].visibility;
713
+ const firstVisitFloor = floor !== null && progressSeq === 0;
714
+ const { batchIds, directTargets, directIds } = selectDirectTargets(topicId, memberId, visibility, batch, floor, progressSeq, { firstVisitFloor, opening });
715
+ const floorHead = selectFloorHead(topicId, memberId, visibility, floor, batchIds, directIds, { firstVisitFloor, opening });
716
+ const pool = messages.after(topicId, progressSeq, memberId, cutoff, { floor, visibility })
717
+ .filter((m) => !batchIds.has(m.id) && !directIds.has(m.id) && m.id !== floorHead?.id && !m.to.includes(memberId)
718
+ && visibleInTurn(m.visibility, memberId, visibility) && !isFilteredBystander(m, memberId));
719
+ const limit = config.get('settings', 'a2a.recent');
720
+ const kept = [];
721
+ const omitted = [];
722
+ let usedSlots = 0;
723
+ let usedChars = 0;
724
+ let openingHead;
725
+ const headAboveLine = floorHead !== undefined && opening && before !== undefined && floorHead.seq < before;
726
+ if (floorHead) {
727
+ if (usedSlots < limit && backgroundChars(floorHead) <= BACKGROUND_BUDGET) {
728
+ usedSlots++;
729
+ usedChars += backgroundChars(floorHead);
730
+ if (headAboveLine)
731
+ openingHead = floorHead;
732
+ else
733
+ kept.push(floorHead);
734
+ }
735
+ else if (!headAboveLine)
736
+ omitted.push(floorHead);
737
+ }
738
+ const newestFirst = [...pool].reverse();
739
+ for (let i = 0; i < newestFirst.length; i++) {
740
+ const m = newestFirst[i];
741
+ if (usedSlots < limit && usedChars + backgroundChars(m) <= BACKGROUND_BUDGET) {
742
+ kept.push(m);
743
+ usedSlots++;
744
+ usedChars += backgroundChars(m);
745
+ }
746
+ else {
747
+ omitted.push(...newestFirst.slice(i));
748
+ break;
749
+ }
750
+ }
751
+ omitted.sort((a, b) => a.seq - b.seq);
752
+ return {
753
+ messages: [...batch, ...directTargets, ...kept].sort((x, y) => x.seq - y.seq),
754
+ omitted,
755
+ ...(omitted.length ? { skipped: { count: omitted.length, from: omitted[0].seq, to: omitted.at(-1).seq } } : {}),
756
+ usedSlots,
757
+ usedChars,
758
+ ...(openingHead ? { openingHead } : {}),
759
+ };
760
+ };
761
+ const pushTurn = (live, event, payload) => {
762
+ if (visibleTo(live[replyVisibility], OWNER_ID))
763
+ push.send(event, payload);
764
+ };
765
+ /** The reply and its read list are recorded together, before anything is handed to the instance. */
766
+ const openTurn = (topicId, memberId, origin, depth, opts = {}) => {
767
+ const turnId = opts.turnId ?? newId('turn');
768
+ const { replyTo, thread, previous } = opts;
769
+ const startedAt = Date.now();
770
+ const model = members.get(memberId)?.options.model;
771
+ const live = store.tx(() => {
772
+ const read = previous ? [...previous.reply.read] : opts.read?.() ?? [];
773
+ const reply = previous ? messages.reopenReply(previous.reply.id, turnId)
774
+ : messages.openReply({ topicId, memberId, turnId, replyTo, thread, read, visibility: opts.visibility });
775
+ const attempt = {
776
+ turnId, topicId, memberId, messageId: reply.id, origin, depth, parts: [], startedAt, replyTo, thread, read,
777
+ ...(previous ? { [priorReply]: reply, seq: reply.seq } : {}),
778
+ [configuredModel]: typeof model === 'string' ? model.trim() : undefined,
779
+ [replyVisibility]: reply.visibility,
780
+ [sources]: new Set(previous ? previous.turn.trace.read : read),
781
+ [deferred]: new Set(),
782
+ [independent]: { posted: [], claimed: new Set(), outsideRead: new Set() },
783
+ };
784
+ db.prepare('INSERT INTO a2a_turns (id, topic_id, member_id, status, origin, reply_id, depth, started_at, trace) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
785
+ .run(turnId, topicId, memberId, 'running', origin, reply.id, depth, startedAt, JSON.stringify(traceOf(attempt)));
786
+ if (opts.client !== undefined)
787
+ saveTurnClient.run(turnId, opts.client);
788
+ return attempt;
789
+ });
790
+ running.set(key(topicId, memberId), live);
791
+ const event = { turn: withDeletedRefs(messages, [liveView(live)])[0] };
792
+ pushTurn(live, 'turn.started', event);
793
+ ctx.runtime.emit('turn.started', event);
794
+ return live;
795
+ };
796
+ const finalize = (live, outcome, error, failure) => {
797
+ const k = key(live.topicId, live.memberId);
798
+ if (stopped || running.get(k) !== live)
799
+ return;
800
+ ctx.runtime.emit('turn.closing', { turn: live });
801
+ running.delete(k);
802
+ const last = live[textMessage];
803
+ const controlFrom = outcome === 'completed' && last?.prefix?.trim() === NO_REPLY ? last.start : undefined;
804
+ const parts = settleParts(live.parts, outcome === 'completed', controlFrom);
805
+ const text = textOf(parts);
806
+ const previous = live[priorReply];
807
+ const visibility = live[replyVisibility];
808
+ const postedId = live[independent].posted.at(-1);
809
+ const quiet = outcome === 'completed' && !text;
810
+ // A positioned reply and a reply with a durable card both keep their address.
811
+ const durable = quiet && (previous || live[revisedReply]);
812
+ const target = quiet && !durable && postedId ? messages.stored(postedId) : undefined;
813
+ const empty = quiet && !durable && !postedId && controlFrom === undefined && !parts.some((part) => part.type !== 'thinking');
814
+ if (empty) {
815
+ outcome = 'failed';
816
+ error = '客户端这一轮没有产出任何内容';
817
+ }
818
+ const discard = !!target || (quiet && controlFrom !== undefined && !durable);
819
+ const expected = live[configuredModel];
820
+ const modelMismatch = expected && live.model && live.model !== expected ? expected : undefined;
821
+ const closeTurn = (replyId, trace) => db.prepare('UPDATE a2a_turns SET reply_id = ?, status = ?, usage = ?, error = ?, ended_at = ?, session_id = COALESCE(session_id, ?), trace = ? WHERE id = ?')
822
+ .run(replyId, outcome, live.usage ? JSON.stringify({ ...live.usage, _inputFormat: 'inclusive' }) : null, error ?? null, Date.now(), instances.session(live.topicId, live.memberId) ?? null, JSON.stringify(savedTraceOf(live, trace.parts, {
823
+ read: trace.read,
824
+ modelMismatch,
825
+ ...(outcome === 'failed' && failure ? { failure } : {}),
826
+ })), live.turnId);
827
+ let message;
828
+ let tooDeep = false;
829
+ if (discard) {
830
+ message = store.tx(() => {
831
+ messages.discardReply(live.messageId);
832
+ if (!target) {
833
+ closeTurn(live.messageId, traceOf(live, parts));
834
+ return;
835
+ }
836
+ const postedParts = target.content && !target.parts.some((part) => part.type === 'text')
837
+ ? [{ type: 'text', text: target.content }, ...target.parts] : target.parts;
838
+ closeTurn(target.id, traceOf(live, [...postedParts, ...parts]));
839
+ return messages.attachTurn(target.id, {
840
+ turnId: live.turnId,
841
+ parts: [...target.parts, ...parts],
842
+ read: [...new Set([...target.read, ...live.read])],
843
+ });
844
+ });
845
+ }
846
+ else {
847
+ // A completed reply can call the agents it names. A failure goes back to agents still awaiting a reply,
848
+ // except the writers of failed replies: two members that fail do not go on telling each other.
849
+ const here = worksIn(live.topicId);
850
+ const asked = () => [...new Set(live.read.map((id) => messages.stored(id)).filter((m) => m?.from.kind === 'member' && m.status !== 'failed').map((m) => m.from.id))]
851
+ .filter((id) => id !== live.memberId && !isPerson(id) && usable(id) && here(id));
852
+ const fullyClaimed = live[independent].claimed.size > 0 && live.read.length === 0;
853
+ const canRelay = outcome === 'completed' && text && !fullyClaimed;
854
+ let to = outcome === 'failed' ? asked() : canRelay ? namedIn(text, { kind: 'member', id: live.memberId }, (id) => id !== live.memberId && usable(id) && here(id)) : [];
855
+ to = to.filter((id) => visibleTo(visibility, id));
856
+ const handover = handOver(live, to, live.replyTo);
857
+ tooDeep = handover.tooDeep;
858
+ const intended = to;
859
+ if (tooDeep)
860
+ to = to.filter(isPerson);
861
+ const content = [previous?.content, text].filter(Boolean).join('\n\n');
862
+ message = messages.closeReply(live.messageId, {
863
+ content, parts: replyParts(live, parts), status: outcome,
864
+ to: previous ? [...new Set([...previous.to, ...to])] : to, read: live.read, reason: error,
865
+ }, (message) => {
866
+ setDepth(message.id, handover.depth);
867
+ const authority = authorityFor(live, live.memberId);
868
+ handoffs.inherit(message.id, authority);
869
+ const blocked = intended.filter((id) => !message.to.includes(id));
870
+ if (tooDeep && canRelay && blocked.length)
871
+ handoffs.record({
872
+ kind: 'reply', authority, from: live.memberId, sourceTopicId: live.topicId, sourceMessageId: message.id,
873
+ sourceThread: live.thread, topicId: live.topicId, thread: live.thread, turnId: live.turnId,
874
+ blocked, delivered: message.to, content, visibility, depth: handover.depth,
875
+ });
876
+ closeTurn(message.id, traceOf(live, parts));
877
+ if (previous)
878
+ redeliver(message, to);
879
+ });
880
+ }
881
+ const turn = readTurn(turnById.get(live.turnId));
882
+ if (outcome === 'failed')
883
+ logFailed(turn);
884
+ const event = {
885
+ turn,
886
+ ...(message ? { message: withReplyModels(messagesOut(messages, [message]))[0] } : {}),
887
+ ...(discard ? { discardedReplyId: live.messageId } : {}),
888
+ };
889
+ pushTurn(live, 'turn.ended', event);
890
+ ctx.runtime.emit('turn.ended', event);
891
+ if (target || previous)
892
+ channelUpdated(live.topicId);
893
+ if (tooDeep)
894
+ messages.publish({ topicId: live.topicId, from: { kind: 'system', id: 'a2a' }, content: '接力深度已达上限,没有继续往下交。', visibility, ...(live.thread ? { thread: live.thread } : {}) });
895
+ for (const wakeUp of idleWaiters.get(k) ?? [])
896
+ wakeUp();
897
+ idleWaiters.delete(k);
898
+ void wake(live.topicId);
899
+ };
900
+ // A turn can be preparing before there is an instance to report its end.
901
+ const cancel = (scope, reason, startingOnly = false) => {
902
+ for (const live of [...running.values()]) {
903
+ if (scope.topicId && live.topicId !== scope.topicId)
904
+ continue;
905
+ if (scope.memberId && live.memberId !== scope.memberId)
906
+ continue;
907
+ finalize(live, 'canceled', reason);
908
+ }
909
+ return instances.stop(scope, { force: true, reason, startingOnly });
910
+ };
911
+ const everyone = () => [...members.list(), ...members.people()].filter((m) => m.enabled);
912
+ const markDispatched = (live) => {
913
+ if (live.origin !== 'host' || live.dispatchedAt !== undefined)
914
+ return;
915
+ live.dispatchedAt = Date.now();
916
+ const prepared = preparedFloorDelivery.get(live);
917
+ if (live.thread && prepared?.floor === live.thread && prepared.seq > 0) {
918
+ live[deliveredFloor] = {
919
+ floor: live.thread,
920
+ seq: Math.max(live[deliveredFloor]?.seq ?? 0, prepared.seq),
921
+ };
922
+ }
923
+ db.prepare('UPDATE a2a_turns SET dispatched_at = ?, session_id = ?, trace = ? WHERE id = ?')
924
+ .run(live.dispatchedAt, instances.session(live.topicId, live.memberId) ?? null, JSON.stringify(savedTraceOf(live)), live.turnId);
925
+ };
926
+ const sendTurn = (live, prepare) => {
927
+ const { topicId, memberId, turnId } = live;
928
+ const current = () => !stopped && running.get(key(topicId, memberId)) === live;
929
+ const ready = async () => {
930
+ const text = await prepare();
931
+ if (!current())
932
+ return;
933
+ if (text === undefined)
934
+ finalize(live, 'canceled', '唤醒这轮的消息已删除');
935
+ else
936
+ return { turnId, text };
937
+ };
938
+ void (async () => {
939
+ const input = await ready();
940
+ if (!input)
941
+ return;
942
+ await instances.send(topicId, memberId, input, current, async () => {
943
+ const input = await ready();
944
+ if (input)
945
+ db.prepare('UPDATE a2a_turns SET input_text = ? WHERE id = ?').run(input.text, turnId);
946
+ return input;
947
+ }, adapter => { saveTurnClient.run(turnId, adapter); });
948
+ if (current())
949
+ markDispatched(live);
950
+ })().catch((error) => {
951
+ if (current())
952
+ finalize(live, 'failed', errorText(error), error instanceof TurnFailureError ? error.failure : undefined);
953
+ });
954
+ };
955
+ /** A session opening here also gets the recent history of the same floor from before what the member was last given. */
956
+ const openingContext = (topicId, memberId, before, floor, visibility, excludeIds, usedSlots, usedChars, reservedHead) => {
957
+ const candidates = messages.floorBefore(topicId, before, memberId, floor, visibility)
958
+ .filter((m) => visibleInTurn(m.visibility, memberId, visibility) && !excludeIds.has(m.id) && !isFilteredBystander(m, memberId));
959
+ const slotRoom = Math.max(0, config.get('settings', 'a2a.recent') - usedSlots);
960
+ const charRoom = Math.max(0, BACKGROUND_BUDGET - usedChars);
961
+ const recent = [];
962
+ const chosen = new Set();
963
+ if (reservedHead && candidates.some((m) => m.id === reservedHead.id)) {
964
+ recent.push(reservedHead);
965
+ chosen.add(reservedHead.id);
966
+ }
967
+ let slots = 0;
968
+ let chars = 0;
969
+ const pick = (m) => {
970
+ if (slots >= slotRoom || chars + backgroundChars(m) > charRoom)
971
+ return false;
972
+ recent.push(m);
973
+ slots++;
974
+ chars += backgroundChars(m);
975
+ chosen.add(m.id);
976
+ return true;
977
+ };
978
+ for (const m of [...candidates].reverse()) {
979
+ if (chosen.has(m.id))
980
+ continue;
981
+ if (!pick(m))
982
+ break;
983
+ }
984
+ recent.sort((a, b) => a.seq - b.seq);
985
+ const earlier = candidates.length - recent.length;
986
+ if (!recent.length && earlier === 0)
987
+ return {};
988
+ return { recent, earlier, ...(earlier ? { omitted: candidates.filter((m) => !chosen.has(m.id)) } : {}) };
989
+ };
990
+ const retryTarget = (topicId, replyId, turnId) => {
991
+ const topic = topics.get(topicId);
992
+ if (!topic || topic.deletedAt)
993
+ return new HttpError(404, '没有这个主题', undefined, ltext('host.err.topicNotFound'));
994
+ if (topic.archivedAt !== null)
995
+ return new HttpError(409, '主题已归档', undefined, ltext('host.err.topicArchived'));
996
+ const reply = messages.stored(replyId);
997
+ if (!reply || reply.topicId !== topicId || reply.from.kind !== 'member' || isPerson(reply.from.id) || !reply.turnId) {
998
+ return new HttpError(404, '这个主题里没有这条成员回合的回复', undefined, ltext('host.err.turnReplyMissing'));
999
+ }
1000
+ if (reply.turnId !== turnId)
1001
+ return new HttpError(409, '这条回复已换到新的回合', undefined, ltext('host.err.turnRetryChanged'));
1002
+ const row = db.prepare('SELECT * FROM a2a_turns WHERE id = ? AND reply_id = ?').get(reply.turnId, reply.id);
1003
+ if (!row)
1004
+ return new HttpError(404, '没有找到这条回复对应的回合', undefined, ltext('host.err.turnNotFound'));
1005
+ const turn = readTurn(row);
1006
+ if (reply.terminal?.status !== turn.status) {
1007
+ return new HttpError(400, '只有失败或已取消的回合可以重试', undefined, ltext('host.err.turnRetryState'));
1008
+ }
1009
+ const member = members.get(turn.memberId);
1010
+ if (!member?.enabled)
1011
+ return new HttpError(409, '这个成员不存在或已停用', undefined, ltext('host.err.memberUnavailable'));
1012
+ if (!worksIn(topicId)(member.id))
1013
+ return new HttpError(409, '这个成员不在这个主题的成员名单里', undefined, ltext('host.err.memberNotInTopic'));
1014
+ if (held || stopped)
1015
+ return new HttpError(409, '宿主正在等待重启,暂时不能开始新回合', undefined, ltext('host.err.restartHolding'));
1016
+ return { turn, reply, member };
1017
+ };
1018
+ const nextRetry = (pair) => {
1019
+ const queue = retryQueue.get(pair);
1020
+ while (queue?.length) {
1021
+ const { topicId, replyId, turnId } = queue.shift();
1022
+ if (!queue.length)
1023
+ retryQueue.delete(pair);
1024
+ const target = retryTarget(topicId, replyId, turnId);
1025
+ if (!(target instanceof HttpError))
1026
+ return target;
1027
+ }
1028
+ };
1029
+ /** First delivery, manual retry and restart recovery open one attempt and dispatch through the same path. */
1030
+ const deliver = (topicId, member, input) => {
1031
+ const sessionId = instances.session(topicId, member.id);
1032
+ const opening = instances.opening(topicId, member.id);
1033
+ let depth;
1034
+ let options;
1035
+ let window;
1036
+ if (Array.isArray(input)) {
1037
+ const first = input[0];
1038
+ const split = input.findIndex((m) => m.thread !== first.thread || !sameVisibility(m.visibility, first.visibility)
1039
+ || (first.thread === null && !opensFloor(first) && opensFloor(m)));
1040
+ const batch = split < 0 ? input : input.slice(0, split);
1041
+ const cutoff = split < 0 ? messages.lastSeq(topicId) : input[split].seq - 1;
1042
+ const floor = first.thread;
1043
+ const progressSeq = floor === null ? cursorOf(topicId, member.id) : floorProgress(topicId, member.id, floor);
1044
+ const before = Math.min(progressSeq + 1, first.seq);
1045
+ window = (sceneNeeded) => {
1046
+ const { usedSlots, usedChars, ...given } = windowFor(topicId, member.id, batch, cutoff, progressSeq, sceneNeeded, before);
1047
+ return { ...given, batch, before, floor, usedSlots, usedChars };
1048
+ };
1049
+ depth = Math.max(...batch.map((m) => depthOf(m.id)));
1050
+ options = {
1051
+ replyTo: first.thread === null ? first.id : batch.at(-1).id, thread: floorOf(first), visibility: first.visibility,
1052
+ read: () => {
1053
+ if (floor === null)
1054
+ setCursor(topicId, member.id, cutoff);
1055
+ return read(member.id, batch.map((m) => m.id));
1056
+ },
1057
+ };
1058
+ }
1059
+ else {
1060
+ const { turn, reply } = input;
1061
+ options = { replyTo: reply.replyTo ?? undefined, thread: reply.thread ?? undefined, previous: input };
1062
+ depth = turn.depth;
1063
+ window = (sceneNeeded) => {
1064
+ const ids = [...live[sources]];
1065
+ if (!ids.length && reply.replyTo)
1066
+ ids.push(reply.replyTo);
1067
+ const batch = ids.map((id) => messages.stored(id)).filter((m) => !!m).sort((a, b) => a.seq - b.seq);
1068
+ const floor = batch[0]?.thread ?? (reply.thread && reply.thread !== batch[0]?.id ? reply.thread : null);
1069
+ const before = batch[0]?.seq ?? messages.lastSeq(topicId) + 1;
1070
+ if (!batch.length)
1071
+ return { batch, messages: batch, before, floor, usedSlots: 0, usedChars: 0 };
1072
+ const progressSeq = floor === null ? cursorOf(topicId, member.id) : floorProgress(topicId, member.id, floor);
1073
+ const visibility = live[replyVisibility];
1074
+ const { batchIds, directTargets, directIds } = selectDirectTargets(topicId, member.id, visibility, batch, floor, progressSeq, { opening: sceneNeeded, replay: true });
1075
+ const floorHead = selectFloorHead(topicId, member.id, visibility, floor, batchIds, directIds, { opening: sceneNeeded });
1076
+ const below = [];
1077
+ let openingHead;
1078
+ let usedSlots = 0;
1079
+ let usedChars = 0;
1080
+ if (floorHead && sceneNeeded) {
1081
+ const limit = config.get('settings', 'a2a.recent');
1082
+ if (usedSlots < limit && backgroundChars(floorHead) <= BACKGROUND_BUDGET) {
1083
+ usedSlots++;
1084
+ usedChars += backgroundChars(floorHead);
1085
+ if (floorHead.seq < before)
1086
+ openingHead = floorHead;
1087
+ else
1088
+ below.push(floorHead);
1089
+ }
1090
+ }
1091
+ return {
1092
+ batch,
1093
+ messages: [...batch, ...directTargets, ...below].sort((x, y) => x.seq - y.seq),
1094
+ before,
1095
+ floor,
1096
+ usedSlots,
1097
+ usedChars,
1098
+ ...(openingHead ? { openingHead } : {}),
1099
+ };
1100
+ };
1101
+ }
1102
+ const previous = options.previous?.turn;
1103
+ const mode = previous && previous.dispatchedAt !== null && previous.sessionId && previous.sessionId === sessionId
1104
+ && !opening && latestTurn.get(topicId, member.id)?.id === previous.id
1105
+ ? 'continue' : 'replay';
1106
+ const pair = key(topicId, member.id);
1107
+ const recovery = interrupted.get(pair);
1108
+ const resuming = previous && recovery?.turn.id === previous.id ? recovery : undefined;
1109
+ const notice = resuming?.notice?.(resuming.turn);
1110
+ const live = openTurn(topicId, member.id, 'host', depth, options);
1111
+ if (resuming)
1112
+ interrupted.delete(pair);
1113
+ const reason = previous?.error ? `(原因:${previous.error})` : '';
1114
+ const instruction = (words) => `[系统] 上一轮未能完成${reason}${words}${notice ? '\n\n[系统] ' + notice.content : ''}`;
1115
+ let prepare;
1116
+ let withScene = opening;
1117
+ sendTurn(live, async () => {
1118
+ // Loading a saved session can fail or a StartInput change can require a new session before delivery.
1119
+ const changed = instances.session(topicId, member.id) !== sessionId || instances.opening(topicId, member.id) !== opening;
1120
+ if (mode === 'continue' && !changed)
1121
+ return instruction(',请接着刚才中断的地方继续完成,不要重复已经完成的部分。');
1122
+ const sceneNeeded = opening || changed;
1123
+ if (!prepare || withScene !== sceneNeeded) {
1124
+ const { batch, before, floor, usedSlots, usedChars, openingHead, omitted = [], ...given } = window(sceneNeeded);
1125
+ const { omitted: earlierOmissions = [], ...scene } = sceneNeeded
1126
+ ? openingContext(topicId, member.id, before, floor, live[replyVisibility], new Set(given.messages.map((m) => m.id)), usedSlots, usedChars, openingHead) : {};
1127
+ if (live.thread) {
1128
+ const progress = floorProgress(topicId, member.id, live.thread);
1129
+ const seq = coveredThrough(topicId, member.id, live.thread, progress, [...given.messages, ...(scene.recent ?? [])], [...omitted, ...earlierOmissions]);
1130
+ if (seq > progress)
1131
+ preparedFloorDelivery.set(live, { floor: live.thread, seq });
1132
+ }
1133
+ prepare = prepareInput({ topicId, member, ...given, ...scene, opening: sceneNeeded, append: false, reply: { replyTo: live.replyTo, thread: live.thread, visibility: live[replyVisibility] },
1134
+ ...(previous ? { note: instruction('。下面的消息请重新处理:') } : {}) }, batch);
1135
+ withScene = sceneNeeded;
1136
+ }
1137
+ return prepare();
1138
+ });
1139
+ if (notice) {
1140
+ try {
1141
+ messages.publish({ topicId, ...notice, to: [], thread: live.thread, visibility: live[replyVisibility] });
1142
+ }
1143
+ catch (error) {
1144
+ log('a2a', 'could not publish the recovery notice', errorText(error));
1145
+ }
1146
+ }
1147
+ return { live, mode };
1148
+ };
1149
+ const appendInput = async (live, batch, text, cutoff, givenMessages = batch, omitted) => {
1150
+ const { topicId, memberId, turnId } = live;
1151
+ if (stopped || text === undefined || running.get(key(topicId, memberId)) !== live)
1152
+ return false;
1153
+ const member = members.get(memberId);
1154
+ if (!worksIn(topicId)(memberId))
1155
+ return false;
1156
+ try {
1157
+ await instances.append(topicId, memberId, { turnId, text });
1158
+ }
1159
+ catch (error) {
1160
+ log('a2a', `append to ${member.name} refused`, errorText(error));
1161
+ return false;
1162
+ }
1163
+ if (stopped || running.get(key(topicId, memberId)) !== live)
1164
+ return false;
1165
+ store.tx(() => {
1166
+ if (cutoff !== undefined)
1167
+ setCursor(topicId, memberId, cutoff);
1168
+ alsoRead(live, read(memberId, batch.map((m) => m.id)));
1169
+ if (live.thread) {
1170
+ const progress = floorProgress(topicId, memberId, live.thread);
1171
+ const seq = coveredThrough(topicId, memberId, live.thread, progress, givenMessages, omitted);
1172
+ if (seq > (live[deliveredFloor]?.seq ?? 0)) {
1173
+ live[deliveredFloor] = { floor: live.thread, seq };
1174
+ saveTrace.run(JSON.stringify(savedTraceOf(live)), live.turnId);
1175
+ }
1176
+ }
1177
+ db.prepare("UPDATE a2a_turns SET input_text = input_text || ? WHERE id = ?").run(`\n\n— 追加 —\n${text}`, turnId);
1178
+ });
1179
+ return true;
1180
+ };
1181
+ /** Normal delivery takes messages from the same input scope and advances its context window. */
1182
+ const appendTo = async (live, member, addressed) => {
1183
+ const fits = (m) => floorOf(m) === live.thread && sameVisibility(m.visibility, live[replyVisibility]);
1184
+ const split = addressed.findIndex((m) => !fits(m));
1185
+ const batch = split < 0 ? addressed : addressed.slice(0, split);
1186
+ if (!batch.length)
1187
+ return false;
1188
+ const cutoff = split < 0 ? messages.lastSeq(live.topicId) : addressed[split].seq - 1;
1189
+ const floor = batch[0].thread;
1190
+ const progressSeq = floor === null ? cursorOf(live.topicId, member.id) : floorProgress(live.topicId, member.id, floor);
1191
+ const { messages: givenMessages, skipped, omitted } = windowFor(live.topicId, member.id, batch, cutoff, progressSeq, false);
1192
+ const prepare = prepareInput({
1193
+ topicId: live.topicId, member, messages: givenMessages, skipped, append: true,
1194
+ reply: { replyTo: live.replyTo, thread: live.thread, visibility: live[replyVisibility] },
1195
+ }, batch);
1196
+ return appendInput(live, batch, await prepare(), floor === null ? cutoff : undefined, givenMessages, omitted);
1197
+ };
1198
+ /** Resume interrupted or queued work before a fresh batch. A busy client may accept an append. */
1199
+ const dispatchTurn = (topicId, member) => {
1200
+ const pair = key(topicId, member.id);
1201
+ if (interrupted.has(pair)) {
1202
+ recover(pair);
1203
+ if (interrupted.has(pair))
1204
+ return;
1205
+ }
1206
+ const live = running.get(pair);
1207
+ if (!live) {
1208
+ const retry = nextRetry(pair);
1209
+ if (retry) {
1210
+ deliver(topicId, member, retry);
1211
+ return;
1212
+ }
1213
+ const addressed = waiting(topicId, member.id);
1214
+ if (addressed.length)
1215
+ deliver(topicId, member, addressed);
1216
+ }
1217
+ else if (!retryQueue.has(pair) && instances.canAppend(topicId, member.id)) {
1218
+ const addressed = waiting(topicId, member.id).filter((m) => !live[deferred].has(m.id));
1219
+ if (addressed.length)
1220
+ return appendTo(live, member, addressed);
1221
+ }
1222
+ };
1223
+ const delivering = new Map();
1224
+ const dispatchMessages = (topicId, memberId, receive) => {
1225
+ for (const { id } of waiting(topicId, memberId)) {
1226
+ const pair = `${id}:${memberId}`;
1227
+ if (delivering.get(pair) === receive)
1228
+ continue;
1229
+ delivering.set(pair, receive);
1230
+ // A connector can take as long as it needs to accept the message. It holds no turn or other recipient.
1231
+ void Promise.resolve().then(async () => {
1232
+ if (stopped || held || members.receiver(memberId) !== receive || !canWake(topicId) || !worksIn(topicId)(memberId))
1233
+ return;
1234
+ const message = messages.stored(id);
1235
+ if (!message || !deliveryVisible(message, memberId))
1236
+ return;
1237
+ const credential = credentialFor(message, memberId);
1238
+ await receive({ message, credential });
1239
+ if (!stopped && members.receiver(memberId) === receive)
1240
+ markDelivered(message, memberId);
1241
+ }).catch((error) => ctx.runtime.onError(`delivery to ${memberId}`, error)).finally(() => {
1242
+ if (delivering.get(pair) === receive)
1243
+ delivering.delete(pair);
1244
+ });
1245
+ }
1246
+ };
1247
+ const dispatchTarget = (topicId, member) => {
1248
+ const receive = members.receiver(member.id);
1249
+ if (receive)
1250
+ return () => dispatchMessages(topicId, member.id, receive);
1251
+ if (member.adapter)
1252
+ return () => dispatchTurn(topicId, member);
1253
+ };
1254
+ const wakeOnce = async (topicId) => {
1255
+ for (const member of members.list()) {
1256
+ if (stopped || held || !canWake(topicId))
1257
+ return;
1258
+ if (!usable(member.id) || !worksIn(topicId)(member.id))
1259
+ continue;
1260
+ const pending = dispatchTarget(topicId, member)?.();
1261
+ if (pending)
1262
+ await pending;
1263
+ }
1264
+ channelUpdated(topicId);
1265
+ };
1266
+ // Once the host is stopping nothing new is started: the store may already be closed.
1267
+ let stopped = false;
1268
+ let held = false;
1269
+ let catchUpReady = false;
1270
+ const stop = () => {
1271
+ if (stopped)
1272
+ return;
1273
+ for (const live of running.values())
1274
+ checkpoint(live);
1275
+ stopped = true;
1276
+ };
1277
+ ctx.on('host.stopping', stop);
1278
+ ctx.effect(stop);
1279
+ const wake = async (topicId) => {
1280
+ if (stopped || held || !canWake(topicId))
1281
+ return;
1282
+ if (waking.has(topicId)) {
1283
+ dirty.add(topicId);
1284
+ return;
1285
+ }
1286
+ waking.add(topicId);
1287
+ try {
1288
+ do {
1289
+ dirty.delete(topicId);
1290
+ await wakeOnce(topicId);
1291
+ } while (dirty.has(topicId));
1292
+ }
1293
+ catch (error) {
1294
+ log('a2a', 'wake failed', error);
1295
+ }
1296
+ finally {
1297
+ waking.delete(topicId);
1298
+ }
1299
+ };
1300
+ const recover = (pair) => {
1301
+ if (!catchUpReady || held || stopped || running.has(pair))
1302
+ return;
1303
+ const { id, topicId, memberId, replyId } = interrupted.get(pair).turn;
1304
+ try {
1305
+ const target = retryTarget(topicId, replyId, id);
1306
+ if (target instanceof HttpError)
1307
+ return;
1308
+ const { mode } = deliver(topicId, target.member, target);
1309
+ log('a2a', `turn resumed: topic=${topicId} member=${memberId} reply=${replyId} mode=${mode}`);
1310
+ }
1311
+ catch (error) {
1312
+ log('a2a', `could not resume: topic=${topicId} member=${memberId} reply=${replyId}`, errorText(error));
1313
+ }
1314
+ finally {
1315
+ interrupted.delete(pair);
1316
+ }
1317
+ };
1318
+ const pendingTopics = db.prepare(`
1319
+ SELECT DISTINCT topic_id FROM a2a_addressed
1320
+ WHERE read_at IS NULL AND member_id IN (SELECT value FROM json_each(?))
1321
+ `);
1322
+ const wakeAll = () => {
1323
+ if (stopped || held)
1324
+ return;
1325
+ for (const pair of interrupted.keys())
1326
+ recover(pair);
1327
+ const recipients = members.list().filter((member) => usable(member.id)).map((member) => member.id);
1328
+ const pending = pendingTopics.all(JSON.stringify(recipients));
1329
+ const affected = new Set(pending.map(({ topic_id }) => topic_id));
1330
+ for (const queue of retryQueue.values())
1331
+ affected.add(queue[0].topicId);
1332
+ for (const id of affected)
1333
+ void wake(id);
1334
+ };
1335
+ const stream = (live, index, delta) => {
1336
+ const raw = live.parts[index];
1337
+ const pending = raw.type === 'text' && index >= (pendingFrom(live) ?? Infinity);
1338
+ if (pending && delta !== undefined)
1339
+ return;
1340
+ const part = pending ? pendingText : raw;
1341
+ pushTurn(live, 'turn.stream', {
1342
+ topicId: live.topicId, turnId: live.turnId, messageId: live.messageId, index: (live[priorReply]?.parts.length ?? 0) + index,
1343
+ ...(delta !== undefined && 'text' in part ? { delta, offset: part.text.length - delta.length } : { part }),
1344
+ });
1345
+ };
1346
+ const revealText = (live, message) => {
1347
+ delete message.prefix;
1348
+ for (let i = message.start; i < live.parts.length; i++) {
1349
+ if (live.parts[i].type === 'text')
1350
+ stream(live, i);
1351
+ }
1352
+ };
1353
+ const liveView = (live) => {
1354
+ const previous = live[priorReply];
1355
+ const parts = publishedParts(live);
1356
+ if (parts === live.parts && !previous)
1357
+ return live;
1358
+ return { ...live, parts: replyParts(live, parts), priorParts: previous?.parts.length };
1359
+ };
1360
+ const onEvent = (topicId, memberId, event, adapter) => {
1361
+ if (stopped)
1362
+ return;
1363
+ const k = key(topicId, memberId);
1364
+ if (event.type === 'turn_start') {
1365
+ if (canWake(topicId) && !held && !running.has(k) && !interrupted.has(k) && !turnById.get(event.turn)) {
1366
+ openTurn(topicId, memberId, 'self', 0, { turnId: event.turn, client: adapter });
1367
+ }
1368
+ return;
1369
+ }
1370
+ const live = running.get(k);
1371
+ // Some clients only tell us their session after accepting the prompt. A replacement starts its own usage.
1372
+ if (event.type === 'session' && live) {
1373
+ const { session_id: previous } = db.prepare('SELECT session_id FROM a2a_turns WHERE id = ?').get(live.turnId);
1374
+ if (previous !== event.id) {
1375
+ if (previous) {
1376
+ delete live.usage;
1377
+ db.prepare('UPDATE a2a_turns SET session_id = ?, usage = NULL WHERE id = ?').run(event.id, live.turnId);
1378
+ }
1379
+ else
1380
+ db.prepare('UPDATE a2a_turns SET session_id = ? WHERE id = ?').run(event.id, live.turnId);
1381
+ }
1382
+ return;
1383
+ }
1384
+ if (!live || !('turn' in event) || (event.turn !== undefined && event.turn !== live.turnId))
1385
+ return;
1386
+ if (event.turn !== undefined)
1387
+ markDispatched(live);
1388
+ if (event.type === 'model') {
1389
+ const alias = event.configuredModel?.trim();
1390
+ if (alias && live[configuredModel])
1391
+ live[configuredModel] = alias;
1392
+ const model = event.model.trim();
1393
+ if (!model || live.model === model)
1394
+ return;
1395
+ saveTurnModel.run(model, live.turnId);
1396
+ live.model = model;
1397
+ pushTurn(live, 'turn.model', { topicId, turnId: live.turnId, messageId: live.messageId, model });
1398
+ return;
1399
+ }
1400
+ if (event.type === 'usage') {
1401
+ // Usage reported while a session loads belongs to the instance, before it has a turn.
1402
+ if (event.turn === undefined && live.origin === 'host' && live.dispatchedAt === undefined)
1403
+ return;
1404
+ live.usage = { ...live.usage, ...event.usage };
1405
+ db.prepare('UPDATE a2a_turns SET usage = ? WHERE id = ?').run(JSON.stringify({ ...live.usage, _inputFormat: 'inclusive' }), live.turnId);
1406
+ return;
1407
+ }
1408
+ if (event.type === 'turn_end') {
1409
+ const outcome = live.stopping && event.outcome === 'failed' ? 'canceled' : event.outcome;
1410
+ const reason = event.error ?? (live.stopping && outcome === 'canceled' ? '被手动停止' : undefined);
1411
+ finalize(live, outcome, reason, event.failure);
1412
+ return;
1413
+ }
1414
+ const before = live.parts.length;
1415
+ let message = live[textMessage];
1416
+ const newMessage = event.type === 'text' && (!message || event.message !== message.id);
1417
+ const closesMessage = newMessage && !!message;
1418
+ if (event.type === 'text' && newMessage) {
1419
+ if (message) {
1420
+ if (message.prefix !== undefined)
1421
+ revealText(live, message);
1422
+ checkpoint(live);
1423
+ }
1424
+ message = live[textMessage] = { id: event.message, start: before, prefix: '' };
1425
+ }
1426
+ const changed = foldEvent(live.parts, event, event.type === 'text' && message?.start === before);
1427
+ let revealedFrom;
1428
+ if (event.type === 'text' && message?.prefix !== undefined) {
1429
+ // Unnumbered clients still match the turn's text projection, with paragraph breaks between its parts.
1430
+ if (message.id === undefined && changed && changed.delta === undefined && message.prefix)
1431
+ message.prefix += '\n\n';
1432
+ message.prefix = (message.prefix + event.delta).trimStart();
1433
+ if (!NO_REPLY.startsWith(message.prefix.trimEnd())) {
1434
+ revealText(live, message);
1435
+ revealedFrom = message.start;
1436
+ }
1437
+ }
1438
+ if (!changed)
1439
+ return;
1440
+ const part = live.parts[changed.index];
1441
+ if (event.type === 'tool' && (changed.index === before || event.phase === 'end')) {
1442
+ checkpoint(live);
1443
+ }
1444
+ else if (part.type === 'text' || part.type === 'thinking') {
1445
+ // Keep the unfinished tail in memory. A blank line can straddle two deltas.
1446
+ const added = changed.delta ?? part.text;
1447
+ const end = added.includes('\n') ? paragraphEnd(part.text, part.text.length - added.length) : 0;
1448
+ if (end) {
1449
+ checkpoint(live, [...live.parts.slice(0, -1), { ...part, text: part.text.slice(0, end) }]);
1450
+ }
1451
+ else if (changed.index === before && !closesMessage) {
1452
+ const previous = live.parts[before - 1];
1453
+ if (previous?.type === 'text' || previous?.type === 'thinking' || (revealedFrom ?? before) < before) {
1454
+ checkpoint(live, live.parts.slice(0, -1));
1455
+ }
1456
+ }
1457
+ }
1458
+ if (revealedFrom === undefined)
1459
+ stream(live, changed.index, changed.delta);
1460
+ };
1461
+ ctx.on('instance.event', ({ topicId, memberId, event, adapter }) => onEvent(topicId, memberId, event, adapter));
1462
+ const whenIdle = (topicId, memberId, timeoutMs) => new Promise((resolve) => {
1463
+ const k = key(topicId, memberId);
1464
+ if (!running.has(k))
1465
+ return resolve(true);
1466
+ const timer = setTimeout(() => resolve(false), timeoutMs);
1467
+ idleWaiters.set(k, [...(idleWaiters.get(k) ?? []), () => (clearTimeout(timer), resolve(true))]);
1468
+ });
1469
+ // A turn is recorded before dispatch. Group and filter it with the current session while its session ID is still pending.
1470
+ const preparingSessions = (topicId) => {
1471
+ const preparing = {};
1472
+ for (const live of running.values()) {
1473
+ if (live.topicId !== topicId)
1474
+ continue;
1475
+ const sessionId = instances.session(topicId, live.memberId);
1476
+ if (sessionId)
1477
+ preparing[live.turnId] = sessionId;
1478
+ }
1479
+ return JSON.stringify(preparing);
1480
+ };
1481
+ const send = (input, { returning, recordChange } = {}) => {
1482
+ const { topicId, from, targets: given, replyTo, quote, thread, attachments, fromTopic, fromThread, summary, visibility: requested } = input;
1483
+ const sender = from.kind === 'member' ? members.get(from.id) : undefined;
1484
+ const plugin = sender?.kind === 'plugin';
1485
+ if (plugin && !members.isRegisteredSender(from))
1486
+ throw new HttpError(403, '插件成员未登记或已经停用');
1487
+ const external = plugin || from.kind === 'system';
1488
+ const explicitOnly = plugin || (from.kind === 'system' && input.parts?.some((part) => part.type === 'excerpt'));
1489
+ let { content } = input;
1490
+ if (typeof content !== 'string')
1491
+ throw new HttpError(400, '消息正文需要文字');
1492
+ if (external)
1493
+ content = cleanExternalText(content);
1494
+ if (attachments !== undefined && !Array.isArray(attachments))
1495
+ throw new HttpError(400, '附件列表无效');
1496
+ if (returning) {
1497
+ content = content.trim();
1498
+ if (!content && !attachments?.length)
1499
+ throw new HttpError(400, '消息不能为空');
1500
+ }
1501
+ const parts = input.parts && cleanIncomingParts(input.parts, external);
1502
+ const topic = topics.get(topicId);
1503
+ if (!topic || topic.deletedAt)
1504
+ throw new Error(`没有这个 topic:${topicId}`);
1505
+ if (topic.archivedAt !== null)
1506
+ throw new HttpError(409, '主题已归档');
1507
+ if (attachments?.length) {
1508
+ for (const item of attachments) {
1509
+ if (typeof item === 'string') {
1510
+ if (plugin || !messages.attachment(topicId, item)?.file) {
1511
+ throw new HttpError(400, '附件须属于当前主题且可读取');
1512
+ }
1513
+ }
1514
+ else if (item && typeof item === 'object' && typeof item.name === 'string' && item.data instanceof Uint8Array) {
1515
+ if (item.data.byteLength > MAX_ATTACHMENT_BYTES)
1516
+ throw new HttpError(413, '太大了:一次最多 100 MB');
1517
+ }
1518
+ else {
1519
+ throw new HttpError(400, '附件需要提供文件名和二进制内容');
1520
+ }
1521
+ }
1522
+ }
1523
+ const incoming = plugin && sender.needsHandling === true;
1524
+ const { agent, source, live } = outgoingTurn(from, fromTopic, topicId);
1525
+ if (source && fromThread !== undefined) {
1526
+ const head = messages.stored(fromThread);
1527
+ if (head?.topicId !== source.id || head.thread !== null)
1528
+ throw new HttpError(400, `来源主题里没有这栋楼:${fromThread}`);
1529
+ }
1530
+ const liveScope = live?.[replyVisibility];
1531
+ const answered = returning?.source ?? (replyTo === undefined ? undefined
1532
+ : messages.forMember(from.id).get(replyTo) ?? (live?.read.includes(replyTo) ? messages.stored(replyTo) : undefined));
1533
+ const threadable = input.threadable ?? (plugin && !members.acceptsDelivery(from.id) ? false : undefined);
1534
+ if (replyTo !== undefined && answered?.topicId !== topicId)
1535
+ throw new Error(`这个主题里没有这条消息:${replyTo}`);
1536
+ const floor = quote ? undefined : answered ? floorOf(answered) : thread;
1537
+ if (floor !== undefined && !answered) {
1538
+ // An already scheduled message keeps its floor even when the head has since been deleted.
1539
+ const head = messages.stored(floor, { includeDeleted: true });
1540
+ if (head?.topicId !== topicId || head.thread !== null)
1541
+ throw new Error(`这个主题里没有这栋楼:${floor}`);
1542
+ }
1543
+ let visibility = returning ? returning.source.visibility : requested ?? (visibleTo(liveScope) ? answered?.visibility ?? liveScope : liveScope);
1544
+ const replyScope = plugin && Array.isArray(answered?.visibility) ? answered.visibility : undefined;
1545
+ if (replyScope && requested !== undefined && requested !== 'shadow') {
1546
+ visibility = replyScope.filter((id) => visibleTo(requested, id));
1547
+ }
1548
+ const person = sender?.kind === 'person';
1549
+ // Replies from an IM carry a parsed list, even when it is empty. A plugin can acknowledge a
1550
+ // delivery on the same floor by omitting the list.
1551
+ const findNext = !source && ((person && given === undefined) || (incoming && !given?.length && (!returning || given !== undefined)));
1552
+ const explicit = given ?? (explicitOnly && !findNext ? [] : undefined);
1553
+ const targets = replyScope && visibility === 'shadow' ? explicit?.filter((id) => replyScope.includes(id)) : explicit;
1554
+ const { to, note: routingNote } = sendRecipients(topic, { ...input, targets }, visibility, !!source, findNext ? () => conversationTargets(topic, from, content, answered) : undefined);
1555
+ const note = routingNote ?? (person && !to.length && given?.length !== 0 ? '没有可投递的成员。请先添加成员,或从 @ 菜单选择成员。' : undefined);
1556
+ // An unquoted message counts from the turn running in the topic the agent says it in.
1557
+ const relayDepth = agent || returning ? handOver(live, to, replyTo) : undefined;
1558
+ const authority = relayDepth ? authorityFor(live, from.id, answered) : null;
1559
+ if (relayDepth?.tooDeep) {
1560
+ const originThread = source ? fromThread ?? live?.thread : floor ?? live?.thread;
1561
+ const originMessage = input.sourceIds?.length === 1 ? input.sourceIds[0]
1562
+ : source && fromThread && fromThread !== live?.thread ? fromThread : answered?.id ?? live?.replyTo ?? originThread;
1563
+ const id = handoffs.record({
1564
+ kind: source ? 'relay' : 'post', authority, from: from.id, sourceTopicId: source?.id ?? topicId,
1565
+ sourceMessageId: originMessage, sourceIds: input.sourceIds, sourceThread: originThread, topicId, thread: floor, replyTo, turnId: live?.turnId,
1566
+ blocked: to, delivered: [], content, visibility, depth: relayDepth.depth,
1567
+ }, liveScope);
1568
+ throw depthError(id);
1569
+ }
1570
+ if (person && topic.title === '新主题') {
1571
+ // Only an accepted message can name the topic.
1572
+ const line = content.trim().split(/\r?\n/)[0];
1573
+ const called = stripMentionMarks(line.replace(/^(?:@[^\s\u2063]+\u2063\s*)+/, '')).slice(0, 40);
1574
+ if (called)
1575
+ topics.update(topicId, { title: called });
1576
+ }
1577
+ const current = live && sameVisibility(visibility, liveScope) ? live : undefined;
1578
+ // The receipt rides on the running reply when it is said on that reply's floor; elsewhere it is a line of its own.
1579
+ const carrier = current && (fromThread === undefined || fromThread === current.thread) ? current : undefined;
1580
+ const relay = source && { topic: source, receiptId: carrier?.messageId ?? newId('msg'), thread: fromThread ?? live?.thread };
1581
+ const settleUnread = !!(agent && !relay && !quote && replyTo && answered && sameVisibility(answered.visibility, visibility)
1582
+ && isUnreadAddressed.get(topicId, from.id, replyTo) !== undefined);
1583
+ const claim = !relay && !quote && replyTo
1584
+ && (current?.read.includes(replyTo) || current?.[independent].claimed.has(replyTo)
1585
+ || current?.[independent].outsideRead.has(replyTo) || settleUnread) ? replyTo : undefined;
1586
+ const publishChange = (published) => {
1587
+ if (relayDepth) {
1588
+ setDepth(published.id, relayDepth.depth);
1589
+ handoffs.inherit(published.id, authority);
1590
+ }
1591
+ if (settleUnread)
1592
+ read(from.id, [replyTo]);
1593
+ recordChange?.(published);
1594
+ };
1595
+ const written = [];
1596
+ let message;
1597
+ try {
1598
+ const storedAttachments = attachments?.length
1599
+ ? attachments.map((item) => {
1600
+ if (typeof item === 'string')
1601
+ return item;
1602
+ const saved = messages.saveAttachment(topicId, item.name, item.data);
1603
+ written.push(saved.path);
1604
+ return saved.path;
1605
+ })
1606
+ : undefined;
1607
+ // Said is said: the message is in the channel at once. Who it asks decides who is woken to read it.
1608
+ message = messages.publish({
1609
+ ...(returning && { id: returning.replyId }),
1610
+ topicId, from, content: person ? stripMentionMarks(content) : content, to, visibility,
1611
+ ...(replyTo ? { replyTo } : {}), ...(floor ? { thread: floor } : {}),
1612
+ ...(threadable !== undefined ? { threadable } : {}), ...(storedAttachments ? { attachments: storedAttachments } : {}),
1613
+ parts: relay ? [...(parts ?? []), {
1614
+ type: 'reference', dir: 'in', address: address.message(relay.topic.id, relay.receiptId), title: relay.topic.title,
1615
+ }] : parts,
1616
+ ...(note ? { note } : {}), ...(returning ? { read: [returning.source.id] } : claim ? { read: [claim] } : {}),
1617
+ }, publishChange);
1618
+ }
1619
+ catch (error) {
1620
+ for (const path of written)
1621
+ rmSync(join(topic.dir, path), { force: true });
1622
+ throw error;
1623
+ }
1624
+ let local = relay ? undefined : message;
1625
+ if (relay) {
1626
+ const ref = {
1627
+ type: 'reference', dir: 'out', address: address.message(topicId, message.id), title: topic.title,
1628
+ recipients: to.map((id) => members.get(id)?.name ?? id), summary: relayBrief(content, summary),
1629
+ };
1630
+ if (carrier) {
1631
+ a2a.reviseReply(carrier.topicId, carrier.memberId, carrier.turnId, (parts) => [...parts, ref]);
1632
+ }
1633
+ else {
1634
+ local = messages.publish({
1635
+ id: relay.receiptId, topicId: relay.topic.id, from, visibility, thread: relay.thread, content: '', parts: [ref],
1636
+ });
1637
+ }
1638
+ }
1639
+ if (settleUnread) {
1640
+ current?.[independent].outsideRead.add(replyTo);
1641
+ channelUpdated(topicId);
1642
+ }
1643
+ if (current) {
1644
+ if (local)
1645
+ current[independent].posted.push(local.id);
1646
+ if (claim && current.read.includes(claim)) {
1647
+ current[independent].claimed.add(claim);
1648
+ current.read = current.read.filter((id) => id !== claim);
1649
+ messages.setReplyRead(current.messageId, current.read);
1650
+ }
1651
+ }
1652
+ void wake(topicId);
1653
+ return { message, targets: to };
1654
+ };
1655
+ const handoffs = blockedHandoffs(ctx, {
1656
+ worksIn: (topicId, memberId) => worksIn(topicId)(memberId),
1657
+ running: (turnId) => [...running.values()].some((turn) => turn.turnId === turnId),
1658
+ send: (input, recordChange) => send(input, { recordChange }).message, setDepth,
1659
+ ack(memberId, receipt) {
1660
+ if (read(memberId, [receipt.messageId]).length)
1661
+ queueMicrotask(() => { if (!stopped)
1662
+ channelUpdated(receipt.topicId); });
1663
+ },
1664
+ received: (message) => isReadAddressed.get(message.topicId, message.to[0], message.id) !== undefined,
1665
+ });
1666
+ const a2a = {
1667
+ blockedHandoffs: handoffs.blockedHandoffs, claimBlockedHandoff: handoffs.claimBlockedHandoff,
1668
+ returnBlockedHandoff: handoffs.returnBlockedHandoff, resolveBlockedHandoff: handoffs.resolveBlockedHandoff,
1669
+ worksIn: (topicId, memberId) => worksIn(topicId)(memberId),
1670
+ recentContacts, pending,
1671
+ *turnSummaries(topicId) {
1672
+ const rows = db.prepare(`SELECT id, member_id, status, reply_id, error, started_at, ended_at, session_id, usage
1673
+ FROM a2a_turns WHERE topic_id = ? ORDER BY started_at DESC, rowid DESC`);
1674
+ for (const row of rows.iterate(topicId)) {
1675
+ yield { memberId: row.member_id, turn: readTurnSummary(row), usage: readUsage(row) };
1676
+ }
1677
+ },
1678
+ *settledUsage(from, until) {
1679
+ for (const row of settledBills.iterate(from, until)) {
1680
+ const failure = row.trace_failure;
1681
+ const modelMismatch = row.trace_model_mismatch;
1682
+ yield {
1683
+ id: row.id, topicId: row.topic_id, memberId: row.member_id,
1684
+ sessionId: row.session_id, model: row.model ?? null,
1685
+ status: row.status === 'interrupted' ? 'failed' : row.status,
1686
+ replyId: row.reply_id, startedAt: row.started_at,
1687
+ endedAt: row.ended_at, usage: readUsage(row), client: row.client,
1688
+ ...(failure ? { failure } : {}),
1689
+ ...(modelMismatch ? { modelMismatch } : {}),
1690
+ };
1691
+ }
1692
+ },
1693
+ lastModel(memberId) {
1694
+ const row = latestMemberModel.get(memberId);
1695
+ const model = typeof row?.model === 'string' && row.model.trim() ? row.model.trim() : null;
1696
+ return model ? { model, turnId: row.id, at: row.at } : null;
1697
+ },
1698
+ turnModel(turnId) {
1699
+ const row = modelOfTurn.get(turnId);
1700
+ return typeof row?.model === 'string' && row.model.trim() ? row.model.trim() : null;
1701
+ },
1702
+ checkNewTopicSend(input, defaultMember) {
1703
+ const { agent, source, live } = outgoingTurn(input.from, input.fromTopic);
1704
+ const { to } = sendRecipients({ defaultMember }, input, input.visibility ?? live?.[replyVisibility], !!source);
1705
+ if (agent && handOver(live, to).tooDeep)
1706
+ throw depthError();
1707
+ },
1708
+ send,
1709
+ checkTargets(topicId, targets) {
1710
+ for (const id of targets) {
1711
+ const member = members.get(id);
1712
+ if (!member)
1713
+ throw new Error(`成员已经不在了:${id}`);
1714
+ if (!member.enabled)
1715
+ throw new Error(`成员 ${member.name} 停用了`);
1716
+ if (!members.canReceive(id))
1717
+ throw new Error(`成员 ${member.name} 未声明接收消息`);
1718
+ if (!worksIn(topicId)(id))
1719
+ throw new Error(`成员 ${member.name} 不在这个主题的成员里`);
1720
+ }
1721
+ },
1722
+ replyToDelivery(sender, credential, content, targets, attachments) {
1723
+ const memberId = sender.id;
1724
+ if (!members.isRegisteredSender(sender) || !members.receiver(memberId) || stopped) {
1725
+ throw new HttpError(403, '回复凭据不属于这个插件成员');
1726
+ }
1727
+ if (typeof credential !== 'string')
1728
+ throw new HttpError(400, '需要回复凭据');
1729
+ const grant = redeemGrant.get(credential, memberId);
1730
+ if (!grant)
1731
+ throw new HttpError(403, '回复凭据不属于这个插件成员');
1732
+ const source = messages.stored(grant.messageId);
1733
+ if (!source || !canWake(grant.topicId) || !worksIn(grant.topicId)(memberId) || !deliveryVisible(source, memberId)) {
1734
+ throw new HttpError(409, '这次投递已不能回复');
1735
+ }
1736
+ const already = messages.stored(grant.replyId, { includeDeleted: true });
1737
+ if (already)
1738
+ return already;
1739
+ const { message } = send({
1740
+ topicId: grant.topicId, from: sender, content, targets, attachments, replyTo: source.id,
1741
+ }, { returning: { source, replyId: grant.replyId } });
1742
+ markDelivered(source, memberId);
1743
+ return message;
1744
+ },
1745
+ unread: (topicId) => everyone().flatMap((m) => {
1746
+ const postponed = running.get(key(topicId, m.id))?.[deferred];
1747
+ return waiting(topicId, m.id).map((message) => ({
1748
+ messageId: message.id, memberId: m.id, from: message.from, ...(postponed?.has(message.id) ? { deferred: true } : {}),
1749
+ }));
1750
+ }),
1751
+ unreadCount,
1752
+ unreadCounts,
1753
+ live: (topicId) => [...running.values()].filter((t) => t.topicId === topicId).map(liveView),
1754
+ queuedRetries(topicId, viewerId) {
1755
+ const history = messages.forMember(viewerId);
1756
+ return [...retryQueue.values()].flat()
1757
+ .filter((request) => request.topicId === topicId && history.get(request.replyId))
1758
+ .map((request) => queuedRetry(request, viewerId));
1759
+ },
1760
+ hold(on) {
1761
+ held = on;
1762
+ if (!on)
1763
+ wakeAll();
1764
+ },
1765
+ appendDuringHold({ topicId, memberId, turnId }, input) {
1766
+ const live = running.get(key(topicId, memberId));
1767
+ if (stopped || !held || live?.turnId !== turnId || !instances.canAppend(topicId, memberId))
1768
+ return;
1769
+ const { message, targets } = send({ ...input, topicId, targets: [memberId], thread: live.thread, visibility: live[replyVisibility] });
1770
+ if (!targets.includes(memberId))
1771
+ return;
1772
+ const batch = [message];
1773
+ const member = members.get(memberId);
1774
+ const prepare = prepareInput({ topicId, member, messages: batch, append: true }, batch);
1775
+ void prepare().then(async (text) => {
1776
+ if (held && pending({ topicId, memberId }).some(({ messageId }) => messageId === message.id)
1777
+ && await appendInput(live, batch, text))
1778
+ channelUpdated(topicId);
1779
+ }).catch((error) => log('a2a', `append to ${member.name} failed`, errorText(error)));
1780
+ return message;
1781
+ },
1782
+ async readNow(topicId, memberId) {
1783
+ if (topics.isArchived(topicId))
1784
+ throw new HttpError(409, '主题已归档');
1785
+ if (!worksIn(topicId)(memberId))
1786
+ throw new HttpError(409, '这个成员不在这个主题的成员名单里');
1787
+ if (running.has(key(topicId, memberId))) {
1788
+ await a2a.stop(topicId, memberId);
1789
+ if (!(await whenIdle(topicId, memberId, 10_000)))
1790
+ await a2a.stop(topicId, memberId, { force: true });
1791
+ }
1792
+ await wake(topicId);
1793
+ },
1794
+ async stop(topicId, memberId, { force = false } = {}) {
1795
+ const targets = memberId === undefined
1796
+ ? [...new Set([...running.values()].filter((turn) => turn.topicId === topicId).map((turn) => turn.memberId))]
1797
+ : [memberId];
1798
+ const stops = [];
1799
+ for (const target of targets) {
1800
+ const live = running.get(key(topicId, target));
1801
+ if (live)
1802
+ live.stopping = true;
1803
+ if (!force) {
1804
+ const interrupted = instances.interrupt(topicId, target);
1805
+ if (interrupted) {
1806
+ if (live && running.get(key(topicId, target)) === live)
1807
+ checkpoint(live);
1808
+ stops.push(interrupted);
1809
+ continue;
1810
+ }
1811
+ if (!live)
1812
+ continue;
1813
+ }
1814
+ stops.push(cancel({ topicId, memberId: target }, force ? '被手动强制结束' : '被手动停止', !force));
1815
+ }
1816
+ await Promise.all(stops);
1817
+ },
1818
+ retry(topicId, replyId, turnId) {
1819
+ const target = retryTarget(topicId, replyId, turnId);
1820
+ if (target instanceof HttpError)
1821
+ throw target;
1822
+ const memberId = target.member.id, pair = key(topicId, memberId);
1823
+ const active = running.has(pair);
1824
+ const queue = retryQueue.get(pair);
1825
+ if (active || queue) {
1826
+ const existing = queue?.find((request) => request.replyId === replyId && request.turnId === turnId);
1827
+ if (existing)
1828
+ return { queued: queuedRetry(existing, OWNER_ID), mode: 'replay' };
1829
+ const request = { topicId, memberId, replyId, turnId, queuedAt: Date.now() };
1830
+ if (queue)
1831
+ queue.push(request);
1832
+ else
1833
+ retryQueue.set(pair, [request]);
1834
+ const queued = queuedRetry(request, OWNER_ID);
1835
+ ctx.runtime.emit('turn.retryQueued', request);
1836
+ channelUpdated(topicId);
1837
+ if (!active)
1838
+ void wake(topicId);
1839
+ return { queued, mode: 'replay' };
1840
+ }
1841
+ const { live, mode } = deliver(topicId, target.member, target);
1842
+ return { turn: withDeletedRefs(messages, [liveView(live)])[0], mode };
1843
+ },
1844
+ claimInterrupted(pairs, notice) {
1845
+ return pairs.flatMap((pair) => {
1846
+ const recovery = interrupted.get(key(pair.topicId, pair.memberId));
1847
+ if (!recovery || (pair.turnId && recovery.turn.id !== pair.turnId))
1848
+ return [];
1849
+ recovery.notice = notice;
1850
+ return [recovery.turn];
1851
+ });
1852
+ },
1853
+ reviseReply(topicId, memberId, turnId, revise) {
1854
+ const live = running.get(key(topicId, memberId));
1855
+ if (!live || live.turnId !== turnId)
1856
+ return;
1857
+ live.parts = revise(live.parts);
1858
+ live[revisedReply] = true;
1859
+ const snapshot = replyParts(live, publishedParts(live));
1860
+ return messages.revise(live.messageId, { content: textOf(snapshot), parts: snapshot }, () => saveTrace.run(JSON.stringify(savedTraceOf(live)), live.turnId));
1861
+ },
1862
+ markRead(topicId, memberId, messageId) {
1863
+ let count = 0;
1864
+ store.tx(() => {
1865
+ const ids = messageId === undefined ? waiting(topicId, memberId).map((m) => m.id)
1866
+ : typeof messageId === 'string' ? [messageId] : messageId;
1867
+ const taken = read(memberId, ids);
1868
+ count = taken.length;
1869
+ if (messageId === undefined)
1870
+ setCursor(topicId, memberId, messages.lastSeq(topicId));
1871
+ const live = running.get(key(topicId, memberId));
1872
+ if (live) {
1873
+ const visibility = live[replyVisibility];
1874
+ const sameFloor = [];
1875
+ for (const id of taken) {
1876
+ const m = messages.stored(id);
1877
+ if (!m || !sameVisibility(m.visibility, visibility))
1878
+ continue;
1879
+ if (floorOf(m) === live.thread)
1880
+ sameFloor.push(id);
1881
+ else
1882
+ live[independent].outsideRead.add(id);
1883
+ }
1884
+ alsoRead(live, sameFloor);
1885
+ }
1886
+ });
1887
+ channelUpdated(topicId);
1888
+ return count;
1889
+ },
1890
+ markCovered(topicId, memberId, floor, shown) {
1891
+ const live = running.get(key(topicId, memberId));
1892
+ if (!live || live.thread !== floor || live.dispatchedAt === undefined)
1893
+ return;
1894
+ const progress = floorProgress(topicId, memberId, floor);
1895
+ const seq = coveredThrough(topicId, memberId, floor, progress, shown);
1896
+ if (seq > (live[deliveredFloor]?.seq ?? 0)) {
1897
+ live[deliveredFloor] = { floor, seq };
1898
+ saveTrace.run(JSON.stringify(savedTraceOf(live)), live.turnId);
1899
+ }
1900
+ },
1901
+ defer(topicId, memberId, messageIds) {
1902
+ const live = running.get(key(topicId, memberId));
1903
+ if (!live)
1904
+ throw new Error('当前没有进行中的回合,不能延后消息');
1905
+ const ids = [...new Set(messageIds.map(String).filter(Boolean))];
1906
+ if (!ids.length)
1907
+ throw new Error('至少传一条要延后的消息编号');
1908
+ for (const id of ids) {
1909
+ if (id === live.replyTo)
1910
+ throw new Error(`${id} 是唤醒本轮的触发消息,不能延后;请先完成本轮处理`);
1911
+ if (!live.read.includes(id) && !live[deferred].has(id))
1912
+ throw new Error(`本轮未读到这条消息,不能延后:${id}`);
1913
+ }
1914
+ const toDefer = ids.filter((id) => live.read.includes(id));
1915
+ if (toDefer.length) {
1916
+ const markUnread = db.prepare('UPDATE a2a_addressed SET read_at = NULL WHERE topic_id = ? AND message_id = ? AND member_id = ?');
1917
+ const insertRow = db.prepare('INSERT OR REPLACE INTO a2a_addressed (topic_id, message_id, member_id, seq, read_at) VALUES (?, ?, ?, ?, NULL)');
1918
+ store.tx(() => {
1919
+ for (const id of toDefer) {
1920
+ if (markUnread.run(topicId, id, memberId).changes === 0) {
1921
+ insertRow.run(topicId, id, memberId, messages.stored(id)?.seq ?? 0);
1922
+ }
1923
+ }
1924
+ live.read = live.read.filter((id) => !toDefer.includes(id));
1925
+ messages.setReplyRead(live.messageId, live.read);
1926
+ });
1927
+ for (const id of toDefer)
1928
+ live[deferred].add(id);
1929
+ channelUpdated(topicId);
1930
+ }
1931
+ return { deferred: ids, remaining: live.read.length };
1932
+ },
1933
+ withReplyModels,
1934
+ turns(topicId, opts = {}) {
1935
+ const { memberId = null, turnId = null, sessionId, withoutSession, limit = 50, summary = false } = typeof opts === 'number' ? { limit: opts } : opts;
1936
+ if (sessionId !== undefined) {
1937
+ if (withoutSession)
1938
+ throw new HttpError(400, 'sessionId 与 withoutSession 不能同时使用');
1939
+ if (!sessionId.trim())
1940
+ throw new HttpError(400, 'sessionId 不能为空');
1941
+ }
1942
+ const preparing = sessionId !== undefined || withoutSession ? preparingSessions(topicId) : '{}';
1943
+ const rows = (summary ? filteredTurnPreviews : filteredTurns).all(preparing, topicId, memberId, memberId, turnId, turnId, sessionId ?? null, sessionId ?? null, withoutSession ? 1 : 0, limit);
1944
+ return rows.map(summary ? readTurnPreview : readTurn);
1945
+ },
1946
+ };
1947
+ ctx.point('turn.init', { title: '组装这一轮的输入', group: '每一轮', about: '把同一位置的待读消息交给成员,带上下一批待读之前最近的旁观消息,组装成这一轮发给它的文字。', order: 30 });
1948
+ ctx.point('turn.ended', { title: '回合结束', group: '每一轮', about: '成员的一轮落定之后,插件可以在这里做后续的事。静默结束的回合只带执行记录。', order: 50 });
1949
+ ctx.effect(topics.status.source('unread', (ids) => unreadCounts(OWNER_ID, ids)));
1950
+ ctx.effect(topics.status.source('running', (ids) => {
1951
+ const active = new Map();
1952
+ const add = ({ topicId, memberId }) => {
1953
+ if (ids && !ids.has(topicId))
1954
+ return;
1955
+ const people = active.get(topicId) ?? new Set();
1956
+ people.add(memberId);
1957
+ active.set(topicId, people);
1958
+ };
1959
+ for (const turn of running.values())
1960
+ add(turn);
1961
+ for (const instance of instances.list())
1962
+ if (instance.busy)
1963
+ add(instance);
1964
+ return new Map([...active].map(([id, people]) => [id, [...people].sort()]));
1965
+ }));
1966
+ const statusRunning = (id) => topics.status.refresh('running', id);
1967
+ ctx.on('turn.started', ({ turn }) => statusRunning(turn.topicId));
1968
+ ctx.on('turn.ended', ({ turn }) => statusRunning(turn.topicId));
1969
+ ctx.on('instances.busy_changed', ({ topicId }) => statusRunning(topicId));
1970
+ ctx.provide('a2a', a2a);
1971
+ const visibleTurns = (turns, memberId, summary) => turns
1972
+ .filter((turn) => (turn.silent?.read ?? [turn.replyId]).every((id) => {
1973
+ const audience = messages.storedRouting(id);
1974
+ return audience && visibleTo(audience.visibility, memberId);
1975
+ }))
1976
+ .map((turn) => {
1977
+ if (summary)
1978
+ return turnPreview(turn);
1979
+ const { trace, ...record } = turn;
1980
+ return record;
1981
+ });
1982
+ const entry = ctx.get('entry');
1983
+ ctx.effect(entry.group('channel', '主题的消息、回合、草稿、收件箱和通知'));
1984
+ const topicId = { type: 'string', description: '主题编号' };
1985
+ const memberKey = { type: 'string', description: '成员编号' };
1986
+ ctx.effect(entry.op({
1987
+ name: 'channel.send', about: '在主题里发消息,也可以在指定消息下面回复或在主线上引用它。',
1988
+ input: object({
1989
+ id: topicId, content: { type: 'string', description: '消息正文' },
1990
+ attachments: { type: 'array', items: { type: 'string' }, description: '当前主题已上传或登记原件的附件路径' },
1991
+ replyTo: { type: 'string', description: '要在楼内回复的消息编号' },
1992
+ quote: { type: 'string', description: '要在主线上引用的消息编号' },
1993
+ thread: { type: 'string', description: '所属楼的楼主编号' },
1994
+ targets: { ...strings, description: '显式指定收件成员的编号' },
1995
+ draftRevision: { type: 'integer', minimum: 0, description: '本次发送对应的频道草稿修订号' },
1996
+ }, ['id']),
1997
+ output: object({
1998
+ message: messageOutput, targets: strings, open: stringValue,
1999
+ draft: draftSchema,
2000
+ }, ['message', 'targets']), sdk: true,
2001
+ http: ['POST', '/api/topics/:id/messages'],
2002
+ run({ id, content: words = '', attachments = [], replyTo, quote, thread, targets, draftRevision }) {
2003
+ const content = words.trim();
2004
+ const found = requireTopic(topics, id);
2005
+ if (!content && !attachments.length)
2006
+ throw new Error('消息不能为空');
2007
+ if (targets)
2008
+ a2a.checkTargets(id, targets);
2009
+ const place = replyTo !== undefined ? { replyTo } : quote !== undefined ? { replyTo: quote, quote: true } : { thread };
2010
+ let draft, notifyDraft;
2011
+ const recordChange = draftRevision === undefined ? undefined : () => {
2012
+ const saved = topics.saveDraft(id, draftRevision, '', { afterCommit: (notify) => { notifyDraft = notify; } });
2013
+ if (!saved.conflict)
2014
+ draft = saved;
2015
+ };
2016
+ const result = send({
2017
+ topicId: found.id, from: { kind: 'member', id: OWNER_ID },
2018
+ content, targets, ...(attachments.length ? { attachments } : {}), ...place,
2019
+ }, { recordChange });
2020
+ notifyDraft?.();
2021
+ return { ...result, ...(draft && { draft }), open: address.message(id, result.message.id) };
2022
+ },
2023
+ }));
2024
+ ctx.effect(entry.op({
2025
+ name: 'channel.state', workload: 'local', about: '查看一个主题正在运行的回合及其当前内容、排队重试的回复和等成员读的消息。',
2026
+ input: object({
2027
+ id: topicId, from: { type: 'integer', minimum: 1, description: '重连时从这个序号起返回完整消息范围及近期回合' },
2028
+ view: { type: 'string', enum: ['timeline', 'floors'], description: '重连快照消息范围的视图模式,默认 timeline;floors 按楼内最新消息序号补齐整楼' },
2029
+ summary: { type: 'boolean', description: '重连快照中的历史消息和回合使用摘要;运行中的回复保留流式更新所需的片段' },
2030
+ }, ['id']), output: channelStateOutput, sdk: true,
2031
+ http: ['GET', '/api/topics/:id/state'], agent: true, topic: 'id', reach: 'any',
2032
+ run({ id, from, view: mode, summary }, caller) {
2033
+ const topic = requireTopic(topics, id);
2034
+ const memberId = caller.member?.id ?? OWNER_ID;
2035
+ const history = messages.forMember(memberId);
2036
+ return {
2037
+ live: withDeletedRefs(messages, a2a.live(topic.id).filter(({ messageId }) => history.get(messageId))),
2038
+ unread: a2a.unread(id).filter(({ messageId }) => history.get(messageId)),
2039
+ queuedRetries: a2a.queuedRetries(topic.id, memberId),
2040
+ ...(from === undefined ? {} : {
2041
+ messages: withReplyModels(messagesOut(messages, history.range(topic.id, from, mode))).map((message) => summary ? messagePreview(message) : message),
2042
+ through: messages.lastSeq(topic.id),
2043
+ turns: visibleTurns(a2a.turns(topic.id, { summary }), memberId, summary),
2044
+ }),
2045
+ };
2046
+ },
2047
+ }));
2048
+ ctx.effect(entry.op({
2049
+ name: 'channel.turns', about: '查看一个主题的回合记录,可按成员与会话筛选。',
2050
+ input: object({
2051
+ id: topicId, memberId: { ...memberKey, member: true },
2052
+ turnId: { type: 'string', description: '只读指定回合' },
2053
+ sessionId: { type: 'string', description: '只读这个会话的回合' },
2054
+ withoutSession: { type: 'boolean', description: '为 true 时只读缺少会话编号的历史回合,此时不能同时指定 sessionId' },
2055
+ limit: { type: 'integer', description: '最多读几轮,默认 50' },
2056
+ detail: { type: 'boolean', description: '在控制台打开执行轨迹,读取该轮原始输入和回复' },
2057
+ summary: { type: 'boolean', description: '省略完整输入。未要求 detail 时只读步骤计数和回复摘录;要求 detail 时保留执行步骤' },
2058
+ }, ['id']), http: ['GET', '/api/topics/:id/turns'], agent: true, topic: 'id', reach: 'any',
2059
+ run({ id, turnId, memberId, sessionId, withoutSession, limit, detail, summary }, caller) {
2060
+ const turns = a2a.turns(requireTopic(topics, id).id, { turnId, memberId, sessionId, withoutSession, limit, summary: summary && !detail });
2061
+ if (detail && !caller.member) {
2062
+ const live = new Map(a2a.live(id).map((item) => [item.turnId, item]));
2063
+ return turns.map((turn) => {
2064
+ const running = live.get(turn.id);
2065
+ const reply = messages.stored(turn.replyId);
2066
+ return { ...(summary ? turnPreview(turn, true) : turn),
2067
+ ...(reply?.turnId === turn.id ? { reply: summary ? messagePreview(reply) : reply } : {}),
2068
+ ...(running ? { live: running } : {}) };
2069
+ });
2070
+ }
2071
+ return visibleTurns(turns, caller.member?.id ?? OWNER_ID, summary);
2072
+ },
2073
+ }));
2074
+ ctx.effect(entry.op({
2075
+ name: 'channel.turn_input', about: '查看这一回合实际收到的输入原文,包括中途追加的内容。',
2076
+ input: object({ id: topicId, turnId: stringValue }, ['id', 'turnId']),
2077
+ output: object({ inputText: stringValue }, ['inputText']),
2078
+ http: ['GET', '/api/topics/:id/turns/:turnId/input'],
2079
+ run({ id, turnId }) {
2080
+ const row = turnInput.get(requireTopic(topics, id).id, turnId);
2081
+ if (!row)
2082
+ throw new HttpError(404, '回合不存在');
2083
+ return { inputText: row.input_text };
2084
+ },
2085
+ }));
2086
+ ctx.effect(entry.group('a2a', '频道消息与回合控制'));
2087
+ ctx.effect(entry.op({
2088
+ name: 'a2a.retry', about: '原位重试成员在这个主题失败或已取消的回复。成员忙时排队,空闲后自动开始。',
2089
+ input: object({
2090
+ id: topicId, replyId: { type: 'string', description: '失败或已取消的回复消息编号' },
2091
+ turnId: { type: 'string', description: '要重试的那次回合编号' },
2092
+ }, ['id', 'replyId', 'turnId']),
2093
+ http: ['POST', '/api/topics/:id/turns/:replyId/retry'], run: ({ id, replyId, turnId }) => a2a.retry(id, replyId, turnId),
2094
+ }));
2095
+ const liveTurn = (id, memberId, turnId) => a2a.live(id).some((item) => item.memberId === memberId && item.turnId === turnId);
2096
+ ctx.effect(entry.op({
2097
+ name: 'channel.stop', about: '停止主题里的回合;不传成员时停掉这个主题的全部在跑回合。force 会结束对应实例。成员提请时要带 memberId 和 turnId,经机主或其他成员会签后执行。',
2098
+ input: object({
2099
+ id: topicId,
2100
+ memberId: { type: 'string', member: true, description: '成员;不传就是主题里所有在跑的回合' },
2101
+ force: { type: 'boolean', description: '结束对应实例。只有人能用' },
2102
+ turnId: { type: 'string', description: '指定要停止的在跑回合。回合已换时返回冲突。' },
2103
+ }, ['id']),
2104
+ http: ['POST', '/api/topics/:id/stop'],
2105
+ agent: 'approve', topic: 'id', reach: 'any', named: true,
2106
+ sign: { members: 2, wait: 5 },
2107
+ targets: ({ id }) => [id],
2108
+ subjects: ({ memberId }) => (memberId ? [memberId] : []),
2109
+ stale: ({ id, memberId, turnId }) => (liveTurn(id, memberId, turnId) ? undefined : '原回合已结束'),
2110
+ validate({ memberId, turnId, force }, caller) {
2111
+ if (!caller.member)
2112
+ return;
2113
+ if (force)
2114
+ throw new ArgsError('成员不能强制结束实例:要强制结束,请人在控制台里做');
2115
+ if (!memberId || !turnId)
2116
+ throw new ArgsError('成员停回合要带 memberId 和 turnId,只停那一个回合');
2117
+ },
2118
+ approval: ({ id, memberId, turnId }) => ({
2119
+ title: '停止回合',
2120
+ target: `@${members.get(memberId)?.handle ?? memberId} 在「${topics.get(id)?.title ?? id}」的回合 ${turnId}`,
2121
+ impact: '只停这一个回合。停止后它收到新消息仍会被叫醒',
2122
+ }),
2123
+ run({ id, memberId, force, turnId }) {
2124
+ const found = requireTopic(topics, id);
2125
+ const turn = turnId === undefined ? undefined
2126
+ : a2a.live(found.id).find((item) => item.turnId === turnId && (memberId === undefined || item.memberId === memberId));
2127
+ if (turnId !== undefined && !turn)
2128
+ throw new HttpError(409, '这个回合已结束或已换回合');
2129
+ return a2a.stop(found.id, turn ? turn.memberId : memberId, { force });
2130
+ },
2131
+ }));
2132
+ ctx.effect(entry.op({
2133
+ name: 'channel.read_now', about: '让成员现在就读等着它的消息,必要时打断进行中的回合。',
2134
+ input: object({ id: topicId, memberId: memberKey }, ['id', 'memberId']),
2135
+ http: ['POST', '/api/topics/:id/read-now'], run: ({ id, memberId }) => a2a.readNow(requireTopic(topics, id).id, memberId),
2136
+ }));
2137
+ ctx.effect(entry.op({
2138
+ name: 'channel.read', about: '推进机主的频道已读位置,或只把指定的收件箱消息标为已读。',
2139
+ input: object({ id: topicId, messageId: { type: ['string', 'null'], description: '消息编号,空值推进普通频道游标' } }, ['id']), http: ['POST', '/api/topics/:id/read'],
2140
+ run({ id, messageId }) {
2141
+ requireTopic(topics, id);
2142
+ if (messageId == null) {
2143
+ const seq = messages.lastSeq(id);
2144
+ if (seq > cursorOf(id, OWNER_ID)) {
2145
+ setCursor(id, OWNER_ID, seq);
2146
+ channelUpdated(id);
2147
+ }
2148
+ return;
2149
+ }
2150
+ if (messages.forMember(OWNER_ID).get(messageId)?.topicId !== id)
2151
+ throw new HttpError(404, '这个主题里没有这条消息');
2152
+ a2a.markRead(id, OWNER_ID, messageId);
2153
+ },
2154
+ }));
2155
+ // The update event also fires when a message touches the topic, before send has recorded its depth.
2156
+ const rosters = new Map(topics.all().map((topic) => [topic.id, topic.members]));
2157
+ ctx.on('topic.updated', ({ topic }) => {
2158
+ const previous = rosters.get(topic.id);
2159
+ rosters.set(topic.id, topic.members);
2160
+ const closed = topic.deletedAt !== null || topic.archivedAt !== null;
2161
+ if (!closed && previous === topic.members)
2162
+ return;
2163
+ const admits = admittedTo(topic);
2164
+ const changed = removeQueuedRetries((request) => request.topicId === topic.id && (closed || !admits(request.memberId)));
2165
+ if (changed.size)
2166
+ channelUpdated(topic.id);
2167
+ if (closed) {
2168
+ void cancel({ topicId: topic.id }, topic.deletedAt ? '主题已删除' : '主题已归档');
2169
+ }
2170
+ else {
2171
+ void wake(topic.id);
2172
+ }
2173
+ });
2174
+ ctx.on('members.changed', ({ id, removed }) => {
2175
+ reconcileGlobalDefault();
2176
+ if (removed || !members.get(id)?.enabled) {
2177
+ for (const topicId of removeQueuedRetries((request) => request.memberId === id))
2178
+ channelUpdated(topicId);
2179
+ void cancel({ memberId: id }, '成员被移除或停用');
2180
+ }
2181
+ if (members.receiver(id) && ctx.runtime.ready) {
2182
+ const unreadTopics = new Set(pending({ memberId: id }).map(({ messageId }) => messages.stored(messageId)?.topicId));
2183
+ for (const topicId of unreadTopics)
2184
+ if (topicId)
2185
+ void wake(topicId);
2186
+ }
2187
+ });
2188
+ reconcileGlobalDefault();
2189
+ // Recover interrupted turns before handing over what was still unread, once the adapters have loaded.
2190
+ const catchUp = setTimeout(() => {
2191
+ catchUpReady = true;
2192
+ wakeAll();
2193
+ }, 1500);
2194
+ catchUp.unref();
2195
+ ctx.effect(() => clearTimeout(catchUp));
2196
+ },
2197
+ };