@uniqbit/mate-core 1.0.0-canary.0 → 1.0.0-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (325) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
  2. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
  3. package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
  4. package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
  5. package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
  6. package/claude-plugin/hooks/hooks.json +10 -1
  7. package/claude-plugin/hooks/tokensave-route.mjs +52 -0
  8. package/opencode-plugin/src/server.ts +4 -0
  9. package/opencode-plugin/src/tui.tsx +2 -0
  10. package/opencode-plugin/tui.tsx +2 -0
  11. package/package.json +45 -16
  12. package/src/brand/terminal.ts +5 -0
  13. package/src/cli/commands/artifact/apply-context.ts +275 -0
  14. package/src/cli/commands/artifact/artifact.ts +4 -0
  15. package/src/cli/commands/artifact/delivery/archive.ts +13 -5
  16. package/src/cli/commands/artifact/delivery/environment.ts +36 -13
  17. package/src/cli/commands/artifact/delivery/link.ts +35 -15
  18. package/src/cli/commands/artifact/delivery/output.ts +31 -0
  19. package/src/cli/commands/artifact/finish/command.ts +50 -5
  20. package/src/cli/commands/artifact/finish/engine.ts +44 -11
  21. package/src/cli/commands/artifact/finish/git.ts +132 -19
  22. package/src/cli/commands/artifact/finish/openspec.ts +6 -1
  23. package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
  24. package/src/cli/commands/cap/index-cmd.ts +64 -15
  25. package/src/cli/commands/cap/tokensave.ts +7 -5
  26. package/src/cli/commands/companion/link.ts +14 -1
  27. package/src/cli/commands/companion/open.ts +16 -11
  28. package/src/cli/commands/companion/sync.ts +10 -0
  29. package/src/cli/commands/companion/tui.ts +17 -7
  30. package/src/cli/commands/companion/update.ts +74 -12
  31. package/src/cli/commands/doctor.ts +20 -5
  32. package/src/cli/commands/factory/factory.ts +301 -0
  33. package/src/cli/commands/install.ts +133 -9
  34. package/src/cli/commands/launch/shared.ts +16 -11
  35. package/src/cli/commands/report/index.ts +20 -1
  36. package/src/cli/commands/session/context.ts +102 -0
  37. package/src/cli/commands/setup.ts +44 -10
  38. package/src/cli/commands/studio/factory-credential.ts +49 -0
  39. package/src/cli/commands/studio/index.ts +29 -2
  40. package/src/cli/commands/studio/payload.ts +249 -15
  41. package/src/cli/commands/studio/routes.ts +41 -8
  42. package/src/cli/commands/studio/selection.ts +142 -16
  43. package/src/cli/commands/studio/server.ts +403 -364
  44. package/src/cli/commands/studio/services.ts +60 -0
  45. package/src/cli/commands/studio/studio-app.ts +67 -0
  46. package/src/cli/commands/studio/terminal-assets.ts +21 -33
  47. package/src/cli/commands/studio/terminal.ts +85 -15
  48. package/src/cli/commands/studio/views/model.ts +18 -0
  49. package/src/cli/commands/studio/views/vault/markdown-tree.ts +267 -0
  50. package/src/cli/commands/studio/views/vault/view.ts +185 -0
  51. package/src/cli/commands/studio/workset-session.ts +131 -0
  52. package/src/cli/commands/unwrap.ts +8 -0
  53. package/src/cli/commands/update.ts +27 -1
  54. package/src/cli/commands/working/cleanup.ts +10 -1
  55. package/src/cli/commands/working/link.ts +76 -0
  56. package/src/cli/commands/working/working.ts +10 -0
  57. package/src/cli/commands/working/worktree.ts +356 -0
  58. package/src/cli/companion-link-wizard.tsx +2 -0
  59. package/src/cli/companion-selector.tsx +2 -0
  60. package/src/cli/confirm.ts +2 -0
  61. package/src/cli/install-plan.tsx +127 -160
  62. package/src/cli/launch-selector.tsx +2 -0
  63. package/src/cli/main.ts +18 -0
  64. package/src/cli/parse-flags.ts +9 -1
  65. package/src/cli/repo-list-table.tsx +2 -0
  66. package/src/cli/setup-selector.tsx +79 -20
  67. package/src/cli/usage.ts +11 -1
  68. package/src/create-mate.ts +5 -4
  69. package/src/hooks/tokensave-route.ts +26 -0
  70. package/src/lib/apply-context/fingerprint.ts +174 -0
  71. package/src/lib/apply-context/protocol.ts +193 -0
  72. package/src/lib/components/confirm-prompt.tsx +21 -9
  73. package/src/lib/components/select-menu.tsx +10 -3
  74. package/src/lib/components/spinner.tsx +4 -2
  75. package/src/lib/components/startup-progress.tsx +227 -41
  76. package/src/lib/components/text-input-display.tsx +2 -0
  77. package/src/lib/components/wizard-footer.tsx +2 -0
  78. package/src/lib/components/wizard-header.tsx +13 -11
  79. package/src/lib/delivery/archive-change.ts +14 -2
  80. package/src/lib/delivery/branches.ts +29 -5
  81. package/src/lib/delivery/environment.ts +7 -1
  82. package/src/lib/delivery/forge.ts +2 -2
  83. package/src/lib/delivery/merge-git.ts +261 -0
  84. package/src/lib/delivery/overlap.ts +11 -4
  85. package/src/lib/delivery/record-delivery.ts +97 -10
  86. package/src/lib/delivery/record.ts +67 -7
  87. package/src/lib/delivery/refresh.ts +104 -10
  88. package/src/lib/delivery/repository-access.ts +46 -2
  89. package/src/lib/delivery/resolve-branch.ts +162 -0
  90. package/src/lib/delivery/token.ts +7 -41
  91. package/src/lib/factory/attach-client.ts +113 -0
  92. package/src/lib/factory/attach.ts +178 -0
  93. package/src/lib/factory/broker.ts +190 -0
  94. package/src/lib/factory/bun-commands.ts +39 -0
  95. package/src/lib/factory/client.ts +92 -0
  96. package/src/lib/factory/command.ts +61 -0
  97. package/src/lib/factory/credential-store.ts +153 -0
  98. package/src/lib/factory/frames.ts +77 -0
  99. package/src/lib/factory/ids.ts +58 -0
  100. package/src/lib/factory/keyed-serial.ts +27 -0
  101. package/src/lib/factory/outcomes/actions.ts +114 -0
  102. package/src/lib/factory/outcomes/index.ts +381 -0
  103. package/src/lib/factory/outcomes/lifecycle.ts +205 -0
  104. package/src/lib/factory/outcomes/runs.ts +81 -0
  105. package/src/lib/factory/outcomes/sessions.ts +38 -0
  106. package/src/lib/factory/prepare.ts +49 -0
  107. package/src/lib/factory/pty.ts +103 -0
  108. package/src/lib/factory/runner/companion-context.ts +178 -0
  109. package/src/lib/factory/runner/control.ts +92 -0
  110. package/src/lib/factory/runner/harness-agent.ts +250 -0
  111. package/src/lib/factory/runner/live.ts +159 -0
  112. package/src/lib/factory/runner/questions.ts +22 -0
  113. package/src/lib/factory/runner/rank.ts +26 -0
  114. package/src/lib/factory/runner/run-policy.ts +12 -0
  115. package/src/lib/factory/runner/run.ts +199 -0
  116. package/src/lib/factory/runner/scheduler.ts +416 -0
  117. package/src/lib/factory/runner/state.ts +233 -0
  118. package/src/lib/factory/runner/workflow.ts +542 -0
  119. package/src/lib/factory/runtime.ts +972 -0
  120. package/src/lib/factory/sandbox.ts +292 -0
  121. package/src/lib/factory/worktree-branch.ts +17 -0
  122. package/src/lib/install.ts +66 -14
  123. package/src/lib/live-progress.ts +36 -0
  124. package/src/lib/member-choices.ts +67 -0
  125. package/src/lib/orchestrator/adapters/base.ts +55 -22
  126. package/src/lib/orchestrator/adapters/claude.ts +6 -1
  127. package/src/lib/orchestrator/config-store.ts +3 -2
  128. package/src/lib/orchestrator/editor.ts +29 -23
  129. package/src/lib/orchestrator/projection-entries.ts +56 -21
  130. package/src/lib/orchestrator/projection-opencode-copies.ts +32 -15
  131. package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
  132. package/src/lib/orchestrator/projection-types.ts +33 -1
  133. package/src/lib/orchestrator/session-context-link.ts +67 -0
  134. package/src/lib/orchestrator/setup-compatibilities.ts +55 -12
  135. package/src/lib/orchestrator/types.ts +5 -0
  136. package/src/lib/orchestrator/working-repo-projection.ts +50 -7
  137. package/src/lib/orchestrator/workspace-document.ts +105 -0
  138. package/src/lib/package-paths.ts +29 -0
  139. package/src/lib/runtime-directory-refresh.ts +17 -1
  140. package/src/lib/workset/record.ts +513 -0
  141. package/src/lib/workset/repositories.ts +55 -0
  142. package/src/lib/workset/stage.ts +148 -0
  143. package/src/lib/workset/stages.ts +113 -0
  144. package/src/lib/workset/worktree-index.ts +116 -0
  145. package/src/lib/workset/worktree.ts +830 -0
  146. package/src/opencode/companion-hooks.ts +45 -2
  147. package/src/opencode/enter-worktree.ts +72 -0
  148. package/src/opencode/tui.tsx +9 -4
  149. package/src/plugins.ts +1 -0
  150. package/src/runtime/claude-delivery-plan.ts +22 -5
  151. package/src/runtime/companion-git.ts +52 -10
  152. package/src/runtime/companion-guidance.ts +7 -7
  153. package/src/runtime/companion-lock.ts +30 -7
  154. package/src/runtime/env.ts +48 -3
  155. package/src/runtime/git-layout.ts +219 -0
  156. package/src/runtime/index.ts +24 -0
  157. package/src/runtime/physical-path.ts +111 -0
  158. package/src/runtime/policy.ts +36 -2
  159. package/src/runtime/runtime-directory.ts +5 -0
  160. package/src/runtime/secret-guard.ts +19 -5
  161. package/src/runtime/secret-patterns.ts +267 -34
  162. package/src/runtime/session-context.ts +98 -0
  163. package/src/runtime/tokensave-route.ts +152 -0
  164. package/src/runtime/wrap-state.ts +24 -16
  165. package/src/studio.ts +124 -0
  166. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +10 -8
  167. package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +16 -98
  168. package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +10 -2
  169. package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +76 -18
  170. package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
  171. package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +2 -0
  172. package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +32 -5
  173. package/src/templates/mate-skills/agents/mate-backfill-spec/SKILL.md +8 -1
  174. package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +16 -1
  175. package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +22 -6
  176. package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +2 -0
  177. package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +8 -1
  178. package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
  179. package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +7 -0
  180. package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +55 -50
  181. package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +47 -0
  182. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +2 -0
  183. package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +2 -0
  184. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +29 -10
  185. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +4 -2
  186. package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +21 -0
  187. package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +13 -0
  188. package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +76 -18
  189. package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
  190. package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +2 -0
  191. package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +32 -5
  192. package/src/templates/mate-skills/claude/mate-backfill-spec/SKILL.md +8 -1
  193. package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +16 -1
  194. package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +22 -6
  195. package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +2 -0
  196. package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +8 -1
  197. package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
  198. package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +7 -0
  199. package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +55 -50
  200. package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +47 -0
  201. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +2 -0
  202. package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +2 -0
  203. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +29 -10
  204. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +4 -2
  205. package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +21 -0
  206. package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +13 -0
  207. package/src/templates/mate-skills/openspec-references.ts +2 -0
  208. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +364 -224
  209. package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
  210. package/src/tools/setup/capabilities/context-mode.ts +34 -5
  211. package/src/tools/setup/capabilities/graphify-secrets.ts +2 -14
  212. package/src/tools/setup/capabilities/graphify.ts +34 -7
  213. package/src/tools/setup/capabilities/openspec.ts +12 -2
  214. package/src/tools/setup/capabilities/react-doctor.ts +8 -1
  215. package/src/tools/setup/capabilities/rtk.ts +4 -0
  216. package/src/tools/setup/capabilities/tokensave.ts +77 -68
  217. package/src/tools/setup/engine.ts +3 -2
  218. package/src/tools/setup/install-contract.ts +8 -0
  219. package/src/tools/setup/mate-skill-copies.ts +51 -0
  220. package/src/tools/setup/package-managers/uv.ts +73 -11
  221. package/src/tools/setup/plugin.ts +5 -0
  222. package/src/tools/setup/providers/claude-plugin-hooks.ts +12 -0
  223. package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
  224. package/src/tools/setup/providers/claude.ts +11 -5
  225. package/src/tools/setup/utils.ts +4 -0
  226. package/src/tools/setup/working-repo-cleanup.ts +29 -1
  227. package/src/tools/setup/working-repo-local-state.ts +252 -75
  228. package/src/tools/setup.ts +57 -16
  229. package/studio-dist/client/assets/companion-view-Csva26Ir.js +1 -0
  230. package/studio-dist/client/assets/delivery-path-DJMpRmiY.js +1 -0
  231. package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
  232. package/studio-dist/client/assets/factory-B7l9ZQyx.js +4 -0
  233. package/studio-dist/client/assets/index-n6uo_92S.js +40 -0
  234. package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
  235. package/studio-dist/client/assets/prepaint-CD5OpmTM.js +24 -0
  236. package/studio-dist/client/assets/queries-CN3JwMBX.js +1 -0
  237. package/studio-dist/client/assets/react-CabXf2Ds.js +1 -0
  238. package/studio-dist/client/assets/report-time-Dc-KOqQu.js +1 -0
  239. package/studio-dist/client/assets/reports-C01RsnMA.js +1 -0
  240. package/studio-dist/client/assets/rolldown-runtime-WkwZ5CU-.js +1 -0
  241. package/studio-dist/client/assets/routes-4pbC-2Hj.js +1 -0
  242. package/studio-dist/client/assets/skills-CihQganl.js +1 -0
  243. package/studio-dist/client/assets/spec-areas-C2L48N4C.js +1 -0
  244. package/studio-dist/client/assets/specs-D24_35_K.js +1 -0
  245. package/studio-dist/client/assets/studio-DKxfi691.css +1 -0
  246. package/studio-dist/client/assets/studio-queries-rvbJupCy.js +3 -0
  247. package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
  248. package/studio-dist/client/assets/vault-Bd4CQiTK.js +1 -0
  249. package/studio-dist/client/assets/warnings-V_Ys51wJ.js +1 -0
  250. package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
  251. package/studio-dist/client/assets/workflow-BJejeVwQ.js +1 -0
  252. package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-BQKuMdJW.js +3881 -0
  253. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +85 -0
  254. package/studio-dist/server/assets/actions-Bvgj9eb8.js +54 -0
  255. package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
  256. package/studio-dist/server/assets/companion-view-aBady57v.js +33 -0
  257. package/studio-dist/server/assets/createServerFn-F5sAOF8V.js +459 -0
  258. package/studio-dist/server/assets/createServerRpc-tK2lE9R2.js +11 -0
  259. package/studio-dist/server/assets/delivery-path-BkKNjgkf.js +778 -0
  260. package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
  261. package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
  262. package/studio-dist/server/assets/factory-D6xnjedJ.js +2385 -0
  263. package/studio-dist/server/assets/factory-DT3UzHlh.js +68 -0
  264. package/studio-dist/server/assets/model-PyPALjii.js +18 -0
  265. package/studio-dist/server/assets/prepaint-BMke0fo1.js +41 -0
  266. package/studio-dist/server/assets/queries-Ag2iL8q2.js +107 -0
  267. package/studio-dist/server/assets/react-COs0LHn-.js +51 -0
  268. package/studio-dist/server/assets/report-time-DAfzln-N.js +8 -0
  269. package/studio-dist/server/assets/reports-BnUNJVtx.js +126 -0
  270. package/studio-dist/server/assets/rolldown-runtime-DYf_mQCB.js +34 -0
  271. package/studio-dist/server/assets/router-BH--drIx.js +4298 -0
  272. package/studio-dist/server/assets/routes-khSDK1bV.js +361 -0
  273. package/studio-dist/server/assets/search-JAKurDNh.js +36 -0
  274. package/studio-dist/server/assets/shell-CboT2f66.js +51 -0
  275. package/studio-dist/server/assets/skills-MWYnWoKs.js +106 -0
  276. package/studio-dist/server/assets/spec-areas-DcnO6vW-.js +16 -0
  277. package/studio-dist/server/assets/specs-DE3w8hZP.js +155 -0
  278. package/studio-dist/server/assets/start-BW5ovN0k.js +33 -0
  279. package/studio-dist/server/assets/studio-BeltxxKt.js +216 -0
  280. package/studio-dist/server/assets/studio-queries-CLnP9kGu.js +3365 -0
  281. package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
  282. package/studio-dist/server/assets/vault-BGulVoNh.js +70 -0
  283. package/studio-dist/server/assets/vault-CuyyhLyB.js +832 -0
  284. package/studio-dist/server/assets/views-Bd7cRr27.js +82 -0
  285. package/studio-dist/server/assets/warnings-BH05rOuG.js +15 -0
  286. package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
  287. package/studio-dist/server/assets/workflow-BSuIKWqH.js +42 -0
  288. package/studio-dist/server/server.js +16220 -0
  289. package/src/cli/commands/studio/client-asset.ts +0 -16
  290. package/src/cli/commands/studio/views/client.ts +0 -44
  291. package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
  292. package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
  293. package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -102
  294. package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
  295. package/src/cli/commands/studio/views/document.tsx +0 -910
  296. package/src/cli/commands/studio/views/error.tsx +0 -20
  297. package/src/cli/commands/studio/views/markdown.tsx +0 -250
  298. package/src/cli/commands/studio/views/palette.ts +0 -134
  299. package/src/cli/commands/studio/views/reports/index.tsx +0 -44
  300. package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
  301. package/src/cli/commands/studio/views/skills/index.tsx +0 -68
  302. package/src/cli/commands/studio/views/specs/index.tsx +0 -149
  303. package/src/cli/commands/studio/views/studio-client/actions.ts +0 -51
  304. package/src/cli/commands/studio/views/studio-client/companion.ts +0 -13
  305. package/src/cli/commands/studio/views/studio-client/index.ts +0 -32
  306. package/src/cli/commands/studio/views/studio-client/keys.ts +0 -3
  307. package/src/cli/commands/studio/views/studio-client/main.ts +0 -3
  308. package/src/cli/commands/studio/views/studio-client/page.ts +0 -146
  309. package/src/cli/commands/studio/views/studio-client/panels.ts +0 -57
  310. package/src/cli/commands/studio/views/studio-client/reports.ts +0 -122
  311. package/src/cli/commands/studio/views/studio-client/theme.ts +0 -63
  312. package/src/cli/commands/studio/views/studio-client/vault-editor.ts +0 -166
  313. package/src/cli/commands/studio/views/studio-client/vault-pane.ts +0 -202
  314. package/src/cli/commands/studio/views/studio-client/vault-tree.ts +0 -258
  315. package/src/cli/commands/studio/views/studio-client.generated.ts +0 -2
  316. package/src/cli/commands/studio/views/styles.ts +0 -530
  317. package/src/cli/commands/studio/views/terminal.tsx +0 -484
  318. package/src/cli/commands/studio/views/vault/state.ts +0 -41
  319. package/src/cli/commands/studio/views/warnings.tsx +0 -21
  320. package/src/cli/commands/studio/views/workflow/delivery-path.tsx +0 -370
  321. package/src/cli/commands/studio/views/workflow/graph.ts +0 -220
  322. package/src/cli/commands/studio/views/workflow/index.tsx +0 -20
  323. package/src/cli/commands/studio/views/workflow/steps.ts +0 -278
  324. package/src/lib/components/theme.ts +0 -2
  325. package/src/tools/setup/git-utils.ts +0 -30
