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,916 @@
1
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { ATTACHMENT_RECORDS, attachmentInputPath, attachmentLocation, referenceAttachment, saveAttachment } from "./attachments.js";
4
+ import { HttpError, sendUserFile } from "./entry.js";
5
+ import { OWNER_ID } from "./members.js";
6
+ import { stripMentionMarks } from "./mentions.js";
7
+ import { array, object } from "./ops.js";
8
+ import { stepSummary } from "./parts.js";
9
+ import { requireTopic } from "./topics.js";
10
+ import { messageSchema } from "./types.js";
11
+ import { log, newId } from "./util.js";
12
+ const stringValue = { type: 'string' };
13
+ const booleanValue = { type: 'boolean' };
14
+ export const deletedReferences = { replyToDeleted: booleanValue, threadDeleted: booleanValue };
15
+ const countValue = { type: 'integer', minimum: 0 };
16
+ const stepsSchema = object({ count: countValue, tools: countValue, failed: countValue }, ['count', 'tools', 'failed']);
17
+ export const messageOutput = { ...messageSchema, properties: { ...messageSchema.properties, ...deletedReferences, steps: stepsSchema, gist: stringValue, model: stringValue, modelMismatch: stringValue } };
18
+ export function messagePreview(message) {
19
+ const steps = stepSummary(message.parts);
20
+ return steps.count
21
+ ? { ...message, parts: message.parts.filter((part) => part.type !== 'tool' && part.type !== 'thinking'), steps }
22
+ : message;
23
+ }
24
+ /** Preserve the state of references even when their targets are outside the current page. */
25
+ export function withDeletedRefs(messages, items) {
26
+ const ids = new Set();
27
+ for (const { replyTo, thread } of items) {
28
+ if (replyTo)
29
+ ids.add(replyTo);
30
+ if (thread)
31
+ ids.add(thread);
32
+ }
33
+ const deleted = messages.deletedIds(ids);
34
+ if (!deleted.size)
35
+ return items;
36
+ return items.map((item) => ({
37
+ ...item,
38
+ ...(item.replyTo && deleted.has(item.replyTo) ? { replyToDeleted: true } : {}),
39
+ ...(item.thread && deleted.has(item.thread) ? { threadDeleted: true } : {}),
40
+ }));
41
+ }
42
+ const relaySentences = new Intl.Segmenter('zh', { granularity: 'sentence' });
43
+ const RELAY_LEAD = /^(?:(?:#{1,6}|[-+*]|\d+[.)])\s+|>\s*|@[^\s,,、::;;。!?!?]+[\s,,、::;;。!?!?]*)+/;
44
+ export function relayBrief(content, summary) {
45
+ const supplied = summary?.trim();
46
+ let brief = (supplied || content.trimStart().replace(RELAY_LEAD, '')).replace(/\s+/g, ' ').trim();
47
+ if (!supplied)
48
+ brief = relaySentences.segment(brief).containing(0)?.segment.trimEnd() ?? '';
49
+ const limit = supplied ? 120 : 80;
50
+ const characters = [...brief];
51
+ return characters.length > limit ? `${characters.slice(0, limit).join('')}…` : brief;
52
+ }
53
+ /** Project stored topic or message references next to the sender in a text-only channel view. */
54
+ export function referenceMark(message) {
55
+ const marks = message.parts
56
+ .filter((p) => p.type === 'reference')
57
+ .map((ref) => {
58
+ const title = ref.title.replace(/[[\]\\]/g, '\\$&');
59
+ const to = ref.recipients?.length ? ' · ' + ref.recipients.join(', ') : '';
60
+ const brief = ref.summary ? ` ${ref.summary}` : '';
61
+ return `${ref.dir === 'in' ? '↙' : '↗'} [${title}](#${ref.address})${to}${brief}`;
62
+ });
63
+ return marks.length ? ` ${marks.join(' · ')}` : '';
64
+ }
65
+ function attachmentMarks(files) {
66
+ const byMark = new Map(files.map((path) => [`[${basename(path)}]`, path]));
67
+ const exact = [...byMark.keys()].sort((a, b) => b.length - a.length).map((mark) => mark.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
68
+ return { byMark, pattern: exact.join('|') };
69
+ }
70
+ /** Keep attachment marks from crowding the message's opening words out of a short excerpt. */
71
+ export function withoutLeadingAttachments(message) {
72
+ const body = message.content.trim();
73
+ if (!message.attachments.length)
74
+ return body;
75
+ const { pattern } = attachmentMarks(message.attachments);
76
+ return body.replace(new RegExp(`^(?:(?:${pattern})\\s*)+`), '').trim() || body;
77
+ }
78
+ /** Every reader names a message in at most a line of about 60 characters; the rest of a long reply stays out of the gist. */
79
+ const GIST_LIMIT = 200;
80
+ /**
81
+ * The words that stand for a message when it is named in a few of them (a floor head, a quoted reply). A member's
82
+ * reply that worked through tools opens with what it set out to do ("let me read the RFC first") and ends with what
83
+ * it found, so its last piece of text stands for it. A trailing NO_REPLY is a control word, not something said.
84
+ */
85
+ export function messageGist(message) {
86
+ const said = message.parts.flatMap((part) => {
87
+ const text = part.type === 'text' ? part.text.trim() : '';
88
+ return text && text !== 'NO_REPLY' ? [text] : [];
89
+ });
90
+ const gist = said.length > 1 ? said[said.length - 1] : withoutLeadingAttachments(message);
91
+ return [...gist.slice(0, GIST_LIMIT * 2)].slice(0, GIST_LIMIT).join('');
92
+ }
93
+ /** A message as it leaves the host: the state of its references and the words that stand for it. */
94
+ export function messagesOut(messages, items) {
95
+ return withDeletedRefs(messages, items).map((message) => ({ ...message, gist: messageGist(message) }));
96
+ }
97
+ /** Name each referenced attachment alongside its full path. */
98
+ export function withFiles(message, dir) {
99
+ if (!message.attachments.length)
100
+ return message.content;
101
+ const { byMark, pattern } = attachmentMarks(message.attachments);
102
+ const pointed = new Set();
103
+ const text = message.content.replace(new RegExp(pattern, 'g'), (mark) => {
104
+ const path = byMark.get(mark);
105
+ pointed.add(path);
106
+ return `[${basename(path)}:${attachmentInputPath(dir, path)}]`;
107
+ });
108
+ const rest = message.attachments.filter((path) => !pointed.has(path)).map((path) => attachmentInputPath(dir, path));
109
+ return rest.length ? `${text}\n(附件:${rest.join('、')})`.trim() : text;
110
+ }
111
+ export function visibleTo(visibility, memberId) {
112
+ return visibility === undefined || visibility === 'all' || (memberId != null && Array.isArray(visibility) && visibility.includes(memberId));
113
+ }
114
+ /** May a message with this visibility appear in the background of a turn with that visibility? */
115
+ export function visibleInTurn(messageVisibility, memberId, turnVisibility) {
116
+ if (!visibleTo(messageVisibility, memberId))
117
+ return false;
118
+ if (turnVisibility === 'shadow')
119
+ return true;
120
+ if (Array.isArray(turnVisibility))
121
+ return turnVisibility.every((id) => visibleTo(messageVisibility, id));
122
+ return visibleTo(messageVisibility, null);
123
+ }
124
+ // The routing cell of older rows is just the recipient list. Keep the scope with that list in the same index.
125
+ const pack = (to, visibility) => JSON.stringify(visibility === undefined ? to : { to, visibility });
126
+ function routing(raw) {
127
+ const value = JSON.parse(raw);
128
+ return Array.isArray(value) ? { to: value } : value;
129
+ }
130
+ function* searchableText(row) {
131
+ yield row.content;
132
+ for (const part of JSON.parse(row.parts)) {
133
+ if (part.type === 'text')
134
+ yield part.text;
135
+ if (part.type === 'excerpt') {
136
+ yield part.text;
137
+ if (part.title)
138
+ yield part.title;
139
+ if (part.author)
140
+ yield part.author;
141
+ if (part.url)
142
+ yield part.url;
143
+ }
144
+ if (part.type === 'reference') {
145
+ yield part.title;
146
+ yield '#' + part.address;
147
+ yield* (part.recipients ?? []);
148
+ if (part.summary)
149
+ yield part.summary;
150
+ }
151
+ if (part.type === 'card') {
152
+ yield part.title;
153
+ if (part.body)
154
+ yield part.body;
155
+ for (const option of part.options ?? []) {
156
+ yield option.label;
157
+ if (option.detail)
158
+ yield option.detail;
159
+ }
160
+ }
161
+ }
162
+ for (const path of JSON.parse(row.attachments))
163
+ yield basename(path);
164
+ }
165
+ function searchLine(text) { return text.replace(/\s+/gu, ' ').trim(); }
166
+ function referenceExcerpt(content) {
167
+ const [first = ''] = stripMentionMarks(content).trimStart().split(/\r?\n/, 1);
168
+ if (/^(?:```|~~~|---\s*$)/.test(first))
169
+ return '';
170
+ const text = searchLine(first.replace(/^(?:(?:#{1,6}|[-+*]|\d+[.)])\s+|>\s*)+/, '')
171
+ .replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, '$1')
172
+ .replace(/(`+|\*{1,3}|__)(.+?)\1/g, '$2'));
173
+ if (/^(?:msg|plan)_[a-z0-9]+$/.test(text))
174
+ return '';
175
+ const characters = [...text];
176
+ return characters.length > 52 ? characters.slice(0, 52).join('') + '…' : text;
177
+ }
178
+ function searchExcerpt(row, pattern, matchedAuthor) {
179
+ let preview = '';
180
+ for (const text of searchableText(row)) {
181
+ const line = searchLine(text);
182
+ if (!line)
183
+ continue;
184
+ if (!preview)
185
+ preview = line;
186
+ if (!pattern)
187
+ break;
188
+ const found = pattern.exec(line);
189
+ if (!found)
190
+ continue;
191
+ const start = found.index, end = start + found[0].length;
192
+ const head = Math.max(0, start - 48), tail = end + 96;
193
+ return {
194
+ before: (head > 0 ? '…' : '') + line.slice(head, start),
195
+ match: found[0],
196
+ after: line.slice(end, tail) + (tail < line.length ? '…' : ''),
197
+ };
198
+ }
199
+ if (!pattern || matchedAuthor) {
200
+ return { before: '', match: '', after: preview.length > 150 ? preview.slice(0, 150) + '…' : preview };
201
+ }
202
+ }
203
+ export const messagesPlugin = {
204
+ name: 'messages',
205
+ core: true,
206
+ needs: ['store', 'topics', 'push', 'members', 'entry'],
207
+ start(ctx) {
208
+ const store = ctx.get('store');
209
+ const topics = ctx.get('topics');
210
+ const push = ctx.get('push');
211
+ const members = ctx.get('members');
212
+ const { db } = store;
213
+ db.function('message_visible', { deterministic: true }, (route, memberId) => Number(visibleTo(routing(route).visibility, memberId)));
214
+ const COLUMNS = ['id', 'topic_id', 'seq', 'from_kind', 'from_id', 'to_members', 'reply_to', 'thread', 'threadable', 'attachments', 'content', 'parts', 'status', 'turn_id', 'retry_of', 'note', 'terminal_reason', 'read_ids', 'created_at', 'deleted_at', 'deleted_by'];
215
+ const PARTS_COLUMNS = ['message_id', 'topic_id', 'type', 'state'];
216
+ const PART_INDEXES = ['message_parts_message', 'message_parts_lookup'];
217
+ const PART_TRIGGERS = ['messages_parts_ai', 'messages_parts_au', 'messages_parts_ad'];
218
+ const create = () => db.exec(`
219
+ CREATE TABLE messages (
220
+ id TEXT PRIMARY KEY, topic_id TEXT NOT NULL, seq INTEGER, from_kind TEXT NOT NULL, from_id TEXT NOT NULL,
221
+ to_members TEXT NOT NULL DEFAULT '[]', reply_to TEXT, thread TEXT, threadable INTEGER, attachments TEXT NOT NULL DEFAULT '[]', content TEXT NOT NULL,
222
+ parts TEXT NOT NULL DEFAULT '[]', status TEXT, turn_id TEXT, retry_of TEXT, note TEXT, terminal_reason TEXT, read_ids TEXT NOT NULL DEFAULT '[]', created_at INTEGER NOT NULL,
223
+ deleted_at INTEGER, deleted_by TEXT
224
+ );
225
+ CREATE INDEX messages_topic_seq ON messages (topic_id, seq);
226
+ CREATE INDEX messages_topic_thread_seq ON messages (topic_id, thread, seq);
227
+ CREATE TABLE message_parts (
228
+ message_id TEXT NOT NULL, topic_id TEXT NOT NULL, type TEXT NOT NULL, state TEXT
229
+ );
230
+ CREATE INDEX message_parts_message ON message_parts (message_id);
231
+ CREATE INDEX message_parts_lookup ON message_parts (type, state, topic_id, message_id);
232
+ CREATE TRIGGER messages_parts_ai AFTER INSERT ON messages BEGIN
233
+ DELETE FROM message_parts WHERE message_id = NEW.id;
234
+ INSERT INTO message_parts (message_id, topic_id, type, state)
235
+ SELECT DISTINCT NEW.id, NEW.topic_id, json_extract(part.value, '$.type'), json_extract(part.value, '$.state')
236
+ FROM json_each(NEW.parts) AS part
237
+ WHERE NEW.deleted_at IS NULL AND json_extract(part.value, '$.type') IS NOT NULL;
238
+ END;
239
+ CREATE TRIGGER messages_parts_au AFTER UPDATE OF parts, deleted_at ON messages BEGIN
240
+ DELETE FROM message_parts WHERE message_id = OLD.id;
241
+ INSERT INTO message_parts (message_id, topic_id, type, state)
242
+ SELECT DISTINCT NEW.id, NEW.topic_id, json_extract(part.value, '$.type'), json_extract(part.value, '$.state')
243
+ FROM json_each(NEW.parts) AS part
244
+ WHERE NEW.deleted_at IS NULL AND json_extract(part.value, '$.type') IS NOT NULL;
245
+ END;
246
+ CREATE TRIGGER messages_parts_ad AFTER DELETE ON messages BEGIN
247
+ DELETE FROM message_parts WHERE message_id = OLD.id;
248
+ END;
249
+ `);
250
+ const markDeleted = 'UPDATE messages SET deleted_at = ?, deleted_by = ? WHERE id = ?';
251
+ const have = db.prepare('PRAGMA table_info(messages)').all().map((c) => c.name);
252
+ const sameMessages = have.length === COLUMNS.length && COLUMNS.every((c) => have.includes(c));
253
+ /**
254
+ * The table is an index over the topics' channel files. When it is missing or has another shape (a new
255
+ * data directory, a database from another version, a deleted database), it is made again from those files.
256
+ */
257
+ const rebuild = () => {
258
+ let count = 0;
259
+ store.tx(() => {
260
+ // In-progress replies and their checkpoints live only in SQLite until closeReply appends them to channel.jsonl.
261
+ const openRows = sameMessages
262
+ ? db.prepare(`SELECT ${COLUMNS.join(', ')} FROM messages WHERE status = 'processing' AND deleted_at IS NULL ORDER BY rowid`).all()
263
+ : [];
264
+ db.exec('DROP TABLE IF EXISTS message_parts; DROP TABLE IF EXISTS messages');
265
+ create();
266
+ const insert = db.prepare(`INSERT OR REPLACE INTO messages (${COLUMNS.join(', ')}) VALUES (${COLUMNS.map(() => '?').join(', ')})`);
267
+ const remove = db.prepare(markDeleted);
268
+ for (const topic of topics.all()) {
269
+ const file = join(topic.dir, 'channel.jsonl');
270
+ if (!existsSync(file))
271
+ continue;
272
+ for (const text of readFileSync(file, 'utf8').split('\n')) {
273
+ if (!text)
274
+ continue;
275
+ const line = JSON.parse(text);
276
+ if (!line.id)
277
+ continue;
278
+ if (line.op === 'delete') {
279
+ remove.run(line.at, line.by, line.id);
280
+ continue;
281
+ }
282
+ if (!line.from)
283
+ continue;
284
+ insert.run(line.id, topic.id, line.seq ?? null, line.from.kind, line.from.id, pack(line.to ?? [], line.visibility), line.replyTo ?? null, line.thread ?? null, line.threadable === undefined ? null : Number(line.threadable), JSON.stringify(line.attachments ?? []), line.content ?? '', JSON.stringify(line.parts ?? []), line.status ?? null, line.turnId ?? null, line.retryOf ?? null, line.note ?? null, line.terminal?.reason ?? null, JSON.stringify(line.read ?? []), line.createdAt ?? 0, null, null);
285
+ count++;
286
+ }
287
+ }
288
+ for (const row of openRows)
289
+ insert.run(...COLUMNS.map((c) => row[c]));
290
+ });
291
+ if (count)
292
+ log('messages', `index rebuilt from the channel files: ${count} messages`);
293
+ };
294
+ const partsInfo = db.prepare('PRAGMA table_info(message_parts)').all();
295
+ const partsHave = partsInfo.map((c) => c.name);
296
+ const stateCol = partsInfo.find((c) => c.name === 'state');
297
+ const indexesHave = db.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'message_parts'").all().map((r) => r.name);
298
+ const triggersHave = db.prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'messages'").all().map((r) => r.name);
299
+ if (!sameMessages
300
+ || partsHave.length !== PARTS_COLUMNS.length || PARTS_COLUMNS.some((c) => !partsHave.includes(c))
301
+ || stateCol?.notnull !== 0
302
+ || PART_INDEXES.some((name) => !indexesHave.includes(name))
303
+ || PART_TRIGGERS.some((name) => !triggersHave.includes(name)))
304
+ rebuild();
305
+ db.prepare('DELETE FROM messages WHERE topic_id NOT IN (SELECT value FROM json_each(?))').run(JSON.stringify(topics.all().map((topic) => topic.id)));
306
+ const deleteTopics = db.prepare('DELETE FROM messages WHERE topic_id IN (SELECT value FROM json_each(?))');
307
+ ctx.on('topic.purged', ({ topicIds }) => { deleteTopics.run(JSON.stringify(topicIds)); });
308
+ const withPartByState = db.prepare(`
309
+ SELECT * FROM messages
310
+ WHERE id IN (SELECT message_id FROM message_parts WHERE type = ? AND state = ? AND (? IS NULL OR topic_id = ?))
311
+ AND deleted_at IS NULL
312
+ ORDER BY created_at, rowid
313
+ `);
314
+ const withPartAnyState = db.prepare(`
315
+ SELECT * FROM messages
316
+ WHERE id IN (SELECT message_id FROM message_parts WHERE type = ? AND (? IS NULL OR topic_id = ?))
317
+ AND deleted_at IS NULL
318
+ ORDER BY created_at, rowid
319
+ `);
320
+ const read = (row) => {
321
+ const status = row.status;
322
+ const terminal = status === 'failed' || status === 'canceled' ? { status, reason: row.terminal_reason } : undefined;
323
+ return {
324
+ id: row.id,
325
+ topicId: row.topic_id,
326
+ seq: row.seq,
327
+ from: { kind: row.from_kind, id: row.from_id },
328
+ ...routing(row.to_members),
329
+ replyTo: row.reply_to,
330
+ thread: row.thread,
331
+ ...(row.threadable === null ? {} : { threadable: Boolean(row.threadable) }),
332
+ attachments: JSON.parse(row.attachments),
333
+ content: row.content,
334
+ parts: JSON.parse(row.parts),
335
+ status,
336
+ turnId: row.turn_id,
337
+ retryOf: row.retry_of,
338
+ note: row.note,
339
+ ...(terminal ? { terminal } : {}),
340
+ read: JSON.parse(row.read_ids),
341
+ createdAt: row.created_at,
342
+ ...(row.deleted_at === null ? {} : { deletedAt: row.deleted_at, deletedBy: row.deleted_by }),
343
+ };
344
+ };
345
+ const stored = (id, { includeDeleted = false } = {}) => {
346
+ const row = db.prepare(`SELECT * FROM messages WHERE id = ?${includeDeleted ? '' : ' AND deleted_at IS NULL'}`).get(id);
347
+ return row ? read(row) : undefined;
348
+ };
349
+ const messageRouting = db.prepare('SELECT to_members FROM messages WHERE id = ?');
350
+ const lastSeq = (topicId) => db.prepare('SELECT MAX(seq) AS seq FROM messages WHERE topic_id = ?').get(topicId).seq ?? 0;
351
+ const countUnread = "deleted_at IS NULL AND NOT (from_kind = 'member' AND from_id = $reader) AND message_visible(to_members, $reader)";
352
+ const countAfter = db.prepare(`
353
+ SELECT COUNT(*) AS count FROM messages WHERE topic_id = $topic AND seq > $seq AND ${countUnread}
354
+ `);
355
+ const grouped = (within) => db.prepare(`
356
+ WITH positions AS MATERIALIZED (SELECT key AS id, value AS seq FROM json_each($positions))
357
+ SELECT topic_id, COUNT(*) AS count FROM messages LEFT JOIN positions ON positions.id = messages.topic_id
358
+ WHERE messages.seq > COALESCE(positions.seq, 0) AND ${countUnread} ${within}
359
+ GROUP BY topic_id
360
+ `);
361
+ const allCounts = grouped('');
362
+ const selectedCounts = grouped('AND topic_id IN (SELECT value FROM json_each($ids))');
363
+ const saveReplyParts = db.prepare("UPDATE messages SET parts = ? WHERE id = ? AND status = 'processing'");
364
+ /** Append records to the topic's own channel. */
365
+ const record = (topicId, ...lines) => {
366
+ const topic = topics.get(topicId);
367
+ if (topic)
368
+ appendFileSync(join(topic.dir, 'channel.jsonl'), lines.map((line) => `${JSON.stringify(line)}\n`).join(''));
369
+ };
370
+ const said = (message) => {
371
+ const event = { message: messagesOut(messages, [message])[0] };
372
+ if (visibleTo(message.visibility, OWNER_ID))
373
+ push.send('message.appended', event);
374
+ ctx.runtime.emit('message.appended', event);
375
+ return message;
376
+ };
377
+ const revised = (message, tell = []) => {
378
+ const event = { message: messagesOut(messages, [message])[0], tell };
379
+ if (visibleTo(message.visibility, OWNER_ID))
380
+ push.send('message.changed', event);
381
+ ctx.runtime.emit('message.changed', event);
382
+ return message;
383
+ };
384
+ const visibleHistory = 'topic_id = ? AND deleted_at IS NULL AND message_visible(to_members, ?)';
385
+ const heads = db.prepare(`SELECT id, seq, from_kind, from_id, to_members, reply_to, thread, content, status, created_at FROM messages
386
+ WHERE ${visibleHistory} AND seq IS NOT NULL AND created_at >= ? ORDER BY seq`);
387
+ const forward = db.prepare(`SELECT * FROM messages WHERE ${visibleHistory} AND seq >= ? AND seq < ? ORDER BY seq LIMIT ?`);
388
+ const floorLastSeq = db.prepare(`SELECT MAX(seq) AS seq FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL AND (id = ? OR thread = ?)`);
389
+ const floorThreadRows = db.prepare(`SELECT * FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL AND (id = ? OR thread = ?) ORDER BY seq`);
390
+ const floorBatchRows = db.prepare(`SELECT * FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL
391
+ AND (id IN (SELECT value FROM json_each(?)) OR thread IN (SELECT value FROM json_each(?))) ORDER BY seq`);
392
+ const floorsBackward = db.prepare(`SELECT COALESCE(thread, id) AS floor_id, MAX(seq) AS last_seq, COUNT(*) AS count
393
+ FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL
394
+ GROUP BY COALESCE(thread, id) HAVING MAX(seq) < ? ORDER BY last_seq DESC LIMIT ?`);
395
+ const floorsForward = db.prepare(`SELECT COALESCE(thread, id) AS floor_id, MAX(seq) AS last_seq, COUNT(*) AS count
396
+ FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL
397
+ GROUP BY COALESCE(thread, id) HAVING MAX(seq) >= ? AND MAX(seq) < ? ORDER BY last_seq ASC LIMIT ?`);
398
+ const floorsAfter = db.prepare(`SELECT COALESCE(thread, id) AS floor_id, MAX(seq) AS last_seq, COUNT(*) AS count
399
+ FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL
400
+ GROUP BY COALESCE(thread, id) HAVING MAX(seq) > ? ORDER BY last_seq ASC LIMIT ?`);
401
+ const floorsRange = db.prepare(`SELECT COALESCE(thread, id) AS floor_id
402
+ FROM messages WHERE ${visibleHistory} AND seq IS NOT NULL
403
+ GROUP BY COALESCE(thread, id) HAVING MAX(seq) >= ?`);
404
+ const loadFloors = (topicId, memberId, floorIds) => {
405
+ if (!floorIds.length)
406
+ return [];
407
+ const ids = JSON.stringify(floorIds);
408
+ return floorBatchRows.all(topicId, memberId, ids, ids).map(read);
409
+ };
410
+ const pickFloors = (rows, cap) => {
411
+ const picked = [];
412
+ let total = 0;
413
+ for (const row of rows) {
414
+ picked.push(row.floor_id);
415
+ total += row.count;
416
+ if (total >= cap)
417
+ break;
418
+ }
419
+ return picked;
420
+ };
421
+ const view = (memberId) => ({
422
+ get(id, opts) {
423
+ const message = stored(id, opts);
424
+ return message && visibleTo(message.visibility, memberId) ? message : undefined;
425
+ },
426
+ locate(topicId, messageId) {
427
+ const message = this.get(messageId, { includeDeleted: true });
428
+ if (!message || message.topicId !== topicId)
429
+ return { status: 'missing' };
430
+ if (message.deletedAt !== undefined)
431
+ return { status: 'deleted' };
432
+ const { id, seq, thread } = message;
433
+ const root = thread ? this.get(thread) : undefined;
434
+ const floorId = thread && thread !== id ? thread : id;
435
+ const floorSeq = floorLastSeq.get(topicId, memberId, floorId, floorId)?.seq ?? null;
436
+ const at = { id, thread, threadSeq: root?.topicId === topicId ? root.seq : null };
437
+ return seq === null ? { status: 'live', ...at, floorSeq } : { status: 'ok', seq, ...at, floorSeq: floorSeq ?? seq };
438
+ },
439
+ page: (topicId, { before, after, from, limit, view: mode = 'timeline', thread } = {}) => ctx.runtime.span('sqlite.read', { database: 'host', query: 'messages.page', view: mode }, () => {
440
+ if (thread !== undefined) {
441
+ if (before === undefined && after === undefined && from === undefined && limit === undefined) {
442
+ return floorThreadRows.all(topicId, memberId, thread, thread).map(read);
443
+ }
444
+ const floorScope = `${visibleHistory} AND seq IS NOT NULL AND (id = ? OR thread = ?)`;
445
+ const cap = Math.max(0, Math.min(limit ?? 50, 200));
446
+ if (cap === 0)
447
+ return [];
448
+ if (from !== undefined) {
449
+ const rows = db.prepare(`SELECT * FROM messages WHERE ${floorScope} AND seq >= ? ORDER BY seq LIMIT ?`)
450
+ .all(topicId, memberId, thread, thread, from, cap);
451
+ return rows.map(read);
452
+ }
453
+ if (after !== undefined) {
454
+ const rows = db.prepare(`SELECT * FROM messages WHERE ${floorScope} AND seq > ? ORDER BY seq LIMIT ?`)
455
+ .all(topicId, memberId, thread, thread, after, cap);
456
+ return rows.map(read);
457
+ }
458
+ const rows = db.prepare(`SELECT * FROM messages WHERE ${floorScope} AND seq < ? ORDER BY seq DESC LIMIT ?`)
459
+ .all(topicId, memberId, thread, thread, before ?? Number.MAX_SAFE_INTEGER, cap);
460
+ return rows.reverse().map(read);
461
+ }
462
+ const cap = limit ?? 50;
463
+ if (mode === 'floors') {
464
+ if (from !== undefined) {
465
+ const size = Math.max(0, Math.min(cap, 200));
466
+ if (size === 0)
467
+ return [];
468
+ const rows = floorsForward.all(topicId, memberId, from, before ?? Number.MAX_SAFE_INTEGER, size);
469
+ return loadFloors(topicId, memberId, pickFloors(rows, size));
470
+ }
471
+ if (after !== undefined) {
472
+ const size = Math.max(0, cap);
473
+ if (size === 0)
474
+ return [];
475
+ const rows = floorsAfter.all(topicId, memberId, after, size);
476
+ return loadFloors(topicId, memberId, pickFloors(rows, size));
477
+ }
478
+ const size = Math.max(0, cap);
479
+ if (size === 0)
480
+ return [];
481
+ const rows = floorsBackward.all(topicId, memberId, before ?? Number.MAX_SAFE_INTEGER, size);
482
+ return loadFloors(topicId, memberId, pickFloors(rows, size));
483
+ }
484
+ if (from !== undefined) {
485
+ const rows = forward.all(topicId, memberId, from, before ?? Number.MAX_SAFE_INTEGER, Math.max(0, Math.min(cap, 200)));
486
+ return rows.map(read);
487
+ }
488
+ if (after !== undefined)
489
+ return db.prepare(`SELECT * FROM messages WHERE ${visibleHistory} AND seq > ? ORDER BY seq LIMIT ?`).all(topicId, memberId, after, cap).map(read);
490
+ const rows = db.prepare(`SELECT * FROM messages WHERE ${visibleHistory} AND seq < ? ORDER BY seq DESC LIMIT ?`)
491
+ .all(topicId, memberId, before ?? Number.MAX_SAFE_INTEGER, cap);
492
+ return rows.reverse().map(read);
493
+ }),
494
+ heads(topicId, since) {
495
+ return heads.all(topicId, memberId, since).map((row) => ({
496
+ id: row.id, seq: row.seq,
497
+ from: { kind: row.from_kind, id: row.from_id },
498
+ to: routing(row.to_members).to,
499
+ replyTo: row.reply_to, thread: row.thread,
500
+ content: row.content, createdAt: row.created_at,
501
+ status: row.status ?? null,
502
+ }));
503
+ },
504
+ range(topicId, from, mode = 'timeline') {
505
+ if (mode === 'floors') {
506
+ const floorIds = floorsRange.all(topicId, memberId, from).map((row) => row.floor_id);
507
+ return loadFloors(topicId, memberId, floorIds);
508
+ }
509
+ return forward.all(topicId, memberId, from, Number.MAX_SAFE_INTEGER, -1).map(read);
510
+ },
511
+ search({ topicId, topicIds, q, author, toMe, before, limit = 40 }) {
512
+ const needle = q && searchLine(q);
513
+ const recipient = toMe ? memberId : null;
514
+ if ((!needle && !author && !toMe) || (toMe && recipient === null))
515
+ return { hits: [], more: false };
516
+ const ids = topics.list().map((topic) => topic.id);
517
+ const scoped = topicIds !== undefined ? topicIds.filter((id) => ids.includes(id)) : topicId !== undefined ? (ids.includes(topicId) ? [topicId] : []) : undefined;
518
+ if (scoped !== undefined && !scoped.length)
519
+ return { hits: [], more: false };
520
+ const pattern = needle ? new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'iu') : undefined;
521
+ const authorMatches = new Map();
522
+ if (pattern) {
523
+ for (const member of [...members.people(), ...members.list()]) {
524
+ authorMatches.set(member.id, pattern.test(searchLine(member.name || member.id)) || pattern.test('@' + member.handle));
525
+ }
526
+ }
527
+ const where = ['seq IS NOT NULL', 'deleted_at IS NULL', 'message_visible(to_members, ?)'];
528
+ const args = [memberId];
529
+ if (scoped === undefined) {
530
+ where.push('topic_id IN (SELECT value FROM json_each(?))');
531
+ args.push(JSON.stringify(ids));
532
+ }
533
+ else {
534
+ where.push('topic_id IN (SELECT value FROM json_each(?))');
535
+ args.push(JSON.stringify(scoped));
536
+ }
537
+ if (author) {
538
+ where.push("from_kind = 'member' AND from_id = ?");
539
+ args.push(author);
540
+ }
541
+ if (before) {
542
+ where.push('(created_at, id) < (?, ?)');
543
+ args.push(before.createdAt, before.id);
544
+ }
545
+ const rows = db.prepare(`
546
+ SELECT id, topic_id, from_kind, from_id, to_members, content, parts, attachments, created_at
547
+ FROM messages WHERE ${where.join(' AND ')} ORDER BY created_at DESC, id DESC
548
+ `).iterate(...args);
549
+ const hits = [], size = Math.max(1, Math.min(100, limit));
550
+ for (const value of rows) {
551
+ const row = value;
552
+ if (recipient !== null && !routing(row.to_members).to.includes(recipient))
553
+ continue;
554
+ const from = { kind: row.from_kind, id: row.from_id };
555
+ const matchedAuthor = !!pattern && from.kind === 'member' && (authorMatches.get(from.id) ?? pattern.test(from.id));
556
+ const excerpt = searchExcerpt(row, pattern, matchedAuthor);
557
+ if (!excerpt)
558
+ continue;
559
+ if (hits.length === size)
560
+ return { hits, more: true };
561
+ hits.push({
562
+ id: row.id,
563
+ topicId: row.topic_id,
564
+ from,
565
+ createdAt: row.created_at,
566
+ excerpt,
567
+ });
568
+ }
569
+ return { hits, more: false };
570
+ },
571
+ });
572
+ function moveBatch(ids, thread, by) {
573
+ const history = view(by);
574
+ const batch = [...new Set(ids)].map((id) => {
575
+ const message = history.get(id);
576
+ if (!message)
577
+ throw new HttpError(404, '没有这条消息');
578
+ return message;
579
+ });
580
+ const topic = requireTopic(topics, batch[0].topicId);
581
+ if (topic.archivedAt !== null)
582
+ throw new HttpError(409, '主题已归档');
583
+ if (batch.some((message) => message.topicId !== topic.id))
584
+ throw new HttpError(400, '只能一起移动同一主题里的消息');
585
+ if (batch.some((message) => message.seq === null || message.status === 'processing'))
586
+ throw new HttpError(400, '这条回复还在进行中,请先停止再移动');
587
+ const changed = batch.filter((message) => message.thread !== thread);
588
+ if (!changed.length)
589
+ return batch;
590
+ if (thread !== null) {
591
+ const head = history.get(thread);
592
+ if (head?.topicId !== topic.id || head.seq === null || head.thread !== null || batch.some(({ id }) => id === thread)) {
593
+ throw new HttpError(400, `这个主题的主线上没有这条消息:${thread}`);
594
+ }
595
+ const replies = db.prepare('SELECT 1 FROM messages WHERE thread = ? AND deleted_at IS NULL LIMIT 1');
596
+ if (changed.some(({ id }) => replies.get(id)))
597
+ throw new HttpError(400, '这条下面还有回复,挪进别的楼会变成楼中楼');
598
+ }
599
+ const moved = store.tx(() => {
600
+ const update = db.prepare('UPDATE messages SET thread = ? WHERE id = ?');
601
+ const now = changed.map((message) => {
602
+ update.run(thread, message.id);
603
+ return { ...message, thread };
604
+ });
605
+ record(topic.id, ...now);
606
+ return new Map(now.map((message) => [message.id, message]));
607
+ });
608
+ log('messages', `moved ${[...moved.keys()].join(', ')} in ${topic.id} to ${thread ?? 'the main line'} by ${by}`);
609
+ return batch.map((message) => {
610
+ const revision = moved.get(message.id);
611
+ return revision ? revised(revision) : message;
612
+ });
613
+ }
614
+ const publicHistory = view(null);
615
+ const messages = {
616
+ ...publicHistory,
617
+ forMember: view,
618
+ stored,
619
+ storedRouting(id) {
620
+ const row = messageRouting.get(id);
621
+ return row && routing(row.to_members);
622
+ },
623
+ saveAttachment(topicId, rawName, data) {
624
+ const topic = requireTopic(topics, topicId);
625
+ if (topic.archivedAt !== null)
626
+ throw new HttpError(409, '主题已归档');
627
+ return saveAttachment(topic.dir, rawName, data);
628
+ },
629
+ attachment(topicId, path) {
630
+ return attachmentLocation(topicId, requireTopic(topics, topicId).dir, path);
631
+ },
632
+ lastSeq,
633
+ countAfter: (topicId, seq, memberId) => countAfter.get({ $topic: topicId, $seq: seq, $reader: memberId }).count,
634
+ countsAfter(positions, memberId, ids) {
635
+ const args = { $positions: JSON.stringify(Object.fromEntries(positions)), $reader: memberId };
636
+ const rows = (ids ? selectedCounts.all({ ...args, $ids: JSON.stringify([...ids]) }) : allCounts.all(args));
637
+ return new Map(rows.map(({ topic_id, count }) => [topic_id, count]));
638
+ },
639
+ remove(id, by) {
640
+ const message = stored(id, { includeDeleted: true });
641
+ if (!message)
642
+ throw new HttpError(404, '没有这条消息');
643
+ if (message.seq === null || message.status === 'processing')
644
+ throw new HttpError(400, '这条回复还在进行中,请先停止再删除');
645
+ const { topicId } = message;
646
+ if (message.deletedAt !== undefined)
647
+ return { id, topicId, deletedAt: message.deletedAt, deletedBy: message.deletedBy };
648
+ const at = Date.now();
649
+ const tombstone = { op: 'delete', id, by, at };
650
+ store.tx(() => {
651
+ db.prepare(markDeleted).run(at, by, id);
652
+ record(topicId, tombstone);
653
+ });
654
+ const event = { topicId, id, by, at };
655
+ if (visibleTo(message.visibility, OWNER_ID))
656
+ push.send('message.deleted', event);
657
+ ctx.runtime.emit('message.deleted', event);
658
+ log('messages', `deleted ${id} in ${topicId} by ${by}`);
659
+ return { id, topicId, deletedAt: at, deletedBy: by };
660
+ },
661
+ move(id, thread, by) {
662
+ return moveBatch([id], thread, by)[0];
663
+ },
664
+ deletedIds(ids) {
665
+ const list = [...ids];
666
+ if (!list.length)
667
+ return new Set();
668
+ const rows = db.prepare('SELECT id FROM messages WHERE id IN (SELECT value FROM json_each(?)) AND deleted_at IS NOT NULL').all(JSON.stringify(list));
669
+ return new Set(rows.map((row) => row.id));
670
+ },
671
+ readBy(id) {
672
+ const message = publicHistory.get(id);
673
+ // A turn can attach later reads to an independent reply already in the channel.
674
+ const row = message && db.prepare(`
675
+ SELECT * FROM messages WHERE topic_id = ? AND seq IS NOT NULL AND deleted_at IS NULL AND message_visible(to_members, NULL)
676
+ AND EXISTS (SELECT 1 FROM json_each(read_ids) WHERE value = ?) ORDER BY seq DESC LIMIT 1
677
+ `).get(message.topicId, id);
678
+ return row ? read(row) : undefined;
679
+ },
680
+ publish({ id = newId('msg'), topicId, from, content, to = [], visibility, replyTo, thread, threadable, attachments = [], note, parts = [], read = [] }, recordChange) {
681
+ if (topics.isArchived(topicId))
682
+ throw new HttpError(409, '主题已归档');
683
+ const message = store.tx(() => {
684
+ db.prepare('INSERT INTO messages (id, topic_id, seq, from_kind, from_id, to_members, reply_to, thread, threadable, attachments, content, parts, note, read_ids, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
685
+ .run(id, topicId, lastSeq(topicId) + 1, from.kind, from.id, pack(to, visibility), replyTo ?? null, thread ?? null, threadable === undefined ? null : Number(threadable), JSON.stringify(attachments), content, JSON.stringify(parts), note ?? null, JSON.stringify(read), Date.now());
686
+ const saved = stored(id);
687
+ recordChange?.(saved);
688
+ record(topicId, saved);
689
+ return saved;
690
+ });
691
+ return said(message);
692
+ },
693
+ revise(id, { content, parts, tell = [] }, recordChange) {
694
+ const was = stored(id);
695
+ if (!was)
696
+ throw new Error(`no such message: ${id}`);
697
+ const message = store.tx(() => {
698
+ db.prepare('UPDATE messages SET content = ?, parts = ?, to_members = ? WHERE id = ?')
699
+ .run(content, JSON.stringify(parts), pack([...new Set([...was.to, ...tell])], was.visibility), id);
700
+ const now = stored(id);
701
+ recordChange?.();
702
+ record(now.topicId, now);
703
+ return now;
704
+ });
705
+ return revised(message, tell);
706
+ },
707
+ withPart({ type, state, topicId }) {
708
+ return ctx.runtime.span('sqlite.read', { database: 'host', query: 'messages.withPart', type }, () => {
709
+ const rows = (state != null
710
+ ? withPartByState.all(type, state, topicId ?? null, topicId ?? null)
711
+ : withPartAnyState.all(type, topicId ?? null, topicId ?? null));
712
+ return rows.map(read);
713
+ });
714
+ },
715
+ openReply({ topicId, memberId, turnId, visibility, replyTo, thread, read = [] }) {
716
+ const id = newId('msg');
717
+ db.prepare(`INSERT INTO messages (id, topic_id, from_kind, from_id, to_members, reply_to, thread, content, status, turn_id, read_ids, created_at)
718
+ VALUES (?, ?, 'member', ?, ?, ?, ?, '', 'processing', ?, ?, ?)`)
719
+ .run(id, topicId, memberId, pack([], visibility), replyTo ?? null, thread ?? null, turnId, JSON.stringify(read), Date.now());
720
+ return stored(id);
721
+ },
722
+ reopenReply(id, turnId) {
723
+ const reply = stored(id);
724
+ if (!reply || reply.seq === null || !reply.terminal)
725
+ throw new Error(`cannot reopen reply: ${id}`);
726
+ db.prepare("UPDATE messages SET status = 'processing', turn_id = ?, terminal_reason = NULL WHERE id = ?").run(turnId, id);
727
+ return stored(id);
728
+ },
729
+ checkpointReply(id, parts) {
730
+ saveReplyParts.run(JSON.stringify(parts), id);
731
+ },
732
+ setReplyRead(id, read) {
733
+ db.prepare("UPDATE messages SET read_ids = ? WHERE id = ? AND status = 'processing'").run(JSON.stringify(read), id);
734
+ },
735
+ closeReply(id, { content, parts, status, to, reason, read = [] }, settle) {
736
+ const open = stored(id);
737
+ if (!open)
738
+ throw new Error(`no such message: ${id}`);
739
+ const publishedAt = open.seq === null ? Math.max(open.createdAt, Date.now()) : open.createdAt;
740
+ const message = store.tx(() => {
741
+ db.prepare('UPDATE messages SET seq = ?, to_members = ?, content = ?, parts = ?, status = ?, terminal_reason = ?, read_ids = ?, created_at = ? WHERE id = ?')
742
+ .run(open.seq ?? lastSeq(open.topicId) + 1, pack(to ?? open.to, open.visibility), content, JSON.stringify(parts), status, reason ?? null, JSON.stringify(read), publishedAt, id);
743
+ const message = stored(id);
744
+ settle?.(message);
745
+ record(message.topicId, message);
746
+ return message;
747
+ });
748
+ return open.seq === null ? said(message) : revised(message);
749
+ },
750
+ discardReply(id) {
751
+ db.prepare("DELETE FROM messages WHERE id = ? AND seq IS NULL AND status = 'processing'").run(id);
752
+ },
753
+ attachTurn(id, { turnId, parts, read }) {
754
+ db.prepare("UPDATE messages SET turn_id = ?, status = 'completed', parts = ?, read_ids = ? WHERE id = ?")
755
+ .run(turnId, JSON.stringify(parts), JSON.stringify(read), id);
756
+ const message = stored(id);
757
+ record(message.topicId, message);
758
+ return message;
759
+ },
760
+ after(topicId, seq, memberId, cutoff = Number.MAX_SAFE_INTEGER, opts) {
761
+ const floor = opts?.floor;
762
+ const reader = opts?.visibility === undefined || opts.visibility === 'all' ? null : memberId;
763
+ const scope = floor === null ? 'AND thread IS NULL' : typeof floor === 'string' ? 'AND (id = ? OR thread = ?)' : '';
764
+ const args = [topicId, seq, cutoff, reader, memberId];
765
+ if (typeof floor === 'string')
766
+ args.push(floor, floor);
767
+ const rows = db.prepare(`SELECT * FROM messages WHERE topic_id = ? AND seq > ? AND seq <= ? AND deleted_at IS NULL AND message_visible(to_members, ?)
768
+ AND (status IS NULL OR status = 'completed') AND NOT (from_kind = 'member' AND from_id = ?) ${scope} ORDER BY seq`).all(...args);
769
+ return rows.map(read);
770
+ },
771
+ floorBefore(topicId, before, memberId, floor, visibility) {
772
+ const reader = visibility === undefined || visibility === 'all' ? null : memberId;
773
+ const scope = floor === null ? 'AND thread IS NULL' : 'AND (id = ? OR thread = ?)';
774
+ const args = [topicId, before, reader];
775
+ if (floor !== null)
776
+ args.push(floor, floor);
777
+ const rows = db.prepare(`SELECT * FROM messages WHERE topic_id = ? AND seq IS NOT NULL AND seq < ? AND deleted_at IS NULL
778
+ AND (status IS NULL OR status = 'completed') AND message_visible(to_members, ?) ${scope} ORDER BY seq`).all(...args);
779
+ return rows.map(read);
780
+ },
781
+ repliers(topicId) {
782
+ return db.prepare(`
783
+ SELECT from_id FROM messages WHERE topic_id = ? AND from_kind = 'member' AND status = 'completed' AND deleted_at IS NULL
784
+ GROUP BY from_id ORDER BY MAX(seq) DESC
785
+ `).all(topicId).map((row) => row.from_id);
786
+ },
787
+ lastReplier: (topicId) => messages.repliers(topicId)[0],
788
+ openReplies: () => db.prepare("SELECT * FROM messages WHERE status = 'processing'").all().map(read),
789
+ };
790
+ ctx.point('message.appended', { title: '消息进入 channel', group: '每一轮', about: '任何一条消息(人说的、成员的回复、插件发的)落进 channel 的那一刻。', order: 40 });
791
+ ctx.provide('messages', messages);
792
+ const entry = ctx.get('entry');
793
+ const topicId = { type: 'string', description: '主题编号' };
794
+ const memberKey = { type: 'string', description: '成员编号' };
795
+ const withReplyModels = (items) => ctx.runtime.has('a2a') ? ctx.get('a2a').withReplyModels(items) : items;
796
+ ctx.effect(entry.op({
797
+ name: 'channel.messages', workload: 'local', about: '分页读一个主题的历史消息,可指定读取的条数、起点和视图。',
798
+ input: object({
799
+ id: topicId, before: { type: 'integer', description: '只读这个序号之前的消息(floors 视图下为楼最新序号游标)' },
800
+ from: { type: 'integer', description: '从这个序号开始往后读,单批最多 200 条' },
801
+ limit: { type: 'integer', description: '最多读几条,默认 50' },
802
+ view: { type: 'string', enum: ['timeline', 'floors'], description: 'timeline:按原始消息序号排序(默认);floors:按楼内最新消息序号聚合分页,每楼返回完整楼主与回复' },
803
+ thread: { type: 'string', description: '只读指定楼的楼主与全部可见回复' },
804
+ summary: { type: 'boolean', description: '只读可显示的正文和步骤计数,工具输入、结果与思考按单条消息读取' },
805
+ }, ['id']),
806
+ output: array(messageOutput), sdk: true,
807
+ http: ['GET', '/api/topics/:id/messages'], agent: true, topic: 'id', reach: 'any',
808
+ run({ id, before, from, limit, view: mode, thread, summary }, caller) {
809
+ const page = messagesOut(messages, messages.forMember(caller.member?.id ?? OWNER_ID).page(requireTopic(topics, id).id, { before, from, limit, view: mode, thread }));
810
+ const replies = withReplyModels(page);
811
+ return summary ? replies.map(messagePreview) : replies;
812
+ },
813
+ }));
814
+ ctx.effect(entry.group('messages', '主题里的消息'));
815
+ ctx.effect(entry.op({
816
+ name: 'messages.detail', about: '打开一条可见消息的完整内容与执行步骤。',
817
+ input: object({ id: topicId, messageId: stringValue }, ['id', 'messageId']), output: messageOutput,
818
+ http: ['GET', '/api/topics/:id/messages/:messageId'],
819
+ run({ id, messageId }, caller) {
820
+ requireTopic(topics, id);
821
+ const message = messages.forMember(caller.member?.id ?? OWNER_ID).get(messageId);
822
+ if (message?.topicId !== id)
823
+ throw new HttpError(404, '消息不存在');
824
+ return withReplyModels(messagesOut(messages, [message]))[0];
825
+ },
826
+ }));
827
+ ctx.hook('address.labels', ({ addresses, memberId }) => {
828
+ const history = messages.forMember(memberId);
829
+ const labels = Object.create(null);
830
+ for (const address of addresses) {
831
+ const match = /^chat-([^/?]+)\/([^/?]+)$/.exec(address);
832
+ if (!match)
833
+ continue;
834
+ const topic = topics.get(match[1]);
835
+ if (!topic || topic.deletedAt !== null)
836
+ continue;
837
+ const message = history.get(match[2]);
838
+ if (message?.topicId !== topic.id)
839
+ continue;
840
+ const sender = message.from.kind === 'member' ? members.get(message.from.id)?.name : message.from.id;
841
+ labels[address] = referenceExcerpt(messageGist(message)) || [sender, topic.title].filter(Boolean).join(' · ');
842
+ }
843
+ return labels;
844
+ });
845
+ ctx.effect(entry.op({
846
+ name: 'messages.search', workload: 'local', about: '在指定范围(当前主题、主题线索或全部)的可见历史里查找,按作者或实际收件人筛选。',
847
+ input: object({
848
+ topicId, scope: { type: 'string', enum: ['topic', 'lineage', 'all'], description: 'topic:当前主题;lineage:当前主题及父主题;all:全部主题。' }, q: stringValue, author: memberKey, toMe: booleanValue,
849
+ beforeAt: { type: 'integer' }, beforeId: stringValue, limit: { type: 'integer' },
850
+ }),
851
+ http: ['GET', '/api/messages/search'],
852
+ run({ topicId, scope, q, author, toMe, beforeAt, beforeId, limit }, caller) {
853
+ if ((beforeAt === undefined) !== (beforeId === undefined))
854
+ throw new HttpError(400, '消息查找的时间与编号游标要一起提供');
855
+ const id = topicId === undefined ? undefined : requireTopic(topics, topicId).id;
856
+ const topicIds = scope && id !== undefined ? topics.scopeIds(id, scope) : undefined;
857
+ return messages.forMember(caller.member?.id ?? OWNER_ID).search({
858
+ topicId: id, topicIds,
859
+ q, author, toMe, limit,
860
+ before: beforeAt === undefined ? undefined : { createdAt: beforeAt, id: beforeId },
861
+ });
862
+ },
863
+ }));
864
+ ctx.effect(entry.op({
865
+ name: 'messages.locate', about: '按固定地址查找主题里的消息位置、所在楼和是否仍可见。',
866
+ input: object({ id: topicId, messageId: { type: 'string', description: '消息编号' } }, ['id', 'messageId']),
867
+ http: ['GET', '/api/topics/:id/messages/:messageId/locate'],
868
+ run: ({ id, messageId }, caller) => messages.forMember(caller.member?.id ?? OWNER_ID).locate(requireTopic(topics, id).id, messageId),
869
+ }));
870
+ ctx.effect(entry.op({
871
+ name: 'messages.delete', about: '删除一条已进入历史的消息。',
872
+ input: object({ id: { type: 'string' } }, ['id']),
873
+ http: ['DELETE', '/api/messages/:id'], run: ({ id }) => messages.remove(id, OWNER_ID),
874
+ }));
875
+ ctx.effect(entry.op({
876
+ name: 'messages.move', about: '把同一主题的一条或多条消息移回主线(thread 为 null),或挪到另一条主线消息的楼里。',
877
+ input: object({
878
+ id: { type: 'string' },
879
+ ids: { type: 'array', items: stringValue, description: '随路径中的消息一起移动的其他消息编号。提供时返回整批消息。' },
880
+ thread: { type: ['string', 'null'], description: '目标楼的楼主消息编号;null 是主线' },
881
+ }, ['id', 'thread']),
882
+ output: { oneOf: [messageOutput, array(messageOutput)] },
883
+ http: ['POST', '/api/messages/:id/move'],
884
+ run({ id, ids, thread }, caller) {
885
+ const moved = messagesOut(messages, moveBatch([id, ...(ids ?? [])], thread, caller.member?.id ?? OWNER_ID));
886
+ return ids ? moved : moved[0];
887
+ },
888
+ }));
889
+ ctx.hook('topic.records', () => ATTACHMENT_RECORDS);
890
+ ctx.effect(entry.route('POST', '/api/topics/:id/attachments', ({ params, query, body }) => {
891
+ if (!Buffer.isBuffer(body))
892
+ throw new HttpError(400, '附件要原样传(application/octet-stream)');
893
+ return messages.saveAttachment(params.id, query.get('name') ?? '', body);
894
+ }));
895
+ ctx.effect(entry.op({
896
+ name: 'messages.reference_attachment',
897
+ about: '将本机选中的单个文件登记为当前主题的附件,保留原件。',
898
+ input: object({ id: topicId, source: { type: 'string', description: '选中的绝对路径或 file: URL' } }, ['id', 'source']),
899
+ output: object({ path: stringValue, name: stringValue, size: countValue }, ['path', 'name', 'size']),
900
+ localPage: true,
901
+ http: ['POST', '/api/topics/:id/attachments/reference'],
902
+ run({ id, source }) {
903
+ const topic = requireTopic(topics, id);
904
+ if (topic.archivedAt !== null)
905
+ throw new HttpError(409, '主题已归档');
906
+ return referenceAttachment(topic.dir, source);
907
+ },
908
+ }));
909
+ ctx.effect(entry.route('GET', '/api/topics/:id/attachments/:name', ({ params, raw, res }) => {
910
+ const file = messages.attachment(params.id, 'attachments/' + params.name)?.file;
911
+ if (!file)
912
+ throw new HttpError(404, '附件不存在或原件已不可读');
913
+ return sendUserFile(res, file, raw);
914
+ }));
915
+ },
916
+ };