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,1088 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { hash } from 'node:crypto';
3
+ import { appendFileSync, createReadStream, existsSync, lstatSync, mkdirSync, realpathSync, rmSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, resolve, sep, win32 } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { array, check, createFileLock, errorText, fileMime, HANDLED, HttpError, inTopicArtifacts, isDirRef, locatorField, log, newId, object, packageRoot, parseResource, refResource, replaceFile, resourceField, resourceWithin, sandboxUserContent, sendUserFile, topicResource, validateLocator, workResource, writeExclusiveFile, } from 'hostlet/sdk';
7
+ import { EVENT_SIZE, eventFields, publicEvent, recentEvents } from "./events.js";
8
+ import { fileVersion, localFile, localFiles, sameVersion } from "./files.js";
9
+ import { registerProjectFiles } from "./project.js";
10
+ import { fileResource, locateFile, previewFile, projectWriteAccess, relativeFile, resourceFile, TOPIC_ROOT, topicFileRoots } from "./resource.js";
11
+ import { viewers } from "./viewers.js";
12
+ import { documentWords } from "./document-words.js";
13
+ import { cleanupCandidates, coreRecords, inventoryEntry, managedResource, removeVerifiedTarget, resourceRetention, storageZone } from "./retention.js";
14
+ const sourceLine = (from) => (from.via === 'ancestor' ? '继承自' : '引用自') + '「' + from.title + '」';
15
+ /** Resolve existing links before creating directories or writing a file. */
16
+ function topicFile(root, path) {
17
+ const parts = path.split(/[\\/]+/).filter((part) => part && part !== '.');
18
+ if (win32.parse(path).root || parts.includes('..') || !parts.length || path.includes('\0')) {
19
+ throw new Error('文件路径须为相对路径,不能含 ..');
20
+ }
21
+ const prefix = root.endsWith(sep) ? root : root + sep;
22
+ let target = root;
23
+ for (const [i, part] of parts.entries()) {
24
+ target = join(target, part);
25
+ let info = lstatSync(target, { throwIfNoEntry: false });
26
+ if (!info)
27
+ return join(target, ...parts.slice(i + 1));
28
+ if (info.isSymbolicLink()) {
29
+ if (!existsSync(target))
30
+ throw new Error(`路径里的符号链接不可用:${target}`);
31
+ target = realpathSync.native(target);
32
+ if (target !== root && !target.startsWith(prefix))
33
+ throw new Error('路径里的符号链接超出主题 artifacts/');
34
+ info = statSync(target);
35
+ }
36
+ const last = i === parts.length - 1;
37
+ if (last && !info.isFile())
38
+ throw new Error(`写入目标须为文件:${target}`);
39
+ if (!last && !info.isDirectory())
40
+ throw new Error(`路径的上级须为目录:${target}`);
41
+ }
42
+ return target;
43
+ }
44
+ /**
45
+ * The works of a topic: what it made, shown first when the topic is opened; a viewer for them; and one small
46
+ * language for what is done with a work (open, go to a place, select, play, pause) that a person's actions in the
47
+ * viewer are recorded in and a member's tool calls are written in. Files under the topic's `artifacts/` are works
48
+ * without anyone registering them; commits made during a topic's turns in the repositories it references are
49
+ * claimed for it, each commit by one topic only.
50
+ */
51
+ export default function worksPlugin(home, ext) {
52
+ return {
53
+ name: 'works',
54
+ title: '文件与产物',
55
+ about: '浏览主题文件和引用目录,管理文件、链接、结论和代码提交,并查看原件与操作记录。',
56
+ group: '主题页',
57
+ needs: ['topics', 'members', 'entry', 'push', 'i18n', 'a2a', 'messages'],
58
+ start(ctx) {
59
+ ctx.effect(ext.config.declare([
60
+ {
61
+ key: 'keep', kind: 'number',
62
+ label: { default: '默认展示产物数',
63
+ translations: { en: 'Works shown by default' } },
64
+ description: { default: '打开主题时先显示最新的几份产物;更早的归到素材(置顶的不算在内)。',
65
+ translations: { en: 'How many recent works to show when opening a topic; earlier ones become materials, excluding pinned works.' } },
66
+ default: 3, minimum: 0, unit: 'items', integer: true, presets: [0, 3, 5, 10, 20],
67
+ },
68
+ ]));
69
+ const topics = ctx.get('topics');
70
+ const messages = ctx.get('messages');
71
+ const members = ctx.get('members');
72
+ const a2a = ctx.get('a2a');
73
+ ctx.effect(ctx.get('i18n').register('works', {
74
+ zh: { document: documentWords.zh }, en: { document: documentWords.en },
75
+ }));
76
+ const actorOf = (caller) => caller.member?.id ?? members.people()[0].id;
77
+ const entry = ctx.get('entry');
78
+ const fileTurns = new Map();
79
+ const changed = (change) => queueMicrotask(() => ctx.runtime.emit('resource.changed', change));
80
+ ctx.effect(ctx.get('push').forward('resource.changed'));
81
+ const registry = viewers();
82
+ let linkIndex;
83
+ const linksIn = (book) => book.items.flatMap((item) => item.kind === 'link' && item.url ? [item.url] : []);
84
+ const ensureLinkIndex = () => linkIndex ??= new Map(topics.list().map((topic) => [topic.id, linksIn(bookOf(topic))]));
85
+ ctx.on('topic.updated', ({ topic, refsBefore }) => {
86
+ if (linkIndex) {
87
+ if (topic.deletedAt)
88
+ linkIndex.delete(topic.id);
89
+ else if (!linkIndex.has(topic.id))
90
+ linkIndex.set(topic.id, linksIn(bookOf(topic)));
91
+ }
92
+ if (!refsBefore)
93
+ return;
94
+ const before = new Map(refsBefore.map((ref) => [ref.refId, ref.path]));
95
+ for (const ref of topic.refs.filter(isDirRef)) {
96
+ const prior = before.get(ref.refId);
97
+ before.delete(ref.refId);
98
+ if (prior !== ref.path)
99
+ changed({ topicId: topic.id, kind: prior === undefined ? 'created' : 'updated', resource: refResource(ref.refId, '') });
100
+ }
101
+ for (const refId of before.keys())
102
+ changed({ topicId: topic.id, kind: 'deleted', resource: refResource(refId, '') });
103
+ });
104
+ ctx.on('topic.purged', ({ topicIds }) => {
105
+ if (!linkIndex)
106
+ return;
107
+ for (const id of topicIds)
108
+ linkIndex.delete(id);
109
+ });
110
+ ctx.effect(entry.group('works', '一个主题的产物、工作台观测和查看器操作'));
111
+ const need = (id) => {
112
+ const topic = topics.get(id);
113
+ if (!topic || topic.deletedAt)
114
+ throw new HttpError(400, `没有这个主题:${id}`);
115
+ return topic;
116
+ };
117
+ const writable = (id) => {
118
+ const topic = need(id);
119
+ if (topic.archivedAt !== null)
120
+ throw new HttpError(409, '主题已归档');
121
+ return topic;
122
+ };
123
+ const rootsOf = (topic) => topicFileRoots(topic, topics.refsOf(topic.id));
124
+ const bookOf = (topic) => ({ items: [], pinned: [], heads: {}, ...(existsSync(join(topic.dir, 'works.json')) ? JSON.parse(readFileSync(join(topic.dir, 'works.json'), 'utf8')) : {}) });
125
+ const save = (topic, book) => {
126
+ writeFileSync(join(topic.dir, 'works.json'), `${JSON.stringify(book, null, 2)}\n`);
127
+ if (linkIndex && !topic.deletedAt)
128
+ linkIndex.set(topic.id, linksIn(book));
129
+ topics.touch(topic.id);
130
+ };
131
+ const rewriteFileRecords = (book, rewrite) => {
132
+ let dirty = false;
133
+ const replace = (id) => {
134
+ const next = rewrite(id);
135
+ if (next !== id)
136
+ dirty = true;
137
+ return next;
138
+ };
139
+ const addresses = (ids) => ids.flatMap((id) => replace(id) ?? []);
140
+ book.pinned = addresses(book.pinned);
141
+ if (book.hidden)
142
+ book.hidden = addresses(book.hidden);
143
+ if (book.retained)
144
+ book.retained = addresses(book.retained);
145
+ book.items = book.items.flatMap((item) => {
146
+ const id = replace(item.id);
147
+ return id ? [{ ...item, id }] : [];
148
+ });
149
+ if (book.files)
150
+ book.files = Object.fromEntries(Object.entries(book.files).flatMap(([id, authors]) => {
151
+ const key = replace(id);
152
+ return key ? [[key, authors]] : [];
153
+ }));
154
+ return dirty;
155
+ };
156
+ const updateFileRecords = (book, resource, next) => rewriteFileRecords(book, (id) => resourceWithin(id, resource) ? next && next + id.slice(resource.length) : id);
157
+ const retentionFor = (topic) => {
158
+ const marks = bookOf(topic);
159
+ return (resource) => managedResource(topic.id, resource) ? resourceRetention(resource, marks) : undefined;
160
+ };
161
+ const projectChanged = (change) => {
162
+ try {
163
+ if (change.kind !== 'moved' && change.kind !== 'deleted')
164
+ return;
165
+ const { resource, topicId } = change;
166
+ const next = change.kind === 'moved' ? change.nextResource : undefined;
167
+ // The same reference resource can be registered by multiple topics through inheritance.
168
+ const affected = resource.startsWith('res:ref/') ? topics.all() : [need(topicId)];
169
+ for (const topic of affected) {
170
+ const book = bookOf(topic);
171
+ if (updateFileRecords(book, resource, next))
172
+ save(topic, book);
173
+ }
174
+ const snapshot = fileTurns.get(topicId)?.files;
175
+ if (!snapshot)
176
+ return;
177
+ for (const [key, file] of [...snapshot]) {
178
+ if (!resourceWithin(key, resource))
179
+ continue;
180
+ snapshot.delete(key);
181
+ if (next) {
182
+ const address = (next + key.slice(resource.length));
183
+ const location = parseResource(address);
184
+ if (location?.kind === 'topic')
185
+ snapshot.set(address, { ...file, path: join(need(topicId).dir, location.path) });
186
+ }
187
+ }
188
+ }
189
+ finally {
190
+ changed(change);
191
+ }
192
+ };
193
+ const madeFile = (id, { path, version }) => ({
194
+ id, kind: 'file', title: basename(path), path, by: '', at: version[0],
195
+ });
196
+ const present = (item) => ({ ...item, resource: item.id });
197
+ const attributed = (work, attribution, version) => {
198
+ const created = attribution?.created;
199
+ const updated = version && sameVersion(attribution?.version, version) ? attribution?.updated : undefined;
200
+ return {
201
+ ...work, by: created?.by ?? '', updatedBy: updated?.by ?? '',
202
+ ...(created ? { byBasis: created.basis } : {}), ...(updated ? { updatedByBasis: updated.basis } : {}),
203
+ };
204
+ };
205
+ const ownList = (topic) => {
206
+ const book = bookOf(topic);
207
+ const local = localFiles(topic, true);
208
+ const rows = new Map([...local].map(([id, file]) => [id, madeFile(id, file)]));
209
+ const pinned = new Set(book.pinned);
210
+ let roots;
211
+ for (const item of book.items) {
212
+ if (item.kind !== 'file') {
213
+ rows.set(item.id, item);
214
+ continue;
215
+ }
216
+ const file = local.get(item.id);
217
+ if (file) {
218
+ rows.set(item.id, { ...madeFile(item.id, file), title: item.title, registeredBy: item.registeredBy });
219
+ continue;
220
+ }
221
+ let path = item.path;
222
+ if (!path) {
223
+ const at = resourceFile(topic.id, roots ??= rootsOf(topic), item.id);
224
+ const candidate = at && join(at.root.dir, at.path);
225
+ if (candidate && existsSync(candidate)) {
226
+ const real = realpathSync.native(candidate);
227
+ if (relativeFile(at.boundary, real) !== undefined)
228
+ path = real;
229
+ }
230
+ }
231
+ if (!path && inTopicArtifacts(topic.id, item.id))
232
+ continue;
233
+ const stat = path ? statSync(path, { throwIfNoEntry: false }) : undefined;
234
+ rows.set(item.id, attributed({ ...item, path }, book.files?.[item.id], stat && fileVersion(stat)));
235
+ }
236
+ for (const [id, file] of local)
237
+ rows.set(id, attributed(rows.get(id), book.files?.[id], file.version));
238
+ const all = [...rows.values()].filter((w) => !book.hidden?.includes(w.id)).sort((a, b) => b.at - a.at);
239
+ const newest = new Set(all.filter((w) => !pinned.has(w.id)).slice(0, Number(ext.config.get('keep') ?? 3)).map((w) => w.id));
240
+ return all.map((w) => ({ ...present(w), pinned: pinned.has(w.id), current: pinned.has(w.id) || newest.has(w.id) }));
241
+ };
242
+ const sharedList = (topic, own = ownList(topic)) => {
243
+ const ancestors = topics.scopeIds(topic.id, 'lineage').filter((id) => id !== topic.id).reverse();
244
+ const inherited = new Set(ancestors);
245
+ const seen = new Set(own.map((work) => work.resource));
246
+ const share = (source, via, note) => {
247
+ const from = { topicId: source.id, title: source.title, via, ...(note ? { note } : {}) };
248
+ return ownList(source).filter((w) => w.kind !== 'commit' && !seen.has(w.resource) && seen.add(w.resource)).map((w) => ({
249
+ ...w, pinned: false, current: false, from,
250
+ }));
251
+ };
252
+ return [
253
+ ...ancestors.flatMap((id) => share(topics.get(id), 'ancestor')),
254
+ ...topics.topicRefsOf(topic.id).filter((ref) => !inherited.has(ref.topicId))
255
+ .flatMap((ref) => share(topics.get(ref.topicId), 'ref', ref.note)),
256
+ ];
257
+ };
258
+ const list = (topic) => {
259
+ const own = ownList(topic);
260
+ return [...own, ...sharedList(topic, own)];
261
+ };
262
+ const sourceOf = (topic, work) => work.from ? topics.get(work.from.topicId) : topic;
263
+ const requireOwn = (topic, resource, action) => {
264
+ const work = findWork(topic, resource);
265
+ if (work.from)
266
+ throw new Error(`共享素材来自「${work.from.title}」,请在来源主题${action}`);
267
+ return work;
268
+ };
269
+ const add = (topic, input, by) => {
270
+ const title = input.title.trim();
271
+ if (!title)
272
+ throw new Error('产物要有一个标题');
273
+ if (input.path) {
274
+ const path = isAbsolute(input.path) ? input.path : resolve(topic.dir, input.path);
275
+ if (!existsSync(path))
276
+ throw new Error(`没有这个文件:${path}`);
277
+ const book = bookOf(topic);
278
+ const real = realpathSync.native(path);
279
+ const stat = statSync(real);
280
+ if (!stat.isFile())
281
+ throw new Error('产物登记需要文件路径');
282
+ const zone = storageZone(relativeFile(realpathSync.native(topic.dir), real) ?? '');
283
+ if (zone === 'attachments' || zone === 'tmp') {
284
+ throw new HttpError(400, '正式产物请放入 artifacts/。聊天附件和临时文件可直接引用原路径。');
285
+ }
286
+ const at = locateFile(rootsOf(topic), real);
287
+ const resource = at && fileResource(topic.id, at.root, at.path);
288
+ const index = book.items.findIndex((item) => item.kind === 'file' && (resource ? item.id === resource :
289
+ item.path === path || (!!item.path && existsSync(item.path) && realpathSync.native(item.path) === real)));
290
+ const prior = book.items[index];
291
+ const work = {
292
+ id: resource ?? prior?.id ?? workResource(topic.id, newId('wrk')), kind: 'file', title,
293
+ ...(resource ? {} : { path: prior?.path ?? path }), by: '', registeredBy: by, at: Date.now(),
294
+ };
295
+ if (prior)
296
+ book.items[index] = work;
297
+ else
298
+ book.items.push(work);
299
+ save(topic, book);
300
+ changed({ topicId: topic.id, resource: work.id, kind: prior || resource && inTopicArtifacts(topic.id, resource) ? 'updated' : 'created' });
301
+ return present(attributed({ ...work, path }, book.files?.[work.id], fileVersion(stat)));
302
+ }
303
+ const book = bookOf(topic);
304
+ const work = { id: workResource(topic.id, newId('wrk')), kind: 'note', title, by, at: Date.now() };
305
+ if (input.url)
306
+ Object.assign(work, { kind: 'link', url: input.url });
307
+ else if (input.text)
308
+ work.text = input.text;
309
+ else
310
+ throw new Error('产物是一个文件(path)、一个链接(url)或一段结论(text)。主题目录 artifacts/ 下的文件不用登记,本来就是产物');
311
+ save(topic, { ...book, items: [...book.items, work] });
312
+ changed({ topicId: topic.id, resource: work.id, kind: 'created' });
313
+ return present(work);
314
+ };
315
+ const authoredWrite = (topic, book, resource, path, file, existed, by) => {
316
+ try {
317
+ const snapshot = localFile(path, statSync(file));
318
+ const op = fileChanged(book, resource, snapshot.version, !existed, { by, basis: 'write' });
319
+ save(topic, book);
320
+ record(topic, op);
321
+ if (inTopicArtifacts(topic.id, resource) && relativeFile(join(topic.dir, 'artifacts'), path)?.split('/').every((part) => !part.startsWith('.'))) {
322
+ fileTurns.get(topic.id)?.files.set(resource, snapshot);
323
+ }
324
+ changed({ topicId: topic.id, resource, kind: existed ? 'updated' : 'created' });
325
+ return present(attributed(madeFile(resource, snapshot), book.files?.[resource], snapshot.version));
326
+ }
327
+ catch (error) {
328
+ throw new Error(`已写入 ${path}。更新产物记录时出错:${errorText(error)}`);
329
+ }
330
+ };
331
+ const write = (topic, input, by) => {
332
+ const base = join(topic.dir, 'artifacts');
333
+ const root = join(realpathSync.native(topic.dir), 'artifacts');
334
+ const folder = lstatSync(root, { throwIfNoEntry: false });
335
+ if (folder && !folder.isDirectory())
336
+ throw new Error(`主题目录 artifacts/ 须为实际目录:${base}`);
337
+ const file = topicFile(root, input.path);
338
+ const rel = relativeFile(root, file);
339
+ const existed = existsSync(file);
340
+ const book = bookOf(topic);
341
+ mkdirSync(dirname(file), { recursive: true });
342
+ writeFileSync(file, input.content);
343
+ return authoredWrite(topic, book, topicResource(topic.id, rel), join(base, rel), file, existed, by);
344
+ };
345
+ const contentUrl = (id, resource) => `/api/topics/${id}/works/content?` + new URLSearchParams({ resource });
346
+ const fileView = (id, resource, path, url, title = basename(path)) => ({ resource, kind: 'file', path, title, url, content: contentUrl(id, resource) });
347
+ const workView = (topic, work) => {
348
+ const { resource, title, kind, path, url, text, repo, hash } = work;
349
+ if (kind !== 'file')
350
+ return { resource, title, kind, url, text, repo, hash, content: contentUrl(topic.id, resource) };
351
+ if (!path || !statSync(path, { throwIfNoEntry: false })?.isFile())
352
+ return;
353
+ const source = sourceOf(topic, work), at = resourceFile(source.id, rootsOf(source), resource);
354
+ return fileView(topic.id, resource, path, at && previewFile(source.id, at.root, at.path), title);
355
+ };
356
+ const resolveResource = (topic, address) => {
357
+ const work = list(topic).find((work) => work.resource === address);
358
+ if (work)
359
+ return workView(topic, work);
360
+ const at = resourceFile(topic.id, rootsOf(topic), address);
361
+ if (!at)
362
+ return;
363
+ const attachment = at.root.root === TOPIC_ROOT && messages.attachment(topic.id, at.path);
364
+ if (attachment) {
365
+ if (attachment.file)
366
+ return fileView(topic.id, address, attachment.file, attachment.url, basename(at.path));
367
+ return;
368
+ }
369
+ const candidate = join(at.root.dir, at.path);
370
+ if (!statSync(candidate, { throwIfNoEntry: false })?.isFile())
371
+ return;
372
+ const path = realpathSync.native(candidate);
373
+ if (relativeFile(at.boundary, path) === undefined)
374
+ return;
375
+ return fileView(topic.id, address, path, previewFile(topic.id, at.root, at.path));
376
+ };
377
+ const dataRoot = realpathSync.native(home.root);
378
+ const editablePath = (topic, resource) => {
379
+ if (topic.archivedAt !== null || !resource.path)
380
+ return;
381
+ const roots = rootsOf(topic);
382
+ const at = resourceFile(topic.id, roots, resource.resource);
383
+ if (!at || (!at.path.startsWith('artifacts/') && at.root === roots[0]))
384
+ return;
385
+ const file = realpathSync.native(resource.path);
386
+ const canonical = locateFile(roots, file);
387
+ if (!canonical || fileResource(topic.id, canonical.root, canonical.path) !== resource.resource ||
388
+ !projectWriteAccess(roots, dataRoot, file, false).canEdit)
389
+ return;
390
+ // Only the current topic's real artifacts/ or the exact mounted reference can supply the writable original.
391
+ if (file !== join(at.root.dir, at.path))
392
+ return;
393
+ if (at.root === roots[0] && !lstatSync(at.boundary, { throwIfNoEntry: false })?.isDirectory())
394
+ return;
395
+ return { file, path: at.root === roots[0] ? join(topic.dir, at.path) : file };
396
+ };
397
+ const viewOf = (topic, resource, locator) => registry.open(resource, { topicId: topic.id, locator, canEdit: !!editablePath(topic, resource) });
398
+ const open = (topic, address, locator) => {
399
+ const resource = resolveResource(topic, address);
400
+ return resource && viewOf(topic, resource, locator);
401
+ };
402
+ registerProjectFiles(ctx, dataRoot, (topicId, resource, file, url) => viewOf(need(topicId), fileView(topicId, resource, file, url)), (path) => registry.match('file', path)?.capabilities, projectChanged, (topicId, resource) => resolveResource(need(topicId), resource)?.path, (topicId) => retentionFor(need(topicId)));
403
+ ctx.effect(entry.op({
404
+ name: 'files.retain', about: '保留或取消保留主题 artifacts/、attachments/、tmp/ 内的原件。保留目录会保护里面的文件。',
405
+ input: object({ id: { type: 'string' }, resource: resourceField, on: { type: 'boolean' } }, ['id', 'resource', 'on']),
406
+ http: ['PUT', '/api/topics/:id/files/retention'], topic: 'id', agent: true,
407
+ run({ id, resource, on }) {
408
+ const topic = writable(id);
409
+ const target = managedResource(id, resource);
410
+ if (!target)
411
+ throw new HttpError(403, '只能保留本主题管理的文件或目录');
412
+ const file = join(realpathSync.native(topic.dir), target.path);
413
+ const stat = lstatSync(file, { throwIfNoEntry: false });
414
+ if (!stat)
415
+ throw new HttpError(404, '文件或目录不存在');
416
+ if (!(stat.isDirectory() || stat.isFile()) || realpathSync.native(file) !== file) {
417
+ throw new HttpError(403, '请选择文件树里的原始位置');
418
+ }
419
+ const book = bookOf(topic);
420
+ const retained = new Set(book.retained);
421
+ if (retained.has(resource) !== on) {
422
+ if (on)
423
+ retained.add(resource);
424
+ else
425
+ retained.delete(resource);
426
+ book.retained = [...retained];
427
+ save(topic, book);
428
+ changed({ topicId: id, resource: resource, kind: 'retention', entry: { path: file } });
429
+ }
430
+ return resourceRetention(resource, book);
431
+ },
432
+ }));
433
+ const editTarget = (id, address) => {
434
+ const topic = writable(id);
435
+ const resource = resolveResource(topic, address);
436
+ if (!resource)
437
+ throw new HttpError(404, '找不到这份文件');
438
+ const path = editablePath(topic, resource);
439
+ if (!path)
440
+ throw new HttpError(403, '这个原件不在当前主题的可写范围中');
441
+ const editor = registry.editor(resource);
442
+ if (!editor)
443
+ throw new HttpError(415, '这个格式只支持阅读');
444
+ return { topic, ...path, editor };
445
+ };
446
+ const revisionOf = (bytes) => hash('sha256', bytes);
447
+ const saveLock = createFileLock();
448
+ ctx.effect(entry.op({
449
+ name: 'files.edit', about: '读取完整的可编辑正文及原件版本。',
450
+ input: object({ id: { type: 'string' }, resource: resourceField }, ['id', 'resource']),
451
+ http: ['GET', '/api/topics/:id/files/edit'],
452
+ async run({ id, resource }) {
453
+ const { file, editor } = editTarget(id, resource);
454
+ const bytes = readFileSync(file);
455
+ return { ...(await editor.read(bytes)), revision: revisionOf(bytes) };
456
+ },
457
+ }));
458
+ ctx.effect(entry.op({
459
+ name: 'files.save', about: '按读取时的版本将正文改动写回原件。',
460
+ input: object({
461
+ id: { type: 'string' }, resource: resourceField, revision: { type: 'string' },
462
+ text: { type: 'string' }, runs: array(object({ index: { type: 'integer' }, text: { type: 'string' } }, ['index', 'text'])),
463
+ }, ['id', 'resource', 'revision']),
464
+ http: ['PUT', '/api/topics/:id/files/edit'],
465
+ async run({ id, resource, revision, text, runs }, caller) {
466
+ const initial = editTarget(id, resource);
467
+ const bytes = readFileSync(initial.file);
468
+ const conflict = () => new HttpError(409, '原件已更新,草稿仍保留');
469
+ if (revisionOf(bytes) !== revision)
470
+ throw conflict();
471
+ const updated = await initial.editor.apply(bytes, { text, runs });
472
+ const verify = () => {
473
+ const current = editTarget(id, resource);
474
+ if (current.file !== initial.file || current.editor !== initial.editor ||
475
+ revisionOf(readFileSync(current.file)) !== revision)
476
+ throw conflict();
477
+ return current;
478
+ };
479
+ return saveLock(initial.file, async () => {
480
+ let current = verify();
481
+ if (bytes.equals(updated))
482
+ return { revision };
483
+ const temp = join(dirname(current.file), '.' + newId('edit'));
484
+ let book;
485
+ let moved = false;
486
+ try {
487
+ const mode = statSync(current.file).mode & 0o777;
488
+ writeExclusiveFile(temp, updated, mode);
489
+ book = await replaceFile(temp, current.file, () => {
490
+ current = verify();
491
+ return bookOf(current.topic);
492
+ });
493
+ moved = true;
494
+ }
495
+ finally {
496
+ if (!moved) {
497
+ try {
498
+ rmSync(temp, { force: true, maxRetries: 5, retryDelay: 20 });
499
+ }
500
+ catch { /* best-effort cleanup of the staged edit file */ }
501
+ }
502
+ }
503
+ authoredWrite(current.topic, book, resource, current.path, current.file, true, actorOf(caller));
504
+ return { revision: revisionOf(updated) };
505
+ });
506
+ },
507
+ }));
508
+ ctx.effect(entry.op({
509
+ name: 'works.resource', about: '读取一个资源由哪种查看器打开、查看器能力及原件内容地址。',
510
+ input: object({ id: { type: 'string' }, resource: resourceField, locator: { type: 'string', description: 'JSON 编码的定位信息' } }, ['id', 'resource']),
511
+ http: ['GET', '/api/topics/:id/works/resource'],
512
+ run({ id, resource, locator }) {
513
+ let location;
514
+ if (locator) {
515
+ try {
516
+ location = JSON.parse(locator);
517
+ }
518
+ catch {
519
+ throw new HttpError(400, 'locator 须为 JSON 对象');
520
+ }
521
+ const problem = check(locatorField, location, 'locator');
522
+ if (problem)
523
+ throw new HttpError(400, problem);
524
+ validateLocator(location);
525
+ }
526
+ const view = open(need(id), resource, location);
527
+ if (!view)
528
+ throw new HttpError(404, '找不到这份产物或文件');
529
+ return view;
530
+ },
531
+ }));
532
+ const nameOf = (id) => (id ? members.get(id)?.name ?? id : '');
533
+ const fileAuthors = (w) => {
534
+ const label = (id, basis) => (nameOf(id ?? '') || '未确认') + (basis === 'turn' ? '(回合推定)' : '');
535
+ return [
536
+ '创建者 ' + label(w.by, w.byBasis),
537
+ '最近修改者 ' + label(w.updatedBy, w.updatedByBasis),
538
+ ...(w.registeredBy ? ['登记者 ' + nameOf(w.registeredBy)] : []),
539
+ ];
540
+ };
541
+ const mountedRoots = () => [...new Set(topics.list().filter((topic) => topic.archivedAt === null)
542
+ .flatMap((topic) => topic.refs.filter(isDirRef).map(({ path }) => path)))]
543
+ .filter((path) => existsSync(path)).map((path) => realpathSync.native(path));
544
+ /** What sits at a topic's root and belongs to someone: the host's records and what plugins declare. */
545
+ const records = async () => new Set([...coreRecords, ...(await ctx.runtime.serial('topic.records', {})).flat()]);
546
+ const activeTmp = (topicId) => !!a2a.live(topicId).length ||
547
+ (ctx.runtime.has('background') && !!ctx.get('background').running(topicId).length);
548
+ ctx.provide('storage.topicResources', {
549
+ async candidates(topicIds) {
550
+ const mounted = mountedRoots(), kept = await records();
551
+ const active = [];
552
+ for (const id of topicIds) {
553
+ const topic = topics.get(id);
554
+ if (topic && topic.deletedAt === null && topic.archivedAt === null)
555
+ active.push(topic);
556
+ }
557
+ const buckets = new Array(active.length);
558
+ let cursor = 0;
559
+ const worker = async () => {
560
+ while (cursor < active.length) {
561
+ const index = cursor++;
562
+ const topic = active[index];
563
+ const list = await cleanupCandidates(topic, {
564
+ marks: bookOf(topic), mounted, zones: ['attachments', 'tmp', 'other'], records: kept,
565
+ activeTmp: activeTmp(topic.id),
566
+ });
567
+ buckets[index] = list.map(inventoryEntry);
568
+ }
569
+ };
570
+ const workers = Math.min(4, active.length);
571
+ await Promise.all(Array.from({ length: workers }, worker));
572
+ return buckets.flat();
573
+ },
574
+ async clean(id, entries) {
575
+ const kept = await records();
576
+ const topic = writable(id);
577
+ const book = bookOf(topic), mounted = mountedRoots();
578
+ const policy = { marks: book, mounted, records: kept, activeTmp: activeTmp(topic.id) };
579
+ const removed = [];
580
+ for (const target of entries) {
581
+ try {
582
+ const done = await removeVerifiedTarget(topic, target, policy);
583
+ if (done)
584
+ removed.push(done);
585
+ }
586
+ catch (error) {
587
+ ctx.runtime.onError(`works: removing ${target.resource}`, error);
588
+ }
589
+ }
590
+ if (!removed.length)
591
+ return removed;
592
+ const gone = removed.map(({ resource }) => resource);
593
+ try {
594
+ if (rewriteFileRecords(book, (res) => gone.some((root) => resourceWithin(res, root)) ? undefined : res))
595
+ save(topic, book);
596
+ else
597
+ topics.touch(topic.id);
598
+ }
599
+ finally {
600
+ const base = existsSync(topic.dir) ? realpathSync.native(topic.dir) : topic.dir;
601
+ const turns = fileTurns.get(topic.id)?.files;
602
+ for (const { resource, path } of removed) {
603
+ if (turns) {
604
+ for (const key of [...turns.keys()])
605
+ if (resourceWithin(key, resource))
606
+ turns.delete(key);
607
+ }
608
+ changed({ topicId: topic.id, resource, kind: 'deleted', entry: { path: join(base, path) } });
609
+ }
610
+ }
611
+ return removed;
612
+ },
613
+ });
614
+ // ── observations and command delivery ─────────────────────────────────
615
+ const opsFile = (topic) => join(topic.dir, 'works.jsonl');
616
+ const journal = (topic, limit, matches) => recentEvents(opsFile(topic), limit, matches);
617
+ const record = (topic, op) => {
618
+ appendFileSync(opsFile(topic), `${JSON.stringify(op)}\n`);
619
+ return op;
620
+ };
621
+ const findWork = (topic, target) => {
622
+ const work = list(topic).find((w) => w.resource === target);
623
+ if (!work)
624
+ throw new HttpError(400, `没有这个产物:${target}(用 works.list 看有哪些)`);
625
+ return work;
626
+ };
627
+ const observe = (topic, input, by) => {
628
+ if (input.event === 'annotate') {
629
+ if (topic.archivedAt !== null)
630
+ throw new HttpError(409, '主题已归档');
631
+ const body = input.payload?.body;
632
+ if (typeof body !== 'string' || !body.trim())
633
+ throw new HttpError(400, '请填写批注正文');
634
+ if (input.resource && !resolveResource(topic, input.resource))
635
+ throw new HttpError(404, '找不到这份产物或文件');
636
+ input.payload = { ...input.payload, body: body.trim(), annotationId: newId('ann') };
637
+ }
638
+ return record(topic, { ...input, by, at: Date.now() });
639
+ };
640
+ const receivers = new Map();
641
+ const receiverKey = (surface, target) => JSON.stringify([surface, target]);
642
+ ctx.provide('works', {
643
+ list, open, parseResource, resourceWithin,
644
+ links(prefix) {
645
+ const hits = [];
646
+ for (const [topicId, urls] of ensureLinkIndex()) {
647
+ for (const url of urls)
648
+ if (url.startsWith(prefix))
649
+ hits.push({ topicId, url });
650
+ }
651
+ return hits;
652
+ },
653
+ link(topic, input, by) {
654
+ const target = writable(topic.id);
655
+ if (bookOf(target).items.some((item) => item.kind === 'link' && item.url === input.url))
656
+ return;
657
+ add(target, input, by);
658
+ },
659
+ registerViewer(viewer) {
660
+ const dispose = registry.register(viewer);
661
+ const push = ctx.get('push');
662
+ push.send('works.viewers', {});
663
+ return () => { dispose(); push.send('works.viewers', {}); };
664
+ },
665
+ register(receiver) {
666
+ const key = receiverKey(receiver.surface, receiver.target);
667
+ if (receivers.has(key))
668
+ throw new Error(`已有操作接收者:${receiver.surface} ${receiver.target}`);
669
+ receivers.set(key, receiver);
670
+ return () => void receivers.delete(key);
671
+ },
672
+ });
673
+ const dispatch = async (topic, input, by) => {
674
+ const op = { ...input, by, at: Date.now() };
675
+ if (op.resource === undefined) {
676
+ const receiver = receivers.get(receiverKey(op.surface, op.target));
677
+ if (!receiver?.events.includes(op.event))
678
+ throw new HttpError(400, `未声明此动作:${op.surface} ${op.target} ${op.event}`);
679
+ await receiver.receive(topic.id, op);
680
+ return record(topic, op);
681
+ }
682
+ const view = open(topic, op.resource, op.locator);
683
+ if (!view)
684
+ throw new HttpError(404, '找不到这份产物或文件');
685
+ if (!view.capabilities.actions?.includes(op.event))
686
+ throw new HttpError(400, `查看器不支持此动作:${op.event}`);
687
+ const { url, frame, initialUrl, renderer } = view.open;
688
+ const written = record(topic, op);
689
+ if (frame)
690
+ ctx.get('push').send('works.op', { topicId: topic.id, op: written });
691
+ if (op.event === 'open') {
692
+ ctx.get('push').send('console.open', {
693
+ topicId: topic.id, url, ...(frame ? {
694
+ frame, title: view.title, initialUrl: renderer ? (initialUrl ?? url) + '#dispatched-open' : initialUrl,
695
+ } : {}),
696
+ });
697
+ }
698
+ return written;
699
+ };
700
+ const opLine = (op, works) => {
701
+ const { page, time, text, ...position } = op.locator ?? {};
702
+ const details = [
703
+ page !== undefined && `第 ${page} 页`, time !== undefined && `${time} 秒处`, text && `「${text}」`,
704
+ Object.keys(position).length && JSON.stringify(position), op.payload && JSON.stringify(op.payload),
705
+ ].filter(Boolean);
706
+ const target = op.resource ? works.get(op.resource)?.title ?? op.resource : `${op.surface} ${op.target}`;
707
+ return [`[${new Date(op.at).toLocaleTimeString()}]`, nameOf(op.by) || '归属未确认', op.event, target, ...details].join(' ');
708
+ };
709
+ // ── file authorship: compare at each turn boundary ─────────────────────────
710
+ const fileChanged = (book, id, version, created, author) => {
711
+ book.files ??= {};
712
+ const original = created ? author : book.files[id]?.created;
713
+ book.files[id] = { version, ...(original ? { created: original } : {}), ...(author ? { updated: author } : {}) };
714
+ return {
715
+ resource: id, event: created ? 'create' : 'update', by: author?.by ?? '',
716
+ at: Date.now(), payload: { basis: author?.basis ?? 'unknown' },
717
+ };
718
+ };
719
+ const captureFiles = (topic, state, files) => {
720
+ const book = bookOf(topic);
721
+ const changedFile = (kind, resource) => ({ topicId: topic.id, resource, kind });
722
+ const appeared = new Map([...files].filter(([id, file]) => file.identity && !state.files.has(id)).map(([id, file]) => [file.identity, id]));
723
+ const moved = new Map();
724
+ const pending = [];
725
+ let metadataChanged = false;
726
+ for (const [resource, prior] of state.files) {
727
+ if (files.has(resource))
728
+ continue;
729
+ const nextResource = prior.identity && appeared.get(prior.identity);
730
+ if (nextResource) {
731
+ updateFileRecords(book, resource, nextResource);
732
+ metadataChanged = true;
733
+ moved.set(nextResource, prior);
734
+ pending.push({ topicId: topic.id, resource, kind: 'moved', nextResource });
735
+ }
736
+ else {
737
+ if (book.files?.[resource]) {
738
+ delete book.files[resource];
739
+ metadataChanged = true;
740
+ }
741
+ pending.push(changedFile('deleted', resource));
742
+ }
743
+ }
744
+ const by = state.active.size === 1 ? state.active.values().next().value : undefined;
745
+ const author = by ? { by, basis: 'turn' } : undefined;
746
+ const observations = [];
747
+ for (const [resource, file] of files) {
748
+ const prior = state.files.get(resource) ?? moved.get(resource);
749
+ if (sameVersion(prior?.version, file.version) || sameVersion(book.files?.[resource]?.version, file.version))
750
+ continue;
751
+ observations.push(fileChanged(book, resource, file.version, !prior, author));
752
+ if (!moved.has(resource))
753
+ pending.push(changedFile(prior ? 'updated' : 'created', resource));
754
+ }
755
+ if (observations.length || metadataChanged) {
756
+ save(topic, book);
757
+ for (const observation of observations)
758
+ record(topic, observation);
759
+ }
760
+ state.files = files;
761
+ for (const change of pending)
762
+ changed(change);
763
+ };
764
+ ctx.on('turn.started', ({ turn }) => {
765
+ const topic = topics.get(turn.topicId);
766
+ if (!topic || topic.deletedAt !== null || topic.archivedAt !== null)
767
+ return;
768
+ const state = fileTurns.get(topic.id);
769
+ if (state) {
770
+ try {
771
+ captureFiles(topic, state, localFiles(topic));
772
+ }
773
+ finally {
774
+ state.active.set(turn.turnId, turn.memberId);
775
+ }
776
+ }
777
+ else
778
+ fileTurns.set(topic.id, { files: localFiles(topic), active: new Map([[turn.turnId, turn.memberId]]) });
779
+ });
780
+ ctx.on('turn.ended', ({ turn }) => {
781
+ const state = fileTurns.get(turn.topicId);
782
+ if (!state?.active.has(turn.id))
783
+ return;
784
+ try {
785
+ const topic = topics.get(turn.topicId);
786
+ if (topic && topic.deletedAt === null && topic.archivedAt === null)
787
+ captureFiles(topic, state, localFiles(topic));
788
+ }
789
+ finally {
790
+ state.active.delete(turn.id);
791
+ if (!state.active.size)
792
+ fileTurns.delete(turn.topicId);
793
+ }
794
+ });
795
+ // ── commits: what was committed during this topic's turns, in the repositories it references ──
796
+ mkdirSync(home.path('plugins', 'works'), { recursive: true });
797
+ const claimedFile = home.path('plugins', 'works', 'claimed.json');
798
+ const git = (repo, args) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
799
+ const reposOf = (topicId) => topics.refsOf(topicId).filter(({ path }) => existsSync(join(path, '.git')));
800
+ const repoPath = (topicId, refId) => topics.refsOf(topicId).find((ref) => ref.refId === refId)?.path;
801
+ const headOf = (repo) => { try {
802
+ return git(repo, ['rev-parse', 'HEAD']);
803
+ }
804
+ catch {
805
+ return '';
806
+ } };
807
+ ctx.on('turn.started', ({ turn }) => {
808
+ const topic = topics.get(turn.topicId);
809
+ if (!topic || topic.deletedAt !== null || topic.archivedAt !== null)
810
+ return;
811
+ const book = bookOf(topic);
812
+ const unseen = reposOf(topic.id).filter(({ refId }) => !(refId in book.heads));
813
+ if (unseen.length)
814
+ writeFileSync(join(topic.dir, 'works.json'), `${JSON.stringify({ ...book, heads: { ...book.heads, ...Object.fromEntries(unseen.map(({ refId, path }) => [refId, headOf(path)])) } }, null, 2)}\n`);
815
+ });
816
+ ctx.on('turn.ended', ({ turn }) => {
817
+ const topic = topics.get(turn.topicId);
818
+ if (!topic || topic.deletedAt !== null || topic.archivedAt !== null)
819
+ return;
820
+ const book = bookOf(topic);
821
+ const claimed = new Set(existsSync(claimedFile) ? JSON.parse(readFileSync(claimedFile, 'utf8')) : []);
822
+ const hashes = new Set([...claimed].map((claim) => claim.slice(claim.indexOf(':') + 1)));
823
+ const found = [];
824
+ let advanced = false;
825
+ for (const { refId, path } of reposOf(topic.id)) {
826
+ const head = headOf(path);
827
+ const old = book.heads[refId];
828
+ if (old === undefined || head === old)
829
+ continue;
830
+ try {
831
+ for (const line of git(path, ['log', '--format=%H%x09%ct%x09%s', '-n', '100', old ? `${old}..HEAD` : 'HEAD']).split('\n').filter(Boolean)) {
832
+ const [hash, at, title] = line.split('\t');
833
+ if (hashes.has(hash))
834
+ continue; // one topic claims a commit, even through another reference to the same repository
835
+ hashes.add(hash);
836
+ claimed.add(`${refId}:${hash}`);
837
+ found.push({ id: workResource(topic.id, `commit:${hash.slice(0, 12)}`), kind: 'commit', title: title ?? hash, repo: refId, hash: hash, by: turn.memberId, at: Number(at) * 1000 });
838
+ }
839
+ book.heads[refId] = head;
840
+ advanced = true;
841
+ }
842
+ catch (problem) {
843
+ ctx.runtime.onError('works: reading commits', problem);
844
+ }
845
+ }
846
+ if (!advanced)
847
+ return;
848
+ if (found.length)
849
+ writeFileSync(claimedFile, JSON.stringify([...claimed]));
850
+ save(topic, { ...book, items: [...book.items, ...found] });
851
+ for (const work of found)
852
+ changed({ topicId: topic.id, resource: work.id, kind: 'created' });
853
+ });
854
+ const workLine = (topic, w) => {
855
+ const detail = w.kind === 'file' ? `文件 ${w.path ?? w.resource}` : w.kind === 'link' ? `链接 ${w.url}` :
856
+ w.kind === 'commit' ? `提交 ${w.hash.slice(0, 8)} @ ${repoPath(topic.id, w.repo) ?? w.repo}` : `结论:${w.text}`;
857
+ return [
858
+ `- ${w.title}(${w.id})${detail}`,
859
+ ...(w.kind === 'file' ? fileAuthors(w) : [nameOf(w.by)]),
860
+ w.from ? sourceLine(w.from) : w.pinned ? '置顶' : w.current ? '' : '素材',
861
+ ].filter(Boolean).join(' · ');
862
+ };
863
+ const describeWork = (topic, w) => {
864
+ const path = w.kind === 'file' && w.path ? relativeFile(sourceOf(topic, w).dir, w.path) ?? w.path : w.resource;
865
+ const detail = w.kind === 'file' ? `文件 ${path}` : w.kind === 'link' ? `链接 ${w.url}` :
866
+ w.kind === 'commit' ? `提交 ${w.hash.slice(0, 8)} · ${basename(repoPath(topic.id, w.repo) ?? w.repo)}` : w.text;
867
+ const target = workView(topic, w);
868
+ const address = target && registry.open(target, { topicId: topic.id }).open;
869
+ return {
870
+ sub: [detail, w.from && sourceLine(w.from), w.from?.note,
871
+ ...(w.kind === 'file' ? fileAuthors(w) : [nameOf(w.by)]), new Date(w.at).toLocaleString()].filter(Boolean).join(' · '),
872
+ ...(address ? { open: { url: address.url, ...(address.frame ? { frame: true } : {}) } } : {}),
873
+ };
874
+ };
875
+ ctx.effect(entry.op({
876
+ name: 'works.list', about: '列出当前主题产物与来自祖先和引用主题的共享素材。',
877
+ input: object({
878
+ id: { type: 'string' },
879
+ scope: { type: 'string', enum: ['all', 'own', 'shared'], description: '默认 all,own 只列本主题产物,shared 只列共享素材' },
880
+ target: { type: 'string', description: '按资源地址查一项' },
881
+ }, ['id']),
882
+ http: ['GET', '/api/topics/:id/works'], topic: 'id', agent: true,
883
+ run({ id, scope, target }) {
884
+ const topic = need(id);
885
+ const available = scope === 'own' ? ownList(topic) : scope === 'shared' ? sharedList(topic) : list(topic);
886
+ const selected = target ? available.filter((work) => work.resource === target) : available;
887
+ const retentionOf = retentionFor(topic);
888
+ return selected.map((work) => ({ ...work, ...describeWork(topic, work),
889
+ retention: work.from ? undefined : retentionOf(work.resource) }));
890
+ },
891
+ text: (works, { id }) => {
892
+ const topic = need(id);
893
+ return works.map((work) => workLine(topic, work)).join('\n') || '(还没有产物)';
894
+ },
895
+ }));
896
+ ctx.effect(entry.op({
897
+ name: 'works.add', about: '登记一件正式产物。填 title 和 path(文件)、url(链接)或 text(结论)之一。主题 artifacts/ 的文件自动列出,外部原件用 path 登记。主题自己的临时文件和聊天附件可直接按路径引用。',
898
+ input: object({
899
+ id: { type: 'string' }, title: { type: 'string' },
900
+ path: { type: 'string' }, url: { type: 'string' }, text: { type: 'string' },
901
+ kind: { type: 'string', enum: ['path', 'url', 'text'] }, value: { type: 'string' },
902
+ }, ['id', 'title']),
903
+ http: ['POST', '/api/topics/:id/works'], topic: 'id', agent: true,
904
+ run: ({ id, title, kind, value, path, url, text }, caller) => add(writable(id), kind ? { title, [kind]: value } : { title, path, url, text }, actorOf(caller)),
905
+ text: (work) => `已登记「${work.title}」。`,
906
+ }));
907
+ ctx.effect(entry.op({
908
+ name: 'works.write', about: '在主题 artifacts/ 写入当前主题的正式产物(RFC、标准文档、资料包)。临时脚本、补丁和验收过程文件直接写入 tmp/。',
909
+ input: object({
910
+ id: { type: 'string' },
911
+ path: { type: 'string', description: '相对于主题 artifacts/ 的文件路径,如 reports/plan.md' },
912
+ content: { type: 'string', description: '要写入的 UTF-8 文本内容' },
913
+ }, ['id', 'path', 'content']),
914
+ http: ['POST', '/api/topics/:id/works/write'], topic: 'id', agent: true,
915
+ run: ({ id, path, content }, caller) => write(writable(id), { path, content }, actorOf(caller)),
916
+ text: (work) => `已写入 ${work.path}(${work.id})。`,
917
+ }));
918
+ ctx.effect(entry.op({
919
+ name: 'works.remove', about: '按资源地址从主题页移除一件产物。文件仍留在原处。',
920
+ input: object({ id: { type: 'string' }, work: { type: 'string' } }, ['id', 'work']),
921
+ http: ['DELETE', '/api/topics/:id/works/:work'], topic: 'id', agent: true,
922
+ run({ id, work }) {
923
+ const topic = writable(id);
924
+ const { resource } = requireOwn(topic, work, '移除');
925
+ const book = bookOf(topic);
926
+ // A file under artifacts/ is only hidden. Registered and claimed works are removed from the book.
927
+ const derived = inTopicArtifacts(topic.id, resource);
928
+ if (!derived && book.files)
929
+ delete book.files[resource];
930
+ save(topic, { ...book, items: derived ? book.items : book.items.filter((w) => w.id !== resource),
931
+ pinned: book.pinned.filter((id) => id !== resource), ...(derived ? { hidden: [...(book.hidden ?? []), resource] } : {}) });
932
+ changed({ topicId: id, resource, kind: 'deleted' });
933
+ },
934
+ }));
935
+ ctx.effect(entry.op({
936
+ name: 'works.pin', about: '按编号置顶一件产物。on 为 true 时置顶,为 false 或省略时取消置顶。',
937
+ input: object({ id: { type: 'string' }, work: { type: 'string' }, on: { type: 'boolean' } }, ['id', 'work']),
938
+ http: ['POST', '/api/topics/:id/works/pin'], topic: 'id', agent: true,
939
+ run({ id, work, on }) {
940
+ const topic = writable(id);
941
+ requireOwn(topic, work, on ? '置顶' : '取消置顶');
942
+ const book = bookOf(topic);
943
+ const rest = book.pinned.filter((id) => id !== work);
944
+ save(topic, { ...book, pinned: on ? [...rest, work] : rest });
945
+ const target = managedResource(id, work);
946
+ if (target)
947
+ changed({ topicId: id, resource: work, kind: 'retention',
948
+ entry: { path: join(realpathSync.native(topic.dir), target.path) } });
949
+ },
950
+ }));
951
+ ctx.effect(entry.op({
952
+ name: 'works.log', about: '按需查看当前主题的观测、批注和已投递动作。可按资源地址、界面、对象、事件或批注编号筛选。',
953
+ input: object({
954
+ id: { type: 'string' }, resource: resourceField, surface: eventFields.surface, target: eventFields.target, event: eventFields.event,
955
+ annotationId: { type: 'string' }, limit: { type: 'number', description: '筛选后最多返回几条' },
956
+ }, ['id']),
957
+ http: ['GET', '/api/topics/:id/works/ops'], topic: 'id', agent: true,
958
+ run({ id, limit, resource, surface, target, event, annotationId }, { member }) {
959
+ const topic = need(id);
960
+ const size = Math.trunc(Math.max(1, Math.min(limit || (member ? 30 : 50), member ? 200 : 500)));
961
+ return journal(topic, size, (op) => (resource === undefined || op.resource === resource) &&
962
+ (surface === undefined || op.surface === surface) && (target === undefined || op.target === target) &&
963
+ (event === undefined || op.event === event) &&
964
+ (annotationId === undefined || (op.event === 'annotate' && op.payload?.annotationId === annotationId)));
965
+ },
966
+ text(ops, { id }) {
967
+ if (!ops.length)
968
+ return '(没有匹配的工作台事件)';
969
+ const works = ops.some((op) => op.resource) ? new Map(list(need(id)).map((w) => [w.resource, w])) : new Map();
970
+ return ops.map((op) => opLine(op, works)).join('\n');
971
+ },
972
+ }));
973
+ ctx.effect(entry.op({
974
+ name: 'works.observe', about: '记下工作台观测。批注填 event: annotate 与 payload.body,返回批注编号。',
975
+ input: object({ id: { type: 'string' }, ...eventFields }, ['id', 'event']),
976
+ http: ['POST', '/api/topics/:id/works/events'], topic: 'id', agent: true, maxBody: 2 * EVENT_SIZE,
977
+ run: ({ id, ...input }, caller) => observe(need(id), publicEvent(input), actorOf(caller)),
978
+ text: (op) => op.payload?.annotationId ? `已保存批注 ${op.payload.annotationId}` : `已记录 ${op.event}`,
979
+ }));
980
+ ctx.effect(entry.op({
981
+ name: 'works.act', about: '向查看器投递 resource、event 与可选 locator。非文件工作台动作使用 surface 和 target 指定接收者。',
982
+ input: object({ id: { type: 'string' }, ...eventFields }, ['id', 'event']),
983
+ http: ['POST', '/api/topics/:id/works/ops'], topic: 'id', agent: true, maxBody: 2 * EVENT_SIZE,
984
+ run: ({ id, ...input }, caller) => dispatch(need(id), publicEvent(input), actorOf(caller)),
985
+ text(op, { id }) {
986
+ const works = op.resource ? new Map(list(need(id)).map((w) => [w.resource, w])) : new Map();
987
+ return `好:${opLine(op, works)}`;
988
+ },
989
+ }));
990
+ ctx.hook('skills.dirs', () => fileURLToPath(new URL('./skills', import.meta.url)));
991
+ ctx.hook('topic.records', () => ['works.json', 'works.jsonl']);
992
+ // ── for the overview, topic context and memory ────────────────────────
993
+ const groupsFor = (topicId) => {
994
+ const topic = topics.get(topicId);
995
+ if (!topic)
996
+ return undefined;
997
+ const all = ownList(topic);
998
+ const entry = (w) => ({ id: w.id, title: w.title, sub: describeWork(topic, w).sub });
999
+ return {
1000
+ current: all.filter((w) => w.current).map(entry),
1001
+ older: all.filter((w) => !w.current).map(entry),
1002
+ shared: sharedList(topic, all).map(entry),
1003
+ };
1004
+ };
1005
+ ctx.note('topic.context', { title: '当前产物清单,及历史素材与共享素材的数量提示', when: '成员查看主题说明或进入主题首轮时(历史与共享素材明细按需用 works.list 查)' });
1006
+ ctx.hook('topic.context', ({ topicId }) => {
1007
+ const groups = groupsFor(topicId);
1008
+ if (!groups)
1009
+ return undefined;
1010
+ const format = (title, rows) => `${title}:${rows.length ? `\n${rows.map((r) => `- ${r.title}(${r.id}):${r.sub}`).join('\n')}` : '(还没有)'}`;
1011
+ return [
1012
+ format('产物', groups.current),
1013
+ ...(groups.older.length ? [`素材:另有 ${groups.older.length} 份更早的素材(需要时用 host_invoke 调 works.list 查看)`] : []),
1014
+ ...(groups.shared.length ? [`共享素材:${groups.shared.length} 份(需要时用 host_invoke 调 works.list(scope: "shared") 查看)`] : []),
1015
+ ].join('\n');
1016
+ });
1017
+ ctx.hook('memory.sources', () => ({
1018
+ event: 'resource.changed',
1019
+ topics(sourceId) {
1020
+ const sources = sourceId ? [sourceId] : topics.list().filter((topic) => ownList(topic).length).map((topic) => topic.id);
1021
+ const affected = new Set(sources);
1022
+ for (const id of affected)
1023
+ for (const child of topics.children(id))
1024
+ affected.add(child.id);
1025
+ for (const id of sources)
1026
+ for (const ref of topics.referencedBy(id))
1027
+ affected.add(ref.topicId);
1028
+ return affected;
1029
+ },
1030
+ docs(topicId) {
1031
+ const groups = groupsFor(topicId);
1032
+ if (!groups)
1033
+ return [];
1034
+ const toDoc = (id, title, rows) => ({
1035
+ id, title,
1036
+ text: rows.map((row) => [row.title, row.sub].filter(Boolean).join(':')).join('\n'),
1037
+ rowIds: rows.map((row) => row.id),
1038
+ });
1039
+ return [
1040
+ ...(groups.current.length ? [toDoc('works', '产物', groups.current)] : []),
1041
+ ...(groups.older.length ? [toDoc('materials', `素材(更早的 ${groups.older.length} 份)`, groups.older)] : []),
1042
+ ...(groups.shared.length ? [toDoc('shared-works', `共享素材(${groups.shared.length} 份)`, groups.shared)] : []),
1043
+ ];
1044
+ },
1045
+ }));
1046
+ // What the viewer shows: the file of a work as it is (with ranges, for video), or what a commit changed.
1047
+ ctx.effect(entry.route('GET', '/api/topics/:id/works/content', ({ params, query, raw, res }) => {
1048
+ const topic = need(params.id);
1049
+ const address = query.get('resource');
1050
+ const work = address && resolveResource(topic, address);
1051
+ if (!work)
1052
+ throw new HttpError(404, '没有这个资源');
1053
+ if (work.kind === 'commit') {
1054
+ const repo = repoPath(topic.id, work.repo);
1055
+ if (!repo)
1056
+ throw new HttpError(404, '没有这个仓库引用');
1057
+ try {
1058
+ return { text: git(repo, ['show', '--stat', '--patch', '--format=%H%n%an %ad%n%n%B', work.hash]).slice(0, 400_000) };
1059
+ }
1060
+ catch (error) {
1061
+ throw new HttpError(400, errorText(error));
1062
+ }
1063
+ }
1064
+ if (work.kind !== 'file')
1065
+ throw new HttpError(404, '这个产物的文件不在了');
1066
+ const file = work.path;
1067
+ if (!fileMime(file).startsWith('text/html'))
1068
+ return sendUserFile(res, file, raw);
1069
+ sandboxUserContent(res);
1070
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-cache', 'content-length': statSync(file).size });
1071
+ const stream = createReadStream(file);
1072
+ res.once('close', () => stream.destroy());
1073
+ stream.on('error', (error) => res.destroy(error)).pipe(res);
1074
+ return HANDLED;
1075
+ }));
1076
+ // The viewer page and its document libraries, straight from where npm put them.
1077
+ const mount = (prefix, dir) => { if (existsSync(dir))
1078
+ ctx.effect(entry.files(prefix, dir)); };
1079
+ const here = fileURLToPath(new URL('.', import.meta.url));
1080
+ mount('/works/lib/docx-preview', join(packageRoot('docx-preview', import.meta.url), 'dist'));
1081
+ mount('/works/lib/jszip', join(packageRoot('jszip', import.meta.url), 'dist'));
1082
+ mount('/works/lib/pdfjs', packageRoot('pdfjs-dist', import.meta.url));
1083
+ mount('/works/lib/pptx-wasm', join(packageRoot('pptx-wasm', import.meta.url), 'dist'));
1084
+ mount('/works/lib/read-excel-file', join(packageRoot('read-excel-file/package.json', import.meta.url), 'bundle'));
1085
+ mount('/works', join(here, 'web'));
1086
+ },
1087
+ };
1088
+ }