@uniqbit/mate-core 1.0.0-canary.9 → 1.0.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 (232) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +5 -4
  3. package/src/cli/commands/artifact/delivery/link.ts +1 -1
  4. package/src/cli/commands/artifact/delivery/output.ts +10 -1
  5. package/src/cli/commands/artifact/delivery/resolve.ts +3 -2
  6. package/src/cli/commands/artifact/delivery/submit.ts +9 -4
  7. package/src/cli/commands/artifact/delivery/take.ts +12 -9
  8. package/src/cli/commands/artifact/finish/command.ts +16 -14
  9. package/src/cli/commands/artifact/finish/engine.ts +8 -8
  10. package/src/cli/commands/artifact/project/command.ts +2 -3
  11. package/src/cli/commands/companion/hub.ts +11 -6
  12. package/src/cli/commands/companion/link.ts +173 -46
  13. package/src/cli/commands/report/contract.ts +0 -17
  14. package/src/cli/commands/studio/access.ts +4 -0
  15. package/src/cli/commands/studio/actions.ts +35 -2
  16. package/src/cli/commands/studio/mcp-manager.ts +162 -0
  17. package/src/cli/commands/studio/routes.ts +12 -0
  18. package/src/cli/commands/studio/selection.ts +44 -11
  19. package/src/cli/commands/studio/server.ts +246 -2
  20. package/src/cli/commands/studio/services.ts +26 -0
  21. package/src/cli/commands/studio/terminal-launch.ts +21 -4
  22. package/src/cli/commands/studio/terminal.ts +3 -14
  23. package/src/cli/commands/studio/work-requests.ts +9 -0
  24. package/src/cli/commands/studio/work.ts +473 -0
  25. package/src/cli/commands/vscode/release-vsix.json +2 -2
  26. package/src/cli/commands/working/cleanup.ts +1 -18
  27. package/src/cli/companion-link-wizard.tsx +158 -91
  28. package/src/cli/usage.ts +1 -1
  29. package/src/lib/agent-credential.ts +131 -0
  30. package/src/lib/credential-kinds.ts +7 -0
  31. package/src/lib/delivery/merge-git.ts +16 -0
  32. package/src/lib/delivery/record-delivery.ts +12 -6
  33. package/src/lib/delivery/record.ts +5 -0
  34. package/src/lib/delivery/refresh.ts +34 -6
  35. package/src/lib/delivery/staging/refs.ts +9 -4
  36. package/src/lib/delivery/staging/submit.ts +81 -22
  37. package/src/lib/mcp-manager/resolve.ts +27 -9
  38. package/src/lib/mcp-manager/store.ts +35 -11
  39. package/src/lib/mcp-manager/types.ts +14 -0
  40. package/src/lib/mcp-manager/validate.ts +6 -10
  41. package/src/lib/opencode-server.ts +2 -17
  42. package/src/lib/orchestrator/repo-local-store.ts +14 -0
  43. package/src/lib/orchestrator/repository-link.ts +80 -52
  44. package/src/lib/orchestrator/root-context.ts +17 -1
  45. package/src/lib/studio-chat/agent.ts +139 -0
  46. package/src/lib/studio-chat/companion-context.ts +136 -0
  47. package/src/lib/studio-chat/credential.ts +79 -0
  48. package/src/lib/studio-chat/harness-chat-agent.ts +334 -0
  49. package/src/lib/studio-chat/host-sandbox.ts +578 -0
  50. package/src/lib/studio-chat/prepare-bridges.ts +95 -0
  51. package/src/lib/studio-chat/session.ts +15 -0
  52. package/src/lib/studio-chat/turns.ts +112 -0
  53. package/src/lib/workset/claims.ts +85 -0
  54. package/src/lib/workset/execution.ts +71 -0
  55. package/src/lib/workset/git-transaction.ts +74 -0
  56. package/src/lib/workset/groups.ts +176 -0
  57. package/src/lib/workset/inventory.ts +196 -0
  58. package/src/lib/workset/projection.ts +237 -0
  59. package/src/lib/workset/record.ts +101 -36
  60. package/src/lib/workset/repositories.ts +24 -0
  61. package/src/lib/workset/sharing.ts +951 -0
  62. package/src/lib/workset/stages.ts +50 -14
  63. package/src/lib/workset/transactions.ts +158 -0
  64. package/src/runtime/companion-git-state.ts +1 -0
  65. package/src/runtime/companion-guidance.ts +2 -2
  66. package/src/runtime/forge-remote.ts +6 -0
  67. package/src/runtime/host-process.ts +28 -0
  68. package/src/runtime/secret-guard.ts +18 -1
  69. package/src/runtime/secret-patterns.ts +4 -3
  70. package/src/runtime/submitted-arrivals.ts +28 -2
  71. package/src/runtime/write-atomic.ts +2 -2
  72. package/src/studio.ts +52 -8
  73. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +1 -1
  74. package/src/templates/capabilities/openspec-cap/mate-full/templates/proposal.md +1 -1
  75. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +3 -2
  76. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +5 -3
  77. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +3 -2
  78. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +5 -3
  79. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +12 -12
  80. package/src/tools/setup/capabilities/mcp-manager.ts +1 -2
  81. package/src/tools/setup/dynamic-plugins/declarations.ts +0 -26
  82. package/src/tools/setup/plugins/gitignore.ts +1 -0
  83. package/src/tools/setup/providers/claude-format.ts +1 -5
  84. package/src/tools/setup/providers/claude.ts +28 -3
  85. package/src/tools/setup/providers/opencode.ts +7 -18
  86. package/src/tools/setup/providers/relative-path-warnings.ts +26 -0
  87. package/studio-dist/THIRD-PARTY-NOTICES.md +297 -0
  88. package/studio-dist/client/THIRD-PARTY-LICENSES.md +4294 -0
  89. package/studio-dist/client/assets/DialogTitle-DOhjDa7H.js +1 -0
  90. package/studio-dist/client/assets/app-CG3vCgyA.css +2 -0
  91. package/studio-dist/client/assets/bundle-mjs-CdK3cBzO.js +1 -0
  92. package/studio-dist/client/assets/button-upSzkd-q.js +1 -0
  93. package/studio-dist/client/assets/chat-DbaMXb8H.js +157 -0
  94. package/studio-dist/client/assets/cn-BCnYnarL.js +1 -0
  95. package/studio-dist/client/assets/combobox-cP9OsRf2.js +1 -0
  96. package/studio-dist/client/assets/{companion-view-C1F0_jbt.js → companion-view-B54_Lj0S.js} +1 -1
  97. package/studio-dist/client/assets/fields-DNZ4a89M.js +1 -0
  98. package/studio-dist/client/assets/friction-DgEimeDB.js +1 -0
  99. package/studio-dist/client/assets/getting-started-BTfYCt5s.js +1 -0
  100. package/studio-dist/client/assets/{getting-started-BN4aTpsz.js → getting-started-CAszmdDJ.js} +1 -1
  101. package/studio-dist/client/assets/getting-started._topic-CHJMf0pa.js +1 -0
  102. package/studio-dist/client/assets/getting-started.index-MR6HftWs.js +1 -0
  103. package/studio-dist/client/assets/{graph-canvas-Be5qgdDt.js → graph-canvas-BdNk2F9O.js} +1 -1
  104. package/studio-dist/client/assets/graph-hRijsC89.js +2 -0
  105. package/studio-dist/client/assets/guides-CwFnh08E.js +1 -0
  106. package/studio-dist/client/assets/highlighted-body-JLMTFACH-BcroQey-.js +1 -0
  107. package/studio-dist/client/assets/index-D5oGyvG8.js +41 -0
  108. package/studio-dist/client/assets/{markdown-view-dku7MGPn.js → markdown-view-CJ8JsLb7.js} +1 -1
  109. package/studio-dist/client/assets/marked.esm-vFuq1cCd.js +65 -0
  110. package/studio-dist/client/assets/mcp-BE9M-bkO.js +4 -0
  111. package/studio-dist/client/assets/mermaid-WFAXDIZX-BjSsakrn.js +1 -0
  112. package/studio-dist/client/assets/panel-CDQ6Lryw.js +1 -0
  113. package/studio-dist/client/assets/plugins._service._view-DRVPUAWN.js +1 -0
  114. package/studio-dist/client/assets/{prepaint-BkoDSw5X.js → prepaint-sD_LlrDN.js} +1 -1
  115. package/studio-dist/client/assets/{queries-CMvC2OkU.js → queries-COL925ML.js} +1 -1
  116. package/studio-dist/client/assets/react-dom-K3Hp2Cdj.js +1 -0
  117. package/studio-dist/client/assets/{react-BYUSgtBs.js → react-h2xQ_NSp.js} +1 -1
  118. package/studio-dist/client/assets/reports-BClsojkb.js +1 -0
  119. package/studio-dist/client/assets/routes-CJQ2MAej.js +1 -0
  120. package/studio-dist/client/assets/search-DhWdEiKT.js +1 -0
  121. package/studio-dist/client/assets/select-B2FsN9FY.js +1 -0
  122. package/studio-dist/client/assets/skills-SoUHk77W.js +1 -0
  123. package/studio-dist/client/assets/{specs-Bqd1ajyD.js → specs-C_tZnAvF.js} +1 -1
  124. package/studio-dist/client/assets/specs-view-C6t3Y5IT.js +1 -0
  125. package/studio-dist/client/assets/steps-CF3-Zpmh.js +1 -0
  126. package/studio-dist/client/assets/{store-BYnEU33C.js → store-pY9gU4uS.js} +1 -1
  127. package/studio-dist/client/assets/studio-X7bnFrRe.js +36 -0
  128. package/studio-dist/client/assets/studio-queries-CKtAnIKP.js +2 -0
  129. package/studio-dist/client/assets/usage-BaaqUpTG.js +55 -0
  130. package/studio-dist/client/assets/useAnchoredPopupScrollLock-BspHR7Wt.js +1 -0
  131. package/studio-dist/client/assets/useBlocker-BQOfcu_f.js +1 -0
  132. package/studio-dist/client/assets/useMutation-DKeEoP5S.js +1 -0
  133. package/studio-dist/client/assets/useOpenInteractionType-CtaZCaFT.js +1 -0
  134. package/studio-dist/client/assets/usePopupHandleStore-Bc7Q4bnF.js +1 -0
  135. package/studio-dist/client/assets/vault-sAPFUnPN.js +1 -0
  136. package/studio-dist/client/assets/{warnings-Cnw99ugO.js → warnings-D7YY1HSG.js} +1 -1
  137. package/studio-dist/client/assets/work-BZek_LGB.js +5 -0
  138. package/studio-dist/client/assets/workflow-N5boHXFz.js +1 -0
  139. package/studio-dist/server/THIRD-PARTY-LICENSES.md +4371 -0
  140. package/studio-dist/server/assets/DialogTitle-DnKSl2V0.js +421 -0
  141. package/studio-dist/server/assets/{__23tanstack-start-server-fn-resolver-CS3QRY4Q.js → __23tanstack-start-server-fn-resolver-Bli9bpSB.js} +38 -18
  142. package/studio-dist/server/assets/_tanstack-start-manifest_v.js +91 -59
  143. package/studio-dist/server/assets/{actions-D8erOphH.js → actions-CHEFA1i9.js} +33 -1
  144. package/studio-dist/server/assets/{cn-DWFJaP_9.js → bundle-mjs-Ot6dQ8Pq.js} +1 -2056
  145. package/studio-dist/server/assets/{button-Ct_WeYLc.js → button-BqA1urbl.js} +14 -7
  146. package/studio-dist/server/assets/chat-zl332Tvu.js +49486 -0
  147. package/studio-dist/server/assets/cn-B0fl6NWK.js +2057 -0
  148. package/studio-dist/server/assets/{combobox-17vO5Uz8.js → combobox-iTjvPCtS.js} +7 -6
  149. package/studio-dist/server/assets/{companion-view-JkxnGLlp.js → companion-view-DIQ6AFIY.js} +2 -2
  150. package/studio-dist/server/assets/{companions-YNLsbnch.js → companions-aVwjRL8j.js} +1 -1
  151. package/studio-dist/server/assets/{fields-VytPpqBq.js → fields-BMap2_Ju.js} +10 -3
  152. package/studio-dist/server/assets/{friction-BW86PCPM.js → friction-BER50hoD.js} +2 -2
  153. package/studio-dist/server/assets/{friction-B6osqFSm.js → friction-BPs9KWdq.js} +8 -8
  154. package/studio-dist/server/assets/{getting-started-CFHSeX5h.js → getting-started-DGfRVmZ_.js} +2 -2
  155. package/studio-dist/server/assets/{getting-started._topic-BK2eU6AS.js → getting-started._topic-BgrBA4Vj.js} +2 -2
  156. package/studio-dist/server/assets/{getting-started.index-DZLuXnNO.js → getting-started.index-BaFfQ9Mn.js} +2 -2
  157. package/studio-dist/server/assets/{graph-BJVZBevL.js → graph-Cgzlrv3P.js} +8 -8
  158. package/studio-dist/server/assets/{graph-DGZHV-Ek.js → graph-DODpuOy_.js} +1 -1
  159. package/studio-dist/server/assets/{graph-canvas-lrNT6jbl.js → graph-canvas-DW_zU1nA.js} +2 -2
  160. package/studio-dist/server/assets/{guides-_G8Vucsk.js → guides-CA_EMG7E.js} +1 -1
  161. package/studio-dist/server/assets/{guides-CEwLOZb9.js → guides-D0SpoD32.js} +1 -1
  162. package/studio-dist/server/assets/{guides.server-ZWFKX2XJ.js → guides.server-DJjQuy03.js} +1 -1
  163. package/studio-dist/server/assets/highlighted-body-JLMTFACH-BeHllu-r.js +41 -0
  164. package/studio-dist/server/assets/{markdown-view-Bmjghg_Z.js → markdown-view-CvVBGMZV.js} +1 -1
  165. package/studio-dist/server/assets/mcp-BU0fLYyJ.js +1103 -0
  166. package/studio-dist/server/assets/mcp-manager-D9YctTQe.js +50 -0
  167. package/studio-dist/server/assets/mermaid-WFAXDIZX-B1yDN6vG.js +1 -0
  168. package/studio-dist/server/assets/{panel-DvRjyil3.js → panel-D1K6Bsux.js} +4 -32
  169. package/studio-dist/server/assets/{plugins._service._view-B32LzraG.js → plugins._service._view-DdO1nELF.js} +4 -4
  170. package/studio-dist/server/assets/{prepaint-BEHwKl51.js → prepaint-BB3dwSmz.js} +1 -1
  171. package/studio-dist/server/assets/{queries-D6Vq0AuZ.js → queries-BwiDxQy5.js} +1 -1
  172. package/studio-dist/server/assets/{react-CiBZPDs8.js → react-B2cLiz-i.js} +1 -1
  173. package/studio-dist/server/assets/{reports-Dn92pLap.js → reports-9Pr7Bz6o.js} +7 -7
  174. package/studio-dist/server/assets/{reports-DDaH5k0H.js → reports-Cc9M3phM.js} +1 -1
  175. package/studio-dist/server/assets/{router-Bjf4S9tO.js → router-DcWe0J7Y.js} +827 -548
  176. package/studio-dist/server/assets/{routes-B4sNiE0X.js → routes-BEXxl0py.js} +8 -8
  177. package/studio-dist/server/assets/{search-DKeJRvg8.js → search-bltT7gwy.js} +39 -7
  178. package/studio-dist/server/assets/{select-CVHYL7oR.js → select-CZvHgGCi.js} +7 -6
  179. package/studio-dist/server/assets/{shell-BxbYYaAk.js → shell-BQ0vMKXN.js} +13 -4
  180. package/studio-dist/server/assets/{skills-Bj8eOgzR.js → skills-Be_52h0i.js} +1 -1
  181. package/studio-dist/server/assets/{skills-B4-0qpqN.js → skills-BpGGUl6L.js} +8 -8
  182. package/studio-dist/server/assets/{specs-rfMug6qW.js → specs-CCGgXE-V.js} +5 -5
  183. package/studio-dist/server/assets/{specs-view-qi1SE1Sl.js → specs-view-DtL5JxYM.js} +12 -11
  184. package/studio-dist/server/assets/{steps-rger6HJc.js → steps-BWFSO6dM.js} +1 -1
  185. package/studio-dist/server/assets/{store-Dg9T7oWs.js → store-X7yLPp7v.js} +1 -1
  186. package/studio-dist/server/assets/{studio-queries-CeFfmIuM.js → studio-queries-ur1ygXi3.js} +117 -13
  187. package/studio-dist/server/assets/{studio-D79JzDLc.js → studio-qzH-UETC.js} +209 -180
  188. package/studio-dist/server/assets/{usage-Dw_UQFX-.js → usage-C1o0DLzS.js} +1 -1
  189. package/studio-dist/server/assets/{usage-BJgYWRCX.js → usage-DWbSPrPD.js} +10 -9
  190. package/studio-dist/server/assets/{useAnchoredPopupScrollLock-ciS_sEq3.js → useAnchoredPopupScrollLock-DLDmv6kM.js} +4 -135
  191. package/studio-dist/server/assets/useBlocker-CQtANHK8.js +111 -0
  192. package/studio-dist/server/assets/{useMutation-DnWK0PhO.js → useMutation-NjlA8oFY.js} +2 -2
  193. package/studio-dist/server/assets/useOpenInteractionType-CZYscfOb.js +136 -0
  194. package/studio-dist/server/assets/usePopupHandleStore-DEEXJYv0.js +26 -0
  195. package/studio-dist/server/assets/{vault-BzarssiL.js → vault-B_kfi1h-.js} +1 -1
  196. package/studio-dist/server/assets/{vault-CvlrLd2H.js → vault-dL79JlKH.js} +8 -115
  197. package/studio-dist/server/assets/{views-CAxwKHMK.js → views-BSGH56lb.js} +3 -3
  198. package/studio-dist/server/assets/{warnings-BpVCugHm.js → warnings-DtUVPV-k.js} +2 -2
  199. package/studio-dist/server/assets/work-D789VXGH.js +110 -0
  200. package/studio-dist/server/assets/work-DsCEfhmK.js +3817 -0
  201. package/studio-dist/server/assets/work-requests-BLhOmQFO.js +11 -0
  202. package/studio-dist/server/assets/{workflow-BdrzcCt8.js → workflow-BOZ2sRYg.js} +9 -9
  203. package/studio-dist/server/server.js +3 -3
  204. package/wrappers/bin/openspec +87 -2
  205. package/studio-dist/client/assets/app-ggXJ_QVh.css +0 -2
  206. package/studio-dist/client/assets/button-C9SQW3kI.js +0 -1
  207. package/studio-dist/client/assets/cn-DC80MJV0.js +0 -1
  208. package/studio-dist/client/assets/combobox-D7mKYCBb.js +0 -1
  209. package/studio-dist/client/assets/fields-CEep8IFT.js +0 -1
  210. package/studio-dist/client/assets/friction-D9dBU7WN.js +0 -1
  211. package/studio-dist/client/assets/getting-started-BDyGvHhc.js +0 -1
  212. package/studio-dist/client/assets/getting-started._topic-B9ajbF4o.js +0 -1
  213. package/studio-dist/client/assets/getting-started.index-CYiBPtb7.js +0 -1
  214. package/studio-dist/client/assets/graph-ah7ZXfTa.js +0 -2
  215. package/studio-dist/client/assets/guides-CsL0660B.js +0 -1
  216. package/studio-dist/client/assets/index-zmRH87D4.js +0 -40
  217. package/studio-dist/client/assets/panel-COgk0vP5.js +0 -1
  218. package/studio-dist/client/assets/plugins._service._view-Cn3WBHab.js +0 -1
  219. package/studio-dist/client/assets/reports-C_AqLBYH.js +0 -1
  220. package/studio-dist/client/assets/routes-BokQmHtC.js +0 -1
  221. package/studio-dist/client/assets/search-DxidNK2M.js +0 -1
  222. package/studio-dist/client/assets/select-CYFCbHUd.js +0 -1
  223. package/studio-dist/client/assets/skills-R3vttWHM.js +0 -1
  224. package/studio-dist/client/assets/specs-view-znqFPx9p.js +0 -1
  225. package/studio-dist/client/assets/steps-tVDWn7j6.js +0 -1
  226. package/studio-dist/client/assets/studio-ndtFcS2Y.js +0 -100
  227. package/studio-dist/client/assets/studio-queries-CkUSByy7.js +0 -2
  228. package/studio-dist/client/assets/usage-Kuhr8dSl.js +0 -55
  229. package/studio-dist/client/assets/useAnchoredPopupScrollLock-dc_kP4Go.js +0 -1
  230. package/studio-dist/client/assets/useMutation-CqtM9COw.js +0 -1
  231. package/studio-dist/client/assets/vault-CSP8kwRg.js +0 -1
  232. package/studio-dist/client/assets/workflow-BPJAmmZi.js +0 -1
