@acryldev/plugin-context 0.0.0-stage → 0.1.0

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 (284) hide show
  1. package/LICENSE +21 -0
  2. package/docs/README.md +160 -0
  3. package/docs/delivery/local-live.md +113 -0
  4. package/docs/delivery/marketplace.md +16 -0
  5. package/docs/docs.json +2836 -0
  6. package/docs/extending/agent-preset.md +37 -0
  7. package/docs/extending/chat-command.md +28 -0
  8. package/docs/extending/client-slot.md +135 -0
  9. package/docs/extending/config-schema.md +7 -0
  10. package/docs/extending/cordis-core.md +63 -0
  11. package/docs/extending/desktop-app.md +53 -0
  12. package/docs/extending/desktop-main.md +25 -0
  13. package/docs/extending/event-hook.md +14 -0
  14. package/docs/extending/host-route.md +33 -0
  15. package/docs/extending/llm-adapter.md +38 -0
  16. package/docs/extending/packaging.md +53 -0
  17. package/docs/extending/prompt-contribution.md +9 -0
  18. package/docs/extending/service.md +13 -0
  19. package/docs/extending/skill-provider.md +9 -0
  20. package/docs/extending/state-and-persistence.md +71 -0
  21. package/docs/extending/three-role-capability.md +33 -0
  22. package/docs/extending/tool-plugin.md +24 -0
  23. package/docs/extending/tui-command.md +8 -0
  24. package/docs/extending/tui-components.md +61 -0
  25. package/docs/extending/ui-branding.md +43 -0
  26. package/docs/extending/ui-components.md +56 -0
  27. package/docs/extending/ui-customization.md +41 -0
  28. package/docs/extending/ui-library.md +66 -0
  29. package/docs/extending/ui-theme.md +55 -0
  30. package/docs/extending/workspace-tab.md +50 -0
  31. package/docs/maps/events.md +108 -0
  32. package/docs/maps/mount-points.md +154 -0
  33. package/docs/maps/slot-contracts.md +3376 -0
  34. package/docs/maps/taxonomy.md +306 -0
  35. package/docs/maps/theme-tokens.md +115 -0
  36. package/docs/maps/ui-components.md +26 -0
  37. package/docs/reference/cookbook/adding-a-package.md +174 -0
  38. package/docs/reference/cookbook/adding-a-remote-api.md +199 -0
  39. package/docs/reference/cookbook/adding-a-settings-card.md +74 -0
  40. package/docs/reference/cookbook/adding-a-tool.md +103 -0
  41. package/docs/reference/cookbook/adding-an-llm-adapter.md +45 -0
  42. package/docs/reference/cookbook/extension-cookbook.md +134 -0
  43. package/docs/reference/cordis-api/context.md +366 -0
  44. package/docs/reference/cordis-api/events.md +209 -0
  45. package/docs/reference/cordis-api/fiber.md +377 -0
  46. package/docs/reference/cordis-api/inherited.md +40 -0
  47. package/docs/reference/cordis-api/registry.md +154 -0
  48. package/docs/reference/cordis-api/service.md +104 -0
  49. package/docs/reference/cordis-guides/cordis-usage-cheatsheet.md +167 -0
  50. package/docs/reference/cordis-guides/cordis_system_guide_for_coding_agents.md +4666 -0
  51. package/docs/reference/cordis-guides/development-canvas-plugin.md +109 -0
  52. package/docs/reference/cordis-guides/hello-world-plugin-guide.md +517 -0
  53. package/docs/reference/harness/agent-lifecycle.md +93 -0
  54. package/docs/reference/harness/architecture.md +168 -0
  55. package/docs/reference/harness/capability-seams.md +675 -0
  56. package/docs/reference/harness/config-catalog.md +4523 -0
  57. package/docs/reference/harness/cordis-primer.md +47 -0
  58. package/docs/reference/harness/defensive-patterns.md +35 -0
  59. package/docs/reference/harness/event-producer-consumer.md +111 -0
  60. package/docs/reference/harness/glossary.md +47 -0
  61. package/docs/reference/harness/tool-catalog.md +2721 -0
  62. package/docs/reference/harness/tool-execution-pipeline.md +67 -0
  63. package/docs/reference/subsystems/README.md +75 -0
  64. package/docs/reference/subsystems/agent-team.md +233 -0
  65. package/docs/reference/subsystems/approval.md +172 -0
  66. package/docs/reference/subsystems/attachment.md +363 -0
  67. package/docs/reference/subsystems/boot.md +324 -0
  68. package/docs/reference/subsystems/browser-use.md +69 -0
  69. package/docs/reference/subsystems/client-modules.md +186 -0
  70. package/docs/reference/subsystems/client-resources.md +94 -0
  71. package/docs/reference/subsystems/commands.md +225 -0
  72. package/docs/reference/subsystems/compaction.md +286 -0
  73. package/docs/reference/subsystems/computer-use.md +58 -0
  74. package/docs/reference/subsystems/conversation.md +287 -0
  75. package/docs/reference/subsystems/core.md +1107 -0
  76. package/docs/reference/subsystems/credentials.md +497 -0
  77. package/docs/reference/subsystems/deliverables.md +180 -0
  78. package/docs/reference/subsystems/extensions.md +386 -0
  79. package/docs/reference/subsystems/feedback.md +402 -0
  80. package/docs/reference/subsystems/filesystem.md +532 -0
  81. package/docs/reference/subsystems/goal.md +315 -0
  82. package/docs/reference/subsystems/invariants.md +90 -0
  83. package/docs/reference/subsystems/jobs.md +501 -0
  84. package/docs/reference/subsystems/llm-streaming.md +1131 -0
  85. package/docs/reference/subsystems/lsp.md +204 -0
  86. package/docs/reference/subsystems/mcp.md +141 -0
  87. package/docs/reference/subsystems/office-to-pdf.md +89 -0
  88. package/docs/reference/subsystems/otel.md +46 -0
  89. package/docs/reference/subsystems/permission-presets.md +169 -0
  90. package/docs/reference/subsystems/persistence.md +418 -0
  91. package/docs/reference/subsystems/plan.md +89 -0
  92. package/docs/reference/subsystems/product-telemetry.md +81 -0
  93. package/docs/reference/subsystems/ptc-runtime.md +234 -0
  94. package/docs/reference/subsystems/sandbox.md +223 -0
  95. package/docs/reference/subsystems/schedule.md +545 -0
  96. package/docs/reference/subsystems/scope.md +61 -0
  97. package/docs/reference/subsystems/session-projection.md +358 -0
  98. package/docs/reference/subsystems/session-query.md +511 -0
  99. package/docs/reference/subsystems/session-reference.md +226 -0
  100. package/docs/reference/subsystems/session-telemetry.md +214 -0
  101. package/docs/reference/subsystems/session-title.md +206 -0
  102. package/docs/reference/subsystems/session.md +1300 -0
  103. package/docs/reference/subsystems/settings.md +157 -0
  104. package/docs/reference/subsystems/shell.md +316 -0
  105. package/docs/reference/subsystems/sidebar-right.md +160 -0
  106. package/docs/reference/subsystems/skills.md +354 -0
  107. package/docs/reference/subsystems/slots.md +201 -0
  108. package/docs/reference/subsystems/spill.md +126 -0
  109. package/docs/reference/subsystems/ssh.md +137 -0
  110. package/docs/reference/subsystems/storage.md +262 -0
  111. package/docs/reference/subsystems/subagent.md +762 -0
  112. package/docs/reference/subsystems/subprocess.md +323 -0
  113. package/docs/reference/subsystems/system-prompt.md +226 -0
  114. package/docs/reference/subsystems/terminal.md +186 -0
  115. package/docs/reference/subsystems/todo.md +34 -0
  116. package/docs/reference/subsystems/token-meter.md +108 -0
  117. package/docs/reference/subsystems/tools.md +749 -0
  118. package/docs/reference/subsystems/typert.md +489 -0
  119. package/docs/reference/subsystems/user-questions.md +309 -0
  120. package/docs/reference/subsystems/voice-input.md +166 -0
  121. package/docs/reference/subsystems/web-client.md +102 -0
  122. package/docs/reference/subsystems/web-server.md +228 -0
  123. package/docs/reference/subsystems/web.md +208 -0
  124. package/docs/reference/subsystems/webhook.md +72 -0
  125. package/docs/reference/subsystems/workflow.md +280 -0
  126. package/docs/reference/subsystems/workspace.md +661 -0
  127. package/docs/start-here/blueprints.md +33 -0
  128. package/docs/start-here/this-runtime.md +84 -0
  129. package/docs/start-here/troubleshooting.md +29 -0
  130. package/docs/start-here/trust-and-safety.md +39 -0
  131. package/docs/start-here/verify-before-done.md +46 -0
  132. package/example-plugins/README.md +45 -0
  133. package/example-plugins/packages/agent-preset-reviewer/agent.cordis.yml +18 -0
  134. package/example-plugins/packages/agent-preset-reviewer/preset.yml +3 -0
  135. package/example-plugins/packages/capability-swap-consumer/cordis.patch.yml +3 -0
  136. package/example-plugins/packages/capability-swap-consumer/index.js +14 -0
  137. package/example-plugins/packages/capability-swap-consumer/package.json +25 -0
  138. package/example-plugins/packages/capability-swap-provider-loud/cordis.patch.yml +3 -0
  139. package/example-plugins/packages/capability-swap-provider-loud/index.js +20 -0
  140. package/example-plugins/packages/capability-swap-provider-loud/package.json +25 -0
  141. package/example-plugins/packages/capability-swap-provider-quiet/cordis.patch.yml +3 -0
  142. package/example-plugins/packages/capability-swap-provider-quiet/index.js +20 -0
  143. package/example-plugins/packages/capability-swap-provider-quiet/package.json +25 -0
  144. package/example-plugins/packages/chat-command-basic/cordis.patch.yml +3 -0
  145. package/example-plugins/packages/chat-command-basic/index.js +26 -0
  146. package/example-plugins/packages/chat-command-basic/package.json +25 -0
  147. package/example-plugins/packages/client-chat-message-action/client.js +46 -0
  148. package/example-plugins/packages/client-chat-message-action/cordis.patch.yml +3 -0
  149. package/example-plugins/packages/client-chat-message-action/index.js +9 -0
  150. package/example-plugins/packages/client-chat-message-action/package.json +31 -0
  151. package/example-plugins/packages/client-slot-header-action/client.js +57 -0
  152. package/example-plugins/packages/client-slot-header-action/cordis.patch.yml +3 -0
  153. package/example-plugins/packages/client-slot-header-action/index.js +13 -0
  154. package/example-plugins/packages/client-slot-header-action/package.json +31 -0
  155. package/example-plugins/packages/client-slot-sidebar-tab/client.js +57 -0
  156. package/example-plugins/packages/client-slot-sidebar-tab/cordis.patch.yml +3 -0
  157. package/example-plugins/packages/client-slot-sidebar-tab/index.js +9 -0
  158. package/example-plugins/packages/client-slot-sidebar-tab/package.json +32 -0
  159. package/example-plugins/packages/client-theme-override/client.js +52 -0
  160. package/example-plugins/packages/client-theme-override/cordis.patch.yml +3 -0
  161. package/example-plugins/packages/client-theme-override/index.js +9 -0
  162. package/example-plugins/packages/client-theme-override/package.json +30 -0
  163. package/example-plugins/packages/client-tool-view/client.js +47 -0
  164. package/example-plugins/packages/client-tool-view/cordis.patch.yml +3 -0
  165. package/example-plugins/packages/client-tool-view/index.js +24 -0
  166. package/example-plugins/packages/client-tool-view/package.json +34 -0
  167. package/example-plugins/packages/client-ui-components/client.js +77 -0
  168. package/example-plugins/packages/client-ui-components/cordis.patch.yml +3 -0
  169. package/example-plugins/packages/client-ui-components/index.js +9 -0
  170. package/example-plugins/packages/client-ui-components/package.json +31 -0
  171. package/example-plugins/packages/client-ui-library/client.js +715 -0
  172. package/example-plugins/packages/client-ui-library/cordis.patch.yml +3 -0
  173. package/example-plugins/packages/client-ui-library/index.js +9 -0
  174. package/example-plugins/packages/client-ui-library/package.json +37 -0
  175. package/example-plugins/packages/client-workspace-tab/client.js +72 -0
  176. package/example-plugins/packages/client-workspace-tab/cordis.patch.yml +3 -0
  177. package/example-plugins/packages/client-workspace-tab/index.js +9 -0
  178. package/example-plugins/packages/client-workspace-tab/package.json +30 -0
  179. package/example-plugins/packages/config-schema-basic/cordis.patch.yml +3 -0
  180. package/example-plugins/packages/config-schema-basic/index.js +19 -0
  181. package/example-plugins/packages/config-schema-basic/package.json +25 -0
  182. package/example-plugins/packages/desktop-main-profile-info/cordis.patch.yml +3 -0
  183. package/example-plugins/packages/desktop-main-profile-info/index.js +22 -0
  184. package/example-plugins/packages/desktop-main-profile-info/package.json +25 -0
  185. package/example-plugins/packages/event-hook-basic/cordis.patch.yml +3 -0
  186. package/example-plugins/packages/event-hook-basic/index.js +17 -0
  187. package/example-plugins/packages/event-hook-basic/package.json +22 -0
  188. package/example-plugins/packages/generated-capability-template/cordis.patch.yml +3 -0
  189. package/example-plugins/packages/generated-capability-template/index.js +16 -0
  190. package/example-plugins/packages/generated-capability-template/package.json +42 -0
  191. package/example-plugins/packages/host-route-basic/cordis.patch.yml +3 -0
  192. package/example-plugins/packages/host-route-basic/index.js +20 -0
  193. package/example-plugins/packages/host-route-basic/package.json +29 -0
  194. package/example-plugins/packages/lifecycle-function-basic/cordis.patch.yml +3 -0
  195. package/example-plugins/packages/lifecycle-function-basic/index.js +12 -0
  196. package/example-plugins/packages/lifecycle-function-basic/package.json +15 -0
  197. package/example-plugins/packages/lifecycle-function-hot-shim/cordis.patch.yml +3 -0
  198. package/example-plugins/packages/lifecycle-function-hot-shim/impl.js +5 -0
  199. package/example-plugins/packages/lifecycle-function-hot-shim/index.js +18 -0
  200. package/example-plugins/packages/lifecycle-function-hot-shim/package.json +23 -0
  201. package/example-plugins/packages/lifecycle-hooks-observer/cordis.patch.yml +3 -0
  202. package/example-plugins/packages/lifecycle-hooks-observer/index.js +23 -0
  203. package/example-plugins/packages/lifecycle-hooks-observer/package.json +22 -0
  204. package/example-plugins/packages/llm-adapter-echo/cordis.patch.yml +3 -0
  205. package/example-plugins/packages/llm-adapter-echo/index.js +42 -0
  206. package/example-plugins/packages/llm-adapter-echo/package.json +25 -0
  207. package/example-plugins/packages/prompt-assemble-hook/cordis.patch.yml +3 -0
  208. package/example-plugins/packages/prompt-assemble-hook/index.js +22 -0
  209. package/example-plugins/packages/prompt-assemble-hook/package.json +22 -0
  210. package/example-plugins/packages/prompt-contribution-basic/cordis.patch.yml +3 -0
  211. package/example-plugins/packages/prompt-contribution-basic/index.js +18 -0
  212. package/example-plugins/packages/prompt-contribution-basic/package.json +22 -0
  213. package/example-plugins/packages/service-consumer-greeter/cordis.patch.yml +3 -0
  214. package/example-plugins/packages/service-consumer-greeter/index.js +14 -0
  215. package/example-plugins/packages/service-consumer-greeter/package.json +22 -0
  216. package/example-plugins/packages/service-provider-greeter/cordis.patch.yml +3 -0
  217. package/example-plugins/packages/service-provider-greeter/index.js +22 -0
  218. package/example-plugins/packages/service-provider-greeter/package.json +25 -0
  219. package/example-plugins/packages/settings-section-basic/cordis.patch.yml +3 -0
  220. package/example-plugins/packages/settings-section-basic/index.js +34 -0
  221. package/example-plugins/packages/settings-section-basic/package.json +26 -0
  222. package/example-plugins/packages/skill-provider-basic/cordis.patch.yml +3 -0
  223. package/example-plugins/packages/skill-provider-basic/index.js +31 -0
  224. package/example-plugins/packages/skill-provider-basic/package.json +22 -0
  225. package/example-plugins/packages/state-host-store/client.js +57 -0
  226. package/example-plugins/packages/state-host-store/cordis.patch.yml +3 -0
  227. package/example-plugins/packages/state-host-store/index.js +90 -0
  228. package/example-plugins/packages/state-host-store/package.json +31 -0
  229. package/example-plugins/packages/state-workspace-file/cordis.patch.yml +3 -0
  230. package/example-plugins/packages/state-workspace-file/index.js +52 -0
  231. package/example-plugins/packages/state-workspace-file/package.json +25 -0
  232. package/example-plugins/packages/tool-basic/cordis.patch.yml +3 -0
  233. package/example-plugins/packages/tool-basic/index.js +25 -0
  234. package/example-plugins/packages/tool-basic/package.json +25 -0
  235. package/example-plugins/packages/tool-policy-hook/cordis.patch.yml +3 -0
  236. package/example-plugins/packages/tool-policy-hook/index.js +28 -0
  237. package/example-plugins/packages/tool-policy-hook/package.json +25 -0
  238. package/example-plugins/packages/tui-command-basic/cordis.patch.yml +3 -0
  239. package/example-plugins/packages/tui-command-basic/index.js +24 -0
  240. package/example-plugins/packages/tui-command-basic/package.json +22 -0
  241. package/example-plugins/packages/tui-overlay-themed/cordis.patch.yml +3 -0
  242. package/example-plugins/packages/tui-overlay-themed/index.js +65 -0
  243. package/example-plugins/packages/tui-overlay-themed/package.json +25 -0
  244. package/example-plugins/packages/tui-ui-library/cordis.patch.yml +3 -0
  245. package/example-plugins/packages/tui-ui-library/index.js +73 -0
  246. package/example-plugins/packages/tui-ui-library/package.json +29 -0
  247. package/example-plugins/packages/web-page-branding/cordis.patch.yml +3 -0
  248. package/example-plugins/packages/web-page-branding/index.js +31 -0
  249. package/example-plugins/packages/web-page-branding/package.json +22 -0
  250. package/example-plugins/scenarios.json +11 -0
  251. package/index.js +384 -0
  252. package/lib/blend-apply.js +107 -0
  253. package/lib/blend-capture.js +249 -0
  254. package/lib/blend-ledger.js +76 -0
  255. package/lib/contract.js +5 -0
  256. package/lib/install.js +516 -0
  257. package/lib/lookup.js +67 -0
  258. package/lib/manifest.js +56 -0
  259. package/lib/pack-root.js +22 -0
  260. package/lib/provenance.js +110 -0
  261. package/lib/publish.js +64 -0
  262. package/lib/reconcile.js +83 -0
  263. package/lib/router.js +55 -0
  264. package/lib/scopes.js +82 -0
  265. package/lib/skills.js +54 -0
  266. package/lib/stage.js +157 -0
  267. package/lib/verify.js +77 -0
  268. package/package.json +56 -3
  269. package/scripts/lib/indexes.mjs +45 -0
  270. package/scripts/lib/manifest.mjs +127 -0
  271. package/scripts/lib/maps.mjs +482 -0
  272. package/skills/acryl-add-provider-or-capability/SKILL.md +12 -0
  273. package/skills/acryl-add-ui/SKILL.md +18 -0
  274. package/skills/acryl-build-plugin/SKILL.md +21 -0
  275. package/skills/acryl-change-plugin/SKILL.md +16 -0
  276. package/skills/acryl-desktop-shell/SKILL.md +12 -0
  277. package/skills/acryl-diagnose-plugin/SKILL.md +10 -0
  278. package/skills/acryl-fix-plugin/SKILL.md +12 -0
  279. package/skills/acryl-improve-ui/SKILL.md +10 -0
  280. package/skills/acryl-remove-plugin/SKILL.md +11 -0
  281. package/skills/acryl-restyle-ui/SKILL.md +14 -0
  282. package/skills/acryl-share-plugin/SKILL.md +23 -0
  283. package/skills/acryl-tui-ui/SKILL.md +12 -0
  284. package/README.md +0 -3