@@ -9,28 +9,55 @@ import {
9
9
  } from "./access";
10
10
  import { MERMAID_RUNTIME_URL } from "../report/renderer";
11
11
  import { collectStudioInventory, type StudioInventory } from "./inventory";
12
- import { assembleCompanionPayload, type StudioCompanionResponse } from "./payload";
12
+ import {
13
+ assembleCompanionPayload,
14
+ readCompanionWorksetStages,
15
+ type StudioCompanionResponse,
16
+ } from "./payload";
13
17
  import { createReportStore, isReportId, REPORT_LIMITS, type ReportStore } from "./reports";
18
+ import { isWorksetId, WorksetError } from "../../../lib/workset/record";
19
+ import type { WorksetWithStage } from "../../../lib/workset/stages";
20
+ import type { LiveViewer } from "../../../lib/factory/runner/live";
21
+ import {
22
+ createFactoryOutcomes,
23
+ type FactoryOutcomes,
24
+ type Outcomes,
25
+ type OutcomesPorts,
26
+ recordOutcomes,
27
+ } from "../../../lib/factory/outcomes";
28
+ import { LiveSessions } from "../../../lib/factory/outcomes/sessions";
29
+ import { FACTORY_BROKER_ENV, factoryClient, type FactoryClient } from "../../../lib/factory/client";
30
+ import { factoryCredentialResponse } from "./factory-credential";
31
+ import { createWorksetResolver } from "./workset-session";
14
32
  import {
33
+ FACTORY_CREDENTIAL_ROUTE,
34
+ FACTORY_WORKSETS_ROUTE,
15
35
  REPORTS_ROUTE,
16
36
  REPORT_VIEW_PREFIX,
37
+ STUDIO_EVENTS_ROUTE,
17
38
  STUDIO_HOSTNAME,
18
- VAULT_CHANGES_ROUTE,
19
- VAULT_DIR_ROUTE,
20
- VAULT_FILTER_ROUTE,
21
- VAULT_PANE_ROUTE,
39
+ type StudioEvent,
40
+ TERMINAL_ASSET_PREFIX,
41
+ TERMINAL_SESSIONS_END_ROUTE,
42
+ TERMINAL_SESSIONS_ROUTE,
43
+ TERMINAL_SOCKET_ROUTE,
44
+ VAULT_EVENTS_ROUTE,
22
45
  } from "./routes";