@@ -0,0 +1,578 @@
1
+ import { spawn as spawnChild, type ChildProcess } from "node:child_process";
2
+ import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { Readable, Writable } from "node:stream";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+
8
+ import type { HarnessV1NetworkSandboxSession } from "@ai-sdk/harness";
9
+
10
+ import { freeLoopbackPort, signalProcessGroup, within } from "../../runtime/host-process";
11
+ import { isWithin, physicalPath } from "../../runtime/physical-path";
12
+ import { mateHome } from "../../runtime/runtime-directory";
13
+ import { writeAtomic } from "../../runtime/write-atomic";
14
+ import { CHAT_HARNESS_NAMES, type ChatHarness } from "./agent";
15
+
16
+ type SandboxSession = ReturnType<HarnessV1NetworkSandboxSession["restricted"]>;
17
+ type ProcessOptions = {
18
+ command: string;
19
+ workingDirectory?: string;
20
+ env?: Record<string, string>;
21
+ abortSignal?: AbortSignal;
22
+ };
23
+
24
+ export interface HostSandboxOptions {
25
+ workDir: string;
26
+ bootstrapCache?: string;
27
+ prebuiltBridges?: string;
28
+ env?: NodeJS.ProcessEnv;
29
+ }
30
+
31
+ export interface HostSandbox extends HarnessV1NetworkSandboxSession {
32
+ readonly home: string;
33
+ readonly port: number;
34
+ }
35
+
36
+ class HostSandboxError extends Error {}
37
+
38
+ export const CREDENTIAL_NAMES: ReadonlySet<string> = new Set([
39
+ "ANTHROPIC_API_KEY",
40
+ "ANTHROPIC_AUTH_TOKEN",
41
+ "CLAUDE_CODE_OAUTH_TOKEN",
42
+ "AI_GATEWAY_API_KEY",
43
+ "VERCEL_OIDC_TOKEN",
44
+ "OPENAI_API_KEY",
45
+ "GOOGLE_GENERATIVE_AI_API_KEY",
46
+ "XAI_API_KEY",
47
+ "GITHUB_TOKEN",
48
+ "GITHUB_COPILOT_TOKEN",
49
+ "POE_API_KEY",
50
+ "OPENCODE_API_KEY",
51
+ "GITLAB_TOKEN",
52
+ "AI_SDK_OPENCODE_NATIVE_ACCESS_TOKEN",
53
+ ]);
54
+
55
+ const CONFIG_NAMES = new Set([
56
+ "CLAUDE_CONFIG_DIR",
57
+ "XDG_CONFIG_HOME",
58
+ "XDG_DATA_HOME",
59
+ "XDG_CACHE_HOME",
60
+ "XDG_STATE_HOME",
61
+ ]);
62
+ const CONFIG_PREFIX = "OPENCODE_";
63
+
64
+ const BOOTSTRAP_LINK = path.join(".ai-sdk-harness", ".harness-bootstrap");
65
+
66
+ const WILDCARD_BIND = 'host: "0.0.0.0"';
67
+ const LOOPBACK_BIND = 'host: "127.0.0.1"';
68
+ const BRIDGE_COMMAND =
69
+ /^\s*(?:node|bun)\s+'([^']*\/bridge\.mjs)'(?:\s+--[\w-]+\s+'(?:[^']|'\\'')*')*\s*$/;
70
+ const SCRIPT_START =
71
+ /(?:^|[;&|(\n"'`]|\$\(|\bexec)\s*(?:node|bunx|npx|deno|tsx|bun(?!\s+install\s))(?:\s|$)/;
72
+ const LOCKFILE_INSTALL =
73
+ /^(?:pnpm|npm|yarn)\s+(?:install|i|ci)(?:\s+(?:--frozen-lockfile|--prefer-offline|--silent|--store-dir[=\s][\w./-]+))*\s*$/;
74
+
75
+ const STOP_GRACE_MS = 2_000;
76
+
77
+ function defaultBootstrapCache(): string {
78
+ return path.join(mateHome(), "cache", "studio-chat", "harness-bootstrap");
79
+ }
80
+
81
+ export function bunCommand(command: string): string {
82
+ const trimmed = command.trimStart();
83
+ if (LOCKFILE_INSTALL.test(trimmed)) return "bun install --frozen-lockfile";
84
+ if (/^node(?=\s)/.test(trimmed)) return trimmed.replace(/^node/, "bun");
85
+ return command;
86
+ }
87
+
88
+ export function loopbackBridge(source: string): string {
89
+ return source.replace(WILDCARD_BIND, LOOPBACK_BIND);
90
+ }
91
+
92
+ const PRE_TOOL_USE = /PreToolUse:\s*\[/;
93
+ const READ_GUARD_MARK = "/* mate-studio-chat: reads stay in the companion, v3 */";
94
+ const LEGACY_READ_GUARD =
95
+ /\/\* mate-studio-chat: reads stay in the companion(?:, v2)? \*\/ \{[\s\S]*?\n {2}\}(?:\)\(\))?\],\n\}, /;
96
+ const READ_GUARD = `${READ_GUARD_MARK} {
97
+ matcher: "Read|Grep|Glob|NotebookRead|LS",
98
+ hooks: [(() => {
99
+ const clean = new Map();
100
+ const leaking = new Set();
101
+ return async (hookInput) => {
102
+ const nodePath = await import("node:path");
103
+ const { realpathSync } = await import("node:fs");
104
+ const { readdir } = await import("node:fs/promises");
105
+ // Where the kernel lands: a link is followed before a later ".." applies, so "link/.." is its target's parent.
106
+ const real = (target) => {
107
+ const absolute = nodePath.isAbsolute(target) ? target : nodePath.resolve(workdir) + nodePath.sep + target;
108
+ let current = nodePath.parse(absolute).root;
109
+ for (const segment of absolute.slice(current.length).split(/[\\\\/]/)) {
110
+ if (segment === "" || segment === ".") continue;
111
+ current = segment === ".." ? nodePath.dirname(current) : nodePath.join(current, segment);
112
+ try {
113
+ current = realpathSync(current);
114
+ } catch {}
115
+ }
116
+ return current;
117
+ };
118
+ const expand = (glob) => {
119
+ const done = [];
120
+ const pending = [glob];
121
+ while (pending.length > 0) {
122
+ if (done.length + pending.length > 256) return null;
123
+ const next = pending.pop();
124
+ const group = /\\{([^{}]*)\\}/.exec(next);
125
+ if (!group) done.push(next);
126
+ else for (const part of group[1].split(",")) pending.push(next.slice(0, group.index) + part + next.slice(group.index + group[0].length));
127
+ }
128
+ return done;
129
+ };
130
+ const root = real(".");
131
+ const skills = process.env.HOME ? real(nodePath.join(process.env.HOME, ".claude", "skills")) : null;
132
+ const under = (resolved, dir) => resolved === dir || resolved.startsWith(dir + nodePath.sep);
133
+ const inside = (resolved) => under(resolved, root) || (skills !== null && under(resolved, skills));
134
+ const parentLike = (segment) => segment.includes("..") || (segment.includes(".") && /^[.?[\\]()@!+|]*$/.test(segment));
135
+ const fixedPart = (pattern) => {
136
+ const segments = pattern.split(/[\\\\/]/);
137
+ const wild = segments.findIndex((segment) => /[*?[\\]()!+@]/.test(segment));
138
+ return (wild === -1 ? segments : segments.slice(0, wild)).join("/") || "/";
139
+ };
140
+ const escapes = (glob) => {
141
+ const patterns = expand(glob);
142
+ return patterns === null || patterns.some((pattern) => pattern.startsWith("~") || pattern.split(/[\\\\/]/).some(parentLike) ||
143
+ (nodePath.isAbsolute(pattern) && !inside(real(fixedPart(pattern)))));
144
+ };
145
+ const walk = async (dir) => {
146
+ const pending = [dir];
147
+ let seen = 0;
148
+ while (pending.length > 0) {
149
+ const current = pending.pop();
150
+ let entries;
151
+ try {
152
+ entries = await readdir(current, { withFileTypes: true });
153
+ } catch {
154
+ continue;
155
+ }
156
+ for (const entry of entries) {
157
+ seen += 1;
158
+ if (seen > 1000000) return true;
159
+ const full = nodePath.join(current, entry.name);
160
+ if (entry.isSymbolicLink()) {
161
+ if (!inside(real(full))) return true;
162
+ } else if (entry.isDirectory()) pending.push(full);
163
+ }
164
+ }
165
+ return false;
166
+ };
167
+ const linksOut = async (dir) => {
168
+ const now = Date.now();
169
+ for (const [done, at] of clean) {
170
+ if (now - at > 5000) clean.delete(done);
171
+ else if (under(dir, done)) return false;
172
+ }
173
+ if (leaking.has(dir)) return true;
174
+ const out = await walk(dir);
175
+ if (out) leaking.add(dir);
176
+ else clean.set(dir, Date.now());
177
+ return out;
178
+ };
179
+ const input = hookInput.tool_input ?? {};
180
+ const paths = [input.file_path, input.notebook_path, input.path].filter((value) => typeof value === "string");
181
+ const globs = [hookInput.tool_name === "Glob" ? input.pattern : undefined, input.glob].filter((value) => typeof value === "string");
182
+ const searches = hookInput.tool_name === "Grep" || hookInput.tool_name === "Glob";
183
+ // Claude Code expands a leading "~" to HOME, outside the companion.
184
+ let outside = paths.some((target) => target.startsWith("~") || !inside(real(target))) || globs.some(escapes);
185
+ if (!outside && searches) {
186
+ const starts = [typeof input.path === "string" ? input.path : "."];
187
+ for (const glob of globs) for (const pattern of expand(glob)) if (nodePath.isAbsolute(pattern)) starts.push(fixedPart(pattern));
188
+ for (const start of starts) if (await linksOut(real(start))) outside = true;
189
+ }
190
+ if (!outside) return {};
191
+ return { hookSpecificOutput: {
192
+ hookEventName: "PreToolUse",
193
+ permissionDecision: "deny",
194
+ permissionDecisionReason: "The chat reads only files inside this companion.",
195
+ } };
196
+ };
197
+ })()],
198
+ }`;
199
+
200
+ export function companionReadGuard(source: string): string {
201
+ if (source.includes(READ_GUARD_MARK)) return source;
202
+ return source
203
+ .replace(LEGACY_READ_GUARD, "")
204
+ .replace(PRE_TOOL_USE, `PreToolUse: [${READ_GUARD}, `);
205
+ }
206
+
207
+ const QUERY_OPTION = "includePartialMessages: true,";
208
+ const USER_SETTINGS_MARK = "/* mate-studio-chat: no companion settings */";
209
+
210
+ export function userSettingsOnly(source: string): string {
211
+ if (source.includes(USER_SETTINGS_MARK)) return source;
212
+ return source.replace(
213
+ QUERY_OPTION,
214
+ `${USER_SETTINGS_MARK} settingSources: ["user"], ${QUERY_OPTION}`,
215
+ );
216
+ }
217
+
218
+ const OPENCODE_ASKED = /webfetch: "ask",(\s*)doom_loop: "ask",(\s*)task: "ask",/;
219
+ const OPENCODE_TOOLS_MARK = "/* mate-studio-chat: no web, no subagents */";
220
+
221
+ export function openCodeToolsOff(source: string): string {
222
+ if (source.includes(OPENCODE_TOOLS_MARK)) return source;
223
+ return source.replace(
224
+ OPENCODE_ASKED,
225
+ `${OPENCODE_TOOLS_MARK} webfetch: "deny", websearch: "deny", codesearch: "deny", todowrite: "deny",$1doom_loop: "ask",$2task: "deny",`,
226
+ );
227
+ }
228
+
229
+ const BRIDGE_GUARDS: Record<
230
+ ChatHarness,
231
+ {
232
+ guard: (source: string) => string;
233
+ marks: readonly (readonly [string, string])[];
234
+ env: Readonly<Record<string, string>>;
235
+ }
236
+ > = {
237
+ "claude-code": {
238
+ guard: (source) => companionReadGuard(userSettingsOnly(source)),
239
+ marks: [
240
+ [READ_GUARD_MARK, "the chat bridge must keep reads inside the companion"],
241
+ [USER_SETTINGS_MARK, "the chat bridge must not load the companion's settings"],
242
+ ],
243
+ env: {},
244
+ },
245
+ opencode: {
246
+ guard: openCodeToolsOff,
247
+ marks: [
248
+ [OPENCODE_TOOLS_MARK, "the chat bridge must not fetch, search the web or run subagents"],
249
+ ],
250
+ env: { OPENCODE_PURE: "1", OPENCODE_DISABLE_PROJECT_CONFIG: "1" },
251
+ },
252
+ };
253
+
254
+ function bridgeKind(file: string): ChatHarness {
255
+ const kind = path.basename(path.dirname(file));
256
+ if (kind === "claude-code" || kind === "opencode") return kind;
257
+ throw new HostSandboxError(`the chat starts no ${kind} bridge`);
258
+ }
259
+
260
+ function guardedBridge(source: string, kind: ChatHarness): string {
261
+ return BRIDGE_GUARDS[kind].guard(loopbackBridge(source));
262
+ }
263
+
264
+ const claimedPorts = new Set<number>();
265
+
266
+ async function claimBridgePort(): Promise<number> {
267
+ for (let attempt = 0; attempt < 5; attempt += 1) {
268
+ // oxlint-disable-next-line no-await-in-loop -- each probe follows a refused port.
269
+ const port = await freeLoopbackPort();
270
+ if (claimedPorts.has(port)) continue;
271
+ claimedPorts.add(port);
272
+ return port;
273
+ }
274
+ throw new HostSandboxError("no free loopback port for the chat bridge");
275
+ }
276
+
277
+ function groupAlive(pid: number): boolean {
278
+ try {
279
+ process.kill(-pid, 0);
280
+ return true;
281
+ } catch {
282
+ return false;
283
+ }
284
+ }
285
+
286
+ function inheritedEnv(env: NodeJS.ProcessEnv, home: string): Record<string, string> {
287
+ const kept: Record<string, string> = {};
288
+ for (const [name, value] of Object.entries(env)) {
289
+ if (value === undefined || CREDENTIAL_NAMES.has(name)) continue;
290
+ if (CONFIG_NAMES.has(name) || name.startsWith(CONFIG_PREFIX)) continue;
291
+ kept[name] = value;
292
+ }
293
+ kept.HOME = home;
294
+ return kept;
295
+ }
296
+
297
+ export async function createHostSandbox(options: HostSandboxOptions): Promise<HostSandbox> {
298
+ const workDir = path.resolve(options.workDir);
299
+ const prebuilt = options.prebuiltBridges;
300
+ const cache = prebuilt ?? options.bootstrapCache ?? defaultBootstrapCache();
301
+ if (!prebuilt) await mkdir(cache, { recursive: true });
302
+ const home = await mkdtemp(path.join(os.tmpdir(), "mate-studio-chat-"));
303
+ const { port, realWorkDir, realHome, realCache } = await prepareHome(home, cache, workDir).catch(
304
+ async (error: unknown) => {
305
+ await rm(home, { recursive: true, force: true });
306
+ throw error;
307
+ },
308
+ );
309
+ const env = inheritedEnv(options.env ?? process.env, home);
310
+ const children = new Map<ChildProcess, Promise<{ exitCode: number }>>();
311
+ let stopped = false;
312
+
313
+ const state = (real: string) => isWithin(real, realHome) || isWithin(real, realCache);
314
+ const readable = (target: string): string => {
315
+ const resolved = path.resolve(workDir, target);
316
+ const real = physicalPath(resolved);
317
+ if (state(real) || isWithin(real, realWorkDir)) return resolved;
318
+ throw new HostSandboxError(`${target} is outside the chat's companion and state`);
319
+ };
320
+ const incompleteBridge = (real: string) => {
321
+ const harness = path.relative(realCache, real).split(path.sep)[0] ?? "";
322
+ const name = CHAT_HARNESS_NAMES[harness as ChatHarness] ?? harness;
323
+ return new HostSandboxError(
324
+ `the prebuilt ${name} bridge in ${prebuilt} is missing or incomplete`,
325
+ );
326
+ };
327
+ const writable = (target: string): string => {
328
+ const resolved = path.resolve(workDir, target);
329
+ const real = physicalPath(resolved);
330
+ if (prebuilt && isWithin(real, realCache)) throw incompleteBridge(real);
331
+ if (isWithin(resolved, home) && state(real) && !isWithin(real, realWorkDir)) return resolved;
332
+ throw new HostSandboxError(`the chat writes nothing outside its own state: ${target}`);
333
+ };
334
+
335
+ /** A group id is not reused while a member lives. */
336
+ const groups = new Set<number>();
337
+
338
+ const killGroup = (child: ChildProcess, signal: NodeJS.Signals) => {
339
+ if (child.pid !== undefined && groups.has(child.pid)) signalProcessGroup(child.pid, signal);
340
+ };
341
+
342
+ const end = async (child: ChildProcess, exited: Promise<{ exitCode: number }>) => {
343
+ killGroup(child, "SIGTERM");
344
+ await within(exited, STOP_GRACE_MS);
345
+ killGroup(child, "SIGKILL");
346
+ await within(exited, STOP_GRACE_MS);
347
+ // A process that left its group may still hold a pipe; letting go of it ends the wait.
348
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream?.destroy();
349
+ await exited;
350
+ };
351
+
352
+ const start = (request: ProcessOptions, stdin: boolean) => {
353
+ if (stopped) throw new HostSandboxError("the chat sandbox has stopped");
354
+ request.abortSignal?.throwIfAborted();
355
+ const cwd = readable(request.workingDirectory ?? workDir);
356
+ const child = spawnChild("bash", ["-c", bunCommand(request.command)], {
357
+ cwd,
358
+ env: { ...env, ...request.env },
359
+ detached: true,
360
+ stdio: [stdin ? "pipe" : "ignore", "pipe", "pipe"],
361
+ });
362
+ const onAbort = () => killGroup(child, "SIGTERM");
363
+ const exited = new Promise<{ exitCode: number }>((resolve) => {
364
+ const done = (exitCode: number) => {
365
+ children.delete(child);
366
+ request.abortSignal?.removeEventListener("abort", onAbort);
367
+ if (child.pid !== undefined && !groupAlive(child.pid)) groups.delete(child.pid);
368
+ resolve({ exitCode });
369
+ };
370
+ child.once("close", (code) => done(code ?? 137));
371
+ child.once("error", () => done(127));
372
+ });
373
+ if (child.pid !== undefined) groups.add(child.pid);
374
+ children.set(child, exited);
375
+ request.abortSignal?.addEventListener("abort", onAbort, { once: true });
376
+ return { child, exited };
377
+ };
378
+
379
+ const run: SandboxSession["run"] = async (request: ProcessOptions) => {
380
+ if (request.command.includes("bridge.mjs")) {
381
+ throw new HostSandboxError("the chat bridge starts only through spawn");
382
+ }
383
+ if (SCRIPT_START.test(bunCommand(request.command))) {
384
+ throw new HostSandboxError("the chat starts no script but its bridge");
385
+ }
386
+ // A harness that finds no installed bridge creates its bootstrap directory, then installs.
387
+ if (prebuilt && request.env?.BOOTSTRAP_DIR !== undefined) {
388
+ throw incompleteBridge(physicalPath(path.resolve(request.env.BOOTSTRAP_DIR)));
389
+ }
390
+ if (prebuilt && LOCKFILE_INSTALL.test(request.command.trimStart())) {
391
+ throw incompleteBridge(physicalPath(readable(request.workingDirectory ?? workDir)));
392
+ }
393
+ const { child, exited } = start(request, false);
394
+ let stdout = "";
395
+ let stderr = "";
396
+ child.stdout?.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk));
397
+ child.stderr?.setEncoding("utf8").on("data", (chunk: string) => (stderr += chunk));
398
+ const { exitCode } = await exited;
399
+ return { exitCode, stdout, stderr };
400
+ };
401
+
402
+ const spawn = async (request: ProcessOptions & { stdin?: boolean }) => {
403
+ const bridge = BRIDGE_COMMAND.exec(request.command)?.[1];
404
+ if (!bridge && request.command.includes("bridge.mjs")) {
405
+ throw new HostSandboxError("the chat bridge must be started alone, from a quoted path");
406
+ }
407
+ if (!bridge && SCRIPT_START.test(bunCommand(request.command))) {
408
+ throw new HostSandboxError("the chat starts no script but its bridge");
409
+ }
410
+ let guardEnv: Readonly<Record<string, string>> = {};
411
+ if (bridge) {
412
+ const { guard, marks, env: bridgeEnv } = BRIDGE_GUARDS[bridgeKind(bridge)];
413
+ guardEnv = bridgeEnv;
414
+ const file = readable(bridge);
415
+ if (!isWithin(physicalPath(file), realCache)) {
416
+ throw new HostSandboxError("the chat starts only its installed bridge");
417
+ }
418
+ let source = await readFile(file, "utf8");
419
+ const guarded = guard(source);
420
+ if (guarded !== source) {
421
+ await writeAtomic(writable(bridge), guarded);
422
+ source = guarded;
423
+ }
424
+ if (source.includes(WILDCARD_BIND) || !source.includes(LOOPBACK_BIND)) {
425
+ throw new HostSandboxError("the chat bridge must listen on loopback only");
426
+ }
427
+ for (const [mark, reason] of marks) {
428
+ if (!source.includes(mark)) throw new HostSandboxError(reason);
429
+ }
430
+ }
431
+ const { child, exited } = start(
432
+ { ...request, env: { ...request.env, ...guardEnv } },
433
+ request.stdin === true,
434
+ );
435
+ const handle = {
436
+ stdout: Readable.toWeb(child.stdout!) as unknown as ReadableStream<Uint8Array>,
437
+ stderr: Readable.toWeb(child.stderr!) as unknown as ReadableStream<Uint8Array>,
438
+ wait: () => exited,
439
+ kill: () => end(child, exited),
440
+ };
441
+ if (!request.stdin) return handle;
442
+ return { ...handle, stdin: Writable.toWeb(child.stdin!) as WritableStream<Uint8Array> };
443
+ };
444
+
445
+ const readBinaryFile = async ({ path: target }: { path: string }): Promise<Uint8Array | null> => {
446
+ try {
447
+ return new Uint8Array(await readFile(readable(target)));
448
+ } catch (error) {
449
+ if (error instanceof HostSandboxError) throw error;
450
+ return null;
451
+ }
452
+ };
453
+
454
+ const writeBinaryFile = async ({
455
+ path: target,
456
+ content,
457
+ }: {
458
+ path: string;
459
+ content: Uint8Array;
460
+ }) => {
461
+ const file = writable(target);
462
+ const bytes =
463
+ path.basename(file) === "bridge.mjs" && isWithin(physicalPath(file), realCache)
464
+ ? new TextEncoder().encode(
465
+ guardedBridge(new TextDecoder().decode(content), bridgeKind(file)),
466
+ )
467
+ : content;
468
+ await mkdir(path.dirname(file), { recursive: true });
469
+ await writeAtomic(file, bytes);
470
+ };
471
+
472
+ const restricted = {
473
+ description: `This machine, read-only for the agent. The working directory is the Companion Repository ${workDir}.`,
474
+ run,
475
+ spawn,
476
+ readBinaryFile,
477
+ readFile: async ({ path: target }: { path: string }) => {
478
+ const bytes = await readBinaryFile({ path: target });
479
+ if (bytes === null) return null;
480
+ return new ReadableStream<Uint8Array>({
481
+ start: (controller) => {
482
+ controller.enqueue(bytes);
483
+ controller.close();
484
+ },
485
+ });
486
+ },
487
+ readTextFile: async ({
488
+ path: target,
489
+ startLine,
490
+ endLine,
491
+ }: {
492
+ path: string;
493
+ startLine?: number;
494
+ endLine?: number;
495
+ }) => {
496
+ const bytes = await readBinaryFile({ path: target });
497
+ if (bytes === null) return null;
498
+ const text = new TextDecoder().decode(bytes);
499
+ if (startLine === undefined && endLine === undefined) return text;
500
+ return text
501
+ .split("\n")
502
+ .slice((startLine ?? 1) - 1, endLine)
503
+ .join("\n");
504
+ },
505
+ writeBinaryFile,
506
+ writeTextFile: ({ path: target, content }: { path: string; content: string }) =>
507
+ writeBinaryFile({ path: target, content: new TextEncoder().encode(content) }),
508
+ writeFile: async ({
509
+ path: target,
510
+ content,
511
+ }: {
512
+ path: string;
513
+ content: ReadableStream<Uint8Array>;
514
+ }) =>
515
+ writeBinaryFile({
516
+ path: target,
517
+ content: new Uint8Array(await new Response(content).arrayBuffer()),
518
+ }),
519
+ } as unknown as SandboxSession;
520
+
521
+ const endpoint = async ({
522
+ port: asked,
523
+ protocol,
524
+ }: {
525
+ port: number;
526
+ protocol?: "http" | "https" | "ws";
527
+ }) => {
528
+ if (asked !== port) throw new HostSandboxError(`port ${asked} is not the chat bridge's`);
529
+ return { url: `${protocol ?? "http"}://127.0.0.1:${port}` };
530
+ };
531
+
532
+ const stop = async () => {
533
+ stopped = true;
534
+ const leaders = new Set([...children.keys()].map((child) => child.pid));
535
+ const orphaned = [...groups].filter((pid) => !leaders.has(pid) && groupAlive(pid));
536
+ for (const pid of orphaned) signalProcessGroup(pid, "SIGTERM");
537
+ await Promise.all([
538
+ ...[...children].map(([child, exited]) => end(child, exited)),
539
+ ...(orphaned.length > 0 ? [delay(STOP_GRACE_MS)] : []),
540
+ ]);
541
+ for (const pid of orphaned) signalProcessGroup(pid, "SIGKILL");
542
+ groups.clear();
543
+ claimedPorts.delete(port);
544
+ await rm(home, { recursive: true, force: true });
545
+ };
546
+
547
+ return {
548
+ ...restricted,
549
+ id: `studio-chat-${path.basename(home)}`,
550
+ home,
551
+ port,
552
+ defaultWorkingDirectory: workDir,
553
+ ports: [port],
554
+ getPortEndpoint: endpoint,
555
+ getPortUrl: async (request: { port: number; protocol?: "http" | "https" | "ws" }) =>
556
+ (await endpoint(request)).url,
557
+ stop,
558
+ destroy: stop,
559
+ restricted: () => restricted,
560
+ } as unknown as HostSandbox;
561
+ }
562
+
563
+ async function prepareHome(home: string, cache: string, workDir: string) {
564
+ await mkdir(path.join(home, path.dirname(BOOTSTRAP_LINK)), { recursive: true });
565
+ await symlink(cache, path.join(home, BOOTSTRAP_LINK));
566
+ await mkdir(path.join(home, ".claude"));
567
+ await writeFile(
568
+ path.join(home, ".claude", "settings.json"),
569
+ JSON.stringify({ disableSkillShellExecution: true }),
570
+ );
571
+ const [realWorkDir, realHome, realCache] = [workDir, home, cache].map(physicalPath) as [
572
+ string,
573
+ string,
574
+ string,
575
+ ];
576
+ const port = await claimBridgePort();
577
+ return { port, realWorkDir, realHome, realCache };
578
+ }
@@ -0,0 +1,95 @@
1
+ import { mkdir, mkdtemp, readdir, rm, symlink } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { CHAT_HARNESSES, CHAT_MODELS, type ChatHarness } from "./agent";
6
+ import { loadAdapter, loadHarness } from "./harness-chat-agent";
7
+ import { createHostSandbox } from "./host-sandbox";
8
+
9
+ export async function prepareChatBridges(destination: string): Promise<void> {
10
+ await mkdir(destination, { recursive: true });
11
+ const { createHarnessSandboxTemplate } = await import("@ai-sdk/harness/agent");
12
+ const workDir = await mkdtemp(path.join(os.tmpdir(), "mate-chat-bridges-"));
13
+ try {
14
+ const sandbox = await createHostSandbox({ workDir, bootstrapCache: destination });
15
+ try {
16
+ for (const harness of CHAT_HARNESSES) {
17
+ // oxlint-disable-next-line no-await-in-loop -- one install at a time.
18
+ const adapter = (await loadAdapter(harness))({
19
+ port: sandbox.port,
20
+ model: CHAT_MODELS[harness][0]!.id,
21
+ });
22
+ // oxlint-disable-next-line no-await-in-loop -- one install at a time.
23
+ const template = await createHarnessSandboxTemplate({ harnesses: [adapter as never] });
24
+ // oxlint-disable-next-line no-await-in-loop -- one install at a time.
25
+ await template?.prepare({ session: sandbox.restricted() });
26
+ // oxlint-disable-next-line no-await-in-loop -- one install at a time.
27
+ await PRUNE[harness]?.(path.join(destination, harness));
28
+ }
29
+ } finally {
30
+ await sandbox.stop();
31
+ }
32
+ } finally {
33
+ await rm(workDir, { recursive: true, force: true });
34
+ }
35
+ }
36
+
37
+ export async function checkChatBridges(directory: string): Promise<void> {
38
+ const workDir = await mkdtemp(path.join(os.tmpdir(), "mate-chat-bridges-"));
39
+ try {
40
+ for (const harness of CHAT_HARNESSES) {
41
+ // oxlint-disable-next-line no-await-in-loop -- one bridge at a time.
42
+ const sandbox = await createHostSandbox({ workDir, prebuiltBridges: directory });
43
+ try {
44
+ // oxlint-disable-next-line no-await-in-loop -- one bridge at a time.
45
+ const modules = await loadHarness(harness);
46
+ const agent = modules.createAgent({ port: sandbox.port, instructions: "", skills: [] });
47
+ const signal = new AbortController().signal;
48
+ // oxlint-disable-next-line no-await-in-loop -- one bridge at a time.
49
+ const session = await agent.createSession({ sandboxSession: sandbox, abortSignal: signal });
50
+ // oxlint-disable-next-line no-await-in-loop -- one bridge at a time.
51
+ await session.stop();
52
+ } finally {
53
+ // oxlint-disable-next-line no-await-in-loop -- one bridge at a time.
54
+ await sandbox.stop();
55
+ }
56
+ }
57
+ } finally {
58
+ await rm(workDir, { recursive: true, force: true });
59
+ }
60
+ }
61
+
62
+ const PRUNE: Partial<Record<ChatHarness, (bridge: string) => Promise<void>>> = {
63
+ "claude-code": async (bridge) => {
64
+ const scope = path.join(bridge, "node_modules", "@anthropic-ai");
65
+ const keep = `claude-agent-sdk-${process.platform}-${process.arch}`;
66
+ const native = /^claude-(?:code|agent-sdk)-/;
67
+ for (const name of await readdir(scope)) {
68
+ if (native.test(name) && name !== keep) {
69
+ // oxlint-disable-next-line no-await-in-loop -- a handful of directories.
70
+ await rm(path.join(scope, name), { recursive: true, force: true });
71
+ }
72
+ }
73
+ // The bootstrap's version check runs `.bin/claude`; it now names the SDK's binary.
74
+ const bin = path.join(bridge, "node_modules", ".bin", "claude");
75
+ await rm(bin, { force: true });
76
+ await symlink(path.join("..", "@anthropic-ai", keep, "claude"), bin);
77
+ },
78
+ };
79
+
80
+ if (import.meta.main) {
81
+ const [first, second] = process.argv.slice(2);
82
+ const check = first === "--check";
83
+ const directory = check ? second : first;
84
+ if (!directory) {
85
+ console.error("usage: bun prepare-bridges.ts [--check] <directory>");
86
+ process.exit(2);
87
+ }
88
+ if (check) {
89
+ await checkChatBridges(path.resolve(directory));
90
+ console.log(`the chat bridges in ${directory} start without installing`);
91
+ } else {
92
+ await prepareChatBridges(path.resolve(directory));
93
+ console.log(`prepared the chat bridges in ${directory}`);
94
+ }
95
+ }
@@ -0,0 +1,15 @@
1
+ import type { ChatHarness } from "./agent";
2
+
3
+ export const CHAT_TOOLS: Readonly<Record<ChatHarness, readonly string[]>> = {
4
+ "claude-code": ["read", "grep", "glob", "Skill"],
5
+ opencode: ["read", "grep", "glob"],
6
+ };
7
+
8
+ export interface ChatSession {
9
+ mcpServers: string[];
10
+ plugins: string[];
11
+ }
12
+
13
+ export function chatSession(): ChatSession {
14
+ return { mcpServers: [], plugins: [] };
15
+ }