package/index.js ADDED
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Extension Context Pack runtime plugin (spec 037). Routes the agent to the
3
+ * pack's docs and verified examples, the way pi.dev's system prompt routes its
4
+ * agent to its own docs, and gives it the one tool it needs to close the loop:
5
+ * install a plugin it wrote and make it live.
6
+ *
7
+ * Provides: `pluginContext`, the prompt section `acryl:plugin-router`, bundled
8
+ * authoring skills (when a `skills` service exists) and the tool `acryl_install_plugin`
9
+ * (when a `tools` service exists).
10
+ * Requires: `systemPrompt`. `tools`, `desktopPnpm` and `livePluginActivation` are
11
+ * optional and read at call time, never captured (the documented ordering trap).
12
+ */
13
+ import { existsSync, readFileSync } from 'node:fs'
14
+ import { isAbsolute, join } from 'node:path'
15
+ import { defineTool } from '@deepseek-ai/dsh-tools'
16
+ import { Acryl } from '@acryldev/blends'
17
+ import { globalPluginsDir } from './lib/reconcile.js'
18
+ import { listInstalledPlugins } from './lib/provenance.js'
19
+ import { captureApp, captureBlend, verifyBlend, writeAppBlend, writeBlend } from './lib/blend-capture.js'
20
+ import { applyBlend } from './lib/blend-apply.js'
21
+ import { appHomeDir, blendDir, useAppInstance } from './lib/scopes.js'
22
+ import { appendLedger, ledgerRecorder, readLedger, trackedBlendDir, verifyLedger } from './lib/blend-ledger.js'
23
+ import { describePermissions } from './lib/manifest.js'
24
+ import { describeInstalledExtensions, installLocalPlugin, syncOnStartup, listLocalPlugins, reloadLocalPlugins, removeLocalPlugin } from './lib/install.js'
25
+ import { lookupExtensionDocs } from './lib/lookup.js'
26
+ import { verifyPackage } from './lib/verify.js'
27
+ import { preparePublish } from './lib/publish.js'
28
+ import { resolvePackRoot } from './lib/pack-root.js'
29
+ import { createSkillProvider } from './lib/skills.js'
30
+ import { buildRouterText, INSTALL_TOOL_NAME, LIST_TOOL_NAME, REMOVE_TOOL_NAME, PUBLISH_TOOL_NAME, VERIFY_TOOL_NAME, LOOKUP_TOOL_NAME, ROUTER_SECTION_NAME, ROUTER_SECTION_ORDER } from './lib/router.js'
31
+
32
+ export const name = 'acryl-plugin-context'
33
+ export const inject = ['systemPrompt']
34
+
35
+ /** The prefix this plugin mounts on the framework's router. */
36
+ export const PLUGIN_CONTEXT_API_PREFIX = '/api/acryl-plugin-context'
37
+ /** Answers once the startup pass has settled; a Web page rendered before then waits on it and reloads. */
38
+ export const STARTUP_PATH = `${PLUGIN_CONTEXT_API_PREFIX}/startup-settled`
39
+ /** Longest hold, as Desktop's (APP_PLUGINS_SETTLE_LIMIT_MS): a slow install still lets the page boot, as it did before the hold existed. */
40
+ export const STARTUP_HOLD_LIMIT_MS = 60_000
41
+
42
+ /**
43
+ * The head script for an index rendered before the startup pass settled. It installs the boot-readiness deferred the client awaits, with a
44
+ * `resolve` that does nothing (the served tail script calls it once every row is in the document), then reloads when STARTUP_PATH answers
45
+ * 204 and boots as served on any other answer or a network error, so a failed hold never leaves a blank page.
46
+ * @param path - the startup-settled route.
47
+ * @returns the script text.
48
+ */
49
+ export function startupHoldScript(path) {
50
+ return `(()=>{const gate=Promise.withResolvers();globalThis.__DSH_BOOT_READY__={promise:gate.promise,resolve(){},reject:gate.reject};`
51
+ + `fetch(${JSON.stringify(path)},{cache:'no-store',credentials:'same-origin'}).then(r=>{if(r.status===204)location.reload();else gate.resolve()},()=>gate.resolve())})()`
52
+ }
53
+
54
+ /**
55
+ * The startup-settled route as one app. The same admission as the Host API (origin and browser cookie), when this host has a connection;
56
+ * then it holds until the startup pass settles (204: reload), the hold limit passes (503: boot with the graph as served), or the page
57
+ * leaves (the request's signal, which the router fires when the client closes).
58
+ * @param settled - the startup pass's promise.
59
+ * @param ctx - the scope that owns the route, read for `connection` at request time.
60
+ * @returns the app to route.
61
+ */
62
+ export function startupRoutes(settled, ctx) {
63
+ const app = new Acryl()
64
+ app.get(STARTUP_PATH, async c => {
65
+ const admission = ctx.get('connection')?.admit({ headers: c.req.raw.headers })
66
+ if (admission !== undefined && 'rejection' in admission) return c.body(null, admission.rejection)
67
+ const signal = c.req.raw.signal
68
+ let timer
69
+ let onAbort
70
+ const limit = new Promise(resolve => { timer = setTimeout(() => resolve('timed-out'), STARTUP_HOLD_LIMIT_MS) })
71
+ const closed = new Promise(resolve => { onAbort = () => resolve('closed'); signal.addEventListener('abort', onAbort, { once: true }) })
72
+ const outcome = await Promise.race([settled.then(() => 'settled'), limit, closed]).finally(() => {
73
+ clearTimeout(timer)
74
+ signal.removeEventListener('abort', onAbort)
75
+ })
76
+ // 204: the pass settled, reload. 503: it did not settle in time (or cannot run on this host), boot with the graph as served. A page that
77
+ // left is answered too, though nobody reads it.
78
+ return c.body(null, outcome === 'settled' ? 204 : 503, { 'cache-control': 'no-store' })
79
+ })
80
+ return app
81
+ }
82
+
83
+ export function apply(ctx) {
84
+ const root = resolvePackRoot()
85
+ const manifest = JSON.parse(readFileSync(join(root, 'docs', 'docs.json'), 'utf8'))
86
+
87
+ // Evaluation switch (evals/README.md): ACRYL_PLUGIN_DOCS=off removes the router, the skills and the installed-plugins note, leaving only the tools,
88
+ // so the same task can be run with and without the docs to measure what they add. Never set it in normal use.
89
+ const docsOff = process.env.ACRYL_PLUGIN_DOCS === 'off'
90
+
91
+ // Where this app keeps what its builder writes, from the runtime's app instance (optional: a stock harness host has none and keeps the classic folders).
92
+ ctx.effect(() => useAppInstance(ctx.get('appInstance')), 'plugin-context: app instance scopes')
93
+
94
+ // Static for the process lifetime: part of the cacheable prompt prefix.
95
+ const text = buildRouterText(root, manifest)
96
+ if (!docsOff) ctx.effect(() => ctx.systemPrompt.section({ name: ROUTER_SECTION_NAME, order: ROUTER_SECTION_ORDER, text }))
97
+
98
+ // Settles when the startup pass below has finished (or cannot run): a surface waits on it before it serves its client, because the client
99
+ // composes once from the plugin list it loads and an app plugin installed after that leaves the page without it (no `layout` on Desktop).
100
+ // It resolves with what the pass did, `{ status: 'done' | 'skipped' | 'failed' | 'disposed', lines }` (`lines` are the logged report, a
101
+ // per-plugin failure among them as `FAILED <name>: <error>`), so a waiter sees why an app plugin is missing without reading the log.
102
+ let settleStartup = () => {}
103
+ const startupSettled = new Promise(resolve => { settleStartup = resolve })
104
+ ctx.effect(() => () => settleStartup({ status: 'disposed', lines: [] }), 'plugin-context: settle startup on disposal')
105
+ let startupDone = false
106
+ void startupSettled.then(() => { startupDone = true })
107
+
108
+ // The Web index embeds the client graph composed when it is requested, and the surface prints its URL before the startup pass has
109
+ // installed the app's plugins, so a page opened in between composes without the app's client plugins (reproduced, specs/001 T097).
110
+ // While the pass runs, the index carries one head script that holds the client's boot (`__DSH_BOOT_READY__`, which the client awaits
111
+ // before it reads the graph), asks STARTUP_PATH to answer once the pass settles, and reloads: the reloaded index renders after it. A
112
+ // page rendered after the pass gets no script. Desktop waits before it loads its window, so its page never gets one either.
113
+ // The route is on the framework's router: a Blueprint without the `framework-kit` row serves no route, so its page gets no script either
114
+ // (it composes as it did before the hold existed) rather than one that asks a route that is not there.
115
+ ctx.inject(['webServer', 'router', 'routerHttp'], scoped => {
116
+ scoped.on('webserver/index-inject', table => {
117
+ if (!startupDone) table.push({ kind: 'script', placement: 'head', text: startupHoldScript(STARTUP_PATH) })
118
+ })
119
+ scoped.router.route('/', startupRoutes(startupSettled, scoped))
120
+ scoped.routerHttp.mount(PLUGIN_CONTEXT_API_PREFIX)
121
+ })
122
+
123
+ ctx.provide('pluginContext', {
124
+ root,
125
+ startupSettled,
126
+ manifest: () => manifest,
127
+ resolveDoc(id) {
128
+ for (const group of manifest.navigation) for (const item of group.items) if (item.id === id) return join(root, 'docs', item.path)
129
+ return undefined
130
+ },
131
+ })
132
+
133
+ // Bundled authoring skills (workflow triggers linking into the docs). Optional: without a
134
+ // `skills` service the router alone still works.
135
+ ctx.inject(['skills'], scoped => {
136
+ if (!docsOff) scoped.skills.registerProvider(() => createSkillProvider(root))
137
+ })
138
+
139
+ // The live view of installed extensions (pi.dev rebuilds its prompt after a reload): a per-assembly dynamic context, empty when none.
140
+ ctx.inject(['systemPrompt'], scoped => {
141
+ if (docsOff) return
142
+ ctx.effect(() => scoped.systemPrompt.context({
143
+ name: 'acryl:installed-plugins',
144
+ order: 9500,
145
+ text: () => describeInstalledExtensions(ctx.get('desktopProfiles')?.current?.dir, ctx.get('livePluginActivation')),
146
+ }), 'plugin-context: installed plugins context')
147
+ })
148
+
149
+ // Startup pass (pi.dev re-discovers extensions on every start): re-sync changed GLOBAL extensions, report everything else. Deferred one tick so it
150
+ // never runs inside the engine's own boot, and it never throws into the host. See syncOnStartup for why project scope is only reported.
151
+ ctx.inject(['desktopProfiles', 'desktopPnpm', 'livePluginActivation'], scoped => {
152
+ scoped.effect(() => {
153
+ let disposed = false
154
+ const timer = setTimeout(async () => {
155
+ if (disposed) return
156
+ let report = { status: 'failed', lines: [] }
157
+ try {
158
+ const profileDir = scoped.get('desktopProfiles')?.current?.dir
159
+ if (!profileDir) { report = { status: 'skipped', lines: ['no current profile'] }; return }
160
+ const dshHome = scoped.get('dshHomePath')
161
+ const services = { pnpm: scoped.get('desktopPnpm'), live: scoped.get('livePluginActivation'), pluginHub: ctx.get('pluginHub'), profileDir, acrylFrameworkPackages: ctx.get('acrylFrameworkPackages') }
162
+ // An app (`acryl new`) installs its own committed plugins at start: a fresh clone has them in plugins/ but nothing installed yet.
163
+ const app = appHomeDir()
164
+ const summary = await syncOnStartup(services, { globalDir: globalPluginsDir(typeof dshHome === 'function' ? dshHome() : undefined), installPending: app !== undefined })
165
+ // ...and the marketplace plugins its lock names, when the lock still matches the app's definition (a stale lock is reported, never guessed).
166
+ let lockNote = ''
167
+ if (app !== undefined && verifyBlend(app).ok) {
168
+ const applied = await applyBlend(app, services, {})
169
+ const installed = applied.results.filter(r => (r.origin === 'registry' || r.origin === 'pulled') && r.status === 'installed').map(r => r.name)
170
+ const failed = applied.results.filter(r => ['failed', 'conflict'].includes(r.status)).map(r => `${r.name} (${r.detail ?? r.status})`)
171
+ lockNote = [installed.length > 0 ? `installed from the app lock: ${installed.join(', ')}` : '', failed.length > 0 ? `FAILED from the app lock: ${failed.join(', ')}` : ''].filter(Boolean).join('; ')
172
+ } else if (app !== undefined && existsSync(join(app, 'blend.lock.json'))) {
173
+ lockNote = 'the app lock no longer matches blend.yaml (type /blend snapshot to refresh it); marketplace and pulled plugins were not installed from it'
174
+ }
175
+ const parts = [
176
+ summary.installed.length > 0 ? `installed the app's plugins ${summary.installed.join(', ')}` : '',
177
+ lockNote,
178
+ summary.updated.length > 0 ? `re-synced ${summary.updated.join(', ')}` : '',
179
+ summary.changed.length > 0 ? `source changed since install (type /reload to apply): ${summary.changed.join(', ')}` : '',
180
+ summary.stale.length > 0 ? `source folder missing (/reload remove-stale): ${summary.stale.join(', ')}` : '',
181
+ summary.pending.length > 0 ? `new global plugins not installed (/reload new): ${summary.pending.join(', ')}` : '',
182
+ ...summary.retried.map(r => `${r.name} installed on the second attempt (the first failed: ${r.error})`),
183
+ ...summary.failed.map(f => `FAILED ${f.name}: ${f.error}`),
184
+ ].filter(Boolean)
185
+ if (parts.length > 0) ctx.logger.info(`[plugin-context] startup: ${parts.join('; ')}`)
186
+ report = { status: 'done', lines: parts }
187
+ } catch (cause) {
188
+ const message = cause instanceof Error ? cause.message : String(cause)
189
+ ctx.logger.warn(`[plugin-context] startup sync failed: ${message}`)
190
+ report = { status: 'failed', lines: [message] }
191
+ } finally { settleStartup(report) }
192
+ }, 0)
193
+ return () => { disposed = true; clearTimeout(timer) }
194
+ }, 'plugin-context: startup sync')
195
+ })
196
+
197
+ // `/reload`: re-install every local plugin from its source directory, and install new folders under <workspace>/.acryl-plugins/.
198
+ ctx.inject(['commands'], scoped => {
199
+ ctx.effect(function* () {
200
+ yield scoped.commands.register({
201
+ name: 'reload',
202
+ description: 'Reload local plugins from their source folders',
203
+ // Without `input` the client treats the command as argument-less and sends `/reload new` to the model as chat.
204
+ input: { hint: '[new|remove-stale]' },
205
+ async handler(invocation) {
206
+ const profileDir = ctx.get('desktopProfiles')?.current?.dir
207
+ if (!profileDir) return { kind: 'error', text: 'The active profile is not available in this runtime.' }
208
+ // The session's workspace, so plugin folders dropped under <workspace>/.acryl-plugins/ are discovered too.
209
+ const workspaceDir = invocation?.agent?.session?.header?.cwd
210
+ // `/reload new` also installs plugin folders found under .acryl-plugins/ that are not installed yet: they run with the
211
+ // user's permissions, so the human opts in explicitly.
212
+ const words = String(invocation?.rawInput ?? '').trim().split(/\s+/u).filter(Boolean)
213
+ const installDiscovered = words.includes('new')
214
+ // `/reload remove-stale` removes installs whose source folder is gone; without it they are only reported.
215
+ const removeStale = words.includes('remove-stale')
216
+ const dshHome = ctx.get('dshHomePath')
217
+ const globalDir = globalPluginsDir(typeof dshHome === 'function' ? dshHome() : undefined)
218
+ const results = await reloadLocalPlugins({ pnpm: ctx.get('desktopPnpm'), live: ctx.get('livePluginActivation'), profileDir, acrylFrameworkPackages: ctx.get('acrylFrameworkPackages'), record: ledgerRecorder(workspaceDir, 'human') }, undefined, { workspaceDir, globalDir, installDiscovered, removeStale })
219
+ if (results.length === 0) return { kind: 'success', text: 'No local plugins installed or found in <workspace>/.acryl-plugins/ or the global plugins folder.' }
220
+ const tag = r => (r.scope ? ` [${r.scope}]` : '')
221
+ const lines = results.map(r =>
222
+ r.stale && r.removed ? `${r.name}: STALE, source folder missing - removed`
223
+ : r.stale && r.ok ? `${r.name}: STALE - source folder ${r.dir} no longer exists, so it cannot be updated. Type /reload remove-stale to remove it`
224
+ : r.shadowed ? `${r.dir}: SHADOWED by the project plugin "${r.name}" - not loaded`
225
+ : r.pending ? `${r.dir}${tag(r)}: NEW, not installed - ${describePermissions(r.permissions)}. It would run with your permissions: review it, then type /reload new`
226
+ : r.ok ? `${r.name}${tag(r)}: ${r.action}${r.discovered ? ' (new)' : ''}`
227
+ : `${r.name}: FAILED - ${(r.errors ?? []).join('; ')}`)
228
+ const failed = results.some(r => !r.ok)
229
+ // The reload hint only matters when something was (re)installed or removed.
230
+ const touched = results.some(r => r.action !== undefined && r.action !== 'unchanged' || r.removed)
231
+ const text = touched ? `${lines.join('\n')}\nReload the page (Web) or window (Desktop, Cmd/Ctrl+R) to pick up UI changes.` : lines.join('\n')
232
+ return failed ? { kind: 'error', text } : { kind: 'success', text }
233
+ },
234
+ })
235
+ }, 'plugin-context reload command')
236
+ })
237
+
238
+ // `/blend snapshot` writes the running composition (marketplace plugins AND local extensions) to <workspace>/.acryl/blend/ as a Blend; `/blend verify`
239
+ // checks it against its own lock. Human-typed, no model tool: capturing state is the user's decision and costs no prompt tokens.
240
+ ctx.inject(['commands'], scoped => {
241
+ ctx.effect(function* () {
242
+ yield scoped.commands.register({
243
+ name: 'blend',
244
+ description: 'Capture the installed plugins (pulled and local) as a Blend, verify it, or apply a captured one',
245
+ input: { hint: '[snapshot|verify|apply|ledger]' },
246
+ async handler(invocation) {
247
+ const profileDir = ctx.get('desktopProfiles')?.current?.dir
248
+ const workspaceDir = invocation?.agent?.session?.header?.cwd
249
+ if (!profileDir) return { kind: 'error', text: 'The active profile is not available in this runtime.' }
250
+ if (!workspaceDir && appHomeDir() === undefined) return { kind: 'error', text: 'This session has no workspace directory to keep the Blend in.' }
251
+ const outDir = blendDir(workspaceDir)
252
+ const verb = String(invocation?.rawInput ?? '').trim().split(/\s+/u)[0]
253
+ if (verb === 'verify') {
254
+ const result = verifyBlend(outDir)
255
+ const ledger = verifyLedger(outDir)
256
+ const problems = [...result.problems, ...ledger.problems]
257
+ return problems.length === 0 ? { kind: 'success', text: `Blend in ${outDir} matches its lock (${result.checked} checks); ledger: ${ledger.entries} entries, chain intact.` } : { kind: 'error', text: `Blend in ${outDir}:\n${problems.map(p => `- ${p}`).join('\n')}` }
258
+ }
259
+ if (verb === 'ledger') {
260
+ if (trackedBlendDir(workspaceDir) === undefined) return { kind: 'error', text: 'This workspace tracks no Blend yet: type /blend snapshot first. The ledger records changes from then on.' }
261
+ const entries = readLedger(outDir).slice(-20)
262
+ return { kind: 'success', text: entries.length === 0 ? 'The ledger is empty.' : entries.map(e => `${e.at} ${e.actor ?? '?'} ${e.kind}${e.module ? ` ${e.module}` : ''}${e.version ? `@${e.version}` : ''}`).join('\n') }
263
+ }
264
+ if (verb === 'apply') {
265
+ // Installs code that runs with the user's permissions: human-typed only, the summary shows what each module requests.
266
+ const result = await applyBlend(outDir, { pnpm: ctx.get('desktopPnpm'), live: ctx.get('livePluginActivation'), pluginHub: ctx.get('pluginHub'), profileDir, acrylFrameworkPackages: ctx.get('acrylFrameworkPackages'), record: ledgerRecorder(workspaceDir, 'human') }, { workspaceDir })
267
+ if (result.problems.length === 0) appendLedger(outDir, { actor: 'human', kind: 'applied', results: result.results.map(r => ({ module: r.name, origin: r.origin, status: r.status })) })
268
+ if (result.problems.length > 0) return { kind: 'error', text: `Nothing was installed; the Blend in ${outDir} does not match its lock:\n${result.problems.map(p => `- ${p}`).join('\n')}` }
269
+ const lines = result.results.map(r => `${r.name} [${r.origin}]: ${r.status}${r.permissions ? ` (${r.permissions})` : ''}${r.detail ? ` - ${r.detail}` : ''}`)
270
+ const touched = result.results.some(r => ['installed', 'updated'].includes(r.status))
271
+ return { kind: result.ok ? 'success' : 'error', text: `${lines.join('\n')}${touched ? '\nReload the page (Web) or window (Desktop, Cmd/Ctrl+R) to pick up UI changes.' : ''}` }
272
+ }
273
+ if (verb !== 'snapshot') return { kind: 'error', text: 'Usage: /blend snapshot (capture the current state), /blend verify, /blend apply (re-create a captured Blend here), or /blend ledger (what changed).' }
274
+ const dshHome = ctx.get('dshHomePath')
275
+ const app = appHomeDir()
276
+ if (app !== undefined) {
277
+ // An app IS its Blend: record into the app folder, keeping the user's blend.yaml and adding only rows it does not name yet.
278
+ const capture = captureApp({ profileDir, appHome: app, globalDir: globalPluginsDir(typeof dshHome === 'function' ? dshHome() : undefined) })
279
+ const files = writeAppBlend(capture, app)
280
+ appendLedger(app, { actor: 'human', kind: 'captured', blend: `${capture.manifest.metadata?.id}@${capture.manifest.metadata?.version}`, modules: capture.lock.modules.length, digest: capture.lock.origin.digest })
281
+ const added = capture.addedRows.length > 0 ? ` Added to blend.yaml: ${capture.addedRows.join(', ')}.` : ''
282
+ const notes = capture.notes.length > 0 ? `\nNot captured:\n${capture.notes.map(n => `- ${n}`).join('\n')}` : ''
283
+ return { kind: 'success', text: `Recorded the app in ${app}: ${capture.lock.modules.length} module(s) locked.${added} Written: ${files.join(', ')}. Commit the app folder to keep this state.${notes}` }
284
+ }
285
+ const capture = captureBlend({ profileDir, workspaceDir, globalDir: globalPluginsDir(typeof dshHome === 'function' ? dshHome() : undefined) })
286
+ const files = writeBlend(capture, outDir)
287
+ appendLedger(outDir, { actor: 'human', kind: 'captured', blend: `${capture.manifest.metadata.id}@${capture.manifest.metadata.version}`, modules: capture.lock.modules.length, digest: capture.lock.origin.digest })
288
+ const local = capture.lock.modules.filter(m => m.origin === 'local').length
289
+ const registry = capture.lock.modules.filter(m => m.origin === 'registry').length
290
+ const pulled = capture.lock.modules.filter(m => m.origin === 'pulled').length
291
+ const notes = capture.notes.length > 0 ? `\nNot captured:\n${capture.notes.map(n => `- ${n}`).join('\n')}` : ''
292
+ return { kind: 'success', text: `Captured ${capture.manifest.kind} ${capture.manifest.metadata.id}@${capture.manifest.metadata.version}: ${registry} marketplace plugin(s), ${pulled} pulled plugin(s), ${local} local plugin(s) vendored.\nWritten to ${outDir}: ${files.join(', ')}${notes}` }
293
+ },
294
+ })
295
+ }, 'plugin-context blend command')
296
+ })
297
+
298
+ ctx.inject(['tools'], scoped => {
299
+ scoped.tools.register(defineTool({
300
+ name: INSTALL_TOOL_NAME,
301
+ description: 'Install a plugin package you wrote into the active ACRYL profile and activate it live (no restart), or UPDATE it if it is already installed. Checks the package first and undoes the install if activation fails. Pass the ABSOLUTE path of the package directory. Returns the plugin status or the exact error to fix.',
302
+ parameters: {
303
+ path: { type: 'string', required: true, description: 'ABSOLUTE path of the plugin package directory (the folder containing package.json).' },
304
+ },
305
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
306
+ async execute(args, exec) {
307
+ const result = await installLocalPlugin({ path: args.path }, { pnpm: ctx.get('desktopPnpm'), live: ctx.get('livePluginActivation'), profileDir: ctx.get('desktopProfiles')?.current?.dir, acrylFrameworkPackages: ctx.get('acrylFrameworkPackages'), record: ledgerRecorder(exec?.agent?.session?.header?.cwd, 'agent') })
308
+ // A thrown error is reported to the model as a tool error with the full detail.
309
+ if (!result.ok) throw new Error(JSON.stringify(result, null, 2))
310
+ return JSON.stringify(result)
311
+ },
312
+ }))
313
+
314
+ scoped.tools.register(defineTool({
315
+ name: LIST_TOOL_NAME,
316
+ description: 'List every plugin installed in the active ACRYL profile with its origin: "local" (built here; a source folder you can edit, a scope), or "pulled"/"registry" (from GitHub, npm or the marketplace; managed, do not edit; has version and digest).',
317
+ parameters: {},
318
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
319
+ async execute() {
320
+ const profile = ctx.get('desktopProfiles')
321
+ if (!profile?.current?.dir) throw new Error('the active profile is not available in this runtime')
322
+ const dshHome = ctx.get('dshHomePath')
323
+ const globalDir = globalPluginsDir(typeof dshHome === 'function' ? dshHome() : undefined)
324
+ // `installedFrom` is kept for local plugins: it is the name the skills and docs already use for the editable source directory.
325
+ return JSON.stringify(listInstalledPlugins(profile.current.dir, { globalDir }).map(plugin => (plugin.origin === 'local' ? { ...plugin, installedFrom: plugin.source } : plugin)))
326
+ },
327
+ }))
328
+
329
+ scoped.tools.register(defineTool({
330
+ name: LOOKUP_TOOL_NAME,
331
+ description: 'Find the ACRYL plugin docs and verified examples for a topic (for example "sidebar tab", "accent color", "a tool", "hook the prompt"). Returns absolute paths to read; it only routes, the docs are the authority.',
332
+ parameters: {
333
+ topic: { type: 'string', required: true, description: 'What you want to build or change, in a few words.' },
334
+ },
335
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
336
+ async execute(args) {
337
+ const result = lookupExtensionDocs(String(args.topic ?? ''), manifest, root)
338
+ if (!result.ok) throw new Error(result.error)
339
+ return JSON.stringify(result)
340
+ },
341
+ }))
342
+
343
+ scoped.tools.register(defineTool({
344
+ name: VERIFY_TOOL_NAME,
345
+ description: 'Check a plugin package you wrote WITHOUT installing it: install lint plus importing the host entry and checking its Cordis shape. Findings include the exact error and the pack doc ids that explain the fix. Pass the ABSOLUTE package directory.',
346
+ parameters: {
347
+ path: { type: 'string', required: true, description: 'ABSOLUTE path of the plugin package directory.' },
348
+ },
349
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
350
+ async execute(args) {
351
+ if (typeof args.path !== 'string' || !isAbsolute(args.path)) throw new Error('path must be the ABSOLUTE package directory')
352
+ return JSON.stringify(await verifyPackage({ path: args.path }))
353
+ },
354
+ }))
355
+
356
+ scoped.tools.register(defineTool({
357
+ name: PUBLISH_TOOL_NAME,
358
+ description: 'Check that a local plugin package is ready for the marketplace (install checks, catalog metadata, npm pack dry run). It NEVER publishes: publishing is done by the user. Pass the ABSOLUTE package directory.',
359
+ parameters: {
360
+ path: { type: 'string', required: true, description: 'ABSOLUTE path of the plugin package directory.' },
361
+ },
362
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
363
+ async execute(args) {
364
+ const result = await preparePublish({ path: args.path })
365
+ if (!result.ok) throw new Error(JSON.stringify(result, null, 2))
366
+ return JSON.stringify(result)
367
+ },
368
+ }))
369
+
370
+ scoped.tools.register(defineTool({
371
+ name: REMOVE_TOOL_NAME,
372
+ description: 'Remove a local plugin from the active ACRYL profile and unmount it live. Pass the package name (see the list tool).',
373
+ parameters: {
374
+ package: { type: 'string', required: true, description: 'Package name of the plugin to remove.' },
375
+ },
376
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
377
+ async execute(args, exec) {
378
+ const result = await removeLocalPlugin({ package: args.package }, { pnpm: ctx.get('desktopPnpm'), live: ctx.get('livePluginActivation'), record: ledgerRecorder(exec?.agent?.session?.header?.cwd, 'agent') })
379
+ if (!result.ok) throw new Error(JSON.stringify(result, null, 2))
380
+ return JSON.stringify(result)
381
+ },
382
+ }))
383
+ })
384
+ }
@@ -0,0 +1,107 @@
1
+ import { cpSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
2
+ import { basename, join } from 'node:path'
3
+ import { currentSourcePath } from '@acryldev/plugin-hub-core'
4
+ import { installLocalPlugin, listLocalPlugins, removeLocalPlugin } from './install.js'
5
+ import { canonical, installState } from './reconcile.js'
6
+ import { verifyBlend } from './blend-capture.js'
7
+ import { listInstalledPlugins, readLockfile } from './provenance.js'
8
+ import { hashPackage } from './stage.js'
9
+ import { describePermissions, readManifest } from './manifest.js'
10
+ import { appHomeDir, projectPluginsDir } from './scopes.js'
11
+
12
+ /**
13
+ * Re-create a captured Blend (see blend-capture.js) in the active profile: the inverse of `/blend snapshot`. Human-typed, like `/reload new`, because it installs code
14
+ * that runs with the user's permissions; the summary lists what each module requests.
15
+ *
16
+ * 1. verify the Blend against its own lock (nothing is installed from a Blend that no longer matches it);
17
+ * 2. local modules: place the vendored source in the project plugin scope (`<workspace>/.acryl-plugins/<name>/`, never overwriting a folder that differs) and install it through
18
+ * the same pipeline as everything else, so `/reload`, the startup pass and provenance apply to it unchanged;
19
+ * 3. registry modules: `dsh plugin add name@version`, then compare the lockfile integrity with the locked digest and undo the install on a mismatch;
20
+ * pulled modules: pulled again through the plugin hub from the locked source, refused unless the tarball's sha512 is the locked digest;
21
+ * 4. modules already installed at the locked state are left alone (idempotent).
22
+ *
23
+ * @param {string} blendDir the captured directory (`<workspace>/.acryl/blend`)
24
+ * @param {{ pnpm: any, live: any, profileDir: string, pluginHub?: { pull(source: string, options?: { expectIntegrity?: string }): Promise<{ status: string, reason?: string, missing?: string[] }> } }} services
25
+ * @param {{ workspaceDir: string }} options
26
+ * @returns {Promise<{ ok: boolean, results: Array<{ name: string, origin: string, status: string, detail?: string, permissions?: string }>, problems: string[] }>}
27
+ */
28
+ export async function applyBlend(blendDir, services, options, fs = { existsSync, readFileSync }) {
29
+ const verified = verifyBlend(blendDir, fs)
30
+ if (!verified.ok) return { ok: false, results: [], problems: verified.problems }
31
+ const lock = JSON.parse(fs.readFileSync(join(blendDir, 'blend.lock.json'), 'utf8'))
32
+ const profile = JSON.parse(fs.readFileSync(join(services.profileDir, 'package.json'), 'utf8'))
33
+ const installed = profile.dependencies ?? {}
34
+ const results = []
35
+
36
+ for (const module of lock.modules ?? []) {
37
+ if (module.origin === 'local') {
38
+ // A lock written before the folders were renamed names `extensions/<name>`: found where it was moved.
39
+ const vendored = currentSourcePath(join(blendDir, module.source))
40
+ // In an app the Blend folder is the app: its modules are already in their place and install from there.
41
+ const folder = appHomeDir() !== undefined ? vendored : join(projectPluginsDir(options.workspaceDir), basename(module.source))
42
+ // A folder of the same name that differs from the locked source is somebody's work: report, never overwrite.
43
+ if (fs.existsSync(join(folder, 'package.json')) && `sha256:${hashPackage(folder, 64)}` !== module.digest) {
44
+ results.push({ name: module.name, origin: 'local', status: 'conflict', detail: `${folder} already exists and differs from the locked source; move it or re-capture` })
45
+ continue
46
+ }
47
+ if (!fs.existsSync(join(folder, 'package.json'))) {
48
+ mkdirSync(folder, { recursive: true })
49
+ cpSync(vendored, folder, { recursive: true })
50
+ }
51
+ const manifest = JSON.parse(fs.readFileSync(join(folder, 'package.json'), 'utf8'))
52
+ const permissions = describePermissions(readManifest(manifest).permissions)
53
+ // Already installed from this folder and in sync with it: nothing to do (applying twice is harmless).
54
+ const current = listLocalPlugins(services.profileDir, fs).find(plugin => plugin.name === module.name)
55
+ if (current && canonical(current.installedFrom) === canonical(folder) && installState(current, hashPackage, fs) === 'in-sync') {
56
+ results.push({ name: module.name, origin: 'local', status: 'unchanged', permissions })
57
+ continue
58
+ }
59
+ const result = await installLocalPlugin({ path: folder }, services)
60
+ results.push(result.ok
61
+ ? { name: module.name, origin: 'local', status: result.action ?? 'installed', permissions }
62
+ : { name: module.name, origin: 'local', status: 'failed', detail: (result.errors ?? []).join('; '), permissions })
63
+ } else if (module.origin === 'registry') {
64
+ if (typeof installed[module.name] === 'string' && (installed[module.name] === module.version || readLockfile(services.profileDir, fs).resolved.get(module.name) === module.version)) {
65
+ results.push({ name: module.name, origin: 'registry', status: 'unchanged' })
66
+ continue
67
+ }
68
+ const handle = services.pnpm.runPlugin(['add', `${module.name}@${module.version}`], options.workspaceDir)
69
+ let output = ''
70
+ if (handle.stdout) for await (const chunk of handle.stdout) output += chunk.toString()
71
+ if (handle.stderr) for await (const chunk of handle.stderr) output += chunk.toString()
72
+ const outcome = await handle.done
73
+ if (outcome.exitCode !== 0) { results.push({ name: module.name, origin: 'registry', status: 'failed', detail: output.trim().slice(-300) || `exit ${outcome.exitCode}` }); continue }
74
+ const integrity = readLockfile(services.profileDir, fs).integrity.get(`${module.name}@${module.version}`)
75
+ if (module.digest && integrity !== module.digest) {
76
+ await removeLocalPlugin({ package: module.name }, services)
77
+ results.push({ name: module.name, origin: 'registry', status: 'failed', detail: `integrity mismatch: locked ${module.digest}, got ${integrity ?? 'none'}; the install was undone` })
78
+ continue
79
+ }
80
+ results.push({ name: module.name, origin: 'registry', status: 'installed' })
81
+ } else if (module.origin === 'pulled') {
82
+ const current = listInstalledPlugins(services.profileDir, {}, fs).find(plugin => plugin.name === module.name)
83
+ if (current?.origin === 'pulled' && current.version === module.version && current.integrity === module.digest) {
84
+ results.push({ name: module.name, origin: 'pulled', status: 'unchanged' })
85
+ continue
86
+ }
87
+ if (services.pluginHub === undefined) {
88
+ results.push({ name: module.name, origin: 'pulled', status: 'failed', detail: `no plugin hub in this app to pull ${module.spec}` })
89
+ continue
90
+ }
91
+ try {
92
+ const pulled = await services.pluginHub.pull(module.spec, { expectIntegrity: module.digest })
93
+ // The hub installs through DSH's own installer: `restart-required` is installed, loading on the next start (found in a live restore).
94
+ results.push(pulled.status === 'installed'
95
+ ? { name: module.name, origin: 'pulled', status: 'installed' }
96
+ : pulled.status === 'restart-required'
97
+ ? { name: module.name, origin: 'pulled', status: 'installed', detail: 'restart the app to load it' }
98
+ : { name: module.name, origin: 'pulled', status: 'failed', detail: pulled.reason ?? (pulled.missing ? `needs ${pulled.missing.join(', ')}` : pulled.status) })
99
+ } catch (cause) {
100
+ results.push({ name: module.name, origin: 'pulled', status: 'failed', detail: cause instanceof Error ? cause.message : String(cause) })
101
+ }
102
+ } else {
103
+ results.push({ name: module.name, origin: module.origin, status: 'skipped', detail: `origin "${module.origin}" is recorded by spec only (${module.spec}); install it yourself` })
104
+ }
105
+ }
106
+ return { ok: results.every(r => !['failed', 'conflict'].includes(r.status)), results, problems: [] }
107
+ }