hostlet 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +916 -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 +130 -0
  330. package/dist/plugins/model-profiles/rules.js +729 -0
  331. package/dist/plugins/model-profiles/skills/model-profile/SKILL.md +59 -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 +84 -0
  335. package/dist/plugins/model-profiles/storage.js +315 -0
  336. package/dist/plugins/model-profiles/types.d.ts +179 -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 +455 -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 +270 -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,1272 @@
1
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { HttpError } from "./entry.js";
4
+ import { object } from "./ops.js";
5
+ import { configOwnership } from "./config.js";
6
+ import { localizeText } from "./config-schema.js";
7
+ import { SessionGoneError } from "./types.js";
8
+ import { errorText, log } from "./util.js";
9
+ const stringValue = { type: 'string' };
10
+ const numberValue = { type: 'number' };
11
+ const booleanValue = { type: 'boolean' };
12
+ export const instanceOutput = object({
13
+ topicId: stringValue, memberId: stringValue, adapter: stringValue, pid: { type: 'integer' }, sessionId: stringValue,
14
+ startedAt: numberValue, lastUsedAt: numberValue, busy: booleanValue, canAppend: booleanValue,
15
+ }, ['topicId', 'memberId', 'adapter', 'startedAt', 'lastUsedAt', 'busy', 'canAppend']);
16
+ const DIMENSIONS = ['prompt', 'tools', 'model', 'options'];
17
+ const APPLY_RANK = { live: 0, restart: 1, 'new-session': 2 };
18
+ /** Sessions older than 15 days open a fresh session on next launch (shorter than the 30-day MCP key overlap). */
19
+ export const SESSION_MAX_AGE_MS = 15 * 86_400_000;
20
+ function canonical(value) {
21
+ if (Array.isArray(value))
22
+ return value.map(canonical);
23
+ if (value && typeof value === 'object') {
24
+ return Object.fromEntries(Object.entries(value)
25
+ .filter(([, entry]) => entry !== undefined)
26
+ .sort(([a], [b]) => a.localeCompare(b))
27
+ .map(([k, entry]) => [k, canonical(entry)]));
28
+ }
29
+ return value;
30
+ }
31
+ const digest = (value) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
32
+ function redactionPatterns(redactions) {
33
+ return [...new Set(redactions.flatMap((secret) => {
34
+ if (!secret)
35
+ return [];
36
+ const encoded = encodeURIComponent(secret);
37
+ return encoded === secret ? [secret] : [secret, encoded];
38
+ }))].sort((a, b) => b.length - a.length);
39
+ }
40
+ export function redactText(text, redactions) {
41
+ const secrets = redactionPatterns(redactions);
42
+ let out = text;
43
+ for (const secret of secrets)
44
+ out = out.split(secret).join('[REDACTED]');
45
+ return out;
46
+ }
47
+ function pendingPrefixLength(text, patterns) {
48
+ const limit = Math.min(text.length, (patterns[0]?.length ?? 1) - 1);
49
+ for (let len = limit; len >= 1; len--) {
50
+ const suffix = text.slice(text.length - len);
51
+ if (patterns.some((pattern) => pattern.startsWith(suffix)))
52
+ return len;
53
+ }
54
+ return 0;
55
+ }
56
+ function redactEvent(event, redactions) {
57
+ if (!redactions.length)
58
+ return event;
59
+ const clean = (value) => redactText(value, redactions);
60
+ switch (event.type) {
61
+ case 'exit':
62
+ return { ...event, reason: clean(event.reason) };
63
+ case 'turn_end':
64
+ return event.error ? { ...event, error: clean(event.error) } : event;
65
+ case 'tool':
66
+ return {
67
+ ...event,
68
+ ...(event.name !== undefined ? { name: clean(event.name) } : {}),
69
+ ...(event.input !== undefined ? { input: clean(event.input) } : {}),
70
+ ...(event.output !== undefined ? { output: clean(event.output) } : {}),
71
+ };
72
+ case 'ask':
73
+ return {
74
+ ...event,
75
+ title: clean(event.title),
76
+ options: event.options.map((option) => ({ ...option, label: clean(option.label) })),
77
+ ...(event.details ? {
78
+ details: {
79
+ ...(event.details.fields ? {
80
+ fields: event.details.fields.map((field) => ({ ...field, label: clean(field.label), value: clean(field.value) })),
81
+ } : {}),
82
+ ...(event.details.code ? {
83
+ code: { ...event.details.code, label: clean(event.details.code.label), text: clean(event.details.code.text) },
84
+ } : {}),
85
+ },
86
+ } : {}),
87
+ };
88
+ case 'model':
89
+ return {
90
+ ...event,
91
+ model: clean(event.model),
92
+ ...(event.configuredModel !== undefined ? { configuredModel: clean(event.configuredModel) } : {}),
93
+ };
94
+ default:
95
+ return event;
96
+ }
97
+ }
98
+ /** Copy an error with its class and custom properties intact while replacing secret-bearing messages. */
99
+ export function redactError(error, redactions) {
100
+ if (!(error instanceof Error))
101
+ return typeof error === 'string' ? redactText(error, redactions) : error;
102
+ const copy = Object.create(Object.getPrototypeOf(error));
103
+ Object.assign(copy, error);
104
+ copy.message = redactText(error.message, redactions);
105
+ if (typeof error.stack === 'string')
106
+ copy.stack = redactText(error.stack, redactions);
107
+ if (error.cause instanceof Error)
108
+ copy.cause = redactError(error.cause, redactions);
109
+ else if (typeof error.cause === 'string')
110
+ copy.cause = redactText(error.cause, redactions);
111
+ else if (error.cause && typeof error.cause === 'object' && 'message' in error.cause && typeof error.cause.message === 'string') {
112
+ copy.cause = { ...error.cause, message: redactText(error.cause.message, redactions) };
113
+ }
114
+ return copy;
115
+ }
116
+ const stableServer = (server) => server.external ? server : { name: server.name, ...(server.url ? { url: server.url } : {}) };
117
+ const sortServers = (list) => [...list].sort((a, b) => a.name.localeCompare(b.name));
118
+ export const instancesPlugin = (home) => ({
119
+ name: 'instances',
120
+ core: true,
121
+ needs: ['store', 'config', 'members', 'topics', 'push', 'entry'],
122
+ start(ctx) {
123
+ const { db } = ctx.get('store');
124
+ const config = configOwnership(ctx.get('config'));
125
+ const members = ctx.get('members');
126
+ const topics = ctx.get('topics');
127
+ db.exec(`CREATE TABLE IF NOT EXISTS sessions (
128
+ topic_id TEXT NOT NULL, member_id TEXT NOT NULL, session_id TEXT, updated_at INTEGER NOT NULL,
129
+ adapter TEXT, adopted INTEGER NOT NULL DEFAULT 0,
130
+ PRIMARY KEY (topic_id, member_id)
131
+ );
132
+ CREATE TABLE IF NOT EXISTS session_fingerprints (
133
+ topic_id TEXT NOT NULL, member_id TEXT NOT NULL,
134
+ session_id TEXT NOT NULL, adapter TEXT NOT NULL,
135
+ prompt TEXT NOT NULL, tools TEXT NOT NULL, model TEXT NOT NULL, options TEXT NOT NULL,
136
+ PRIMARY KEY (topic_id, member_id)
137
+ );
138
+ CREATE TABLE IF NOT EXISTS session_ends (
139
+ topic_id TEXT NOT NULL, member_id TEXT NOT NULL, session_id TEXT NOT NULL,
140
+ reason TEXT NOT NULL, at INTEGER NOT NULL,
141
+ PRIMARY KEY (topic_id, member_id, session_id)
142
+ );
143
+ CREATE TABLE IF NOT EXISTS session_starts (
144
+ topic_id TEXT NOT NULL, member_id TEXT NOT NULL, session_id TEXT NOT NULL,
145
+ started_at INTEGER NOT NULL,
146
+ PRIMARY KEY (topic_id, member_id, session_id)
147
+ )`);
148
+ for (const declaration of [
149
+ { key: 'a2a.autoAllow', kind: 'boolean', default: true, label: { default: '自动答复允许项', translations: { zh: '自动答复允许项', en: 'Auto-approve client prompts' } }, section: 'clientPermissions', description: { default: '自动答复客户端明确提供的允许选项;需要人工确认的请求仍进收件箱。', translations: { zh: '自动答复客户端明确提供的允许选项;需要人工确认的请求仍进收件箱。', en: 'Automatically answer explicit allow options from clients; prompts requiring confirmation still go to the inbox.' } } },
150
+ { key: 'instances.keepAlive', kind: 'boolean', default: true, label: { default: '回合后保留进程', translations: { zh: '回合后保留进程', en: 'Keep processes alive' } }, section: 'runtime', description: { default: '关闭后每轮结束即退出客户端进程。', translations: { zh: '关闭后每轮结束即退出客户端进程。', en: 'When off, client processes exit after each turn finishes.' } } },
151
+ { key: 'instances.idleMinutes', kind: 'number', default: 30, minimum: 1, maximum: 1440, unit: 'minutes', presets: [5, 10, 15, 30, 60, 120, 240], section: 'runtime', label: { default: '空闲回收时长', translations: { zh: '空闲回收时长', en: 'Idle instance timeout' } }, description: { default: '实例空闲超过该时长后自动回收。', translations: { zh: '实例空闲超过该时长后自动回收。', en: 'Recycle an idle instance after this many minutes.' } } },
152
+ { key: 'instances.max', kind: 'number', default: 8, minimum: 1, maximum: 64, unit: 'count', presets: [1, 2, 4, 6, 8, 12, 16, 24, 32], section: 'runtime', label: { default: '最大并发实例数', translations: { zh: '最大并发实例数', en: 'Max active instances' } }, description: { default: '最多同时保留的实例数;超出时回收最久没用的空闲实例。', translations: { zh: '最多同时保留的实例数;超出时回收最久没用的空闲实例。', en: 'Maximum active instances kept at once; least-recently-used idle instances are recycled first.' } } },
153
+ ])
154
+ ctx.effect(config.declare({ scope: 'settings', owner: 'core', fields: [declaration] }));
155
+ const adapters = new Map();
156
+ const adapterOf = (name) => adapters.get(name)?.at(-1)?.adapter;
157
+ const quotaKeyFile = home.path('secrets', 'quota-account-ids.key');
158
+ let quotaKey;
159
+ const configuredQuotaKey = (identity) => {
160
+ if (!quotaKey) {
161
+ const key = randomBytes(32);
162
+ try {
163
+ writeFileSync(quotaKeyFile, key, { flag: 'wx', mode: 0o600 });
164
+ quotaKey = key;
165
+ }
166
+ catch (error) {
167
+ if (error.code !== 'EEXIST')
168
+ throw error;
169
+ const saved = readFileSync(quotaKeyFile);
170
+ if (saved.length !== key.length)
171
+ throw new Error('本机账号的编号密钥无效');
172
+ quotaKey = saved;
173
+ }
174
+ }
175
+ return 'local-env:' + createHmac('sha256', quotaKey).update(JSON.stringify(identity)).digest('base64url');
176
+ };
177
+ function quotaAccountEnv(member, names) {
178
+ if (!member.env)
179
+ return [];
180
+ try {
181
+ const { env } = config.resolveMemberEnv(member.env);
182
+ const effective = names.map((name) => [name, env[name] ?? process.env[name]]);
183
+ return effective.some(([name, value]) => value !== process.env[name]) ? effective.sort() : [];
184
+ }
185
+ catch {
186
+ // An unresolved login must not borrow the default account's quota.
187
+ return [['unresolved', member.id]];
188
+ }
189
+ }
190
+ const handles = new Map();
191
+ const metricsByPair = new Map();
192
+ const metricsByPlugin = new Map();
193
+ let latestMetrics;
194
+ let promptPermission;
195
+ const starting = new Map();
196
+ // A ready instance still needs protection from reclamation until its awaited send can take it.
197
+ const delivering = new Map();
198
+ const stopping = new Map();
199
+ const key = (topicId, memberId) => `${topicId}:${memberId}`;
200
+ const push = ctx.get('push');
201
+ const changed = () => push.send('instances.changed', {});
202
+ const selectSession = db.prepare('SELECT member_id, session_id, adapter, adopted, updated_at FROM sessions WHERE topic_id = ? AND member_id = ?');
203
+ const selectAdopted = db.prepare('SELECT 1 FROM sessions WHERE member_id = ? AND adopted = 1 AND session_id IS NOT NULL LIMIT 1');
204
+ const selectTopicSessions = db.prepare('SELECT member_id, session_id, adapter, adopted, updated_at FROM sessions WHERE topic_id = ?');
205
+ const selectFingerprints = db.prepare('SELECT session_id, adapter, prompt, tools, model, options FROM session_fingerprints WHERE topic_id = ? AND member_id = ?');
206
+ const upsertFingerprints = db.prepare(`INSERT INTO session_fingerprints (topic_id, member_id, session_id, adapter, prompt, tools, model, options)
207
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
208
+ ON CONFLICT(topic_id, member_id) DO UPDATE SET
209
+ session_id = excluded.session_id, adapter = excluded.adapter,
210
+ prompt = excluded.prompt, tools = excluded.tools, model = excluded.model, options = excluded.options`);
211
+ const deleteFingerprints = db.prepare('DELETE FROM session_fingerprints WHERE topic_id = ? AND member_id = ?');
212
+ const upsertSessionEnd = db.prepare(`INSERT INTO session_ends (topic_id, member_id, session_id, reason, at) VALUES (?, ?, ?, ?, ?)
213
+ ON CONFLICT(topic_id, member_id, session_id) DO UPDATE SET reason = excluded.reason, at = excluded.at`);
214
+ const insertSessionEndIfAbsent = db.prepare(`INSERT INTO session_ends (topic_id, member_id, session_id, reason, at) VALUES (?, ?, ?, ?, ?)
215
+ ON CONFLICT(topic_id, member_id, session_id) DO NOTHING`);
216
+ const deleteSessionEnd = db.prepare('DELETE FROM session_ends WHERE topic_id = ? AND member_id = ? AND session_id = ?');
217
+ const selectLatestSessionEnd = db.prepare('SELECT reason FROM session_ends WHERE topic_id = ? AND member_id = ? ORDER BY at DESC LIMIT 1');
218
+ const selectTopicSessionEnds = db.prepare('SELECT member_id, session_id, reason, at FROM session_ends WHERE topic_id = ?');
219
+ const selectSessionStart = db.prepare('SELECT started_at FROM session_starts WHERE topic_id = ? AND member_id = ? AND session_id = ?');
220
+ const insertSessionStartIfAbsent = db.prepare(`INSERT INTO session_starts (topic_id, member_id, session_id, started_at) VALUES (?, ?, ?, ?)
221
+ ON CONFLICT(topic_id, member_id, session_id) DO NOTHING`);
222
+ const upsertSessionStart = db.prepare(`INSERT INTO session_starts (topic_id, member_id, session_id, started_at) VALUES (?, ?, ?, ?)
223
+ ON CONFLICT(topic_id, member_id, session_id) DO UPDATE SET started_at = excluded.started_at`);
224
+ const deleteSessionStart = db.prepare('DELETE FROM session_starts WHERE topic_id = ? AND member_id = ? AND session_id = ?');
225
+ const sessionStartedAt = (topicId, memberId, saved) => {
226
+ if (!saved.session_id)
227
+ return saved.updated_at;
228
+ const row = selectSessionStart.get(topicId, memberId, saved.session_id);
229
+ return row?.started_at ?? saved.updated_at;
230
+ };
231
+ const recordSessionEnd = (topicId, memberId, sessionId, reason) => {
232
+ if (sessionId)
233
+ upsertSessionEnd.run(topicId, memberId, sessionId, reason, Date.now());
234
+ };
235
+ const clearSessionEnd = (topicId, memberId, sessionId) => {
236
+ deleteSessionEnd.run(topicId, memberId, sessionId);
237
+ };
238
+ const latestSessionEnd = (topicId, memberId) => {
239
+ const row = selectLatestSessionEnd.get(topicId, memberId);
240
+ return row?.reason;
241
+ };
242
+ const sessionMatches = (row, member) => row.adapter === member?.adapter;
243
+ const sessionRow = (topicId, memberId) => {
244
+ const row = selectSession.get(topicId, memberId);
245
+ return row && sessionMatches(row, members.get(memberId)) ? row : undefined;
246
+ };
247
+ const savedFingerprints = (topicId, memberId, sessionId, adapterName) => {
248
+ const row = selectFingerprints.get(topicId, memberId);
249
+ if (!row || row.session_id !== sessionId || row.adapter !== adapterName)
250
+ return undefined;
251
+ return { prompt: row.prompt, tools: row.tools, model: row.model, options: row.options };
252
+ };
253
+ const saveFingerprints = (topicId, memberId, sessionId, adapterName, fp) => {
254
+ if (!sessionId || !fp)
255
+ return;
256
+ upsertFingerprints.run(topicId, memberId, sessionId, adapterName, fp.prompt, fp.tools, fp.model, fp.options);
257
+ };
258
+ const clearSession = (topicId, memberId) => {
259
+ db.prepare('UPDATE sessions SET session_id = NULL, adopted = 0, updated_at = ? WHERE topic_id = ? AND member_id = ?')
260
+ .run(Date.now(), topicId, memberId);
261
+ deleteFingerprints.run(topicId, memberId);
262
+ };
263
+ /** The mark belongs to the session: saving the same id again keeps it, another id takes the one given. */
264
+ const saveSession = (topicId, memberId, sessionId, adopted = false) => {
265
+ const now = Date.now();
266
+ db.prepare(`INSERT INTO sessions (topic_id, member_id, session_id, adapter, adopted, updated_at) VALUES (?, ?, ?, ?, ?, ?)
267
+ ON CONFLICT(topic_id, member_id) DO UPDATE SET adopted = CASE WHEN excluded.session_id IS sessions.session_id THEN sessions.adopted ELSE excluded.adopted END,
268
+ session_id = excluded.session_id, adapter = excluded.adapter, updated_at = excluded.updated_at`)
269
+ .run(topicId, memberId, sessionId, members.get(memberId)?.adapter ?? null, adopted ? 1 : 0, now);
270
+ if (sessionId) {
271
+ if (adopted)
272
+ upsertSessionStart.run(topicId, memberId, sessionId, now);
273
+ else
274
+ insertSessionStartIfAbsent.run(topicId, memberId, sessionId, now);
275
+ clearSessionEnd(topicId, memberId, sessionId);
276
+ }
277
+ };
278
+ const info = (handle) => ({
279
+ topicId: handle.topicId,
280
+ memberId: handle.memberId,
281
+ adapter: handle.adapter,
282
+ ...(handle.instance.pid !== undefined ? { pid: handle.instance.pid } : {}),
283
+ ...(handle.sessionId ? { sessionId: handle.sessionId } : {}),
284
+ startedAt: handle.startedAt,
285
+ lastUsedAt: handle.lastUsedAt,
286
+ busy: handle.busyTurn !== undefined,
287
+ canAppend: handle.canAppend,
288
+ });
289
+ ctx.on('card.answered', ({ message, card, answer }) => {
290
+ if (card.ask === undefined)
291
+ return;
292
+ const handle = handles.get(key(message.topicId, message.from.id));
293
+ if (handle && handle.busyTurn === message.turnId)
294
+ handle.instance.answer(card.ask, answer.picked[0]);
295
+ });
296
+ const dispatchEvent = (handle, event) => {
297
+ const k = key(handle.topicId, handle.memberId);
298
+ if (event.type === 'ask') {
299
+ const allow = config.get('settings', 'a2a.autoAllow') ? event.options.find((option) => option.kind?.startsWith('allow')) : undefined;
300
+ if (allow) {
301
+ handle.instance.answer(event.askId, allow.id);
302
+ return;
303
+ }
304
+ if (!promptPermission?.(handle.topicId, handle.memberId, event)) {
305
+ void stopHandle(handle, true, '客户端需要人工确认,但没有权限确认入口').then(changed);
306
+ return;
307
+ }
308
+ }
309
+ if (event.type === 'turn_start')
310
+ handle.busyTurn = event.turn;
311
+ if (event.type === 'usage' && event.usage.contextUsed !== undefined && event.usage.contextSize)
312
+ handle.context = { used: event.usage.contextUsed, size: event.usage.contextSize };
313
+ const sessionChanged = event.type === 'session' && event.id !== handle.sessionId;
314
+ if (event.type === 'session') {
315
+ if (sessionChanged && handle.sessionId)
316
+ handle.context = undefined;
317
+ handle.sessionId = event.id;
318
+ saveSession(handle.topicId, handle.memberId, event.id);
319
+ }
320
+ if (event.type === 'turn_end') {
321
+ handle.busyTurn = undefined;
322
+ handle.lastUsedAt = Date.now();
323
+ if (event.outcome === 'completed' && handle.sessionId && handle.fingerprints) {
324
+ saveFingerprints(handle.topicId, handle.memberId, handle.sessionId, handle.adapter, handle.fingerprints);
325
+ }
326
+ // Retired while this turn ran: end it now that it settled, before the turn's end is published,
327
+ // so what dispatches next waits for the stop and opens a new instance under the current adapter.
328
+ retireIfSettled(handle);
329
+ }
330
+ if (event.type === 'exit') {
331
+ handles.delete(k);
332
+ if (handle.busyTurn) {
333
+ const turn = handle.busyTurn;
334
+ handle.busyTurn = undefined;
335
+ ctx.runtime.emit('instance.event', {
336
+ topicId: handle.topicId, memberId: handle.memberId, adapter: handle.adapter,
337
+ event: { type: 'turn_end', turn, outcome: 'failed', error: `进程退出:${event.reason}` },
338
+ });
339
+ }
340
+ }
341
+ ctx.runtime.emit('instance.event', { topicId: handle.topicId, memberId: handle.memberId, adapter: handle.adapter, event });
342
+ if (sessionChanged || event.type === 'turn_end' || event.type === 'exit' || event.type === 'turn_start')
343
+ changed();
344
+ if (event.type === 'turn_start' || event.type === 'turn_end' || event.type === 'exit') {
345
+ ctx.runtime.emit('instances.busy_changed', { topicId: handle.topicId });
346
+ }
347
+ if (event.type === 'turn_end' && !config.get('settings', 'instances.keepAlive')) {
348
+ void instances.stop({ topicId: handle.topicId, memberId: handle.memberId }, { force: false });
349
+ }
350
+ };
351
+ const flushPendingStream = (handle) => {
352
+ const pending = handle.pendingStream;
353
+ if (!pending)
354
+ return;
355
+ handle.pendingStream = undefined;
356
+ if (!pending.buffer)
357
+ return;
358
+ const delta = redactText(pending.buffer, handle.redactions ?? []);
359
+ if (!delta)
360
+ return;
361
+ dispatchEvent(handle, pending.kind === 'text'
362
+ ? { type: 'text', turn: pending.turn, delta, ...(pending.message !== undefined ? { message: pending.message } : {}) }
363
+ : { type: 'thinking', turn: pending.turn, delta });
364
+ };
365
+ const onEvent = (handle, rawEvent) => {
366
+ const k = key(handle.topicId, handle.memberId);
367
+ if (handles.get(k) !== handle && rawEvent.type !== 'turn_end')
368
+ return; // a reclaimed instance has nothing more to say
369
+ if ('turn' in rawEvent && rawEvent.turn !== undefined && handle.busyTurn !== rawEvent.turn
370
+ && (rawEvent.type !== 'turn_start' || handle.busyTurn !== undefined))
371
+ return;
372
+ const redactions = handle.redactions ?? [];
373
+ const errorRedactions = handle.errorRedactions ?? redactions;
374
+ if (rawEvent.type === 'text' || rawEvent.type === 'thinking') {
375
+ const pending = handle.pendingStream;
376
+ if (pending && (pending.kind !== rawEvent.type || pending.turn !== rawEvent.turn
377
+ || (rawEvent.type === 'text' && pending.message !== rawEvent.message))) {
378
+ flushPendingStream(handle);
379
+ }
380
+ const patterns = redactionPatterns(redactions);
381
+ if (!patterns.length) {
382
+ dispatchEvent(handle, rawEvent);
383
+ return;
384
+ }
385
+ if (rawEvent.type === 'text' && rawEvent.delta === '' && !handle.pendingStream) {
386
+ dispatchEvent(handle, rawEvent);
387
+ return;
388
+ }
389
+ const combined = (handle.pendingStream?.buffer ?? '') + rawEvent.delta;
390
+ const redacted = redactText(combined, patterns);
391
+ const hold = pendingPrefixLength(redacted, patterns);
392
+ const safe = hold ? redacted.slice(0, -hold) : redacted;
393
+ const tail = hold ? redacted.slice(-hold) : '';
394
+ handle.pendingStream = tail
395
+ ? {
396
+ kind: rawEvent.type,
397
+ turn: rawEvent.turn,
398
+ ...(rawEvent.type === 'text' && rawEvent.message !== undefined ? { message: rawEvent.message } : {}),
399
+ buffer: tail,
400
+ }
401
+ : undefined;
402
+ if (safe) {
403
+ dispatchEvent(handle, rawEvent.type === 'text'
404
+ ? { type: 'text', turn: rawEvent.turn, delta: safe, ...(rawEvent.message !== undefined ? { message: rawEvent.message } : {}) }
405
+ : { type: 'thinking', turn: rawEvent.turn, delta: safe });
406
+ }
407
+ return;
408
+ }
409
+ if (rawEvent.type === 'tool' || rawEvent.type === 'ask' || rawEvent.type === 'turn_end' || rawEvent.type === 'exit' || rawEvent.type === 'turn_start') {
410
+ flushPendingStream(handle);
411
+ }
412
+ dispatchEvent(handle, redactEvent(rawEvent, rawEvent.type === 'exit' || rawEvent.type === 'turn_end' ? errorRedactions : redactions));
413
+ };
414
+ /** A member whose client can list the sessions it has, which is also its word that one made outside the host can be continued here. */
415
+ const outside = (memberId) => {
416
+ const member = members.get(memberId);
417
+ if (!member || member.kind !== 'agent')
418
+ throw new Error(`没有这个成员:${memberId}`);
419
+ const adapter = adapterOf(member.adapter);
420
+ if (!adapter)
421
+ throw new Error(`成员 ${member.name} 用的适配器 ${member.adapter} 没有加载`);
422
+ if (!adapter.sessions)
423
+ throw new Error(`${adapter.title} 不能列出它已有的会话,外面开的会话接不进来`);
424
+ return { member, adapter };
425
+ };
426
+ /** The key a member names, for its client; a member naming a key that is gone is not started without it. */
427
+ const keyOf = async (adapter, id, purpose = 'client') => {
428
+ if (!id)
429
+ return {};
430
+ const [key] = await ctx.runtime.serial('key.resolve', { id });
431
+ if (!key)
432
+ throw new HttpError(404, '所选密钥或账号不在了,到成员的「编辑」里重新选择');
433
+ // Quota probes decide which API keys have a subscription. A native login always belongs to one client.
434
+ if ('adapter' in key || purpose === 'client')
435
+ instances.accepts(adapter, key);
436
+ return 'env' in key ? { env: key.env } : { key };
437
+ };
438
+ const collectStartInput = async (topicId, member, recordMetrics) => {
439
+ const topic = topics.get(topicId);
440
+ if (!topic || topic.deletedAt)
441
+ throw new Error(`没有这个 topic:${topicId}`);
442
+ const pieces = await ctx.runtime.serialBy('session.init', { topicId, member });
443
+ const servers = await ctx.runtime.serialBy('session.mcp', { topicId, member });
444
+ const extras = await ctx.runtime.serialBy('session.input', { topicId, member });
445
+ const keyInput = await keyOf(member.adapter, member.key);
446
+ const resolvedMemberEnv = config.resolveMemberEnv(member.env ?? {});
447
+ const memberEnv = resolvedMemberEnv.env;
448
+ const redactions = [...new Set(resolvedMemberEnv.redactions)];
449
+ const errorRedactions = [...new Set([...redactions, ...(keyInput.key?.apiKey ? [keyInput.key.apiKey] : [])])];
450
+ // Aggregate session.init contributions per plugin and measure observed size without dropping any segment.
451
+ const grouped = [];
452
+ const indexByPlugin = new Map();
453
+ for (const { plugin, value } of pieces) {
454
+ const idx = indexByPlugin.get(plugin);
455
+ if (idx === undefined) {
456
+ indexByPlugin.set(plugin, grouped.length);
457
+ grouped.push({ plugin, text: value });
458
+ }
459
+ else {
460
+ grouped[idx].text = `${grouped[idx].text}\n\n${value}`;
461
+ }
462
+ }
463
+ const byPlugin = grouped.map(({ plugin, text }) => ({
464
+ plugin,
465
+ chars: text.length,
466
+ bytes: Buffer.byteLength(text, 'utf8'),
467
+ }));
468
+ const systemPrompt = grouped.length ? grouped.map(({ text }) => text).join('\n\n') : undefined;
469
+ const totalChars = systemPrompt?.length ?? 0;
470
+ const totalBytes = systemPrompt ? Buffer.byteLength(systemPrompt, 'utf8') : 0;
471
+ const mcpServers = servers.flatMap(({ value }) => value);
472
+ const now = Date.now();
473
+ const metrics = {
474
+ topicId, memberId: member.id, at: now,
475
+ totalChars, totalBytes, mcpServers: mcpServers.length,
476
+ byPlugin,
477
+ };
478
+ if (recordMetrics) {
479
+ metricsByPair.set(key(topicId, member.id), metrics);
480
+ latestMetrics = metrics;
481
+ for (const item of byPlugin)
482
+ metricsByPlugin.set(item.plugin, { ...item, at: now });
483
+ }
484
+ const extraFor = (dim) => extras
485
+ .filter(({ value }) => value[dim] !== undefined)
486
+ .map(({ plugin, value }) => [plugin, value[dim]])
487
+ .sort(([a], [b]) => a.localeCompare(b));
488
+ const dirs = topics.refsOf(topicId).map((ref) => ref.path);
489
+ const { model, ...otherOptions } = member.options;
490
+ const promptParts = [...grouped].sort((a, b) => a.plugin.localeCompare(b.plugin)).map(({ plugin, text }) => [plugin, text]);
491
+ const fingerprints = {
492
+ prompt: digest({ pieces: promptParts, extra: extraFor('prompt') }),
493
+ tools: digest({ servers: sortServers(mcpServers.map(stableServer)), extra: extraFor('tools') }),
494
+ model: digest({ model: model ?? null, extra: extraFor('model') }),
495
+ options: digest({
496
+ cwd: topic.dir, dirs,
497
+ key: keyInput.key
498
+ ? { protocol: keyInput.key.protocol, endpoint: keyInput.key.endpoint ?? '', apiKey: digest(keyInput.key.apiKey) }
499
+ : keyInput.env
500
+ ? Object.entries(keyInput.env).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, value === undefined ? null : digest(value)])
501
+ : null,
502
+ options: otherOptions,
503
+ extra: extraFor('options'),
504
+ }),
505
+ };
506
+ const liveToolsFingerprint = digest({ servers: sortServers(mcpServers), extra: extraFor('tools') });
507
+ const liveEnvFingerprint = digest(Object.entries(memberEnv).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => [key, digest(value)]));
508
+ return {
509
+ startInputBase: {
510
+ cwd: topic.dir, dirs,
511
+ ...(systemPrompt !== undefined ? { systemPrompt } : {}),
512
+ mcpServers, ...keyInput, ...(Object.keys(memberEnv).length ? { memberEnv } : {}), options: member.options,
513
+ },
514
+ fingerprints, liveToolsFingerprint, liveEnvFingerprint, redactions, errorRedactions, metrics,
515
+ };
516
+ };
517
+ const ensure = async (topicId, memberId, current) => {
518
+ const k = key(topicId, memberId);
519
+ // Adapter absence right now may mean a reload is between stop and start rather than the adapter being
520
+ // gone: wait for reloads in flight to settle, then judge. The whole round — the wait, the fingerprint
521
+ // decision, the final check — goes by one registration; if the registration changed underneath the
522
+ // asynchronous parts, the round starts over, so a changed model or prompt is judged by the applies of
523
+ // the registration that will actually open the instance. From the final comparison through opened()
524
+ // to the adapter lookup in open() there is no await, so a delivery withdrawn or a topic deleted while
525
+ // waiting is still caught there. A truly disabled or unloaded adapter fails in open() as before.
526
+ for (;;) {
527
+ let member = members.get(memberId);
528
+ let adapter = member ? adapterOf(member.adapter) : undefined;
529
+ if (member && !adapter) {
530
+ await ctx.runtime.reloaded();
531
+ member = members.get(memberId);
532
+ adapter = member ? adapterOf(member.adapter) : undefined;
533
+ }
534
+ let idle = handles.get(k);
535
+ // Retired while a delivery was in flight or no turn came after it: end it now, so what opens next
536
+ // is a new instance under the current adapter. From here on the pair is treated as having no instance.
537
+ if (idle?.retire && !idle.busyTurn && !starting.has(k)) {
538
+ await stopHandle(idle, false, idle.retire);
539
+ idle = undefined;
540
+ }
541
+ const topic = topics.get(topicId);
542
+ let saved = sessionRow(topicId, memberId);
543
+ if (member && adapter && topic && !topic.deletedAt && topic.archivedAt === null
544
+ && !starting.has(k) && !idle?.busyTurn && saved?.session_id
545
+ && Date.now() - sessionStartedAt(topicId, memberId, saved) >= SESSION_MAX_AGE_MS) {
546
+ const judged = () => adapterOf(member.adapter) === adapter;
547
+ if (current() && judged() && handles.get(k) === idle && !idle?.busyTurn) {
548
+ const why = '会话已超过 15 天,按交接逻辑开启新会话';
549
+ log('instances', `${member.name} ${why}(旧会话 ${saved.session_id})`);
550
+ if (idle) {
551
+ await stopHandle(idle, false, why);
552
+ idle = undefined;
553
+ }
554
+ if (!judged())
555
+ continue;
556
+ recordSessionEnd(topicId, memberId, saved.session_id, 'expired');
557
+ clearSession(topicId, memberId);
558
+ saved = undefined;
559
+ }
560
+ }
561
+ let baseline;
562
+ let missingSavedFp = false;
563
+ let changedDims = [];
564
+ if (!starting.has(k) && !(idle?.busyTurn) && member) {
565
+ const savedFp = saved?.session_id ? savedFingerprints(topicId, memberId, saved.session_id, member.adapter) : undefined;
566
+ if (saved?.session_id && !savedFp) {
567
+ if (idle?.fingerprints && idle.sessionId === saved.session_id)
568
+ baseline = idle.fingerprints;
569
+ else {
570
+ missingSavedFp = true;
571
+ changedDims = [...DIMENSIONS];
572
+ }
573
+ }
574
+ else {
575
+ baseline = savedFp ?? idle?.fingerprints;
576
+ }
577
+ }
578
+ if (member && adapter && (baseline || missingSavedFp) && topic && !topic.deletedAt && topic.archivedAt === null) {
579
+ const collected = await collectStartInput(topicId, member, false);
580
+ if (!missingSavedFp && baseline)
581
+ changedDims = DIMENSIONS.filter((dim) => baseline[dim] !== collected.fingerprints[dim]);
582
+ let action = 'live';
583
+ for (const dim of changedDims) {
584
+ const mode = adapter.applies[dim];
585
+ if (APPLY_RANK[mode] > APPLY_RANK[action])
586
+ action = mode;
587
+ }
588
+ const liveTokenChanged = idle !== undefined && idle.liveToolsFingerprint !== collected.liveToolsFingerprint;
589
+ if (liveTokenChanged && APPLY_RANK[action] < APPLY_RANK.restart && APPLY_RANK[adapter.applies.tools] >= APPLY_RANK.restart) {
590
+ action = 'restart';
591
+ }
592
+ const liveEnvChanged = idle !== undefined && idle.liveEnvFingerprint !== collected.liveEnvFingerprint;
593
+ if (liveEnvChanged && APPLY_RANK[action] < APPLY_RANK.restart) {
594
+ action = 'restart';
595
+ }
596
+ // The registration that judged the change must still be the one in place before anything is written.
597
+ const judged = () => adapterOf(member.adapter) === adapter;
598
+ if (current() && judged() && handles.get(k) === idle && !idle?.busyTurn) {
599
+ if (action === 'new-session' && saved?.adopted !== 1) {
600
+ const why = `启动输入变化(${changedDims.join('、')}),需开新会话`;
601
+ log('instances', `${member.name} ${why}`);
602
+ if (idle)
603
+ await stopHandle(idle, false, why);
604
+ if (!judged())
605
+ continue;
606
+ recordSessionEnd(topicId, memberId, saved?.session_id, 'prompt');
607
+ clearSession(topicId, memberId);
608
+ }
609
+ else if ((action === 'restart' || (action === 'new-session' && saved?.adopted === 1)) && idle) {
610
+ const why = `启动输入变化(${(changedDims.length ? changedDims : [liveEnvChanged ? 'env' : 'tools']).join('、')})`;
611
+ log('instances', `${member.name} 的实例重新拉起:${why}`);
612
+ await stopHandle(idle, false, why);
613
+ }
614
+ }
615
+ }
616
+ while (stopping.has(k))
617
+ await stopping.get(k);
618
+ const now = members.get(memberId);
619
+ if (now && adapterOf(now.adapter) !== adapter) {
620
+ if (!current())
621
+ return;
622
+ continue;
623
+ }
624
+ if (current())
625
+ return opened(topicId, memberId);
626
+ return;
627
+ }
628
+ };
629
+ const opened = (topicId, memberId, adoption) => {
630
+ const topic = topics.get(topicId);
631
+ if (!topic || topic.deletedAt)
632
+ return Promise.reject(new Error(`没有这个 topic:${topicId}`));
633
+ if (topic.archivedAt !== null)
634
+ return Promise.reject(new HttpError(409, '主题已归档'));
635
+ const k = key(topicId, memberId);
636
+ const pending = starting.get(k);
637
+ if (pending)
638
+ return pending;
639
+ const existing = handles.get(k);
640
+ if (existing && !adoption)
641
+ return Promise.resolve(existing);
642
+ const promise = (async () => {
643
+ const member = members.get(memberId);
644
+ if (!member)
645
+ throw new Error(`没有这个成员:${memberId}`);
646
+ const open = async (sessionId, opening) => {
647
+ const adapter = adapterOf(member.adapter);
648
+ if (!adapter)
649
+ throw new Error(`成员 ${member.name} 用的适配器 ${member.adapter} 没有加载`);
650
+ const handle = {
651
+ topicId, memberId, adapter: member.adapter, startedAt: Date.now(), lastUsedAt: Date.now(),
652
+ canAppend: adapter.append === true,
653
+ instance: undefined,
654
+ };
655
+ handle.instance = adapter.open({
656
+ topicId, member,
657
+ emit: (event) => onEvent(handle, event),
658
+ log: (message) => log(`instance ${member.handle}`, redactText(message, handle.errorRedactions ?? handle.redactions ?? [])),
659
+ });
660
+ handle.canAppend = adapter.append === true || typeof handle.instance.append === 'function';
661
+ handles.set(k, handle);
662
+ let collected;
663
+ try {
664
+ // Side-effecting preparation runs only when an instance is actually starting or restarting.
665
+ await ctx.runtime.serial('session.prepare', { topicId, member });
666
+ if (handles.get(k) !== handle)
667
+ throw new Error('实例已停止');
668
+ collected = await collectStartInput(topicId, member, true);
669
+ handle.fingerprints = collected.fingerprints;
670
+ handle.liveToolsFingerprint = collected.liveToolsFingerprint;
671
+ handle.liveEnvFingerprint = collected.liveEnvFingerprint;
672
+ handle.redactions = collected.redactions;
673
+ handle.errorRedactions = collected.errorRedactions;
674
+ if (handles.get(k) !== handle)
675
+ throw new Error('实例已停止');
676
+ const startInput = {
677
+ ...(sessionId ? { sessionId } : {}),
678
+ opening,
679
+ ...collected.startInputBase,
680
+ };
681
+ if (sessionId && !opening) {
682
+ const prevFp = savedFingerprints(topicId, memberId, sessionId, member.adapter);
683
+ const diffs = prevFp ? DIMENSIONS.filter((dim) => prevFp[dim] !== collected.fingerprints[dim]) : [...DIMENSIONS];
684
+ if (diffs.length)
685
+ Object.assign(startInput, { changed: diffs });
686
+ }
687
+ handle.sessionId = await handle.instance.start(startInput);
688
+ if (handles.get(k) !== handle)
689
+ throw new Error('实例已停止');
690
+ saveSession(topicId, memberId, handle.sessionId);
691
+ return handle;
692
+ }
693
+ catch (error) {
694
+ if (handles.get(k) === handle)
695
+ handles.delete(k);
696
+ await handle.instance.stop({ force: true }).catch(() => { });
697
+ throw redactError(error, collected?.errorRedactions ?? handle.errorRedactions ?? handle.redactions ?? []);
698
+ }
699
+ };
700
+ if (adoption) {
701
+ const { id, previous, previousFp } = adoption;
702
+ const previousStart = selectSessionStart.get(topicId, memberId, id);
703
+ // Reserve the session while it loads, and restore the pair before reporting a failed start.
704
+ saveSession(topicId, memberId, id, true);
705
+ try {
706
+ if (existing)
707
+ await stopHandle(existing, false, '接上另一个会话');
708
+ return await open(id, true);
709
+ }
710
+ catch (error) {
711
+ if (previous) {
712
+ db.prepare('UPDATE sessions SET session_id = ?, adapter = ?, adopted = ?, updated_at = ? WHERE topic_id = ? AND member_id = ?')
713
+ .run(previous.session_id, previous.adapter, previous.adopted, previous.updated_at, topicId, memberId);
714
+ }
715
+ else {
716
+ db.prepare('DELETE FROM sessions WHERE topic_id = ? AND member_id = ?').run(topicId, memberId);
717
+ }
718
+ if (previousStart)
719
+ upsertSessionStart.run(topicId, memberId, id, previousStart.started_at);
720
+ else
721
+ deleteSessionStart.run(topicId, memberId, id);
722
+ if (previousFp) {
723
+ upsertFingerprints.run(topicId, memberId, previousFp.session_id, previousFp.adapter, previousFp.prompt, previousFp.tools, previousFp.model, previousFp.options);
724
+ }
725
+ else {
726
+ deleteFingerprints.run(topicId, memberId);
727
+ }
728
+ throw error;
729
+ }
730
+ }
731
+ const saved = sessionRow(topicId, memberId);
732
+ const sessionId = saved?.session_id ?? undefined;
733
+ const adopted = !!sessionId && saved?.adopted === 1;
734
+ try {
735
+ return await open(sessionId, !sessionId || adopted);
736
+ }
737
+ catch (error) {
738
+ // A session taken in from outside that cannot be continued is said so, not quietly replaced by a new one.
739
+ if (!(error instanceof SessionGoneError) || !sessionId || adopted || topic.deletedAt || topic.archivedAt !== null
740
+ || stopping.has(k) || !adapterOf(member.adapter))
741
+ throw error;
742
+ recordSessionEnd(topicId, memberId, sessionId, 'gone');
743
+ log('instances', `${member.name} 续接 session ${sessionId} 失败,改开新 session`, errorText(error));
744
+ return open(undefined, true);
745
+ }
746
+ })();
747
+ starting.set(k, promise);
748
+ promise.finally(() => {
749
+ starting.delete(k);
750
+ const handle = handles.get(k);
751
+ if (handle)
752
+ retireIfSettled(handle);
753
+ changed();
754
+ }).catch(() => { });
755
+ return promise;
756
+ };
757
+ const stopHandle = async (handle, force, reason) => {
758
+ const k = key(handle.topicId, handle.memberId);
759
+ handles.delete(k);
760
+ const turn = handle.busyTurn;
761
+ // The turn's end is the host's word, with the host's reason: it goes first, so a cancel the adapter
762
+ // itself emits while stopping is filtered out as belonging to no running turn.
763
+ if (turn) {
764
+ flushPendingStream(handle);
765
+ handle.busyTurn = undefined;
766
+ ctx.runtime.emit('instance.event', {
767
+ topicId: handle.topicId, memberId: handle.memberId, adapter: handle.adapter,
768
+ event: { type: 'turn_end', turn, outcome: 'canceled', error: redactText(reason, handle.redactions ?? []) },
769
+ });
770
+ ctx.runtime.emit('instances.busy_changed', { topicId: handle.topicId });
771
+ }
772
+ else {
773
+ handle.pendingStream = undefined;
774
+ }
775
+ const pending = starting.get(k);
776
+ const stopped = (async () => {
777
+ await handle.instance.stop({ force }).catch((error) => log('instances', 'stop failed', errorText(redactError(error, handle.redactions ?? []))));
778
+ // A new instance must wait until a stopped start has released the session too.
779
+ if (pending)
780
+ await Promise.allSettled([pending]);
781
+ })();
782
+ stopping.set(k, stopped);
783
+ await stopped;
784
+ stopping.delete(k);
785
+ };
786
+ /** Nothing holds this instance: no turn, no start in flight, no delivery waiting to hand it a turn. */
787
+ const settled = (handle) => {
788
+ const k = key(handle.topicId, handle.memberId);
789
+ return !handle.busyTurn && !starting.has(k) && !delivering.has(k);
790
+ };
791
+ /** A retired instance ends as soon as nothing holds it any more: no turn, no start in flight, no delivery. */
792
+ const retireIfSettled = (handle) => {
793
+ if (handle.retire && settled(handle))
794
+ void stopHandle(handle, false, handle.retire).then(changed);
795
+ };
796
+ /** Idle too long, or more than the limit: reclaim idle instances, least recently used first. */
797
+ const reclaim = () => {
798
+ const idleMs = config.get('settings', 'instances.idleMinutes') * 60_000;
799
+ const max = config.get('settings', 'instances.max');
800
+ const idle = [...handles.values()]
801
+ .filter((handle) => settled(handle))
802
+ .sort((a, b) => a.lastUsedAt - b.lastUsedAt);
803
+ let over = handles.size - max;
804
+ for (const handle of idle) {
805
+ if (Date.now() - handle.lastUsedAt > idleMs || over > 0) {
806
+ over -= 1;
807
+ void stopHandle(handle, false, '空闲回收').then(changed);
808
+ }
809
+ }
810
+ };
811
+ const timer = setInterval(reclaim, 60_000);
812
+ timer.unref();
813
+ ctx.effect(() => clearInterval(timer));
814
+ const instances = {
815
+ registerPermissionPrompt(prompt) {
816
+ if (promptPermission)
817
+ throw new Error('已有权限确认入口');
818
+ promptPermission = prompt;
819
+ return () => { promptPermission = undefined; };
820
+ },
821
+ localQuotaAccount(memberId) {
822
+ const member = members.get(memberId);
823
+ if (member?.kind !== 'agent' || member.key)
824
+ return;
825
+ const adapter = adapterOf(member.adapter);
826
+ const command = typeof member.options?.command === 'string' ? member.options.command.trim() : '';
827
+ const defaultCommand = (adapter?.command ?? '').trim();
828
+ const customCmd = command === defaultCommand ? '' : command;
829
+ if (adapter && !defaultCommand && !customCmd)
830
+ return;
831
+ const env = quotaAccountEnv(member, adapter?.quotaAccountEnv ?? []);
832
+ const configured = env.length > 0;
833
+ const key = configured ? configuredQuotaKey([member.adapter, customCmd, env])
834
+ : customCmd ? `${member.adapter}:${customCmd}` : member.adapter;
835
+ return { key, customCmd, configured };
836
+ },
837
+ registerAdapter(name, adapter) {
838
+ const stack = adapters.get(name) ?? [];
839
+ const replacing = stack.length > 0;
840
+ const registration = { adapter };
841
+ stack.push(registration);
842
+ adapters.set(name, stack);
843
+ if (replacing)
844
+ void instances.stop({ adapter: name }, { force: false, retire: true, reason: '适配器已替换' });
845
+ return async () => {
846
+ const index = stack.indexOf(registration);
847
+ if (index === -1)
848
+ return;
849
+ const active = index === stack.length - 1;
850
+ stack.splice(index, 1);
851
+ if (!stack.length)
852
+ adapters.delete(name);
853
+ if (active)
854
+ void instances.stop({ adapter: name }, { force: false, retire: true, reason: '适配器被卸载' });
855
+ };
856
+ },
857
+ adapters: () => [...adapters.entries()].map(([name, stack]) => ({ name, adapter: stack.at(-1).adapter })),
858
+ async send(topicId, memberId, input, current, prepare, onDispatch) {
859
+ const k = key(topicId, memberId);
860
+ delivering.set(k, input.turnId);
861
+ let handle;
862
+ try {
863
+ handle = await ensure(topicId, memberId, current);
864
+ if (!handle || !current())
865
+ return;
866
+ const ready = prepare ? await prepare() : input;
867
+ if (!ready || !current())
868
+ return;
869
+ if (handles.get(k) !== handle)
870
+ throw new Error('实例在收到这一轮之前已停止');
871
+ onDispatch?.(handle.adapter);
872
+ handle.busyTurn = input.turnId;
873
+ handle.lastUsedAt = Date.now();
874
+ changed();
875
+ ctx.runtime.emit('instances.busy_changed', { topicId });
876
+ reclaim();
877
+ handle.instance.send(ready);
878
+ db.prepare('UPDATE sessions SET adopted = 0 WHERE topic_id = ? AND member_id = ? AND adopted = 1').run(topicId, memberId);
879
+ }
880
+ catch (error) {
881
+ if (handle?.busyTurn === input.turnId) {
882
+ handle.busyTurn = undefined;
883
+ changed();
884
+ ctx.runtime.emit('instances.busy_changed', { topicId });
885
+ }
886
+ throw redactError(error, handle?.errorRedactions ?? handle?.redactions ?? handles.get(k)?.errorRedactions ?? handles.get(k)?.redactions ?? []);
887
+ }
888
+ finally {
889
+ if (delivering.get(k) === input.turnId)
890
+ delivering.delete(k);
891
+ const currentHandle = handles.get(k);
892
+ if (currentHandle)
893
+ retireIfSettled(currentHandle);
894
+ }
895
+ },
896
+ async append(topicId, memberId, input) {
897
+ const handle = handles.get(key(topicId, memberId));
898
+ if (!handle?.instance.append || !handle.busyTurn)
899
+ throw new Error('这个实例现在不能追加');
900
+ try {
901
+ await handle.instance.append(input);
902
+ }
903
+ catch (error) {
904
+ throw redactError(error, handle.errorRedactions ?? handle.redactions ?? []);
905
+ }
906
+ },
907
+ canAppend(topicId, memberId) {
908
+ const handle = handles.get(key(topicId, memberId));
909
+ return !!handle?.canAppend;
910
+ },
911
+ interrupt(topicId, memberId) {
912
+ const handle = handles.get(key(topicId, memberId));
913
+ if (!handle?.busyTurn)
914
+ return;
915
+ try {
916
+ return handle.instance.interrupt().catch((error) => { throw redactError(error, handle.redactions ?? []); });
917
+ }
918
+ catch (error) {
919
+ throw redactError(error, handle.errorRedactions ?? handle.redactions ?? []);
920
+ }
921
+ },
922
+ async stop(scope, { force, reason = '被强制停止', startingOnly = false, retire = false }) {
923
+ const busy = [];
924
+ const stops = [];
925
+ for (const handle of [...handles.values()]) {
926
+ if (scope.topicId && handle.topicId !== scope.topicId)
927
+ continue;
928
+ if (scope.memberId && handle.memberId !== scope.memberId)
929
+ continue;
930
+ if (scope.adapter && handle.adapter !== scope.adapter)
931
+ continue;
932
+ if (startingOnly && !starting.has(key(handle.topicId, handle.memberId)))
933
+ continue;
934
+ if (retire && !force) {
935
+ if (settled(handle))
936
+ stops.push(stopHandle(handle, force, reason));
937
+ else {
938
+ handle.retire = reason;
939
+ busy.push(info(handle));
940
+ }
941
+ }
942
+ else if (handle.busyTurn && !force)
943
+ busy.push(info(handle));
944
+ else
945
+ stops.push(stopHandle(handle, force, reason));
946
+ }
947
+ await Promise.all(stops);
948
+ changed();
949
+ return busy;
950
+ },
951
+ list: () => [...handles.values()].map(info),
952
+ startMetrics: (topicId, memberId) => metricsByPair.get(key(topicId, memberId)),
953
+ promptMetrics: () => ({
954
+ ...(latestMetrics ? { latest: latestMetrics } : {}),
955
+ byPlugin: Object.fromEntries(metricsByPlugin.entries()),
956
+ }),
957
+ topicSessions(topicId) {
958
+ const sessions = new Map();
959
+ for (const row of selectTopicSessions.all(topicId)) {
960
+ const member = members.get(row.member_id);
961
+ const matches = sessionMatches(row, member);
962
+ const sessionId = member && matches ? row.session_id || null : null;
963
+ sessions.set(row.member_id, {
964
+ topicId, memberId: row.member_id, updatedAt: row.updated_at, sessionId,
965
+ adopted: sessionId !== null && row.adopted === 1,
966
+ sealed: row.session_id === null && latestSessionEnd(topicId, row.member_id) === 'sealed',
967
+ });
968
+ }
969
+ for (const handle of handles.values()) {
970
+ if (handle.topicId !== topicId)
971
+ continue;
972
+ const instance = { ...info(handle), ...(handle.context ? { context: handle.context } : {}) };
973
+ const session = sessions.get(handle.memberId);
974
+ if (session)
975
+ session.instance = instance;
976
+ else
977
+ sessions.set(handle.memberId, {
978
+ topicId, memberId: handle.memberId, updatedAt: handle.lastUsedAt,
979
+ sessionId: null, adopted: false, sealed: false, instance,
980
+ });
981
+ }
982
+ return [...sessions.values()];
983
+ },
984
+ sessionEnds(topicId) {
985
+ return selectTopicSessionEnds.all(topicId).map((row) => ({
986
+ memberId: row.member_id,
987
+ sessionId: row.session_id,
988
+ reason: row.reason,
989
+ at: row.at,
990
+ }));
991
+ },
992
+ session: (topicId, memberId) => sessionRow(topicId, memberId)?.session_id ?? undefined,
993
+ storedSessionAdapter(topicId, memberId, sessionId) {
994
+ const row = selectSession.get(topicId, memberId);
995
+ return row?.session_id === sessionId ? row.adapter ?? undefined : undefined;
996
+ },
997
+ opening(topicId, memberId) {
998
+ const row = sessionRow(topicId, memberId);
999
+ return !row?.session_id || row.adopted === 1;
1000
+ },
1001
+ hasAdopted: (memberId) => selectAdopted.get(memberId) !== undefined,
1002
+ async sessions(memberId, cwd) {
1003
+ const { member, adapter } = outside(memberId);
1004
+ const used = new Map(db.prepare('SELECT session_id, topic_id FROM sessions WHERE session_id IS NOT NULL').all().map((r) => [r.session_id, r.topic_id]));
1005
+ const { env } = await keyOf(member.adapter, member.key);
1006
+ return (await adapter.sessions(cwd, member.options, env)).map((s) => ({ ...s, ...(used.has(s.id) ? { topicId: used.get(s.id) } : {}) }));
1007
+ },
1008
+ async adopt(topicId, memberId, sessionId) {
1009
+ const { member } = outside(memberId);
1010
+ const topic = topics.get(topicId);
1011
+ if (!topic || topic.deletedAt)
1012
+ throw new Error(`没有这个 topic:${topicId}`);
1013
+ const id = sessionId.trim();
1014
+ if (!id)
1015
+ throw new Error('要说接哪个会话');
1016
+ const k = key(topicId, memberId);
1017
+ // A session is one pair's. (A topic that was removed no longer holds on to its sessions.)
1018
+ const user = db.prepare('SELECT topic_id, member_id FROM sessions WHERE session_id = ?').all(id).find((r) => topics.get(r.topic_id) && !topics.get(r.topic_id).deletedAt);
1019
+ if (user)
1020
+ throw new Error(user.topic_id === topicId && user.member_id === memberId ? `${member.name} 在这个主题里用的已经是这个会话` : `这个会话已经是主题「${topics.get(user.topic_id)?.title ?? user.topic_id}」里的会话`);
1021
+ if (starting.has(k) || handles.get(k)?.busyTurn)
1022
+ throw new Error(`${member.name} 在这个主题里正在工作,等它这一轮结束再接`);
1023
+ const previous = selectSession.get(topicId, memberId);
1024
+ const previousFp = selectFingerprints.get(topicId, memberId);
1025
+ const replaced = previous && sessionMatches(previous, member) ? previous.session_id : null;
1026
+ const at = Date.now();
1027
+ const handle = await opened(topicId, memberId, { id, previous, previousFp });
1028
+ if (replaced)
1029
+ recordSessionEnd(topicId, memberId, replaced, 'adopted');
1030
+ reclaim();
1031
+ log('instances', `${member.name} 在 ${topic.title} 接上了会话 ${id},用时 ${Date.now() - at}ms`);
1032
+ return { sessionId: id, ...(replaced ? { replaced } : {}), ms: Date.now() - at, ...(handle.context ? { context: handle.context } : {}) };
1033
+ },
1034
+ accepts(adapterName, key) {
1035
+ const adapter = adapterOf(adapterName);
1036
+ if ('adapter' in key) {
1037
+ if (key.adapter !== adapterName || !adapter?.account)
1038
+ throw new Error(`该账号只能用于 ${key.adapter} 客户端`);
1039
+ return;
1040
+ }
1041
+ if (!adapter?.protocols?.includes(key.protocol)) {
1042
+ throw new Error(adapter?.protocols?.length
1043
+ ? `${adapter.title} 不认 ${key.protocol} 协议的密钥(它认:${adapter.protocols.join('、')})`
1044
+ : `${adapter?.title ?? adapterName} 不支持用密钥,只能用它自己登录的账号:到成员的「编辑」里去掉密钥`);
1045
+ }
1046
+ },
1047
+ async seal(topicId, memberId) {
1048
+ // stop removes idle handles synchronously and emits instances.changed after they finish stopping.
1049
+ const stopped = instances.stop({ topicId, memberId }, { force: false });
1050
+ recordSessionEnd(topicId, memberId, sessionRow(topicId, memberId)?.session_id, 'sealed');
1051
+ clearSession(topicId, memberId);
1052
+ await stopped;
1053
+ },
1054
+ };
1055
+ ctx.point('session.init', { title: '会话开始', group: '一段会话', about: '纯只读的静态提示词片段:汇总后计入 prompt 指纹并统计各插件体量,变更时按适配器能力刷新。', order: 10 });
1056
+ ctx.point('session.mcp', { title: '交给客户端的工具', group: '一段会话', about: '纯只读的 MCP 服务清单:实例启动时交给客户端,并计入 tools 指纹。', order: 20 });
1057
+ ctx.point('session.input', { title: '启动静态指纹', group: '一段会话', about: '非文本静态输入(如客户端自读 Skill 链接、原生 MCP 配置)的只读指纹,参与四维刷新比对。', order: 22 });
1058
+ ctx.point('session.prepare', { title: '启动前准备', group: '一段会话', about: '仅在真正拉起或重启实例前执行的准备工作(如同步工作目录软链、对账来源提示),变更检查阶段不触碰磁盘。', order: 25 });
1059
+ ctx.provide('instances', instances);
1060
+ const entry = ctx.get('entry');
1061
+ const memberId = { type: 'string', member: true };
1062
+ const topicId = { type: 'string', description: '主题编号' };
1063
+ const memberKey = { type: 'string', description: '成员编号' };
1064
+ ctx.effect(entry.op({
1065
+ name: 'members.adapters', about: '列出宿主支持的客户端、安装情况和适配器能力。',
1066
+ http: ['GET', '/api/adapters'], agent: true,
1067
+ run: () => Promise.all(instances.adapters().map(async ({ name, adapter }) => ({
1068
+ name,
1069
+ title: adapter.title,
1070
+ memberTemplate: adapter.memberTemplate,
1071
+ icon: adapter.icon,
1072
+ applies: adapter.applies,
1073
+ // What this client can do, as its adapter declares it. The console shows it; the host acts on the same declarations.
1074
+ capabilities: {
1075
+ detect: !!adapter.detect, options: !!adapter.options, quota: !!adapter.quota, append: adapter.append === true,
1076
+ keys: adapter.protocols ?? [], account: !!adapter.account,
1077
+ ...(adapter.account?.token ? {
1078
+ accountToken: {
1079
+ label: adapter.account.token.label,
1080
+ ...(adapter.account.token.placeholder ? { placeholder: adapter.account.token.placeholder } : {}),
1081
+ ...(adapter.account.token.help ? { help: adapter.account.token.help } : {}),
1082
+ },
1083
+ } : {}),
1084
+ command: adapter.command ?? '', requiresCommand: adapter.requiresCommand === true, sessions: !!adapter.sessions,
1085
+ },
1086
+ detected: adapter.detect ? await adapter.detect().catch((error) => ({ installed: false, note: String(error) })) : { installed: true },
1087
+ }))),
1088
+ }));
1089
+ const OPTIONS_CACHE_TTL_MS = 600_000;
1090
+ const OPTIONS_CACHE_MAX = 32;
1091
+ const optionsCache = new WeakMap();
1092
+ const optionsInFlight = new WeakMap();
1093
+ const optionsCacheKey = (key, env) => {
1094
+ if (!key && !env)
1095
+ return 'default';
1096
+ return createHash('sha256').update(JSON.stringify({
1097
+ ...(key ? { key: { protocol: key.protocol, endpoint: key.endpoint ?? '', apiKeyHash: createHash('sha256').update(key.apiKey).digest('hex') } } : {}),
1098
+ ...(env ? { env: Object.entries(env).sort(([a], [b]) => a.localeCompare(b)) } : {}),
1099
+ })).digest('hex');
1100
+ };
1101
+ const readAdapterOptions = async (adapter, forceFresh, key, env) => {
1102
+ if (!adapter.options)
1103
+ return [];
1104
+ const cacheKey = optionsCacheKey(key, env);
1105
+ let cache = optionsCache.get(adapter);
1106
+ if (!cache) {
1107
+ cache = new Map();
1108
+ optionsCache.set(adapter, cache);
1109
+ }
1110
+ if (!forceFresh) {
1111
+ const hit = cache.get(cacheKey);
1112
+ if (hit && Date.now() - hit.at < OPTIONS_CACHE_TTL_MS)
1113
+ return hit.options;
1114
+ }
1115
+ let inflight = optionsInFlight.get(adapter);
1116
+ if (!inflight) {
1117
+ inflight = new Map();
1118
+ optionsInFlight.set(adapter, inflight);
1119
+ }
1120
+ if (!forceFresh && inflight.has(cacheKey))
1121
+ return inflight.get(cacheKey);
1122
+ const probe = adapter.options(forceFresh, key, env).then((result) => {
1123
+ if (inflight.get(cacheKey) === probe && !result.some((field) => field.error !== undefined)) {
1124
+ cache.delete(cacheKey);
1125
+ cache.set(cacheKey, { at: Date.now(), options: result });
1126
+ while (cache.size > OPTIONS_CACHE_MAX) {
1127
+ const oldest = cache.keys().next().value;
1128
+ if (oldest === undefined)
1129
+ break;
1130
+ cache.delete(oldest);
1131
+ }
1132
+ }
1133
+ return result;
1134
+ }).finally(() => {
1135
+ if (inflight.get(cacheKey) === probe)
1136
+ inflight.delete(cacheKey);
1137
+ });
1138
+ inflight.set(cacheKey, probe);
1139
+ return probe;
1140
+ };
1141
+ ctx.effect(entry.op({
1142
+ name: 'members.adapter_options', about: '查看适配器的可配置选项,可指定成员所用的密钥来查可选模型。',
1143
+ input: object({
1144
+ name: { type: 'string', description: '适配器的名字' },
1145
+ key: { type: 'string', description: 'API 密钥或客户端账号的编号' },
1146
+ fresh: { type: 'string', description: '填 1 重新获取客户端的选项' },
1147
+ }, ['name']),
1148
+ http: ['GET', '/api/adapters/:name/options'], agent: true,
1149
+ async run({ name, key: keyId, fresh }) {
1150
+ const adapter = instances.adapters().find((a) => a.name === name)?.adapter;
1151
+ if (!adapter)
1152
+ throw new HttpError(404, '没有这个适配器');
1153
+ // With a key, the choices (the models above all) are what that key can use.
1154
+ const { key, env } = await keyOf(name, keyId);
1155
+ const options = await readAdapterOptions(adapter, fresh === '1', key, env).catch((error) => {
1156
+ throw new HttpError(400, errorText(error));
1157
+ });
1158
+ // What a member of this adapter can be set to: how its client is started (when it is a command), what the
1159
+ // adapter itself offers, and what plugins add for every member.
1160
+ const language = ctx.runtime.has('i18n') ? ctx.get('i18n').lang() : 'zh';
1161
+ const localized = (field) => ({
1162
+ ...field,
1163
+ label: localizeText(field.label, language, field.key),
1164
+ ...(field.description !== undefined ? { description: localizeText(field.description, language) } : {}),
1165
+ ...(field.error !== undefined ? { error: localizeText(field.error, language) } : {}),
1166
+ options: field.options?.map((option) => ({ ...option, label: localizeText(option.label, language, option.value), ...(option.hint !== undefined ? { hint: localizeText(option.hint, language) } : {}) })),
1167
+ suggestions: field.suggestions?.map((option) => ({ ...option, label: localizeText(option.label, language, option.value), ...(option.hint !== undefined ? { hint: localizeText(option.hint, language) } : {}) })),
1168
+ });
1169
+ return [
1170
+ ...(adapter.command ? [{ key: 'command', label: '启动命令', kind: 'string', default: adapter.command, description: '这个客户端是怎么启动的。通常不用改;装在别处或要包一层时写完整的命令行,比如 /opt/bin/kimi acp。' }] : []),
1171
+ ...options,
1172
+ ...(await ctx.runtime.serial('member.options', { adapter: name })).flat(),
1173
+ { key: 'env', label: '环境变量', kind: 'map', description: '成员专属环境变量模板;值可用 ${name} 引用系统可见配置或宿主环境变量。' },
1174
+ ].map(localized);
1175
+ },
1176
+ }));
1177
+ ctx.effect(entry.op({
1178
+ name: 'members.adapter_quota', workload: 'external', about: '查看支持额度查询的客户端还剩多少用量、何时重置。',
1179
+ input: object({
1180
+ name: { type: 'string', description: '适配器的名字' },
1181
+ member: { ...memberId, description: '成员编号或 @ 名,省略时查询客户端默认账号' },
1182
+ key: { type: 'string', description: '从密钥页按指定凭据查询' },
1183
+ }, ['name']),
1184
+ http: ['GET', '/api/adapters/:name/quota'], agent: true,
1185
+ async run({ name, member, key }) {
1186
+ const adapter = instances.adapters().find((a) => a.name === name)?.adapter;
1187
+ if (!adapter?.quota)
1188
+ throw new HttpError(404, '这个适配器不提供额度');
1189
+ if (member && key)
1190
+ throw new HttpError(400, '请选择成员或凭据中的一个');
1191
+ let quota;
1192
+ let redactions = [];
1193
+ if (member !== undefined) {
1194
+ const found = member.startsWith('@') ? members.list().find((one) => one.handle === member.slice(1)) : members.get(member);
1195
+ if (found?.kind !== 'agent')
1196
+ throw new HttpError(404, '没有这个成员');
1197
+ if (found.adapter !== name)
1198
+ throw new HttpError(400, '这个成员使用的适配器与请求不一致');
1199
+ let memberEnv;
1200
+ if (found.env) {
1201
+ try {
1202
+ const resolved = config.resolveMemberEnv(found.env);
1203
+ memberEnv = resolved.env;
1204
+ redactions = resolved.redactions;
1205
+ }
1206
+ catch (error) {
1207
+ throw new HttpError(400, errorText(error));
1208
+ }
1209
+ }
1210
+ quota = { ...await keyOf(name, found.key, 'quota'), options: found.options, ...(memberEnv && { memberEnv }) };
1211
+ }
1212
+ else if (key)
1213
+ quota = await keyOf(name, key, 'quota');
1214
+ try {
1215
+ return await (quota ? adapter.quota(quota) : adapter.quota());
1216
+ }
1217
+ catch (error) {
1218
+ const accountValues = (adapter.quotaAccountEnv ?? []).flatMap((name) => {
1219
+ const value = quota?.env?.[name] ?? quota?.memberEnv?.[name];
1220
+ return value ? [value] : [];
1221
+ });
1222
+ const message = redactText(errorText(error), [...redactions, ...accountValues]);
1223
+ const apiKey = quota?.key?.apiKey;
1224
+ throw new HttpError(400, apiKey ? message.replaceAll(apiKey, '[已隐藏]') : message);
1225
+ }
1226
+ },
1227
+ }));
1228
+ ctx.effect(entry.group('instances', '运行中的实例、外部会话、交接和后台任务'));
1229
+ ctx.effect(entry.op({ name: 'instances.list', about: '查看宿主的实例及其运行状态。', http: ['GET', '/api/instances'], agent: true, run: () => instances.list() }));
1230
+ ctx.effect(entry.op({
1231
+ name: 'instances.start_input',
1232
+ about: '查看最近一次会话启动输入的体量观测及各插件字符数分布。',
1233
+ http: ['GET', '/api/instances/start-input'],
1234
+ agent: true,
1235
+ run: (_args, caller) => {
1236
+ const summary = instances.promptMetrics();
1237
+ const current = caller.topicId && caller.member ? instances.startMetrics(caller.topicId, caller.member.id) : undefined;
1238
+ return {
1239
+ latest: summary.latest ?? null,
1240
+ byPlugin: summary.byPlugin,
1241
+ ...(caller.topicId && caller.member ? { current: current ?? null } : {}),
1242
+ };
1243
+ },
1244
+ }));
1245
+ ctx.effect(entry.op({
1246
+ name: 'instances.stop', about: '停止指定范围的实例。默认只停空闲实例,返回仍忙的实例。',
1247
+ input: object({
1248
+ scope: object({ topicId, memberId: memberKey, adapter: { type: 'string' } }),
1249
+ force: { type: 'boolean', description: '强制停止正在运行的实例' },
1250
+ }),
1251
+ http: ['POST', '/api/instances/stop'],
1252
+ run: ({ scope = {}, force = false }) => instances.stop(scope, { force, reason: '在实例列表里被结束' }),
1253
+ }));
1254
+ ctx.on('members.changed', ({ id }) => {
1255
+ const member = members.get(id);
1256
+ if (member) {
1257
+ const rows = db.prepare('SELECT topic_id, session_id FROM sessions WHERE member_id = ? AND session_id IS NOT NULL AND adapter IS NOT NULL AND adapter != ?')
1258
+ .all(id, member.adapter);
1259
+ for (const row of rows)
1260
+ insertSessionEndIfAbsent.run(row.topic_id, id, row.session_id, 'adapter', Date.now());
1261
+ }
1262
+ // Moved to another client: what runs under the old one is not this member any more.
1263
+ if (member?.enabled && [...handles.values()].some((h) => h.memberId === id && h.adapter !== member.adapter)) {
1264
+ void instances.stop({ memberId: id }, { force: true, reason: '成员换了客户端' });
1265
+ }
1266
+ });
1267
+ ctx.effect(async () => {
1268
+ await instances.stop({}, { force: true, reason: '宿主退出' });
1269
+ await Promise.all(stopping.values());
1270
+ });
1271
+ },
1272
+ });