gentle-pi 4.7.0 → 4.8.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 (365) hide show
  1. package/README.md +55 -44
  2. package/assets/agents/gentle-ai-explore.md +3 -3
  3. package/assets/agents/gentle-ai-verify.md +20 -6
  4. package/assets/agents/gentle-ai-worker.md +6 -6
  5. package/assets/agents/jd-judge-a.md +1 -3
  6. package/assets/agents/jd-judge-b.md +1 -3
  7. package/assets/agents/review-readability.md +1 -5
  8. package/assets/agents/review-reliability.md +1 -5
  9. package/assets/agents/review-resilience.md +1 -5
  10. package/assets/agents/review-risk.md +1 -5
  11. package/assets/design-canvas/canvas-api.js +45 -0
  12. package/assets/design-canvas/canvas-boards.js +456 -0
  13. package/assets/design-canvas/canvas-boot.js +217 -0
  14. package/assets/design-canvas/canvas-checks.js +491 -0
  15. package/assets/design-canvas/canvas-comments.js +315 -0
  16. package/assets/design-canvas/canvas-compare.js +159 -0
  17. package/assets/design-canvas/canvas-events.js +75 -0
  18. package/assets/design-canvas/canvas-export.js +393 -0
  19. package/assets/design-canvas/canvas-focus.js +203 -0
  20. package/assets/design-canvas/canvas-handoffs.js +150 -0
  21. package/assets/design-canvas/canvas-i18n-es.js +392 -0
  22. package/assets/design-canvas/canvas-i18n.js +108 -0
  23. package/assets/design-canvas/canvas-layout.js +526 -0
  24. package/assets/design-canvas/canvas-menu.js +213 -0
  25. package/assets/design-canvas/canvas-messages.js +86 -0
  26. package/assets/design-canvas/canvas-minimap.js +163 -0
  27. package/assets/design-canvas/canvas-parts.js +401 -0
  28. package/assets/design-canvas/canvas-popover.js +234 -0
  29. package/assets/design-canvas/canvas-rail.js +348 -0
  30. package/assets/design-canvas/canvas-sizes.js +524 -0
  31. package/assets/design-canvas/canvas-store.js +164 -0
  32. package/assets/design-canvas/canvas-tokens.js +674 -0
  33. package/assets/design-canvas/canvas-ui.js +24 -0
  34. package/assets/design-canvas/canvas-view.js +184 -0
  35. package/assets/design-canvas/canvas.css +746 -15
  36. package/assets/design-canvas/canvas.js +2 -1506
  37. package/assets/design-canvas/index.html +117 -36
  38. package/assets/design-canvas/inspector.js +546 -16
  39. package/assets/install-wizard/wizard.js +5 -1
  40. package/assets/migrations/agent-body-history.json +24 -0
  41. package/assets/orchestrator-delegation-reference.md +8 -14
  42. package/assets/orchestrator-delegation.md +4 -4
  43. package/assets/orchestrator-full-delegation-card.md +4 -5
  44. package/assets/orchestrator-full-delegation.md +8 -8
  45. package/assets/orchestrator-memory.md +2 -2
  46. package/assets/orchestrator-prompts.md +1 -1
  47. package/assets/orchestrator-quota-recovery.md +5 -0
  48. package/assets/orchestrator-skills.md +13 -12
  49. package/assets/orchestrator-tracking.md +10 -14
  50. package/assets/orchestrator-verification.md +10 -8
  51. package/assets/orchestrator-writer.md +4 -4
  52. package/assets/orchestrator.md +18 -22
  53. package/bin/gentle-shell.mjs +128 -9
  54. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
  55. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
  56. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
  57. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
  58. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
  59. package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
  60. package/docs/assets/brand/sponsor-banner.svg +60 -0
  61. package/docs/bundled-install.md +14 -6
  62. package/docs/delegated-verification.md +18 -2
  63. package/docs/desktop-rpc.md +1253 -0
  64. package/docs/gentle-agents-activity.md +26 -0
  65. package/docs/gentle-shell.md +39 -16
  66. package/docs/install-wizard.md +30 -21
  67. package/docs/odd-preparation-continuity.md +24 -0
  68. package/docs/permission-modes.md +9 -1
  69. package/docs/prompt-budget.md +12 -0
  70. package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
  71. package/docs/readme-reference.md +76 -24
  72. package/docs/review-coordinator.md +29 -9
  73. package/docs/review-delivery-preflight.md +22 -0
  74. package/docs/work-continuity.md +11 -1
  75. package/extensions/ask-user-question.ts +2 -2
  76. package/extensions/child-context.ts +21 -7
  77. package/extensions/gentle-agents.ts +234 -33
  78. package/extensions/gentle-ai.ts +576 -135
  79. package/extensions/gentle-design.ts +69 -3
  80. package/extensions/gentle-desktop-rpc.ts +143 -0
  81. package/extensions/gentle-guide.ts +3 -0
  82. package/extensions/gentle-shell.ts +105 -52
  83. package/extensions/gentle-todo.ts +48 -25
  84. package/extensions/skill-registry.ts +248 -223
  85. package/lib/agent-assets.ts +30 -6
  86. package/lib/agent-tool-overlay.ts +117 -0
  87. package/lib/agents-config.ts +47 -6
  88. package/lib/agents-message-delivery.ts +17 -0
  89. package/lib/agents-messaging.ts +8 -2
  90. package/lib/agents-protocol.ts +15 -0
  91. package/lib/agents-report-cap.ts +115 -0
  92. package/lib/agents-runner.ts +91 -6
  93. package/lib/agents-session-transport.ts +17 -1
  94. package/lib/background-jobs-tools.ts +9 -4
  95. package/lib/bounded-writer-admission.ts +184 -31
  96. package/lib/child-context-files.ts +21 -6
  97. package/lib/codemode-renderer.ts +1 -0
  98. package/lib/delivery-conflict-markers.ts +349 -0
  99. package/lib/design-canvas-assets.ts +36 -0
  100. package/lib/design-canvas-server.ts +241 -23
  101. package/lib/design-comments.ts +94 -4
  102. package/lib/design-handoffs.ts +2 -1
  103. package/lib/design-layout.ts +125 -0
  104. package/lib/design-parts.ts +281 -0
  105. package/lib/design-system-tokens.ts +111 -0
  106. package/lib/desktop-agents-service.ts +294 -0
  107. package/lib/desktop-design-service.ts +233 -0
  108. package/lib/desktop-jobs-service.ts +263 -0
  109. package/lib/desktop-rpc-agents.ts +294 -0
  110. package/lib/desktop-rpc-config.ts +731 -0
  111. package/lib/desktop-rpc-design.ts +138 -0
  112. package/lib/desktop-rpc-jobs.ts +181 -0
  113. package/lib/desktop-rpc-permissions.ts +177 -0
  114. package/lib/desktop-rpc-profiles.ts +196 -0
  115. package/lib/desktop-rpc-usage.ts +229 -0
  116. package/lib/desktop-rpc.ts +225 -0
  117. package/lib/desktop-usage-service.ts +310 -0
  118. package/lib/destructive-command-guard.ts +188 -13
  119. package/lib/gentle-ai-renderer.ts +13 -1
  120. package/lib/gentle-design.ts +201 -14
  121. package/lib/gentle-shell-bundled.ts +100 -9
  122. package/lib/hidden-tools.ts +35 -0
  123. package/lib/inprocess-reviewer.ts +96 -12
  124. package/lib/model-fallback-policy.ts +9 -0
  125. package/lib/model-routing-authority.ts +9 -0
  126. package/lib/nan-provider.ts +42 -28
  127. package/lib/native-review-cli.ts +79 -4
  128. package/lib/orchestrator-discovery.ts +39 -2
  129. package/lib/reply-language-anchor.ts +27 -2
  130. package/lib/request-context-placement.ts +53 -0
  131. package/lib/review-candidate-view.ts +11 -1
  132. package/lib/review-continuation-registry.ts +17 -0
  133. package/lib/review-coordinator.ts +252 -8
  134. package/lib/review-delivery-preflight.ts +85 -0
  135. package/lib/review-host-relay.ts +5 -1
  136. package/lib/review-integration-v2.ts +56 -3
  137. package/lib/reviewer-stream.ts +87 -0
  138. package/lib/shell-prompt.ts +16 -3
  139. package/lib/shell-usage.ts +10 -0
  140. package/lib/vim-editor-adapter.ts +9 -2
  141. package/lib/writer-batch-admission.ts +55 -0
  142. package/lib/yolo-session-policy.ts +6 -1
  143. package/package.json +2 -2
  144. package/prompts/skill-creation.md +1 -10
  145. package/runtime/design-canvas-assets.mjs +37 -0
  146. package/runtime/gentle-shell-bundled.mjs +100 -9
  147. package/runtime/native-review-cli.mjs +79 -4
  148. package/runtime/review-integration-v2.mjs +56 -3
  149. package/scripts/bootstrap.cmd +2 -2
  150. package/scripts/bootstrap.sh +41 -4
  151. package/scripts/build-full-delegation-card.mjs +4 -0
  152. package/scripts/build-runtime-modules.mjs +1 -0
  153. package/scripts/gentle-ai-installer.mjs +10 -10
  154. package/scripts/gentle-ai-proxy.mjs +1 -1
  155. package/scripts/installer-downloads.mjs +34 -8
  156. package/scripts/installer-preflight.mjs +28 -17
  157. package/scripts/installer-probes.mjs +25 -5
  158. package/scripts/installer-server.mjs +38 -9
  159. package/scripts/installer-windows.mjs +2 -2
  160. package/scripts/pi-update.mjs +166 -27
  161. package/scripts/prepare-verifier.mjs +107 -0
  162. package/scripts/update-agent-body-history.mjs +55 -8
  163. package/scripts/verify-package-files.mjs +40 -19
  164. package/skills/branch-pr/SKILL.md +16 -16
  165. package/skills/comment-writer/SKILL.md +1 -1
  166. package/skills/design/SKILL.md +6 -6
  167. package/skills/gentle-ai/SKILL.md +5 -5
  168. package/skills/judgment-day/SKILL.md +2 -2
  169. package/skills/judgment-day/references/prompts-and-formats.md +1 -1
  170. package/skills/rdd-defect-workflow/SKILL.md +6 -6
  171. package/skills/skill-improver/SKILL.md +2 -2
  172. package/skills/skill-registry/SKILL.md +11 -13
  173. package/skills/tui-design/SKILL.md +1 -1
  174. package/skills/work-unit-commits/SKILL.md +5 -5
  175. package/tests/agent-prompt-diet-contract.test.ts +101 -0
  176. package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
  177. package/tests/agent-tool-overlay.test.ts +89 -0
  178. package/tests/agents-config.test.ts +10 -1
  179. package/tests/agents-message-delivery.test.ts +36 -0
  180. package/tests/agents-queries.test.ts +144 -4
  181. package/tests/agents-report-cap.test.ts +126 -0
  182. package/tests/agents-runner.test.ts +37 -1
  183. package/tests/agents-session-transport.test.ts +34 -0
  184. package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
  185. package/tests/append-system-prompt-route.test.ts +10 -2
  186. package/tests/approved-text-leftovers-contract.test.ts +136 -0
  187. package/tests/artifact-language.test.ts +1 -1
  188. package/tests/ask-user-question.test.ts +2 -1
  189. package/tests/audit-leftovers-contract.test.ts +51 -0
  190. package/tests/bounded-stop-contract.test.ts +9 -1
  191. package/tests/branch-pr-skill.test.ts +10 -1
  192. package/tests/bundled-install.test.ts +1 -1
  193. package/tests/child-context-files.test.ts +64 -8
  194. package/tests/child-skills-catalog.test.ts +56 -0
  195. package/tests/codemode-rendering.test.ts +4 -1
  196. package/tests/delegate-for-reason-contract.test.ts +30 -8
  197. package/tests/delivery-conflict-markers.test.ts +348 -0
  198. package/tests/design-canvas-all-sizes.test.ts +631 -0
  199. package/tests/design-canvas-allowlist.test.ts +32 -0
  200. package/tests/design-canvas-assets.test.ts +11 -878
  201. package/tests/design-canvas-boards.test.ts +77 -0
  202. package/tests/design-canvas-checks.test.ts +655 -0
  203. package/tests/design-canvas-compare.test.ts +79 -0
  204. package/tests/design-canvas-events.test.ts +59 -0
  205. package/tests/design-canvas-export.test.ts +1168 -0
  206. package/tests/design-canvas-focus.test.ts +113 -0
  207. package/tests/design-canvas-handoffs.test.ts +59 -0
  208. package/tests/design-canvas-i18n-review.test.ts +513 -0
  209. package/tests/design-canvas-i18n-views.test.ts +259 -0
  210. package/tests/design-canvas-i18n.test.ts +526 -0
  211. package/tests/design-canvas-inspector.test.ts +937 -0
  212. package/tests/design-canvas-layout.test.ts +1222 -0
  213. package/tests/design-canvas-minimap.test.ts +413 -0
  214. package/tests/design-canvas-modules.test.ts +90 -0
  215. package/tests/design-canvas-parts.test.ts +721 -0
  216. package/tests/design-canvas-rail.test.ts +799 -0
  217. package/tests/design-canvas-server.test.ts +855 -17
  218. package/tests/design-canvas-sizes.test.ts +548 -0
  219. package/tests/design-canvas-store.test.ts +180 -0
  220. package/tests/design-canvas-tokens.test.ts +965 -0
  221. package/tests/design-canvas-view.test.ts +299 -0
  222. package/tests/design-comments.test.ts +201 -1
  223. package/tests/design-handoffs.test.ts +20 -0
  224. package/tests/design-layout.test.ts +100 -0
  225. package/tests/design-parts.test.ts +260 -0
  226. package/tests/design-system-tokens.test.ts +215 -0
  227. package/tests/desktop-rpc-agents.test.ts +893 -0
  228. package/tests/desktop-rpc-config.test.ts +1452 -0
  229. package/tests/desktop-rpc-design.test.ts +662 -0
  230. package/tests/desktop-rpc-jobs.test.ts +796 -0
  231. package/tests/desktop-rpc-permissions.test.ts +311 -0
  232. package/tests/desktop-rpc-profiles.test.ts +140 -0
  233. package/tests/desktop-rpc-safety.test.ts +119 -0
  234. package/tests/desktop-rpc-usage.test.ts +697 -0
  235. package/tests/desktop-rpc.test.ts +252 -0
  236. package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
  237. package/tests/devbinary/review-session-consent.devtest.ts +84 -0
  238. package/tests/engram-safety.test.ts +111 -0
  239. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
  240. package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
  241. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
  242. package/tests/fixtures/refusal-identity.probe.mjs +139 -0
  243. package/tests/full-delegation-closure.test.ts +29 -0
  244. package/tests/gentle-agents.test.ts +329 -4
  245. package/tests/gentle-ai-binary.test.ts +1 -1
  246. package/tests/gentle-ai-child-guards.test.ts +1 -0
  247. package/tests/gentle-ai-installer.test.ts +52 -51
  248. package/tests/gentle-ai-renderer.test.ts +36 -2
  249. package/tests/gentle-ai.test.ts +121 -6
  250. package/tests/gentle-design.test.ts +365 -1
  251. package/tests/gentle-shell-bundled.test.ts +91 -5
  252. package/tests/gentle-shell-launcher.test.ts +1 -1
  253. package/tests/gentle-shell.test.ts +118 -87
  254. package/tests/gentle-todo.test.ts +32 -9
  255. package/tests/hidden-tools.test.ts +188 -0
  256. package/tests/independent-recovery-delivery.test.ts +19 -5
  257. package/tests/inprocess-reviewer.test.ts +73 -0
  258. package/tests/install-wizard.test.ts +27 -1
  259. package/tests/installer-downloads.test.ts +30 -1
  260. package/tests/installer-posix-bootstrap.test.ts +114 -13
  261. package/tests/installer-preflight.test.ts +49 -1
  262. package/tests/installer-probes.test.ts +146 -0
  263. package/tests/installer-server.test.ts +203 -4
  264. package/tests/installer-windows-bootstrap.test.ts +19 -1
  265. package/tests/judgment-day-severity-admission.test.ts +46 -0
  266. package/tests/lazy-module-contradictions-contract.test.ts +158 -0
  267. package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
  268. package/tests/maintainer/pi-update-source.maintest.ts +48 -18
  269. package/tests/model-fallback-policy.test.ts +26 -7
  270. package/tests/nan-provider-runtime.test.ts +17 -3
  271. package/tests/nan-provider.test.ts +111 -56
  272. package/tests/native-review-capability-contract.test.ts +11 -1
  273. package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
  274. package/tests/native-review-parity.test.ts +24 -5
  275. package/tests/native-review-refusal-identity.test.ts +25 -0
  276. package/tests/no-self-pause-contract.test.ts +11 -3
  277. package/tests/odd-integration.test.ts +11 -3
  278. package/tests/odd-routing-contract.test.ts +80 -28
  279. package/tests/orchestrator-budget.test.ts +30 -5
  280. package/tests/orchestrator-consultation-sdk.test.ts +32 -6
  281. package/tests/orchestrator-delegation-mode.test.ts +2 -1
  282. package/tests/orchestrator-discovery.test.ts +28 -0
  283. package/tests/orchestrator-prompt-budget.test.ts +11 -2
  284. package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
  285. package/tests/orchestrator-rdd-ownership.test.ts +2 -1
  286. package/tests/orchestrator-work-search.test.ts +4 -2
  287. package/tests/package-files.test.ts +25 -1
  288. package/tests/package-manifest.test.ts +11 -10
  289. package/tests/parallel-reason-contract.test.ts +6 -3
  290. package/tests/permission-allowlist.test.ts +200 -30
  291. package/tests/persona-neutral-voseo.test.ts +4 -4
  292. package/tests/persona-reply-language.test.ts +1 -1
  293. package/tests/persona-single-channel.test.ts +13 -5
  294. package/tests/pi-update-launcher.test.ts +17 -7
  295. package/tests/pi-update-source.test.ts +113 -6
  296. package/tests/pi-update.test.ts +294 -19
  297. package/tests/pnpm-workspace-policy.test.ts +47 -0
  298. package/tests/primary-context-files.test.ts +233 -0
  299. package/tests/primary-context-three-files.test.ts +174 -0
  300. package/tests/provider-defect-handoff.test.ts +9 -2
  301. package/tests/rdd-aware-verification-contract.test.ts +1 -1
  302. package/tests/rdd-status-line.test.ts +94 -1
  303. package/tests/reply-language-anchor-placement.test.ts +184 -0
  304. package/tests/reply-language-anchor.test.ts +17 -1
  305. package/tests/request-context-append-only.test.ts +218 -0
  306. package/tests/request-context-placement.test.ts +148 -0
  307. package/tests/review-agent-end-preflight.test.ts +79 -1
  308. package/tests/review-candidate-view.test.ts +65 -0
  309. package/tests/review-continuation-registry.test.ts +31 -0
  310. package/tests/review-contract-prompt.test.ts +1 -1
  311. package/tests/review-controller.test.ts +2 -1
  312. package/tests/review-coordinator-correction-gate.test.ts +105 -0
  313. package/tests/review-coordinator-findings.test.ts +206 -0
  314. package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
  315. package/tests/review-coordinator.test.ts +271 -4
  316. package/tests/review-delivery-preflight.test.ts +462 -0
  317. package/tests/review-due-compaction.test.ts +31 -0
  318. package/tests/review-due-public-boundary.test.ts +26 -0
  319. package/tests/review-integration-nonblocking-findings.test.ts +108 -0
  320. package/tests/review-json-arguments.test.ts +41 -2
  321. package/tests/review-ledger-contract.test.ts +19 -40
  322. package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
  323. package/tests/review-one-call-findings.test.ts +131 -0
  324. package/tests/review-one-call-followups.test.ts +308 -0
  325. package/tests/review-one-call-reviewer-requests.test.ts +207 -0
  326. package/tests/review-one-call.test.ts +452 -0
  327. package/tests/review-relay-transport-agent.test.ts +28 -1
  328. package/tests/review-reviewer-evidence.test.ts +41 -1
  329. package/tests/review-risk-assessment.test.ts +52 -5
  330. package/tests/review-run-statement-guidance-independent.test.ts +54 -0
  331. package/tests/review-session-standing-permission-controller.test.ts +32 -2
  332. package/tests/review-tool-prose-budget.test.ts +1 -0
  333. package/tests/reviewer-stream.test.ts +149 -0
  334. package/tests/session-profile-extension.test.ts +2 -2
  335. package/tests/shell-prompt.test.ts +17 -0
  336. package/tests/shell-usage.test.ts +59 -10
  337. package/tests/skill-contradictions-contract.test.ts +122 -0
  338. package/tests/skill-registry-watcher.test.ts +216 -2
  339. package/tests/skill-registry.test.ts +929 -306
  340. package/tests/support/design-canvas-dom.ts +369 -0
  341. package/tests/support/review-coordinator-runtime.ts +212 -17
  342. package/tests/task-size-routing-contract.test.ts +42 -11
  343. package/tests/test-strength-contract.test.ts +2 -1
  344. package/tests/todo-request-append-only.test.ts +214 -0
  345. package/tests/tool-batching-contract.test.ts +3 -1
  346. package/tests/update-agent-body-history.test.ts +138 -0
  347. package/tests/verification-tiers-contract.test.ts +229 -0
  348. package/tests/verifier-preparation.test.ts +229 -0
  349. package/tests/verify-agent-contract.test.ts +20 -2
  350. package/tests/verify-first-launch-contract.test.ts +87 -11
  351. package/tests/vim-editor-adapter.test.ts +2 -2
  352. package/tests/work-continuity-contract.test.ts +54 -11
  353. package/tests/writer-admission-messages.test.ts +232 -0
  354. package/tests/writer-batch-admission.test.ts +66 -0
  355. package/tests/writer-edit-surface-scope.test.ts +52 -20
  356. package/tests/writer-feature-document-admission.test.ts +184 -0
  357. package/tests/yolo-mode.test.ts +39 -0
  358. package/skills/_shared/review-ledger-contract.md +0 -106
  359. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
  360. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
  361. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
  362. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  363. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,111 @@
