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,921 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, constants, copyFileSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, statSync } from 'node:fs';
4
+ import { cp } from 'node:fs/promises';
5
+ import { basename, isAbsolute, join, resolve, sep } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { extractPluginArchive, PLUGIN_ARCHIVE_LIMIT } from "../archive.js";
8
+ import { writeDocuments } from "../documents.js";
9
+ import { HttpError } from "../entry.js";
10
+ import { object } from "../ops.js";
11
+ import { errorText, log, readJson } from "../util.js";
12
+ import { readPlugin } from "./index.js";
13
+ import { isNpmPackage, isNpmVersion, newerNpmVersion, npmArchive, npmRelease, sha512Integrity } from "./npm.js";
14
+ import { pluginCatalog } from "./catalog.js";
15
+ import { PLUGIN_ID, readPluginPackage, validateConfigFields } from "./plugin-manifest.js";
16
+ import { configOwnership } from "../config.js";
17
+ import { topicOwnership } from "../topics.js";
18
+ const stringValue = { type: 'string' };
19
+ const booleanValue = { type: 'boolean' };
20
+ const nullableString = { type: ['string', 'null'] };
21
+ const overrideSubdir = '.override';
22
+ function applyManifest(info, manifest) {
23
+ if (!manifest)
24
+ return info;
25
+ const { name, version, description } = manifest;
26
+ return {
27
+ ...info,
28
+ ...(manifest.foundation ? { foundation: true } : {}),
29
+ ...(version === undefined ? {} : { version }),
30
+ title: name ?? info.title,
31
+ about: (typeof description === 'object' ? description.default : description) ?? info.about,
32
+ };
33
+ }
34
+ const builtinRoot = fileURLToPath(new URL('../../plugins/', import.meta.url));
35
+ /**
36
+ * The code a package directory would load, as one digest: every file's path and bytes, following links the way the
37
+ * loader does (a link is digested as what it points to), without its saved settings.
38
+ */
39
+ function contentDigest(dir) {
40
+ const hash = createHash('sha256');
41
+ const seen = new Set();
42
+ const walk = (at, rel) => {
43
+ const real = realpathSync(at);
44
+ if (seen.has(real))
45
+ return;
46
+ seen.add(real);
47
+ for (const entry of readdirSync(at, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
48
+ const path = join(at, entry.name), name = rel ? `${rel}/${entry.name}` : entry.name;
49
+ if (name === 'settings.json')
50
+ continue;
51
+ let stat;
52
+ try {
53
+ stat = statSync(path);
54
+ }
55
+ catch {
56
+ hash.update(name).update('\0broken\0');
57
+ continue;
58
+ }
59
+ if (stat.isDirectory())
60
+ walk(path, name);
61
+ else if (stat.isFile())
62
+ hash.update(name).update('\0').update(readFileSync(path)).update('\0');
63
+ }
64
+ };
65
+ walk(dir, '');
66
+ return hash.digest('hex').slice(0, 16);
67
+ }
68
+ /** Owns the registry of shipped and installed packages. Mutations use the host's plugin change queue. */
69
+ export function pluginPackages(home, runtime) {
70
+ const bundled = new Map();
71
+ const registered = new Map();
72
+ const config = () => configOwnership(runtime.get('config'));
73
+ const off = () => config().get('settings', 'plugins.disabled');
74
+ const stoppedByDefault = (item) => config().get('settings', 'plugins.disabled').includes(item.record.id);
75
+ const dirOf = (id) => home.path('plugins', id);
76
+ const recordList = () => Array.from(registered.values(), (item) => item.record).filter(({ source }) => source.kind !== 'builtin');
77
+ const saveIndex = (records) => writeDocuments(home, [{ path: home.path('plugins.json'), value: { installed: records } }]);
78
+ const manifestOf = (name) => registered.get(name)?.package?.manifest;
79
+ const pluginSecretsFile = (id) => `secrets/${id}.json`;
80
+ const boundTopic = (id) => runtime.has('topics')
81
+ ? runtime.get('topics').all().find((topic) => topic.plugin === id && topic.deletedAt === null)
82
+ : undefined;
83
+ const clearTrashedBindings = (topics, ownership, owner, keepId) => {
84
+ for (const old of topics.all().filter((topic) => topic.plugin === owner && topic.deletedAt !== null && topic.id !== keepId)) {
85
+ ownership.bind(old.id, null);
86
+ }
87
+ };
88
+ function declareStaticConfig(item, pkg) {
89
+ item.configDisposer?.();
90
+ delete item.configDisposer;
91
+ const manifest = pkg?.manifest;
92
+ if (!manifest)
93
+ return;
94
+ item.configDisposer = config().declare({
95
+ scope: `plugin:${item.record.id}`,
96
+ owner: item.record.id,
97
+ source: item.record.source.kind === 'builtin' ? 'builtin' : 'external',
98
+ ...(manifest.name !== undefined ? { title: manifest.name } : {}),
99
+ ...(manifest.description !== undefined ? { description: manifest.description } : {}),
100
+ ...(manifest.steps !== undefined ? { steps: manifest.steps } : {}),
101
+ ...(manifest.configurationVariants !== undefined ? { variants: manifest.configurationVariants } : {}),
102
+ ...(manifest.visibility !== undefined ? { visibility: manifest.visibility } : {}),
103
+ ...(manifest.approvalRisk !== undefined ? { approvalRisk: manifest.approvalRisk } : {}),
104
+ fields: manifest.configuration ?? [],
105
+ }, 'manifest');
106
+ }
107
+ // A plugin asking for its own reload once per batch of configuration keys: one is enough, it re-reads everything.
108
+ const reloadPending = new Set();
109
+ // Each change can stop plugins and remove registrations. Finish it before another can change them.
110
+ let pluginChange = Promise.resolve();
111
+ const changePlugin = async (change) => {
112
+ const before = pluginChange;
113
+ const { promise, resolve } = Promise.withResolvers();
114
+ pluginChange = promise;
115
+ await before;
116
+ try {
117
+ return await change();
118
+ }
119
+ finally {
120
+ resolve();
121
+ }
122
+ };
123
+ // Dynamic declarations are valid only while the plugin is running; the wrapper in loadPackage owns their disposal.
124
+ const dynamicConfig = new Map();
125
+ function pluginContext(id, manifest, dir) {
126
+ const scope = `plugin:${id}`;
127
+ const dynamicFields = [];
128
+ let schemaRefresh = false;
129
+ const refreshRunningSchema = (active) => {
130
+ if (schemaRefresh || dynamicConfig.get(id) !== active || !runtime.list().some((p) => p.name === id && p.state === 'started'))
131
+ return;
132
+ schemaRefresh = true;
133
+ queueMicrotask(() => {
134
+ schemaRefresh = false;
135
+ if (dynamicConfig.get(id) === active)
136
+ runtime.emit('plugin.changed', { name: id, kind: 'configured' });
137
+ });
138
+ };
139
+ return {
140
+ id, dir, manifest,
141
+ config: {
142
+ get: (key) => config().get(scope, key, { owner: id, includeSecret: false }),
143
+ all: () => config().all(scope, { owner: id }),
144
+ set: (key, value) => config().set(scope, key, value, { owner: id }),
145
+ declare: (fields) => {
146
+ const active = dynamicConfig.get(id);
147
+ if (!active)
148
+ throw new Error(`插件 ${id} 只能在运行中声明动态配置`);
149
+ validateConfigFields(fields, [...manifest?.configuration ?? [], ...dynamicFields, ...fields]);
150
+ const dispose = config().declare({ scope, owner: id, fields });
151
+ dynamicFields.push(...fields);
152
+ refreshRunningSchema(active);
153
+ let activeUndo = true;
154
+ const undo = () => {
155
+ if (!activeUndo)
156
+ return;
157
+ activeUndo = false;
158
+ dispose();
159
+ for (const field of fields) {
160
+ const at = dynamicFields.indexOf(field);
161
+ if (at >= 0)
162
+ dynamicFields.splice(at, 1);
163
+ }
164
+ const idx = active.indexOf(undo);
165
+ if (idx >= 0)
166
+ active.splice(idx, 1);
167
+ refreshRunningSchema(active);
168
+ };
169
+ active.push(undo);
170
+ return undo;
171
+ },
172
+ applyOperation: async (operationKey, updates) => {
173
+ const field = manifest?.configuration?.find((one) => one.key === operationKey) ??
174
+ dynamicFields.find((one) => one.key === operationKey);
175
+ if (field?.kind !== 'operation')
176
+ throw new Error(`插件 ${id} 没有配置操作 ${operationKey}`);
177
+ const outside = Object.keys(updates).filter((key) => !field.target?.includes(key));
178
+ if (outside.length)
179
+ throw new Error(`配置操作 ${operationKey} 不能写:${outside.join(', ')}`);
180
+ return config().patch(scope, updates, { owner: id, operation: operationKey });
181
+ },
182
+ },
183
+ secrets: { get: (key) => config().get(scope, key, { owner: id, includeSecret: true }) },
184
+ topic() {
185
+ const declared = manifest?.topic;
186
+ if (!declared)
187
+ throw new Error(`插件 ${id} 没有在 plugin.yaml 声明 topic`);
188
+ if (!runtime.has('topics'))
189
+ throw new Error('主题服务还没有准备好');
190
+ const topics = runtime.get('topics');
191
+ const ownership = topicOwnership(topics);
192
+ const bound = topics.all().find((topic) => topic.plugin === id && topic.deletedAt === null);
193
+ if (bound) {
194
+ clearTrashedBindings(topics, ownership, id, bound.id);
195
+ return bound;
196
+ }
197
+ const system = ownership.ensureSystem();
198
+ let parentId = system.id;
199
+ if (system.archivedAt !== null) {
200
+ parentId = null;
201
+ log('host', `系统主题 ${system.id} 已归档,插件 ${id} 的主题改建在顶层`);
202
+ }
203
+ else {
204
+ const depth = topics.path(system.id).length;
205
+ const maxDepth = config().get('settings', 'topics.maxDepth');
206
+ if (depth >= maxDepth) {
207
+ parentId = null;
208
+ log('host', `系统主题 ${system.id} 位于第 ${depth} 层,已达最大层级 ${maxDepth},插件 ${id} 的主题改建在顶层`);
209
+ }
210
+ }
211
+ const result = ownership.create({
212
+ title: declared.title, summary: declared.summary, parentId, pinned: declared.pinned, view: declared.view ?? null,
213
+ }, id);
214
+ clearTrashedBindings(topics, ownership, id, result.id);
215
+ return result;
216
+ },
217
+ reload() {
218
+ if (reloadPending.has(id))
219
+ return;
220
+ reloadPending.add(id);
221
+ setImmediate(() => {
222
+ changePlugin(async () => {
223
+ try {
224
+ await reload(id);
225
+ }
226
+ finally {
227
+ reloadPending.delete(id);
228
+ }
229
+ }).catch((error) => log('host', `插件 ${id} 自行重启失败`, errorText(error)));
230
+ });
231
+ },
232
+ };
233
+ }
234
+ /**
235
+ * The code of the built-in plugin instance that runs now: set when an instance read from that code starts. The first
236
+ * read is the code the process started from; a later read takes the commit on disk at that moment (marked when the
237
+ * working tree had other changes too), and is unknown (null) when it cannot be told.
238
+ */
239
+ const loadedCode = new Map();
240
+ const codeNow = () => {
241
+ try {
242
+ const git = (...args) => execFileSync('git', ['-C', builtinRoot, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
243
+ const head = git('rev-parse', '--short', 'HEAD');
244
+ return head && (git('status', '--porcelain') ? `${head}+changes@${Date.now()}` : head);
245
+ }
246
+ catch {
247
+ return undefined;
248
+ }
249
+ };
250
+ function summary(name, running) {
251
+ const item = registered.get(name);
252
+ if (!item && !running)
253
+ throw new HttpError(404, `没有这个插件:${name}`);
254
+ const info = running ?? {
255
+ name, core: false, state: item && stoppedByDefault(item) ? 'stopped' : 'failed',
256
+ needs: [], provides: [], waitingFor: [], error: item?.readError,
257
+ };
258
+ const manifest = manifestOf(name);
259
+ if (!item || item.record.source.kind === 'builtin') {
260
+ const code = loadedCode.has(name) ? loadedCode.get(name) : home.codeCommit;
261
+ return { ...applyManifest({ ...info, ...(code ? { code } : {}) }, manifest), hasConfig: config().hasVisibleConfig(`plugin:${name}`) };
262
+ }
263
+ const { version, source, installedAt, updatedAt } = item.record;
264
+ const fallback = bundled.get(name);
265
+ return {
266
+ ...applyManifest({ ...info, version, source, installedAt, updatedAt, external: true }, manifest),
267
+ ...(source.kind === 'npm' ? { version } : {}),
268
+ ...(fallback ? { overrides: 'builtin' } : {}),
269
+ ...(fallback?.package?.manifest?.foundation ? { foundation: true } : {}),
270
+ hasConfig: config().hasVisibleConfig(`plugin:${name}`),
271
+ };
272
+ }
273
+ function list() {
274
+ const entries = new Map(runtime.list().map((info) => [info.name, info]));
275
+ return Array.from(new Set([...entries.keys(), ...registered.keys()]), (name) => summary(name, entries.get(name)));
276
+ }
277
+ function detail(name) {
278
+ return summary(name, runtime.list().find((plugin) => plugin.name === name));
279
+ }
280
+ function external(name) {
281
+ const item = registered.get(name);
282
+ if (item && item.record.source.kind !== 'builtin')
283
+ return item;
284
+ if (item || runtime.list().some((info) => info.name === name))
285
+ throw new HttpError(400, `插件 ${name} 没有本地安装记录`);
286
+ throw new HttpError(404, `没有这个插件:${name}`);
287
+ }
288
+ async function loadPackage(item, { pkg: initial, stopped = stoppedByDefault(item), boot = false } = {}) {
289
+ const { dir, record: { id, source } } = item;
290
+ let reads = 0;
291
+ const read = async (pkg = readPluginPackage(dir)) => {
292
+ // The code this read takes (told before reading), recorded for the instance that starts from it, and only then.
293
+ const code = source.kind !== 'builtin' ? null : reads++ === 0 && boot ? home.codeCommit ?? null : codeNow() ?? null;
294
+ const plugin = await readOnce(pkg);
295
+ if (source.kind !== 'builtin')
296
+ return plugin;
297
+ return { ...plugin, stop: plugin.stop?.bind(plugin), async start(ctx) {
298
+ await plugin.start.call(plugin, ctx);
299
+ loadedCode.set(id, code);
300
+ } };
301
+ };
302
+ const readOnce = async (pkg) => {
303
+ const { fragment, manifest } = pkg;
304
+ if (manifest && manifest.pluginId !== id)
305
+ throw new Error(`plugin.yaml 的 pluginId 应为 ${id}`);
306
+ item.package = pkg;
307
+ declareStaticConfig(item, pkg);
308
+ const ext = pluginContext(id, manifest, dir);
309
+ const plugin = await readPlugin(join(dir, pkg.entrypoint), home, ext);
310
+ if (plugin.name !== id)
311
+ throw new Error(`插件必须以 ${id} 为名`);
312
+ if (source.kind !== 'builtin' && plugin.core)
313
+ throw new Error(`外部插件必须可卸载:${id}`);
314
+ const icon = manifest?.icon;
315
+ return {
316
+ ...plugin,
317
+ topicSwitch: manifest?.topicSwitch ?? !bundled.has(id),
318
+ icon: icon === undefined ? plugin.icon : join(dir, icon),
319
+ stop: plugin.stop?.bind(plugin),
320
+ async start(ctx) {
321
+ const disposers = [];
322
+ dynamicConfig.set(id, disposers);
323
+ try {
324
+ await plugin.start(ctx);
325
+ }
326
+ catch (error) {
327
+ dynamicConfig.delete(id);
328
+ while (disposers.length)
329
+ disposers.pop()();
330
+ throw error;
331
+ }
332
+ ctx.effect(() => {
333
+ dynamicConfig.delete(id);
334
+ while (disposers.length)
335
+ disposers.pop()();
336
+ });
337
+ if (!fragment)
338
+ return;
339
+ let unregister;
340
+ const register = () => { unregister = ctx.get('console').register(ctx.name, fragment); };
341
+ ctx.on('console.ready', register);
342
+ ctx.effect(() => unregister?.());
343
+ if (ctx.runtime.has('console'))
344
+ register();
345
+ },
346
+ };
347
+ };
348
+ await runtime.load(await read(initial), { stopped, source: read });
349
+ delete item.readError;
350
+ }
351
+ async function restoreItem(item, boot = false) {
352
+ const { id } = item.record;
353
+ try {
354
+ await loadPackage(item, { boot });
355
+ }
356
+ catch (error) {
357
+ item.readError = errorText(error);
358
+ const problem = `插件 ${id} 读不进来:${item.readError}`;
359
+ log('host', problem);
360
+ return problem;
361
+ }
362
+ }
363
+ function readIndex({ installed }, root, builtin, reserved, problems) {
364
+ const entries = new Map();
365
+ const prefix = resolve(root) + sep;
366
+ for (const record of installed) {
367
+ const { id, source, codeDir } = record;
368
+ const validSource = builtin ? source?.kind === 'builtin' :
369
+ source?.kind === 'local-directory' || source?.kind === 'local-archive' ||
370
+ (source?.kind === 'npm' && isNpmPackage(source.package) && isNpmVersion(record.version));
371
+ if (typeof id !== 'string' || !PLUGIN_ID.test(id) || reserved.has(id) || entries.has(id) || !validSource ||
372
+ (codeDir !== undefined && (builtin || codeDir !== overrideSubdir))) {
373
+ problems.push(`插件登记清单中有无效或重复的记录:${id}`);
374
+ continue;
375
+ }
376
+ const path = source.kind === 'builtin' ? source.path : id;
377
+ const dir = typeof path === 'string' && !isAbsolute(path) ? resolve(root, path) : '';
378
+ if (!dir.startsWith(prefix)) {
379
+ problems.push(`插件 ${id} 的目录必须在清单所在的插件目录内`);
380
+ continue;
381
+ }
382
+ entries.set(id, { record, dir: codeDir ? join(dir, codeDir) : dir });
383
+ }
384
+ return entries;
385
+ }
386
+ async function load(extra = [], root = builtinRoot) {
387
+ const problems = [];
388
+ const disabled = new Set(off());
389
+ const reserved = new Set(runtime.list().map(({ name }) => name));
390
+ const shipped = JSON.parse(readFileSync(join(root, 'builtin.json'), 'utf8'));
391
+ for (const [id, item] of readIndex(shipped, root, true, reserved, problems))
392
+ bundled.set(id, item);
393
+ const index = readJson(home.path('plugins.json'), { installed: [] });
394
+ const installed = readIndex(index, home.path('plugins'), false, new Set([...reserved, ...extra.map(({ name }) => name)]), problems);
395
+ const activate = async (item) => {
396
+ registered.set(item.record.id, item);
397
+ const problem = await restoreItem(item, true);
398
+ if (problem)
399
+ problems.push(problem);
400
+ };
401
+ for (const [id, fallback] of bundled) {
402
+ const override = installed.get(id);
403
+ if (override) {
404
+ // Keep the bundled policy even when its code is not started.
405
+ try {
406
+ fallback.package = readPluginPackage(fallback.dir);
407
+ }
408
+ catch (error) {
409
+ const problem = `插件 ${id} 的随包版本读不进来:${errorText(error)}`;
410
+ log('host', problem);
411
+ problems.push(problem);
412
+ }
413
+ log('host', `插件 ${id} 使用本地覆盖版本`, override.record.source);
414
+ }
415
+ await activate(override ?? fallback);
416
+ }
417
+ for (const plugin of extra)
418
+ await runtime.load(plugin, { stopped: disabled.has(plugin.name) });
419
+ for (const [id, item] of installed)
420
+ if (!bundled.has(id))
421
+ await activate(item);
422
+ return problems;
423
+ }
424
+ async function discoverId(pkg, dir, source) {
425
+ // A manifest-free factory can use its source name during discovery. Activation uses the exported ID.
426
+ const id = source.kind === 'local-directory' ? basename(source.path) :
427
+ source.kind === 'local-archive' ? source.filename.replace(/\.(?:tgz|tar\.gz)$/i, '') : source.package.split('/').at(-1);
428
+ const unset = () => undefined;
429
+ const ext = { id, dir, config: { get: unset, all: () => ({}), set: () => { }, declare: () => () => { }, applyOperation: async () => ({ saved: true, scope: `plugin:${id}` }) }, secrets: { get: unset }, topic: () => { throw new Error('主题服务还没有准备好'); }, reload: () => { } };
430
+ return (await readPlugin(join(dir, pkg.entrypoint), home, ext)).name;
431
+ }
432
+ function keepSettings(from, to) {
433
+ const file = join(from, 'settings.json');
434
+ if (existsSync(file)) {
435
+ mkdirSync(to, { recursive: true });
436
+ copyFileSync(file, join(to, 'settings.json'));
437
+ }
438
+ }
439
+ async function install(source, populate, replace, { expectedId, version } = {}) {
440
+ const stage = home.storage.temporary('plugin-install');
441
+ try {
442
+ const candidate = join(stage.path, 'package'), backup = join(stage.path, 'before');
443
+ mkdirSync(candidate);
444
+ await populate(candidate);
445
+ let pkg, id;
446
+ try {
447
+ pkg = readPluginPackage(candidate);
448
+ if (source.kind === 'npm') {
449
+ const identity = readJson(join(candidate, 'package.json'), {});
450
+ if (identity.name !== source.package || identity.version !== version ||
451
+ (pkg.manifest?.version !== undefined && pkg.manifest.version !== version)) {
452
+ throw new Error('npm 包的名称或版本与包内声明不匹配');
453
+ }
454
+ }
455
+ id = pkg.manifest?.pluginId ?? expectedId ?? await discoverId(pkg, candidate, source);
456
+ if (!PLUGIN_ID.test(id))
457
+ throw new Error(`插件 ID 无效:${id}`);
458
+ if (expectedId && id !== expectedId)
459
+ throw new Error(`更新来源声明了 ${id},应为 ${expectedId}`);
460
+ }
461
+ catch (error) {
462
+ throw new HttpError(400, errorText(error));
463
+ }
464
+ const before = registered.get(id);
465
+ const running = runtime.list().find((info) => info.name === id);
466
+ let attempted;
467
+ if (running && (!before || running.core)) {
468
+ throw new HttpError(400, `插件 ID 已被宿主使用:${id}`);
469
+ }
470
+ const previous = before?.record.source.kind === 'builtin' ? undefined : before;
471
+ const codeDir = previous ? previous.record.codeDir : bundled.has(id) ? overrideSubdir : undefined;
472
+ const dataDir = dirOf(id);
473
+ const dest = codeDir ? join(dataDir, codeDir) : dataDir;
474
+ const parent = codeDir && lstatSync(dataDir, { throwIfNoEntry: false });
475
+ if (parent && !parent.isDirectory())
476
+ throw new HttpError(400, `安装位置需要是目录:${dataDir}`);
477
+ const occupied = lstatSync(dest, { throwIfNoEntry: false });
478
+ if ((before || occupied) && !replace)
479
+ throw new HttpError(409, `插件 ${id} 已有安装记录或目录,确认后可以覆盖更新`);
480
+ if (occupied && !occupied.isDirectory())
481
+ throw new HttpError(400, `安装位置需要是目录:${dest}`);
482
+ await runtime.unload(id);
483
+ before?.configDisposer?.();
484
+ if (before)
485
+ delete before.configDisposer;
486
+ try {
487
+ if (occupied) {
488
+ if (!codeDir)
489
+ keepSettings(dest, candidate);
490
+ renameSync(dest, backup);
491
+ }
492
+ if (codeDir)
493
+ mkdirSync(dataDir, { recursive: true });
494
+ renameSync(candidate, dest);
495
+ const now = Date.now();
496
+ const record = { id, version: version ?? pkg.manifest?.version ?? null, source, ...(codeDir ? { codeDir } : {}),
497
+ installedAt: previous?.record.installedAt ?? now, updatedAt: now };
498
+ const item = { record, dir: dest };
499
+ attempted = item;
500
+ await loadPackage(item, { pkg }).catch((error) => { throw new HttpError(400, errorText(error)); });
501
+ if (source.kind === 'npm' && running?.state === 'started') {
502
+ const active = runtime.list().find((row) => row.name === id);
503
+ if (active?.state !== 'started')
504
+ throw new HttpError(400, active?.error ?? '新版插件未能启动');
505
+ }
506
+ saveIndex([...recordList().filter((row) => row.id !== id), record]);
507
+ registered.set(id, item);
508
+ }
509
+ catch (error) {
510
+ attempted?.configDisposer?.();
511
+ await runtime.unload(id);
512
+ if (!existsSync(candidate))
513
+ renameSync(dest, candidate);
514
+ if (existsSync(backup))
515
+ renameSync(backup, dest);
516
+ if (before)
517
+ await restoreItem(before);
518
+ throw error;
519
+ }
520
+ try {
521
+ // Only a fresh reinstall unarchives the bound topic, and only when the plugin's own uninstall archived it.
522
+ // An overwrite update never touches topics; recovery happens after the install is committed.
523
+ if (!before) {
524
+ const owned = boundTopic(id);
525
+ if (owned && owned.archivedAt !== null && topicOwnership(runtime.get('topics')).archivedBy(owned.id) === `plugin:${id}`) {
526
+ const state = runtime.list().find((plugin) => plugin.name === id)?.state;
527
+ if (state === 'started')
528
+ runtime.get('topics').unarchive(owned.id, `plugin:${id}`);
529
+ else
530
+ log('host', `插件 ${id} 启动后状态为 ${state ?? 'missing'},主题 ${owned.id} 保持归档`);
531
+ }
532
+ }
533
+ }
534
+ catch (recoveryError) {
535
+ log('host', `插件 ${id} 的主题恢复失败,安装已完成`, recoveryError);
536
+ }
537
+ runtime.emit('plugin.changed', { name: id, kind: before ? 'updated' : 'installed' });
538
+ return detail(id);
539
+ }
540
+ finally {
541
+ stage.release();
542
+ }
543
+ }
544
+ function installDirectory(path, replace = false, expectedId) {
545
+ if (!isAbsolute(path) || !existsSync(path) || !statSync(path).isDirectory())
546
+ throw new HttpError(400, '请选择实际存在的本地插件目录(绝对路径)');
547
+ const root = realpathSync(path);
548
+ return install({ kind: 'local-directory', path: resolve(path) }, (dir) => cp(root, dir, {
549
+ recursive: true,
550
+ filter(file) {
551
+ if (join(root, basename(file)) === file && basename(file).toLowerCase() === 'settings.json')
552
+ return false;
553
+ const info = lstatSync(file);
554
+ if (!info.isFile() && !info.isDirectory())
555
+ throw new HttpError(400, `插件目录只支持普通文件和目录:${file}`);
556
+ return true;
557
+ },
558
+ }), replace, { expectedId });
559
+ }
560
+ async function reload(name) {
561
+ const before = runtime.list().find((plugin) => plugin.name === name);
562
+ if (!before)
563
+ throw new HttpError(404, `没有这个插件:${name}`);
564
+ if (before.state !== 'started')
565
+ throw new Error(`${name} 现在没在运行(${before.state}),重新读不了:要启用它用 host.plugin_switch`);
566
+ await runtime.reload(name);
567
+ runtime.emit('plugin.changed', { name, kind: 'reloaded' });
568
+ return runtime.list().filter((plugin) => plugin.name === name);
569
+ }
570
+ function installArchive(filename, buffer, replace) {
571
+ return install({ kind: 'local-archive', filename }, (dir) => extractPluginArchive(buffer, dir), replace);
572
+ }
573
+ /**
574
+ * A package on this machine is read once from the file descriptor that was opened: its type and size are what
575
+ * that descriptor shows, so a path that changes after it was picked is refused like a bad upload. Opening does
576
+ * not wait on a pipe or device. The installed copy does not depend on the file afterwards.
577
+ */
578
+ function installArchiveFile(path, replace = false) {
579
+ const filename = basename(path);
580
+ const missing = () => new HttpError(400, '请选择实际存在的 .tgz 或 .tar.gz 插件离线包(绝对路径)');
581
+ if (!isAbsolute(path) || !/\.(?:tgz|tar\.gz)$/i.test(filename))
582
+ throw missing();
583
+ let fd;
584
+ try {
585
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
586
+ }
587
+ catch {
588
+ throw missing();
589
+ }
590
+ try {
591
+ if (!fstatSync(fd).isFile())
592
+ throw missing();
593
+ const buffer = Buffer.alloc(PLUGIN_ARCHIVE_LIMIT + 1);
594
+ let size = 0, read;
595
+ while (size < buffer.length && (read = readSync(fd, buffer, size, buffer.length - size, null)) > 0)
596
+ size += read;
597
+ if (size > PLUGIN_ARCHIVE_LIMIT)
598
+ throw new HttpError(413, '插件离线包太大');
599
+ return installArchive(filename, buffer.subarray(0, size), replace);
600
+ }
601
+ finally {
602
+ closeSync(fd);
603
+ }
604
+ }
605
+ async function installNpm(pkg, replace, expected) {
606
+ const release = await npmRelease(pkg, expected?.version);
607
+ if (expected && release.integrity !== expected.integrity)
608
+ throw new HttpError(409, 'npm 版本的完整性记录已变,请重新检查更新');
609
+ const stage = home.storage.temporary('plugin-npm');
610
+ try {
611
+ const downloads = join(stage.path, 'download');
612
+ mkdirSync(downloads);
613
+ const archive = await npmArchive(release, downloads);
614
+ return await install({ kind: 'npm', package: pkg }, (dir) => extractPluginArchive(archive, dir), replace, { expectedId: expected?.id, version: release.version });
615
+ }
616
+ finally {
617
+ stage.release();
618
+ }
619
+ }
620
+ async function checkUpdate(name) {
621
+ const { source, version } = external(name).record;
622
+ if (source.kind !== 'npm' || !isNpmVersion(version))
623
+ throw new HttpError(400, '只有 npm 安装的插件可检查 Registry 更新');
624
+ const release = await npmRelease(source.package);
625
+ return { installed: version, available: newerNpmVersion(release.version, version) ? release : null };
626
+ }
627
+ function update(name, version, integrity) {
628
+ const { source, version: installed } = external(name).record;
629
+ if (source.kind === 'npm') {
630
+ if (!isNpmVersion(version) || !integrity || sha512Integrity(integrity) !== integrity) {
631
+ throw new HttpError(400, '请先检查 npm 更新,确认具体版本和 SHA-512 后升级');
632
+ }
633
+ if (!isNpmVersion(installed) || !newerNpmVersion(version, installed))
634
+ throw new HttpError(409, '所选版本没有比已安装的版本新');
635
+ return installNpm(source.package, true, { id: name, version, integrity });
636
+ }
637
+ if (version !== undefined || integrity !== undefined)
638
+ throw new HttpError(409, '插件的安装来源已变,请重新确认');
639
+ if (source.kind === 'local-directory')
640
+ return installDirectory(source.path, true, name);
641
+ throw new HttpError(400, '离线包插件需要上传新版安装包来更新');
642
+ }
643
+ async function switchPlugin(name, action) {
644
+ const item = registered.get(name);
645
+ const overrides = new Set(config().get('settings', 'plugins.disabled'));
646
+ const before = runtime.list().find((info) => info.name === name);
647
+ const disabling = action === 'disable';
648
+ if (disabling) {
649
+ if (!item || before)
650
+ await runtime.disable(name);
651
+ }
652
+ else if (item && !before) {
653
+ await loadPackage(item, { stopped: false });
654
+ }
655
+ else {
656
+ await runtime.enable(name);
657
+ }
658
+ const changed = overrides.has(name) !== disabling;
659
+ if (changed) {
660
+ if (disabling)
661
+ overrides.add(name);
662
+ else
663
+ overrides.delete(name);
664
+ config().set('settings', 'plugins.disabled', [...overrides]);
665
+ }
666
+ const plugins = list();
667
+ if (changed || before?.state !== plugins.find((info) => info.name === name)?.state) {
668
+ runtime.emit('plugin.changed', { name, kind: disabling ? 'disabled' : 'enabled' });
669
+ }
670
+ return plugins;
671
+ }
672
+ async function restoreBundled(item, fallback) {
673
+ const name = item.record.id;
674
+ let pkg;
675
+ try {
676
+ pkg = readPluginPackage(fallback.dir);
677
+ }
678
+ catch (error) {
679
+ throw new HttpError(400, `插件 ${name} 的随包版本读不进来:${errorText(error)}`);
680
+ }
681
+ const stage = home.storage.temporary('plugin-restore-builtin');
682
+ const backup = join(stage.path, 'package');
683
+ let committed = false;
684
+ try {
685
+ await runtime.unload(name);
686
+ item.configDisposer?.();
687
+ delete item.configDisposer;
688
+ try {
689
+ if (existsSync(item.dir)) {
690
+ renameSync(item.dir, backup);
691
+ if (!item.record.codeDir)
692
+ keepSettings(backup, item.dir);
693
+ }
694
+ await loadPackage(fallback, { pkg });
695
+ const running = runtime.list().find((info) => info.name === name);
696
+ if (running?.state === 'failed')
697
+ throw new Error(running.error ?? '随包版本启动失败');
698
+ saveIndex(recordList().filter((record) => record.id !== name));
699
+ registered.set(name, fallback);
700
+ committed = true;
701
+ }
702
+ catch (error) {
703
+ await runtime.unload(name);
704
+ fallback.configDisposer?.();
705
+ delete fallback.configDisposer;
706
+ if (existsSync(backup)) {
707
+ if (existsSync(item.dir))
708
+ renameSync(item.dir, join(stage.path, 'discarded'));
709
+ renameSync(backup, item.dir);
710
+ }
711
+ await restoreItem(item);
712
+ throw new HttpError(400, `插件 ${name} 切回随包版失败:${errorText(error)}`);
713
+ }
714
+ }
715
+ finally {
716
+ if (committed || !existsSync(backup))
717
+ stage.release();
718
+ }
719
+ runtime.emit('plugin.changed', { name, kind: 'updated' });
720
+ return { name };
721
+ }
722
+ async function uninstall(name, purgeData) {
723
+ const item = external(name);
724
+ const fallback = bundled.get(name);
725
+ if (fallback)
726
+ return restoreBundled(item, fallback);
727
+ const previousOff = off();
728
+ const stage = home.storage.temporary('plugin-uninstall');
729
+ const files = [dirOf(name), ...(purgeData ? [home.path(pluginSecretsFile(name))] : [])];
730
+ const moved = [];
731
+ let changedOff = false;
732
+ const owned = boundTopic(name);
733
+ const archiveIt = !!owned && owned.archivedAt === null;
734
+ try {
735
+ if (archiveIt)
736
+ runtime.get('topics').archive(owned.id, `plugin:${name}`);
737
+ await runtime.unload(name);
738
+ item.configDisposer?.();
739
+ for (const [i, from] of files.entries()) {
740
+ if (!existsSync(from))
741
+ continue;
742
+ const to = join(stage.path, String(i));
743
+ renameSync(from, to);
744
+ moved.push({ from, to });
745
+ }
746
+ if (previousOff.includes(name)) {
747
+ changedOff = true;
748
+ config().set('settings', 'plugins.disabled', previousOff.filter((id) => id !== name));
749
+ }
750
+ saveIndex(recordList().filter((record) => record.id !== name));
751
+ registered.delete(name);
752
+ }
753
+ catch (error) {
754
+ if (archiveIt && owned) {
755
+ try {
756
+ runtime.get('topics').unarchive(owned.id, `plugin:${name}`);
757
+ }
758
+ catch (rollbackError) {
759
+ log('host', `插件 ${name} 的主题归档回滚失败`, rollbackError);
760
+ }
761
+ }
762
+ for (const { from, to } of moved.reverse())
763
+ renameSync(to, from);
764
+ if (changedOff)
765
+ config().set('settings', 'plugins.disabled', previousOff);
766
+ await restoreItem(item);
767
+ throw error;
768
+ }
769
+ finally {
770
+ stage.release();
771
+ }
772
+ runtime.emit('plugin.changed', { name, kind: 'uninstalled' });
773
+ return { name };
774
+ }
775
+ const plugin = {
776
+ name: 'plugins',
777
+ core: true,
778
+ needs: ['entry', 'config'],
779
+ start(ctx) {
780
+ const entry = ctx.get('entry');
781
+ ctx.effect(config().declare({ scope: 'settings', owner: 'core', fields: [
782
+ { key: 'plugins.disabled', kind: 'list', default: [], managedBy: 'host.plugin_switch', description: { default: '被停用的插件。', translations: { zh: '被停用的插件。', en: 'Plugins switched off.' } } },
783
+ { key: 'plugins.registries', kind: 'list', default: ['https://hostlet.dev/plugins.json'],
784
+ label: { default: '插件目录源', translations: { en: 'Plugin catalogs' } },
785
+ description: { default: '能力扩展中浏览的 JSON 目录地址。清空后关闭目录发现。', translations: { en: 'JSON catalog URLs browsed under Extensions. Clear the list to disable discovery.' } } },
786
+ ] }));
787
+ config().setPluginLifecycle({
788
+ isOperationAvailable: (pluginId) => runtime.list().some((plugin) => plugin.name === pluginId && plugin.state === 'started'),
789
+ });
790
+ const pluginName = object({ name: { type: 'string', description: '插件的名字(host.plugins 里列的)' } }, ['name']);
791
+ // A standing or one-time permission for one package: this installation, this action and, to enable, this code.
792
+ const installation = (item) => `${item.record.source.kind}:${item.record.installedAt}:${item.record.updatedAt}`;
793
+ const switchGrant = (name, action) => {
794
+ const item = registered.get(name);
795
+ if (!item)
796
+ return undefined;
797
+ // Enabling loads code from a directory that can change under the loader: bound to what was shown, but asked every
798
+ // time until the loader can take a checked snapshot of the package.
799
+ if (action === 'enable')
800
+ return { key: [name, installation(item), action, contentDigest(item.dir)].join('|'), label: `启用插件 ${name}(当前安装和代码)`, once: true };
801
+ return { key: [name, installation(item), action].join('|'), label: `停用插件 ${name}(当前安装)` };
802
+ };
803
+ const uninstallGrant = (name, purgeData) => {
804
+ const item = registered.get(name);
805
+ if (!item || item.record.source.kind === 'builtin')
806
+ return undefined;
807
+ if (bundled.has(name))
808
+ return { key: `${name}|${installation(item)}|builtin`, label: `将插件 ${name} 切回随包版` };
809
+ // Removing the secrets as well binds the same installation, but is asked for every time.
810
+ if (purgeData)
811
+ return { key: `${name}|${installation(item)}|purge`, label: `卸载插件 ${name} 并清除密钥`, once: true };
812
+ return { key: `${name}|${installation(item)}`, label: `卸载插件 ${name}(当前安装,不清除密钥)` };
813
+ };
814
+ /** Checked where the change happens, in the queue: what was allowed has to be what is there now. */
815
+ const heldTo = (caller, current) => {
816
+ if (caller.grant !== undefined && (current?.key ?? null) !== caller.grant) {
817
+ throw new HttpError(409, '批准的对象已经变了(插件重装、代码或状态变化),这次没有执行。请重新提请,让机主按现在的对象确认');
818
+ }
819
+ };
820
+ ctx.effect(entry.op({ name: 'host.plugins', about: '列出核心、内置和已安装的外部插件,以及它们的状态、来源、需要和提供的服务。', http: ['GET', '/api/plugins'], agent: true, run: list }));
821
+ ctx.effect(entry.op({
822
+ name: 'host.plugin_catalog', about: '读取配置的插件目录源。各源分别返回包名清单或读取错误。',
823
+ http: ['GET', '/api/plugin-catalog'], run: () => pluginCatalog(config().get('settings', 'plugins.registries')),
824
+ }));
825
+ ctx.effect(entry.op({
826
+ name: 'host.plugin_detail', about: '查看插件详情及声明的版本、来源、状态与错误。',
827
+ input: pluginName, http: ['GET', '/api/plugins/:name'], agent: true,
828
+ run: ({ name }) => detail(name),
829
+ }));
830
+ ctx.effect(entry.op({
831
+ name: 'host.plugin_reload', about: '重新读取在运行的插件代码并重启该插件,给出它现在的状态。此操作适用于内置和外部插件。',
832
+ input: pluginName,
833
+ http: ['POST', '/api/plugins/:name/reload'], agent: true,
834
+ run: ({ name }) => changePlugin(() => reload(name)),
835
+ }));
836
+ ctx.effect(entry.op({
837
+ name: 'host.plugin_switch', about: '停用或启用一个插件:立刻生效,下次启动也照这样。启用时重新读它自己的代码。核心的停不了。',
838
+ input: object({ name: { type: 'string' }, action: { type: 'string', enum: ['enable', 'disable'] } }, ['name', 'action']),
839
+ http: ['POST', '/api/plugins/:name/switch'], agent: 'approve',
840
+ // The same package doing the same thing; enabling also reads its code again, so the code is part of it.
841
+ grant: ({ name, action }) => switchGrant(name, action),
842
+ grantKey: /^[^|]+\|[\w-]+:\d+:\d+\|disable$/,
843
+ approval: ({ name, action }) => ({
844
+ title: action === 'disable' ? '停用插件' : '启用插件', target: name,
845
+ impact: '立即生效,宿主下次启动时沿用',
846
+ ...(action === 'disable' ? { risk: '插件提供的能力将撤下,依赖这些能力的插件可能停止' } : {}),
847
+ }),
848
+ run: ({ name, action }, caller) => changePlugin(() => {
849
+ heldTo(caller, switchGrant(name, action));
850
+ return switchPlugin(name, action);
851
+ }),
852
+ }));
853
+ ctx.effect(entry.op({
854
+ name: 'host.plugin_install', about: '按 npm 包名、本地目录或本机离线包安装插件。传 replace: true 可覆盖,保留现有配置和密钥。',
855
+ input: object({ source: object({
856
+ kind: { type: 'string', enum: ['local-directory', 'local-archive', 'npm'] },
857
+ package: { type: 'string', description: 'kind 为 npm 时提供的 npm 包名' },
858
+ path: { type: 'string', description: '插件源目录或离线包的绝对路径' },
859
+ }, ['kind']), replace: booleanValue }, ['source']),
860
+ http: ['POST', '/api/plugins/install'], agent: 'approve',
861
+ approval: ({ source, replace }) => ({
862
+ title: replace ? '覆盖安装插件' : '安装插件',
863
+ target: source.kind === 'npm' ? `${source.package ?? ''}@latest` : source.path ?? '',
864
+ impact: source.kind === 'npm' ? '从本机 npm Registry 下载并校验 SHA-512,保留配置和密钥' :
865
+ source.kind === 'local-archive' ? '将离线包解到宿主的插件目录,按插件的启用状态加载' : '将本地代码复制到宿主的插件目录,按插件的启用状态加载',
866
+ ...(replace ? { risk: '已有同名插件时会替换其代码,保留现有配置和密钥' } : {}),
867
+ }),
868
+ run: ({ source, replace = false }) => changePlugin(() => {
869
+ if (source.kind === 'npm')
870
+ return installNpm(source.package ?? '', replace);
871
+ return source.kind === 'local-archive' ? installArchiveFile(source.path ?? '', replace) : installDirectory(source.path ?? '', replace);
872
+ }),
873
+ }));
874
+ ctx.effect(entry.route('POST', '/api/plugins/install/archive', ({ query, body }) => {
875
+ const filename = query.get('filename'), replace = query.get('replace');
876
+ if (!Buffer.isBuffer(body))
877
+ throw new HttpError(400, '插件离线包要原样传(application/octet-stream)');
878
+ if (!filename || !/^[^/\\]+\.(?:tgz|tar\.gz)$/i.test(filename))
879
+ throw new HttpError(400, '请选择 .tgz 或 .tar.gz 插件离线包');
880
+ if (replace !== null && replace !== '1')
881
+ throw new HttpError(400, '覆盖安装请传 replace=1');
882
+ return changePlugin(() => installArchive(filename, body, replace === '1'));
883
+ }, { maxBody: PLUGIN_ARCHIVE_LIMIT }));
884
+ ctx.effect(entry.op({
885
+ name: 'host.plugin_check_update', about: '用本机 npm Registry 检查已安装插件的可用版本和 SHA-512 完整性记录。',
886
+ input: pluginName, http: ['GET', '/api/plugins/:name/update'], agent: true, run: ({ name }) => checkUpdate(name),
887
+ }));
888
+ ctx.effect(entry.op({
889
+ name: 'host.plugin_update', about: '从登记的本地目录更新插件,或按检查结果指定 version 和 integrity 升级 npm 插件。保留配置与密钥。',
890
+ input: object({ name: stringValue, version: stringValue, integrity: stringValue }, ['name']),
891
+ http: ['POST', '/api/plugins/:name/update'], agent: 'approve',
892
+ approval: ({ name, version }) => registered.get(name)?.record.source.kind === 'npm' ? {
893
+ title: '升级 npm 插件', target: `${name} → ${version ?? ''}`, impact: '按指定版本校验 SHA-512 并热重载,保留配置和密钥',
894
+ } : {
895
+ title: '更新插件', target: name, impact: '重新同步原本地目录的代码,保留配置和密钥',
896
+ },
897
+ run: ({ name, version, integrity }) => changePlugin(() => update(name, version, integrity)),
898
+ }));
899
+ ctx.effect(entry.op({
900
+ name: 'host.plugin_uninstall', about: '卸载外部插件,或将覆盖过的内置插件切回随包版。卸载时 purgeData: true 会同时清除密钥,切回时保留配置与密钥。',
901
+ input: object({ name: stringValue, purgeData: booleanValue }, ['name']),
902
+ http: ['DELETE', '/api/plugins/:name'], agent: 'approve',
903
+ // An ordinary uninstall of this installation. Removing the secrets as well is asked every time.
904
+ grant: ({ name, purgeData }) => uninstallGrant(name, purgeData),
905
+ grantKey: /^[^|]+\|[\w-]+:\d+:\d+(?:\|builtin)?$/,
906
+ approval: ({ name, purgeData }) => bundled.has(name) ? {
907
+ title: '切回随包版', target: name, impact: '移除覆盖代码并加载随包版本,保留配置、密钥和主题',
908
+ } : ({
909
+ title: '卸载外部插件', target: name,
910
+ impact: '卸载插件并删除安装目录和配置',
911
+ ...(purgeData ? { risk: '同时清除该插件的密钥,重新安装后需要重新填写' } : {}),
912
+ }),
913
+ run: ({ name, purgeData = false }, caller) => changePlugin(() => {
914
+ heldTo(caller, uninstallGrant(name, purgeData));
915
+ return uninstall(name, purgeData);
916
+ }),
917
+ }));
918
+ },
919
+ };
920
+ return { plugin, load };
921
+ }