23
46
  import {
24
47
  COMPANION_DIGEST_PATTERN,
25
48
  COMPANION_PARAM,
26
49
  companionDigest,
50
+ modePolicy,
27
51
  parse,
28
52
  parseVaultSelection,
29
53
  resolveCompanion,
30
- type StudioVaultSelection,
54
+ type StudioModePolicy,
55
+ type StudioProfile,
56
+ type StudioSelection,
31
57
  } from "./selection";
58
+ import { errorMessage } from "../../../runtime/error-message";
32
59
  import { createStudioSnapshotCache, type StudioSnapshotCache } from "./snapshot";
33
- import type { StudioPage, StudioVaultPage } from "./views/model";
60
+ import type { StudioPage } from "./views/model";
34
61
  import { createVaultManager, resolveVaultPath, VaultPathError, type VaultManager } from "./vault";
35
62
  import {
36
63
  DEFAULT_DETACH_MINUTES,
@@ -38,7 +65,8 @@ import {
38
65
  type TerminalConnection,
39
66
  type TerminalRegistryOptions,
40
67
  } from "./terminal";
41
- import { studioClientAsset } from "./client-asset";
68
+ import type { StudioFormField, StudioServices } from "./services";
69
+ import { studioAppAsset, type StudioApp } from "./studio-app";
42
70
  import { terminalAsset } from "./terminal-assets";
43
71
  import {
44
72
  createLaunchResolver,
@@ -48,8 +76,8 @@ import {
48
76
 
49
77
  export { STUDIO_HOSTNAME } from "./routes";
50
78
 
51
- /** Read methods; every other method is refused before any collection runs. */
52
- const READ_METHODS = new Set(["GET", "HEAD"]);
79
+ /** Where Start's server functions are called; the only POSTs the application makes. */
80
+ const STUDIO_APP_CALL_PREFIX = "/_serverFn/";
53
81
 
54
82
  /** The socket Bun hands a WebSocket handler; `data` is what the upgrade attached. */
55
83
  export interface StudioSocket {
@@ -103,13 +131,21 @@ export interface StudioServerHandle {
103
131
  export interface StudioServerDeps {
104
132
  collectStudioInventory?: () => Promise<StudioInventory>;
105
133
  assembleCompanionPayload?: (companionPath: string) => Promise<StudioCompanionResponse>;
106
- renderDocument?: (page: StudioPage) => string | Promise<string>;
107
134
  serve?: (options: StudioServeOptions) => StudioBoundServer;
108
135
  snapshots?: StudioSnapshotCache;
109
136
  vault?: VaultManager;
110
137
  reports?: ReportStore;
111
138
  terminal?: Partial<TerminalRegistryOptions>;
112
139
  launchableAgents?: typeof launchableAgents;
140
+ /**
141
+ * The factory's Outcomes, built from the ports Studio creates first for the companion it
142
+ * serves; from the environment in factory mode when absent.
143
+ */
144
+ factoryOutcomes?: (portsFor: (companionPath: string) => OutcomesPorts) => FactoryOutcomes | null;
145
+ /** A companion's Workset stages; read from OpenSpec when absent. */
146
+ worksetStages?: (companionPath: string) => Promise<{ worksets: WorksetWithStage[] }>;
147
+ /** The factory broker's client; from the environment when absent, null outside factory mode. */
148
+ factoryClient?: FactoryClient | null;
113
149
  }
114
150
 
115
151
  export interface StudioServerOptions {
@@ -129,55 +165,23 @@ export interface StudioServerOptions {
129
165
  idleTimeout?: number;
130
166
  /** Terminal launches skip companion Git synchronization. */
131
167
  noGit?: boolean;
168
+ /** Which Studio modes are enabled; `standard` when absent. Never read from a request. */
169
+ profile?: StudioProfile;
170
+ /** Studio's built application, loaded by the studio command. */
171
+ app?: StudioApp | null;
132
172
  }
133
173
 
134
- /**
135
- * Loaded at the point of use so no other command pays for the renderer: `hono/jsx`
136
- * is reachable from the studio path alone.
137
- */
138
- async function renderStudioDocument(page: StudioPage): Promise<string> {
139
- const views = await import("./views/document");
140
- return views.renderStudioDocument(page);
141
- }
142
-
143
- async function renderVaultView(page: StudioPage): Promise<string> {
144
- const views = await import("./views/document");
145
- return views.renderVaultView(page);
146
- }
147
-
148
- async function renderVaultPane(page: StudioPage): Promise<string> {
149
- const views = await import("./views/document");
150
- return views.renderVaultPane(page);
151
- }
152
-
153
- async function renderVaultChildren(page: StudioPage): Promise<string | null> {
154
- const views = await import("./views/document");
155
- return views.renderVaultChildren(page);
156
- }
157
-
158
- async function renderVaultMatches(page: StudioPage, query: string): Promise<string> {
159
- const views = await import("./views/document");
160
- return views.renderVaultMatches(page, query);
161
- }
162
-
163
- /** Keep the CLI entry free of eager Studio view imports. */
164
- async function collectVaultState(
165
- vault: VaultManager,
166
- companionPath: string,
167
- selection: StudioVaultSelection,
168
- options: { tree: "prefetch" | "await" | "skip" },
169
- ): Promise<StudioVaultPage> {
170
- const { vaultState } = await import("./views/vault/state");
171
- return vaultState(vault, companionPath, selection, options);
172
- }
174
+ /** Answered to a document request when no Studio build is installed; carries no companion data. */
175
+ const MISSING_BUILD_PAGE = `<!doctype html>
176
+ <html lang="en">
177
+ <head><meta charset="utf-8"><title>Mate Studio</title></head>
178
+ <body><p>Studio's application build is missing. Run <code>bun run build</code> in <code>packages/mate-studio</code>, then reload.</p></body>
179
+ </html>
180
+ `;
173
181
 
174
- /** A pane is never a refresh, so the listing it skips is not asked to be rebuilt. */
175
- function plainSelection(selection: StudioVaultSelection): StudioVaultSelection {
176
- return { ...selection, refresh: false };
177
- }
178
-
179
- function html(body: string): Response {
182
+ function html(body: string, status = 200): Response {
180
183
  return new Response(body, {
184
+ status,
181
185
  headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
182
186
  });
183
187
  }
@@ -191,6 +195,59 @@ const TOKEN_REQUIRED_PAGE = `<!doctype html>
191
195
  If the token was pinned with <code>--token</code> or <code>MATE_STUDIO_TOKEN</code>,
192
196
  open this address with <code>?token=</code> followed by that value.</p></main></body></html>`;
193
197
 
198
+ /** A Workset's run log, or its live stream when the second group matched. */
199
+ const FACTORY_LOG = new RegExp(`^${FACTORY_WORKSETS_ROUTE}/([^/]+)/log(/stream)?$`);
200
+
201
+ /**
202
+ * What a route is, for its guard. A read needs the token where the invocation requires it
203
+ * for reading; a write also needs the same origin, the token for saving and, when it names
204
+ * a reason, the write path; a terminal call needs the token for the terminal and, when
205
+ * privileged, the same origin; a session call is checked by its own bearer credential only.
206
+ */
207
+ type RouteKind =
208
+ | { kind: "read"; methods: readonly string[] }
209
+ | { kind: "write"; methods: readonly string[]; writable?: string }
210
+ | { kind: "terminal"; methods: readonly string[]; privileged: boolean }
211
+ | { kind: "session"; methods: readonly string[] };
212
+
213
+ const ORIGIN_REASON = {
214
+ write: "a change must come from Studio's own page",
215
+ terminal: "the terminal is reachable only from Studio's own page",
216
+ } as const;
217
+
218
+ const READS = ["GET", "HEAD"] as const;
219
+
220
+ /** Every route core answers, by kind; the rest are reads the application answers. */
221
+ function routeOf(url: URL, method: string, hasApp: boolean): RouteKind {
222
+ const { pathname } = url;
223
+ if (pathname === REPORTS_ROUTE && method === "POST")
224
+ return { kind: "session", methods: ["POST"] };
225
+ if (pathname === FACTORY_CREDENTIAL_ROUTE) {
226
+ return method === "GET" || method === "HEAD"
227
+ ? { kind: "read", methods: [method] }
228
+ : {
229
+ kind: "write",
230
+ methods: [method],
231
+ writable: "start Studio with --writable to set the agent credential",
232
+ };
233
+ }
234
+ if (pathname === TERMINAL_SOCKET_ROUTE) {
235
+ return { kind: "terminal", methods: READS, privileged: true };
236
+ }
237
+ if (pathname === TERMINAL_SESSIONS_END_ROUTE) {
238
+ return { kind: "terminal", methods: ["POST"], privileged: true };
239
+ }
240
+ if (pathname.startsWith(`${TERMINAL_SOCKET_ROUTE}/`)) {
241
+ return { kind: "terminal", methods: READS, privileged: false };
242
+ }
243
+ // A server function is a read when called with GET and a write when called with POST; the
244
+ // write path for its changes is checked by the services it calls.
245
+ if (hasApp && pathname.startsWith(STUDIO_APP_CALL_PREFIX) && method === "POST") {
246
+ return { kind: "write", methods: ["POST"] };
247
+ }
248
+ return { kind: "read", methods: READS };
249
+ }
250
+
194
251
  function refused(reason: string, status: number): Response {
195
252
  return new Response(JSON.stringify({ reason }), {
196
253
  status,
@@ -216,14 +273,10 @@ const REPORT_CSP = [
216
273
  "connect-src 'none'",
217
274
  ].join("; ");
218
275
 
219
- /** Page-facing report announcement; carries no path and no content. */
220
- interface ReportPublishedEvent {
221
- type: "report-published";
222
- /** Digest of the companion the report belongs to. */
223
- companion: string;
276
+ /** A published report as open pages are told of it; carries no path and no content. */
277
+ interface PublishedReport {
224
278
  id: string;
225
279
  title: string;
226
- createdAt: number;
227
280
  }
228
281
 
229
282
  /**
@@ -256,9 +309,17 @@ async function readCapped(request: Request, limit: number): Promise<string | nul
256
309
  return over ? null : Buffer.concat(chunks).toString("utf8");
257
310
  }
258
311
 
312
+ const NOT_WRITABLE = "start Studio with --writable to create or start Worksets";
313
+
259
314
  const TOKEN_REASON =
260
315
  "Studio's access token is required; open the address Studio printed when it started";
261
316
 
317
+ const NO_COMPANION = "no registered companion was selected";
318
+
319
+ function notFound(): Response {
320
+ return new Response("not found", { status: 404 });
321
+ }
322
+
262
323
  function json(value: unknown, status = 200): Response {
263
324
  return new Response(JSON.stringify(value), {
264
325
  status,
@@ -269,12 +330,13 @@ function json(value: unknown, status = 200): Response {
269
330
  interface StudioFetch {
270
331
  (request: Request, server?: StudioUpgrader): Promise<Response | undefined>;
271
332
  terminal: TerminalRegistry | null;
333
+ services: StudioServices;
272
334
  close(): Promise<void>;
273
335
  }
274
336
 
275
337
  export interface StudioFetchOptions extends Pick<
276
338
  StudioServerOptions,
277
- "writable" | "launchCompanion" | "noGit" | "detachMinutes"
339
+ "writable" | "launchCompanion" | "noGit" | "detachMinutes" | "profile"
278
340
  > {
279
341
  access?: StudioAccess;
280
342
  /** Loopback origin the terminal's processes publish to; read at spawn. */
@@ -283,6 +345,8 @@ export interface StudioFetchOptions extends Pick<
283
345
  publicOrigin?: string | null;
284
346
  /** Enables the terminal; the invocation sets its default detach window. */
285
347
  terminal?: boolean;
348
+ /** Studio's built application; paths the handler does not serve itself go to it. */
349
+ app?: StudioApp | null;
286
350
  }
287
351
 
288
352
  /**
@@ -300,11 +364,42 @@ export function createStudioFetch(
300
364
  ): StudioFetch {
301
365
  const inventory = deps.collectStudioInventory ?? collectStudioInventory;
302
366
  const companion = deps.assembleCompanionPayload ?? assembleCompanionPayload;
303
- const render = deps.renderDocument ?? renderStudioDocument;
304
367
  const snapshots =
305
368
  deps.snapshots ?? createStudioSnapshotCache({ assembleCompanionPayload: companion });
306
369
  const vault = deps.vault ?? createVaultManager();
307
370
  const writable = options.writable === true;
371
+ const policy = modePolicy(options.profile ?? "standard");
372
+ const broker = deps.factoryClient !== undefined ? deps.factoryClient : factoryClient();
373
+ const reports = deps.reports ?? createReportStore();
374
+ const stagesOf = deps.worksetStages ?? ((path: string) => readCompanionWorksetStages(path));
375
+ // Created before the terminal and the Outcomes, so neither needs the other.
376
+ const sessions = new LiveSessions();
377
+ const launchCompanion = options.launchCompanion ?? null;
378
+ const outcomesPorts = (companionPath: string): OutcomesPorts => ({
379
+ stages: () => stagesOf(companionPath),
380
+ reports: {
381
+ publish: (report) => reports.publish(companionDigest(companionPath), report),
382
+ ids: async () =>
383
+ (await reports.list(companionDigest(companionPath))).map((report) => report.id),
384
+ },
385
+ sessions,
386
+ });
387
+ const outcomes = (() => {
388
+ try {
389
+ if (deps.factoryOutcomes) return deps.factoryOutcomes(outcomesPorts);
390
+ return createFactoryOutcomes(launchCompanion, outcomesPorts(launchCompanion ?? ""));
391
+ } catch (error) {
392
+ process.stderr.write(
393
+ `mate studio: the factory runner did not start: ${(error as Error).message}\n`,
394
+ );
395
+ return null;
396
+ }
397
+ })();
398
+ /** A companion's Outcomes: the factory's for the companion it runs, record-only otherwise. */
399
+ const outcomesFor = (companionPath: string): Outcomes =>
400
+ outcomes?.companionPath === companionPath
401
+ ? outcomes
402
+ : recordOutcomes(companionPath, () => stagesOf(companionPath));
308
403
  const access =
309
404
  options.access ??
310
405
  createStudioAccess({
@@ -313,11 +408,9 @@ export function createStudioFetch(
313
408
  hostname: STUDIO_HOSTNAME,
314
409
  port: () => 80,
315
410
  });
316
- const reports = deps.reports ?? createReportStore();
317
411
  void reports.cleanup().catch(() => {});
318
412
  const publicOrigin = options.publicOrigin ? normalizeOrigin(options.publicOrigin) : null;
319
- const reportListeners = new Map<string, Set<(event: ReportPublishedEvent) => void>>();
320
- const launchCompanion = options.launchCompanion ?? null;
413
+ const reportListeners = new Map<string, Set<(event: PublishedReport) => void>>();
321
414
  const agentsFor = deps.launchableAgents ?? launchableAgents;
322
415
  const terminal = options.terminal
323
416
  ? new TerminalRegistry({
@@ -328,12 +421,25 @@ export function createStudioFetch(
328
421
  launchableAgents: (companionPath) => agentsFor(companionPath),
329
422
  }),
330
423
  mateCommand: process.argv.slice(0, 2),
424
+ sessions,
425
+ ...(process.env[FACTORY_BROKER_ENV]
426
+ ? {
427
+ resolveWorkset: createWorksetResolver({
428
+ collectInventory: inventory,
429
+ launchCompanion,
430
+ mateCommand: process.argv.slice(0, 2),
431
+ env: process.env,
432
+ noGit: options.noGit === true,
433
+ // A person in control continues the factory's own conversation.
434
+ takenOver: async (id) => (outcomes ? outcomes.takenOver(id) : null),
435
+ }),
436
+ }
437
+ : {}),
331
438
  noGit: options.noGit === true,
332
439
  reportUrl: options.reportOrigin,
333
440
  ...deps.terminal,
334
441
  })
335
442
  : null;
336
-
337
443
  /** Stores a report for the live terminal session holding the bearer credential. */
338
444
  const publishReport = async (request: Request): Promise<Response> => {
339
445
  const token = readBearer(request);
@@ -362,13 +468,7 @@ export function createStudioFetch(
362
468
  html: body.html,
363
469
  });
364
470
  for (const notify of reportListeners.get(digest) ?? []) {
365
- notify({
366
- type: "report-published",
367
- companion: digest,
368
- id: stored.id,
369
- title: stored.title,
370
- createdAt: stored.createdAt,
371
- });
471
+ notify({ id: stored.id, title: stored.title });
372
472
  }
373
473
  const path = `${REPORT_VIEW_PREFIX}${stored.id}`;
374
474
  return json({
@@ -378,6 +478,121 @@ export function createStudioFetch(
378
478
  });
379
479
  };
380
480
 
481
+ /** One document's model, with the factory, report and terminal state its address needs. */
482
+ const collectPage = async (url: URL): Promise<StudioPage> => {
483
+ const page = await collectStudioPage(url, policy, inventory, snapshots, vault, writable);
484
+ if (page.payload && page.companion && isAnalystOverview(page.selection)) {
485
+ page.reports = await reports.list(companionDigest(page.companion.path)).then(
486
+ (listed) => listed.map(({ id, title, createdAt }) => ({ id, title, createdAt })),
487
+ () => null,
488
+ );
489
+ }
490
+ page.renderedAt = Date.now();
491
+ page.factoryRuns = page.companion ? await outcomesFor(page.companion.path).runs() : null;
492
+ if (terminal) {
493
+ const target = await effectiveLaunchCompanion(
494
+ page.inventory,
495
+ launchCompanion,
496
+ page.selection.companionDigest,
497
+ );
498
+ page.worksetSessions = process.env[FACTORY_BROKER_ENV]
499
+ ? Object.fromEntries(
500
+ terminal
501
+ .list()
502
+ .flatMap((session) => (session.workset ? [[session.workset.id, session.id]] : [])),
503
+ )
504
+ : null;
505
+ page.terminal = {
506
+ pinned: launchCompanion !== null,
507
+ target: target ? { path: target.path, digest: companionDigest(target.path) } : null,
508
+ agents: target ? await agentsFor(target.path) : [],
509
+ };
510
+ }
511
+ return page;
512
+ };
513
+
514
+ /** A registered companion by digest, or a refusal the caller reports. */
515
+ const companionPathOf = async (digest: string): Promise<string> => {
516
+ const selected = await selectedCompanion(digest || null, inventory);
517
+ if (!selected) throw new WorksetError(NO_COMPANION);
518
+ return selected.path;
519
+ };
520
+
521
+ /** Viewers of a companion's board, by digest; told when an Outcome or run changes. */
522
+ const boardListeners = new Map<string, Set<() => void>>();
523
+ const boardChanged = (digest: string) => {
524
+ for (const notify of boardListeners.get(digest) ?? []) notify();
525
+ };
526
+ if (outcomes) {
527
+ const digest = companionDigest(outcomes.companionPath);
528
+ outcomes.onChanged(() => boardChanged(digest));
529
+ }
530
+
531
+ const services: StudioServices = {
532
+ writable,
533
+ factoryMode: broker !== null,
534
+ modePolicy: policy,
535
+ page: collectPage,
536
+ worksetAction: async (digest, id, action, field: StudioFormField) => {
537
+ if (!writable) throw new WorksetError(NOT_WRITABLE);
538
+ await outcomesFor(await companionPathOf(digest)).act(id, action, field);
539
+ boardChanged(digest);
540
+ },
541
+ createOutcome: async (digest, field) => {
542
+ if (!writable) throw new WorksetError(NOT_WRITABLE);
543
+ await outcomesFor(await companionPathOf(digest)).create(field);
544
+ boardChanged(digest);
545
+ },
546
+ vault: async (digest, request) => {
547
+ const { vaultView } = await import("./views/vault/view");
548
+ return vaultView(vault, await companionPathOf(digest), request);
549
+ },
550
+ vaultChildren: async (digest, dir) => {
551
+ const { vaultChildren } = await import("./views/vault/view");
552
+ return vaultChildren(vault, await companionPathOf(digest), dir);
553
+ },
554
+ vaultMatches: async (digest, query) => {
555
+ const { vaultMatches } = await import("./views/vault/view");
556
+ return vaultMatches(vault, await companionPathOf(digest), query);
557
+ },
558
+ vaultSave: async (digest, path, content, token) => {
559
+ if (!writable) throw new VaultPathError("start Studio with --writable to enable saving");
560
+ return vault.save(await companionPathOf(digest), path, content, token);
561
+ },
562
+ };
563
+ const app = options.app ?? null;
564
+
565
+ /** The route's refusal under its kind, decided once before it acts (design D4); `null` lets it act. */
566
+ const refusalFor = (
567
+ route: Exclude<RouteKind, { kind: "session" }>,
568
+ request: Request,
569
+ url: URL,
570
+ acceptedOrigin: string,
571
+ ): Response | null => {
572
+ if (access.requires("read") && !access.hasToken(request)) {
573
+ if (url.pathname !== "/") return refused(TOKEN_REASON, 401);
574
+ return html(TOKEN_REQUIRED_PAGE, 401);
575
+ }
576
+ if (route.kind === "read") return null;
577
+ if (route.kind === "terminal" && !terminal) {
578
+ return refused("start Studio with --writable --terminal to enable the terminal", 404);
579
+ }
580
+ const privileged = route.kind === "write" || route.privileged;
581
+ if (privileged && !access.originMatches(request, acceptedOrigin)) {
582
+ return refused(ORIGIN_REASON[route.kind], 403);
583
+ }
584
+ if (
585
+ access.requires(route.kind === "write" ? "save" : "terminal") &&
586
+ !access.hasToken(request)
587
+ ) {
588
+ return refused(TOKEN_REASON, 401);
589
+ }
590
+ if (route.kind === "write" && route.writable && !writable) {
591
+ return refused(route.writable, 403);
592
+ }
593
+ return null;
594
+ };
595
+
381
596
  const handler = async (
382
597
  request: Request,
383
598
  server?: StudioUpgrader,
@@ -389,23 +604,11 @@ export function createStudioFetch(
389
604
  const exchanged = exchangeStudioToken(request, access, acceptedOrigin);
390
605
  if (exchanged) return exchanged;
391
606
 
392
- if (url.pathname === REPORTS_ROUTE && request.method === "POST") {
393
- return publishReport(request);
394
- }
395
-
396
- const isSave = url.pathname === "/api/vault/save";
397
- const isEnd = url.pathname === "/api/terminal/sessions/end";
398
- const isPost = isSave || isEnd;
399
- if (isPost && request.method !== "POST") {
400
- return new Response(`${isSave ? "vault save" : "ending a session"} requires POST`, {
401
- status: 405,
402
- headers: { allow: "POST" },
403
- });
404
- }
405
- if (!READ_METHODS.has(request.method) && !(isPost && request.method === "POST")) {
406
- return new Response("studio serves read requests only", {
607
+ const route = routeOf(url, request.method, app !== null);
608
+ if (!route.methods.includes(request.method)) {
609
+ return new Response(`${request.method} is not served here`, {
407
610
  status: 405,
408
- headers: { allow: isPost ? "POST" : "GET, HEAD" },
611
+ headers: { allow: route.methods.join(", ") },
409
612
  });
410
613
  }
411
614
 
@@ -414,18 +617,14 @@ export function createStudioFetch(
414
617
  ? new Response(null, { status: response.status, headers: response.headers })
415
618
  : response;
416
619
 
417
- if (access.requires("read") && !access.hasToken(request)) {
418
- if (url.pathname === "/") {
419
- const page = html(TOKEN_REQUIRED_PAGE);
420
- return respond(new Response(page.body, { status: 401, headers: page.headers }));
421
- }
422
- return respond(refused(TOKEN_REASON, 401));
423
- }
620
+ if (route.kind === "session") return publishReport(request);
621
+ const refusal = refusalFor(route, request, url, acceptedOrigin);
622
+ if (refusal) return respond(refusal);
424
623
 
425
624
  if (url.pathname === REPORTS_ROUTE) {
426
625
  const digest = url.searchParams.get(COMPANION_PARAM) ?? "";
427
626
  if (!COMPANION_DIGEST_PATTERN.test(digest)) {
428
- return respond(json({ reason: "no registered companion was selected" }, 400));
627
+ return respond(json({ reason: NO_COMPANION }, 400));
429
628
  }
430
629
  return respond(json({ reports: await reports.list(digest) }));
431
630
  }
@@ -433,7 +632,7 @@ export function createStudioFetch(
433
632
  if (url.pathname.startsWith(REPORT_VIEW_PREFIX)) {
434
633
  const id = url.pathname.slice(REPORT_VIEW_PREFIX.length);
435
634
  const stored = isReportId(id) ? await reports.read(id) : null;
436
- if (stored === null) return respond(new Response("not found", { status: 404 }));
635
+ if (stored === null) return respond(notFound());
437
636
  return respond(
438
637
  new Response(stored, {
439
638
  headers: {
@@ -447,35 +646,31 @@ export function createStudioFetch(
447
646
  );
448
647
  }
449
648
 
450
- const clientAsset = await studioClientAsset(url.pathname);
451
- if (clientAsset) return respond(clientAsset);
649
+ if (url.pathname === FACTORY_CREDENTIAL_ROUTE) {
650
+ if (broker === null) return respond(notFound());
651
+ return respond(await factoryCredentialResponse(broker, request));
652
+ }
452
653
 
453
- if (url.pathname.startsWith("/studio/terminal/") && terminal) {
454
- const asset = await terminalAsset(url.pathname);
654
+ if (app) {
655
+ const asset = await studioAppAsset(app, url.pathname);
455
656
  if (asset) return respond(asset);
456
657
  }
457
658
 
458
- if (url.pathname === "/api/terminal" || url.pathname.startsWith("/api/terminal/")) {
459
- if (!terminal) {
460
- return respond(
461
- refused("start Studio with --writable --terminal to enable the terminal", 404),
462
- );
463
- }
464
- const privileged = url.pathname === "/api/terminal" || isEnd;
465
- if (privileged && !access.originMatches(request, acceptedOrigin)) {
466
- return respond(refused("the terminal is reachable only from Studio's own page", 403));
467
- }
468
- if (access.requires("terminal") && !access.hasToken(request)) {
469
- return respond(refused(TOKEN_REASON, 401));
470
- }
471
- if (url.pathname === "/api/terminal") {
659
+ // The terminal's asset prefix is core's own, with or without the terminal.
660
+ if (url.pathname.startsWith(TERMINAL_ASSET_PREFIX)) {
661
+ const asset = terminal ? await terminalAsset(url.pathname) : null;
662
+ return respond(asset ?? notFound());
663
+ }
664
+
665
+ if (route.kind === "terminal" && terminal) {
666
+ if (url.pathname === TERMINAL_SOCKET_ROUTE) {
472
667
  if (request.headers.get("upgrade")?.toLowerCase() !== "websocket" || !server) {
473
668
  return respond(refused("the terminal is a WebSocket endpoint", 426));
474
669
  }
475
670
  if (server.upgrade(request, { data: {} })) return undefined;
476
671
  return respond(refused("the terminal connection could not be upgraded", 400));
477
672
  }
478
- if (url.pathname === "/api/terminal/sessions") {
673
+ if (url.pathname === TERMINAL_SESSIONS_ROUTE) {
479
674
  const now = Date.now();
480
675
  return respond(
481
676
  json({
@@ -485,12 +680,13 @@ export function createStudioFetch(
485
680
  companion: companionDigest(session.companionPath),
486
681
  companionPath: session.companionPath,
487
682
  attached: session.attached,
683
+ ...(session.workset ? { workset: session.workset } : {}),
488
684
  ageSeconds: Math.max(0, Math.round((now - session.startedAt) / 1000)),
489
685
  })),
490
686
  }),
491
687
  );
492
688
  }
493
- if (isEnd) {
689
+ if (url.pathname === TERMINAL_SESSIONS_END_ROUTE) {
494
690
  let body: { id?: unknown };
495
691
  try {
496
692
  body = (await request.json()) as typeof body;
@@ -502,224 +698,50 @@ export function createStudioFetch(
502
698
  }
503
699
  return respond(json({ ended: body.id }));
504
700
  }
505
- return respond(new Response("not found", { status: 404 }));
701
+ return respond(notFound());
506
702
  }
507
703
 
508
- if (url.pathname === "/api/vault/tree") {
509
- const selection = parseVaultSelection(url);
510
- const selected = await selectedCompanion(selection.companionDigest, inventory);
511
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
512
- try {
513
- return respond(json(await vault.tree(selected.path, selection.refresh)));
514
- } catch (error) {
515
- return respond(
516
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
517
- );
518
- }
519
- }
520
-
521
- if (url.pathname === "/api/vault/view") {
522
- const collected = await inventory();
523
- const selection = parseVaultSelection(url);
524
- const companion = resolveCompanion(collected, selection.companionDigest);
525
- if (!companion) return respond(json({ reason: "no registered companion was selected" }, 400));
526
- const state = await collectVaultState(vault, companion.path, selection, { tree: "await" });
527
- return respond(
528
- new Response(
529
- await renderVaultView({
530
- inventory: collected,
531
- selection,
532
- companion,
533
- payload: null,
534
- error: null,
535
- collectedAt: null,
536
- writable,
537
- vault: state,
538
- terminal: null,
539
- }),
540
- { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } },
541
- ),
542
- );
543
- }
544
-
545
- if (url.pathname === VAULT_PANE_ROUTE) {
546
- const collected = await inventory();
547
- const selection = parseVaultSelection(url);
548
- const companion = resolveCompanion(collected, selection.companionDigest);
549
- if (!companion) return respond(json({ reason: "no registered companion was selected" }, 400));
550
- const state = await collectVaultState(vault, companion.path, plainSelection(selection), {
551
- tree: "skip",
552
- });
553
- return respond(
554
- new Response(
555
- await renderVaultPane({
556
- inventory: collected,
557
- selection,
558
- companion,
559
- payload: null,
560
- error: null,
561
- collectedAt: null,
562
- writable,
563
- vault: state,
564
- terminal: null,
565
- }),
566
- { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } },
567
- ),
568
- );
569
- }
570
-
571
- if (url.pathname === VAULT_DIR_ROUTE || url.pathname === VAULT_FILTER_ROUTE) {
572
- const selection = parseVaultSelection(url);
573
- const selected = await selectedCompanion(selection.companionDigest, inventory);
574
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
575
- let listed;
576
- try {
577
- listed = await vault.tree(selected.path);
578
- } catch (error) {
579
- return respond(
580
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
581
- );
582
- }
583
- const page: StudioPage = {
584
- inventory: await inventory(),
585
- selection,
586
- companion: selected,
587
- payload: null,
588
- error: null,
589
- collectedAt: null,
590
- writable,
591
- vault: {
592
- tree: listed.tree,
593
- open: null,
594
- refusal: null,
595
- incoming: null,
596
- overwritten: null,
597
- watching: listed.watching,
598
- warning: listed.warning,
599
- generation: listed.generation,
600
- },
601
- terminal: null,
602
- };
603
- const headers = {
604
- "content-type": "text/html; charset=utf-8",
605
- "cache-control": "no-store",
606
- "x-vault-generation": String(listed.generation),
607
- };
608
- if (url.pathname === VAULT_FILTER_ROUTE) {
609
- const matches = await renderVaultMatches(page, url.searchParams.get("q") ?? "");
610
- return respond(new Response(matches, { headers }));
611
- }
612
- const children = await renderVaultChildren(page);
613
- if (children === null) {
614
- return respond(json({ reason: "that folder is not in the listed tree" }, 404));
615
- }
616
- return respond(new Response(children, { headers }));
617
- }
618
-
619
- if (url.pathname === VAULT_CHANGES_ROUTE) {
620
- const selection = parseVaultSelection(url);
621
- const selected = await selectedCompanion(selection.companionDigest, inventory);
622
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
704
+ if (url.pathname === STUDIO_EVENTS_ROUTE) {
705
+ const digest = url.searchParams.get(COMPANION_PARAM) ?? "";
706
+ const selected = await selectedCompanion(digest || null, inventory);
707
+ if (!selected) return respond(json({ reason: NO_COMPANION }, 400));
623
708
  server?.timeout?.(request, 0);
624
- const reportsOnly = url.searchParams.get("scope") === "reports";
625
- return respond(
626
- changeStream(vault, selected.path, reportsOnly, (notify) => {
627
- const digest = companionDigest(selected.path);
628
- const set = reportListeners.get(digest) ?? new Set();
629
- set.add(notify);
630
- reportListeners.set(digest, set);
631
- return () => {
632
- set.delete(notify);
633
- if (set.size === 0) reportListeners.delete(digest);
634
- };
635
- }),
636
- );
637
- }
638
-
639
- if (url.pathname === "/api/vault/file") {
640
- const selection = parseVaultSelection(url);
641
- const selected = await selectedCompanion(selection.companionDigest, inventory);
642
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
643
- try {
644
- return respond(json(await vault.open(selected.path, selection.openPath ?? "")));
645
- } catch (error) {
646
- return respond(
647
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
648
- );
649
- }
709
+ return respond(studioEvents(vault, selected.path, boardListeners, reportListeners));
650
710
  }
651
711
 
652
- if (url.pathname === "/api/vault/events") {
653
- const selection = parseVaultSelection(url);
712
+ if (url.pathname === VAULT_EVENTS_ROUTE) {
713
+ const selection = parseVaultSelection(url, policy);
654
714
  const selected = await selectedCompanion(selection.companionDigest, inventory);
655
- if (!selected) return respond(json({ reason: "no registered companion was selected" }, 400));
715
+ if (!selected) return respond(json({ reason: NO_COMPANION }, 400));
656
716
  try {
657
717
  const opened = await resolveVaultPath(selected.path, selection.openPath ?? "");
658
718
  server?.timeout?.(request, 0);
659
719
  return respond(vaultEvents(vault, selected.path, opened.relative));
660
720
  } catch (error) {
661
- return respond(
662
- json({ reason: error instanceof Error ? error.message : String(error) }, 400),
663
- );
721
+ return respond(json({ reason: errorMessage(error) }, 400));
664
722
  }
665
723
  }
666
724
 
667
- if (isSave) {
668
- if (!access.originMatches(request, acceptedOrigin)) {
669
- return respond(refused("a save must come from Studio's own page", 403));
670
- }
671
- if (access.requires("save") && !access.hasToken(request)) {
672
- return respond(refused(TOKEN_REASON, 401));
673
- }
674
- if (!writable)
675
- return respond(json({ reason: "start Studio with --writable to enable saving" }, 403));
676
- let body: { companion?: string; path?: string; content?: string; token?: string };
677
- try {
678
- body = (await request.json()) as typeof body;
679
- } catch {
680
- return respond(json({ reason: "save requires a JSON body" }, 400));
681
- }
682
- const selected = await selectedCompanion(
683
- typeof body.companion === "string" ? body.companion : null,
684
- inventory,
725
+ const logMatch = FACTORY_LOG.exec(url.pathname);
726
+ if (logMatch) {
727
+ const id = decodeURIComponent(logMatch[1]!);
728
+ if (!outcomes || !isWorksetId(id)) return respond(notFound());
729
+ if (logMatch[2]) return respond(logStream(outcomes, id));
730
+ return respond(
731
+ new Response(await outcomes.log(id), {
732
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
733
+ }),
685
734
  );
686
- if (!selected || typeof body.path !== "string" || typeof body.content !== "string") {
687
- return respond(
688
- json({ reason: "save requires a registered companion, path, and content" }, 400),
689
- );
690
- }
691
- try {
692
- const result = await vault.save(selected.path, body.path, body.content, body.token);
693
- return respond(json(result, result.kind === "conflict" ? 409 : 200));
694
- } catch (error) {
695
- return respond(
696
- json(
697
- { reason: error instanceof Error ? error.message : String(error) },
698
- error instanceof VaultPathError ? 400 : 500,
699
- ),
700
- );
701
- }
702
735
  }
703
736
 
704
- if (url.pathname !== "/") return respond(new Response("not found", { status: 404 }));
705
-
706
- const page = await collectStudioPage(url, inventory, snapshots, vault, writable);
707
- if (terminal) {
708
- const target = await effectiveLaunchCompanion(
709
- page.inventory,
710
- launchCompanion,
711
- page.selection.companionDigest,
712
- );
713
- page.terminal = {
714
- pinned: launchCompanion !== null,
715
- target: target ? { path: target.path, digest: companionDigest(target.path) } : null,
716
- agents: target ? await agentsFor(target.path) : [],
717
- };
718
- }
719
- return respond(html(await render(page)));
737
+ // Everything else is the application's: its documents, views and server functions.
738
+ if (app) return respond(await app.fetch(request, { context: { studio: services } }));
739
+ if (url.pathname === "/") return respond(html(MISSING_BUILD_PAGE));
740
+ return respond(notFound());
720
741
  };
721
742
 
722
743
  handler.terminal = terminal;
744
+ handler.services = services;
723
745
  handler.close = async () => {
724
746
  vault.stop();
725
747
  await terminal?.stopAll();
@@ -765,49 +787,79 @@ function eventStream(
765
787
  });
766
788
  }
767
789
 
768
- function vaultEvents(vault: VaultManager, companionPath: string, requestedPath: string): Response {
769
- return eventStream("studio vault events", (send) =>
770
- vault.subscribe(companionPath, requestedPath, send),
771
- );
772
- }
773
-
774
790
  /**
775
- * Typed events for one companion: `vault-tree-changed` (a generation) and
776
- * `report-published`. No paths and no file content leave through this stream.
777
- * `reportsOnly` skips the vault subscription, which starts a watcher and listing.
791
+ * A Workset's run log as it grows: one `replay` (the stored log and the text still
792
+ * streaming), then the live events. Read-only; leaving never touches the run.
778
793
  */
779
- function changeStream(
794
+ function logStream(live: { watch(id: string): LiveViewer }, id: string): Response {
795
+ return eventStream("studio factory log", (send) => {
796
+ const viewer = live.watch(id);
797
+ void (async () => {
798
+ send({ type: "replay", ...(await viewer.replay) });
799
+ // oxlint-disable-next-line no-await-in-loop -- events arrive one at a time, in order
800
+ for (let event = await viewer.next(); event; event = await viewer.next()) send(event);
801
+ })().catch(() => viewer.close());
802
+ return () => viewer.close();
803
+ });
804
+ }
805
+
806
+ /** One stream per page, so a view updates in place instead of reloading (design D7). */
807
+ function studioEvents(
780
808
  vault: VaultManager,
781
809
  companionPath: string,
782
- reportsOnly: boolean,
783
- subscribeReports: (notify: (event: ReportPublishedEvent) => void) => () => void,
810
+ boards: Map<string, Set<() => void>>,
811
+ reports: Map<string, Set<(event: PublishedReport) => void>>,
784
812
  ): Response {
785
- return eventStream("studio changes", (send) => {
786
- const stopReports = subscribeReports(send);
787
- const stopTree = reportsOnly
788
- ? () => {}
789
- : vault.subscribeTree(companionPath, (generation) =>
790
- send({ type: "vault-tree-changed", generation }),
791
- );
813
+ const digest = companionDigest(companionPath);
814
+ const join = <T>(map: Map<string, Set<T>>, listener: T) => {
815
+ const set = map.get(digest) ?? new Set<T>();
816
+ set.add(listener);
817
+ map.set(digest, set);
818
+ return () => {
819
+ set.delete(listener);
820
+ if (set.size === 0) map.delete(digest);
821
+ };
822
+ };
823
+ return eventStream("studio events", (send: (event: StudioEvent) => void) => {
824
+ const leaveBoard = join(boards, () => send({ type: "board" }));
825
+ const leaveReports = join(reports, (report) =>
826
+ send({ type: "reports", id: report.id, title: report.title }),
827
+ );
828
+ const stopTree = vault.subscribeTree(companionPath, (generation) =>
829
+ send({ type: "vault-tree", generation }),
830
+ );
792
831
  return () => {
793
- stopReports();
832
+ leaveBoard();
833
+ leaveReports();
794
834
  stopTree();
795
835
  };
796
836
  });
797
837
  }
798
838
 
839
+ function vaultEvents(vault: VaultManager, companionPath: string, requestedPath: string): Response {
840
+ return eventStream("studio vault events", (send) =>
841
+ vault.subscribe(companionPath, requestedPath, send),
842
+ );
843
+ }
844
+
845
+ /** Reports are not part of the snapshot: this Overview lists them at render time. */
846
+ function isAnalystOverview(selection: StudioSelection): boolean {
847
+ return selection.studioMode === "analysis" && selection.view === "dashboard";
848
+ }
849
+
799
850
  /**
800
851
  * One rendered document's worth of state. An absent or unresolvable companion
801
852
  * is not a failure: the page renders the selector and the server keeps serving.
802
853
  */
803
854
  async function collectStudioPage(
804
855
  url: URL,
856
+ policy: StudioModePolicy,
805
857
  collectInventory: () => Promise<StudioInventory>,
806
858
  snapshots: StudioSnapshotCache,
807
859
  vault: VaultManager,
808
860
  writable: boolean,
809
861
  ): Promise<StudioPage> {
810
- const selection = parse(url);
862
+ const selection = parse(url, policy);
811
863
  const inventory = await collectInventory();
812
864
  const companion = resolveCompanion(inventory, selection.companionDigest);
813
865
  const page: StudioPage = {
@@ -822,19 +874,8 @@ async function collectStudioPage(
822
874
  terminal: null,
823
875
  };
824
876
 
825
- if (!companion) {
826
- vault.deactivate();
827
- return page;
828
- }
829
-
830
- if (selection.view === "vault") {
831
- return {
832
- ...page,
833
- vault: await collectVaultState(vault, companion.path, selection, { tree: "prefetch" }),
834
- };
835
- }
836
-
837
877
  vault.deactivate();
878
+ if (!companion) return page;
838
879
 
839
880
  try {
840
881
  const snapshot = await snapshots.read(companion.path, selection.refresh);
@@ -846,7 +887,7 @@ async function collectStudioPage(
846
887
  ...page,
847
888
  error: {
848
889
  companionPath: companion.path,
849
- reason: error instanceof Error ? error.message : String(error),
890
+ reason: errorMessage(error),
850
891
  },
851
892
  };
852
893
  }
@@ -867,15 +908,15 @@ function bunServe(options: StudioServeOptions): StudioBoundServer {
867
908
  return runtime.serve(options);
868
909
  }
869
910
 
911
+ /** An IPv6 literal in brackets, as a URL needs it; any other host as it is. */
912
+ function urlHost(hostname: string): string {
913
+ return hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname;
914
+ }
915
+
870
916
  /** Where a process on this host reaches the server: loopback for wildcard binds. */
871
917
  function reportOrigin(hostname: string, port: number): string {
872
918
  const wildcard = hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]";
873
- const host = wildcard
874
- ? "127.0.0.1"
875
- : hostname.includes(":") && !hostname.startsWith("[")
876
- ? `[${hostname}]`
877
- : hostname;
878
- return `http://${host}:${port}`;
919
+ return `http://${wildcard ? "127.0.0.1" : urlHost(hostname)}:${port}`;
879
920
  }
880
921
 
881
922
  /**
@@ -908,6 +949,8 @@ export function startStudioServer(
908
949
  detachMinutes: options.detachMinutes,
909
950
  launchCompanion: options.launchCompanion,
910
951
  noGit: options.noGit,
952
+ profile: options.profile,
953
+ app: options.app,
911
954
  });
912
955
  const registry = fetchHandler.terminal;
913
956
  const server = serve({
@@ -944,12 +987,8 @@ export function startStudioServer(
944
987
  : {}),
945
988
  });
946
989
  boundPort = server.port;
947
- const urlHostname =
948
- hostname === STUDIO_HOSTNAME || hostname === "localhost" || hostname === "::1"
949
- ? "localhost"
950
- : hostname.includes(":") && !hostname.startsWith("[")
951
- ? `[${hostname}]`
952
- : hostname;
990
+ const loopback = hostname === STUDIO_HOSTNAME || hostname === "localhost" || hostname === "::1";
991
+ const urlHostname = loopback ? "localhost" : urlHost(hostname);
953
992
 
954
993
  return {
955
994
  url: `http://${urlHostname}:${server.port}`,