1
+ import { realpath, stat } from "node:fs/promises";
2
+ import { join, sep } from "node:path";
3
+ import { readDesignFile } from "./design-comments.ts";
4
+
5
+ // The design tokens of design/system.md (written by /gentle:design sync), read-only. The canvas
6
+ // inspector compares what an artboard renders with them. A token is a table row whose first cell is a
7
+ // backticked CSS custom property (`--name`) and whose second cell is its backticked value, filed under
8
+ // the `##` section it appears in. The file is the project's own markdown, so nothing here may fail the
9
+ // canvas: a missing, huge or malformed file just yields fewer tokens.
10
+
11
+ export const SYSTEM_TOKENS_FILE = "system.md";
12
+ export const MAX_SYSTEM_MD_BYTES = 256 * 1024;
13
+ export const MAX_SYSTEM_TOKENS = 500;
14
+ const MAX_NAME = 64;
15
+ const MAX_VALUE = 400;
16
+ const MAX_SECTION = 80;
17
+ // A token row is short; a longer line is skipped before any pattern runs on it.
18
+ export const MAX_SYSTEM_LINE = 1000;
19
+
20
+ export type DesignTokenGroup = "color" | "font" | "spacing" | "radius" | "shadow" | "layout" | "other";
21
+ export type DesignToken = { name: string; value: string; section: string; group: DesignTokenGroup };
22
+ export type DesignSystemTokens = { exists: boolean; tokens: DesignToken[]; problem?: "too-large" | "unreadable" };
23
+
24
+ const NAME = /^--[A-Za-z0-9_-]+$/;
25
+ const TICKED = /`([^`]+)`/g;
26
+ // Tokens written inline in a first cell, as "`--radius-sm` 8px, `--radius-md` 12px" or "`--font-sans`: `Inter, ...`".
27
+ // No two adjacent runs can match the same text (the second whitespace run follows the colon, and a
28
+ // number is digits with an optional fraction or a bare fraction), so a failing match stays linear.
29
+ const INLINE = /`(--[A-Za-z0-9_-]+)`[ \t]*(?::[ \t]*)?(?:`([^`]+)`|(-?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|%|ms|s)?|#[0-9a-fA-F]{3,8}))[ \t]*(?=[,;]|$|`--)/g;
30
+
31
+ function groupOf(section: string): DesignTokenGroup {
32
+ if (/color/i.test(section)) return "color";
33
+ if (/typograph|font/i.test(section)) return "font";
34
+ if (/spacing/i.test(section)) return "spacing";
35
+ if (/radius/i.test(section)) return "radius";
36
+ if (/shadow|motion/i.test(section)) return "shadow";
37
+ if (/layout/i.test(section)) return "layout";
38
+ return "other";
39
+ }
40
+
41
+ /** The cells of a markdown table row, with escaped pipes restored; undefined when the line is not a row. */
42
+ function cellsOf(line: string): string[] | undefined {
43
+ const trimmed = line.trim();
44
+ if (!trimmed.startsWith("|")) return undefined;
45
+ return trimmed.replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/).map((cell) => cell.replace(/\\\|/g, "|").trim());
46
+ }
47
+
48
+ function ticked(cell: string): { items: string[]; rest: string } {
49
+ const items = [...cell.matchAll(TICKED)].map((match) => match[1].trim());
50
+ return { items, rest: cell.replace(TICKED, "") };
51
+ }
52
+
53
+ /** [name, value] pairs of one row: name and value cells (lists pair up by position), else tokens inline in the first cell. */
54
+ function pairsOf(cells: string[]): Array<[string, string]> {
55
+ const names = ticked(cells[0] ?? "");
56
+ if (!names.items.some((item) => NAME.test(item))) return [];
57
+ if (names.items.every((item) => NAME.test(item)) && /^[\s/,&]*$/.test(names.rest)) {
58
+ const values = ticked(cells[1] ?? "").items;
59
+ return values.length === names.items.length ? names.items.map((name, index): [string, string] => [name, values[index]]) : [];
60
+ }
61
+ return [...(cells[0] ?? "").matchAll(INLINE)].map((match): [string, string] => [match[1], (match[2] ?? match[3]).trim()]);
62
+ }
63
+
64
+ /** The tokens of a design/system.md text; a name defined twice keeps its first definition. */
65
+ export function parseSystemTokens(text: string): DesignToken[] {
66
+ const tokens: DesignToken[] = [];
67
+ const seen = new Set<string>();
68
+ let section = "";
69
+ for (const line of text.split(/\r\n?|\n/)) {
70
+ const heading = /^##\s+(.*)$/.exec(line);
71
+ if (heading) {
72
+ section = heading[1].trim().slice(0, MAX_SECTION);
73
+ continue;
74
+ }
75
+ if (line.length > MAX_SYSTEM_LINE) continue;
76
+ const cells = cellsOf(line);
77
+ if (!cells) continue;
78
+ for (const [name, value] of pairsOf(cells)) {
79
+ if (name.length > MAX_NAME || value.length === 0 || value.length > MAX_VALUE || seen.has(name)) continue;
80
+ if (tokens.length >= MAX_SYSTEM_TOKENS) return tokens;
81
+ seen.add(name);
82
+ tokens.push({ name, value, section, group: groupOf(section) });
83
+ }
84
+ }
85
+ return tokens;
86
+ }
87
+
88
+ /** Real path of `<designRoot>/system.md` when it is a regular file inside the real design root, else undefined. */
89
+ async function locate(designRoot: string): Promise<string | undefined> {
90
+ try {
91
+ const root = await realpath(designRoot);
92
+ const target = await realpath(join(root, SYSTEM_TOKENS_FILE));
93
+ if (!target.startsWith(root.endsWith(sep) ? root : root + sep)) return undefined;
94
+ return (await stat(target)).isFile() ? target : undefined;
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ /** The tokens of `<designRoot>/system.md`; never throws: no file is `exists: false`, a bad one has `problem`. */
101
+ export async function readSystemTokens(designRoot: string): Promise<DesignSystemTokens> {
102
+ const path = await locate(designRoot);
103
+ if (!path) return { exists: false, tokens: [] };
104
+ const tooLarge = new Error("too-large");
105
+ try {
106
+ const text = await readDesignFile(path, MAX_SYSTEM_MD_BYTES, () => tooLarge);
107
+ return text === undefined ? { exists: false, tokens: [] } : { exists: true, tokens: parseSystemTokens(text) };
108
+ } catch (error) {
109
+ return { exists: true, tokens: [], problem: error === tooLarge ? "too-large" : "unreadable" };
110
+ }
111
+ }
@@ -0,0 +1,294 @@
1
+ // Gentle Desktop subagents bridge: reaches the existing agents owner (the
2
+ // single parent-session `TaskStore` plus the parent `AgentRunner`, inside
3
+ // `extensions/gentle-agents.ts`) through a defensive, versioned owner-service
4
+ // event/adapter — the agents analogue of the jobs `discoverDesktopJobsService`
5
+ // seam. It never starts, stops, or spawns a subagent itself and keeps no
6
+ // second store or runner: every list and every cancel is the owner's own
7
+ // answer, shaped into the Desktop RPC contract by
8
+ // `lib/desktop-rpc-agents.ts`.
9
+
10
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ AGENT_NOT_FOUND,
13
+ AGENTS_UNAVAILABLE,
14
+ DESKTOP_AGENTS_EVENT,
15
+ DESKTOP_AGENTS_SERVICE_CHANNEL,
16
+ isDesktopAgentsServiceShape,
17
+ parseCancelSubagentParams,
18
+ parseDesktopAgentEntry,
19
+ parseListSubagentsParams,
20
+ type DesktopAgentEntry,
21
+ type DesktopAgentsOwnerRead,
22
+ type DesktopAgentsService,
23
+ } from "./desktop-rpc-agents.ts";
24
+ import type { DesktopRpcOutcome } from "./desktop-rpc.ts";
25
+
26
+ const DISCOVERY_TIMEOUT_MS = 100;
27
+ const DEFAULT_COALESCE_MS = 150;
28
+
29
+ /** The `agents_update` event payload: the active session's projected subagent list. */
30
+ export interface DesktopAgentsUpdateEvent {
31
+ agents: DesktopAgentEntry[];
32
+ }
33
+
34
+ interface HostUiAgentsRequest { context: ExtensionContext; respond(service: DesktopAgentsService): void }
35
+
36
+ /**
37
+ * Discover the live agents owner exactly like the jobs seam: emit a bounded,
38
+ * versioned request and accept only an adapter-shaped responder.
39
+ */
40
+ export function discoverDesktopAgentsService(pi: ExtensionAPI, context: ExtensionContext): Promise<DesktopAgentsService | undefined> {
41
+ return new Promise((resolve) => {
42
+ let settled = false;
43
+ const timer = setTimeout(() => { settled = true; resolve(undefined); }, DISCOVERY_TIMEOUT_MS);
44
+ const respond = (value: unknown) => {
45
+ if (!isDesktopAgentsServiceShape(value)) return;
46
+ if (settled) { value.dispose(); return; }
47
+ settled = true; clearTimeout(timer); resolve(value);
48
+ };
49
+ try {
50
+ pi.events.emit(DESKTOP_AGENTS_SERVICE_CHANNEL, { context, respond } satisfies HostUiAgentsRequest);
51
+ } catch {
52
+ settled = true; clearTimeout(timer); resolve(undefined);
53
+ }
54
+ });
55
+ }
56
+
57
+ type Emit = (event: string, data: Record<string, unknown>) => void;
58
+
59
+ interface DesktopAgentsBridgeOptions {
60
+ discover?: typeof discoverDesktopAgentsService;
61
+ schedule?: (fn: () => void, ms: number) => () => void;
62
+ coalesceMs?: number;
63
+ }
64
+
65
+ function defaultSchedule(fn: () => void, ms: number): () => void {
66
+ const timer = setTimeout(fn, ms);
67
+ (timer as unknown as { unref?: () => void }).unref?.();
68
+ return () => clearTimeout(timer);
69
+ }
70
+
71
+ /**
72
+ * The Desktop domain slice for `list_subagents`, `cancel_subagent`, and the
73
+ * `agents_update` event. It is wired to the router's `emit` so TaskStore
74
+ * transitions become ordered events, and it owns the session-scoped lifecycle:
75
+ * a reset (session replacement or shutdown) disconnects the owner observer,
76
+ * cancels any pending coalesced flush, and drops stale async outcomes. Bursts
77
+ * of transitions are coalesced into one flush per window and byte-identical
78
+ * projected lists are deduped, matching the activity publisher's behavior.
79
+ */
80
+ export class DesktopAgentsBridge {
81
+ private readonly pi: ExtensionAPI;
82
+ private readonly discover: typeof discoverDesktopAgentsService;
83
+ private readonly schedule: (fn: () => void, ms: number) => () => void;
84
+ private readonly coalesceMs: number;
85
+ private host: ExtensionContext | undefined;
86
+ private service: DesktopAgentsService | undefined;
87
+ private discovering: Promise<DesktopAgentsService | undefined> | undefined;
88
+ private generation = 0;
89
+ private observeDispose: (() => void) | undefined;
90
+ private observeGeneration = 0;
91
+ private emit: Emit | undefined;
92
+ private flushTimer: (() => void) | undefined;
93
+ /** Byte-identical projected list already emitted; suppresses observer duplicates. */
94
+ private lastEmittedAgents: string | undefined;
95
+
96
+ constructor(pi: ExtensionAPI, options: DesktopAgentsBridgeOptions = {}) {
97
+ this.pi = pi;
98
+ this.discover = options.discover ?? discoverDesktopAgentsService;
99
+ this.schedule = options.schedule ?? defaultSchedule;
100
+ this.coalesceMs = options.coalesceMs ?? DEFAULT_COALESCE_MS;
101
+ }
102
+
103
+ /** The live interactive context of this Desktop session; bound per command. */
104
+ attach(context: ExtensionContext): void {
105
+ this.host = context;
106
+ }
107
+
108
+ /** Route agent-driven `agents_update` events through the router's sequencer. */
109
+ wire(emit: Emit): void {
110
+ this.emit = emit;
111
+ }
112
+
113
+ /** Eager discovery/subscription so agent-driven transitions arrive before any request. */
114
+ async start(): Promise<void> {
115
+ const host = this.host;
116
+ if (!host) return;
117
+ await this.owner(host);
118
+ }
119
+
120
+ /** Session start/shutdown: the owner adapter of a previous session is invalid. */
121
+ reset(): void {
122
+ this.generation += 1;
123
+ this.observeDispose?.();
124
+ this.observeDispose = undefined;
125
+ this.flushTimer?.();
126
+ this.flushTimer = undefined;
127
+ const service = this.service;
128
+ this.service = undefined;
129
+ this.discovering = undefined;
130
+ this.host = undefined;
131
+ this.emit = undefined;
132
+ this.lastEmittedAgents = undefined;
133
+ try {
134
+ service?.dispose();
135
+ } catch {
136
+ /* owner teardown */
137
+ }
138
+ }
139
+
140
+ async handle(method: string, params: Record<string, unknown>): Promise<DesktopRpcOutcome | undefined> {
141
+ if (method !== "list_subagents" && method !== "cancel_subagent") return undefined;
142
+ const host = this.host;
143
+ if (!host) return { ok: false, error: AGENTS_UNAVAILABLE };
144
+ // Parse before discovery: a malformed request must never trigger owner work.
145
+ if (method === "list_subagents") {
146
+ const parsed = parseListSubagentsParams(params);
147
+ if ("error" in parsed) return { ok: false, error: parsed.error };
148
+ } else {
149
+ const parsed = parseCancelSubagentParams(params);
150
+ if ("error" in parsed) return { ok: false, error: parsed.error };
151
+ }
152
+ const generation = this.generation;
153
+ const service = await this.owner(host);
154
+ if (generation !== this.generation || !service) return { ok: false, error: AGENTS_UNAVAILABLE };
155
+ return method === "list_subagents" ? this.list(service) : this.cancel(service, params);
156
+ }
157
+
158
+ private async owner(context: ExtensionContext): Promise<DesktopAgentsService | undefined> {
159
+ if (this.service) return this.service;
160
+ if (!this.discovering) {
161
+ const generation = this.generation;
162
+ const discovering = Promise.resolve()
163
+ .then(() => this.discover(this.pi, context))
164
+ .then((service) => {
165
+ // A reset/replacement happened while discovery was in flight: the
166
+ // late adapter belongs to a superseded session. Dispose it and never
167
+ // cache or re-subscribe it for the next session.
168
+ if (generation !== this.generation || !service) {
169
+ try { service?.dispose(); } catch { /* owner teardown */ }
170
+ return undefined;
171
+ }
172
+ this.service = service;
173
+ this.subscribe(service);
174
+ return service;
175
+ })
176
+ .catch(() => undefined)
177
+ .finally(() => {
178
+ if (this.discovering === discovering) this.discovering = undefined;
179
+ });
180
+ this.discovering = discovering;
181
+ }
182
+ return this.discovering;
183
+ }
184
+
185
+ private subscribe(service: DesktopAgentsService): void {
186
+ this.observeGeneration = this.generation;
187
+ try {
188
+ this.observeDispose = service.observe((sessionId) => this.onChanged(service, sessionId));
189
+ } catch {
190
+ this.observeDispose = undefined;
191
+ }
192
+ }
193
+
194
+ /** Agent-driven transition: coalesce and then project the active session's list. */
195
+ private onChanged(service: DesktopAgentsService, sessionId: string): void {
196
+ if (this.observeGeneration !== this.generation) return;
197
+ const host = this.host;
198
+ const emit = this.emit;
199
+ if (!host || !emit) return;
200
+ if (sessionId !== this.activeSessionId(host)) return;
201
+ this.scheduleFlush(service);
202
+ }
203
+
204
+ private scheduleFlush(service: DesktopAgentsService): void {
205
+ if (this.flushTimer) return;
206
+ this.flushTimer = this.schedule(() => {
207
+ this.flushTimer = undefined;
208
+ this.flush(service);
209
+ }, this.coalesceMs);
210
+ }
211
+
212
+ /** Emit the active session's projected list once, deduping byte-identical content. */
213
+ private flush(service: DesktopAgentsService): void {
214
+ if (this.observeGeneration !== this.generation) return;
215
+ const host = this.host;
216
+ const emit = this.emit;
217
+ if (!host || !emit) return;
218
+ const read = this.readOwner(service);
219
+ if (!read) return;
220
+ const key = JSON.stringify(read.agents);
221
+ if (key === this.lastEmittedAgents) return;
222
+ this.lastEmittedAgents = key;
223
+ emit(DESKTOP_AGENTS_EVENT, { agents: read.agents } satisfies DesktopAgentsUpdateEvent);
224
+ }
225
+
226
+ private activeSessionId(host: ExtensionContext): string {
227
+ return host.sessionManager?.getSessionId?.() ?? "";
228
+ }
229
+
230
+ private readOwner(service: DesktopAgentsService): DesktopAgentsOwnerRead | undefined {
231
+ try {
232
+ const read = service.read();
233
+ if (!read || typeof read !== "object") return undefined;
234
+ const agents = this.parseAgents(read.agents);
235
+ if (agents === undefined) return undefined;
236
+ return { sessionId: read.sessionId, agents };
237
+ } catch {
238
+ // Raw owner failures carry prompt text and path detail; none of it
239
+ // crosses the contract. An unreadable owner is treated as absent.
240
+ return undefined;
241
+ }
242
+ }
243
+
244
+ private parseAgents(value: unknown): DesktopAgentEntry[] | undefined {
245
+ if (!Array.isArray(value)) return undefined;
246
+ const agents: DesktopAgentEntry[] = [];
247
+ for (const entry of value) {
248
+ const parsed = parseDesktopAgentEntry(entry);
249
+ if (parsed === undefined) return undefined;
250
+ agents.push(parsed);
251
+ }
252
+ return agents;
253
+ }
254
+
255
+ private list(service: DesktopAgentsService): DesktopRpcOutcome {
256
+ const read = this.readOwner(service);
257
+ if (!read) return { ok: false, error: AGENTS_UNAVAILABLE };
258
+ return { ok: true, data: { agents: read.agents } as unknown as Record<string, unknown> };
259
+ }
260
+
261
+ private cancel(service: DesktopAgentsService, params: Record<string, unknown>): DesktopRpcOutcome {
262
+ // Params were already validated before discovery; reparse defensively.
263
+ const parsed = parseCancelSubagentParams(params);
264
+ if ("error" in parsed) return { ok: false, error: parsed.error };
265
+ let outcome: ReturnType<DesktopAgentsService["cancel"]>;
266
+ try {
267
+ outcome = service.cancel(parsed.id);
268
+ } catch {
269
+ // Raw owner failures carry prompt text and path detail; none of it crosses.
270
+ return { ok: false, error: AGENTS_UNAVAILABLE };
271
+ }
272
+ if (!outcome || outcome.kind === "not_found") return { ok: false, error: AGENT_NOT_FOUND };
273
+ // The owner's projected entry crosses the event bus: re-validate it.
274
+ const agent = parseDesktopAgentEntry(outcome.agent);
275
+ if (agent === undefined) return { ok: false, error: AGENTS_UNAVAILABLE };
276
+ const data = { agent } as unknown as Record<string, unknown>;
277
+ // A no-op (already-terminal) cancellation changes nothing: answer the
278
+ // terminal state and emit no event.
279
+ if (outcome.changed !== true) return { ok: true, data };
280
+ // Response-before-event: carry the event so the router publishes the
281
+ // response line first, then one `agents_update` with the post-action list.
282
+ const read = this.readOwner(service);
283
+ const agents = read ? read.agents : [agent];
284
+ this.lastEmittedAgents = JSON.stringify(agents);
285
+ return {
286
+ ok: true,
287
+ data,
288
+ event: {
289
+ name: DESKTOP_AGENTS_EVENT,
290
+ data: { agents } satisfies DesktopAgentsUpdateEvent,
291
+ },
292
+ };
293
+ }
294
+ }
@@ -0,0 +1,233 @@
1
+ // Gentle Desktop design-canvas bridge: reaches the existing design owner (the
2
+ // single `DesignCanvas` from `createDesignCanvas`, plus `listDesigns`, inside
3
+ // `extensions/gentle-design.ts`) through a defensive, versioned owner-service
4
+ // event/adapter — the design analogue of the usage `discoverDesktopUsageService`
5
+ // seam. It never starts a server, opens a browser, or keeps a second canvas
6
+ // store: every read and every transition is the owner's own answer, shaped into
7
+ // the Desktop RPC contract by `lib/desktop-rpc-design.ts`.
8
+
9
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ DESIGN_UNAVAILABLE,
12
+ DESKTOP_DESIGN_EVENT,
13
+ DESKTOP_DESIGN_SERVICE_CHANNEL,
14
+ isDesktopDesignServiceShape,
15
+ isValidDesktopDesignOwnerState,
16
+ parseDesktopDesignEntries,
17
+ parseDesignCanvasParams,
18
+ type DesktopDesignEntry,
19
+ type DesktopDesignOwnerState,
20
+ type DesktopDesignOwnerTransition,
21
+ type DesktopDesignService,
22
+ } from "./desktop-rpc-design.ts";
23
+ import type { DesktopRpcOutcome } from "./desktop-rpc.ts";
24
+ import { isInteractiveRpcHost } from "./rpc-host.ts";
25
+
26
+ const DISCOVERY_TIMEOUT_MS = 100;
27
+
28
+ interface HostUiDesignRequest { context: ExtensionContext; respond(service: DesktopDesignService): void }
29
+
30
+ /**
31
+ * Discover the live design owner exactly like the usage seam: emit a bounded,
32
+ * versioned request and accept only an adapter-shaped responder.
33
+ */
34
+ export function discoverDesktopDesignService(pi: ExtensionAPI, context: ExtensionContext): Promise<DesktopDesignService | undefined> {
35
+ return new Promise((resolve) => {
36
+ let settled = false;
37
+ const timer = setTimeout(() => { settled = true; resolve(undefined); }, DISCOVERY_TIMEOUT_MS);
38
+ const respond = (value: unknown) => {
39
+ if (!isDesktopDesignServiceShape(value)) return;
40
+ if (settled) { value.dispose(); return; }
41
+ settled = true; clearTimeout(timer); resolve(value);
42
+ };
43
+ try {
44
+ pi.events.emit(DESKTOP_DESIGN_SERVICE_CHANNEL, { context, respond } satisfies HostUiDesignRequest);
45
+ } catch {
46
+ settled = true; clearTimeout(timer); resolve(undefined);
47
+ }
48
+ });
49
+ }
50
+
51
+ type Emit = (event: string, data: Record<string, unknown>) => void;
52
+
53
+ interface DesktopDesignBridgeOptions {
54
+ discover?: typeof discoverDesktopDesignService;
55
+ /** The interactive-host trust gate for URL inclusion; injectable for tests. */
56
+ trusted?: (context: ExtensionContext) => boolean;
57
+ }
58
+
59
+ /**
60
+ * The Desktop domain slice for `get_design_canvas` and the `design_canvas`
61
+ * event. It is wired to the router's `emit` so agent-driven canvas transitions
62
+ * become ordered events, and it owns the session-scoped lifecycle: a reset
63
+ * (session replacement or shutdown) disconnects the owner observer and drops
64
+ * stale async outcomes. There is no open/stop method here — those remain the
65
+ * `gentle_design` tool's job.
66
+ */
67
+ export class DesktopDesignBridge {
68
+ private readonly pi: ExtensionAPI;
69
+ private readonly discover: typeof discoverDesktopDesignService;
70
+ private readonly trustedHost: (context: ExtensionContext) => boolean;
71
+ private host: ExtensionContext | undefined;
72
+ private service: DesktopDesignService | undefined;
73
+ private discovering: Promise<DesktopDesignService | undefined> | undefined;
74
+ private generation = 0;
75
+ private observeDispose: (() => void) | undefined;
76
+ private observeGeneration = 0;
77
+ private emit: Emit | undefined;
78
+
79
+ constructor(pi: ExtensionAPI, options: DesktopDesignBridgeOptions = {}) {
80
+ this.pi = pi;
81
+ this.discover = options.discover ?? discoverDesktopDesignService;
82
+ this.trustedHost = options.trusted ?? ((context) => isInteractiveRpcHost(context.mode));
83
+ }
84
+
85
+ /** The live interactive context of this Desktop session; bound per command. */
86
+ attach(context: ExtensionContext): void {
87
+ this.host = context;
88
+ }
89
+
90
+ /** Route agent-driven `design_canvas` events through the router's sequencer. */
91
+ wire(emit: Emit): void {
92
+ this.emit = emit;
93
+ }
94
+
95
+ /** Eager discovery/subscription so agent-driven transitions arrive before any request. */
96
+ async start(): Promise<void> {
97
+ const host = this.host;
98
+ if (!host) return;
99
+ await this.owner(host);
100
+ }
101
+
102
+ /** Session start/shutdown: the owner adapter of a previous session is invalid. */
103
+ reset(): void {
104
+ this.generation += 1;
105
+ this.observeDispose?.();
106
+ this.observeDispose = undefined;
107
+ const service = this.service;
108
+ this.service = undefined;
109
+ this.discovering = undefined;
110
+ this.host = undefined;
111
+ this.emit = undefined;
112
+ try {
113
+ service?.dispose();
114
+ } catch {
115
+ /* display-only owner teardown */
116
+ }
117
+ }
118
+
119
+ async handle(method: string, params: Record<string, unknown>): Promise<DesktopRpcOutcome | undefined> {
120
+ if (method !== "get_design_canvas") return undefined;
121
+ const host = this.host;
122
+ if (!host) return { ok: false, error: DESIGN_UNAVAILABLE };
123
+ // Parse before discovery: a malformed request must never trigger owner work.
124
+ const parsed = parseDesignCanvasParams(params);
125
+ if ("error" in parsed) return { ok: false, error: parsed.error };
126
+ const generation = this.generation;
127
+ const service = await this.owner(host);
128
+ if (generation !== this.generation || !service) return { ok: false, error: DESIGN_UNAVAILABLE };
129
+ return this.read(service, parsed.includeUrl, host);
130
+ }
131
+
132
+ private async owner(context: ExtensionContext): Promise<DesktopDesignService | undefined> {
133
+ if (this.service) return this.service;
134
+ if (!this.discovering) {
135
+ const generation = this.generation;
136
+ const discovering = Promise.resolve()
137
+ .then(() => this.discover(this.pi, context))
138
+ .then((service) => {
139
+ // A reset/replacement happened while discovery was in flight: the
140
+ // late adapter belongs to a superseded session. Dispose it and never
141
+ // cache or re-subscribe it for the next session.
142
+ if (generation !== this.generation || !service) {
143
+ try { service?.dispose(); } catch { /* owner teardown */ }
144
+ return undefined;
145
+ }
146
+ this.service = service;
147
+ this.subscribe(service);
148
+ return service;
149
+ })
150
+ .catch(() => undefined)
151
+ .finally(() => {
152
+ if (this.discovering === discovering) this.discovering = undefined;
153
+ });
154
+ this.discovering = discovering;
155
+ }
156
+ return this.discovering;
157
+ }
158
+
159
+ private subscribe(service: DesktopDesignService): void {
160
+ this.observeGeneration = this.generation;
161
+ // The tokenized URL follows the same trust gate as `includeUrl` on a read:
162
+ // only a trusted interactive Desktop client receives it in events.
163
+ const includeUrl = this.host ? this.trustedHost(this.host) : false;
164
+ try {
165
+ this.observeDispose = service.observe({ includeUrl }, (transition) => this.onTransition(transition));
166
+ } catch {
167
+ this.observeDispose = undefined;
168
+ }
169
+ }
170
+
171
+ /** Agent-driven transition: forward it exactly as the owner projected it. */
172
+ private onTransition(transition: DesktopDesignOwnerTransition): void {
173
+ if (this.observeGeneration !== this.generation) return;
174
+ const emit = this.emit;
175
+ if (!emit) return;
176
+ emit(DESKTOP_DESIGN_EVENT, {
177
+ transition: transition.transition,
178
+ running: transition.running,
179
+ slug: transition.slug,
180
+ connectedClients: transition.connectedClients,
181
+ ...(transition.url === undefined ? {} : { url: transition.url }),
182
+ });
183
+ }
184
+
185
+ private async read(service: DesktopDesignService, includeUrl: boolean, host: ExtensionContext): Promise<DesktopRpcOutcome> {
186
+ let state: DesktopDesignOwnerState;
187
+ try {
188
+ const raw = await service.read();
189
+ // The owner's answer crosses the event bus: re-validate before projecting,
190
+ // so a foreign or malformed state can never become a malformed success.
191
+ if (!isValidDesktopDesignOwnerState(raw)) return { ok: false, error: DESIGN_UNAVAILABLE };
192
+ state = raw;
193
+ } catch {
194
+ // Raw owner failures carry paths and token detail; none of it crosses
195
+ // the contract. An unreadable owner is treated as absent.
196
+ return { ok: false, error: DESIGN_UNAVAILABLE };
197
+ }
198
+
199
+ let designs: DesktopDesignEntry[];
200
+ try {
201
+ const parsed = parseDesktopDesignEntries(service.listDesigns());
202
+ // A malformed design list (non-array or a bad entry) is junk, not an
203
+ // empty project: answer unavailable rather than echoing bad data.
204
+ if (parsed === undefined) return { ok: false, error: DESIGN_UNAVAILABLE };
205
+ designs = parsed;
206
+ } catch {
207
+ designs = [];
208
+ }
209
+
210
+ const wantUrl = includeUrl && this.trustedHost(host);
211
+ let url: string | undefined;
212
+ if (wantUrl) {
213
+ try {
214
+ const candidate = service.url();
215
+ // The tokenized URL is a capability: a non-string value is dropped
216
+ // exactly like a throwing owner, never emitted as junk.
217
+ url = typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;
218
+ } catch {
219
+ url = undefined;
220
+ }
221
+ }
222
+ return {
223
+ ok: true,
224
+ data: {
225
+ running: state.running,
226
+ slug: state.slug,
227
+ connectedClients: state.connectedClients,
228
+ designs,
229
+ ...(url === undefined ? {} : { url }),
230
+ } as unknown as Record<string, unknown>,
231
+ };
232
+ }
233
+ }