@madarco/agentbox 0.23.5 → 0.24.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 (180) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/LICENSE +21 -0
  3. package/README.md +3 -2
  4. package/dist/{_cloud-attach-D4OQO5AJ.js → _cloud-attach-T6GPR6LJ.js} +5 -5
  5. package/dist/{chunk-KY32JO6J.js → chunk-5KHEH47T.js} +91 -79
  6. package/dist/chunk-5KHEH47T.js.map +1 -0
  7. package/dist/{chunk-YRTM3KNT.js → chunk-6U2S6QWD.js} +219 -18
  8. package/dist/chunk-6U2S6QWD.js.map +1 -0
  9. package/dist/{chunk-JYEZ6Q5M.js → chunk-DEDTPG2D.js} +874 -146
  10. package/dist/chunk-DEDTPG2D.js.map +1 -0
  11. package/dist/chunk-G3H2L3O2.js +0 -0
  12. package/dist/{chunk-JNY5GPIM.js → chunk-I654PBHA.js} +290 -330
  13. package/dist/chunk-I654PBHA.js.map +1 -0
  14. package/dist/{chunk-6KOQRSHH.js → chunk-K2EDQGZP.js} +18 -4
  15. package/dist/chunk-K2EDQGZP.js.map +1 -0
  16. package/dist/{chunk-KZWJMNLP.js → chunk-LC4E2EIZ.js} +3 -3
  17. package/dist/{chunk-KZWJMNLP.js.map → chunk-LC4E2EIZ.js.map} +1 -1
  18. package/dist/{chunk-DADOEMXP.js → chunk-NACA6AM7.js} +183 -49
  19. package/dist/chunk-NACA6AM7.js.map +1 -0
  20. package/dist/{chunk-FX32NZD4.js → chunk-RYQLFKCP.js} +20 -10
  21. package/dist/chunk-RYQLFKCP.js.map +1 -0
  22. package/dist/{chunk-QT3SHMLY.js → chunk-UIRBYL4G.js} +43 -12
  23. package/dist/chunk-UIRBYL4G.js.map +1 -0
  24. package/dist/chunk-WJFZJZIM.js +0 -0
  25. package/dist/chunk-WLHJZPFJ.js +845 -0
  26. package/dist/chunk-WLHJZPFJ.js.map +1 -0
  27. package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
  28. package/dist/dist-3KIJ2KQ2.js +1437 -0
  29. package/dist/dist-3KIJ2KQ2.js.map +1 -0
  30. package/dist/{dist-564EDHFF.js → dist-7OUOHQPA.js} +196 -151
  31. package/dist/dist-7OUOHQPA.js.map +1 -0
  32. package/dist/{dist-CAT2TN75.js → dist-B7TNWGVG.js} +8 -4
  33. package/dist/{dist-UDQMBWYW.js → dist-KYV3LEHG.js} +10 -6
  34. package/dist/{dist-EAR4BLL2.js → dist-PHYCFYKH.js} +37 -17
  35. package/dist/dist-PHYCFYKH.js.map +1 -0
  36. package/dist/{dist-2BTJQUJS.js → dist-T5MXBZGP.js} +2 -2
  37. package/dist/{dist-O5Y4X4C5.js → dist-Z7KEPQC7.js} +6 -6
  38. package/dist/index.js +2560 -1108
  39. package/dist/index.js.map +1 -1
  40. package/dist/{prepared-state-BUO75YLZ-PW64VQMT.js → prepared-state-BUO75YLZ-RQRFFBJW.js} +2 -2
  41. package/package.json +28 -28
  42. package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
  43. package/runtime/_shared/agentbox-codex-hooks.json +1 -1
  44. package/runtime/_shared/agentbox-dockerd-start +0 -0
  45. package/runtime/_shared/agentbox-open +0 -0
  46. package/runtime/_shared/agentbox-portless-trust +0 -0
  47. package/runtime/_shared/agentbox-vnc-start +0 -0
  48. package/runtime/_shared/ctl.cjs +468 -97
  49. package/runtime/_shared/gh-shim +0 -0
  50. package/runtime/_shared/git-shim +53 -3
  51. package/runtime/_shared/linear-shim +0 -0
  52. package/runtime/_shared/ntn-shim +0 -0
  53. package/runtime/daytona/custom-system-CLAUDE.md +1 -1
  54. package/runtime/digitalocean/agentbox-checkpoint-cleanup +55 -0
  55. package/runtime/digitalocean/agentbox-codex-hooks.json +68 -0
  56. package/runtime/digitalocean/agentbox-dockerd-start +145 -0
  57. package/runtime/digitalocean/agentbox-open +28 -0
  58. package/runtime/digitalocean/agentbox-portless-trust +82 -0
  59. package/runtime/digitalocean/agentbox-setup-skill.md +317 -0
  60. package/runtime/digitalocean/agentbox-vnc-start +102 -0
  61. package/runtime/digitalocean/claude-managed-settings.json +116 -0
  62. package/runtime/digitalocean/ctl.cjs +27852 -0
  63. package/runtime/digitalocean/custom-system-CLAUDE.md +39 -0
  64. package/runtime/digitalocean/gh-shim +344 -0
  65. package/runtime/digitalocean/git-shim +181 -0
  66. package/runtime/digitalocean/linear-shim +181 -0
  67. package/runtime/digitalocean/ntn-shim +95 -0
  68. package/runtime/digitalocean/opencode-agentbox-plugin.js +76 -0
  69. package/runtime/digitalocean/scripts/install-box.sh +462 -0
  70. package/runtime/docker/Dockerfile.box +5 -0
  71. package/runtime/docker/packages/ctl/dist/bin.cjs +468 -97
  72. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
  73. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json +1 -1
  74. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-dockerd-start +0 -0
  75. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-open +0 -0
  76. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-portless-trust +0 -0
  77. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-sshd-start +0 -0
  78. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-vnc-start +0 -0
  79. package/runtime/docker/packages/sandbox-docker/scripts/chromium-resolver +0 -0
  80. package/runtime/docker/packages/sandbox-docker/scripts/custom-system-CLAUDE.md +2 -1
  81. package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +0 -0
  82. package/runtime/docker/packages/sandbox-docker/scripts/git-shim +53 -3
  83. package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -0
  84. package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -0
  85. package/runtime/e2b/agentbox-checkpoint-cleanup +0 -0
  86. package/runtime/e2b/agentbox-codex-hooks.json +1 -1
  87. package/runtime/e2b/agentbox-dockerd-start +0 -0
  88. package/runtime/e2b/agentbox-open +0 -0
  89. package/runtime/e2b/agentbox-vnc-start +0 -0
  90. package/runtime/e2b/ctl.cjs +468 -97
  91. package/runtime/e2b/custom-system-CLAUDE.md +6 -3
  92. package/runtime/e2b/gh-shim +0 -0
  93. package/runtime/e2b/git-shim +53 -3
  94. package/runtime/e2b/linear-shim +0 -0
  95. package/runtime/e2b/ntn-shim +0 -0
  96. package/runtime/e2b/scripts/build-template.sh +16 -0
  97. package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
  98. package/runtime/hetzner/agentbox-codex-hooks.json +1 -1
  99. package/runtime/hetzner/agentbox-dockerd-start +0 -0
  100. package/runtime/hetzner/agentbox-open +0 -0
  101. package/runtime/hetzner/agentbox-portless-trust +0 -0
  102. package/runtime/hetzner/agentbox-vnc-start +0 -0
  103. package/runtime/hetzner/ctl.cjs +468 -97
  104. package/runtime/hetzner/custom-system-CLAUDE.md +1 -1
  105. package/runtime/hetzner/gh-shim +0 -0
  106. package/runtime/hetzner/git-shim +53 -3
  107. package/runtime/hetzner/linear-shim +0 -0
  108. package/runtime/hetzner/ntn-shim +0 -0
  109. package/runtime/hetzner/scripts/install-box.sh +5 -0
  110. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  111. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  113. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  115. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  117. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  119. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  120. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +12 -12
  121. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +1 -1
  122. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +1 -1
  123. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +1 -1
  124. package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +8 -8
  125. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ro6vh6._.js +1 -1
  126. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0b_hsjl._.js +1 -1
  127. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  128. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  129. package/runtime/hub/apps/hub/.next/static/chunks/380qcmusmigzz.js +1 -0
  130. package/runtime/hub/apps/hub/{auth-675P3LQS.js → auth-Q447765C.js} +2 -2
  131. package/runtime/hub/apps/hub/{auth-config-AOBEKRZQ.js → auth-config-SIL635ZD.js} +2 -2
  132. package/runtime/hub/apps/hub/{chunk-FSEPYTQ6.js → chunk-3VE7AYVK.js} +594 -145
  133. package/runtime/hub/apps/hub/{chunk-EXQCBM5Q.js → chunk-64WEKO34.js} +42 -11
  134. package/runtime/hub/apps/hub/{chunk-56YQBVN2.js → chunk-DZPQB2JZ.js} +1 -1
  135. package/runtime/hub/apps/hub/{chunk-7M6FXZIO.js → chunk-FGBXEXUV.js} +350 -292
  136. package/runtime/hub/apps/hub/{chunk-Z7ZAL24C.js → chunk-YVELHPNY.js} +218 -17
  137. package/runtime/hub/apps/hub/{dist-EKQHCXWE.js → dist-33ZNVTC6.js} +183 -49
  138. package/runtime/hub/apps/hub/{dist-V4TJ44MT.js → dist-4SXAJBOC.js} +195 -150
  139. package/runtime/hub/apps/hub/{dist-QIXUPGPP.js → dist-EPJFN2J3.js} +116 -86
  140. package/runtime/hub/apps/hub/{dist-STQK5XM6.js → dist-GF5EBRNG.js} +1 -1
  141. package/runtime/hub/apps/hub/{dist-JGZ55OIJ.js → dist-UJVIROA4.js} +19 -5
  142. package/runtime/hub/apps/hub/dist-XULFTIMT.js +2212 -0
  143. package/runtime/hub/apps/hub/{dist-GGWYKXJE.js → dist-YM5J25H6.js} +7 -3
  144. package/runtime/hub/apps/hub/{hub-token-2BZFBBW3.js → hub-token-UITZEWVP.js} +2 -2
  145. package/runtime/hub/apps/hub/package.json +1 -0
  146. package/runtime/hub/apps/hub/{prepared-state-BUO75YLZ-UICXTY25.js → prepared-state-BUO75YLZ-O4GZMDRF.js} +1 -1
  147. package/runtime/hub/apps/hub/server.js +17 -15
  148. package/runtime/relay/bin.cjs +275 -59
  149. package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
  150. package/runtime/vercel/agentbox-codex-hooks.json +1 -1
  151. package/runtime/vercel/agentbox-dockerd-start +0 -0
  152. package/runtime/vercel/agentbox-open +0 -0
  153. package/runtime/vercel/agentbox-vnc-start +0 -0
  154. package/runtime/vercel/ctl.cjs +468 -97
  155. package/runtime/vercel/custom-system-CLAUDE.md +3 -2
  156. package/runtime/vercel/gh-shim +0 -0
  157. package/runtime/vercel/git-shim +53 -3
  158. package/runtime/vercel/linear-shim +0 -0
  159. package/runtime/vercel/ntn-shim +0 -0
  160. package/runtime/vercel/scripts/provision.sh +16 -0
  161. package/dist/chunk-6KOQRSHH.js.map +0 -1
  162. package/dist/chunk-DADOEMXP.js.map +0 -1
  163. package/dist/chunk-FX32NZD4.js.map +0 -1
  164. package/dist/chunk-JNY5GPIM.js.map +0 -1
  165. package/dist/chunk-JYEZ6Q5M.js.map +0 -1
  166. package/dist/chunk-KY32JO6J.js.map +0 -1
  167. package/dist/chunk-QT3SHMLY.js.map +0 -1
  168. package/dist/chunk-YRTM3KNT.js.map +0 -1
  169. package/dist/dist-564EDHFF.js.map +0 -1
  170. package/dist/dist-EAR4BLL2.js.map +0 -1
  171. package/runtime/hub/apps/hub/.next/static/chunks/0joh_xsiowfc4.js +0 -1
  172. /package/dist/{_cloud-attach-D4OQO5AJ.js.map → _cloud-attach-T6GPR6LJ.js.map} +0 -0
  173. /package/dist/{dist-2BTJQUJS.js.map → dist-B7TNWGVG.js.map} +0 -0
  174. /package/dist/{dist-CAT2TN75.js.map → dist-KYV3LEHG.js.map} +0 -0
  175. /package/dist/{dist-O5Y4X4C5.js.map → dist-T5MXBZGP.js.map} +0 -0
  176. /package/dist/{dist-UDQMBWYW.js.map → dist-Z7KEPQC7.js.map} +0 -0
  177. /package/dist/{prepared-state-BUO75YLZ-PW64VQMT.js.map → prepared-state-BUO75YLZ-RQRFFBJW.js.map} +0 -0
  178. /package/runtime/hub/apps/hub/.next/static/{lOi70Di6lcnEBsUUHKrQ5 → XtIjHGqvY4mQsOY2-m1Jy}/_buildManifest.js +0 -0
  179. /package/runtime/hub/apps/hub/.next/static/{lOi70Di6lcnEBsUUHKrQ5 → XtIjHGqvY4mQsOY2-m1Jy}/_clientMiddlewareManifest.js +0 -0
  180. /package/runtime/hub/apps/hub/.next/static/{lOi70Di6lcnEBsUUHKrQ5 → XtIjHGqvY4mQsOY2-m1Jy}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../packages/sandbox-docker/src/docker-provider.ts","../../../packages/sandbox-docker/src/sync/docker-sync.ts","../../../packages/sandbox-docker/src/sync/agents/claude.ts","../../../packages/sandbox-docker/src/docker.ts","../../../packages/sandbox-docker/src/sync/host-export.ts","../../../packages/sandbox-docker/src/box-cp.ts","../../../packages/sandbox-docker/src/sync/sync-transport.ts","../../../packages/sandbox-docker/src/sync/claude-credentials.ts","../../../packages/sandbox-docker/src/state.ts","../../../packages/sandbox-docker/src/sync/agents/codex.ts","../../../packages/sandbox-docker/src/sync/agents/skills.ts","../../../packages/sandbox-docker/src/sync/agents/opencode.ts","../../../packages/sandbox-docker/src/sync/in-box-git.ts","../../../packages/sandbox-docker/src/git-worktree.ts","../../../packages/sandbox-docker/src/create.ts","../../../packages/sandbox-docker/src/dockerd.ts","../../../packages/sandbox-docker/src/vnc.ts","../../../packages/sandbox-docker/src/ssh.ts","../../../packages/sandbox-docker/src/web.ts","../../../packages/sandbox-docker/src/portless.ts","../../../packages/sandbox-docker/src/snapshot.ts","../../../packages/sandbox-docker/src/checkpoint.ts","../../../packages/sandbox-docker/src/ctl.ts","../../../packages/sandbox-docker/src/box-env.ts","../../../packages/sandbox-docker/src/home-ownership.ts","../../../packages/sandbox-docker/src/relay.ts","../../../packages/sandbox-docker/src/vscode.ts","../../../packages/sandbox-docker/src/lifecycle.ts","../../../packages/sandbox-docker/src/shell-session.ts","../../../packages/sandbox-docker/src/endpoints.ts","../../../packages/sandbox-docker/src/stats.ts","../../../packages/sandbox-docker/src/provider-module.ts","../../../packages/sandbox-docker/src/sync/settings-propagate.ts","../../../packages/sandbox-docker/src/hub.ts","../../../packages/sandbox-docker/src/index.ts","../../../packages/sandbox-docker/src/sync/dynamic-sync.ts","../../../packages/sandbox-docker/src/browser.ts","../../../packages/ctl/src/types.ts","../../../packages/ctl/src/client.ts","../../../packages/ctl/src/render.ts","../../../packages/ctl/src/config.ts","../../../packages/ctl/src/replace.ts","../../../packages/ctl/src/carry.ts","../../../packages/relay/src/types.ts","../../../packages/relay/src/registry.ts","../../../packages/relay/src/status-store.ts","../../../packages/relay/src/store/memory-store.ts","../../../packages/relay/src/prompts.ts","../../../packages/relay/src/permission.ts","../../../packages/relay/src/worktree.ts","../../../packages/relay/src/git-pat.ts","../../../packages/relay/src/lease.ts","../../../packages/relay/src/github-app.ts","../../../packages/relay/src/create-worker.ts","../../../packages/relay/src/store/store-rpc.ts","../../../packages/relay/src/core/handler.ts","../../../packages/relay/src/store/postgres-store.ts","../../../packages/relay/src/server.ts","../../../packages/relay/src/host-actions.ts","../../../packages/relay/src/gh.ts","../../../packages/relay/src/host-initiated.ts","../../../packages/relay/src/cp-rpc.ts","../../../packages/relay/src/integrations.ts","../../../packages/relay/src/safe-transfer.ts","../../../packages/relay/src/host-action-queue.ts","../../../packages/relay/src/hub-notifier.ts","../../../packages/relay/src/notices.ts","../../../packages/relay/src/credentials-fanout.ts","../../../packages/relay/src/autopause.ts","../../../packages/relay/src/queue.ts","../../../packages/relay/src/cloud-keepalive.ts","../../../packages/relay/src/daemon.ts","../../../packages/integrations/src/connectors/linear.ts","../../../packages/integrations/src/connectors/notion.ts","../../../packages/integrations/src/registry.ts"],"sourcesContent":["/**\n * `DockerProvider` — the local-Docker implementation of the provider-neutral\n * `Provider` interface. A thin adapter: every method delegates to the existing\n * `createBox` / lifecycle / docker / stats functions. The CLI resolves this via\n * the provider registry for any box whose `provider` is `'docker'`.\n */\n\nimport type {\n BoxRecord,\n BoxResourceStats,\n BoxRuntimeState,\n CreateBoxRequest,\n CreatedBox,\n ExecOptions,\n ExecResult,\n InspectedBox,\n PrepareOptions,\n PrepareResult,\n Provider,\n ProviderSync,\n ResyncResult,\n SyncTransport,\n} from '@agentbox/core';\nimport { claudeInstallFingerprint, makeSyncContext } from '@agentbox/sandbox-core';\nimport { makeDockerSync } from './sync/docker-sync.js';\nimport { createDockerSyncTransport } from './sync/sync-transport.js';\nimport { createBox, type CreateBoxOptions } from './create.js';\nimport { destroyBox, inspectBox, pauseBox, startBox, stopBox, unpauseBox } from './lifecycle.js';\nimport { execInBox, inspectContainerStatus } from './docker.js';\nimport { boxResourceStats } from './stats.js';\nimport { detectEngine } from './sync/host-export.js';\nimport { portlessGetUrl } from './portless.js';\nimport { DEFAULT_BOX_IMAGE, imageExists, pullOrBuild } from './image.js';\nimport {\n computeDockerContextFingerprint,\n preparedMatches,\n readPreparedDockerState,\n} from './prepared-state.js';\nimport { downloadFromBox, uploadToBox } from './box-cp.js';\n\n/**\n * Docker-specific knobs the CLI passes through `CreateBoxRequest.providerOptions`.\n * Kept out of the provider-neutral `CreateBoxRequest` so cloud backends don't\n * carry Docker concepts.\n */\nexport interface DockerCreateOptions {\n useSnapshot?: boolean;\n sharedCache?: boolean;\n portless?: boolean;\n portlessStateDir?: string;\n claudeConfig?: { isolate: boolean };\n codexConfig?: { isolate: boolean };\n opencodeConfig?: { isolate: boolean };\n claudeEnv?: Record<string, string>;\n}\n\nexport const dockerProvider: Provider = {\n name: 'docker',\n\n async create(req: CreateBoxRequest): Promise<CreatedBox> {\n const po = (req.providerOptions ?? {}) as DockerCreateOptions;\n const opts: CreateBoxOptions = {\n workspacePath: req.workspacePath,\n name: req.name,\n useSnapshot: po.useSnapshot ?? false,\n checkpointRef: req.checkpointRef,\n fromBranch: req.fromBranch,\n useBranch: req.useBranch,\n resyncOnStart: req.resyncOnStart,\n image: req.image,\n allowPull: req.allowPull,\n imageRegistry: req.imageRegistry,\n onLog: req.onLog,\n claudeConfig: po.claudeConfig,\n claudeEnv: po.claudeEnv,\n codexConfig: po.codexConfig,\n opencodeConfig: po.opencodeConfig,\n withPlaywright: req.withPlaywright,\n withEnv: req.withEnv,\n envFilesToImport: req.envFilesToImport,\n carry: req.carry,\n vnc: req.vnc,\n docker: po.sharedCache !== undefined ? { sharedCache: po.sharedCache } : undefined,\n portless: po.portless,\n portlessStateDir: po.portlessStateDir,\n projectRoot: req.projectRoot,\n limits: req.limits ?? undefined,\n credentialSync: req.credentialSync,\n };\n const result = await createBox(opts);\n return {\n record: { ...result.record, provider: 'docker' },\n imageBuilt: result.imageBuilt,\n resync: result.resync,\n };\n },\n\n async start(box: BoxRecord): Promise<BoxRecord> {\n const { record } = await startBox(box.id);\n return { ...record, provider: 'docker' };\n },\n\n async reconnect(box: BoxRecord): Promise<BoxRecord> {\n // Reconnect re-establishes host-side wiring without a needless power-cycle.\n // A PAUSED container can't `docker start` (\"cannot start a paused\n // container\") — unpause resumes its still-frozen ctl/dockerd/vnc, and the\n // portless alias is untouched by pause, so that's all it needs. A running or\n // stopped container goes through `startBox`, which is idempotent (a\n // `docker start` on a live container is a no-op) and relaunches the daemons\n // + re-registers portless — the work a host reboot / relay restart needs.\n const insp = await inspectBox(box.id);\n if (insp.state === 'missing' || insp.state === 'destroyed') {\n throw new Error(`box ${box.name} has no container; was it destroyed?`);\n }\n if (insp.state === 'paused') {\n const record = await unpauseBox(box.id);\n return { ...record, provider: 'docker' };\n }\n const { record } = await startBox(box.id);\n return { ...record, provider: 'docker' };\n },\n\n async pause(box: BoxRecord): Promise<void> {\n await pauseBox(box.id);\n },\n\n async resume(box: BoxRecord): Promise<void> {\n await unpauseBox(box.id);\n },\n\n async stop(box: BoxRecord): Promise<void> {\n await stopBox(box.id);\n },\n\n async destroy(box: BoxRecord): Promise<void> {\n await destroyBox(box.id);\n },\n\n async resyncWorkspace(box: BoxRecord, onLog?: (line: string) => void): Promise<ResyncResult> {\n // Merge the host's current branch into each per-box worktree + overlay the\n // host's uncommitted/untracked (box wins). Reproduces `resyncBox`: the\n // facade short-circuits when the box has no worktrees. Only `ctx.onLog` is\n // read by resync (the concern reads each worktree's hostMainRepo).\n const ctx = makeSyncContext({\n boxName: box.name,\n boxId: box.id,\n provider: 'docker',\n hostWorkspace: box.workspacePath,\n onLog,\n });\n return makeDockerSync({ container: box.container }).resyncWorkspace(ctx, box.gitWorktrees ?? []);\n },\n\n sync(box: BoxRecord): ProviderSync {\n return makeDockerSync({ container: box.container });\n },\n\n syncTransport(box: BoxRecord): SyncTransport {\n return createDockerSyncTransport({ container: box.container, image: box.image });\n },\n\n async inspect(box: BoxRecord): Promise<InspectedBox> {\n const insp = await inspectBox(box.id);\n return {\n record: insp.record,\n // The Docker `BoxState` adds a 'destroyed' value the provider-neutral\n // `BoxRuntimeState` folds into 'missing'.\n state: insp.state === 'destroyed' ? 'missing' : insp.state,\n endpoints: insp.endpoints,\n raw: insp.dockerInspect,\n };\n },\n\n async probeState(box: BoxRecord): Promise<BoxRuntimeState> {\n return inspectContainerStatus(box.container);\n },\n\n async stats(box: BoxRecord): Promise<BoxResourceStats> {\n return boxResourceStats(box);\n },\n\n async exec(box: BoxRecord, argv: string[], opts?: ExecOptions): Promise<ExecResult> {\n const r = await execInBox(box.container, argv, opts?.user ? { user: opts.user } : {});\n return { exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr };\n },\n\n async uploadPath(\n box: BoxRecord,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n const r = await uploadToBox(box, hostSrcs, boxDst, exclude);\n return { finalPath: r.finalPath };\n },\n\n async downloadPath(\n box: BoxRecord,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n ): Promise<{ finalPath: string }> {\n const r = await downloadFromBox(box, boxSrcs, hostDst, exclude);\n return { finalPath: r.finalPath };\n },\n\n async resolveUrl(\n box: BoxRecord,\n opts?: { loopback?: boolean; kind?: 'web' | 'vnc'; ttl?: number },\n ): Promise<string> {\n if (box.webContainerPort === undefined) {\n throw new Error(\n `box ${box.name} predates the reserved web port; recreate it to use \\`agentbox url\\``,\n );\n }\n const engine = await detectEngine();\n if (engine === 'orbstack' && !opts?.loopback) {\n // OrbStack auto-routes <container>.orb.local to the container; :80 is\n // declared (EXPOSE 80) so no port suffix is needed.\n return `http://${box.container}.orb.local`;\n }\n if (box.portlessAlias && !opts?.loopback) {\n return box.portlessUrl ?? (await portlessGetUrl(box.portlessAlias));\n }\n if (box.webHostPort === undefined) {\n throw new Error(`web port not resolved for box ${box.name}; is the container running?`);\n }\n return `http://127.0.0.1:${String(box.webHostPort)}`;\n },\n\n async prepare(opts: PrepareOptions): Promise<PrepareResult> {\n // Docker uses the rsync-into-named-volume flow at create time, so the\n // base image stays generic — no agent-config layering. `prepare` here is\n // just an explicit handle on the build step `agentbox create` does\n // lazily on first use. Idempotent: skip when the image exists *and* the\n // build-context fingerprint matches the recorded one. `--force`\n // overrides both checks.\n const ref = DEFAULT_BOX_IMAGE;\n const claudeInstall = opts.claudeInstall ?? 'native';\n const rawFingerprint = await computeDockerContextFingerprint();\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged).\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : null;\n const prepared = readPreparedDockerState();\n\n if (!opts.force) {\n const exists = await imageExists(ref);\n if (exists && fingerprint && preparedMatches(prepared, fingerprint.contextSha256)) {\n opts.onLog?.(\n `docker image ${ref} up to date (fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping (use --force to rebuild)`,\n );\n return {};\n }\n if (exists && !fingerprint) {\n opts.onLog?.(\n `docker image ${ref} present but build context could not be fingerprinted — skipping (use --force to rebuild)`,\n );\n return {};\n }\n }\n\n // `--force` skips the registry pull and always builds a fresh local image.\n // npm mode must also build locally — the published GHCR image is native-only.\n const npm = claudeInstall === 'npm';\n const { source } = await pullOrBuild(ref, fingerprint, {\n onProgress: opts.onLog,\n allowPull: opts.force || npm ? false : opts.allowPull,\n registry: opts.registry,\n buildArgs: npm ? { AGENTBOX_CLAUDE_INSTALL: 'npm' } : undefined,\n });\n if (fingerprint) {\n opts.onLog?.(\n `docker image ${ref} ${source}; recorded fingerprint ${fingerprint.contextSha256.slice(0, 12)}`,\n );\n } else {\n opts.onLog?.(\n `docker image ${ref} ${source} (fingerprint unavailable, prepared state not written)`,\n );\n }\n return {};\n },\n};\n","/**\n * `makeDockerSync` — the co-located `ProviderSync` facade for the docker\n * provider. THIS FILE is \"everything docker syncs\": one method per shared sync\n * op, each a thin delegation to the existing docker seed/copy/credential/resync\n * function, byte-identical to the pre-facade create path.\n *\n * The handle is closed at construction. Post-create (`dockerProvider.sync(box)`)\n * needs only `{ container }` — it's used for `resyncWorkspace`. The create path\n * builds the full handle (image + the resolved per-tool volume specs) so\n * `seedAgentConfig` / `seedCredentials` can run the volume seeds; create.ts still\n * resolves those specs once and builds the container mounts from them (one source\n * of truth for the `--isolate-*` flags + want-codex/opencode conditionals).\n *\n * NOT here (deliberate carve-out): **workspace seed** — docker's `git worktree\n * add` + `mount --bind` replay of host stash/untracked has no cloud analog (cloud\n * clones), so it stays a provider-specific step called directly by `create()`.\n * See `docs/sync-architecture.md` §\"Deliberate non-unifications\".\n */\n\nimport type {\n CarryApplyResult,\n GitWorktreeRecord,\n ProviderSync,\n ResolvedCarryEntry,\n ResyncResult,\n SyncContext,\n} from '@agentbox/core';\nimport { dryRunProviderSync, SYNC_DRYRUN_ENV } from '@agentbox/core';\nimport { renderCarryEntries } from '@agentbox/sandbox-core';\nimport type { ClaudeConfigSpec } from './agents/claude.js';\nimport { ensureClaudeVolume, seedSetupSkillIntoVolume } from './agents/claude.js';\nimport { syncClaudeCredentials } from './claude-credentials.js';\nimport type { CodexConfigSpec } from './agents/codex.js';\nimport { ensureCodexVolume, seedCodexAgentsOverride, seedCodexHooks } from './agents/codex.js';\nimport type { AgentsConfigSpec } from './agents/skills.js';\nimport { ensureAgentsVolume } from './agents/skills.js';\nimport type { OpencodeConfigSpec } from './agents/opencode.js';\nimport { ensureOpencodeVolume, seedOpencodePlugin } from './agents/opencode.js';\nimport { copyCarryPathsToBox, copyHostEnvFilesToBox } from './host-export.js';\nimport { resyncWorkspaceFromHost } from './in-box-git.js';\n\nexport interface DockerSyncHandle {\n /** Running container name (all box-side ops target it). */\n container: string;\n /**\n * Box image (ensureRef) used by the throwaway root seed-helper containers.\n * Required for the create-path seeds (`seedAgentConfig`/`seedCredentials`);\n * omitted post-create (those ops don't run then).\n */\n image?: string;\n /** Resolved claude config-volume spec (create-path). */\n claudeSpec?: ClaudeConfigSpec;\n /** Whether the claude config volume is per-box isolated (gates the credential extract). */\n claudeIsolate?: boolean;\n /** Resolved codex spec, or undefined when codex isn't wanted (host has no ~/.codex + no `agentbox codex`). */\n codexSpec?: CodexConfigSpec;\n /** Resolved agents (~/.agents) spec, or undefined when the host has no ~/.agents. */\n agentsSpec?: AgentsConfigSpec;\n /** Resolved opencode spec, or undefined when opencode isn't wanted. */\n opencodeSpec?: OpencodeConfigSpec;\n}\n\n/** Guard: the create-path seeds need the box image + resolved claude spec in the handle. */\nfunction requireCreateHandle(\n handle: DockerSyncHandle,\n op: string,\n): { image: string; claudeSpec: ClaudeConfigSpec } {\n if (!handle.image || !handle.claudeSpec) {\n throw new Error(\n `dockerSync.${op} requires a create-time handle (image + claudeSpec); it is not available post-create`,\n );\n }\n return { image: handle.image, claudeSpec: handle.claudeSpec };\n}\n\nexport function makeDockerSync(handle: DockerSyncHandle): ProviderSync {\n if (process.env[SYNC_DRYRUN_ENV]) return dryRunProviderSync('docker');\n return {\n async resyncWorkspace(\n ctx: SyncContext,\n worktrees: GitWorktreeRecord[],\n ): Promise<ResyncResult> {\n // Reproduces `resyncBox`'s empty-worktrees short-circuit, then drives the\n // provider-neutral resync concern through the docker resync ports.\n if (worktrees.length === 0) return { repos: [], hadConflicts: false };\n const repos = await resyncWorkspaceFromHost({\n container: handle.container,\n worktrees,\n onLog: ctx.onLog,\n });\n const hadConflicts = repos.some(\n (r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0,\n );\n return { repos, hadConflicts };\n },\n\n async seedAgentConfig(ctx: SyncContext): Promise<void> {\n // The per-tool config volume seeds, in create order. Static config +\n // skills + dynamic + box-facts all ride these volume rsyncs / overrides:\n // - claude: ensureClaudeVolume (host ~/.claude rsync, carries dynamic\n // workflows/memory + box-facts via .claude) + the box-only\n // /agentbox-setup skill seed.\n // - codex: ensureCodexVolume + activity hooks + the AGENTS.override.md\n // box-facts fold.\n // - agents: ensureAgentsVolume (~/.agents skills).\n // - opencode: ensureOpencodeVolume + the state-reporting plugin.\n // Volume *mounts* are built by create.ts from the same specs.\n const { image, claudeSpec } = requireCreateHandle(handle, 'seedAgentConfig');\n const log = ctx.onLog;\n\n const claudeEnsured = await ensureClaudeVolume(claudeSpec, {\n syncFromHost: true,\n image,\n hostWorkspace: ctx.hostWorkspace,\n });\n if (claudeEnsured.synced) {\n log(`synced ${claudeSpec.volume} from ~/.claude`);\n if ((claudeEnsured.filteredHookCount ?? 0) > 0) {\n log(`filtered ${String(claudeEnsured.filteredHookCount)} host-path hook(s) (paths under ~/)`);\n }\n if (claudeEnsured.installMethodFixed) {\n log('set installMethod=native in synced .claude.json (matches box native install)');\n }\n if (claudeEnsured.aliasedProjectKey) {\n log(`aliased project state for ${ctx.hostWorkspace} -> /workspace in synced .claude.json`);\n }\n if (claudeEnsured.workspaceTrusted) {\n log('pre-trusted /workspace in synced .claude.json (skips the trust dialog)');\n }\n } else if (claudeEnsured.created) {\n log(`created empty volume ${claudeSpec.volume} (no host ~/.claude to sync)`);\n } else {\n log(`reusing volume ${claudeSpec.volume} (no host ~/.claude to sync)`);\n }\n const seeded = await seedSetupSkillIntoVolume(claudeSpec.volume, image);\n if (seeded.seeded) log(`refreshed /agentbox-setup skill into ${claudeSpec.volume}`);\n\n if (handle.codexSpec) {\n const codexSpec = handle.codexSpec;\n const codexEnsured = await ensureCodexVolume(codexSpec, { syncFromHost: true, image });\n if (codexEnsured.synced) log(`synced ${codexSpec.volume} from ~/.codex`);\n else if (codexEnsured.created) log(`created empty volume ${codexSpec.volume} (no host ~/.codex)`);\n else log(`reusing volume ${codexSpec.volume}`);\n const codexHooks = await seedCodexHooks(codexSpec.volume, image);\n if (codexHooks.seeded) log(`seeded Codex activity hooks into ${codexSpec.volume}`);\n const codexOverride = await seedCodexAgentsOverride(codexSpec.volume, image);\n if (codexOverride.seeded) log(`seeded Codex AGENTS.override.md into ${codexSpec.volume}`);\n }\n\n if (handle.agentsSpec) {\n const agentsSpec = handle.agentsSpec;\n const agentsEnsured = await ensureAgentsVolume(agentsSpec, { syncFromHost: true, image });\n if (agentsEnsured.synced) log(`synced ${agentsSpec.volume} from ~/.agents`);\n else if (agentsEnsured.created) log(`created empty volume ${agentsSpec.volume}`);\n else log(`reusing volume ${agentsSpec.volume}`);\n }\n\n if (handle.opencodeSpec) {\n const opencodeSpec = handle.opencodeSpec;\n const opencodeEnsured = await ensureOpencodeVolume(opencodeSpec, { syncFromHost: true, image });\n if (opencodeEnsured.synced) log(`synced ${opencodeSpec.volume} from ~/.config + ~/.local/share opencode`);\n else if (opencodeEnsured.created) log(`created empty volume ${opencodeSpec.volume} (no host opencode)`);\n else log(`reusing volume ${opencodeSpec.volume}`);\n const opencodePlugin = await seedOpencodePlugin(opencodeSpec.volume, image);\n if (opencodePlugin.seeded) log(`seeded agentbox-state plugin into ${opencodeSpec.volume}`);\n }\n },\n\n async seedCredentials(ctx: SyncContext): Promise<void> {\n // Mirror the in-box OAuth credentials with the host backup: extract a\n // box-written `.credentials.json` out, or seed a fresh volume from a\n // previous login. syncClaudeCredentials decides the direction; isolate\n // boxes are read-seed only. Best-effort (never throws).\n const { image, claudeSpec } = requireCreateHandle(handle, 'seedCredentials');\n const credSync = await syncClaudeCredentials(claudeSpec, {\n image,\n isolate: handle.claudeIsolate ?? false,\n });\n if (credSync.direction === 'extracted') {\n ctx.onLog('extracted box claude credentials to host backup');\n } else if (credSync.direction === 'seeded') {\n ctx.onLog(`seeded claude credentials into ${claudeSpec.volume} from host backup`);\n }\n },\n\n // Docker has no separate post-create credential extract: the box shares the\n // host's real auth via the config volume, and `seedCredentials` already does\n // the bidirectional volume↔host-backup sync (extract branch of\n // syncClaudeCredentials) at create. So `dockerProvider` omits\n // `extractAgentCredentials` and this peer method is a documented no-op.\n extractCredentials(): Promise<string[]> {\n return Promise.resolve([]);\n },\n\n // Docker bind-mounts the host's ~/.gitconfig straight into the box, so there\n // is nothing to seed. Documented no-op (the cloud body copies it in).\n seedGitIdentity(): Promise<void> {\n return Promise.resolve();\n },\n\n async seedEnvFiles(ctx: SyncContext, patterns: string[]): Promise<{ copied: number }> {\n return copyHostEnvFilesToBox({\n container: handle.container,\n workspaceDir: ctx.hostWorkspace,\n patterns,\n onLog: ctx.onLog,\n });\n },\n\n async applyCarry(ctx: SyncContext, entries: ResolvedCarryEntry[]): Promise<CarryApplyResult> {\n // Render `replaceEnvs`/`replace` entries host-side (placeholder + rule\n // substitution) then apply the per-entry tar copy.\n const rendered = await renderCarryEntries(\n entries,\n {\n name: ctx.boxName,\n id: ctx.boxId,\n kind: 'docker',\n hostWorkspace: ctx.hostWorkspace,\n projectRoot: ctx.projectRoot,\n },\n ctx.onLog,\n );\n return copyCarryPathsToBox({ container: handle.container, entries: rendered, onLog: ctx.onLog });\n },\n };\n}\n","import { spawnSync } from 'node:child_process';\nimport { mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { execa } from 'execa';\nimport {\n addProjectAlias,\n filterHostHooks,\n setInstallMethodNative,\n trustWorkspace,\n} from '@agentbox/sandbox-core';\nimport {\n claudeInventoryScript,\n computeClaudePullPlan,\n parseClaudeInventory,\n referencedPluginVersionKeys,\n writeClaudeMergedRegistries,\n} from '@agentbox/sandbox-core';\nimport type { PullClaudeResult } from '@agentbox/sandbox-core';\nexport type { PullClaudeResult } from '@agentbox/sandbox-core';\nimport { ensureVolume, volumeExists } from '../../docker.js';\nimport { detectEngine, orbstackVolumePath } from '../host-export.js';\nimport { encodeClaudeProjectsKey } from '@agentbox/sandbox-core';\n// The host-side unsyncable-symlink pre-scan moved to the shared sync layer\n// (also used by the ~/.agents skills seed); re-exported for existing importers\n// (the find-unsyncable-symlinks test) and used internally by the claude stage.\nimport { findUnsyncableSymlinks } from '@agentbox/sandbox-core';\nexport { findUnsyncableSymlinks };\n\nexport const SHARED_CLAUDE_VOLUME = 'agentbox-claude-config';\nexport const DEFAULT_CLAUDE_SESSION = 'claude';\nconst CONTAINER_CLAUDE_DIR = '/home/vscode/.claude';\nexport const CONTAINER_USER = 'vscode';\n/** Workspace is always mounted here inside the box, regardless of host path. */\nconst CONTAINER_WORKSPACE = '/workspace';\n/**\n * Image-baked copy of the agentbox-setup skill (Dockerfile.box COPYs\n * `apps/cli/share/agentbox-setup/SKILL.md` here). We seed it into the\n * claude-config volume so `/agentbox-setup` is available *inside boxes only* —\n * it is intentionally never written to the host's ~/.claude.\n */\nconst IN_BOX_SETUP_GUIDE_PATH = '/usr/local/share/agentbox/setup-guide.md';\n/** Destination skill file inside the claude-config volume (mounted at /dst). */\nconst SETUP_SKILL_DST = '/dst/skills/agentbox-setup/SKILL.md';\n\nexport interface ClaudeConfigSpec {\n /** Resolved Docker volume name mounted at /home/vscode/.claude. */\n volume: string;\n}\n\nexport function resolveClaudeVolume(opts: { isolate: boolean; boxId: string }): ClaudeConfigSpec {\n if (opts.isolate) {\n return { volume: `${SHARED_CLAUDE_VOLUME}-${opts.boxId}` };\n }\n return { volume: SHARED_CLAUDE_VOLUME };\n}\n\nexport interface EnsureClaudeVolumeOptions {\n /**\n * When true and the host's ~/.claude exists, rsync host -> volume on every call.\n * Sync is additive: files present on host overwrite same-named files in the\n * volume; box-only files (e.g. `projects/<hash>/*.jsonl` session history written\n * inside earlier boxes) are preserved.\n */\n syncFromHost: boolean;\n /** Image used by the throwaway sync helper container; we use the box image to avoid extra pulls. */\n image: string;\n /**\n * Host-absolute path of the workspace being bound to /workspace inside the\n * box. When provided, the synced `_claude.json` gets `projects[<hostWorkspace>]`\n * duplicated to `projects['/workspace']` so project-scoped MCP servers,\n * trust state, and history match what the host has for this project.\n */\n hostWorkspace?: string;\n}\n\nexport interface EnsureClaudeVolumeResult {\n /** True only the very first time the volume is created (on this host). */\n created: boolean;\n /** True when the rsync helper actually ran (syncFromHost was true AND host ~/.claude existed). */\n synced: boolean;\n /**\n * Number of hook entries dropped during sync because their `command` pointed\n * at a host path (under `$HOME/`) that wouldn't exist inside the container.\n * 0 when nothing was filtered or no sync ran.\n */\n filteredHookCount?: number;\n /**\n * True when the synced `_claude.json` had its install-method fields\n * (installMethod / autoUpdates / autoUpdatesProtectedForNative) coerced\n * to match the box's native install. False when they already matched.\n */\n installMethodFixed?: boolean;\n /**\n * True when `projects[<hostWorkspace>]` was duplicated to\n * `projects['/workspace']` in the synced `_claude.json` so the in-box claude\n * sees the host's project-scoped state (mcpServers, history, …).\n */\n aliasedProjectKey?: boolean;\n /**\n * True when `projects['/workspace'].hasTrustDialogAccepted` was set to `true`\n * in the synced `_claude.json` (it wasn't already). Pre-trusting the box's\n * workspace skips the trust dialog and avoids the Claude Code untrusted-\n * workspace `400 role 'system'` bug.\n */\n workspaceTrusted?: boolean;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True when the claude-config volume already holds a `_claude.json` at its\n * root. Claude Code treats `~/.claude.json` as its own mutable runtime/auth\n * state (`oauthAccount`, `userID`, onboarding flags, ...). Once the volume has\n * one — written by an earlier box session or the throwaway `claude auth login`\n * container — overwriting it with the host's copy clobbers that state, and the\n * box's first API request then fails with `400 \"system\" role is not supported`.\n * Callers use this to keep `_claude.json` write-once.\n */\nasync function volumeHasClaudeJson(volume: string, image: string): Promise<boolean> {\n const res = await execa(\n 'docker',\n ['run', '--rm', '-v', `${volume}:/dst`, image, 'sh', '-c', 'test -e /dst/_claude.json'],\n { reject: false },\n );\n return res.exitCode === 0;\n}\n\n\n/**\n * Ensure the named volume exists, then (when {@link EnsureClaudeVolumeOptions.syncFromHost}\n * is true and the host has a `~/.claude` directory) rsync host -> volume via a throwaway\n * helper container. The host is treated as the authoritative source for config:\n * settings, auth token, skills, plugins, and MCP entries on the host overwrite the\n * same-named files in the volume on every call. Files that only exist in the volume\n * (in-box session history under `projects/`, statsig cache, etc.) are preserved —\n * rsync runs without `--delete`.\n *\n * Caveat: if another box is currently running with the same shared volume mounted,\n * the rsync can change config files under it mid-session. We accept this as part of\n * \"host is authoritative\" — per-box state under `projects/` is untouched, so the\n * effect is limited to overlapping config files (rare to be edited live).\n *\n * Returns `created: true` only on the very first run for this volume; `synced: true`\n * whenever the rsync actually executed.\n */\nexport async function ensureClaudeVolume(\n spec: ClaudeConfigSpec,\n opts: EnsureClaudeVolumeOptions,\n): Promise<EnsureClaudeVolumeResult> {\n const existed = await volumeExists(spec.volume);\n await ensureVolume(spec.volume);\n const created = !existed;\n\n if (!opts.syncFromHost) return { created, synced: false };\n\n const hostClaude = join(homedir(), '.claude');\n if (!(await pathExists(hostClaude))) return { created, synced: false };\n\n // rsync (not cp -a) so repeat syncs skip unchanged files. rsync is installed in\n // the box image (Dockerfile.box). Trailing slash on /src-claude/ means\n // \"contents of src\", matching the original cp -a /src/. /dst/ semantics.\n // We run as root (--user 0) because the volume's existing content may be a\n // mix of UIDs (host's macOS UID for files copied from ~/.claude, plus\n // vscode's UID 1000 for anything claude wrote inside a box); only root can\n // rewrite arbitrary ownership. The post-chown brings everything back to\n // UID 1000 so the in-box vscode user can read/write.\n //\n // We also pull in ~/.claude.json (the *file* at home root that Claude Code\n // uses for global state: hasCompletedOnboarding, anonymousId, oauthAccount,\n // plugin caches). It's not inside ~/.claude, so we bind-mount it separately\n // (when present) and copy it into the volume as _claude.json. A symlink\n // baked into the image (/home/vscode/.claude.json -> .../_claude.json)\n // makes it reachable from the path claude expects.\n const hostClaudeJson = join(homedir(), '.claude.json');\n const hasJson = await pathExists(hostClaudeJson);\n // `_claude.json` is write-once in the volume. The first writer wins — the\n // throwaway `claude auth login` container (seeded just before it via this\n // same function), or an earlier box session. Re-copying the host's\n // ~/.claude.json on every create/start would clobber Claude's own\n // `oauthAccount` and break the box's first request (see volumeHasClaudeJson).\n const seedClaudeJson = !(await volumeHasClaudeJson(spec.volume, opts.image));\n const hostHome = homedir();\n // Claude Code's user-skills convention: ~/.claude/skills/<name> is a\n // RELATIVE symlink to ../../.agents/skills/<name>. From /src-claude/skills/\n // inside the helper that resolves to /.agents/skills/<name>. Bind-mount the\n // host's ~/.agents at /.agents so --copy-unsafe-links can dereference each\n // symlink into a real directory in /dst. Without this, rsync errors with\n // \"symlink has no referent\" and the whole sync aborts.\n const hostAgents = join(homedir(), '.agents');\n const hasAgents = await pathExists(hostAgents);\n const args: string[] = [\n 'run',\n '--rm',\n '--user',\n '0',\n // HOST_HOME used inside the shell script to rewrite host-absolute\n // installPath values in plugins/installed_plugins.json.\n '-e',\n `HOST_HOME=${hostHome}`,\n '-v',\n `${spec.volume}:/dst`,\n '-v',\n `${hostClaude}:/src-claude:ro`,\n ];\n if (hasJson && seedClaudeJson) args.push('-v', `${hostClaudeJson}:/src-claude-json:ro`);\n if (hasAgents) args.push('-v', `${hostAgents}:/.agents:ro`);\n\n // Pre-filter host-path hooks. Hook commands whose path is under the user's\n // host home (e.g. `/Users/marco/.config/iterm2/cc-status`) won't exist\n // inside the Linux container, and Claude logs a noisy\n // `SessionStart:startup hook error /bin/sh: …: not found` every time. We\n // build a small tempdir with filtered copies of `settings.json` /\n // `.claude.json`, mount it as `/src-filter`, and let the helper container\n // overlay it on top of what rsync brought in. The host files are never\n // touched.\n const filterDir = await mkdtemp(join(tmpdir(), 'agentbox-claude-filter-'));\n let filteredHookCount = 0;\n let installMethodFixed = false;\n let aliasedProjectKey = false;\n let workspaceTrusted = false;\n try {\n const settingsResult = await maybeFilterTo(\n join(hostClaude, 'settings.json'),\n join(filterDir, 'settings.json'),\n hostHome,\n );\n filteredHookCount += settingsResult.removedHooks;\n if (!seedClaudeJson) {\n // The volume already has a `_claude.json`; write-once leaves it intact\n // (see seedClaudeJson). No host overlay is generated for it — the\n // settings.json filtering above still applies.\n } else if (hasJson) {\n const jsonResult = await maybeFilterTo(\n hostClaudeJson,\n join(filterDir, '_claude.json'),\n hostHome,\n {\n setInstallMethodNative: true,\n aliasProject: opts.hostWorkspace\n ? { from: opts.hostWorkspace, to: CONTAINER_WORKSPACE }\n : undefined,\n trustWorkspacePath: CONTAINER_WORKSPACE,\n },\n );\n filteredHookCount += jsonResult.removedHooks;\n installMethodFixed = jsonResult.installMethodFixed;\n aliasedProjectKey = jsonResult.aliasedProjectKey;\n workspaceTrusted = jsonResult.workspaceTrusted;\n } else {\n // Host has no ~/.claude.json. Write a minimal _claude.json directly to\n // the filter dir so the in-box claude still gets installMethod=native\n // (skips the integrity warning) and a pre-trusted /workspace (skips the\n // trust dialog — and avoids the Claude Code bug where an untrusted\n // workspace yields `400 role 'system' is not supported on this model`).\n await writeFile(\n join(filterDir, '_claude.json'),\n JSON.stringify(\n {\n installMethod: 'native',\n autoUpdates: false,\n autoUpdatesProtectedForNative: true,\n projects: { [CONTAINER_WORKSPACE]: { hasTrustDialogAccepted: true } },\n },\n null,\n 2,\n ),\n );\n installMethodFixed = true;\n workspaceTrusted = true;\n }\n if (filteredHookCount > 0 || installMethodFixed || aliasedProjectKey || workspaceTrusted) {\n args.push('-v', `${filterDir}:/src-filter:ro`);\n }\n // Pre-scan for symlinks the in-container rsync can't dereference. With\n // --copy-unsafe-links rsync errors out and exits 23 when an unsafe\n // symlink's referent is missing inside the box — either broken on the host\n // (`~/.claude/debug/latest` points at a reaped debug file) or valid on the\n // host but pointing outside the mounted trees (`~/.claude` + `~/.agents`),\n // e.g. a dev's skills symlinked into an agentbox source checkout. We can't\n // predict every case, so we walk once and tell rsync to skip those entries.\n const reachableRoots = hasAgents ? [hostClaude, hostAgents] : [hostClaude];\n const brokenSymlinks = await findUnsyncableSymlinks(hostClaude, reachableRoots);\n // Exclude the host-keyed `projects/` tree: its dir name encodes the host\n // cwd, but the in-box claude (cwd /workspace) reads the `-workspace` key,\n // so a verbatim copy never lines up and just leaks host paths into the\n // volume. We re-add only the current project's memory below, rekeyed to\n // -workspace. (Box-written -workspace sessions stay put — rsync has no\n // --delete; session-teleport still uploads its single jsonl directly.)\n const rsyncExcludes = ['--exclude=node_modules', '--exclude=/projects'];\n for (const rel of brokenSymlinks) rsyncExcludes.push(`--exclude=/${rel}`);\n const rsyncFlags = `-a --copy-unsafe-links ${rsyncExcludes.join(' ')}`;\n // Rekey the host project's memory/ -> /dst/projects/-workspace/memory.\n // The key is [A-Za-z0-9-] only (encodeClaudeProjectsKey), so it's shell-safe\n // to interpolate. Empty snippet when no workspace or the helper finds no\n // host memory dir (the `[ -d ... ]` guard).\n const memoryKey = opts.hostWorkspace ? encodeClaudeProjectsKey(opts.hostWorkspace) : null;\n const memoryRekeyStep = memoryKey\n ? ` && { [ -d \"/src-claude/projects/${memoryKey}/memory\" ] && ` +\n `mkdir -p /dst/projects/-workspace && ` +\n `rm -rf /dst/projects/-workspace/memory && ` +\n `cp -a \"/src-claude/projects/${memoryKey}/memory\" /dst/projects/-workspace/memory; true; }`\n : '';\n args.push(\n opts.image,\n 'sh',\n '-c',\n // Each step in its own brace group so a missing optional file (no\n // .claude.json on host, no filtered overlays) doesn't short-circuit the\n // final chown.\n //\n // --copy-unsafe-links: dereference symlinks pointing OUTSIDE\n // /src-claude (e.g. ~/.claude/skills/* -> ../../.agents/skills/*),\n // so user skills materialize as real directories inside the volume\n // without needing to also bind-mount ~/.agents.\n // --exclude=node_modules: skip every node_modules directory anywhere\n // in the tree. Plugin caches (plugins/cache/<m>/<p>/<v>/node_modules)\n // ship host-platform-specific binaries (darwin-arm64 fsevents,\n // esbuild, rollup, sharp) that are useless on linux/amd64. The\n // plugin source still lands; node_modules is rebuilt lazily inside\n // the box on first claude session (see rebuildPluginNativeDeps).\n //\n // The top-level plugin registry JSONs (installed_plugins.json,\n // known_marketplaces.json) carry host-absolute `installPath` /\n // `installLocation` values; without rewriting, claude resolves them\n // to `/Users/<you>/...` (or, when claude detects the missing path,\n // falls back to a slug derived from `source.repo` like\n // `microsoft-playwright-cli` — neither exists in the box, and the\n // marketplace fails to load, which masquerades as \"plugin not\n // found in marketplace\"). One sweep over every JSON directly under\n // /dst/plugins/ catches both files (and any future registry).\n // One-shot migration for volumes that were populated before\n // --exclude=node_modules existed. Without it, the volume keeps\n // host-darwin node_modules forever (rsync without --delete won't\n // remove them). The `.agentbox-cleaned-nm-v1` sentinel makes the wipe\n // a no-op after the first run; rebuildPluginNativeDeps repopulates\n // linux/amd64 node_modules on the next `agentbox claude`.\n '{ [ ! -f /dst/.agentbox-cleaned-nm-v1 ] && ' +\n 'find /dst -name node_modules -type d -prune -exec rm -rf {} + && ' +\n 'touch /dst/.agentbox-cleaned-nm-v1; true; }' +\n ` && rsync ${rsyncFlags} /src-claude/ /dst/` +\n ' && { [ -f /src-claude-json ] && cp -a /src-claude-json /dst/_claude.json; true; }' +\n ' && { [ -f /src-filter/settings.json ] && cp -a /src-filter/settings.json /dst/settings.json; true; }' +\n ' && { [ -f /src-filter/_claude.json ] && cp -a /src-filter/_claude.json /dst/_claude.json; true; }' +\n ' && { [ -d /dst/plugins ] && [ -n \"$HOST_HOME\" ] && ' +\n 'find /dst/plugins -maxdepth 1 -type f -name \"*.json\" ' +\n '-exec sed -i \"s|$HOST_HOME/.claude/plugins/|/home/vscode/.claude/plugins/|g\" {} +; true; }' +\n memoryRekeyStep +\n ' && chown -R 1000:1000 /dst',\n );\n await execa('docker', args);\n } finally {\n await rm(filterDir, { recursive: true, force: true });\n }\n\n return {\n created,\n synced: true,\n filteredHookCount,\n installMethodFixed,\n aliasedProjectKey,\n workspaceTrusted,\n };\n}\n\n/**\n * Seed the `agentbox-setup` skill into the claude-config volume from the\n * image-baked copy ({@link IN_BOX_SETUP_GUIDE_PATH}). This is the box-only\n * install path: the skill is intentionally never written to the host's\n * ~/.claude (so `agentbox claude` doesn't pollute the user's machine).\n *\n * Independent of `ensureClaudeVolume`'s host rsync — it runs even when the\n * host has no ~/.claude or `syncFromHost` was false. The skill is\n * agentbox-owned and image-versioned (not user-customizable, excluded from\n * the host<->box sync), so we re-copy it unconditionally: a stale copy in a\n * long-lived shared volume must not pin an old skill after an image upgrade.\n *\n * Best-effort: a failure here must not fail box creation.\n */\nexport async function seedSetupSkillIntoVolume(\n volume: string,\n image: string,\n): Promise<{ seeded: boolean }> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n // Always overwrite from the image so an image upgrade propagates. Prints\n // SEEDED on success; the whole thing is `|| true` so a missing image\n // asset is a clean no-op, never a non-zero exit.\n `{ [ -f ${IN_BOX_SETUP_GUIDE_PATH} ] && ` +\n `rm -rf /dst/skills/agentbox-setup && ` +\n `mkdir -p /dst/skills/agentbox-setup && ` +\n `cp -a ${IN_BOX_SETUP_GUIDE_PATH} ${SETUP_SKILL_DST} && ` +\n `chown -R 1000:1000 /dst/skills/agentbox-setup && echo SEEDED; } || true`,\n ]);\n return { seeded: stdout.includes('SEEDED') };\n } catch {\n return { seeded: false };\n }\n}\n\n/**\n * Read a JSON file, run it through {@link filterHostHooks}, (when opted in)\n * {@link setInstallMethodNative}, {@link addProjectAlias}, and\n * {@link trustWorkspace}, and write the result to `dest` ONLY when at least\n * one change was made. Tolerant of missing or garbage JSON — silently returns\n * zero changes in those cases (sync proceeds with the raw rsync'd file).\n */\nasync function maybeFilterTo(\n src: string,\n dest: string,\n hostHome: string,\n opts: {\n setInstallMethodNative?: boolean;\n aliasProject?: { from: string; to: string };\n trustWorkspacePath?: string;\n } = {},\n): Promise<{\n removedHooks: number;\n installMethodFixed: boolean;\n aliasedProjectKey: boolean;\n workspaceTrusted: boolean;\n}> {\n const zero = {\n removedHooks: 0,\n installMethodFixed: false,\n aliasedProjectKey: false,\n workspaceTrusted: false,\n };\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(src, 'utf8'));\n } catch {\n return zero;\n }\n const filtered = filterHostHooks(parsed, hostHome);\n let working: unknown = filtered.data;\n let installFixed = false;\n if (opts.setInstallMethodNative) {\n const r = setInstallMethodNative(working);\n working = r.data;\n installFixed = r.applied;\n }\n let aliased = false;\n if (opts.aliasProject) {\n const r = addProjectAlias(working, opts.aliasProject.from, opts.aliasProject.to);\n working = r.data;\n aliased = r.aliased;\n }\n let trusted = false;\n if (opts.trustWorkspacePath) {\n const r = trustWorkspace(working, opts.trustWorkspacePath);\n working = r.data;\n trusted = r.trusted;\n }\n if (filtered.removedCommands.length === 0 && !installFixed && !aliased && !trusted) {\n return zero;\n }\n await writeFile(dest, JSON.stringify(working, null, 2));\n return {\n removedHooks: filtered.removedCommands.length,\n installMethodFixed: installFixed,\n aliasedProjectKey: aliased,\n workspaceTrusted: trusted,\n };\n}\n\nexport interface ClaudeMountResult {\n /** Docker -v spec strings to append to runBox(extraVolumes). */\n extraVolumes: string[];\n /** Env vars to forward into the container; only includes keys that were set + non-empty on the host. */\n env: Record<string, string>;\n volumeName: string;\n}\n\n// Forwarded from the host's `process.env` into the box at `docker run -e` time\n// (and re-forwarded by `startClaudeSession` at `docker exec -e` time, so a\n// later `agentbox claude start <existing-box>` picks up the host's current\n// session env even when the container was created from a different shell).\n//\n// CLAUDE_EFFORT / ANTHROPIC_MODEL: Claude Code stores the user's model\n// selection (Opus/Sonnet/Haiku via /model or --effort) only in the parent\n// claude's process env — not in `~/.claude.json` or `~/.claude/settings.json`.\n// When the user invokes `agentbox claude` from inside their host claude\n// session, that env IS present in the calling shell; forwarding it is the\n// only way the in-box claude inherits the same model default.\nexport const CLAUDE_FORWARDED_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'CLAUDE_EFFORT',\n 'ANTHROPIC_MODEL',\n] as const;\n// Internal alias kept so existing usages in this file stay terse.\nconst FORWARDED_ENV_KEYS = CLAUDE_FORWARDED_ENV_KEYS;\n\nexport function buildClaudeMounts(\n spec: ClaudeConfigSpec,\n hostEnv: NodeJS.ProcessEnv,\n): ClaudeMountResult {\n const env: Record<string, string> = {};\n for (const k of FORWARDED_ENV_KEYS) {\n const v = hostEnv[k];\n if (typeof v === 'string' && v.length > 0) env[k] = v;\n }\n return {\n extraVolumes: [`${spec.volume}:${CONTAINER_CLAUDE_DIR}`],\n env,\n volumeName: spec.volume,\n };\n}\n\nexport interface RebuildPluginNativeDepsResult {\n /** Plugin cache directories whose node_modules was (re)installed during this call. */\n rebuilt: string[];\n /** Plugin cache directories where install failed; non-fatal, claude often still loads. */\n failed: Array<{ dir: string; stderr: string }>;\n /**\n * Stale plugin-version cache dirs (`<m>/<p>/<v>`, not referenced by\n * `installed_plugins.json`) whose `node_modules` was pruned during this call.\n */\n pruned: string[];\n /** Total bytes freed by {@link RebuildPluginNativeDepsResult.pruned}. */\n prunedBytes: number;\n /**\n * True when the in-box exec was skipped entirely because a host-side scan\n * proved every package.json-bearing plugin already carries its install\n * marker. Only possible when the volume is host-visible (OrbStack).\n */\n skipped: boolean;\n}\n\n/** Per-plugin sentinel written inside the cache dir after a successful install. */\nconst PLUGIN_INSTALLED_MARKER = '.agentbox-installed';\n\n/**\n * Per-plugin sentinel written (mtime = failure time) when an install fails. A\n * plugin with a *recent* fail marker is skipped instead of retried on every\n * launch; once the marker ages past {@link PLUGIN_INSTALL_BACKOFF_MS} it's\n * retried. Cleared on a later success.\n */\nconst PLUGIN_FAILED_MARKER = '.agentbox-install-failed';\n\n/** How long a failed plugin install is skipped before it's retried. */\nconst PLUGIN_INSTALL_BACKOFF_MS = 6 * 60 * 60 * 1000;\n\n/** Backoff window in whole minutes, for the in-box `find -mmin` recency test. */\nconst PLUGIN_INSTALL_BACKOFF_MIN = Math.round(PLUGIN_INSTALL_BACKOFF_MS / 60000);\n\n/**\n * Persistent npm cache, kept inside the claude-config volume so a given\n * package@version is fetched from the registry once *globally* and reused by\n * every later box and plugin version. Shared across boxes with the default\n * shared volume; per-box only under `--isolate-claude-config`. Not named\n * `node_modules`, so the one-time node_modules cleanup migration leaves it\n * alone; the host->volume rsync is additive (won't delete it) and `pull claude`\n * only pulls skills/plugins/agents/commands (won't drag it to the host).\n */\nconst NPM_CACHE_DIR = '/home/vscode/.claude/.agentbox-npm-cache';\n\nasync function isFile(p: string): Promise<boolean> {\n try {\n return (await stat(p)).isFile();\n } catch {\n return false;\n }\n}\n\n/** True when `p` exists and its mtime is within the install-backoff window. */\nasync function isRecentFailMarker(p: string): Promise<boolean> {\n try {\n const st = await stat(p);\n return Date.now() - st.mtimeMs < PLUGIN_INSTALL_BACKOFF_MS;\n } catch {\n return false;\n }\n}\n\nasync function isDir(p: string): Promise<boolean> {\n try {\n return (await stat(p)).isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Read `installed_plugins.json` next to a plugin cache dir and reduce it to the\n * set of `<m>/<p>/<v>` version keys it actively references. Missing/unparseable\n * file -> empty set (\"can't determine\"), which callers treat as \"apply no\n * reference-based filtering\".\n */\nasync function readReferencedPluginKeys(installedPluginsJsonPath: string): Promise<Set<string>> {\n try {\n const raw = await readFile(installedPluginsJsonPath, 'utf8');\n return referencedPluginVersionKeys(JSON.parse(raw) as unknown);\n } catch {\n return new Set<string>();\n }\n}\n\n/**\n * Pure host-side scan of a plugin `cache/<m>/<p>/<v>/` tree. Returns true iff\n * at least one version dir has a `package.json`, no install marker, and no\n * *recent* failure marker — i.e. the in-box rebuild would actually do npm\n * work. A missing/empty cache root means nothing to do (false). Mirrors the\n * in-box script's accept/skip rules (`packages/sandbox-docker/src/claude.ts`\n * rebuild script) so the host pre-check and the container never disagree.\n *\n * When the sibling `installed_plugins.json` yields a non-empty referenced set,\n * unreferenced version dirs are ignored here exactly as the in-box loop skips\n * installing them (prevention) — a stale dir is never \"rebuild work\".\n */\nexport async function scanPluginCacheForRebuild(cacheRoot: string): Promise<boolean> {\n const referenced = await readReferencedPluginKeys(\n join(cacheRoot, '..', 'installed_plugins.json'),\n );\n let marketplaces;\n try {\n marketplaces = await readdir(cacheRoot, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const m of marketplaces) {\n if (!m.isDirectory()) continue;\n const mPath = join(cacheRoot, m.name);\n let plugins;\n try {\n plugins = await readdir(mPath, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const p of plugins) {\n if (!p.isDirectory()) continue;\n const pPath = join(mPath, p.name);\n let versions;\n try {\n versions = await readdir(pPath, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const v of versions) {\n if (!v.isDirectory()) continue;\n if (referenced.size > 0 && !referenced.has(`${m.name}/${p.name}/${v.name}`)) continue;\n const vPath = join(pPath, v.name);\n if (!(await isFile(join(vPath, 'package.json')))) continue;\n if (await isFile(join(vPath, PLUGIN_INSTALLED_MARKER))) continue;\n if (await isRecentFailMarker(join(vPath, PLUGIN_FAILED_MARKER))) continue;\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Host-visible `plugins/cache` dir for a claude-config volume, or null when the\n * engine doesn't expose volume contents to the host (Docker Desktop / other).\n * Returns the cache path even if it doesn't exist yet — {@link\n * scanPluginCacheForRebuild} treats a missing cache as \"nothing to do\" — but\n * only once the volume itself is materialized on the host.\n */\nasync function resolveClaudeCacheLiveOnHost(volume: string): Promise<string | null> {\n if ((await detectEngine()) !== 'orbstack') return null;\n if (!(await isDir(orbstackVolumePath(volume)))) return null;\n return orbstackVolumePath(volume, 'plugins', 'cache');\n}\n\n/**\n * Walk `/home/vscode/.claude/plugins/cache/<m>/<p>/<v>/` inside the box and run\n * `npm install` (or `npm ci` when a lockfile is present) for any plugin that\n * ships a `package.json` but hasn't been installed yet. Marker-gated (not\n * node_modules — plugins with empty dep lists install cleanly without ever\n * creating a node_modules dir, so a dir check would loop forever).\n *\n * This exists because the host→volume rsync excludes `node_modules` (host\n * darwin-arm64 native binaries like fsevents.node / @esbuild/darwin-arm64\n * are useless on the linux/amd64 box). The first claude session in a fresh\n * box pays the install cost; subsequent attaches don't.\n *\n * Three things keep this fast: installs run **in parallel** (bounded), npm\n * shares a **persistent cache in the claude-config volume** ({@link\n * NPM_CACHE_DIR}) with `--prefer-offline` so a package@version is fetched once\n * globally, and a failed plugin records {@link PLUGIN_FAILED_MARKER} so it's\n * skipped (not retried) until {@link PLUGIN_INSTALL_BACKOFF_MS} elapses.\n *\n * Failures on individual plugins are reported but don't throw — most\n * plugins still load with a partial dependency graph, and we prefer\n * launching claude over blocking on a third-party plugin's install hiccup.\n *\n * When this pass runs at all (i.e. a plugin difference was detected, so a\n * rebuild is warranted) it also **prunes** stale plugin-version dirs: when\n * Claude updates a plugin it leaves the old `cache/<m>/<p>/<v>/` dir on disk,\n * and its ~hundreds-of-MB `node_modules` would otherwise live forever in the\n * shared claude-config volume. Any version dir not referenced by\n * `installed_plugins.json` has its `node_modules` (and our markers) removed,\n * and the install loop never (re)installs into an unreferenced dir.\n */\nasync function readBoxReferencedPluginKeys(container: string): Promise<Set<string>> {\n const res = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n CONTAINER_USER,\n container,\n 'cat',\n `${CONTAINER_CLAUDE_DIR}/plugins/installed_plugins.json`,\n ],\n { reject: false },\n );\n if (res.exitCode !== 0 || !res.stdout) return new Set<string>();\n try {\n return referencedPluginVersionKeys(JSON.parse(res.stdout) as unknown);\n } catch {\n return new Set<string>();\n }\n}\n\nexport async function rebuildPluginNativeDeps(\n container: string,\n opts: {\n onProgress?: (line: string) => void;\n /**\n * The claude-config volume backing this box. When given and host-visible\n * (OrbStack), a pure-fs pre-scan skips the `docker exec` entirely if every\n * package.json plugin already has its install marker — the common case for\n * every box after the first global install.\n */\n volume?: string;\n } = {},\n): Promise<RebuildPluginNativeDepsResult> {\n if (opts.volume) {\n const cacheRoot = await resolveClaudeCacheLiveOnHost(opts.volume);\n if (cacheRoot && !(await scanPluginCacheForRebuild(cacheRoot))) {\n return { rebuilt: [], failed: [], pruned: [], prunedBytes: 0, skipped: true };\n }\n }\n // Reference set from the box's installed_plugins.json: version dirs Claude no\n // longer points at are stale. An empty set (file missing / unparseable)\n // disables both prevention and the prune pass — the script then behaves\n // exactly as it did before this feature.\n const referenced = await readBoxReferencedPluginKeys(container);\n const refSetup =\n referenced.size > 0\n ? `cat <<'AGENTBOX_REF_EOF' > \"$WORK/referenced\"\\n${[...referenced].sort().join('\\n')}\\nAGENTBOX_REF_EOF\\n`\n : '';\n // The host parser below expects the REBUILD_START / REBUILD_OK /\n // REBUILD_FAIL..REBUILD_FAIL_END protocol (plus PRUNE_OK lines); parallel\n // jobs write per-dir result+stderr files and we replay them after `wait`.\n const script = `set -u\nPLUGINS_DIR=/home/vscode/.claude/plugins/cache\nMARKER=${PLUGIN_INSTALLED_MARKER}\nFAILMARKER=${PLUGIN_FAILED_MARKER}\nNPM_CACHE=${NPM_CACHE_DIR}\nBACKOFF_MIN=${PLUGIN_INSTALL_BACKOFF_MIN}\nMAX=4\n[ -d \"$PLUGINS_DIR\" ] || exit 0\nmkdir -p \"$NPM_CACHE\"\nWORK=\\$(mktemp -d)\n${refSetup}relkey() { printf '%s' \"\\${1#$PLUGINS_DIR/}\" | tr '/' '_'; }\n# True when refs are unknown (no file) or $1 (<m>/<p>/<v>) is referenced.\nis_referenced() {\n [ -s \"$WORK/referenced\" ] || return 0\n grep -Fxq \"$1\" \"$WORK/referenced\"\n}\n# Run one plugin's install. $1 is frozen by value at call time, so it's safe\n# to read from the backgrounded subshell; the rest are set-once constants.\ndo_one() {\n d=\\$1\n key=\\$(relkey \"$d\")\n if (cd \"$d\" && \\\\\n if [ -f package-lock.json ]; then \\\\\n npm ci --no-audit --no-fund --silent --prefer-offline --cache \"$NPM_CACHE\"; \\\\\n else \\\\\n npm install --no-audit --no-fund --silent --no-package-lock --prefer-offline --cache \"$NPM_CACHE\"; \\\\\n fi) >\"$WORK/$key.out\" 2>\"$WORK/$key.err\"; then\n touch \"$d/$MARKER\"\n rm -f \"$d/$FAILMARKER\"\n printf 'OK\\\\n' > \"$WORK/$key.res\"\n else\n : > \"$d/$FAILMARKER\"\n printf 'FAIL\\\\n' > \"$WORK/$key.res\"\n fi\n}\n# Prune pass: every unreferenced (stale) version dir loses its node_modules and\n# our markers. Only runs when installed_plugins.json gave us a reference set.\nif [ -s \"$WORK/referenced\" ]; then\n for dir in \"$PLUGINS_DIR\"/*/*/*/; do\n [ -d \"$dir\" ] || continue\n rel=\\${dir%/}; rel=\\${rel#$PLUGINS_DIR/}\n grep -Fxq \"$rel\" \"$WORK/referenced\" && continue\n if [ -d \"$dir/node_modules\" ]; then\n bytes=\\$(du -sb \"$dir/node_modules\" 2>/dev/null | cut -f1)\n [ -n \"$bytes\" ] || bytes=0\n rm -rf \"$dir/node_modules\" \"$dir/$MARKER\" \"$dir/$FAILMARKER\"\n echo \"PRUNE_OK $rel $bytes\"\n else\n rm -f \"$dir/$MARKER\" \"$dir/$FAILMARKER\"\n fi\n done\nfi\nn=0\nfor dir in \"$PLUGINS_DIR\"/*/*/*/; do\n [ -d \"$dir\" ] || continue\n [ -f \"$dir/package.json\" ] || continue\n rel=\\${dir%/}; rel=\\${rel#$PLUGINS_DIR/}\n is_referenced \"$rel\" || continue\n [ -f \"$dir/$MARKER\" ] && continue\n [ -n \"\\$(find \"$dir\" -maxdepth 1 -name \"$FAILMARKER\" -mmin -\\$BACKOFF_MIN 2>/dev/null)\" ] && continue\n echo \"REBUILD_START \\${dir#$PLUGINS_DIR/}\"\n n=\\$((n+1))\n printf '%s\\\\n' \"$dir\" >> \"$WORK/dirs\"\ndone\nif [ \"$n\" -eq 0 ]; then rm -rf \"$WORK\"; exit 0; fi\nrunning=0\nwhile IFS= read -r dir; do\n do_one \"$dir\" &\n running=\\$((running+1))\n if [ \"$running\" -ge \"$MAX\" ]; then wait; running=0; fi\ndone < \"$WORK/dirs\"\nwait\nwhile IFS= read -r dir; do\n key=\\$(relkey \"$dir\")\n rel=\\${dir#$PLUGINS_DIR/}\n [ -f \"$WORK/$key.res\" ] || continue\n read -r st < \"$WORK/$key.res\"\n if [ \"$st\" = OK ]; then\n echo \"REBUILD_OK $rel\"\n else\n echo \"REBUILD_FAIL $rel\"\n sed 's/^/ /' \"$WORK/$key.err\"\n echo \"REBUILD_FAIL_END\"\n fi\ndone < \"$WORK/dirs\"\nrm -rf \"$WORK\"\n`;\n const result = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'sh', '-c', script],\n { reject: false },\n );\n const rebuilt: string[] = [];\n const failed: Array<{ dir: string; stderr: string }> = [];\n const pruned: string[] = [];\n let prunedBytes = 0;\n const lines = (result.stdout ?? '').split('\\n');\n let collectingFail: { dir: string; stderr: string[] } | null = null;\n for (const line of lines) {\n if (collectingFail) {\n if (line === 'REBUILD_FAIL_END') {\n failed.push({ dir: collectingFail.dir, stderr: collectingFail.stderr.join('\\n') });\n collectingFail = null;\n } else {\n collectingFail.stderr.push(line);\n }\n continue;\n }\n if (line.startsWith('REBUILD_START ')) {\n opts.onProgress?.(`rebuilding ${line.slice('REBUILD_START '.length)}`);\n } else if (line.startsWith('REBUILD_OK ')) {\n rebuilt.push(line.slice('REBUILD_OK '.length));\n } else if (line.startsWith('REBUILD_FAIL ')) {\n collectingFail = { dir: line.slice('REBUILD_FAIL '.length), stderr: [] };\n } else if (line.startsWith('PRUNE_OK ')) {\n // `PRUNE_OK <m>/<p>/<v> <bytes>` — bytes is the last space-delimited token.\n const rest = line.slice('PRUNE_OK '.length);\n const sp = rest.lastIndexOf(' ');\n if (sp > 0) {\n const dir = rest.slice(0, sp);\n const bytes = Number(rest.slice(sp + 1));\n pruned.push(dir);\n if (Number.isFinite(bytes)) prunedBytes += bytes;\n opts.onProgress?.(`pruning stale plugin cache ${dir}`);\n }\n }\n }\n return { rebuilt, failed, pruned, prunedBytes, skipped: false };\n}\n\nexport class ClaudeSessionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ClaudeSessionError';\n }\n}\n\nexport interface StartClaudeSessionOptions {\n container: string;\n claudeArgs: string[];\n sessionName?: string;\n /** Previously fed into the in-tmux status bar; now unused (the outer UI\n * shows the name). Kept for back-compat — callers may still pass it. */\n boxName?: string;\n}\n\n/**\n * Single-quote a token for /bin/sh. Conservative: anything outside the safe alphabet\n * gets wrapped. We don't try to detect \"obviously safe\" inputs; quoting is cheap.\n */\nfunction shQuote(arg: string): string {\n if (arg.length === 0) return `''`;\n if (/^[A-Za-z0-9_\\-./=:@%+,]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Start a detached tmux session running Claude Code inside the container. The session\n * survives client disconnects; reattach via {@link attachClaudeSession}.\n *\n * We forward the host's TERM (default xterm-256color) so the in-container tmux\n * picks the right terminal-overrides at session creation time — without this,\n * docker exec defaults TERM to `xterm` and tmux can't declare 24-bit color.\n *\n * We also re-forward {@link FORWARDED_ENV_KEYS} from the host's process env.\n * Values set at container-create time (via runBox -e) are still inherited\n * for free, but the user might be invoking `agentbox claude start <box>`\n * from a different shell session — e.g. inside their host claude (which sets\n * CLAUDE_EFFORT) for a box created earlier from a plain terminal. Re-passing\n * at exec time lets the in-box claude pick up the host's *current* selection.\n */\nexport async function startClaudeSession(opts: StartClaudeSessionOptions): Promise<void> {\n const sessionName = opts.sessionName ?? DEFAULT_CLAUDE_SESSION;\n const cmd = ['claude', ...opts.claudeArgs].map(shQuote).join(' ');\n const term = process.env['TERM'] ?? 'xterm-256color';\n const envFlags: string[] = ['-e', `TERM=${term}`];\n for (const k of FORWARDED_ENV_KEYS) {\n const v = process.env[k];\n if (typeof v === 'string' && v.length > 0) envFlags.push('-e', `${k}=${v}`);\n }\n const result = await execa(\n 'docker',\n [\n 'exec',\n ...envFlags,\n '--user',\n CONTAINER_USER,\n opts.container,\n 'tmux',\n 'new-session',\n '-d',\n '-s',\n sessionName,\n cmd,\n ...buildTmuxSessionArgs(sessionName),\n ],\n { reject: false },\n );\n if (result.exitCode === 0) return;\n const stderr = (result.stderr ?? '').toString();\n if (result.exitCode === 127 || /command not found|tmux: not found/i.test(stderr)) {\n throw new ClaudeSessionError(\n `tmux is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/claude.*not found|exec: \"claude\"/i.test(stderr)) {\n throw new ClaudeSessionError(\n `claude is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/duplicate session/i.test(stderr)) {\n throw new ClaudeSessionError(\n `a tmux session \"${sessionName}\" already exists in ${opts.container}; use \\`agentbox claude attach\\` to reattach.`,\n );\n }\n throw new ClaudeSessionError(\n `failed to start claude session in ${opts.container}: ${stderr.trim() || `exit ${String(result.exitCode)}`}`,\n );\n}\n\n/**\n * Replace the current process with `docker exec -it tmux attach`. Ctrl+a d returns\n * the user to their host shell with exit 0. We forward TERM so tmux declares\n * the outer terminal's true-color and hyperlink capabilities; without it\n * docker exec sets TERM=xterm and Claude renders without RGB.\n */\n/**\n * The `docker` argv that attaches an interactive terminal to a box's Claude\n * tmux session. Shared by {@link attachClaudeSession} (which `spawnSync`s it\n * directly) and the dashboard command (which hands it to `tmux respawn-pane`).\n */\n/**\n * Shell snippet (run via `sh -c`) that guarantees TERM resolves inside the box\n * before tmux starts. The box runs Ubuntu, whose terminfo database does not\n * carry every host terminal: notably `xterm-ghostty`, which was added to\n * ncurses after 24.04 shipped. Forwarding such a TERM makes `tmux attach` exit\n * immediately with \"missing or unsuitable terminal\", which looks like a brief\n * flash and an instant exit. When the box cannot resolve $TERM, fall back to\n * xterm-256color, which the image always provides.\n */\nexport const TERM_FALLBACK_SNIPPET =\n 'if ! infocmp \"$TERM\" >/dev/null 2>&1; then TERM=xterm-256color; export TERM; fi; ';\n\n/**\n * Build the `docker exec` argv that runs an in-box tmux command under `sh -c`\n * with the TERM guard ({@link TERM_FALLBACK_SNIPPET}) applied first.\n *\n * `tmuxScript` is the tmux command line as it should reach tmux (use `\\;` for\n * tmux's own command separator, since a shell now parses it). `positionals` are\n * bound to \"$1\", \"$2\", ... inside the script, so session names are passed as\n * args rather than interpolated, keeping names with odd characters safe. The\n * host's TERM is still forwarded via `-e`, so a box that does know it keeps full\n * fidelity; the guard only downgrades the unknown case.\n */\nexport function buildTermSafeTmuxExec(opts: {\n container: string;\n user: string;\n tmuxScript: string;\n positionals: string[];\n}): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return [\n 'exec',\n '-it',\n '-e',\n `TERM=${term}`,\n '--user',\n opts.user,\n opts.container,\n 'sh',\n '-c',\n `${TERM_FALLBACK_SNIPPET}${opts.tmuxScript}`,\n 'sh',\n ...opts.positionals,\n ];\n}\n\nexport function buildClaudeAttachArgv(container: string, sessionName?: string): string[] {\n const name = sessionName ?? DEFAULT_CLAUDE_SESSION;\n return buildTermSafeTmuxExec({\n container,\n user: CONTAINER_USER,\n tmuxScript: 'exec tmux attach -t \"$1\"',\n positionals: [name],\n });\n}\n\n/**\n * Like {@link buildClaudeAttachArgv}, but for the dashboard's right pane.\n * Agent-agnostic — `sessionName` selects which agent's tmux session to attach\n * (`claude` / `codex` / `opencode`). The dashboard already draws its own bottom\n * status bar, so a second client must not show the inner tmux status bar. We\n * attach via a *grouped* sibling session (`<name>-dash`, `tmux new-session -t\n * <name>`): grouped sessions share the same windows/panes (identical live\n * screen + scrollback) but keep independent session options, so `status off`\n * here does not affect a direct `agentbox <agent> attach` to `<name>`. The\n * `\\;` elements are tmux's command separator, escaped so the wrapping `sh -c`\n * passes them to tmux verbatim instead of treating them as shell separators.\n * `new-session -A -d` is a no-op if the grouped session already exists;\n * `attach` runs after `status off` so the footer is gone on first paint. Runs\n * under the shared TERM guard ({@link buildTermSafeTmuxExec}) for the same\n * reason the direct attach builders do.\n */\nexport function buildDashboardAttachArgv(\n container: string,\n sessionName?: string,\n): string[] {\n const name = sessionName ?? DEFAULT_CLAUDE_SESSION;\n // The grouped sibling session name (\"<name>-dash\") is derived in-shell from\n // $1, so the session name stays a single positional that sh never re-parses.\n return buildTermSafeTmuxExec({\n container,\n user: CONTAINER_USER,\n tmuxScript:\n 'dash=\"$1-dash\"; exec tmux new-session -A -d -s \"$dash\" -t \"$1\" \\\\; set -t \"$dash\" status off \\\\; attach -t \"$dash\"',\n positionals: [name],\n });\n}\n\n/**\n * Poll a box's tmux pane until it has rendered non-blank content, or until\n * `timeoutMs` elapses. The dashboard's right-pane terminal emulator can latch\n * blank if it attaches while a heavy agent TUI (notably OpenCode's Bun-based\n * UI) is still initializing — a fresh attach gets tmux's full screen replay,\n * but a mid-init attach can miss it. Waiting for first content means the\n * dashboard attaches in the working (post-draw) condition. Best-effort:\n * returns on timeout regardless so a never-drawing agent never hangs the UI.\n */\nexport async function waitForTmuxPaneContent(\n container: string,\n sessionName: string,\n timeoutMs = 20_000,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const res = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'tmux', 'capture-pane', '-p', '-t', sessionName],\n { reject: false },\n );\n if (res.exitCode === 0 && (res.stdout ?? '').trim().length > 0) return;\n await delay(400);\n }\n}\n\n/**\n * The list of tmux subcommands that configure a session: remap the prefix\n * (Ctrl+a primary, Ctrl+b kept as secondary), enable CSI-u extended-key\n * reporting so Claude Code can distinguish Shift+Enter from Enter, and turn\n * the inner tmux status bar off so it doesn't double up with the outer\n * wrapped-pty footer. Single source of truth shared by the docker path\n * (via {@link buildTmuxSessionArgs}, which folds these into execa argv with\n * `;` separators) and the cloud path (via\n * {@link buildTmuxConfigShellSnippet}, which formats them as `tmux …`\n * shell statements for SSH transport).\n *\n * `prefix`/`bind-key` are server-global (no `-t`) — fine because each box\n * runs one tmux server per session role. `status off` is session-scoped\n * with `-t <session>` so the dashboard's grouped sibling session\n * (`<name>-dash`) keeps its own option scope.\n */\nfunction tmuxConfigSubcommands(sessionName: string): readonly (readonly string[])[] {\n return [\n ['set', '-g', 'prefix', 'C-a'],\n ['set', '-g', 'prefix2', 'C-b'],\n ['bind-key', 'C-a', 'send-prefix'],\n ['bind-key', 'C-b', 'send-prefix', '-2'],\n ['bind-key', 'd', 'detach-client'],\n ['set', '-g', 'extended-keys', 'on'],\n ['set', '-as', 'terminal-features', ',*:extkeys'],\n ['set', '-t', sessionName, 'status', 'off'],\n ];\n}\n\n/**\n * tmux command-list (separator-prefixed) appended after `tmux new-session …`\n * in {@link startClaudeSession}. The bare `;` elements are tmux's command\n * separator (execa array args, no host shell, so they reach tmux verbatim).\n * See {@link tmuxConfigSubcommands} for the shared subcommand definitions\n * and why each setting is set the way it is.\n */\nexport function buildTmuxSessionArgs(sessionName: string): string[] {\n const out: string[] = [];\n for (const sub of tmuxConfigSubcommands(sessionName)) {\n out.push(';', ...sub);\n }\n return out;\n}\n\n/**\n * Same tmux configuration as {@link buildTmuxSessionArgs}, formatted as a\n * shell snippet (`tmux <args>; tmux <args>; …`) suitable for transports\n * that go through a remote shell — i.e. the cloud providers' `ssh -t`\n * attach in `@agentbox/sandbox-cloud`'s `renderInnerCommand`. The docker\n * path uses execa argv directly and doesn't need this.\n *\n * Each subcommand is its own `tmux` invocation joined with `; ` (shell\n * statement separator), because the in-tmux `;` separator can't pass\n * through `ssh -t '...'` without ambiguity — single-quoted shell args\n * forward `;` to the remote shell, where it would split the command line\n * before reaching tmux. Multiple `tmux` invocations are equivalent\n * (they're all idempotent `set`/`bind-key` operations) and re-applying\n * on every reattach is harmless.\n */\nexport function buildTmuxConfigShellSnippet(sessionName: string): string {\n return tmuxConfigSubcommands(sessionName)\n .map((sub) => `tmux ${sub.map(shellSingleQuoteIfNeeded).join(' ')}`)\n .join('; ');\n}\n\n/**\n * Wrap `s` in POSIX single quotes only if it contains characters that\n * shells (sh/bash/zsh) parse specially. Tmux args like `,*:extkeys` need\n * quoting (the `*` would glob); plain identifiers like `C-a` or `prefix`\n * don't. Keeping the unquoted form when safe makes the generated SSH\n * command easier to read in logs.\n */\nfunction shellSingleQuoteIfNeeded(s: string): string {\n return /^[A-Za-z0-9_:.\\/=+-]+$/.test(s) ? s : \"'\" + s.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n\n/**\n * The `docker` argv for an interactive login shell in a box — the same shape\n * `agentbox shell` uses (vscode user, image WORKDIR `/workspace`, `bash -l`).\n * Handed to node-pty by the dashboard's \"open a shell\" action.\n */\nexport function buildShellArgv(container: string): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return ['exec', '-it', '-e', `TERM=${term}`, '--user', CONTAINER_USER, container, 'bash', '-l'];\n}\n\n/**\n * The `docker run` argv for an interactive `claude auth login` in a throwaway\n * container. Mounts the claude-config volume at `~/.claude` so the written\n * credentials persist; runs before any box exists. `extraArgs` are appended\n * verbatim (e.g. `['--claudeai']`, `['--sso']`).\n *\n * `DISPLAY` is blanked: the box image bakes `DISPLAY=:1` (a VNC X server) and\n * `claude auth login` would otherwise try to open a browser on that invisible\n * display. An empty `DISPLAY` forces claude's terminal URL/paste-code flow.\n */\nexport function buildClaudeLoginRunArgv(opts: {\n volume: string;\n image: string;\n extraArgs: string[];\n}): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return [\n 'run',\n '-it',\n '--rm',\n '-e',\n `TERM=${term}`,\n '-e',\n 'DISPLAY=',\n '-v',\n `${opts.volume}:${CONTAINER_CLAUDE_DIR}`,\n '--user',\n CONTAINER_USER,\n opts.image,\n 'claude',\n 'auth',\n 'login',\n ...opts.extraArgs,\n ];\n}\n\n/**\n * Run an interactive docker argv (from {@link buildClaudeLoginRunArgv}) with\n * the user's terminal attached. Returns the exit code; a null status (killed /\n * failed to spawn) is reported as 1.\n */\nexport function runInteractiveClaudeLogin(dockerArgv: string[]): { exitCode: number } {\n const child = spawnSync('docker', dockerArgv, { stdio: 'inherit' });\n return { exitCode: child.status ?? 1 };\n}\n\nexport interface WarmUpClaudeResult {\n /** True once a headless `claude -p` request actually succeeded. */\n warmed: boolean;\n /** How many attempts were made (1 = warm on the first try). */\n attempts: number;\n}\n\n/**\n * After a fresh `claude auth login`, the *first* Claude Code inference request\n * on the newly minted Claude.ai subscription token is rejected by the API with\n * `400 role 'system' is not supported on this model` — the account/token needs\n * one inference round-trip to be provisioned. A later process then works\n * (confirmed empirically: the first in-box session 400s, every later\n * box/session on the same credentials succeeds).\n *\n * Absorb that sacrificial request here: run a headless `claude -p` in a\n * throwaway container against the shared volume the login just wrote to,\n * retrying until one request actually succeeds — so the user's real box\n * session is never the first request. `--dangerously-skip-permissions` keeps\n * the headless run from stalling on a trust/permission prompt (this is a\n * throwaway sandbox container; nothing it does is persisted beyond the volume).\n *\n * Best-effort and time-boxed: if it never succeeds we return `warmed: false`\n * and the caller proceeds anyway — the box then behaves exactly as it did\n * before this warm-up existed.\n */\nexport async function warmUpClaudeCredentials(\n volume: string,\n image: string,\n opts: { onProgress?: (line: string) => void } = {},\n): Promise<WarmUpClaudeResult> {\n const MAX_ATTEMPTS = 6;\n const SLEEP_MS = 5000;\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n opts.onProgress?.(`checking credentials... ${attempt}/${MAX_ATTEMPTS}`);\n const res = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '-v',\n `${volume}:${CONTAINER_CLAUDE_DIR}`,\n '--user',\n CONTAINER_USER,\n '-e',\n 'DISABLE_AUTOUPDATER=1',\n image,\n 'claude',\n '--dangerously-skip-permissions',\n '-p',\n 'ok',\n ],\n { reject: false, timeout: 60_000 },\n );\n // `claude -p` can exit 0 while printing an API error as the turn's text,\n // so success needs a clean exit AND no error signature in the output.\n const out = `${res.stdout ?? ''}\\n${res.stderr ?? ''}`;\n const apiError = /API Error|is not supported on this model|\"type\":\\s*\"error\"/i.test(out);\n if (res.exitCode === 0 && !apiError) return { warmed: true, attempts: attempt };\n if (attempt < MAX_ATTEMPTS) await delay(SLEEP_MS);\n }\n return { warmed: false, attempts: MAX_ATTEMPTS };\n}\n\nexport function formatDetachNotice(\n ref: string,\n command: 'claude' | 'shell' | 'codex' | 'opencode' = 'claude',\n suffix = '',\n): string {\n return `Session detached. Reattach with: agentbox ${command} attach ${ref}${suffix}`;\n}\n\nexport function attachClaudeSession(\n container: string,\n sessionName?: string,\n reattachRef?: string,\n): never {\n const child = spawnSync('docker', buildClaudeAttachArgv(container, sessionName), {\n stdio: 'inherit',\n });\n const code = child.status ?? 0;\n if (reattachRef && code === 0) {\n // Overwrite tmux's own `[detached (from session …)]` line (printed just\n // above the cursor on a clean detach). Best-effort cosmetics: if the\n // terminal ignores the cursor moves, our line still prints below it.\n process.stdout.write('\\x1b[1A\\x1b[2K\\r' + formatDetachNotice(reattachRef) + '\\n');\n }\n process.exit(code);\n}\n\nexport interface ClaudeSessionInfo {\n running: boolean;\n sessionName: string;\n /** ISO-8601 timestamp from tmux's `#{session_created}` format string, or null when not running. */\n startedAt: string | null;\n}\n\n/**\n * Best-effort: returns `{ running: false, …, startedAt: null }` for any non-zero exit\n * from `tmux has-session` (which includes \"no server running\" and \"no such session\").\n */\nexport async function claudeSessionInfo(\n container: string,\n sessionName?: string,\n): Promise<ClaudeSessionInfo> {\n const name = sessionName ?? DEFAULT_CLAUDE_SESSION;\n const has = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'tmux', 'has-session', '-t', name],\n { reject: false },\n );\n if (has.exitCode !== 0) {\n return { running: false, sessionName: name, startedAt: null };\n }\n const ts = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n CONTAINER_USER,\n container,\n 'tmux',\n 'display-message',\n '-p',\n '-t',\n name,\n '#{session_created}',\n ],\n { reject: false },\n );\n let startedAt: string | null = null;\n if (ts.exitCode === 0) {\n const secs = Number.parseInt((ts.stdout ?? '').trim(), 10);\n if (Number.isFinite(secs) && secs > 0) startedAt = new Date(secs * 1000).toISOString();\n }\n return { running: true, sessionName: name, startedAt };\n}\n\nexport interface PullClaudeOptions {\n /** Image for the throwaway helper container; use the box's image to avoid extra pulls. */\n image: string;\n /** When true, compute the delta but write nothing. */\n dryRun?: boolean;\n}\n\n/**\n * Reverse of {@link ensureClaudeVolume}: pull box-installed Claude extensions\n * (skills/agents/commands dirs + plugins) from the claude-config volume back to\n * the host's `~/.claude`. Additive only — an item already present on the host\n * is never overwritten. The box need not be running; we read the *volume* via a\n * throwaway helper container (the exact mirror of the forward sync), so this\n * also works while the box is stopped.\n *\n * The inventory/delta/registry-merge logic is the shared core in\n * `@agentbox/sandbox-core` (`agent-pull.ts`) — the same plan drives the\n * cloud transport pull. Only the container-based inventory run and the\n * rsync-out step are docker-specific here.\n */\nexport async function pullClaudeExtras(\n spec: ClaudeConfigSpec,\n opts: PullClaudeOptions,\n): Promise<PullClaudeResult> {\n const hostClaude = join(homedir(), '.claude');\n\n // Inventory pass: enumerate the volume's contents via a read-only helper\n // container. `--user 0` so root can read files claude wrote as uid 1000.\n const inv = await execa(\n 'docker',\n ['run', '--rm', '--user', '0', '-v', `${spec.volume}:/src:ro`, opts.image, 'sh', '-c', claudeInventoryScript('/src')],\n { reject: false },\n );\n if (inv.exitCode !== 0) {\n throw new ClaudeSessionError(\n `failed to read claude-config volume ${spec.volume}: ${(inv.stderr ?? '').toString().trim() || `exit ${String(inv.exitCode)}`}`,\n );\n }\n\n // Delta + registry merges are computed host-side (the host ~/.claude is\n // directly accessible — only the volume needed a container).\n const inventory = parseClaudeInventory((inv.stdout ?? '').toString());\n const plan = await computeClaudePullPlan(inventory);\n const { newItems, mergedRegistries } = plan;\n const sourceRegistries = inventory.registries;\n\n if (opts.dryRun || (newItems.length === 0 && mergedRegistries.length === 0)) {\n return { newItems, mergedRegistries, sourceRegistries };\n }\n\n // Apply pass: rsync each new item dir from the volume into the host\n // ~/.claude bind mount. --ignore-existing is belt-and-suspenders (the\n // host-side delta is the real guard); --exclude=node_modules because the\n // box carries linux/amd64 binaries useless on the darwin host (claude/host\n // rebuilds lazily, same rationale as the forward sync's exclude).\n if (plan.copyRels.length > 0) {\n const cmds = plan.copyRels.map((rel) => {\n const dest = `/dst/${rel}`;\n const parent = dest.slice(0, dest.lastIndexOf('/'));\n return `mkdir -p '${parent}' && rsync -a --ignore-existing --exclude=node_modules '/src/${rel}/' '${dest}/'`;\n });\n const apply = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/src:ro`,\n '-v',\n `${hostClaude}:/dst`,\n opts.image,\n 'sh',\n '-c',\n cmds.join(' && '),\n ],\n { reject: false },\n );\n if (apply.exitCode !== 0) {\n throw new ClaudeSessionError(\n `failed to copy extensions from ${spec.volume}: ${(apply.stderr ?? '').toString().trim() || `exit ${String(apply.exitCode)}`}`,\n );\n }\n }\n\n // Registry JSONs are written host-side — only when the merge added keys.\n await writeClaudeMergedRegistries(plan);\n\n return { newItems, mergedRegistries, sourceRegistries };\n}\n","import { execa, type Result } from 'execa';\n\nexport interface DockerExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport type ContainerRuntimeState = 'running' | 'paused' | 'stopped' | 'missing';\n\nexport async function dockerInfo(): Promise<void> {\n const result: Result = await execa('docker', ['info'], { reject: false });\n if (result.exitCode !== 0) {\n throw new Error(\n `docker info failed (exit ${String(result.exitCode)}). Is the Docker daemon running?\\n${String(result.stderr)}`,\n );\n }\n}\n\n/**\n * Engine-agnostic resource ceilings. Memory in bytes, cpus fractional, disk a\n * raw engine-native size string. `null`/absent = unlimited.\n */\nexport interface BoxLimitSpec {\n memoryBytes?: number | null;\n cpus?: number | null;\n pidsLimit?: number | null;\n disk?: string | null;\n}\n\nexport interface RunBoxSpec {\n name: string;\n image: string;\n extraVolumes?: string[];\n env?: Record<string, string>;\n limits?: BoxLimitSpec;\n /**\n * docker `-p` mappings to forward host ports into the container. `hostPort: 0`\n * lets Docker pick a free ephemeral port; resolve it back with\n * {@link publishedHostPort}. `hostIp` defaults to all interfaces — pin it to\n * `127.0.0.1` for loopback-only exposure.\n */\n portMappings?: Array<{ hostPort: number; containerPort: number; hostIp?: string }>;\n}\n\nexport async function runBox(spec: RunBoxSpec): Promise<string> {\n const args: string[] = [\n 'run',\n '-d',\n '--name',\n spec.name,\n '--hostname',\n spec.name,\n '--cap-add=SYS_ADMIN',\n // dockerd inside the box (always-on, see launchDockerdDaemon) needs\n // NET_ADMIN to set up its bridge + iptables NAT for inner containers.\n // seccomp:unconfined is required because the default profile blocks\n // syscalls (notably keyctl, clone3 in some kernels) that nested containers\n // need. Both are scoped to the outer box's namespaces — inner containers\n // can't escape it. We still avoid --privileged for cloud portability.\n '--cap-add=NET_ADMIN',\n // /dev/fuse + SYS_ADMIN + apparmor:unconfined used to be required for the\n // outer /workspace FUSE overlay. That overlay is gone, but they're still\n // load-bearing for the *inner* dockerd's storage driver, which\n // agentbox-dockerd-start selects at runtime: SYS_ADMIN lets it `mount -t\n // overlay` for the preferred kernel-native overlay2 driver, and /dev/fuse\n // + SYS_ADMIN + apparmor:unconfined are needed for the fuse-overlayfs\n // fallback (used where overlay2's runtime probe fails).\n '--device=/dev/fuse',\n '--security-opt=apparmor:unconfined',\n '--security-opt=seccomp=unconfined',\n // cgroup v2 + DinD: with --cgroupns=host (the OrbStack default) the\n // outer container sees the host's read-only cgroup hierarchy at\n // /sys/fs/cgroup, so the inner dockerd can't `mkdir /sys/fs/cgroup/docker`\n // for its own slice and inner `docker run` fails with \"read-only file\n // system\". Private gives the box its own writable cgroup namespace; runc\n // creates the docker slice there and inner containers nest under it.\n '--cgroupns=private',\n // Make the host reachable from inside the container at the well-known DNS\n // name host.docker.internal. Docker Desktop / OrbStack ship this alias by\n // default; on Linux native Docker it requires this explicit flag (no-op\n // on the macOS engines). Boxes use it to reach the host relay process.\n '--add-host=host.docker.internal:host-gateway',\n ];\n // Nested AgentBox-in-AgentBox dev only: the outer sandbox lacks\n // CAP_SYS_PTRACE, so the inner dockerd can't bind-mount /proc/<pid>/ns/net\n // for a non-root container init (image default USER is vscode → uid 1000).\n // Forcing init to uid 0 makes init's /proc readable by daemon (same uid) so\n // netns setup succeeds. Gated on AGENTBOX=1 so normal-host runs are\n // unaffected. shell/exec flows pass --user explicitly (CONTAINER_USER),\n // so this only changes which uid the supervisor + service tree run as\n // inside a nested box.\n if (process.env.AGENTBOX === '1') {\n args.push('--user', '0');\n }\n const lim = spec.limits;\n if (lim) {\n if (lim.memoryBytes && lim.memoryBytes > 0) {\n args.push('--memory', String(Math.floor(lim.memoryBytes)));\n }\n if (lim.cpus && lim.cpus > 0) {\n args.push('--cpus', String(lim.cpus));\n }\n if (lim.pidsLimit && lim.pidsLimit > 0) {\n args.push('--pids-limit', String(Math.floor(lim.pidsLimit)));\n }\n // Best-effort: a no-op on overlay2 / the macOS engines. createBox() drops\n // this on those drivers (and warns) so `docker run` doesn't hard-error.\n if (lim.disk) {\n args.push('--storage-opt', `size=${lim.disk}`);\n }\n }\n for (const v of spec.extraVolumes ?? []) {\n args.push('-v', v);\n }\n for (const pm of spec.portMappings ?? []) {\n const host = pm.hostIp ? `${pm.hostIp}:${String(pm.hostPort)}` : String(pm.hostPort);\n args.push('-p', `${host}:${String(pm.containerPort)}`);\n }\n for (const [k, val] of Object.entries(spec.env ?? {})) {\n args.push('-e', `${k}=${val}`);\n }\n args.push(spec.image, 'sleep', 'infinity');\n\n const { stdout } = await execa('docker', args);\n return stdout.trim();\n}\n\n/**\n * The engine's storage driver (`overlay2`, `fuse-overlayfs`, `btrfs`, …).\n * `--storage-opt size=` is only enforced by devicemapper/btrfs/zfs/windowsfilter\n * — a no-op everywhere the macOS engines run. Empty string on probe failure.\n */\nexport async function dockerStorageDriver(): Promise<string> {\n const result = await execa('docker', ['info', '--format', '{{.Driver}}'], { reject: false });\n if (result.exitCode !== 0) return '';\n return (result.stdout ?? '').trim();\n}\n\nexport async function execInBox(\n container: string,\n cmd: string[],\n opts: { user?: string; detach?: boolean; timeoutMs?: number } = {},\n): Promise<DockerExecResult> {\n const args: string[] = ['exec'];\n if (opts.detach) args.push('-d');\n if (opts.user) args.push('--user', opts.user);\n args.push(container, ...cmd);\n const result = await execa('docker', args, {\n reject: false,\n ...(opts.timeoutMs ? { timeout: opts.timeoutMs } : {}),\n });\n return {\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nexport async function removeContainer(container: string): Promise<void> {\n await execa('docker', ['rm', '-f', container], { reject: false });\n}\n\nexport async function removeVolume(name: string): Promise<void> {\n await execa('docker', ['volume', 'rm', name], { reject: false });\n}\n\n/**\n * Best-effort `docker image rm`. Returns true when the image was actually\n * removed, false when it was already absent (or removal failed). `-f` is\n * passed by default so a stale tagged image with no live containers goes away\n * even if other tags point at the same layers.\n */\nexport async function removeImage(ref: string, opts: { force?: boolean } = {}): Promise<boolean> {\n const args = ['image', 'rm'];\n if (opts.force !== false) args.push('-f');\n args.push(ref);\n const result = await execa('docker', args, { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function containerExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['container', 'inspect', '--format', '{{.Id}}', name], {\n reject: false,\n });\n return result.exitCode === 0;\n}\n\nexport async function volumeExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['volume', 'inspect', name], { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function ensureVolume(name: string): Promise<void> {\n if (await volumeExists(name)) return;\n await execa('docker', ['volume', 'create', name]);\n}\n\nexport async function networkExists(name: string): Promise<boolean> {\n const result = await execa('docker', ['network', 'inspect', name], { reject: false });\n return result.exitCode === 0;\n}\n\nexport async function ensureNetwork(name: string): Promise<void> {\n if (await networkExists(name)) return;\n await execa('docker', ['network', 'create', name]);\n}\n\nexport async function removeNetwork(name: string): Promise<void> {\n await execa('docker', ['network', 'rm', name], { reject: false });\n}\n\nexport async function containerIsRunning(name: string): Promise<boolean> {\n return (await inspectContainerStatus(name)) === 'running';\n}\n\nexport async function pauseContainer(name: string): Promise<void> {\n await execa('docker', ['pause', name]);\n}\n\nexport async function unpauseContainer(name: string): Promise<void> {\n await execa('docker', ['unpause', name]);\n}\n\nexport async function stopContainer(name: string): Promise<void> {\n await execa('docker', ['stop', name]);\n}\n\nexport async function startContainer(name: string): Promise<void> {\n await execa('docker', ['start', name]);\n}\n\nexport async function inspectContainerStatus(name: string): Promise<ContainerRuntimeState> {\n const result = await execa('docker', ['inspect', '--format', '{{.State.Status}}', name], {\n reject: false,\n });\n if (result.exitCode !== 0) return 'missing';\n const status = (result.stdout ?? '').trim();\n switch (status) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n case 'created':\n case 'exited':\n case 'dead':\n case 'restarting':\n case 'removing':\n return 'stopped';\n default:\n return 'missing';\n }\n}\n\nexport async function inspectContainer(name: string): Promise<unknown | null> {\n const result = await execa('docker', ['inspect', name], { reject: false });\n if (result.exitCode !== 0) return null;\n try {\n const parsed = JSON.parse(result.stdout ?? 'null') as unknown[];\n return Array.isArray(parsed) ? (parsed[0] ?? null) : null;\n } catch {\n return null;\n }\n}\n\nexport async function inspectVolumeMountpoint(name: string): Promise<string | null> {\n const result = await execa('docker', ['volume', 'inspect', '--format', '{{.Mountpoint}}', name], {\n reject: false,\n });\n if (result.exitCode !== 0) return null;\n return (result.stdout ?? '').trim() || null;\n}\n\nconst AGENTBOX_PREFIX = 'agentbox-';\n\nexport async function listAgentboxContainers(): Promise<string[]> {\n const result = await execa(\n 'docker',\n ['ps', '-a', '--filter', `name=^${AGENTBOX_PREFIX}`, '--format', '{{.Names}}'],\n { reject: false },\n );\n if (result.exitCode !== 0) return [];\n return (result.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(AGENTBOX_PREFIX));\n}\n\n/**\n * Resolve the host port Docker assigned to a `-p hostPort:containerPort` mapping\n * that used `hostPort=0`. Returns null when the port isn't published or the\n * container is gone. `docker port <name> 6080/tcp` prints e.g.\n * `127.0.0.1:54321` (one line per binding); we take the first.\n */\nexport async function publishedHostPort(\n container: string,\n containerPort: number,\n): Promise<number | null> {\n const result = await execa('docker', ['port', container, `${String(containerPort)}/tcp`], {\n reject: false,\n });\n if (result.exitCode !== 0) return null;\n const first = (result.stdout ?? '').split('\\n')[0]?.trim();\n if (!first) return null;\n const m = /:(\\d+)$/.exec(first);\n return m ? Number(m[1]) : null;\n}\n\nexport async function listAgentboxVolumes(): Promise<string[]> {\n const result = await execa(\n 'docker',\n ['volume', 'ls', '--filter', `name=^${AGENTBOX_PREFIX}`, '--format', '{{.Name}}'],\n { reject: false },\n );\n if (result.exitCode !== 0) return [];\n return (result.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(AGENTBOX_PREFIX));\n}\n","import { mkdir, readFile, readdir, stat } from 'node:fs/promises';\nimport { createHash } from 'node:crypto';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport { sanitizeMnemonic } from '@agentbox/config';\nimport {\n hostOpenCommand,\n makeSyncContext,\n pushEnvFiles,\n planCarryEntry,\n BOX_HOME,\n ENV_PRUNE_DIRS,\n} from '@agentbox/sandbox-core';\nimport type { ResolvedCarryEntry } from '@agentbox/core';\nimport type { BoxStatus } from '@agentbox/ctl';\nimport { streamTarPipe } from '../box-cp.js';\nimport { execInBox } from '../docker.js';\nimport { createDockerSyncTransport } from './sync-transport.js';\nimport type { BoxRecord } from '../state.js';\n\n// Env/config-file sync moved to the shared concern (`@agentbox/sandbox-core`'s\n// sync/concerns/env). Re-exported here so existing importers (wizard,\n// download*, the scan test) keep their `@agentbox/sandbox-docker` import site.\nexport {\n DEFAULT_ENV_PATTERNS,\n scanHostEnvFiles,\n buildHostEnvFindArgs,\n} from '@agentbox/sandbox-core';\n\nexport type DockerEngine = 'orbstack' | 'docker-desktop' | 'other';\n\n/** In-container path bind-mounted to the per-box host export dir by createBox. */\nexport const CONTAINER_EXPORT_MERGED = '/host-export';\n\nexport interface HostPaths {\n /** Per-box runtime dir on host, e.g. ~/.agentbox/boxes/<id>. */\n boxDir: string;\n /** Snapshot target for the merged /workspace view (rsync'd in by `refreshExport`). */\n mergedExport: string;\n}\n\nlet cachedEngine: DockerEngine | null = null;\n\n/**\n * Inspect the docker daemon to decide which host-side conventions apply.\n * `docker info --format '{{.OperatingSystem}}'` returns strings like\n * \"OrbStack\" or \"Docker Desktop\" — we only care about those two on macOS.\n */\nexport async function detectEngine(): Promise<DockerEngine> {\n if (cachedEngine !== null) return cachedEngine;\n const result = await execa('docker', ['info', '--format', '{{.OperatingSystem}}'], {\n reject: false,\n });\n const os = (result.stdout ?? '').trim().toLowerCase();\n if (os.includes('orbstack')) cachedEngine = 'orbstack';\n else if (os.includes('docker desktop')) cachedEngine = 'docker-desktop';\n else cachedEngine = 'other';\n return cachedEngine;\n}\n\n/**\n * Pin the engine to a specific value, bypassing the `docker info` probe. Two\n * callers today:\n * 1. The CLI bootstrap (apps/cli) when the user has set `engine.kind` in\n * ~/.agentbox/config.yaml — the override applies for the rest of the\n * process so every `detectEngine()` returns the user's choice.\n * 2. Tests, via `__setEngineForTesting` (kept as an alias for back-compat).\n */\nexport function setEngineOverride(engine: DockerEngine | null): void {\n cachedEngine = engine;\n}\n\n/** @deprecated alias for `setEngineOverride`; kept so existing tests don't churn. */\nexport function __setEngineForTesting(engine: DockerEngine | null): void {\n cachedEngine = engine;\n}\n\n/**\n * The active Docker context name — `docker context show` (which honors the\n * `DOCKER_CONTEXT` / `DOCKER_HOST` overrides and `~/.docker/config.json`'s\n * `currentContext`). Embedded in the VS Code attached-container URI so the\n * Dev Containers extension talks to the same daemon agentbox used — without\n * it, switching engines (OrbStack ⇄ Docker Desktop) makes the extension probe\n * the wrong daemon. Best-effort: returns undefined if the probe fails.\n */\nexport async function getDockerContext(): Promise<string | undefined> {\n const result = await execa('docker', ['context', 'show'], { reject: false });\n if (result.exitCode !== 0) return undefined;\n const ctx = (result.stdout ?? '').trim();\n return ctx.length > 0 ? ctx : undefined;\n}\n\nexport const BOXES_ROOT = join(homedir(), '.agentbox', 'boxes');\n\n/** Box-identity subset every dir helper accepts. Structurally compatible with\n * `BoxRecord`, but only the fields the segment needs. `projectIndex` is the\n * 1-based per-project number (`agentbox list`'s `N` column); when present, it\n * appears between the id and the mnemonic so dir listings sort cleanly within\n * a project and the segment matches `agentbox <cmd> <n>` intuitively. Legacy\n * (pre-feature) boxes lack it and keep the original `<id>-<mnemonic>` shape.\n */\nexport interface BoxDirRef {\n id: string;\n name: string;\n projectIndex?: number;\n}\n\n/** On-disk dir segment for a box: `<id>-<n>-<mnemonic>` (or `<id>-<mnemonic>` legacy). */\nexport function boxDirSegment(box: BoxDirRef): string {\n const mnemonic = sanitizeMnemonic(box.name);\n const n = box.projectIndex;\n if (typeof n === 'number' && Number.isFinite(n) && n > 0) {\n return `${box.id}-${String(n)}-${mnemonic}`;\n }\n return `${box.id}-${mnemonic}`;\n}\n\nexport function boxRunDirFor(box: BoxDirRef): string {\n return join(BOXES_ROOT, boxDirSegment(box));\n}\n\n/**\n * Per-box durable status file. The host relay writes it (atomic tmp+rename)\n * when the in-box daemon pushes a `box-status` snapshot; it persists here on\n * the host fs even while the box is paused/stopped. Path must stay in sync\n * with `boxStatusPathFor` in @agentbox/relay's status-store.\n */\nexport function boxStatusPathFor(box: BoxDirRef): string {\n return join(boxRunDirFor(box), 'status.json');\n}\n\n/**\n * Read the persisted box status, or null when there is none (box predates the\n * feature, relay never received a push, corrupt JSON, or a future-incompatible\n * schema). Never throws — callers fall back to live/“unknown”.\n */\nexport async function readBoxStatus(box: BoxDirRef): Promise<BoxStatus | null> {\n try {\n const raw = await readFile(boxStatusPathFor(box), 'utf8');\n const parsed = JSON.parse(raw) as BoxStatus;\n if (parsed.schema !== 1) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Host path to a subpath inside an OrbStack-managed named volume.\n *\n * OrbStack exposes named volumes at `~/OrbStack/docker/volumes/<name>/` —\n * NO `_data` wrapper. `docker volume inspect` reports the in-VM mountpoint\n * instead, which isn't reachable from macOS. Returns the path regardless of\n * whether it exists; callers stat it themselves. Used by claude's plugin-cache\n * pre-scan to find host-visible package.jsons on OrbStack.\n */\nexport function orbstackVolumePath(volume: string, ...sub: string[]): string {\n return join(homedir(), 'OrbStack', 'docker', 'volumes', volume, ...sub);\n}\n\nexport async function getHostPaths(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex'>,\n): Promise<HostPaths> {\n const boxDir = boxRunDirFor(record);\n return {\n boxDir,\n mergedExport: join(boxDir, 'workspace'),\n };\n}\n\nexport interface RefreshOptions {\n /** When true, include /workspace/node_modules in the merged export. Off by default. */\n includeNodeModules?: boolean;\n}\n\nexport interface RefreshResult {\n /** Host path that now reflects the box's current state. */\n hostPath: string;\n /** True when an rsync copy actually ran (always true today; kept for callers). */\n copied: boolean;\n /** True when the box predates the /host-export bind and we used the tar-pipe fallback. */\n usedFallback: boolean;\n}\n\nasync function hasContainerPath(container: string, path: string): Promise<boolean> {\n const probe = await execInBox(container, ['test', '-d', path], { user: 'root' });\n return probe.exitCode === 0;\n}\n\n/**\n * Refresh the per-box merged host export (~/.agentbox/boxes/<id>/workspace) so\n * Finder sees the box's current `/workspace`. /workspace lives in the\n * container's writable layer and is invisible to macOS directly, so we always\n * have to copy it out. Prefers rsync via the /host-export bind-mount; falls\n * back to a `tar | tar` pipe through `docker exec` for boxes that predate the\n * bind.\n */\nexport async function refreshExport(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container'>,\n opts: RefreshOptions = {},\n): Promise<RefreshResult> {\n const paths = await getHostPaths(record);\n const excludeNodeModules = !opts.includeNodeModules;\n await mkdir(paths.mergedExport, { recursive: true });\n\n const bindAvailable = await hasContainerPath(record.container, CONTAINER_EXPORT_MERGED);\n if (bindAvailable) {\n const args = ['rsync', '-a', '--delete'];\n if (excludeNodeModules) args.push('--exclude=node_modules');\n args.push('/workspace/', `${CONTAINER_EXPORT_MERGED}/`);\n const r = await execInBox(record.container, args, { user: 'root' });\n if (r.exitCode !== 0) {\n throw new ExportError(`rsync into ${CONTAINER_EXPORT_MERGED} failed`, r.stdout, r.stderr);\n }\n return { hostPath: paths.mergedExport, copied: true, usedFallback: false };\n }\n\n // Fallback for pre-existing boxes: stream a tar through docker exec into the\n // host target. Slower and skips the in-place delete that rsync gives us, but\n // it works without recreating the container.\n const excludes = excludeNodeModules ? ['--exclude=node_modules'] : [];\n const result = await execa(\n 'docker',\n ['exec', '--user', 'root', record.container, 'tar', '-cf', '-', ...excludes, '-C', '/workspace', '.'],\n { reject: false, encoding: 'buffer' },\n );\n if (result.exitCode !== 0) {\n throw new ExportError(\n `tar from /workspace failed`,\n '',\n typeof result.stderr === 'string' ? result.stderr : (result.stderr as Buffer).toString('utf8'),\n );\n }\n const extract = await execa('tar', ['-xf', '-', '-C', paths.mergedExport], {\n input: result.stdout as Buffer,\n reject: false,\n });\n if (extract.exitCode !== 0) {\n throw new ExportError('tar extract on host failed', extract.stdout, extract.stderr);\n }\n return { hostPath: paths.mergedExport, copied: true, usedFallback: true };\n}\n\n/**\n * Build the in-box `find` argv that enumerates env/config files by basename\n * glob, pruning `ENV_PRUNE_DIRS`. `-printf '%P\\0'` emits NUL-delimited paths\n * already relative to /workspace (so they feed rsync --files-from --from0\n * directly, exactly like `git ls-files -z`).\n */\nfunction buildEnvFindArgs(patterns: string[]): string[] {\n const nameGroup = (names: string[]): string[] => {\n const out: string[] = [];\n names.forEach((n, i) => {\n if (i > 0) out.push('-o');\n out.push('-name', n);\n });\n return out;\n };\n return [\n 'find',\n '/workspace',\n '(',\n '-type',\n 'd',\n '(',\n ...nameGroup(ENV_PRUNE_DIRS),\n ')',\n '-prune',\n ')',\n '-o',\n '(',\n '-type',\n 'f',\n '(',\n ...nameGroup(patterns),\n ')',\n '-printf',\n '%P\\\\0',\n ')',\n ];\n}\n\nexport interface CopyHostEnvOptions {\n /** Target container name (must be running with the overlay mounted). */\n container: string;\n /** Absolute host workspace dir — the same dir that maps to /workspace. */\n workspaceDir: string;\n /** Basename globs to copy (normally DEFAULT_ENV_PATTERNS). */\n patterns: string[];\n onLog?: (line: string) => void;\n}\n\n/**\n * Copy the host's env/config files (selected by `patterns`, gitignore ignored)\n * into the running box's `/workspace`. The reverse of `pullToHost`'s env\n * segment. Writes land in the overlay's writable upper layer (the container is\n * up + mounted at call time), so they survive pause/stop/start.\n *\n * Best-effort: a tar/exec failure or an empty match set logs and returns the\n * count rather than throwing — a missing secret shouldn't abort an otherwise\n * healthy box. Files extract as uid 1000 so they're owned by `vscode` like the\n * rest of /workspace.\n */\nexport async function copyHostEnvFilesToBox(\n opts: CopyHostEnvOptions,\n): Promise<{ copied: number }> {\n // Thin wrapper over the shared env concern: same host-side find + tar pack,\n // with the docker transport's `applyTarball` reproducing the exact\n // `docker exec -i --user 1000:1000 tar -xf - -C /workspace` extract.\n const ctx = makeSyncContext({\n boxName: '',\n boxId: '',\n provider: 'docker',\n hostWorkspace: opts.workspaceDir,\n onLog: opts.onLog,\n });\n const transport = createDockerSyncTransport({ container: opts.container });\n return pushEnvFiles(ctx, transport, opts.patterns);\n}\n\nexport interface CopyHostFilesOptions {\n /** Target container name (must be running). */\n container: string;\n /** Absolute host workspace dir — the same dir that maps to /workspace. */\n workspaceDir: string;\n /** Relative paths (to workspaceDir) to copy. NUL-safe; no glob expansion. */\n files: string[];\n onLog?: (line: string) => void;\n}\n\n/**\n * Sibling to `copyHostEnvFilesToBox` that skips the `find` scan and trusts a\n * pre-vetted file list (e.g. the user's multiselect picks from the wizard).\n * Same tar-pipe body: tar reads the NUL-delimited list on stdin and pipes into\n * `docker exec tar -x`. Best-effort error handling — a tar/exec failure logs\n * and returns the count rather than throwing.\n */\nexport async function copyHostFilesToBox(\n opts: CopyHostFilesOptions,\n): Promise<{ copied: number }> {\n const log = opts.onLog ?? (() => {});\n // Normalise — drop any leading \"./\" so the in-container extract lands at the\n // right path, and drop empties so a stray trailing NUL doesn't become `tar: ''`.\n const list = opts.files.map((p) => p.replace(/^\\.\\//, '')).filter((p) => p.length > 0);\n if (list.length === 0) return { copied: 0 };\n\n const packed = await execa('tar', ['-C', opts.workspaceDir, '--null', '-T', '-', '-cf', '-'], {\n input: list.join('\\0'),\n encoding: 'buffer',\n reject: false,\n });\n if (packed.exitCode !== 0) {\n log(`warning: env-file tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n const extract = await execa(\n 'docker',\n ['exec', '-i', '--user', '1000:1000', opts.container, 'tar', '-xf', '-', '-C', '/workspace'],\n { input: packed.stdout as Buffer, reject: false },\n );\n if (extract.exitCode !== 0) {\n log(`warning: env-file copy into box failed: ${String(extract.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n return { copied: list.length };\n}\n\nexport interface PullOptions {\n /** Default true. When false, skip git ls-files and use the static exclude-list. */\n respectGitignore?: boolean;\n /** Default false. When true, don't filter node_modules even in fallback mode. */\n includeNodeModules?: boolean;\n /** Default false. Skip the initial refreshExport — pull whatever's already in the scratch dir. */\n noRefresh?: boolean;\n /** Default false. Run rsync with --dry-run; return the change list without writing. */\n dryRun?: boolean;\n /**\n * Extra env/config files to pull, selected by these basename globs via an\n * in-box `find` (heavy dirs pruned). Composes WITH gitignore selection: the\n * rsync file list is the union of the git-tracked set (unless\n * respectGitignore is false) and these matches. Empty/undefined = no env\n * segment.\n */\n envPatterns?: string[];\n}\n\nexport interface PullResult {\n /** Absolute host workspace path the pull targeted (record.workspacePath). */\n hostPath: string;\n /** Per-file rsync change list (itemized `-i` lines, transfers/deletes only). */\n changes: string[];\n /** True when an actual write happened. False on dry-run. */\n applied: boolean;\n /** True when gitignore-mode was used (vs. the fallback exclude-list). */\n usedGitignore: boolean;\n}\n\n/**\n * Keep only itemized lines that represent an actual file transfer or delete.\n * rsync `-i` emits a leading 11-char code: char 0 is the update type\n * (`>`/`<`/`c`/`*` = transfer/change/delete; `.` = attr-only, skipped) and\n * char 1 is the entry type (`f` file, `d` dir, ...). Directory lines (`d`)\n * are pruned: rsync creates parent dirs as a side effect of transferring\n * files, so counting them would overstate \"files changed\".\n */\nfunction parseItemizedChanges(stdout: string): string[] {\n return stdout\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.length > 0)\n .filter((l) => {\n const code = l[0];\n const kind = l[1];\n return (code === '>' || code === '<' || code === 'c' || code === '*') && kind !== 'd';\n });\n}\n\n/**\n * Reverse of `refreshExport`: bring the box's merged `/workspace` view back\n * into the user's actual host working directory (`record.workspacePath`).\n *\n * Two-stage: (1) `refreshExport` materializes `/workspace` in the per-box\n * scratch dir (`~/.agentbox/boxes/<id>/workspace`) — `/workspace` lives in\n * the container's writable layer, invisible to macOS directly; (2) a\n * host-side rsync copies scratch → `workspacePath`.\n *\n * Filtering: by default we ask git *inside the box* which files it would\n * track (`git ls-files --cached --others --exclude-standard`) so node_modules\n * / build dirs / gitignored secrets never leak back. Non-git workspaces (or\n * `respectGitignore: false`) fall back to a static `--exclude` list.\n *\n * Never passes `--delete`: files that exist on the host but not in the box\n * are preserved. Removals are the user's call.\n */\nexport async function pullToHost(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container' | 'workspacePath'>,\n opts: PullOptions = {},\n): Promise<PullResult> {\n const paths = await getHostPaths(record);\n\n let scratchDir: string;\n if (opts.noRefresh) {\n scratchDir = paths.mergedExport;\n await mkdir(scratchDir, { recursive: true });\n } else {\n const refreshed = await refreshExport(record, {\n includeNodeModules: opts.includeNodeModules,\n });\n scratchDir = refreshed.hostPath;\n }\n\n // The rsync file list is the union of up to two independent NUL-delimited\n // segments: git-tracked (gitignore-aware) and env-pattern (gitignore\n // bypassed). If neither is produced we fall through to the static\n // exclude-list (non-git workspace, no env patterns).\n const segments: string[] = [];\n let usedGitignore = false;\n if (opts.respectGitignore !== false) {\n const isGit = await execInBox(\n record.container,\n ['git', '-C', '/workspace', 'rev-parse', '--is-inside-work-tree'],\n { user: 'root' },\n );\n if (isGit.exitCode === 0 && isGit.stdout.trim() === 'true') {\n const ls = await execInBox(\n record.container,\n ['git', '-C', '/workspace', 'ls-files', '-z', '--cached', '--others', '--exclude-standard'],\n { user: 'root' },\n );\n if (ls.exitCode !== 0) {\n throw new ExportError('git ls-files in box failed', ls.stdout, ls.stderr);\n }\n // git -z is NUL-delimited; rsync --from0 wants the same.\n const tracked = ls.stdout.replace(/\\0$/, '');\n if (tracked.length > 0) segments.push(tracked);\n usedGitignore = true;\n }\n }\n if (opts.envPatterns && opts.envPatterns.length > 0) {\n const found = await execInBox(\n record.container,\n buildEnvFindArgs(opts.envPatterns),\n { user: 'root' },\n );\n if (found.exitCode !== 0) {\n throw new ExportError('find env files in box failed', found.stdout, found.stderr);\n }\n const envFiles = found.stdout.replace(/\\0$/, '');\n if (envFiles.length > 0) segments.push(envFiles);\n }\n const fileList =\n segments.length > 0\n ? Array.from(new Set(segments.join('\\0').split('\\0'))).join('\\0')\n : null;\n\n // --checksum, not the default size+mtime quick-check: the box runs on a\n // fresh git worktree so every file's mtime differs from the user's working\n // tree even when the content is byte-identical. Without -c, rsync would\n // \"update\" the entire tree. -c compares content hashes so only genuinely\n // changed files are written.\n const baseArgs = ['-a', '--checksum'];\n if (fileList === null) {\n baseArgs.push('--exclude=.git');\n if (!opts.includeNodeModules) baseArgs.push('--exclude=node_modules');\n } else {\n baseArgs.push('--files-from=-', '--from0');\n }\n const src = `${scratchDir}/`;\n const dst = `${record.workspacePath}/`;\n\n const dry = await execa('rsync', [...baseArgs, '--dry-run', '-i', src, dst], {\n reject: false,\n input: fileList !== null ? fileList : undefined,\n });\n if (dry.exitCode !== 0) {\n throw new ExportError('rsync dry-run failed', dry.stdout, dry.stderr);\n }\n const changes = parseItemizedChanges(dry.stdout);\n\n if (opts.dryRun) {\n return { hostPath: record.workspacePath, changes, applied: false, usedGitignore };\n }\n\n const real = await execa('rsync', [...baseArgs, src, dst], {\n reject: false,\n input: fileList !== null ? fileList : undefined,\n });\n if (real.exitCode !== 0) {\n throw new ExportError(`rsync into ${record.workspacePath} failed`, real.stdout, real.stderr);\n }\n return { hostPath: record.workspacePath, changes, applied: true, usedGitignore };\n}\n\nexport interface OpenOptions extends RefreshOptions {\n /** When true, skip rsync and just open whatever's already on disk. */\n noRefresh?: boolean;\n /** When true, refresh as usual but don't launch macOS `open` on the resulting path. */\n noOpen?: boolean;\n}\n\nexport interface OpenResult {\n hostPath: string;\n copied: boolean;\n usedFallback: boolean;\n engine: DockerEngine;\n}\n\n/**\n * Refresh the merged export (unless suppressed) and launch the macOS `open`\n * command on it. Returns the host path that was opened.\n *\n * Set `noOpen: true` to refresh and return the path without launching\n * Finder — used by `agentbox open --path` so scripted callers get a fresh\n * path in one call.\n */\nexport async function openInFinder(\n record: Pick<BoxRecord, 'id' | 'name' | 'projectIndex' | 'container'>,\n opts: OpenOptions,\n): Promise<OpenResult> {\n const engine = await detectEngine();\n let hostPath: string;\n let copied = false;\n let usedFallback = false;\n\n if (opts.noRefresh) {\n const paths = await getHostPaths(record);\n hostPath = paths.mergedExport;\n await mkdir(hostPath, { recursive: true });\n } else {\n const refreshed = await refreshExport(record, opts);\n hostPath = refreshed.hostPath;\n copied = refreshed.copied;\n usedFallback = refreshed.usedFallback;\n }\n\n if (!opts.noOpen) {\n const opened = await execa(hostOpenCommand(), [hostPath], { reject: false });\n if (opened.exitCode !== 0) {\n throw new ExportError(`open ${hostPath} failed`, opened.stdout, opened.stderr);\n }\n }\n\n return { hostPath, copied, usedFallback, engine };\n}\n\nexport class ExportError extends Error {\n constructor(\n message: string,\n public readonly stdout: string,\n public readonly stderr: string,\n ) {\n super(`${message}${stderr ? `: ${stderr.trim()}` : ''}`);\n this.name = 'ExportError';\n }\n}\n\nexport interface CopyCarryOptions {\n /** Running container name. */\n container: string;\n /** Resolved + approved carry entries. */\n entries: ResolvedCarryEntry[];\n onLog?: (line: string) => void;\n}\n\nexport interface CopyCarryResult {\n copied: number;\n errors: string[];\n /** Audit summary for BoxRecord.carry. `hash` is the host source content hash at copy time. */\n applied: Array<{ src: string; dest: string; bytes: number; hash?: string }>;\n}\n\n/**\n * Content hash of a carry source, used by the on-start resync to re-copy only\n * entries whose host source changed. Files hash their bytes; dirs hash a\n * deterministic manifest of (relpath, size, mtime). Returns undefined on a read\n * error (treated as \"changed\" so a re-copy is attempted). `missing` → undefined.\n */\nexport async function carrySourceHash(entry: ResolvedCarryEntry): Promise<string | undefined> {\n if (entry.kind === 'missing') return undefined;\n try {\n if (entry.kind === 'file') {\n return createHash('sha256').update(await readFile(entry.absSrc)).digest('hex');\n }\n // Hash file *content* (not mtime) so a touch with identical content doesn't\n // trigger a spurious re-copy. Skip the same paths the copy step excludes so\n // the hash tracks only what actually lands in the box (and so resync isn't\n // dragged through heavy excluded subtrees like node_modules).\n const exclude = entry.exclude ?? [];\n const h = createHash('sha256');\n const walk = async (dir: string, rel: string): Promise<void> => {\n const names = (await readdir(dir)).sort();\n for (const name of names) {\n const relPath = rel ? `${rel}/${name}` : name;\n if (carryRelExcluded(relPath, exclude)) continue;\n const abs = join(dir, name);\n const st = await stat(abs);\n if (st.isDirectory()) {\n h.update(`d\\0${relPath}\\n`);\n await walk(abs, relPath);\n } else {\n h.update(`f\\0${relPath}\\0`);\n h.update(await readFile(abs));\n h.update('\\n');\n }\n }\n };\n await walk(entry.absSrc, '');\n return h.digest('hex');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Mirror the tar `--exclude` patterns on `entry.exclude` for the source-hash\n * walk so it tracks the same fileset the copy step packs. Bare names (and the\n * `*​/name` form `toTarExcludes` emits) match a path component; richer globs are\n * matched against the full relpath.\n */\nfunction carryRelExcluded(relPath: string, patterns: string[]): boolean {\n if (patterns.length === 0) return false;\n const segs = relPath.split('/');\n for (const p of patterns) {\n const isGlob = p.includes('*') || p.includes('?');\n if (!isGlob) {\n if (segs.includes(p)) return true;\n } else if (p.startsWith('*/') && !/[*?/]/.test(p.slice(2))) {\n if (segs.includes(p.slice(2))) return true;\n } else {\n const re = new RegExp(\n `^${p.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*').replace(/\\?/g, '.')}$`,\n );\n if (re.test(relPath)) return true;\n }\n }\n return false;\n}\n\n/**\n * Apply the `carry:` block: copy each host path to its declared in-box dest.\n * Per-entry tar pipe (not muxed onto one stream) because each entry has its\n * own dest. `~/` in `absDest` is expanded inside the container via `$HOME` —\n * never on the host — so the box's vscode home (`/home/vscode`) is the\n * reference, not the user's macOS home.\n *\n * Files: tar a single regular file (preserves mode) and extract at the parent\n * of dest, renamed to the basename of dest. Dirs: tar the directory contents\n * (after `cd src`) and extract into the dest path (which is created with\n * `mkdir -p`). Both extracts pass `--no-same-permissions --no-same-owner` so\n * macOS attrs don't leak in; a recursive `chmod` runs when `mode` is set.\n *\n * `missing` entries (optional + absent on host) are silently skipped.\n * Per-entry failures are recorded in `errors` and the function returns rather\n * than throwing — the box stays usable; the caller logs the misses.\n */\nexport async function copyCarryPathsToBox(opts: CopyCarryOptions): Promise<CopyCarryResult> {\n const log = opts.onLog ?? (() => {});\n let copied = 0;\n const errors: string[] = [];\n const applied: CopyCarryResult['applied'] = [];\n\n for (const [i, entry] of opts.entries.entries()) {\n const where = `carry[${String(i)}] \"${entry.rawSrc}\"`;\n if (entry.kind === 'missing') {\n log(`${where}: skipped (missing on host, optional)`);\n continue;\n }\n try {\n await copyOneEntry(opts.container, entry);\n copied += 1;\n applied.push({\n src: entry.absSrc,\n dest: entry.absDest,\n bytes: entry.bytes ?? 0,\n hash: await carrySourceHash(entry),\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n errors.push(`${where}: ${msg}`);\n log(`${where}: failed: ${msg}`);\n }\n }\n\n return { copied, errors, applied };\n}\n\nasync function copyOneEntry(container: string, entry: ResolvedCarryEntry): Promise<void> {\n // Shared, byte-for-byte carry decisions (~/ expansion, file-vs-dir, exclude,\n // uid/mode defaults, rename-needed, parent-chain-needed) — see\n // `@agentbox/sandbox-core`'s files concern. `~/` is expanded host-side, NOT\n // inside the box's shell, so we never depend on the executing user's $HOME\n // (which is /root when we `--user 0:0` below).\n const plan = planCarryEntry(entry);\n if (!plan) return; // missing (optional + absent on host)\n const { boxDest, parentDir, exclude, uid, mode, fileBase, renameNeeded, parentChainNeeded } =\n plan;\n\n // Pre-create the dest's parent dir. Run as root so destinations outside\n // /home/vscode work; we re-chown to vscode if the dest is in $HOME.\n const mkdir = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'mkdir', '-p', parentDir],\n { reject: false },\n );\n if (mkdir.exitCode !== 0) {\n throw new Error(`mkdir -p ${parentDir} failed: ${String(mkdir.stderr).slice(0, 300)}`);\n }\n\n if (!plan.isDir) {\n // `docker cp` cannot write into the bind-mounted /workspace (it fails with a\n // tar \"read/write on closed pipe\"). Stream the file through `docker exec\n // tar -x` instead — that extracts from *inside* the container, through the\n // normal filesystem, exactly like the dir path below. tar archives by the\n // source basename, so rename in-box afterwards when the dest name differs.\n const srcDir = dirname(entry.absSrc);\n const [packed, extract] = await streamTarPipe(\n 'tar',\n ['-C', srcDir, '-cf', '-', fileBase],\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n '0:0',\n container,\n 'tar',\n '-xf',\n '-',\n '-C',\n parentDir,\n '--no-same-permissions',\n '--no-same-owner',\n '-m',\n ],\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n if (extract.exitCode !== 0) {\n throw new Error(`tar extract failed: ${String(extract.stderr).slice(0, 300)}`);\n }\n if (renameNeeded) {\n const mv = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'mv', '-f', `${parentDir}/${fileBase}`, boxDest],\n { reject: false },\n );\n if (mv.exitCode !== 0) {\n throw new Error(`rename to ${boxDest} failed: ${String(mv.stderr).slice(0, 300)}`);\n }\n }\n } else {\n // Tar the directory contents (cd in + tar .) so they extract at the\n // dest without a duplicated basename layer. --no-same-permissions /\n // --no-same-owner so macOS attrs don't leak into the linux box.\n // Stream the tarball straight into the box (see streamTarPipe — a buffered\n // round-trip hits execa's 100 MB maxBuffer and silently fails on any\n // sizable carry source). `exclude` drops heavy/regenerable subtrees.\n const excludeArgs = exclude.map((p) => `--exclude=${p}`);\n const [packed, extract] = await streamTarPipe(\n 'tar',\n ['-C', entry.absSrc, '-cf', '-', ...excludeArgs, '.'],\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n '0:0',\n container,\n 'tar',\n '-xf',\n '-',\n '-C',\n boxDest,\n '--no-same-permissions',\n '--no-same-owner',\n '-m',\n ],\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n if (extract.exitCode !== 0) {\n throw new Error(`tar extract failed: ${String(extract.stderr).slice(0, 300)}`);\n }\n }\n\n if (mode) {\n const chmod = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'chmod', '-R', mode, boxDest],\n { reject: false },\n );\n if (chmod.exitCode !== 0) {\n throw new Error(`chmod failed: ${String(chmod.stderr).slice(0, 300)}`);\n }\n }\n\n // Always chown explicitly so the result is predictable across providers.\n // Default uid 1000 (in-box vscode); `user: 0` lands explicit root:root.\n // (For docker cp this matters — without an explicit chown the host's\n // macOS uid/gid leaks through into the container.)\n const chown = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'chown', '-R', `${String(uid)}:${String(uid)}`, boxDest],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n throw new Error(`chown failed: ${String(chown.stderr).slice(0, 300)}`);\n }\n\n // Parent-chain chown: `mkdir -p` above ran as root, so any new dirs\n // between $HOME and dirname(boxDest) are root-owned even though the\n // leaf is now uid-owned. Walk back up to $HOME (exclusive) and chown\n // each. Only walk when dest is under $HOME — for destinations like\n // /etc/* or /opt/*, leave system parents alone.\n if (parentChainNeeded) {\n const safeDest = boxDest.replace(/'/g, `'\\\\''`);\n const script =\n `set -e; parent=\"$(dirname '${safeDest}')\"; ` +\n `while [ \"$parent\" != \"${BOX_HOME}\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown ${String(uid)}:${String(uid)} \"$parent\"; ` +\n `parent=\"$(dirname \"$parent\")\"; ` +\n `done`;\n const chownParents = await execa(\n 'docker',\n ['exec', '--user', '0:0', container, 'bash', '-c', script],\n { reject: false },\n );\n if (chownParents.exitCode !== 0) {\n throw new Error(`chown parents failed: ${String(chownParents.stderr).slice(0, 300)}`);\n }\n }\n}\n","/**\n * Docker provider's symmetric host↔box file-copy primitives. Mirrors\n * `cloud-cp.ts` in `@agentbox/sandbox-cloud` so both providers expose the same\n * `uploadPath` / `downloadPath` capability.\n *\n * `docker cp` can't see through the `/workspace` overlay mount AgentBox boxes\n * set up (the file lands in the image layer beneath the mount and is invisible\n * to the running container). Everything goes through `docker exec tar`, which\n * runs inside the container's mount namespace — same mounts the in-box agent\n * sees.\n */\n\nimport { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';\nimport { basename, dirname, posix, resolve } from 'node:path';\nimport { execa } from 'execa';\nimport type { BoxRecord } from '@agentbox/core';\n\n/** In-box home for the agent user; boxes always run as `vscode` (uid 1000). */\nconst BOX_HOME = '/home/vscode';\n\nfunction posixDirname(p: string): string {\n return posix.dirname(p) || '/';\n}\n\n/**\n * `execa({ encoding: 'buffer' })` returns stderr as a `Buffer`; `String(buf)`\n * on Node 20+ stringifies it as a comma-joined byte list, so error messages\n * come out as e.g. `116,97,114,…` instead of text. Decode explicitly.\n */\nfunction asText(s: string | Uint8Array | undefined): string {\n if (s === undefined) return '';\n if (typeof s === 'string') return s;\n return Buffer.from(s).toString('utf8');\n}\n\nexport interface BoxCpResult {\n finalPath: string;\n /** Non-fatal warning the caller may want to surface (e.g. chown failed). */\n warn?: string;\n}\n\n/** `--exclude=<pat>` args for each tar pattern (already expanded by the caller). */\nfunction tarExcludeArgs(exclude: string[] | undefined): string[] {\n return (exclude ?? []).map((p) => `--exclude=${p}`);\n}\n\n/**\n * Stream a tar producer into a tar consumer without buffering. execa buffers\n * each subprocess' stdout into memory by default and caps it at 100 MB\n * (`maxBuffer`), which silently kills the producer (\"tar: Write error\") on any\n * sizable copy — so we disable stdout buffering on the producer and pipe the\n * raw stream into the consumer's stdin. stderr stays buffered for diagnostics.\n * Returns both results; callers check exit codes producer-first.\n */\ninterface ProcOutcome {\n exitCode: number | undefined;\n stderr: string | Uint8Array | undefined;\n}\n\nexport async function streamTarPipe(\n producerFile: string,\n producerArgs: string[],\n consumerFile: string,\n consumerArgs: string[],\n producerEnv?: NodeJS.ProcessEnv,\n): Promise<[ProcOutcome, ProcOutcome]> {\n const producer = execa(producerFile, producerArgs, {\n reject: false,\n buffer: { stdout: false },\n ...(producerEnv ? { env: producerEnv } : {}),\n });\n const consumer = execa(consumerFile, consumerArgs, {\n reject: false,\n buffer: { stdout: false },\n });\n producer.stdout?.pipe(consumer.stdin!);\n const [p, c] = await Promise.all([producer, consumer]);\n return [\n { exitCode: p.exitCode, stderr: p.stderr },\n { exitCode: c.exitCode, stderr: c.stderr },\n ];\n}\n\nasync function uploadOneToBox(\n box: BoxRecord,\n hostSrc: string,\n boxDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n const srcAbs = resolve(hostSrc);\n if (!existsSync(srcAbs)) throw new Error(`source not found: ${hostSrc}`);\n const srcBasename = basename(srcAbs);\n const srcParent = dirname(srcAbs);\n\n // Decide box parent dir + final name (docker cp semantics):\n // - trailing `/` → dst is a directory; src lands as <dst>/<srcBasename>\n // - dst exists as a dir in box → same\n // - else dst is the full target path; rename during extraction\n let boxParent: string;\n let finalName: string;\n if (boxDst.endsWith('/')) {\n boxParent = boxDst.replace(/\\/+$/, '') || '/';\n finalName = srcBasename;\n } else {\n const isDir = await execa(\n 'docker',\n ['exec', box.container, 'test', '-d', boxDst],\n { reject: false },\n );\n if (isDir.exitCode === 0) {\n boxParent = boxDst.replace(/\\/+$/, '') || '/';\n finalName = srcBasename;\n } else {\n boxParent = posixDirname(boxDst);\n finalName = posix.basename(boxDst);\n }\n }\n const finalPath = boxParent === '/' ? `/${finalName}` : `${boxParent}/${finalName}`;\n\n const mk = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mkdir', '-p', boxParent],\n { reject: false },\n );\n if (mk.exitCode !== 0) {\n throw new Error(`mkdir -p ${boxParent} in box failed: ${asText(mk.stderr).slice(0, 300)}`);\n }\n\n // Stream the tarball straight from host `tar` into the box's `tar -xf -`\n // instead of buffering it (see streamTarPipe — execa's 100 MB maxBuffer\n // otherwise silently fails large copies with \"tar: Write error\").\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n const [packed, extracted] = await streamTarPipe(\n 'tar',\n ['-C', srcParent, '-cf', '-', ...tarExcludeArgs(exclude), srcBasename],\n 'docker',\n ['exec', '-i', '--user', 'root', box.container, 'tar', '-xf', '-', '-C', boxParent],\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract in box failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n\n if (finalName !== srcBasename) {\n const initial = boxParent === '/' ? `/${srcBasename}` : `${boxParent}/${srcBasename}`;\n const mv = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mv', initial, finalPath],\n { reject: false },\n );\n if (mv.exitCode !== 0) {\n throw new Error(\n `rename ${initial} -> ${finalPath} in box failed: ${asText(mv.stderr).slice(0, 300)}`,\n );\n }\n }\n\n const chown = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'chown', '-R', '1000:1000', finalPath],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n return {\n finalPath,\n warn: `chown ${finalPath} to vscode (uid 1000) failed; ownership inside the box may be root.`,\n };\n }\n\n // Parent-chain chown: `mkdir -p` ran as root, so any new dirs between $HOME\n // and the landed path are root-owned. When the dest is under the box home,\n // walk back up to $HOME (exclusive) and chown each so the agent (vscode) can\n // write siblings — e.g. session-teleport lands a rollout under\n // `~/.codex/sessions/YYYY/MM/DD/` and Codex must then create its\n // `state_*.sqlite` index in that subtree. Non-fatal (matches the warn-only\n // policy of the chown above).\n // Strictly *under* home (trailing segment) — never `=== BOX_HOME`, else the\n // walk's `dirname` would be `/home` and could reassign `/home` itself.\n if (finalPath.startsWith(BOX_HOME + '/')) {\n const walk = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n box.container,\n 'sh',\n '-c',\n `parent=$(dirname \"$1\"); ` +\n `while [ \"$parent\" != \"$2\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown 1000:1000 \"$parent\" || true; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`,\n 'sh',\n finalPath,\n BOX_HOME,\n ],\n { reject: false },\n );\n if (walk.exitCode !== 0) {\n return {\n finalPath,\n warn: `chown of parent dirs under ${BOX_HOME} failed; some may remain root-owned.`,\n };\n }\n }\n return { finalPath };\n}\n\nasync function downloadOneFromBox(\n box: BoxRecord,\n boxSrc: string,\n hostDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n const srcBasename = posix.basename(boxSrc);\n const srcParent = posixDirname(boxSrc);\n\n const dstAbs = resolve(hostDst);\n let hostParent: string;\n let finalName: string;\n const dstExists = existsSync(dstAbs);\n if (hostDst.endsWith('/') || (dstExists && statSync(dstAbs).isDirectory())) {\n hostParent = dstAbs;\n finalName = srcBasename;\n } else {\n hostParent = dirname(dstAbs);\n finalName = basename(dstAbs);\n }\n mkdirSync(hostParent, { recursive: true });\n const finalPath = posix.join(hostParent, finalName);\n\n // Stream box `tar` → host `tar -xf -` (see streamTarPipe for why we don't buffer).\n const [packed, extracted] = await streamTarPipe(\n 'docker',\n ['exec', box.container, 'tar', '-C', srcParent, '-cf', '-', ...tarExcludeArgs(exclude), srcBasename],\n 'tar',\n ['-xf', '-', '-C', hostParent],\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack in box failed: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract on host failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n\n if (finalName !== srcBasename) {\n renameSync(posix.join(hostParent, srcBasename), finalPath);\n }\n return { finalPath };\n}\n\n/** `docker exec test -d` — true when `p` is a directory inside the box. */\nasync function boxIsDir(container: string, p: string): Promise<boolean> {\n const r = await execa('docker', ['exec', container, 'test', '-d', p], { reject: false });\n return r.exitCode === 0;\n}\n\n/**\n * Resolve the box-side destination *directory* for a multi-source copy. With\n * ≥2 sources the destination must be a directory (POSIX `cp`/`scp`): a trailing\n * `/` says so explicitly (and we `mkdir -p` it), otherwise it must already be a\n * directory in the box.\n */\nasync function resolveBoxDestDir(box: BoxRecord, boxDst: string): Promise<string> {\n if (boxDst.endsWith('/')) return boxDst.replace(/\\/+$/, '') || '/';\n if (await boxIsDir(box.container, boxDst)) return boxDst.replace(/\\/+$/, '') || '/';\n throw new Error(\n `cannot copy multiple sources to '${boxDst}': destination is not a directory (add a trailing slash, e.g. ${boxDst}/)`,\n );\n}\n\n/** Group paths by their parent dir so one `tar` invocation packs each group. */\nfunction groupByParent(\n paths: string[],\n dir: (p: string) => string,\n base: (p: string) => string,\n): Map<string, string[]> {\n const groups = new Map<string, string[]>();\n for (const p of paths) {\n const parent = dir(p);\n const arr = groups.get(parent);\n if (arr) arr.push(base(p));\n else groups.set(parent, [base(p)]);\n }\n return groups;\n}\n\n/**\n * Copy one or more host sources into the box. A single source keeps full\n * `docker cp` semantics (rename if the dest is a file path); ≥2 sources land\n * under a destination directory (one `tar` per distinct source parent).\n */\nexport async function uploadToBox(\n box: BoxRecord,\n hostSrcs: string[],\n boxDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n if (hostSrcs.length === 1) return uploadOneToBox(box, hostSrcs[0]!, boxDst, exclude);\n\n const absSrcs = hostSrcs.map((s) => {\n const a = resolve(s);\n if (!existsSync(a)) throw new Error(`source not found: ${s}`);\n return a;\n });\n const boxDir = await resolveBoxDestDir(box, boxDst);\n\n const mk = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'mkdir', '-p', boxDir],\n { reject: false },\n );\n if (mk.exitCode !== 0) {\n throw new Error(`mkdir -p ${boxDir} in box failed: ${asText(mk.stderr).slice(0, 300)}`);\n }\n\n for (const [parent, basenames] of groupByParent(absSrcs, dirname, basename)) {\n const [packed, extracted] = await streamTarPipe(\n 'tar',\n ['-C', parent, '-cf', '-', ...tarExcludeArgs(exclude), ...basenames],\n 'docker',\n ['exec', '-i', '--user', 'root', box.container, 'tar', '-xf', '-', '-C', boxDir],\n { ...process.env, COPYFILE_DISABLE: '1' },\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack failed for ${parent}: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract in box failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n }\n\n // chown each landed entry (never `chown -R` the whole dest dir — that would\n // re-own pre-existing siblings the copy never touched).\n let warn: string | undefined;\n for (const a of absSrcs) {\n const landed = boxDir === '/' ? `/${basename(a)}` : `${boxDir}/${basename(a)}`;\n const chown = await execa(\n 'docker',\n ['exec', '--user', 'root', box.container, 'chown', '-R', '1000:1000', landed],\n { reject: false },\n );\n if (chown.exitCode !== 0) {\n warn = `chown under ${boxDir} to vscode (uid 1000) failed; ownership inside the box may be root.`;\n }\n }\n // Parent-chain chown of the dest dir itself + ancestors back to $HOME (see\n // uploadOneToBox for the rationale). Skipped for system / /workspace dests.\n if (boxDir.startsWith(BOX_HOME + '/')) {\n const walk = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n box.container,\n 'sh',\n '-c',\n `parent=\"$1\"; ` +\n `while [ \"$parent\" != \"$2\" ] && [ \"$parent\" != \"/\" ]; do ` +\n `chown 1000:1000 \"$parent\" || true; ` +\n `parent=$(dirname \"$parent\"); ` +\n `done`,\n 'sh',\n boxDir,\n BOX_HOME,\n ],\n { reject: false },\n );\n if (walk.exitCode !== 0) {\n warn = warn ?? `chown of parent dirs under ${BOX_HOME} failed; some may remain root-owned.`;\n }\n }\n return warn ? { finalPath: `${boxDir}/`, warn } : { finalPath: `${boxDir}/` };\n}\n\n/**\n * Copy one or more box sources to the host. A single source keeps full\n * `docker cp` semantics; ≥2 sources land under a destination directory (one\n * `tar` per distinct source parent).\n */\nexport async function downloadFromBox(\n box: BoxRecord,\n boxSrcs: string[],\n hostDst: string,\n exclude?: string[],\n): Promise<BoxCpResult> {\n if (boxSrcs.length === 1) return downloadOneFromBox(box, boxSrcs[0]!, hostDst, exclude);\n\n const dstAbs = resolve(hostDst);\n const dstExists = existsSync(dstAbs);\n if (!hostDst.endsWith('/') && !(dstExists && statSync(dstAbs).isDirectory())) {\n throw new Error(\n `cannot copy multiple sources to '${hostDst}': destination is not a directory (add a trailing slash, e.g. ${hostDst}/)`,\n );\n }\n mkdirSync(dstAbs, { recursive: true });\n\n for (const [parent, basenames] of groupByParent(boxSrcs, posixDirname, posix.basename)) {\n const [packed, extracted] = await streamTarPipe(\n 'docker',\n ['exec', box.container, 'tar', '-C', parent, '-cf', '-', ...tarExcludeArgs(exclude), ...basenames],\n 'tar',\n ['-xf', '-', '-C', dstAbs],\n );\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack in box failed for ${parent}: ${asText(packed.stderr).slice(0, 300)}`);\n }\n if (extracted.exitCode !== 0) {\n throw new Error(`tar extract on host failed: ${asText(extracted.stderr).slice(0, 300)}`);\n }\n }\n return { finalPath: dstAbs };\n}\n","/**\n * `DockerSyncTransport` — the docker implementation of the `SyncTransport` seam\n * (`@agentbox/core`). Every method is a thin wrapper over the `docker` CLI\n * primitives the provider already uses (`docker exec`/`cp`/`run`), so it needs\n * only a container name (works at create time, before a full `BoxRecord`).\n *\n * `applyTarball` reproduces `copyHostEnvFilesToBox`'s extract exactly:\n * `docker exec -i --user <uid>:<uid> <c> tar -xf - -C <dest>` streaming the\n * tarball via stdin.\n */\n\nimport { createReadStream } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type {\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n VolumeHostSource,\n} from '@agentbox/core';\n\nexport interface DockerSyncTransportInit {\n /** Target container name (running, overlay mounted). */\n container: string;\n /** Image for the throwaway rsync helper container (`seedVolumeFromHost`). */\n image?: string;\n}\n\nconst DOCKER_CAPS: TransportCaps = {\n persistentVolumes: true,\n helperContainer: true,\n ephemeralFs: false,\n};\n\nexport function createDockerSyncTransport(init: DockerSyncTransportInit): SyncTransport {\n const { container } = init;\n\n const execArgsPrefix = (opts?: SyncExecOptions): string[] => {\n const pre: string[] = ['exec'];\n if (opts?.user) pre.push('--user', opts.user);\n if (opts?.cwd) pre.push('-w', opts.cwd);\n for (const [k, v] of Object.entries(opts?.env ?? {})) pre.push('-e', `${k}=${v}`);\n return pre;\n };\n\n const transport: SyncTransport = {\n caps: DOCKER_CAPS,\n\n async exec(cmd: string[], opts?: SyncExecOptions): Promise<SyncExecResult> {\n const r = await execa('docker', [...execArgsPrefix(opts), container, ...cmd], {\n reject: false,\n });\n return {\n exitCode: typeof r.exitCode === 'number' ? r.exitCode : 1,\n stdout: String(r.stdout ?? ''),\n stderr: String(r.stderr ?? ''),\n };\n },\n\n async applyTarball(hostTarPath: string, boxDestDir: string, opts?: PushOptions): Promise<void> {\n const uid = opts?.uid ?? 1000;\n const tarArgs = ['tar', '-xf', '-', '-C', boxDestDir];\n if (opts?.noSamePerms) tarArgs.push('--no-same-permissions', '--no-same-owner', '-m');\n // Always pin the extract user explicitly (`--user <uid>:<uid>`), incl.\n // `0:0` for root — omitting it would run as the image's default USER\n // (vscode), which is wrong for a root-owned carry extract.\n const args = ['exec', '-i', '--user', `${uid}:${uid}`, container, ...tarArgs];\n const r = await execa('docker', args, { input: createReadStream(hostTarPath), reject: false });\n if (r.exitCode !== 0) {\n throw new Error(`docker tar extract into ${boxDestDir} failed: ${String(r.stderr).slice(0, 300)}`);\n }\n },\n\n async pushTree(hostSrcDir: string, boxDestDir: string, opts?: PushOptions): Promise<void> {\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-pushtree-'));\n const localTar = join(stage, 'tree.tar');\n try {\n const packArgs = ['-C', hostSrcDir];\n for (const ex of opts?.exclude ?? []) packArgs.push(`--exclude=${ex}`);\n packArgs.push('-cf', localTar, '.');\n const packed = await execa('tar', packArgs, { reject: false });\n if (packed.exitCode !== 0) {\n throw new Error(`tar pack of ${hostSrcDir} failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n await transport.applyTarball(localTar, boxDestDir, opts);\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n\n async pushFile(hostSrcPath: string, boxDestPath: string, opts?: PushOptions): Promise<void> {\n const cp = await execa('docker', ['cp', hostSrcPath, `${container}:${boxDestPath}`], {\n reject: false,\n });\n if (cp.exitCode !== 0) {\n throw new Error(`docker cp into ${boxDestPath} failed: ${String(cp.stderr).slice(0, 300)}`);\n }\n if (opts?.uid !== undefined && opts.uid !== 0) {\n await this.exec(['chown', `${opts.uid}:${opts.uid}`, boxDestPath]);\n }\n if (opts?.mode !== undefined) {\n await this.exec(['chmod', opts.mode.toString(8), boxDestPath]);\n }\n },\n\n async pullTree(boxSrcDir: string, hostDestDir: string, opts?: { exclude?: string[] }): Promise<void> {\n const tarArgs = ['exec', container, 'tar', '-C', boxSrcDir];\n for (const ex of opts?.exclude ?? []) tarArgs.push(`--exclude=${ex}`);\n tarArgs.push('-cf', '-', '.');\n const packed = await execa('docker', tarArgs, { encoding: 'buffer', reject: false });\n if (packed.exitCode !== 0) {\n throw new Error(`docker tar of ${boxSrcDir} failed: ${String(packed.stderr).slice(0, 300)}`);\n }\n await execa('tar', ['-xf', '-', '-C', hostDestDir], {\n input: packed.stdout as Buffer,\n reject: false,\n });\n },\n\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n const cp = await execa('docker', ['cp', `${container}:${boxSrcPath}`, hostDestPath], {\n reject: false,\n });\n if (cp.exitCode !== 0) {\n throw new Error(`docker cp from ${boxSrcPath} failed: ${String(cp.stderr).slice(0, 300)}`);\n }\n },\n\n async readText(boxPath: string): Promise<string | null> {\n const r = await execa('docker', ['exec', container, 'cat', boxPath], { reject: false });\n if (r.exitCode !== 0) return null;\n return String(r.stdout ?? '');\n },\n\n async ensureVolume(name: string): Promise<{ volumeId: string }> {\n await execa('docker', ['volume', 'create', name], { reject: false });\n return { volumeId: name };\n },\n\n async seedVolumeFromHost(volume: string, sources: VolumeHostSource[]): Promise<void> {\n if (!init.image) throw new Error('seedVolumeFromHost requires an image');\n const args = ['run', '--rm', '--user', '0', '-v', `${volume}:/dst`];\n const steps: string[] = [];\n sources.forEach((src, i) => {\n const mount = `/src-${String(i)}`;\n args.push('-v', `${src.hostDir}:${mount}:ro`);\n const dest = src.destSubpath ? `/dst/${src.destSubpath}` : '/dst';\n const rsync = ['rsync', '-a'];\n if (src.copyUnsafeLinks) rsync.push('--copy-unsafe-links');\n if (src.update) rsync.push('--update');\n for (const ex of src.exclude ?? []) rsync.push(`--exclude=${ex}`);\n rsync.push(`${mount}/`, `${dest}/`);\n steps.push(`mkdir -p ${dest} && ${rsync.join(' ')}`);\n });\n steps.push('chown -R 1000:1000 /dst');\n args.push(init.image, 'sh', '-c', steps.join(' && '));\n const r = await execa('docker', args, { reject: false });\n if (r.exitCode !== 0) {\n throw new Error(`seedVolumeFromHost(${volume}) failed: ${String(r.stderr).slice(0, 300)}`);\n }\n },\n };\n\n return transport;\n}\n","import { chmod, mkdir } from 'node:fs/promises';\nimport { basename, join } from 'node:path';\nimport { execa } from 'execa';\nimport type { ClaudeConfigSpec } from './agents/claude.js';\nimport { STATE_DIR } from '../state.js';\n\n// The pure credential guards (`isRealAgentCredential`, `hostClaudeBackupExpired`,\n// `hostBackupHasCredentials`) + `CredentialAgentKind` moved to the provider-\n// neutral credentials concern in @agentbox/sandbox-core (the per-agent\n// real-credential shape is now registry data, `credential.realShape`, shared\n// with cloud). Re-exported here so existing docker importers/tests — and the\n// `@agentbox/sandbox-docker` barrel — are untouched.\nexport {\n isRealAgentCredential,\n hostClaudeBackupExpired,\n hostBackupHasCredentials,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-core';\n\n/**\n * Host-side backup of the in-box Claude Code OAuth credentials.\n *\n * Claude's interactive login (inside a box) writes the only Linux auth file:\n * `~/.claude/.credentials.json`, holding a `claudeAiOauth` block with a real\n * `refreshToken` — that refresh token is what makes claude report \"Claude Max\"\n * instead of \"Claude API\". This host backup mirrors that blob so a fresh\n * `--isolate-claude-config` box, or a recreated shared volume, can be seeded\n * with the user's login instead of forcing a re-login.\n *\n * Security: the file holds a live refresh token. It is written mode 0600 under\n * `~/.agentbox/` (already the 0600-convention dir for `auth.json`). Plaintext\n * on disk matches the existing model — the claude-config volume already stores\n * the same blob in the clear; macOS Keychain is the *host* claude's store and\n * is unreachable from a Linux container.\n */\nexport const CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'claude-credentials.json');\n\n/**\n * Host-side backups of the in-box codex / opencode auth files, the cloud\n * analogue of {@link CREDENTIALS_BACKUP_FILE} for Claude. Unlike docker (which\n * bind-mounts the host's real `~/.codex` / `~/.config/opencode`), cloud\n * providers have no shared volume, so a login captured inside a cloud box is\n * stored here (by `extractCloudAgentCredentials` on `checkpoint --set-default`)\n * and re-pushed to the next box. The cloud stagers prefer these copies and fall\n * back to the host's real path when absent. Written mode 0600 like the claude\n * backup.\n */\nexport const CODEX_CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'codex-credentials.json');\nexport const OPENCODE_CREDENTIALS_BACKUP_FILE = join(STATE_DIR, 'opencode-credentials.json');\n\n/** Result line parser for the volume→backup extract helper. Pure (unit-tested). */\nexport function parseExtractResult(stdout: string): { copied: boolean } {\n return { copied: /\\bCOPIED=yes\\b/.test(stdout) };\n}\n\n/**\n * One-directional extract of a codex/opencode `auth.json` from a shared docker\n * config volume to a host backup under `~/.agentbox` — the cloud analogue of\n * `syncClaudeCredentials`'s extract, used after a host `agentbox <agent> login`\n * so the cloud push can seed the captured login into future boxes. The volume\n * root holds `auth.json` (same convention `volumeHas{Codex,Opencode}Auth` uses\n * for `/dst/auth.json`). Best-effort: any failure resolves to not-copied and\n * never throws into a login flow.\n */\nexport async function extractVolumeAuthToBackup(opts: {\n volume: string;\n image: string;\n backupFile: string;\n}): Promise<{ copied: boolean }> {\n try {\n await mkdir(STATE_DIR, { recursive: true });\n const script =\n 'COPIED=no; ' +\n 'if [ -s /dst/auth.json ]; then cp -a /dst/auth.json \"/host-state/$DEST\" && COPIED=yes; fi; ' +\n 'echo \"COPIED=$COPIED\"';\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${opts.volume}:/dst`,\n '-v',\n `${STATE_DIR}:/host-state`,\n '-e',\n // Pass the destination filename via env so the path isn't interpolated\n // into the script string (keeps the docker arg list static + injection-safe).\n `DEST=${basename(opts.backupFile)}`,\n opts.image,\n 'sh',\n '-c',\n script,\n ]);\n const result = parseExtractResult(stdout);\n if (result.copied) await chmod(opts.backupFile, 0o600).catch(() => {});\n return result;\n } catch {\n return { copied: false };\n }\n}\n\n/** Extract codex `auth.json` from its shared volume to `~/.agentbox/codex-credentials.json`. */\nexport function extractCodexCredentials(volume: string, image: string): Promise<{ copied: boolean }> {\n return extractVolumeAuthToBackup({ volume, image, backupFile: CODEX_CREDENTIALS_BACKUP_FILE });\n}\n\n/** Extract opencode `auth.json` from its shared volume to `~/.agentbox/opencode-credentials.json`. */\nexport function extractOpencodeCredentials(volume: string, image: string): Promise<{ copied: boolean }> {\n return extractVolumeAuthToBackup({ volume, image, backupFile: OPENCODE_CREDENTIALS_BACKUP_FILE });\n}\n\nexport type CredentialSyncDirection = 'extracted' | 'seeded' | 'noop';\n\nexport interface SyncClaudeCredentialsResult {\n /**\n * `extracted` — the volume's live credentials were copied out to the host\n * backup. `seeded` — the host backup was copied into an empty volume.\n * `noop` — nothing to do (or the best-effort helper failed silently).\n */\n direction: CredentialSyncDirection;\n /**\n * Whether the volume holds a real OAuth blob *after* the sync (true also\n * right after a `seeded`). When false, the in-box claude will fall back to\n * the setup-token / API key, or prompt for an interactive login.\n */\n volumeHasCredentials: boolean;\n}\n\nexport interface VolumeClaudeCredentials {\n /** A `.credentials.json` exists in the shared claude-config volume. */\n present: boolean;\n /** That file carries a usable (non-empty) `claudeAiOauth.refreshToken`. */\n hasRefreshToken: boolean;\n}\n\n/**\n * Parse the `PRESENT=<yes|no> REFRESH=<yes|no>` line the probe container prints.\n * Pure — unit-tested independently of docker.\n */\nexport function parseVolumeClaudeCredentials(stdout: string): VolumeClaudeCredentials {\n return {\n present: /\\bPRESENT=yes\\b/.test(stdout),\n hasRefreshToken: /\\bREFRESH=yes\\b/.test(stdout),\n };\n}\n\n// Probe the live `.credentials.json` the box actually boots from. `jq` ships in\n// the box image; the \"usable\" test matches SYNC_SCRIPT — a non-empty\n// `claudeAiOauth.refreshToken`. A file present with a blanked refreshToken is\n// the dead state claude leaves behind after a rejected refresh.\nconst VOLUME_CRED_PROBE_SCRIPT = `\nPRESENT=no\nREFRESH=no\nVOL=/dst/.credentials.json\nif [ -f \"$VOL\" ]; then\n PRESENT=yes\n if jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$VOL\" >/dev/null 2>&1; then REFRESH=yes; fi\nfi\necho \"PRESENT=$PRESENT REFRESH=$REFRESH\"\n`;\n\n/**\n * Inspect the shared claude-config VOLUME's live `.credentials.json` — the\n * authoritative store the in-box claude reads and refreshes. Unlike the host\n * backup (a mirror that lags and diverges when a refresh fails), this reports\n * what the next box will actually boot with: whether a credentials file exists\n * and whether it still holds a usable refresh token. Used to offer a re-login\n * only when the volume's login is dead (file present, refresh token blanked),\n * not on a merely-stale access token the in-box refresh can renew on its own.\n *\n * Best-effort: an unreadable volume / missing image resolves to\n * `{ present: false, hasRefreshToken: false }` and never throws into a flow.\n */\nexport async function volumeClaudeCredentials(\n volume: string,\n image: string,\n): Promise<VolumeClaudeCredentials> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n VOLUME_CRED_PROBE_SCRIPT,\n ]);\n return parseVolumeClaudeCredentials(stdout);\n } catch {\n return { present: false, hasRefreshToken: false };\n }\n}\n\n/**\n * Parse the `EXTRACTED=<yes|no> SEEDED=<yes|no> VOLREAL=<yes|no>` line the\n * helper container prints. Pure — unit-tested independently of docker.\n */\nexport function parseSyncResult(stdout: string): SyncClaudeCredentialsResult {\n const volumeHasCredentials = /\\bVOLREAL=yes\\b/.test(stdout);\n if (/\\bEXTRACTED=yes\\b/.test(stdout)) return { direction: 'extracted', volumeHasCredentials };\n if (/\\bSEEDED=yes\\b/.test(stdout)) return { direction: 'seeded', volumeHasCredentials };\n return { direction: 'noop', volumeHasCredentials };\n}\n\n// Bidirectional, best-effort. `jq` ships in the box image. A credentials blob\n// only counts as \"real\" when `claudeAiOauth.refreshToken` is a non-empty\n// string — a setup-token blob has an accessToken but no refreshToken, and\n// seeding/extracting it would just reproduce the \"Claude API\" label. The\n// final `echo` always runs so the caller can read the outcome; a failed `cp`\n// leaves the flag at `no` and the whole thing still exits 0.\nconst SYNC_SCRIPT = `\nEXTRACTED=no\nSEEDED=no\nVOL=/dst/.credentials.json\nHOST=/host-state/claude-credentials.json\nif [ -f \"$VOL\" ] && jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$VOL\" >/dev/null 2>&1; then VOL_REAL=yes; else VOL_REAL=no; fi\nif [ -f \"$HOST\" ] && jq -e '(.claudeAiOauth.refreshToken // \"\") | length > 0' \"$HOST\" >/dev/null 2>&1; then HOST_REAL=yes; else HOST_REAL=no; fi\nif [ \"$VOL_REAL\" = yes ] && [ \"$ISOLATE\" != yes ]; then\n cp -a \"$VOL\" \"$HOST\" && chmod 600 \"$HOST\" && EXTRACTED=yes\nelif [ \"$VOL_REAL\" = no ] && [ \"$HOST_REAL\" = yes ]; then\n cp -a \"$HOST\" \"$VOL\" && chown 1000:1000 \"$VOL\" && chmod 600 \"$VOL\" && SEEDED=yes && VOL_REAL=yes\nfi\necho \"EXTRACTED=$EXTRACTED SEEDED=$SEEDED VOLREAL=$VOL_REAL\"\n`;\n\n/**\n * Bidirectionally sync the box's `.credentials.json` with the host backup:\n *\n * - volume has a real OAuth blob and the box is **not** isolate → copy it OUT\n * to {@link CREDENTIALS_BACKUP_FILE} (the volume is authoritative — it is\n * the live copy the in-box claude refreshes).\n * - volume has no `.credentials.json` and the host backup is real → copy it\n * IN (seeds a fresh isolate box, or a recreated shared volume).\n * - otherwise → noop.\n *\n * Isolate boxes are read-seed only — never extract — so N isolate boxes can't\n * race on the single host backup.\n *\n * Best-effort: any failure resolves to `{ direction: 'noop' }` and never\n * throws into a box operation.\n */\nexport async function syncClaudeCredentials(\n spec: ClaudeConfigSpec,\n opts: { image: string; isolate: boolean },\n): Promise<SyncClaudeCredentialsResult> {\n try {\n await mkdir(STATE_DIR, { recursive: true });\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/dst`,\n '-v',\n `${STATE_DIR}:/host-state`,\n '-e',\n `ISOLATE=${opts.isolate ? 'yes' : 'no'}`,\n opts.image,\n 'sh',\n '-c',\n SYNC_SCRIPT,\n ]);\n const result = parseSyncResult(stdout);\n // The helper runs as root; re-assert 0600 from the host side so the backup\n // is owner-only regardless of how the bind mount maps ownership.\n if (result.direction === 'extracted') {\n await chmod(CREDENTIALS_BACKUP_FILE, 0o600).catch(() => {});\n }\n return result;\n } catch {\n return { direction: 'noop', volumeHasCredentials: false };\n }\n}\n","// The box state store is provider-neutral and lives in @agentbox/sandbox-core\n// so cloud providers share it. The record TYPES live in @agentbox/core. Both\n// are re-exported here so existing `@agentbox/sandbox-docker` consumers keep\n// importing them from the same place.\nexport {\n STATE_DIR,\n STATE_FILE,\n allocateProjectIndex,\n autoPickProjectBox,\n findBox,\n readState,\n recordBox,\n recordLastAgent,\n removeBoxRecord,\n reserveProjectIndex,\n resolveBoxRef,\n writeState,\n} from '@agentbox/sandbox-core';\nexport type { BoxRecord, FindBoxResult, GitWorktreeRecord, StateFile } from '@agentbox/core';\n","import { spawnSync } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport { buildTermSafeTmuxExec, buildTmuxSessionArgs, CONTAINER_USER } from './claude.js';\nimport {\n CODEX_PULL_ITEMS,\n sanitizeCodexConfigForBox,\n mergeCodexConfigForBox,\n MINIMAL_TRUSTED_CODEX_CONFIG,\n} from '@agentbox/sandbox-core';\nimport { ensureVolume, volumeExists } from '../../docker.js';\n\n/**\n * Codex support mirrors the Claude support in `claude.ts`, trimmed for what\n * Codex actually has: a synced `~/.codex` config volume, a detachable tmux\n * session, and `codex login`. Codex plugins ride the config sync (git\n * marketplaces + `plugins/cache` + the `.tmp/marketplaces` snapshots; box\n * `config.toml` is merge-reconciled, not overwritten) — there is no\n * plugin-native-deps rebuild and no setup-skill seeding here.\n */\nexport const SHARED_CODEX_VOLUME = 'agentbox-codex-config';\nexport const DEFAULT_CODEX_SESSION = 'codex';\n/** Workspace inside the box, same as for claude. */\nconst CONTAINER_CODEX_DIR = '/home/vscode/.codex';\n/**\n * Image-baked copy of the AgentBox Codex activity hooks (Dockerfile.box COPYs\n * `scripts/agentbox-codex-hooks.json` here). {@link seedCodexHooks} copies it\n * into the codex-config volume as `~/.codex/hooks.json`.\n */\nconst IN_BOX_CODEX_HOOKS_PATH = '/usr/local/share/agentbox/codex-hooks.json';\n/**\n * Image-baked box \"system prompt\": operational facts about the sandbox (it's a\n * container, `/workspace` is a per-box worktree, push/PR/cp go through the host\n * relay, identity in `/etc/agentbox/box.env`). Installed at this path on every\n * provider (Dockerfile.box COPY for docker/daytona; the cloud install scripts\n * copy it here too). {@link buildCodexAgentsOverrideScript} folds it into\n * `~/.codex/AGENTS.override.md` so the in-box Codex agent reads the same facts\n * Claude gets — Codex has no `/etc`-level memory slot of its own.\n */\nexport const BOX_SYSTEM_PROMPT_PATH = '/etc/claude-code/CLAUDE.md';\n/** Marks our generated override so we never fold our own output back in. */\nconst CODEX_OVERRIDE_SENTINEL =\n '<!-- agentbox:box-facts (generated; edit AGENTS.md instead) -->';\n/**\n * Stdout marker the generator prints ONLY after it actually writes the override.\n * Callers key their \"seeded\" log off this (not just exit 0), since the script\n * also exits 0 in the no-op case where the box-facts file is absent.\n */\nexport const CODEX_OVERRIDE_WROTE_MARKER = 'agentbox:codex-override-written';\n\n/**\n * Build the `sh` snippet that (re)generates `<codexHome>/AGENTS.override.md` =\n * sentinel + box facts ({@link BOX_SYSTEM_PROMPT_PATH}) + the user's own global\n * Codex instructions. Codex loads the first non-empty of\n * `AGENTS.override.md` then `AGENTS.md` from CODEX_HOME (first-match-wins, no\n * concat, no `@import`), so to be additive we must own the override and fold the\n * user's content in below the facts.\n *\n * Idempotent: a sentinel on line 1 distinguishes our file from a user-authored\n * one, so re-runs don't fold our own output back in (no feedback loop). The\n * user's global — `AGENTS.md`, or a hand-authored `AGENTS.override.md` — is\n * folded in beneath the box facts. Because the host `~/.codex` is re-synced\n * before each seed (docker) the user's source is restored every create, so the\n * fold is stable across runs; the sentinel-only file is regenerated from that\n * fresh source. Box facts are read fresh too, so an image upgrade propagates on\n * the next create. No-op when the box-facts file is absent.\n *\n * Caller owns the file afterwards (docker chowns to uid 1000; the cloud path\n * runs the script as `vscode`, so ownership is already correct). `codexHome` is\n * `/dst` for the docker volume-seed container and `$HOME/.codex` in-box.\n */\nexport function buildCodexAgentsOverrideScript(codexHome: string): string {\n // `codexHome` is a build-time constant from our own callers, never user input.\n return [\n 'set -e',\n `BOX=${BOX_SYSTEM_PROMPT_PATH}`,\n '[ -f \"$BOX\" ] || exit 0',\n `DIR=${codexHome}`,\n 'OVR=\"$DIR/AGENTS.override.md\"',\n 'AGT=\"$DIR/AGENTS.md\"',\n `SENTINEL='${CODEX_OVERRIDE_SENTINEL}'`,\n 'UC=\"\"',\n 'if [ -f \"$OVR\" ] && ! head -n1 \"$OVR\" | grep -qF \"$SENTINEL\"; then',\n ' UC=$(cat \"$OVR\")',\n 'elif [ -f \"$AGT\" ]; then',\n ' UC=$(cat \"$AGT\")',\n 'fi',\n 'mkdir -p \"$DIR\"',\n 'TMP=\"$OVR.agentbox.tmp\"',\n '{',\n \" printf '%s\\\\n' \\\"$SENTINEL\\\"\",\n ' cat \"$BOX\"',\n ' if [ -n \"$UC\" ]; then',\n \" printf '\\\\n\\\\n'\",\n \" printf '%s\\\\n' \\\"$UC\\\"\",\n ' fi',\n '} > \"$TMP\"',\n 'mv \"$TMP\" \"$OVR\"',\n // Printed only on a real write; the early `exit 0` (box facts absent) skips\n // it, so callers can distinguish \"wrote\" from \"no-op\" on a 0 exit.\n `printf '%s\\\\n' '${CODEX_OVERRIDE_WROTE_MARKER}'`,\n ].join('\\n');\n}\n\nexport interface CodexConfigSpec {\n /** Resolved Docker volume name mounted at /home/vscode/.codex. */\n volume: string;\n}\n\nexport function resolveCodexVolume(opts: { isolate: boolean; boxId: string }): CodexConfigSpec {\n if (opts.isolate) {\n return { volume: `${SHARED_CODEX_VOLUME}-${opts.boxId}` };\n }\n return { volume: SHARED_CODEX_VOLUME };\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Single-quote a token for /bin/sh. Conservative: anything outside the safe\n * alphabet gets wrapped. Mirrors the helper in claude.ts (not exported there).\n */\nfunction shQuote(arg: string): string {\n if (arg.length === 0) return `''`;\n if (/^[A-Za-z0-9_\\-./=:@%+,]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport interface EnsureCodexVolumeOptions {\n /**\n * When true and the host's ~/.codex exists, rsync host -> volume on every\n * call. Additive (no `--delete`): host files win on overlap, box-only files\n * (e.g. an `auth.json` written by an in-box `codex login`) are preserved.\n * `config.toml` is the exception — never rsynced; reconcileVolumeCodexConfig\n * rewrites it as sanitized-host + box-only entries merged.\n */\n syncFromHost: boolean;\n /** Image used by the throwaway sync helper container (the box image). */\n image: string;\n}\n\nexport interface EnsureCodexVolumeResult {\n /** True only the very first time the volume is created (on this host). */\n created: boolean;\n /** True when the rsync helper ran (syncFromHost was true AND host ~/.codex existed). */\n synced: boolean;\n}\n\n/**\n * Ensure the codex-config volume exists, then (when {@link\n * EnsureCodexVolumeOptions.syncFromHost} is true and the host has a `~/.codex`)\n * rsync host -> volume via a throwaway helper container. The host is treated as\n * authoritative — same model as {@link import('./claude.js').ensureClaudeVolume}.\n *\n * Rollout transcripts (`sessions/`), logs (`log/`) and shell history\n * (`history.jsonl`) are excluded: large, box-irrelevant, and not something the\n * in-box codex needs seeded.\n *\n * Codex's session-state DBs and indexes are also excluded:\n * - `state_*.sqlite*` is the `threads` INDEX over the rollout files\n * (id -> rollout_path, cwd, title, git, ...). Codex reads the resume cwd\n * from `threads.cwd`, so seeding the host copy made a teleported session\n * resume at its *host* cwd and pop Codex's \"Choose working directory\"\n * prompt — overriding the cwd we rewrite in the rollout. The index is a\n * derived cache (Codex backfills it from the rollouts present, see the\n * `backfill_state` table), so the box rebuilds it from the one teleported\n * rollout (already rewritten to /workspace) -> no prompt.\n * - `logs_*.sqlite*`, `session_index.jsonl`,\n * `external_agent_session_imports.json`, `shell_snapshots/` are likewise\n * host-session runtime state, not config. Excluding them also stops the\n * host's entire cross-project Codex history from leaking into every box.\n * Config / auth / extensions (`config.toml`, `auth.json`, `prompts/`, `skills/`,\n * `plugins/`, `rules/`, `memories/`) are still synced.\n *\n * When there is nothing to sync the volume root is still `chown`ed to uid 1000\n * so a throwaway `codex login` container (running as `vscode`) can write\n * `auth.json` into a freshly created, otherwise root-owned volume.\n */\nexport async function ensureCodexVolume(\n spec: CodexConfigSpec,\n opts: EnsureCodexVolumeOptions,\n): Promise<EnsureCodexVolumeResult> {\n const existed = await volumeExists(spec.volume);\n await ensureVolume(spec.volume);\n const created = !existed;\n\n const hostCodex = join(homedir(), '.codex');\n const willSync = opts.syncFromHost && (await pathExists(hostCodex));\n if (willSync) {\n // Skills handling depends on whether the host uses the shared ~/.agents dir.\n // WITH ~/.agents: ~/.codex/skills/<x> are symlinks into ~/.agents/skills,\n // which the box mounts from its own volume (agents.ts) — codex reads\n // ~/.agents/skills directly, so the per-codex copies are redundant.\n // Exclude `skills` (also dodges an rsync \"could not make way for new\n // symlink\" failure when the shared volume holds them as real dirs from an\n // earlier deref) and `find`-purge those stale non-system dirs, keeping\n // codex's runtime-managed `.system`.\n // WITHOUT ~/.agents: the user keeps real skills directly under\n // ~/.codex/skills — sync them as-is (no exclude, no purge) so they reach\n // the box (the box has no ~/.agents volume to fall back on).\n const hasAgents = await pathExists(join(homedir(), '.agents'));\n const skillsExclude = hasAgents ? ' --exclude=skills' : '';\n const skillsPurge = hasAgents\n ? ' && { [ -d /dst/skills ] && find /dst/skills -mindepth 1 -maxdepth 1 ! -name .system -exec rm -rf {} + || true; }'\n : '';\n await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/dst`,\n '-v',\n `${hostCodex}:/src:ro`,\n opts.image,\n 'sh',\n '-c',\n // --exclude=hooks.json: the AgentBox activity hooks file is box-owned\n // (seeded by seedCodexHooks); never let the host copy clobber it.\n // --exclude=/config.toml (anchored — plugin repos legitimately contain\n // files named config.toml): box config is owned by\n // reconcileVolumeCodexConfig (sanitize + merge), never rsynced — copying\n // the host file here would wipe box-side `codex plugin add`/`mcp add`\n // state before the merge could read it.\n // The `.tmp/marketplaces` includes come FIRST (rsync filter rules are\n // first-match-wins): git-marketplace snapshots must reach the box or\n // in-box `codex plugin` breaks; `/.tmp/*` then drops `.tmp`'s other\n // children (the heavy desktop-app payloads) and the unanchored `.tmp`\n // still blocks nested `.tmp` dirs elsewhere.\n // The session-state DBs / indexes are excluded so a teleported session\n // resumes at /workspace (Codex reads the cwd from state_*.sqlite's threads\n // index, which it backfills from the box's rollouts) and the host's\n // cross-project Codex history doesn't leak into the box.\n // The trailing `rm -rf` purges anything a PREVIOUS sync (before these\n // excludes) already copied into the shared volume — rsync without\n // --delete only adds/updates. The globs are no-ops with `-f` when absent,\n // and never touch box-owned `sessions/` (the teleported rollouts) or\n // `hooks.json`. `.tmp` gets a selective purge that keeps `marketplaces/`.\n // Heavy host-only artifacts are also excluded (mirrors the codex spec in\n // sandbox-core's registry): `packages` (macOS standalone release binaries —\n // the in-box codex is npm-installed), `plugins/.plugin-appserver` (the\n // platform-specific plugin app-server runtime), `computer-use` (the macOS\n // `Codex Computer Use.app` bundle), `archived_sessions` (host history), and\n // the regenerable caches (`tmp`, `cache`, `vendor_imports`, `sqlite`,\n // `models_cache.json`). Without these the shared volume balloons to\n // ~1.5 GB and every create's rsync crawls.\n 'rsync -a --include=/.tmp/ --include=/.tmp/marketplaces/*** --exclude=/.tmp/*' +\n ' --exclude=sessions --exclude=log --exclude=history.jsonl --exclude=hooks.json' +\n ' --exclude=/config.toml' +\n skillsExclude +\n ' --exclude=state_*.sqlite* --exclude=logs_*.sqlite* --exclude=session_index.jsonl' +\n ' --exclude=external_agent_session_imports.json --exclude=shell_snapshots' +\n ' --exclude=packages --exclude=plugins/.plugin-appserver --exclude=computer-use' +\n ' --exclude=archived_sessions --exclude=.tmp --exclude=tmp --exclude=cache' +\n ' --exclude=vendor_imports --exclude=sqlite --exclude=models_cache.json' +\n ' /src/ /dst/' +\n ' && rm -rf /dst/state_*.sqlite* /dst/logs_*.sqlite* /dst/session_index.jsonl' +\n ' /dst/external_agent_session_imports.json /dst/shell_snapshots' +\n ' /dst/packages /dst/plugins/.plugin-appserver /dst/computer-use' +\n ' /dst/archived_sessions /dst/tmp /dst/cache' +\n ' /dst/vendor_imports /dst/sqlite /dst/models_cache.json' +\n ' && { [ -d /dst/.tmp ] && find /dst/.tmp -mindepth 1 -maxdepth 1 ! -name marketplaces -exec rm -rf {} + || true; }' +\n skillsPurge +\n ' && chown -R 1000:1000 /dst',\n ]);\n await reconcileVolumeCodexConfig(spec.volume, opts.image);\n return { created, synced: true };\n }\n\n // No host ~/.codex to sync — still make the (possibly freshly created,\n // root-owned) volume root writable by the in-box `vscode` user.\n await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/dst`,\n opts.image,\n 'sh',\n '-c',\n 'chown 1000:1000 /dst',\n ],\n { reject: false },\n );\n // Even with nothing to sync, pre-trust /workspace so a Codex user with no host\n // ~/.codex/config.toml doesn't hit the trust prompt. reconcileVolumeCodexConfig\n // merges the minimal trusted config into whatever the box already has.\n if (!(await pathExists(join(hostCodex, 'config.toml')))) {\n await reconcileVolumeCodexConfig(spec.volume, opts.image);\n }\n return { created, synced: false };\n}\n\n/**\n * Seed the AgentBox Codex activity hooks into the codex-config volume from the\n * image-baked copy ({@link IN_BOX_CODEX_HOOKS_PATH}) as `~/.codex/hooks.json`.\n * Codex auto-discovers that file; its hooks accumulate with any the user\n * defined, so this never disables the user's own hooks.\n *\n * Re-seeded on every create/start (image-versioned) so an image upgrade\n * propagates. Best-effort — a failure must not fail box creation.\n *\n * Shape note (codex 0.134.0): `hooks.json` must be `{ hooks: { Event: [...] } }`\n * (matching the `HooksFile` Rust struct), with NO extra top-level keys — codex's\n * strict parser rejects unknown fields (a stray `$comment` produced a startup\n * `failed to parse hooks config` warning). Loading also needs `--enable hooks`\n * and either the in-TUI trust dialog or `--dangerously-bypass-hook-trust`, both\n * supplied by {@link CODEX_AGENTBOX_FLAGS}. In practice JSON-hook firing is still\n * unreliable in 0.134.0 (TUI mode skips them on some startup paths) — the real\n * mechanism that lights up state in production is the tmux-pane scraper in\n * `packages/ctl/src/codex-scraper.ts`. These hooks remain a defense-in-depth\n * seed so any future codex build that fixes the firing also lights up state.\n */\nexport async function seedCodexHooks(\n volume: string,\n image: string,\n): Promise<{ seeded: boolean }> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n `{ [ -f ${IN_BOX_CODEX_HOOKS_PATH} ] && cp -a ${IN_BOX_CODEX_HOOKS_PATH} /dst/hooks.json && ` +\n `chown 1000:1000 /dst/hooks.json && echo SEEDED; } || true`,\n ]);\n return { seeded: stdout.includes('SEEDED') };\n } catch {\n return { seeded: false };\n }\n}\n\n/**\n * Regenerate `~/.codex/AGENTS.override.md` in the codex-config volume so the\n * in-box Codex agent picks up the box \"system prompt\" ({@link\n * BOX_SYSTEM_PROMPT_PATH}). Runs in a throwaway container with the volume at\n * `/dst`; reads the box-facts file from the image's own fs and any user global\n * from the volume. Must run AFTER {@link ensureCodexVolume} (the host rsync) so\n * the user's synced `AGENTS.md`/override is in place to fold in. Best-effort —\n * never fail box creation. See {@link buildCodexAgentsOverrideScript}.\n */\nexport async function seedCodexAgentsOverride(\n volume: string,\n image: string,\n): Promise<{ seeded: boolean }> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n buildCodexAgentsOverrideScript('/dst') +\n '\\nchown 1000:1000 \"$OVR\" 2>/dev/null || true',\n ]);\n return { seeded: stdout.includes(CODEX_OVERRIDE_WROTE_MARKER) };\n } catch {\n return { seeded: false };\n }\n}\n\n/**\n * Shell snippet that deletes marketplace artifacts the merged config no longer\n * references: `plugins/cache/<name>` (installed-plugin payloads — the host's\n * desktop-app caches carry macOS junk) and `.tmp/marketplaces/<name>` (snapshot\n * checkouts, incl. codex's transient `.staging`). Keep-set names are\n * shell-quoted; an empty keep-set purges everything (no marketplaces\n * configured ⇒ nothing to keep). Exported for unit tests.\n */\nexport function buildCodexOrphanPurgeScript(keptMarketplaces: string[]): string {\n const keepFlags = keptMarketplaces.map((n) => `! -name ${shQuote(n)}`).join(' ');\n const purgeDir = (dir: string): string =>\n `{ [ -d ${dir} ] && find ${dir} -mindepth 1 -maxdepth 1` +\n (keepFlags.length > 0 ? ` ${keepFlags}` : '') +\n ` -exec rm -rf {} + || true; }`;\n return `${purgeDir('/dst/plugins/cache')} && ${purgeDir('/dst/.tmp/marketplaces')}`;\n}\n\n/**\n * Reconcile the box's `~/.codex/config.toml` in the codex-config volume: the\n * sanitized host config ({@link sanitizeCodexConfigForBox} — drops\n * desktop-Codex.app MCP servers, the macOS `notify` helper, local-source\n * marketplaces) is the base, and the box's existing config is folded in\n * additively ({@link mergeCodexConfigForBox}) so in-box `codex plugin add` /\n * `codex mcp add` / bootstrapped marketplaces survive re-syncs. The rsync in\n * {@link ensureCodexVolume} deliberately excludes `config.toml`; this function\n * is the file's sole writer.\n *\n * Afterwards, in the same helper container, marketplace caches/snapshots not\n * referenced by the *merged* config are purged (the merged set — not the\n * sanitize set — so marketplaces installed in-box keep their caches).\n *\n * Best-effort throughout: on a host-config parse failure we keep an existing\n * box config untouched (or fall back to the raw host text when the volume has\n * none — the box must never end up without a `config.toml`); on any container\n * error the volume is left as-is.\n */\nasync function reconcileVolumeCodexConfig(\n volume: string,\n image: string,\n): Promise<{ reconciled: boolean }> {\n try {\n // Read the box's current config first — the merge input, and the fallback\n // decider when the host config doesn't parse.\n const boxRead = await execa(\n 'docker',\n ['run', '--rm', '-v', `${volume}:/dst`, image, 'sh', '-c', 'cat /dst/config.toml'],\n { reject: false },\n );\n const boxText = boxRead.exitCode === 0 ? boxRead.stdout : null;\n\n const hostConfig = join(homedir(), '.codex', 'config.toml');\n // No host config: merge the minimal /workspace-pre-trust config into\n // whatever the box has, so a Codex user without a host config.toml doesn't\n // hit the \"trust this folder?\" prompt and box-side state still survives.\n let base: string;\n if (!(await pathExists(hostConfig))) {\n base = MINIMAL_TRUSTED_CODEX_CONFIG;\n } else {\n const hostText = await readFile(hostConfig, 'utf8');\n try {\n base = sanitizeCodexConfigForBox(hostText).text;\n } catch {\n // Host TOML doesn't parse. An existing box config is more trustworthy\n // than the raw host text — keep it (and skip the purge: keep-set\n // unknown). With an empty volume, seed the raw host text verbatim.\n if (boxText !== null) return { reconciled: false };\n await writeVolumeCodexConfig(volume, image, hostText, null);\n return { reconciled: true };\n }\n }\n\n const merged = mergeCodexConfigForBox(base, boxText);\n await writeVolumeCodexConfig(volume, image, merged.text, merged.marketplaces);\n return { reconciled: true };\n } catch {\n return { reconciled: false };\n }\n}\n\n/**\n * Write `config.toml` into the volume via a throwaway container, then (when a\n * keep-set is known) purge orphaned marketplace dirs in the same shell. `-i`\n * keeps stdin attached so execa's `input` reaches `cat`; without it the\n * container gets immediate EOF and `>` truncates config.toml to empty. Write\n * to a temp file then `mv` so a partial/failed write never clobbers the\n * existing copy.\n */\nasync function writeVolumeCodexConfig(\n volume: string,\n image: string,\n text: string,\n keptMarketplaces: string[] | null,\n): Promise<void> {\n const purge = keptMarketplaces === null ? '' : ` && ${buildCodexOrphanPurgeScript(keptMarketplaces)}`;\n await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '-i',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n 'cat > /dst/config.toml.tmp && chown 1000:1000 /dst/config.toml.tmp && ' +\n 'mv /dst/config.toml.tmp /dst/config.toml' +\n purge,\n ],\n { input: text },\n );\n}\n\nexport interface CodexMountResult {\n /** Docker -v spec strings to append to runBox(extraVolumes). */\n extraVolumes: string[];\n /** Env vars to forward into the container; only keys set + non-empty on the host. */\n env: Record<string, string>;\n volumeName: string;\n}\n\n// Forwarded from the host's `process.env` into the box at `docker run -e` time\n// (and re-forwarded by `startCodexSession` at `docker exec -e` time). Codex\n// stores the selected model in `~/.codex/config.toml`, not the environment, so\n// the API key is the only thing worth forwarding.\nexport const CODEX_FORWARDED_ENV_KEYS = ['OPENAI_API_KEY'] as const;\n\nexport function buildCodexMounts(\n spec: CodexConfigSpec,\n hostEnv: NodeJS.ProcessEnv,\n): CodexMountResult {\n const env: Record<string, string> = {};\n for (const k of CODEX_FORWARDED_ENV_KEYS) {\n const v = hostEnv[k];\n if (typeof v === 'string' && v.length > 0) env[k] = v;\n }\n return {\n extraVolumes: [`${spec.volume}:${CONTAINER_CODEX_DIR}`],\n env,\n volumeName: spec.volume,\n };\n}\n\nexport class CodexSessionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CodexSessionError';\n }\n}\n\nexport interface EnsureCodexInstalledResult {\n /**\n * True when codex had to be installed just now — i.e. it was absent from the\n * box image. Happens for boxes created from a checkpoint image captured\n * before Codex was baked into the base image, or from an older base image.\n */\n installed: boolean;\n}\n\n/**\n * Make sure the `codex` binary is on PATH inside the box. Codex is baked into\n * the current base image, but a box created from a **checkpoint** image (a\n * frozen snapshot — see docs/create-and-checkpoints.md) captured before Codex\n * support, or from an older base image, won't have it. In that case we\n * `npm install -g @openai/codex` into the box's writable layer (persists across\n * stop/start, wiped on destroy), mirroring how `--with-playwright` installs at\n * create time.\n *\n * Fast no-op (one `command -v`) when codex is already present — the case for\n * every box built from the current base image. Throws {@link CodexSessionError}\n * when codex is absent *and* the install fails.\n */\nexport async function ensureCodexInstalled(\n container: string,\n opts: { onProgress?: (line: string) => void } = {},\n): Promise<EnsureCodexInstalledResult> {\n const probe = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'sh', '-c', 'command -v codex'],\n { reject: false },\n );\n if (probe.exitCode === 0) return { installed: false };\n\n opts.onProgress?.('installing codex (absent from this box image)');\n const install = await execa(\n 'docker',\n ['exec', '--user', 'root', container, 'bash', '-lc', 'npm install -g @openai/codex 2>&1'],\n { reject: false },\n );\n if (install.exitCode !== 0) {\n throw new CodexSessionError(\n `codex is not in this box's image and \\`npm install -g @openai/codex\\` failed ` +\n `(exit ${String(install.exitCode)}). This box was likely created from a ` +\n `checkpoint captured before Codex support — recapture the project checkpoint ` +\n `from a fresh box. Install output:\\n${(install.stdout ?? '').toString().slice(-600)}`,\n );\n }\n return { installed: true };\n}\n\nexport interface StartCodexSessionOptions {\n container: string;\n codexArgs: string[];\n sessionName?: string;\n}\n\n/**\n * Start a detached tmux session running the Codex CLI inside the container.\n * Survives client disconnects; reattach via {@link buildCodexAttachArgv}. The\n * shared {@link buildTmuxSessionArgs} remaps the prefix (Ctrl+a / Ctrl+b) and\n * hides the inner status bar, exactly as for the claude session.\n */\n// Flags codex needs to actually try our seeded hooks.json from the box image:\n// - `--enable hooks` opts into Claude-style lifecycle hook loading (the codex\n// feature was renamed from `codex_hooks` -> `hooks` in 0.134.0).\n// - `--dangerously-bypass-hook-trust` skips the in-TUI \"trust these hooks?\"\n// dialog that would otherwise block startup on every fresh box. The hooks\n// are AgentBox-managed and pre-vetted; the user never sees them, so trust\n// verification has no UX value here.\n// The flag makes codex print a (cosmetic, duplicated) \"--dangerously-bypass-\n// hook-trust is enabled\" warning at startup. There is NO codex option to\n// silence only that warning. The only way to drop it is to stop passing the\n// flag and instead persist hook trust in config.toml as\n// `[hooks.state.\"<hooks.json path>:<event>:0:0\"] trusted_hash = \"sha256:…\"`\n// (one entry per event, written when you accept the dialog). We deliberately\n// do NOT seed those: the hash is an opaque codex-internal digest (not\n// reproducible from the hook command) tied to both hooks.json content and the\n// codex version — a mismatch turns the cosmetic warning into a *blocking*\n// \"Hooks need review\" dialog on every box. The bypass flag always works, so\n// the warning is the accepted cost. (`hooks.managed_dir` auto-trusts but did\n// not fire the hooks in testing.)\n// The actual mechanism that lights up codex.state in production is the\n// tmux-pane scraper (codex-scraper.ts); these flags are defense-in-depth for\n// the day codex's JSON-hook firing becomes reliable (it does fire on 0.141.0).\nconst CODEX_AGENTBOX_FLAGS = ['--enable', 'hooks', '--dangerously-bypass-hook-trust'] as const;\n\nexport async function startCodexSession(opts: StartCodexSessionOptions): Promise<void> {\n const sessionName = opts.sessionName ?? DEFAULT_CODEX_SESSION;\n const cmd = ['codex', ...CODEX_AGENTBOX_FLAGS, ...opts.codexArgs].map(shQuote).join(' ');\n const term = process.env['TERM'] ?? 'xterm-256color';\n const envFlags: string[] = ['-e', `TERM=${term}`];\n for (const k of CODEX_FORWARDED_ENV_KEYS) {\n const v = process.env[k];\n if (typeof v === 'string' && v.length > 0) envFlags.push('-e', `${k}=${v}`);\n }\n const result = await execa(\n 'docker',\n [\n 'exec',\n ...envFlags,\n '--user',\n CONTAINER_USER,\n opts.container,\n 'tmux',\n 'new-session',\n '-d',\n '-s',\n sessionName,\n cmd,\n ...buildTmuxSessionArgs(sessionName),\n ],\n { reject: false },\n );\n if (result.exitCode === 0) return;\n const stderr = (result.stderr ?? '').toString();\n if (result.exitCode === 127 || /command not found|tmux: not found/i.test(stderr)) {\n throw new CodexSessionError(\n `tmux is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/codex.*not found|exec: \"codex\"/i.test(stderr)) {\n throw new CodexSessionError(\n `codex is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/duplicate session/i.test(stderr)) {\n throw new CodexSessionError(\n `a tmux session \"${sessionName}\" already exists in ${opts.container}; use \\`agentbox codex attach\\` to reattach.`,\n );\n }\n throw new CodexSessionError(\n `failed to start codex session in ${opts.container}: ${stderr.trim() || `exit ${String(result.exitCode)}`}`,\n );\n}\n\n/**\n * The `docker` argv that attaches an interactive terminal to a box's Codex\n * tmux session. Mirrors {@link import('./claude.js').buildClaudeAttachArgv}.\n */\nexport function buildCodexAttachArgv(container: string, sessionName?: string): string[] {\n const name = sessionName ?? DEFAULT_CODEX_SESSION;\n return buildTermSafeTmuxExec({\n container,\n user: CONTAINER_USER,\n tmuxScript: 'exec tmux attach -t \"$1\"',\n positionals: [name],\n });\n}\n\n/**\n * The `docker run` argv for an interactive `codex login` in a throwaway\n * container. Mounts the codex-config volume at `~/.codex` so the written\n * credentials persist. Defaults to `--device-auth` — the headless device-code\n * flow (prints a URL + one-time code, no localhost callback to publish) — which\n * is the only OAuth flow that works cleanly from inside a container. Explicit\n * `extraArgs` (e.g. `['--api-key']`) override the default verbatim.\n *\n * `DISPLAY` is blanked for the same reason as the claude login: the image bakes\n * `DISPLAY=:1` (a VNC X server) and codex must not try to open a browser there.\n */\nexport function buildCodexLoginRunArgv(opts: {\n volume: string;\n image: string;\n extraArgs: string[];\n}): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n const loginArgs = opts.extraArgs.length > 0 ? opts.extraArgs : ['--device-auth'];\n return [\n 'run',\n '-it',\n '--rm',\n '-e',\n `TERM=${term}`,\n '-e',\n 'DISPLAY=',\n '-v',\n `${opts.volume}:${CONTAINER_CODEX_DIR}`,\n '--user',\n CONTAINER_USER,\n opts.image,\n 'codex',\n 'login',\n ...loginArgs,\n ];\n}\n\n/**\n * Run an interactive docker argv (from {@link buildCodexLoginRunArgv}) with the\n * user's terminal attached. Returns the exit code; a null status is reported\n * as 1.\n */\nexport function runInteractiveCodexLogin(dockerArgv: string[]): { exitCode: number } {\n const child = spawnSync('docker', dockerArgv, { stdio: 'inherit' });\n return { exitCode: child.status ?? 1 };\n}\n\n/**\n * True when the codex-config volume already holds an `auth.json`. Used to skip\n * the first-run sign-in offer when an earlier box / `agentbox codex login`\n * already authenticated.\n */\nexport async function volumeHasCodexAuth(volume: string, image: string): Promise<boolean> {\n const res = await execa(\n 'docker',\n ['run', '--rm', '-v', `${volume}:/dst`, image, 'sh', '-c', 'test -e /dst/auth.json'],\n { reject: false },\n );\n return res.exitCode === 0;\n}\n\nexport interface CodexSessionInfo {\n running: boolean;\n sessionName: string;\n /** ISO-8601 timestamp from tmux's `#{session_created}`, or null when not running. */\n startedAt: string | null;\n}\n\n/**\n * Best-effort: returns `{ running: false, …, startedAt: null }` for any\n * non-zero exit from `tmux has-session`. Mirrors `claudeSessionInfo`.\n */\nexport async function codexSessionInfo(\n container: string,\n sessionName?: string,\n): Promise<CodexSessionInfo> {\n const name = sessionName ?? DEFAULT_CODEX_SESSION;\n const has = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'tmux', 'has-session', '-t', name],\n { reject: false },\n );\n if (has.exitCode !== 0) {\n return { running: false, sessionName: name, startedAt: null };\n }\n const ts = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n CONTAINER_USER,\n container,\n 'tmux',\n 'display-message',\n '-p',\n '-t',\n name,\n '#{session_created}',\n ],\n { reject: false },\n );\n let startedAt: string | null = null;\n if (ts.exitCode === 0) {\n const secs = Number.parseInt((ts.stdout ?? '').trim(), 10);\n if (Number.isFinite(secs) && secs > 0) startedAt = new Date(secs * 1000).toISOString();\n }\n return { running: true, sessionName: name, startedAt };\n}\n\nexport interface PullCodexResult {\n /** Volume items copied to the host (or, in dry-run, that would be copied). */\n newItems: string[];\n}\n\nexport interface PullCodexOptions {\n /** Image for the throwaway helper container; use the box's image. */\n image: string;\n /** When true, compute the delta but write nothing. */\n dryRun?: boolean;\n}\n\n/**\n * Reverse of {@link ensureCodexVolume}: pull box-side codex config/auth from\n * the codex-config volume back to the host's `~/.codex`. Additive only — an\n * item already present on the host is never overwritten. The box need not be\n * running (we read the *volume* via a throwaway helper container).\n */\nexport async function pullCodexConfig(\n spec: CodexConfigSpec,\n opts: PullCodexOptions,\n): Promise<PullCodexResult> {\n const hostCodex = join(homedir(), '.codex');\n\n const inv = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/src:ro`,\n opts.image,\n 'sh',\n '-c',\n `for f in ${CODEX_PULL_ITEMS.join(' ')}; do [ -e \"/src/$f\" ] && echo \"$f\"; done; true`,\n ],\n { reject: false },\n );\n if (inv.exitCode !== 0) {\n throw new CodexSessionError(\n `failed to read codex-config volume ${spec.volume}: ${(inv.stderr ?? '').toString().trim() || `exit ${String(inv.exitCode)}`}`,\n );\n }\n\n const present = new Set(\n (inv.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean),\n );\n const newItems: string[] = [];\n for (const item of CODEX_PULL_ITEMS) {\n if (!present.has(item)) continue;\n if (await pathExists(join(hostCodex, item))) continue; // additive — never overwrite\n newItems.push(item);\n }\n\n if (opts.dryRun || newItems.length === 0) return { newItems };\n\n // Copy each new item from the volume into the host ~/.codex. `--user 0` so\n // root can read uid-1000 files; chown the result back to the host user so\n // the host's own `codex` can read/write a freshly created ~/.codex.\n const uid = process.getuid?.() ?? 0;\n const gid = process.getgid?.() ?? 0;\n const cmds = newItems.map((it) => `cp -a '/src/${it}' '/dst/${it}'`);\n const apply = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/src:ro`,\n '-v',\n `${hostCodex}:/dst`,\n opts.image,\n 'sh',\n '-c',\n `mkdir -p /dst && ${cmds.join(' && ')} && chown -R ${String(uid)}:${String(gid)} /dst`,\n ],\n { reject: false },\n );\n if (apply.exitCode !== 0) {\n throw new CodexSessionError(\n `failed to copy codex config from ${spec.volume}: ${(apply.stderr ?? '').toString().trim() || `exit ${String(apply.exitCode)}`}`,\n );\n }\n return { newItems };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { seedAgentsVolume } from '@agentbox/sandbox-core';\nimport { ensureVolume, volumeExists } from '../../docker.js';\nimport { createDockerSyncTransport } from '../sync-transport.js';\n\n/**\n * The shared `~/.agents` directory — the cross-agent \"Agent Skills\" location\n * (`~/.agents/skills/<name>`, managed by the open skills installer). Codex\n * discovers skills from here directly (not just `~/.codex/skills`), and the\n * per-agent `~/.codex/skills/<x>` symlinks point back into it\n * (`../../.agents/skills/<x>`). We mount it into the box so the in-box agents\n * see the same skill set the host does.\n *\n * Unlike claude/codex this holds no auth — it's skills only — but it's synced\n * the same host-authoritative way and shares one volume across boxes.\n */\nexport const SHARED_AGENTS_VOLUME = 'agentbox-agents-config';\n\n/** Where the agents volume is mounted in the box. */\nconst CONTAINER_AGENTS_DIR = '/home/vscode/.agents';\n\nexport interface AgentsConfigSpec {\n /** Resolved Docker volume name mounted at /home/vscode/.agents. */\n volume: string;\n}\n\n/** Always the shared volume — `~/.agents` is skills-only, so per-box isolation\n * buys nothing (no auth to keep separate). */\nexport function resolveAgentsVolume(): AgentsConfigSpec {\n return { volume: SHARED_AGENTS_VOLUME };\n}\n\nexport interface EnsureAgentsVolumeOptions {\n /**\n * When true and the host's ~/.agents exists, rsync host -> volume on every\n * call. Additive (no `--delete`): host files win on overlap.\n */\n syncFromHost: boolean;\n /** Image used by the throwaway sync helper container (the box image). */\n image: string;\n}\n\nexport interface EnsureAgentsVolumeResult {\n /** True only the very first time the volume is created (on this host). */\n created: boolean;\n /** True when the rsync helper ran (syncFromHost was true AND host ~/.agents existed). */\n synced: boolean;\n}\n\n/**\n * Ensure the agents-config volume exists, then (when {@link\n * EnsureAgentsVolumeOptions.syncFromHost} is true and the host has a `~/.agents`)\n * rsync host -> volume via a throwaway helper container. Mirrors\n * {@link import('./codex.js').ensureCodexVolume}.\n *\n * `--copy-unsafe-links` dereferences a skill's symlinks that point outside\n * `~/.agents` into real files in the volume; broken / out-of-tree symlinks are\n * `--exclude`d (via {@link findUnsyncableSymlinks}) so the sync can't abort with\n * \"symlink has no referent\".\n */\nexport async function ensureAgentsVolume(\n spec: AgentsConfigSpec,\n opts: EnsureAgentsVolumeOptions,\n): Promise<EnsureAgentsVolumeResult> {\n const existed = await volumeExists(spec.volume);\n await ensureVolume(spec.volume);\n const created = !existed;\n\n // The host→volume rsync (symlink handling, `--copy-unsafe-links`, the\n // no-host-dir writable-chown fallback) is the shared skills concern, driven\n // through the transport's throwaway rsync-helper container. `container: ''`\n // because the seed needs only the helper image, not a running box.\n const transport = createDockerSyncTransport({ container: '', image: opts.image });\n const { synced } = await seedAgentsVolume({\n transport,\n volume: spec.volume,\n hostAgents: join(homedir(), '.agents'),\n syncFromHost: opts.syncFromHost,\n });\n return { created, synced };\n}\n\nexport interface AgentsMountResult {\n /** Docker -v spec strings to append to runBox(extraVolumes). */\n extraVolumes: string[];\n /** The resolved volume name (for BoxRecord). */\n volumeName: string;\n}\n\nexport function buildAgentsMounts(spec: AgentsConfigSpec): AgentsMountResult {\n return {\n extraVolumes: [`${spec.volume}:${CONTAINER_AGENTS_DIR}`],\n volumeName: spec.volume,\n };\n}\n","import { spawnSync } from 'node:child_process';\nimport { stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport { buildTermSafeTmuxExec, buildTmuxSessionArgs, CONTAINER_USER } from './claude.js';\nimport {\n OPENCODE_PULL_CONFIG_ITEMS,\n OPENCODE_PULL_DATA_ITEMS,\n} from '@agentbox/sandbox-core';\nimport { ensureVolume, volumeExists } from '../../docker.js';\n\n/**\n * OpenCode support mirrors the Codex support in `codex.ts`. The one structural\n * difference: OpenCode splits its state across two XDG directories —\n * `~/.config/opencode` (config) and `~/.local/share/opencode` (data + the\n * `auth.json` provider credentials). A single volume holds both: it is mounted\n * at the data dir, and the config dir is relocated into a `config/` subdir of\n * that same volume via the `OPENCODE_CONFIG_DIR` env var (OpenCode-specific, so\n * safe to set box-global — unlike `XDG_DATA_HOME`).\n */\nexport const SHARED_OPENCODE_VOLUME = 'agentbox-opencode-config';\nexport const DEFAULT_OPENCODE_SESSION = 'opencode';\n/** Volume mount point inside the box — OpenCode's native data dir. */\nconst CONTAINER_OPENCODE_DIR = '/home/vscode/.local/share/opencode';\n/** Relocated config dir (a subdir of the volume); the value of `OPENCODE_CONFIG_DIR`. */\nconst CONTAINER_OPENCODE_CONFIG_DIR = '/home/vscode/.local/share/opencode/config';\n/**\n * Relocated XDG state base (a subdir of the volume); the value of `XDG_STATE_HOME`.\n * OpenCode derives its state dir as `$XDG_STATE_HOME/opencode`, so its state\n * (incl. `model.json` — the last-selected model) lands at\n * `<volume>/.state/opencode` and persists with the volume. OpenCode has no\n * dedicated `OPENCODE_STATE_DIR`, so `XDG_STATE_HOME` is the only knob.\n */\nconst CONTAINER_OPENCODE_STATE_HOME = '/home/vscode/.local/share/opencode/.state';\n/** Image-baked AgentBox OpenCode plugin (copied in from packages/sandbox-docker/scripts/). */\nconst IN_BOX_OPENCODE_PLUGIN_PATH = '/usr/local/share/agentbox/opencode-agentbox-plugin.js';\n\nexport interface OpencodeConfigSpec {\n /** Resolved Docker volume name mounted at the OpenCode data dir. */\n volume: string;\n}\n\nexport function resolveOpencodeVolume(opts: {\n isolate: boolean;\n boxId: string;\n}): OpencodeConfigSpec {\n if (opts.isolate) {\n return { volume: `${SHARED_OPENCODE_VOLUME}-${opts.boxId}` };\n }\n return { volume: SHARED_OPENCODE_VOLUME };\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Single-quote a token for /bin/sh. Conservative: anything outside the safe\n * alphabet gets wrapped. Mirrors the helper in codex.ts.\n */\nfunction shQuote(arg: string): string {\n if (arg.length === 0) return `''`;\n if (/^[A-Za-z0-9_\\-./=:@%+,]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport interface EnsureOpencodeVolumeOptions {\n /**\n * When true and the host has OpenCode dirs, rsync host -> volume on every\n * call. Additive (no `--delete`): host files win on overlap, box-only files\n * (e.g. an `auth.json` written by an in-box `opencode auth login`) are kept.\n */\n syncFromHost: boolean;\n /** Image used by the throwaway sync helper container (the box image). */\n image: string;\n}\n\nexport interface EnsureOpencodeVolumeResult {\n /** True only the very first time the volume is created (on this host). */\n created: boolean;\n /** True when the rsync helper ran (syncFromHost was true AND a host dir existed). */\n synced: boolean;\n}\n\n/**\n * Ensure the opencode-config volume exists, then (when {@link\n * EnsureOpencodeVolumeOptions.syncFromHost} is true and the host has OpenCode\n * state) rsync host -> volume via a throwaway helper container. The host is\n * authoritative — same model as the claude/codex volumes.\n *\n * Three host sources land in the one volume: `~/.local/share/opencode` -> volume\n * root (the data dir, holds `auth.json`), `~/.config/opencode` -> volume\n * `config/` (the relocated config dir), and `~/.local/state/opencode` ->\n * volume `.state/opencode` (the relocated state dir, holds `model.json` — the\n * last-selected model, matched by `XDG_STATE_HOME` in {@link buildOpencodeMounts}).\n * The data sync excludes the SQLite session storage / logs (`storage`, `log`,\n * `project`, `cache`, `bin`) — large, box-irrelevant, and host binaries don't run\n * on linux. The state sync is newest-wins (`--update`) since the model is two-way.\n *\n * When there is nothing to sync the volume root is still `chown`ed to uid 1000\n * so a throwaway `opencode auth login` container can write into it.\n */\nexport async function ensureOpencodeVolume(\n spec: OpencodeConfigSpec,\n opts: EnsureOpencodeVolumeOptions,\n): Promise<EnsureOpencodeVolumeResult> {\n const existed = await volumeExists(spec.volume);\n await ensureVolume(spec.volume);\n const created = !existed;\n\n const hostData = join(homedir(), '.local', 'share', 'opencode');\n const hostConfig = join(homedir(), '.config', 'opencode');\n const hostState = join(homedir(), '.local', 'state', 'opencode');\n const hasData = await pathExists(hostData);\n const hasConfig = await pathExists(hostConfig);\n const hasState = await pathExists(hostState);\n const willSync = opts.syncFromHost && (hasData || hasConfig || hasState);\n\n if (willSync) {\n const args = ['run', '--rm', '--user', '0', '-v', `${spec.volume}:/dst`];\n if (hasData) args.push('-v', `${hostData}:/src-data:ro`);\n if (hasConfig) args.push('-v', `${hostConfig}:/src-config:ro`);\n if (hasState) args.push('-v', `${hostState}:/src-state:ro`);\n const steps: string[] = [];\n if (hasData) {\n // Exclude the SQLite session store (`opencode.db*`), logs, cloned repos\n // and host binaries — large / box-irrelevant. `auth.json` (when present)\n // and small json carry over.\n steps.push(\n 'rsync -a --exclude=storage --exclude=log --exclude=project --exclude=cache' +\n ' --exclude=bin --exclude=repos --exclude=config' +\n ' --exclude=opencode.db --exclude=opencode.db-shm --exclude=opencode.db-wal' +\n ' /src-data/ /dst/',\n );\n }\n if (hasConfig) {\n steps.push('mkdir -p /dst/config && rsync -a /src-config/ /dst/config/');\n }\n if (hasState) {\n // The selected model (`model.json`) is two-way state, not host-authoritative\n // config: `--update` (newest-wins) keeps a stale host file from clobbering a\n // model picked inside the box (which persists in this volume). `locks` is a\n // runtime lock dir — host-local, never synced.\n steps.push(\n 'mkdir -p /dst/.state/opencode &&' +\n ' rsync -a --update --exclude=locks /src-state/ /dst/.state/opencode/',\n );\n }\n steps.push('chown -R 1000:1000 /dst');\n args.push(opts.image, 'sh', '-c', steps.join(' && '));\n await execa('docker', args);\n return { created, synced: true };\n }\n\n // No host OpenCode state to sync — still make the (possibly freshly created,\n // root-owned) volume root writable by the in-box `vscode` user.\n await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/dst`,\n opts.image,\n 'sh',\n '-c',\n 'chown 1000:1000 /dst',\n ],\n { reject: false },\n );\n return { created, synced: false };\n}\n\n/**\n * Seed the AgentBox state-reporting plugin into the OpenCode config volume\n * from the image-baked copy ({@link IN_BOX_OPENCODE_PLUGIN_PATH}) as\n * `<volume>/config/plugins/agentbox-state.js`. OpenCode auto-loads any\n * JS/TS file under `$OPENCODE_CONFIG_DIR/plugins/` at startup; the plugin\n * subscribes to OpenCode's event bus and shells `agentbox-ctl opencode-state`\n * for each lifecycle transition.\n *\n * Re-seeded on every create/start (image-versioned) so an image upgrade\n * propagates. Best-effort — a failure must not fail box creation.\n */\nexport async function seedOpencodePlugin(\n volume: string,\n image: string,\n): Promise<{ seeded: boolean }> {\n try {\n const { stdout } = await execa('docker', [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n `{ [ -f ${IN_BOX_OPENCODE_PLUGIN_PATH} ] && mkdir -p /dst/config/plugins && ` +\n `cp -a ${IN_BOX_OPENCODE_PLUGIN_PATH} /dst/config/plugins/agentbox-state.js && ` +\n `chown -R 1000:1000 /dst/config/plugins && echo SEEDED; } || true`,\n ]);\n return { seeded: stdout.includes('SEEDED') };\n } catch {\n return { seeded: false };\n }\n}\n\nexport interface OpencodeMountResult {\n /** Docker -v spec strings to append to runBox(extraVolumes). */\n extraVolumes: string[];\n /**\n * Env vars for the container: the fixed `OPENCODE_CONFIG_DIR` (relocates the\n * config dir into the volume) plus any forwarded provider keys set on the host.\n */\n env: Record<string, string>;\n volumeName: string;\n}\n\n// Provider API keys forwarded from the host's `process.env` into the box.\n// OpenCode's primary auth is the synced `auth.json`; these are a fallback /\n// supplement (OpenCode \"loads keys from environment variables at startup\").\n// Both Google key names are forwarded: `opencode auth list` recognizes\n// `GEMINI_API_KEY`, but the underlying provider SDK reads\n// `GOOGLE_GENERATIVE_AI_API_KEY` at request time.\nexport const OPENCODE_FORWARDED_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'OPENAI_API_KEY',\n 'OPENROUTER_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_GENERATIVE_AI_API_KEY',\n 'GOOGLE_API_KEY',\n 'GROQ_API_KEY',\n] as const;\n\nexport function buildOpencodeMounts(\n spec: OpencodeConfigSpec,\n hostEnv: NodeJS.ProcessEnv,\n): OpencodeMountResult {\n // OPENCODE_CONFIG_DIR is a fixed box-internal path (relocates the config dir\n // into the volume). It is OpenCode-specific, so setting it box-global is\n // safe — unlike XDG_DATA_HOME, which would move every app's data dir.\n // XDG_STATE_HOME relocates OpenCode's state dir (model.json etc.) into the\n // volume too; it is generic, but the only state we read back is the\n // `opencode/` subdir, so other tools' state landing there is harmless.\n const env: Record<string, string> = {\n OPENCODE_CONFIG_DIR: CONTAINER_OPENCODE_CONFIG_DIR,\n XDG_STATE_HOME: CONTAINER_OPENCODE_STATE_HOME,\n };\n for (const k of OPENCODE_FORWARDED_ENV_KEYS) {\n const v = hostEnv[k];\n if (typeof v === 'string' && v.length > 0) env[k] = v;\n }\n return {\n extraVolumes: [`${spec.volume}:${CONTAINER_OPENCODE_DIR}`],\n env,\n volumeName: spec.volume,\n };\n}\n\nexport class OpencodeSessionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OpencodeSessionError';\n }\n}\n\nexport interface EnsureOpencodeInstalledResult {\n /**\n * True when opencode had to be installed just now — i.e. it was absent from\n * the box image. Happens for boxes created from a checkpoint image captured\n * before OpenCode support, or from an older base image.\n */\n installed: boolean;\n}\n\n/**\n * Make sure the `opencode` binary is on PATH inside the box. OpenCode is baked\n * into the current base image, but a box created from a checkpoint image (a\n * frozen snapshot) captured before OpenCode support — or from an older base\n * image — won't have it. In that case we `npm install -g opencode-ai` into the\n * box's writable layer (persists across stop/start, wiped on destroy), mirroring\n * how `--with-playwright` installs at create time.\n *\n * Fast no-op (one `command -v`) when opencode is already present. Throws\n * {@link OpencodeSessionError} when opencode is absent *and* the install fails.\n */\nexport async function ensureOpencodeInstalled(\n container: string,\n opts: { onProgress?: (line: string) => void } = {},\n): Promise<EnsureOpencodeInstalledResult> {\n const probe = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'sh', '-c', 'command -v opencode'],\n { reject: false },\n );\n if (probe.exitCode === 0) return { installed: false };\n\n opts.onProgress?.('installing opencode (absent from this box image)');\n const install = await execa(\n 'docker',\n ['exec', '--user', 'root', container, 'bash', '-lc', 'npm install -g opencode-ai 2>&1'],\n { reject: false },\n );\n if (install.exitCode !== 0) {\n throw new OpencodeSessionError(\n `opencode is not in this box's image and \\`npm install -g opencode-ai\\` failed ` +\n `(exit ${String(install.exitCode)}). This box was likely created from a ` +\n `checkpoint captured before OpenCode support — recapture the project checkpoint ` +\n `from a fresh box. Install output:\\n${(install.stdout ?? '').toString().slice(-600)}`,\n );\n }\n return { installed: true };\n}\n\nexport interface StartOpencodeSessionOptions {\n container: string;\n opencodeArgs: string[];\n sessionName?: string;\n}\n\n/**\n * Start a detached tmux session running the OpenCode TUI inside the container.\n * Survives client disconnects; reattach via {@link buildOpencodeAttachArgv}. The\n * shared {@link buildTmuxSessionArgs} remaps the prefix and hides the inner\n * status bar, exactly as for the claude/codex sessions.\n *\n * `OPENCODE_CONFIG_DIR` is already in the container env (set at `docker run -e`\n * by {@link buildOpencodeMounts}), so `docker exec` inherits it — only the\n * host-forwarded provider keys are re-passed here to pick up the host shell's\n * current values.\n */\nexport async function startOpencodeSession(opts: StartOpencodeSessionOptions): Promise<void> {\n const sessionName = opts.sessionName ?? DEFAULT_OPENCODE_SESSION;\n const cmd = ['opencode', ...opts.opencodeArgs].map(shQuote).join(' ');\n const term = process.env['TERM'] ?? 'xterm-256color';\n const envFlags: string[] = ['-e', `TERM=${term}`];\n for (const k of OPENCODE_FORWARDED_ENV_KEYS) {\n const v = process.env[k];\n if (typeof v === 'string' && v.length > 0) envFlags.push('-e', `${k}=${v}`);\n }\n const result = await execa(\n 'docker',\n [\n 'exec',\n ...envFlags,\n '--user',\n CONTAINER_USER,\n opts.container,\n 'tmux',\n 'new-session',\n '-d',\n '-s',\n sessionName,\n cmd,\n ...buildTmuxSessionArgs(sessionName),\n ],\n { reject: false },\n );\n if (result.exitCode === 0) return;\n const stderr = (result.stderr ?? '').toString();\n if (result.exitCode === 127 || /command not found|tmux: not found/i.test(stderr)) {\n throw new OpencodeSessionError(\n `tmux is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/opencode.*not found|exec: \"opencode\"/i.test(stderr)) {\n throw new OpencodeSessionError(\n `opencode is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n if (/duplicate session/i.test(stderr)) {\n throw new OpencodeSessionError(\n `a tmux session \"${sessionName}\" already exists in ${opts.container}; use \\`agentbox opencode attach\\` to reattach.`,\n );\n }\n throw new OpencodeSessionError(\n `failed to start opencode session in ${opts.container}: ${stderr.trim() || `exit ${String(result.exitCode)}`}`,\n );\n}\n\n/**\n * The `docker` argv that attaches an interactive terminal to a box's OpenCode\n * tmux session. Mirrors {@link import('./codex.js').buildCodexAttachArgv}.\n */\nexport function buildOpencodeAttachArgv(container: string, sessionName?: string): string[] {\n const name = sessionName ?? DEFAULT_OPENCODE_SESSION;\n return buildTermSafeTmuxExec({\n container,\n user: CONTAINER_USER,\n tmuxScript: 'exec tmux attach -t \"$1\"',\n positionals: [name],\n });\n}\n\n/**\n * The `docker run` argv for an interactive `opencode auth login` in a throwaway\n * container. Mounts the opencode-config volume so the written `auth.json`\n * persists, and sets `OPENCODE_CONFIG_DIR` so config writes land in the volume\n * too. `opencode auth login` is interactive (provider picker); `extraArgs` are\n * appended verbatim (e.g. `['--provider', 'anthropic']`).\n *\n * `DISPLAY` is blanked for the same reason as the claude/codex login: the image\n * bakes `DISPLAY=:1` (a VNC X server) and opencode must not try to open a\n * browser there — forcing the terminal URL/paste-code flow.\n */\nexport function buildOpencodeLoginRunArgv(opts: {\n volume: string;\n image: string;\n extraArgs: string[];\n}): string[] {\n const term = process.env['TERM'] ?? 'xterm-256color';\n return [\n 'run',\n '-it',\n '--rm',\n '-e',\n `TERM=${term}`,\n '-e',\n 'DISPLAY=',\n '-e',\n `OPENCODE_CONFIG_DIR=${CONTAINER_OPENCODE_CONFIG_DIR}`,\n '-e',\n `XDG_STATE_HOME=${CONTAINER_OPENCODE_STATE_HOME}`,\n '-v',\n `${opts.volume}:${CONTAINER_OPENCODE_DIR}`,\n '--user',\n CONTAINER_USER,\n opts.image,\n 'opencode',\n 'auth',\n 'login',\n ...opts.extraArgs,\n ];\n}\n\n/**\n * Run an interactive docker argv (from {@link buildOpencodeLoginRunArgv}) with\n * the user's terminal attached. Returns the exit code; a null status is\n * reported as 1.\n */\nexport function runInteractiveOpencodeLogin(dockerArgv: string[]): { exitCode: number } {\n const child = spawnSync('docker', dockerArgv, { stdio: 'inherit' });\n return { exitCode: child.status ?? 1 };\n}\n\n/**\n * True when the opencode-config volume already holds an `auth.json` (at the\n * data-dir root). Used to skip the first-run sign-in offer when an earlier box\n * / `agentbox opencode login` already authenticated.\n */\nexport async function volumeHasOpencodeAuth(volume: string, image: string): Promise<boolean> {\n const res = await execa(\n 'docker',\n ['run', '--rm', '-v', `${volume}:/dst`, image, 'sh', '-c', 'test -e /dst/auth.json'],\n { reject: false },\n );\n return res.exitCode === 0;\n}\n\nexport interface OpencodeSessionInfo {\n running: boolean;\n sessionName: string;\n /** ISO-8601 timestamp from tmux's `#{session_created}`, or null when not running. */\n startedAt: string | null;\n}\n\n/**\n * Best-effort: returns `{ running: false, …, startedAt: null }` for any\n * non-zero exit from `tmux has-session`. Mirrors `codexSessionInfo`.\n */\nexport async function opencodeSessionInfo(\n container: string,\n sessionName?: string,\n): Promise<OpencodeSessionInfo> {\n const name = sessionName ?? DEFAULT_OPENCODE_SESSION;\n const has = await execa(\n 'docker',\n ['exec', '--user', CONTAINER_USER, container, 'tmux', 'has-session', '-t', name],\n { reject: false },\n );\n if (has.exitCode !== 0) {\n return { running: false, sessionName: name, startedAt: null };\n }\n const ts = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n CONTAINER_USER,\n container,\n 'tmux',\n 'display-message',\n '-p',\n '-t',\n name,\n '#{session_created}',\n ],\n { reject: false },\n );\n let startedAt: string | null = null;\n if (ts.exitCode === 0) {\n const secs = Number.parseInt((ts.stdout ?? '').trim(), 10);\n if (Number.isFinite(secs) && secs > 0) startedAt = new Date(secs * 1000).toISOString();\n }\n return { running: true, sessionName: name, startedAt };\n}\n\nexport interface PullOpencodeResult {\n /** Volume items copied to the host (or, in dry-run, that would be copied). */\n newItems: string[];\n}\n\nexport interface PullOpencodeOptions {\n /** Image for the throwaway helper container; use the box's image. */\n image: string;\n /** When true, compute the delta but write nothing. */\n dryRun?: boolean;\n}\n\n/**\n * Reverse of {@link ensureOpencodeVolume}: pull box-side OpenCode config/auth\n * from the volume back to the host. Additive only — an item already present on\n * the host is never overwritten. The box need not be running (we read the\n * *volume* via a throwaway helper container). `auth.json` lands in the host's\n * `~/.local/share/opencode`; config items in `~/.config/opencode`.\n */\nexport async function pullOpencodeConfig(\n spec: OpencodeConfigSpec,\n opts: PullOpencodeOptions,\n): Promise<PullOpencodeResult> {\n const hostData = join(homedir(), '.local', 'share', 'opencode');\n const hostConfig = join(homedir(), '.config', 'opencode');\n\n // Inventory: data items at the volume root, config items under `config/`.\n const inv = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/src:ro`,\n opts.image,\n 'sh',\n '-c',\n `for f in ${OPENCODE_PULL_DATA_ITEMS.join(' ')}; do [ -e \"/src/$f\" ] && echo \"data $f\"; done;` +\n ` for f in ${OPENCODE_PULL_CONFIG_ITEMS.join(' ')}; do [ -e \"/src/config/$f\" ] && echo \"config $f\"; done;` +\n ' true',\n ],\n { reject: false },\n );\n if (inv.exitCode !== 0) {\n throw new OpencodeSessionError(\n `failed to read opencode-config volume ${spec.volume}: ${(inv.stderr ?? '').toString().trim() || `exit ${String(inv.exitCode)}`}`,\n );\n }\n\n // Volume items not already on the host (additive — never overwrite).\n const newItems: Array<{ label: string; src: string; hostDst: 'data' | 'config'; name: string }> =\n [];\n for (const line of (inv.stdout ?? '').split('\\n')) {\n const [group, name] = line.trim().split(/\\s+/, 2);\n if (!name || (group !== 'data' && group !== 'config')) continue;\n const hostBase = group === 'data' ? hostData : hostConfig;\n if (await pathExists(join(hostBase, name))) continue;\n newItems.push({\n label: group === 'data' ? name : `config/${name}`,\n src: group === 'data' ? `/src/${name}` : `/src/config/${name}`,\n hostDst: group,\n name,\n });\n }\n\n if (opts.dryRun || newItems.length === 0) {\n return { newItems: newItems.map((i) => i.label) };\n }\n\n // Copy each new item from the volume into the matching host dir. `--user 0`\n // so root can read uid-1000 files; chown the result back to the host user.\n const uid = process.getuid?.() ?? 0;\n const gid = process.getgid?.() ?? 0;\n const cmds = newItems.map(\n (i) => `cp -a '${i.src}' '${i.hostDst === 'data' ? '/dst-data' : '/dst-config'}/${i.name}'`,\n );\n const apply = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${spec.volume}:/src:ro`,\n '-v',\n `${hostData}:/dst-data`,\n '-v',\n `${hostConfig}:/dst-config`,\n opts.image,\n 'sh',\n '-c',\n `mkdir -p /dst-data /dst-config && ${cmds.join(' && ')}` +\n ` && chown -R ${String(uid)}:${String(gid)} /dst-data /dst-config`,\n ],\n { reject: false },\n );\n if (apply.exitCode !== 0) {\n throw new OpencodeSessionError(\n `failed to copy opencode config from ${spec.volume}: ${(apply.stderr ?? '').toString().trim() || `exit ${String(apply.exitCode)}`}`,\n );\n }\n return { newItems: newItems.map((i) => i.label) };\n}\n","import { execa } from 'execa';\nimport type { GitWorktreeRecord } from '@agentbox/core';\nimport { execInBox } from '../docker.js';\nimport type { DetectedGitRepo } from '../git-worktree.js';\nimport { GitWorktreeError } from '../git-worktree.js';\n// The box-wins classifier + the resync orchestration moved to the provider-\n// neutral git/workspace concern in @agentbox/sandbox-core; the resync runs\n// against a `WorkspaceResyncPorts` this file supplies. The host-side ports are\n// the shared `makeHostGitPorts()` (host git is provider-neutral); only the\n// box-side ports are docker-specific here. `classifyUntrackedOverlay` is\n// re-exported so the docker test is untouched.\nimport { classifyUntrackedOverlay, makeHostGitPorts, resyncWorkspace } from '@agentbox/sandbox-core';\nimport type { RepoResyncResult, WorkspaceResyncPorts } from '@agentbox/core';\nexport { classifyUntrackedOverlay };\nexport type { RepoResyncResult };\n\n/**\n * Root for per-box git-worktree directories inside the container. Each box\n * registers its worktree at a unique subpath here so the host main repo's\n * worktree registry can list multiple concurrent boxes without path\n * collision; `/workspace` is then a symlink to the per-box dir. Lives under\n * the vscode user's home so it's writable without sudo. Exported for the\n * fs-safe path helper.\n */\nexport const WORKTREE_ROOT = '/home/vscode/.agentbox-worktrees';\n\n/** Sanitize a branch name into an FS-safe path segment. */\nexport function fsSafeBranch(branch: string): string {\n return branch.replace(/[^A-Za-z0-9._-]+/g, '_');\n}\n\n/**\n * Per-box per-repo path at which `git worktree add` registers the worktree\n * inside the container. The agent's working tree path stays `/workspace`\n * (root) / `/workspace/<sub>` (nested) via symlinks created after the add.\n * Unique because the branch name carries the box name, so the host main\n * repo never sees a path collision when multiple boxes from the same\n * project run concurrently.\n */\nexport function gitWorktreePathFor(branch: string): string {\n return `${WORKTREE_ROOT}/${fsSafeBranch(branch)}`;\n}\n\n/**\n * Per-repo carry-over captured on the host before the container starts. The\n * host runs the `git stash create` + `ls-files --others` here against the\n * user's main checkout, then `seedWorkspace` replays both inside the box.\n *\n * `stashSha` and the untracked tarball are stored in the shared `.git/`\n * object database (stash) and as a buffer (untracked) so the container can\n * apply them after `git worktree add` runs against the bind-mounted `.git`.\n */\nexport interface RepoCarryOver {\n repo: DetectedGitRepo;\n /**\n * Agent-visible container path of the worktree (`/workspace` for root,\n * `/workspace/<sub>` for nested). After seedWorkspace runs this is a\n * symlink to `gitWorktreePath`.\n */\n containerPath: string;\n /**\n * Real container path where git registered the worktree\n * (`/home/vscode/.agentbox-worktrees/<fsSafeBranch>`). Per-box unique, so\n * concurrent boxes from the same project don't collide in the host main\n * repo's worktree registry.\n */\n gitWorktreePath: string;\n /** Branch name to pass to `git worktree add -b`. */\n branch: string;\n /** Stash-commit SHA (`git stash create`); null when the host main was clean. */\n stashSha: string | null;\n /**\n * NUL-separated list of repo-relative untracked paths. We tar these up\n * host-side and pipe them in inside seedWorkspace. Empty when no untracked\n * files.\n */\n untrackedNul: string;\n /** Host dir to tar from (== repo.hostMainRepo, kept here so seedWorkspace doesn't need to know about the repo shape). */\n hostSource: string;\n /**\n * Reuse the existing branch `<branch>` instead of forking a fresh one:\n * `git worktree add <wt> <branch>` (no `-b`, no base ref). Set by the\n * `--use-branch` path for the root repo. When unset/false the worktree is\n * created with `-b <branch>` from `fromBranch ?? HEAD` (the default fork).\n */\n reuseBranch?: boolean;\n}\n\n/**\n * Collect host-side state for each detected repo so it can be replayed\n * inside the container by `seedWorkspace`. Pure of any docker calls — every\n * shell-out is host git.\n *\n * Branch picking is left to the caller (so it can be allocated before\n * `docker run` and recorded on the BoxRecord regardless of how the rest of\n * create proceeds).\n */\nexport async function collectRepoCarryOver(\n repo: DetectedGitRepo,\n branch: string,\n containerPath: string,\n gitWorktreePath: string,\n): Promise<RepoCarryOver> {\n // `stash create` writes a stash commit without touching the working tree or\n // stash list; empty output = clean. The commit lands in the host's `.git/`\n // object DB, which is bind-mounted into the container — so the in-box\n // worktree can `stash apply <sha>` against it.\n const stash = await execa('git', ['-C', repo.hostMainRepo, 'stash', 'create'], { reject: false });\n const stashSha = stash.exitCode === 0 ? stash.stdout.trim() || null : null;\n\n const untracked = await execa(\n 'git',\n ['-C', repo.hostMainRepo, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n const untrackedNul = untracked.exitCode === 0 ? untracked.stdout : '';\n\n return {\n repo,\n containerPath,\n gitWorktreePath,\n branch,\n stashSha,\n untrackedNul,\n hostSource: repo.hostMainRepo,\n };\n}\n\nexport interface SeedWorkspaceOptions {\n container: string;\n /** Repos with collected carry-over, in DAG order: root first, nested after. */\n repos: RepoCarryOver[];\n /**\n * Base ref each worktree is forked from. `undefined` (default) → `HEAD`.\n * Caller validates host-side; passed verbatim to `git worktree add`. Set\n * by `agentbox create --from-branch <ref>` so the box can start from main\n * (or any ref) instead of whatever the host happens to have checked out.\n */\n fromBranch?: string;\n onLog?: (line: string) => void;\n}\n\n/**\n * docker exec helper that throws GitWorktreeError on non-zero exit. `cwd`\n * defaults to `/` so callers that intentionally rebind `/workspace` (the\n * image's WORKDIR) don't get hit by \"chdir failed: no such file or directory\"\n * on the next exec.\n */\nasync function dexec(\n container: string,\n argv: string[],\n user: 'vscode' | 'root' = 'vscode',\n cwd: string = '/',\n): Promise<void> {\n const r = await execa(\n 'docker',\n ['exec', '-w', cwd, '--user', user, container, ...argv],\n { reject: false },\n );\n if (r.exitCode !== 0) {\n throw new GitWorktreeError(`${argv.join(' ')} failed: ${r.stderr || r.stdout}`);\n }\n}\n\n/**\n * Minimum shape `bindWorktrees` needs — keeps the helper independent of\n * the `RepoCarryOver` / `GitWorktreeRecord` types so both `seedWorkspace`\n * (after creation) and `startBox` (after `docker start`) can call it.\n */\nexport interface WorktreeBindSpec {\n kind: 'root' | 'nested';\n containerPath: string;\n gitWorktreePath: string;\n}\n\n/**\n * Apply the `/workspace` (and `/workspace/<sub>`) bind mounts that expose\n * each per-box git worktree at its canonical agent path.\n *\n * Idempotent for `startBox` re-runs: if the target is already a mountpoint\n * we unmount it first. Root bind first so the nested mount points (created\n * by the root worktree's `worktree add`) exist before we cover them.\n *\n * The mount runs as `root` because `mount(2)` requires `CAP_SYS_ADMIN` —\n * which we already grant the outer container for the in-box dockerd. The\n * bind itself respects file ownership on the source side (vscode-owned),\n * so subsequent in-container operations under `/workspace` work as vscode.\n */\n/**\n * Make the in-container parent directory of each bind-mounted `.git` owned by\n * `vscode`. Docker auto-creates the intermediate path for a bind mount\n * (e.g. `/Users/marco/Projects/Foo/` for a `.git` at `/Users/marco/Projects/Foo/.git`)\n * in the container's writable layer as `root:root 755`. The bind-mounted\n * `.git` itself keeps its host UIDs, but agents (turborepo, build caches,\n * etc.) often want to write *siblings* of `.git` at the project root —\n * `.turbo/`, `.next/`, scratch files — which fails as `vscode` if the parent\n * is root-owned. This flips just that parent dir's UID.\n *\n * NOT recursive on purpose: `chown -R` would descend into `.git` (the\n * bind-mount inode) and propagate ownership changes back to the host,\n * defeating the \"no host perms touched\" property.\n *\n * Best-effort: failures are logged, not thrown — the box still functions,\n * only sibling writes at the project root are affected.\n */\nexport async function chownGitBindParents(args: {\n container: string;\n hostMainRepos: string[];\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = args.onLog ?? (() => {});\n // Dedupe — nested-repo carry-overs can repeat hostMainRepo.\n const repos = Array.from(new Set(args.hostMainRepos));\n for (const repo of repos) {\n const result = await execInBox(args.container, ['chown', 'vscode:vscode', repo], {\n user: 'root',\n });\n if (result.exitCode === 0) {\n log(`chowned ${repo} to vscode:vscode (parent of bind-mounted .git)`);\n } else {\n const msg = (result.stderr || result.stdout || `exit ${result.exitCode}`).trim();\n log(`chown ${repo} failed (best-effort, ignoring): ${msg}`);\n }\n }\n}\n\nexport async function bindWorktrees(\n container: string,\n binds: WorktreeBindSpec[],\n onLog?: (line: string) => void,\n): Promise<void> {\n const log = onLog ?? (() => {});\n // Root first; nested mountpoints live inside the root worktree's tree so\n // the root bind has to be in place before we cover sub-paths.\n const ordered = [...binds].sort((a, b) =>\n a.kind === 'root' && b.kind !== 'root' ? -1 : a.kind !== 'root' && b.kind === 'root' ? 1 : 0,\n );\n for (const b of ordered) {\n // Best-effort unmount of any leftover bind at the target (idempotent for\n // startBox: container stop drops mounts, but a partial create might\n // leave one in place).\n await execa(\n 'docker',\n ['exec', '-w', '/', '--user', 'root', container, 'sh', '-c', `mountpoint -q ${b.containerPath} && umount ${b.containerPath} || true`],\n { reject: false },\n );\n // For nested: parent must exist. The root bind exposes the root\n // worktree's tracked tree, which typically contains <sub>/, but if the\n // root .gitignores it or the nested repo is in a fresh path, mkdir is\n // needed.\n if (b.kind === 'nested') {\n await dexec(container, ['mkdir', '-p', ctParent(b.containerPath)], 'root');\n await dexec(container, ['mkdir', '-p', b.containerPath], 'root');\n }\n await dexec(container, ['mount', '--bind', b.gitWorktreePath, b.containerPath], 'root');\n log(`bind-mounted ${b.containerPath} <- ${b.gitWorktreePath}`);\n }\n}\n\n/**\n * Best-effort host-side `git lfs fetch` of the LFS objects reachable from\n * `baseRef`, BEFORE the in-box `git worktree add` checkout smudges them.\n *\n * Why host-side: the box has no access to the host's git credentials (the\n * git-shim only relays push/pull/fetch/clone, and git-lfs uses its own HTTP\n * transfer), so an in-box smudge of an object that isn't cached yet would\n * reach the network unauthenticated and fail. The host *does* have creds, and\n * `.git/lfs/objects/` is part of the bind-mounted `.git/` shared with the box.\n * So we fetch here, the objects land in the shared store, and the in-box\n * checkout resolves every object from cache with zero box network or creds.\n *\n * Quiet and safe: we first probe `git lfs ls-files` so the overwhelmingly\n * common non-LFS repo does nothing and logs nothing. Any failure (no git-lfs\n * on the host, no `origin`, offline, private without creds) is logged and\n * swallowed, so create proceeds and the in-box checkout still resolves\n * whatever is already cached. Mirrors the host-side, best-effort style of\n * `collectRepoCarryOver`.\n */\nasync function prefetchHostLfs(\n hostMainRepo: string,\n baseRef: string,\n log: (line: string) => void,\n): Promise<void> {\n // Probe whether this repo tracks anything with LFS (ls-files defaults to\n // HEAD). Empty output or a non-zero exit (no git-lfs binary, not LFS) → no\n // work to do, and crucially no log noise on the common non-LFS path.\n const tracked = await execa('git', ['-C', hostMainRepo, 'lfs', 'ls-files', '-n'], {\n reject: false,\n });\n if (tracked.exitCode !== 0 || tracked.stdout.trim().length === 0) return;\n\n // `origin` matches the convention used by from-branch.ts; a repo with a\n // differently-named remote just falls through to the best-effort skip below.\n const remote = 'origin';\n const fetched = await execa('git', ['-C', hostMainRepo, 'lfs', 'fetch', remote, baseRef], {\n reject: false,\n });\n if (fetched.exitCode === 0) {\n log(`prefetched git-lfs objects for ${baseRef} into shared .git/lfs (host ${remote})`);\n } else {\n const msg = (fetched.stderr || fetched.stdout || `exit ${String(fetched.exitCode ?? '?')}`)\n .trim()\n .split('\\n')[0];\n log(`git-lfs prefetch for ${baseRef} skipped (best-effort, continuing): ${msg}`);\n }\n}\n\n/**\n * Materialize each per-box git worktree *inside* the container against the\n * bind-mounted `.git/`, then replay the host's uncommitted state (stash +\n * untracked) into it. Runs as `vscode` (the in-container user) so files in\n * /workspace are owned by uid 1000.\n *\n * Layout: every worktree is registered at a per-box unique path under\n * `WORKTREE_ROOT` (`/home/vscode/.agentbox-worktrees/<fsSafeBranch>`), then\n * a `mount --bind` exposes it at `/workspace` (and `/workspace/<sub>` for\n * nested repos). The uniqueness is load-bearing — the host main repo's\n * worktree registry is keyed by absolute path, so multiple concurrent\n * boxes from the same project must register at *different* paths. They\n * share the object DB (the bind-mounted `.git/`) but have independent\n * HEAD/index in their own `.git/worktrees/<subdir>`.\n *\n * The bind mount (not a symlink) is intentional: getcwd() / realpath() /\n * git rev-parse --show-toplevel / Node's process.cwd() all return\n * `/workspace`. A symlink would leak the per-box physical path everywhere\n * tools canonicalize. Cost: the mount is per-container-namespace and\n * doesn't survive `docker stop`, so `startBox` re-binds via\n * {@link bindWorktrees}. Host's `git worktree list` will show each box's\n * registered path as `/home/vscode/.agentbox-worktrees/...` (container-only\n * — host marks it `prunable`, which is harmless).\n */\nexport async function seedWorkspace(opts: SeedWorkspaceOptions): Promise<void> {\n const log = opts.onLog ?? (() => {});\n\n // Ensure the per-box worktree root exists. Idempotent — multiple boxes\n // can be created in parallel against the same image.\n await dexec(opts.container, ['mkdir', '-p', WORKTREE_ROOT]);\n\n // Phase 1: register each worktree at its per-box unique path.\n // `fromBranch` (when set) overrides the default `HEAD` base ref for the\n // *root* repo only — the CLI's `--from-branch <ref>` is resolved against\n // the user's primary repo, and a nested submodule/monorepo-sub-repo will\n // almost never carry that same ref. Applying it uniformly would fail\n // `git worktree add` for nested repos that don't have `<ref>`, aborting\n // box creation. Mirrors the cloud path's behavior in\n // `packages/sandbox-cloud/src/workspace-seed.ts` (which only forwards\n // `fromBranch` to the root clone).\n for (const r of opts.repos) {\n const main = r.repo.hostMainRepo;\n const wt = r.gitWorktreePath;\n // reuse: check out the existing branch directly (`git worktree add <wt>\n // <branch>`). Git refuses if the host already has it checked out — that\n // stderr is surfaced verbatim below. fork (default): create a fresh\n // branch with `-b` from `fromBranch ?? HEAD` (root only; nested → HEAD).\n const baseRef = r.repo.kind === 'root' ? (opts.fromBranch ?? 'HEAD') : 'HEAD';\n // Pull the checkout's LFS objects into the shared (bind-mounted) .git/lfs\n // cache host-side first, so the in-box smudge below never reaches the\n // network without the host's credentials. Best-effort; never aborts.\n await prefetchHostLfs(main, baseRef, log);\n const addArgs = r.reuseBranch\n ? ['worktree', 'add', wt, r.branch]\n : ['worktree', 'add', '-b', r.branch, wt, baseRef];\n const add = await execa(\n 'docker',\n ['exec', '--user', 'vscode', opts.container, 'git', '-C', main, ...addArgs],\n { reject: false },\n );\n if (add.exitCode !== 0) {\n throw new GitWorktreeError(\n `git worktree add ${wt} (branch ${r.branch}) failed: ${add.stderr || add.stdout}`,\n );\n }\n log(`worktree ${wt} on branch ${r.branch} (host main ${main})`);\n\n // Boxes don't carry the user's signing keys, so commit.gpgsign=true on\n // the host would make every in-box `git commit` fail. Enable per-worktree\n // config on the main repo, then disable signing on just this worktree.\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n main,\n 'config',\n 'extensions.worktreeConfig',\n 'true',\n ],\n { reject: false },\n );\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n wt,\n 'config',\n '--worktree',\n 'commit.gpgsign',\n 'false',\n ],\n { reject: false },\n );\n }\n\n // Phase 2: bind each worktree onto its agent-visible /workspace path.\n await bindWorktrees(\n opts.container,\n opts.repos.map((r) => ({\n kind: r.repo.kind,\n containerPath: r.containerPath,\n gitWorktreePath: r.gitWorktreePath,\n })),\n log,\n );\n\n // Phase 3: replay host carry-over into each worktree (via the\n // /workspace[*] symlinks, so the agent sees the changes at the canonical\n // paths it expects).\n for (const r of opts.repos) {\n const ct = r.containerPath;\n if (r.stashSha) {\n const withIndex = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n ct,\n 'stash',\n 'apply',\n '--index',\n r.stashSha,\n ],\n { reject: false },\n );\n if (withIndex.exitCode !== 0) {\n const noIndex = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'git',\n '-C',\n ct,\n 'stash',\n 'apply',\n r.stashSha,\n ],\n { reject: false },\n );\n if (noIndex.exitCode !== 0) {\n log(\n `warning: stash apply failed in ${ct} (${withIndex.stderr || withIndex.stdout || 'no message'})`,\n );\n } else {\n log(`applied tracked changes (without index — staged state lost) in ${ct}`);\n }\n } else {\n log(`applied tracked changes from host main into ${ct}`);\n }\n }\n if (r.untrackedNul.length > 0) {\n const tarOut = await execa('tar', ['-C', r.hostSource, '--null', '-T', '-', '-cf', '-'], {\n input: r.untrackedNul.replace(/\\0$/, ''),\n encoding: 'buffer',\n reject: false,\n });\n if (tarOut.exitCode !== 0) {\n log(`warning: tar of untracked files for ${r.repo.hostMainRepo} failed: ${tarOut.stderr}`);\n continue;\n }\n const tarIn = await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', opts.container, 'tar', '-C', ct, '-xf', '-'],\n { input: tarOut.stdout as Buffer, reject: false },\n );\n if (tarIn.exitCode !== 0) {\n log(`warning: untracked-file copy into ${ct} failed: ${tarIn.stderr}`);\n } else {\n const count = r.untrackedNul.split('\\0').filter((s) => s.length > 0).length;\n log(`copied ${String(count)} untracked file(s) into ${ct}`);\n }\n }\n }\n}\n\n/**\n * One restored worktree's regeneration plan. A docker checkpoint bakes the\n * *source* box's branch + worktree path into the manifest, but neither its\n * `.git` worktree metadata (host-side, bind-mounted) nor its branch ref\n * (also host-side) is captured in the image. Restoring those verbatim is\n * unsafe — see {@link regenerateRestoredWorktrees}.\n */\nexport interface RestoreWorktreePlan {\n hostMainRepo: string;\n kind: 'root' | 'nested';\n /** Container path the baked content currently sits at (manifest's gitWorktreePath). */\n bakedGitWorktreePath: string;\n /** Fresh, per-box-unique branch (allocated host-side via pickFreshBranch). */\n freshBranch: string;\n /** Fresh, per-box-unique worktree path the baked content is renamed to. */\n freshGitWorktreePath: string;\n}\n\n/**\n * Re-attach each baked `/workspace` worktree to a FRESH per-box branch when\n * restoring from a checkpoint.\n *\n * A docker checkpoint bakes the source box's worktree *content* into the image\n * but not its `.git` worktree metadata (that lived on the host, bind-mounted)\n * nor its branch ref (also host-side). The manifest only records the source\n * branch + path. Reusing them verbatim is the shared-worktree bug: every box\n * from one checkpoint would share a single branch + index (commits clobber\n * each other; `index.lock` fights), and once the source box was destroyed its\n * host worktree metadata is pruned, leaving the baked `/workspace/.git` gitfile\n * dangling (\"fatal: not a git repository\").\n *\n * So per worktree we: rename the baked content dir to a fresh unique path (an\n * O(1) rename within the container's writable layer — no copy), mint a fresh\n * branch at the host's base ref, author fresh worktree metadata under the\n * bind-mounted host `.git/worktrees/`, repoint the worktree's gitfile at it,\n * and rebuild the index from the branch tip (working tree untouched, so the\n * baked deviations survive as uncommitted changes). Mirrors the manual repair\n * documented for the shared-worktree bug.\n *\n * Runs as `vscode` against the bind-mounted host `.git` (same as seedWorkspace).\n */\nexport async function regenerateRestoredWorktrees(opts: {\n container: string;\n plans: RestoreWorktreePlan[];\n /** Base ref for the *root* worktree's fresh branch (default HEAD). Nested → HEAD. */\n fromBranch?: string;\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = opts.onLog ?? (() => {});\n // Positional args ($1..$6) so paths/branches with odd chars never re-parse.\n const script = [\n 'set -e',\n 'OLD=\"$1\"; NEW=\"$2\"; MAIN=\"$3\"; BR=\"$4\"; BASE=\"$5\"; META=\"$6\"',\n // Rename baked content to the fresh unique path (rename, not copy).\n '[ \"$OLD\" = \"$NEW\" ] || mv \"$OLD\" \"$NEW\"',\n // Fresh branch at the base ref; -f is safe because pickFreshBranch already\n // guaranteed BR is unused on the host.\n 'git -C \"$MAIN\" branch -f \"$BR\" \"$BASE\"',\n // Author worktree metadata under the bind-mounted host .git.\n 'mkdir -p \"$META\"',\n 'printf \"../..\\\\n\" > \"$META/commondir\"',\n 'printf \"%s\\\\n\" \"$NEW/.git\" > \"$META/gitdir\"',\n 'printf \"ref: refs/heads/%s\\\\n\" \"$BR\" > \"$META/HEAD\"',\n // Point the worktree's gitfile at the fresh metadata dir.\n 'printf \"gitdir: %s\\\\n\" \"$META\" > \"$NEW/.git\"',\n // Reset tracked files to the fork base so the box starts CLEAN at the host\n // base ref — same git state as a fresh create. The baked tree was captured\n // on the source box's (possibly divergent/older) branch, so its tracked\n // deviations are staleness, not work; resetting drops that noise. The\n // gitignored warm artifacts (node_modules, .next, build caches) are\n // untouched by reset --hard — that warm state is the checkpoint's value.\n 'git -C \"$NEW\" reset -q --hard HEAD',\n // Boxes carry no signing key; mirror seedWorkspace's per-worktree config so\n // host commit.gpgsign=true doesn't break in-box commits. extensions.\n // worktreeConfig writes the SHARED (bind-mounted) .git/config, so concurrent\n // boxes race on .git/config.lock — retry through the contention rather than\n // aborting (best-effort, like seedWorkspace). The per-worktree gpgsign write\n // needs the extension enabled first, so it follows the retry.\n 'set +e',\n 'for i in 1 2 3 4 5 6 7 8; do git -C \"$MAIN\" config extensions.worktreeConfig true && break; sleep 0.25; done',\n 'git -C \"$NEW\" config --worktree commit.gpgsign false',\n 'exit 0',\n ].join('\\n');\n for (const p of opts.plans) {\n const baseRef = p.kind === 'root' ? (opts.fromBranch ?? 'HEAD') : 'HEAD';\n // Same as seedWorkspace: the restore script's `reset --hard HEAD` smudges\n // LFS files in-box, so pull their objects into the shared .git/lfs\n // host-side first. Best-effort; never aborts the restore.\n await prefetchHostLfs(p.hostMainRepo, baseRef, log);\n const metaDir = `${p.hostMainRepo}/.git/worktrees/${fsSafeBranch(p.freshBranch)}`;\n const r = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'vscode',\n opts.container,\n 'bash',\n '-c',\n script,\n 'bash',\n p.bakedGitWorktreePath,\n p.freshGitWorktreePath,\n p.hostMainRepo,\n p.freshBranch,\n baseRef,\n metaDir,\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) {\n throw new GitWorktreeError(\n `regenerate worktree for ${p.freshBranch} failed: ${r.stderr || r.stdout}`,\n );\n }\n log(\n `restored worktree ${p.freshGitWorktreePath} on fresh branch ${p.freshBranch} (base ${baseRef})`,\n );\n }\n}\n\n/**\n * Tar-pipe a host source dir into the container's /workspace. Used for the\n * no-git case (no detected repos), and for the `--host-snapshot` flow where\n * the source is the APFS clone instead of the live workspace.\n *\n * Runs as uid:gid 1000:1000 so extracted files are owned by `vscode` (the\n * in-container user) — same convention as `copyHostEnvFilesToBox`.\n */\nexport async function seedWorkspaceFromDir(opts: {\n container: string;\n hostSource: string;\n onLog?: (line: string) => void;\n}): Promise<void> {\n const log = opts.onLog ?? (() => {});\n const tarOut = await execa('tar', ['-C', opts.hostSource, '-cf', '-', '.'], {\n encoding: 'buffer',\n reject: false,\n });\n if (tarOut.exitCode !== 0) {\n throw new GitWorktreeError(`tar of ${opts.hostSource} failed: ${tarOut.stderr}`);\n }\n const tarIn = await execa(\n 'docker',\n ['exec', '-i', '--user', '1000:1000', opts.container, 'tar', '-C', '/workspace', '-xf', '-'],\n { input: tarOut.stdout as Buffer, reject: false },\n );\n if (tarIn.exitCode !== 0) {\n throw new GitWorktreeError(`tar extract into /workspace failed: ${tarIn.stderr}`);\n }\n log(`seeded /workspace from ${opts.hostSource}`);\n}\n\n/**\n * Remove an in-container worktree from the host's main repo's worktree\n * registry. Called from `destroyBox` per registered worktree. The registered\n * path (`gitWorktreePath`) was a container-only path (under `WORKTREE_ROOT`),\n * so `git worktree remove` will see it as missing and we go straight to\n * `worktree prune` to drop the registry entry. Best-effort throughout.\n */\nexport async function removeInBoxWorktree(args: {\n hostMainRepo: string;\n gitWorktreePath: string;\n}): Promise<void> {\n const remove = await execa(\n 'git',\n ['-C', args.hostMainRepo, 'worktree', 'remove', '--force', args.gitWorktreePath],\n { reject: false },\n );\n if (remove.exitCode === 0) return;\n await execa('git', ['-C', args.hostMainRepo, 'worktree', 'prune'], { reject: false });\n}\n\nfunction ctParent(p: string): string {\n const i = p.lastIndexOf('/');\n return i <= 0 ? '/' : p.slice(0, i);\n}\n\nexport interface ResyncWorkspaceOptions {\n container: string;\n /** The box's recorded worktrees (root + nested). */\n worktrees: GitWorktreeRecord[];\n onLog?: (line: string) => void;\n}\n\n/** Split a `-z` (NUL-delimited) git output into non-empty entries. */\nfunction splitNul(s: string): string[] {\n return s.split('\\0').filter((p) => p.length > 0);\n}\n\n/**\n * Docker implementation of the workspace-resync ports (`@agentbox/core`): the\n * host-side git probes are the shared, provider-neutral `makeHostGitPorts()`\n * (host git is the host's own repo either way); the box-side ports run via\n * `docker exec --user vscode`. Every method reproduces the pre-refactor\n * `resyncWorkspaceFromHost` command byte-for-byte — the docker `.git/` bind\n * mount means the host branch ref is already present in the box (no fetch\n * needed).\n */\nfunction makeDockerResyncPorts(container: string): WorkspaceResyncPorts {\n return {\n ...makeHostGitPorts(),\n async boxGit(ct, args) {\n return execInBox(container, ['git', '-C', ct, ...args], { user: 'vscode' });\n },\n async probeUntrackedTokens(ct, relPaths) {\n // For each existing path emit `<token>\\0<path>\\0`: the file's sha256 (fed\n // on stdin so filenames with spaces/newlines are safe), or `-` for a\n // non-regular file. `ct` is $1 (never interpolated) so a worktree path\n // with spaces is safe; `bash` for `read -d ''` (NUL), which dash lacks.\n const probe = await execa(\n 'docker',\n [\n 'exec',\n '-i',\n '--user',\n 'vscode',\n container,\n 'bash',\n '-c',\n 'cd \"$1\" && while IFS= read -r -d \"\" f; do ' +\n 'if [ -f \"$f\" ] && [ ! -L \"$f\" ]; then ' +\n 'printf \"%s\\\\0%s\\\\0\" \"$(sha256sum < \"$f\" | cut -d\" \" -f1)\" \"$f\"; ' +\n 'elif [ -e \"$f\" ]; then printf \"%s\\\\0%s\\\\0\" \"-\" \"$f\"; fi; done',\n 'bash',\n ct,\n ],\n { input: relPaths.join('\\0'), reject: false },\n );\n const boxTokens = new Map<string, string>();\n if (probe.exitCode === 0) {\n const flat = splitNul(probe.stdout);\n for (let i = 0; i + 1 < flat.length; i += 2) {\n const token = flat[i];\n const path = flat[i + 1];\n if (token !== undefined && path !== undefined) boxTokens.set(path, token);\n }\n }\n return boxTokens;\n },\n async applyTarToBox(ct, tar) {\n await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', container, 'tar', '-C', ct, '-xf', '-'],\n { input: tar, reject: false },\n );\n },\n };\n}\n\n/**\n * Resync each box worktree with the host's current state (merge the host branch\n * into the box branch, overlay host uncommitted + untracked, box wins on\n * conflict). Thin docker wrapper: the provider-neutral `resyncWorkspace` concern\n * (`@agentbox/sandbox-core`) drives the orchestration through the docker resync\n * ports. Best-effort throughout — a failed step is logged and skipped rather\n * than aborting the box start.\n */\nexport async function resyncWorkspaceFromHost(\n opts: ResyncWorkspaceOptions,\n): Promise<RepoResyncResult[]> {\n return resyncWorkspace(opts.worktrees, makeDockerResyncPorts(opts.container), opts.onLog);\n}\n","// Host-side git-repo detection is provider-neutral (cloud boxes also seed from\n// git) and lives in @agentbox/sandbox-core. Re-exported here so existing\n// `@agentbox/sandbox-docker` consumers are unchanged.\nexport {\n detectGitRepos,\n GitWorktreeError,\n pickFreshBranch,\n type DetectedGitRepo,\n} from '@agentbox/sandbox-core';\n","import { mkdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport { execa } from 'execa';\nimport { ConfigError, loadConfig } from '@agentbox/ctl';\nimport { makeSyncContext, syncAgentboxSshConfig } from '@agentbox/sandbox-core';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { makeDockerSync } from './sync/docker-sync.js';\nimport { buildClaudeMounts, resolveClaudeVolume } from './sync/agents/claude.js';\nimport {\n buildCodexMounts,\n resolveCodexVolume,\n type CodexMountResult,\n} from './sync/agents/codex.js';\nimport { buildAgentsMounts, resolveAgentsVolume, type AgentsMountResult } from './sync/agents/skills.js';\nimport {\n buildOpencodeMounts,\n resolveOpencodeVolume,\n type OpencodeMountResult,\n} from './sync/agents/opencode.js';\nimport {\n type BoxLimitSpec,\n containerExists,\n dockerInfo,\n dockerStorageDriver,\n ensureVolume,\n publishedHostPort,\n runBox,\n} from './docker.js';\nimport { dockerVolumeName, launchDockerdDaemon } from './dockerd.js';\nimport { generateVncPassword, launchVncDaemon, VNC_CONTAINER_PORT } from './vnc.js';\nimport { setUpBoxSshd, SSH_CONTAINER_PORT } from './ssh.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\nimport { detectGitRepos, pickFreshBranch } from './git-worktree.js';\nimport {\n bindWorktrees,\n chownGitBindParents,\n collectRepoCarryOver,\n gitWorktreePathFor,\n regenerateRestoredWorktrees,\n removeInBoxWorktree,\n seedWorkspace,\n seedWorkspaceFromDir,\n type RepoCarryOver,\n type RestoreWorktreePlan,\n} from './sync/in-box-git.js';\nimport {\n CONTAINER_EXPORT_MERGED,\n DEFAULT_ENV_PATTERNS,\n boxRunDirFor,\n copyHostFilesToBox,\n detectEngine,\n} from './sync/host-export.js';\nimport {\n detectPortless,\n portlessAlias,\n portlessBrowserEnv,\n portlessGetUrl,\n portlessStartHint,\n resolvePortlessHostStateDir,\n} from './portless.js';\nimport { DEFAULT_BOX_IMAGE, ensureImage } from './image.js';\nimport {\n readState,\n recordBox,\n removeBoxRecord,\n reserveProjectIndex,\n type BoxRecord,\n type GitWorktreeRecord,\n} from './state.js';\nimport { generateBoxId, type ResolvedCarryEntry, type ResyncResult } from '@agentbox/core';\nimport { createSnapshot, snapshotPathFor } from './snapshot.js';\nimport { resolveCheckpoint } from './checkpoint.js';\nimport {\n computeDockerContextFingerprint,\n readPreparedDockerState,\n} from './prepared-state.js';\nimport { launchCtlDaemon } from './ctl.js';\nimport { writeBoxEnvFile } from './box-env.js';\nimport { ensureHomeOwnedByVscode } from './home-ownership.js';\nimport {\n ensureRelay,\n generateRelayToken,\n registerBoxWithRelay,\n rehydrateRelayRegistry,\n} from './relay.js';\nimport {\n buildIdeMounts,\n cursorServerVolumeName,\n ensureIdeVolumes,\n repairIdeOwnership,\n vscodeServerVolumeName,\n} from './vscode.js';\n\nexport interface CreateBoxOptions {\n /**\n * `box.credentialSync` resolved by the caller (CLI flag override included).\n * Undefined → fall back to the local config load below.\n */\n credentialSync?: boolean;\n workspacePath: string;\n name?: string;\n /**\n * Take a `cp -c` APFS clone of the host workspace into\n * `~/.agentbox/snapshots/<id>/` before seeding `/workspace`. Stabilizes the\n * source of the tar pipe in the non-git case (and the untracked-file\n * pipe in the git case) against host edits during create. Effectively a\n * no-op when a git worktree is detected — the worktree's tracked content\n * comes from `.git`, not from a workspace copy.\n */\n useSnapshot: boolean;\n /**\n * Start the box from a project checkpoint (the `--snapshot <ref>` path).\n * Resolved against `projectRoot` (or `workspacePath` when unset). The\n * checkpoint is a local Docker *image* tag now; the box is created with\n * `docker run <ckpt-image>` and inherits a populated `/workspace`. No\n * `seedWorkspace` runs in this path.\n */\n checkpointRef?: string;\n /**\n * Base ref the box's per-box branch is forked from (default: HEAD). Caller\n * is responsible for validation + any required fetch beforehand. Accepts\n * any ref `git rev-parse` resolves; passed verbatim to `git worktree add`.\n */\n fromBranch?: string;\n /**\n * Reuse an existing branch (root repo only) instead of forking a fresh\n * `agentbox/<name>`. The root worktree is created with `git worktree add\n * <wt> <branch>` (no `-b`), so git fails fast if the host already has\n * `<useBranch>` checked out. No host stash / untracked carry-over is\n * replayed — the box gets the branch's committed tip. Nested repos keep\n * their per-box `agentbox/<name>--<sub>` branches. Mutually exclusive with\n * `fromBranch` (enforced by the CLI).\n */\n useBranch?: string;\n /**\n * When starting from a checkpoint, merge the host's current branch into the\n * restored worktree and overlay the host's uncommitted/untracked changes\n * (box wins on conflict). Defaults to true. No effect on a non-checkpoint\n * fresh create (which already forks from HEAD + carry-over).\n */\n resyncOnStart?: boolean;\n image?: string;\n /** Try the registry before building the base image. Defaults to true. */\n allowPull?: boolean;\n /** Registry repo for the base-image pull. Defaults to `BOX_IMAGE_REGISTRY`; empty disables. */\n imageRegistry?: string;\n onLog?: (line: string) => void;\n /**\n * Claude Code config volume. When omitted, defaults to `{ isolate: false }` —\n * every box mounts the shared `agentbox-claude-config` volume at\n * /home/vscode/.claude so auth / skills / plugins persist across boxes.\n */\n claudeConfig?: { isolate: boolean };\n /** Extra env vars forwarded to the container (merged on top of claude env forwarding). */\n claudeEnv?: Record<string, string>;\n /**\n * Codex CLI config volume. When provided (i.e. `agentbox codex`), the box\n * always mounts a synced `agentbox-codex-config` volume at /home/vscode/.codex.\n * When omitted, `createBox` still mounts it *if the host has a `~/.codex`*\n * (so a plain `agentbox create` for a Codex user gets a working box) — see\n * the codex block below. `isolate: true` opts into a per-box volume.\n */\n codexConfig?: { isolate: boolean };\n /**\n * OpenCode CLI config volume. When provided (i.e. `agentbox opencode`), the\n * box always mounts a synced `agentbox-opencode-config` volume. When omitted,\n * `createBox` still mounts it *if the host uses OpenCode* (`~/.config/opencode`\n * or `~/.local/share/opencode` exists). `isolate: true` opts into a per-box\n * volume. See the opencode block below.\n */\n opencodeConfig?: { isolate: boolean };\n /**\n * When true, run `npm install -g @playwright/cli@latest` inside the box after\n * `/workspace` is seeded. agent-browser is always installed in the image;\n * this flag adds the Playwright CLI on top for boxes that need it.\n */\n withPlaywright?: boolean;\n /**\n * When true, copy the host's env/config files (DEFAULT_ENV_PATTERNS basename\n * globs — `.env*`, `secrets.toml`, `agentbox.yaml`, ...) into the box's\n * /workspace after seeding, bypassing gitignore. The reverse of `pull env`.\n * One-shot at create time; the files persist in the container's writable\n * layer across pause/stop/start.\n */\n withEnv?: boolean;\n /**\n * Explicit relative-path file list to copy from `workspacePath` into the\n * box's /workspace after seeding (no glob expansion, no scan — the list is\n * pre-vetted, e.g. picked by the wizard's multiselect). Independent of\n * `withEnv`: if both are set, both run (idempotent on overlapping files).\n * One-shot at create time; persists across pause/stop/start.\n */\n envFilesToImport?: string[];\n /**\n * Pre-approved host→box file copies from `agentbox.yaml`'s `carry:` block.\n * Resolved + user-approved by the apps/cli layer (resolveCarry + the carry\n * prompt) before being threaded in here. Each entry is copied to its\n * declared `absDest` (NOT under /workspace) after env-file imports and\n * before the supervisor starts, so the first declared task can already\n * read e.g. `~/.agentbox/secrets.env`. Empty / undefined → no-op.\n */\n carry?: ResolvedCarryEntry[];\n /**\n * VNC stack (Xvnc on :1 + websockify serving noVNC on container :6080).\n * Defaults to enabled. The CLI exposes `--no-vnc` for opt-out. Disabling\n * skips port mapping + password generation + the in-container supervisor\n * launch; the apt-installed binaries stay in the image but are unused.\n */\n vnc?: { enabled: boolean };\n /**\n * Docker-in-Docker. Always-on (the in-box dockerd is part of the box\n * surface). When `sharedCache` is true the per-box `agentbox-docker-<id>`\n * volume is replaced with the shared `agentbox-docker-cache` volume — image\n * layers persist across boxes (and `destroy`/`prune` won't remove it).\n */\n docker?: { sharedCache: boolean };\n /**\n * When true, register a Portless route (`portless alias <box-name> <webPort>`)\n * so the box web app is reachable at `https://<box-name>.localhost`. Only\n * acts on non-OrbStack engines (OrbStack already has `.orb.local`) and only\n * when Portless is installed on the host — best-effort, never fails create.\n */\n portless?: boolean;\n /**\n * Override for the host Portless state directory shared into the box (the\n * `portless.stateDir` config key). When unset, `createBox` resolves Portless's\n * own default. Only consulted when `portless` is true.\n */\n portlessStateDir?: string;\n /**\n * Absolute host path of the cwd's project at create time. When provided,\n * `createBox` stamps `projectRoot` + an allocated `projectIndex` on the\n * BoxRecord so the CLI can auto-pick / resolve by index. The CLI computes\n * this via `findProjectRoot(workspacePath)` from `@agentbox/config`; this\n * package stays free of the config dep. Omit for unowned boxes created\n * directly via the programmatic API.\n */\n projectRoot?: string;\n /**\n * Container resource ceilings (engine-agnostic: bytes / fractional cpus /\n * pid count / raw disk size string). Absent fields = unlimited. `disk` is\n * best-effort: dropped (with a warning via `onLog`) when the engine's\n * storage driver can't enforce `--storage-opt size=` (overlay2 / macOS).\n */\n limits?: BoxLimitSpec;\n}\n\nexport interface CreatedBox {\n record: BoxRecord;\n imageBuilt: boolean;\n /** Conflicts from the on-create resync (checkpoint-restore path). Absent when no resync ran. */\n resync?: ResyncResult;\n}\n\n/**\n * Compact the engine-applied limits into the BoxRecord shape: only fields that\n * actually constrain the box (>0 / non-empty). Returns undefined when nothing\n * was applied so legacy/unlimited boxes stay free of the field.\n */\nfunction persistableLimits(\n lim: BoxLimitSpec | undefined,\n): BoxRecord['resourceLimits'] | undefined {\n if (!lim) return undefined;\n const out: NonNullable<BoxRecord['resourceLimits']> = {};\n if (lim.memoryBytes && lim.memoryBytes > 0) out.memoryBytes = Math.floor(lim.memoryBytes);\n if (lim.cpus && lim.cpus > 0) out.cpus = lim.cpus;\n if (lim.pidsLimit && lim.pidsLimit > 0) out.pidsLimit = Math.floor(lim.pidsLimit);\n if (lim.disk) out.disk = lim.disk;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\nexport function sanitizeBasename(workspacePath: string): string {\n const raw = basename(resolve(workspacePath));\n return raw\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^[-._]+|[-._]+$/g, '')\n .slice(0, 30)\n .replace(/[-._]+$/, '');\n}\n\nexport function defaultBoxName(workspacePath: string, id: string): string {\n const base = sanitizeBasename(workspacePath);\n return base.length > 0 ? `${base}-${id}` : id;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Trust the (TLS) host Portless CA inside a docker box so the in-box VNC\n * Chromium and Playwright accept `https://<name>.localhost`. The CA is the\n * host's, bind-mounted at /home/vscode/.portless/ca.pem (PORTLESS_STATE_DIR).\n * The baked `agentbox-portless-trust` helper installs it into the system store\n * + the vscode NSS db; we then drop a profile.d export of NODE_EXTRA_CA_CERTS\n * for Node-based agents. Best-effort: never throws.\n */\nasync function trustInBoxPortlessCa(\n container: string,\n log: (line: string) => void,\n): Promise<void> {\n const script =\n 'agentbox-portless-trust /home/vscode/.portless/ca.pem >/dev/null 2>&1 || true; ' +\n \"echo 'export NODE_EXTRA_CA_CERTS=/usr/local/share/ca-certificates/agentbox-portless-ca.crt' \" +\n '> /etc/profile.d/agentbox-portless-ca.sh 2>/dev/null || true';\n const r = await execa(\n 'docker',\n ['exec', '--user', 'root', container, 'bash', '-lc', script],\n { reject: false },\n );\n if (r.exitCode === 0) log('portless: trusted host CA in box (system store + NSS)');\n else log('portless: in-box CA trust failed (best-effort) — in-box https may warn');\n}\n\n// ~/.claude and ~/.codex are intentionally NOT in this list: each lives in a\n// named volume (`agentbox-claude-config` / `agentbox-codex-config`, see\n// resolveClaudeVolume / resolveCodexVolume) so auth persists inside the\n// container without leaking host state. Only the remaining identity files are\n// bind-mounted from the host.\nasync function buildIdentityMounts(): Promise<string[]> {\n const home = homedir();\n const candidates: Array<{ src: string; dst: string; readOnly: boolean }> = [\n { src: join(home, '.gitconfig'), dst: '/home/vscode/.gitconfig', readOnly: true },\n ];\n const out: string[] = [];\n for (const c of candidates) {\n if (await pathExists(c.src)) {\n out.push(`${c.src}:${c.dst}${c.readOnly ? ':ro' : ''}`);\n }\n }\n return out;\n}\n\nexport async function createBox(opts: CreateBoxOptions): Promise<CreatedBox> {\n const log = opts.onLog ?? (() => {});\n const workspace = resolve(opts.workspacePath);\n if (!(await pathExists(workspace))) {\n throw new Error(`workspace does not exist: ${workspace}`);\n }\n\n // Pre-flight agentbox.yaml validation on the host so the user sees the real\n // ConfigError instead of an opaque \"socket did not appear\" timeout from the\n // detached daemon exec later. The daemon re-validates inside the box anyway\n // — defence in depth, and necessary because the file lives in the\n // container's writable layer and can be edited after create.\n const cfgPath = join(workspace, 'agentbox.yaml');\n if (await pathExists(cfgPath)) {\n try {\n const cfg = await loadConfig(cfgPath);\n log(`agentbox.yaml validated (${String(cfg.services.length)} service(s))`);\n } catch (err) {\n if (err instanceof ConfigError) {\n throw new Error(`agentbox.yaml validation failed:\\n ${err.message}`);\n }\n throw err;\n }\n }\n\n await dockerInfo();\n log('docker daemon reachable');\n\n // Checkpoint resolution happens *before* image ensure because a checkpoint\n // image replaces the base image as the docker-run base. resolveCheckpoint\n // returns null on miss; we error with the ref so the user can fix it.\n let checkpointImage: string | undefined;\n let checkpointSource: BoxRecord['checkpointSource'];\n let restoredWorktrees: GitWorktreeRecord[] | undefined;\n let resyncResult: ResyncResult | undefined;\n if (opts.checkpointRef) {\n const projectRootForCkpt = opts.projectRoot ?? workspace;\n const head = await resolveCheckpoint(projectRootForCkpt, opts.checkpointRef);\n if (!head) {\n throw new Error(`checkpoint not found: ${opts.checkpointRef}`);\n }\n checkpointImage = head.manifest.image;\n // Chain: head first then its parents (base-most last). For a flattened\n // checkpoint this collapses to a single-entry chain.\n const chain = [head.name, ...head.manifest.parents];\n checkpointSource = { ref: opts.checkpointRef, type: head.manifest.type, chain };\n // The source's per-worktree paths persisted on the manifest so we can\n // re-establish the /workspace bind mount(s) after `docker run` (docker\n // commit doesn't capture bind-mount content, so the image's /workspace\n // is empty until we re-bind).\n restoredWorktrees = head.manifest.worktrees;\n log(\n `starting from checkpoint ${opts.checkpointRef} (${head.manifest.type}, ${String(chain.length)} layer(s), image ${head.manifest.image})`,\n );\n\n // Stale-checkpoint warning: the checkpoint image replaces the base image\n // as the docker-run base, so any base-image update (a CLI upgrade, an\n // edit to `custom-system-CLAUDE.md`, etc.) is invisible inside a box\n // restored from a pre-update checkpoint. Compare the captured\n // fingerprint with the current prepared state and surface the\n // mismatch loudly. We never block — the user might intentionally pin\n // an old image — but they need to know.\n const ckptFingerprint = head.manifest.baseFingerprint;\n const ckptCliVersion = head.manifest.cliVersion ?? 'unknown';\n if (head.manifest.schema === 2) {\n log(\n `WARNING: checkpoint '${opts.checkpointRef}' was captured before checkpoint versioning landed.\\n` +\n ` Its base-image layers may be older than your current base image. If the box is missing\\n` +\n ` expected updates, remove the checkpoint with \\`agentbox checkpoint rm ${opts.checkpointRef}\\` and recreate it.`,\n );\n } else {\n const prepared = readPreparedDockerState();\n const currentFingerprint =\n prepared?.base?.contextSha256 ??\n (await computeDockerContextFingerprint())?.contextSha256;\n if (\n ckptFingerprint &&\n currentFingerprint &&\n ckptFingerprint !== currentFingerprint\n ) {\n log(\n `WARNING: checkpoint '${opts.checkpointRef}' was captured against an older base image.\\n` +\n ` captured: cli ${ckptCliVersion}, fingerprint ${ckptFingerprint.slice(0, 12)}\\n` +\n ` current : cli ${prepared?.base?.cliVersion ?? 'unknown'}, fingerprint ${currentFingerprint.slice(0, 12)}\\n` +\n ` The restored box will keep the old base layers and will NOT include base-image updates.\\n` +\n ` To pick up updates: \\`agentbox checkpoint rm ${opts.checkpointRef}\\` and recreate from a fresh box.`,\n );\n }\n }\n }\n\n const imageRef = checkpointImage ?? opts.image ?? DEFAULT_BOX_IMAGE;\n // ensureImage only acts on the base image; checkpoint images are local-only\n // and must already exist (they were created by `agentbox checkpoint`).\n const ensureRef = checkpointImage ? (opts.image ?? DEFAULT_BOX_IMAGE) : imageRef;\n const { built } = await ensureImage(ensureRef, {\n onProgress: (line) => log(`[image] ${line}`),\n allowPull: opts.allowPull,\n registry: opts.imageRegistry,\n });\n log(built ? `built image ${ensureRef}` : `using cached image ${imageRef}`);\n\n // Bring up the host relay before the box so the box can post events\n // immediately on boot. Best-effort — a relay outage shouldn't block create.\n // Always re-push known box tokens after ensure: the relay's registry is\n // in-memory, so a daemon restart or `docker restart agentbox-relay` between\n // CLI invocations leaves it empty. Repushing is idempotent and cheap.\n let relayUp = false;\n try {\n await ensureRelay({ onLog: log });\n const existing = await readState();\n await rehydrateRelayRegistry(existing.boxes);\n relayUp = true;\n } catch (err) {\n log(`relay unavailable: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const id = generateBoxId();\n const name = opts.name ?? defaultBoxName(workspace, id);\n const containerName = `agentbox-${name}`;\n const createdAt = new Date().toISOString();\n if (await containerExists(containerName)) {\n throw new Error(`container ${containerName} already exists; remove it first`);\n }\n\n // Per-project monotonic index. Reserved *atomically* here (under the state\n // lock, persisting a minimal record that claims it) so it can flow into the\n // box / snapshot dir segments (`<id>-<n>-<mnemonic>`) and the\n // `AGENTBOX_PROJECT_INDEX` env var with no risk of a concurrent create\n // claiming the same number and forcing a later bump that would desync the\n // recorded index from the dir already created from it. The full record is\n // written over this reservation by the provisional + final recordBox below.\n // Pre-feature legacy boxes never pass `projectRoot`; those keep `projectIndex`\n // undefined and the dir segments fall back to `<id>-<mnemonic>`.\n let projectIndex: number | undefined;\n if (opts.projectRoot) {\n projectIndex = await reserveProjectIndex(\n { id, name, container: containerName, image: imageRef, workspacePath: workspace, createdAt },\n opts.projectRoot,\n );\n }\n\n // Repo detection + host-side carry-over capture. Branches are picked here\n // (against the host main repos' refs) so they're recorded on the BoxRecord\n // regardless of whether the in-container `git worktree add` succeeds later.\n // When restoring from a checkpoint, the source's per-worktree records are\n // restored from the manifest *here* (not after `docker run`) so the\n // `.git/` bind-mounts in `extraVolumes` know which host main repos to\n // wire up — without those binds the in-container `/workspace/.git` would\n // resolve to a path that doesn't exist in the new container.\n const repoCarryOvers: RepoCarryOver[] = [];\n const gitWorktreeRecords: GitWorktreeRecord[] = [];\n // Checkpoint restore: the manifest's worktree records carry the *source*\n // box's branch + path. Reusing them verbatim is the shared-worktree bug —\n // every box from one checkpoint would share a single branch + index, and the\n // baked /workspace/.git gitfile dangles once the source box's host worktree\n // metadata was pruned. So mint a FRESH per-box branch + unique worktree path\n // here (host-side, before docker run, like the non-checkpoint path) and\n // regenerate the in-box worktree over the baked content after run.\n const restoreWorktreePlans: RestoreWorktreePlan[] = [];\n if (checkpointImage && restoredWorktrees && restoredWorktrees.length > 0) {\n for (const w of restoredWorktrees) {\n const branchBase =\n w.kind === 'root'\n ? `agentbox/${name}`\n : `agentbox/${name}--${w.relPathFromWorkspace.replace(/[^A-Za-z0-9._-]+/g, '_')}`;\n const freshBranch = await pickFreshBranch(w.hostMainRepo, branchBase);\n const freshGitWorktreePath = gitWorktreePathFor(freshBranch);\n restoreWorktreePlans.push({\n hostMainRepo: w.hostMainRepo,\n kind: w.kind,\n bakedGitWorktreePath: w.gitWorktreePath,\n freshBranch,\n freshGitWorktreePath,\n });\n gitWorktreeRecords.push({\n kind: w.kind,\n hostMainRepo: w.hostMainRepo,\n containerPath: w.containerPath,\n gitWorktreePath: freshGitWorktreePath,\n branch: freshBranch,\n sanctionedBranch: freshBranch,\n relPathFromWorkspace: w.relPathFromWorkspace,\n });\n }\n }\n if (!checkpointImage) {\n const repos = await detectGitRepos(workspace);\n if (repos.length > 0) {\n log(\n `detected ${String(repos.length)} git repo(s): ` +\n repos.map((r) => `${r.kind}${r.relPathFromWorkspace ? '@' + r.relPathFromWorkspace : ''}`).join(', '),\n );\n }\n for (const r of repos) {\n const containerPath =\n r.kind === 'root' ? '/workspace' : `/workspace/${r.relPathFromWorkspace}`;\n // --use-branch reuses the named branch for the *root* repo only: no\n // pickFreshBranch (we want the exact branch), no carry-over replay (the\n // user wants the branch's committed tip, not host uncommitted state).\n // Nested repos always fork their own per-box branch — the root's reused\n // branch won't exist in a nested repo.\n const reuseBranch = r.kind === 'root' && opts.useBranch !== undefined;\n if (reuseBranch) {\n const branch = opts.useBranch as string;\n const gitWorktreePath = gitWorktreePathFor(branch);\n repoCarryOvers.push({\n repo: r,\n containerPath,\n gitWorktreePath,\n branch,\n stashSha: null,\n untrackedNul: '',\n hostSource: r.hostMainRepo,\n reuseBranch: true,\n });\n gitWorktreeRecords.push({\n kind: r.kind,\n hostMainRepo: r.hostMainRepo,\n containerPath,\n gitWorktreePath,\n branch,\n sanctionedBranch: branch,\n relPathFromWorkspace: r.relPathFromWorkspace,\n });\n continue;\n }\n const branchBase =\n r.kind === 'root'\n ? `agentbox/${name}`\n : `agentbox/${name}--${r.relPathFromWorkspace.replace(/[^A-Za-z0-9._-]+/g, '_')}`;\n const branch = await pickFreshBranch(r.hostMainRepo, branchBase);\n const gitWorktreePath = gitWorktreePathFor(branch);\n const carry = await collectRepoCarryOver(r, branch, containerPath, gitWorktreePath);\n repoCarryOvers.push(carry);\n gitWorktreeRecords.push({\n kind: r.kind,\n hostMainRepo: r.hostMainRepo,\n containerPath,\n gitWorktreePath,\n branch,\n sanctionedBranch: branch,\n relPathFromWorkspace: r.relPathFromWorkspace,\n });\n }\n }\n\n // --host-snapshot: APFS clone the workspace into a per-box scratch dir.\n // Only the no-git, no-checkpoint path actually consumes the clone (as the\n // source of the tar pipe in seedWorkspaceFromDir). For the git path the\n // worktree content comes from `.git`'s object DB (bind-mounted) and the\n // untracked-file tar pipe reads from the live host main repo — neither\n // touches `snapshotDir`, so we skip it. For checkpoint restore there's no\n // seedWorkspace at all. Kept on the BoxRecord so destroyBox can clean it up.\n let snapshotDir: string | null = null;\n const snapshotIsUseful = !checkpointImage && repoCarryOvers.length === 0;\n if (opts.useSnapshot && snapshotIsUseful) {\n snapshotDir = snapshotPathFor({ id, name, projectIndex });\n log(`cloning workspace to ${snapshotDir} (APFS clone where available)`);\n const snap = await createSnapshot({ source: workspace, destination: snapshotDir });\n log(`pruned ${snap.prunedPaths.length} platform-dependent dirs from snapshot`);\n } else if (opts.useSnapshot && !checkpointImage) {\n log('skipping --host-snapshot: git worktree path reads content from .git, not from a workspace clone');\n }\n\n await ensureIdeVolumes(id);\n const dockerCacheShared = opts.docker?.sharedCache === true;\n const dockerVolume = dockerVolumeName(id, dockerCacheShared);\n await ensureVolume(dockerVolume);\n log(`prepared volumes ${vscodeServerVolumeName(id)}, ${cursorServerVolumeName(id)}, ${dockerVolume}`);\n const ide = buildIdeMounts(id);\n\n // Agent config volumes (claude/codex/agents/opencode). Each is\n // host-authoritative and additively synced from the host on every create (a\n // new login/skill/MCP on the host flows into the next box; box-only state like\n // session logs is preserved). `--isolate-<tool>-config` opts into a per-box\n // volume. Resolve the specs + want-conditionals here (one source of truth —\n // they also drive the mounts below), then walk the docker ProviderSync facade\n // to run the actual volume seeds + credential sync.\n const claudeSpec = resolveClaudeVolume({\n isolate: opts.claudeConfig?.isolate ?? false,\n boxId: id,\n });\n // Codex: wanted when the caller passes `codexConfig` (`agentbox codex`) OR the\n // host already uses codex (`~/.codex` exists) — so a plain create for a Codex\n // user still gets a working box.\n const wantCodex =\n opts.codexConfig !== undefined || (await pathExists(join(homedir(), '.codex')));\n const codexSpec = wantCodex\n ? resolveCodexVolume({ isolate: opts.codexConfig?.isolate ?? false, boxId: id })\n : undefined;\n // Agents skills (~/.agents): mounted whenever the host has one; shared across\n // boxes (skills only, no auth). Codex discovers skills from ~/.agents/skills.\n const agentsSpec = (await pathExists(join(homedir(), '.agents')))\n ? resolveAgentsVolume()\n : undefined;\n // OpenCode: wanted when the caller passes `opencodeConfig` OR the host already\n // uses OpenCode (`~/.config/opencode` or `~/.local/share/opencode`).\n const wantOpencode =\n opts.opencodeConfig !== undefined ||\n (await pathExists(join(homedir(), '.config', 'opencode'))) ||\n (await pathExists(join(homedir(), '.local', 'share', 'opencode')));\n const opencodeSpec = wantOpencode\n ? resolveOpencodeVolume({ isolate: opts.opencodeConfig?.isolate ?? false, boxId: id })\n : undefined;\n\n // Walk the docker ProviderSync facade (see sync/docker-sync.ts for the full\n // per-op picture): seed every agent-config volume (claude static+skills+dynamic\n // +box-facts, codex hooks+AGENTS.override, opencode plugin) then sync the claude\n // credentials. The seeds run against throwaway helper containers + the box image\n // — the box container `containerName` doesn't exist yet, which is fine (those\n // ops don't touch it). Workspace *seed* + the mount building below stay here:\n // they're docker-specific, non-facade steps that feed `runBox`.\n const syncCtx = makeSyncContext({\n boxName: name,\n boxId: id,\n provider: 'docker',\n hostWorkspace: workspace,\n projectRoot: opts.projectRoot ?? workspace,\n onLog: log,\n });\n const sync = makeDockerSync({\n container: containerName,\n image: ensureRef,\n claudeSpec,\n claudeIsolate: opts.claudeConfig?.isolate ?? false,\n codexSpec,\n agentsSpec,\n opencodeSpec,\n });\n await sync.seedAgentConfig(syncCtx);\n await sync.seedCredentials(syncCtx);\n\n // Container mounts, built from the same specs (pure).\n const claudeMounts = buildClaudeMounts(claudeSpec, process.env);\n let codexMounts: CodexMountResult | undefined;\n let codexConfigVolume: string | undefined;\n if (codexSpec) {\n codexMounts = buildCodexMounts(codexSpec, process.env);\n codexConfigVolume = codexSpec.volume;\n }\n let agentsMounts: AgentsMountResult | undefined;\n let agentsConfigVolume: string | undefined;\n if (agentsSpec) {\n agentsMounts = buildAgentsMounts(agentsSpec);\n agentsConfigVolume = agentsSpec.volume;\n }\n let opencodeMounts: OpencodeMountResult | undefined;\n let opencodeConfigVolume: string | undefined;\n if (opencodeSpec) {\n opencodeMounts = buildOpencodeMounts(opencodeSpec, process.env);\n opencodeConfigVolume = opencodeSpec.volume;\n }\n\n const boxDir = boxRunDirFor({ id, name, projectIndex });\n const socketDir = join(boxDir, 'run');\n const socketPath = join(socketDir, 'ctl.sock');\n // Per-box host dir that `agentbox open` refreshes the merged /workspace\n // into. Bound in at create time so `docker exec rsync` can write straight\n // to the host filesystem — no container restart needed.\n const mergedExportDir = join(boxDir, 'workspace');\n await mkdir(socketDir, { recursive: true });\n await mkdir(mergedExportDir, { recursive: true });\n\n const extraVolumes = await buildIdentityMounts();\n extraVolumes.push(...claudeMounts.extraVolumes);\n if (codexMounts) extraVolumes.push(...codexMounts.extraVolumes);\n if (agentsMounts) extraVolumes.push(...agentsMounts.extraVolumes);\n if (opencodeMounts) extraVolumes.push(...opencodeMounts.extraVolumes);\n extraVolumes.push(...ide.extraVolumes);\n extraVolumes.push(`${socketDir}:/run/agentbox`);\n extraVolumes.push(`${mergedExportDir}:${CONTAINER_EXPORT_MERGED}`);\n // In-box dockerd's data root. Per-box (`agentbox-docker-<id>`, wiped on\n // destroy) by default; shared (`agentbox-docker-cache`, preserved) when\n // `box.dockerCacheShared` is set.\n extraVolumes.push(`${dockerVolume}:/var/lib/docker`);\n // Bind-mount each main repo's `.git/` at its identical absolute host path,\n // RW. The in-container `git worktree add` writes to <main>/.git/worktrees/\n // and the agent's commits write to refs/objects; both have to hit the same\n // path on host and inside the container so `git push` from the host main\n // repo sees the new commits without further sync.\n for (const w of gitWorktreeRecords) {\n extraVolumes.push(`${w.hostMainRepo}/.git:${w.hostMainRepo}/.git`);\n }\n\n // Portless: when enabled (and not OrbStack), (1) make the in-box browser\n // route the box's `<name>.localhost` URL out to the host proxy\n // (`portlessBrowserEnv`), and (2) bind-mount the host's Portless state dir so\n // the in-box `portless` CLI shares the host's route registry (discovery).\n // Best-effort; a missing host dir is created so the bind has a source.\n // PORTLESS_STATE_DIR pins both sides to the same path.\n const portlessEnv: Record<string, string> = {};\n if (opts.portless === true && (await detectEngine()) !== 'orbstack') {\n Object.assign(portlessEnv, portlessBrowserEnv(name, { mapTarget: 'host.docker.internal' }));\n try {\n const hostStateDir = await resolvePortlessHostStateDir(opts.portlessStateDir);\n await mkdir(hostStateDir, { recursive: true });\n const boxStateDir = '/home/vscode/.portless';\n extraVolumes.push(`${hostStateDir}:${boxStateDir}`);\n portlessEnv['PORTLESS_STATE_DIR'] = boxStateDir;\n } catch (err) {\n log(\n `portless: state-dir share skipped (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n }\n\n for (const v of extraVolumes) log(`mounting agent dir: ${v}`);\n\n // Resolve the per-box host-action auto-approve policy from config (workspace\n // > project > global). Read here, in the construction layer, so every\n // entrypoint (create/claude/codex/opencode/wizard/queued worker) gets the\n // same behavior without each caller threading the flag.\n const effectiveBoxCfg = (await loadEffectiveConfig(opts.projectRoot ?? workspace)).effective.box;\n const autoApproveHostActions = effectiveBoxCfg.autoApproveHostActions;\n const autoApproveSafeHostActions = effectiveBoxCfg.autoApproveSafeHostActions;\n\n // Per-box bearer token for the host relay. Register *before* runBox so the\n // box's supervisor can post on boot. Skip if the relay isn't reachable —\n // the box still works, it just won't deliver events to the host.\n const relayToken = generateRelayToken();\n if (relayUp) {\n try {\n await registerBoxWithRelay({\n boxId: id,\n token: relayToken,\n name,\n containerName,\n createdAt,\n projectIndex,\n worktrees: gitWorktreeRecords,\n autoApproveHostActions,\n autoApproveSafeHostActions,\n });\n log(`registered box token with relay`);\n } catch (err) {\n log(`relay register failed: ${err instanceof Error ? err.message : String(err)}`);\n relayUp = false;\n }\n }\n const relayEnv: Record<string, string> = relayUp\n ? {\n // The in-box ctl client always talks to its own in-box relay/forwarder\n // on AGENTBOX_BOX_RELAY_PORT (default 8788). For docker boxes the\n // forwarder transparently proxies to the host relay at\n // host.docker.internal:8787 (the matching `--add-host` is set in\n // runBox). This keeps :8787 inside the box free for a nested\n // agentbox to claim its own host relay.\n AGENTBOX_RELAY_URL: `http://127.0.0.1:8788`,\n AGENTBOX_RELAY_TOKEN: relayToken,\n AGENTBOX_HOST_RELAY_URL: `http://host.docker.internal:8787`,\n }\n : {};\n\n // VNC stack defaults on; the CLI surfaces `--no-vnc` for opt-out. Generate\n // the password and the port mapping up front so they're baked into the\n // container's env + `-p` flags before `docker run` — both must be set at\n // create time (env survives stop/start; port mappings are immutable).\n const vncEnabled = opts.vnc?.enabled !== false;\n const vncPassword = vncEnabled ? generateVncPassword() : undefined;\n const vncEnv: Record<string, string> = vncEnabled && vncPassword\n ? { AGENTBOX_VNC_PASSWORD: vncPassword }\n : {};\n const vncPortMappings = vncEnabled\n ? [{ hostPort: 0, containerPort: VNC_CONTAINER_PORT, hostIp: '127.0.0.1' }]\n : [];\n\n // Reserve the web port unconditionally: `docker run -p` is immutable, but the\n // `expose:`-flagged service is usually only known after the in-box wizard\n // writes agentbox.yaml. The supervisor forwards :80 to it later; here we just\n // guarantee a published host port exists for whenever that happens.\n const webPortMappings = [\n { hostPort: 0, containerPort: WEB_CONTAINER_PORT, hostIp: '127.0.0.1' },\n ];\n\n // sshd is always-on: publish container :22 on an ephemeral loopback host port\n // so `agentbox open` (sshfs) and the Codex app can reach the box over SSH. Like\n // the web/VNC mappings this must be set at `docker run` (port maps are immutable)\n // and re-resolved on every start (the host port is reassigned).\n const sshPortMappings = [\n { hostPort: 0, containerPort: SSH_CONTAINER_PORT, hostIp: '127.0.0.1' },\n ];\n\n // Identity vars that make the box self-aware. `projectIndex` was allocated\n // earlier (right after `id`/`name`) so dir-segment helpers could see it; we\n // just read the binding here.\n const agentboxEnv: Record<string, string> = {\n AGENTBOX: '1',\n AGENTBOX_BOX_NAME: name,\n AGENTBOX_HOST_WORKSPACE: workspace,\n // Absent = enabled; the ctl credential watcher only checks for '0'. The\n // caller-resolved value wins (it sees CLI overrides like\n // --no-credential-sync that this function's own config load can't).\n ...((opts.credentialSync ?? effectiveBoxCfg.credentialSync) === false\n ? { AGENTBOX_CREDENTIAL_SYNC: '0' }\n : {}),\n ...(opts.projectRoot ? { AGENTBOX_PROJECT_ROOT: opts.projectRoot } : {}),\n ...(projectIndex !== undefined\n ? { AGENTBOX_PROJECT_INDEX: String(projectIndex) }\n : {}),\n };\n const boxEnvForFile: Record<string, string> = {\n AGENTBOX_BOX_ID: id,\n ...agentboxEnv,\n ...portlessEnv,\n };\n\n // `--storage-opt size=` is only enforced by devicemapper/btrfs/zfs.\n const appliedLimits: BoxLimitSpec | undefined = opts.limits;\n let effectiveLimits = appliedLimits;\n if (appliedLimits?.disk) {\n const driver = await dockerStorageDriver();\n if (!/^(devicemapper|btrfs|zfs|windowsfilter)$/.test(driver)) {\n log(\n `warning: --disk/box.disk is a no-op on this engine (storage-driver=${driver || 'unknown'}); ignoring`,\n );\n effectiveLimits = { ...appliedLimits, disk: null };\n }\n }\n\n // Everything about the box that's known before `docker run`. Recorded\n // provisionally right after the container starts (below) so a failure during\n // the rest of finalization (seed, ctl/vnc/dockerd launch, port publish,\n // portless) still leaves a state.json record — destroy/prune resolve the box\n // by its real name from state.json instead of relying on the orphan-container\n // fallback, and the late-known fields (ports, portless, carry) are merged in\n // by the final `recordBox` on success.\n const baseRecord: BoxRecord = {\n id,\n name,\n container: containerName,\n image: imageRef,\n workspacePath: workspace,\n snapshotDir,\n socketPath,\n claudeConfigVolume: claudeSpec.volume,\n codexConfigVolume,\n agentsConfigVolume,\n opencodeConfigVolume,\n vscodeServerVolume: vscodeServerVolumeName(id),\n cursorServerVolume: cursorServerVolumeName(id),\n relayToken: relayUp ? relayToken : undefined,\n gitWorktrees: gitWorktreeRecords.length > 0 ? gitWorktreeRecords : undefined,\n withPlaywright: opts.withPlaywright ? true : undefined,\n withEnv: opts.withEnv ? true : undefined,\n autoApproveHostActions: autoApproveHostActions ? true : undefined,\n // Default on: persist only when explicitly disabled (mirrors the relay's\n // `!== false` read); an absent field on an older record stays relaxed.\n autoApproveSafeHostActions: autoApproveSafeHostActions === false ? false : undefined,\n vncEnabled: vncEnabled ? true : undefined,\n vncContainerPort: vncEnabled ? VNC_CONTAINER_PORT : undefined,\n vncPassword: vncPassword,\n webContainerPort: WEB_CONTAINER_PORT,\n sshEnabled: true,\n sshContainerPort: SSH_CONTAINER_PORT,\n dockerVolume,\n dockerCacheShared: dockerCacheShared || undefined,\n projectRoot: opts.projectRoot,\n projectIndex,\n checkpointImage,\n checkpointSource,\n resourceLimits: persistableLimits(effectiveLimits),\n createdAt,\n };\n\n await runBox({\n name: containerName,\n image: imageRef,\n extraVolumes,\n limits: effectiveLimits,\n portMappings: [...vncPortMappings, ...webPortMappings, ...sshPortMappings],\n env: {\n AGENTBOX_BOX_ID: id,\n ...agentboxEnv,\n ...claudeMounts.env,\n ...(codexMounts?.env ?? {}),\n ...(opencodeMounts?.env ?? {}),\n ...relayEnv,\n ...vncEnv,\n ...portlessEnv,\n ...(opts.claudeEnv ?? {}),\n },\n });\n log(`container ${containerName} started`);\n\n // Provisional registration: the box now exists, so persist it before the\n // remaining finalization steps. If create dies past this point, the record\n // (with the real name) is already in state.json for destroy/prune to find.\n await recordBox(baseRecord);\n\n // Flip the in-container parent dir of each bind-mounted `.git` to\n // vscode-owned. Docker auto-creates the intermediates (e.g. the project root\n // path that contains `.git`) as root:root 755 in the writable layer; without\n // this chown the agent can't write siblings of `.git` (`.turbo/`, `.next/`,\n // build caches) at the project root. Non-recursive — the bind-mounted `.git`\n // itself stays untouched (recursive chown would propagate to the host).\n if (gitWorktreeRecords.length > 0) {\n await chownGitBindParents({\n container: containerName,\n hostMainRepos: gitWorktreeRecords.map((w) => w.hostMainRepo),\n onLog: log,\n });\n }\n\n // /etc/agentbox/box.env: sourced by /etc/profile.d/agentbox.sh in login\n // shells (the docker-run env doesn't reach `agentbox shell <box>` cleanly\n // without it). Best-effort — env vars on the container are the primary\n // path; this file is for shells launched via tools that strip env.\n const boxEnv = await writeBoxEnvFile(containerName, boxEnvForFile);\n if (boxEnv.ok) log('wrote /etc/agentbox/box.env');\n else log(`writing /etc/agentbox/box.env failed: ${boxEnv.reason}`);\n\n // Re-own /home/vscode to vscode. Root-run exec steps (checkpoint cleanup,\n // dockerd setup) and boxes restored from a checkpoint can leave home-dir\n // files root-owned; the shell + agent run as vscode and would silently\n // fail to write them (e.g. dropped `.bash_history`). Best-effort.\n await ensureHomeOwnedByVscode(containerName);\n\n // Seed /workspace.\n // - Checkpoint restore: the image already has the source box's per-box\n // worktree dir populated; we only need to re-establish the bind mount\n // onto /workspace (docker commit doesn't capture bind-mount content).\n // - Git path: create in-container worktrees + bind + replay stash + untracked.\n // - No-git path: tar-pipe host workspace (or its APFS clone) into\n // /workspace (no bind — files live directly in the image's writable\n // layer at /workspace).\n if (!checkpointImage) {\n if (repoCarryOvers.length > 0) {\n try {\n await seedWorkspace({\n container: containerName,\n repos: repoCarryOvers,\n fromBranch: opts.fromBranch,\n onLog: log,\n });\n log('seeded /workspace from in-container git worktree(s)');\n } catch (err) {\n // --use-branch seed failures are almost always \"branch already used by\n // another worktree\" (the host has it checked out). There's nothing\n // useful to inspect, and a leftover container + worktree registration\n // would block the next attempt, so tear it down. Other seed failures\n // keep the existing inspect-on-failure behavior.\n if (opts.useBranch !== undefined) {\n log(`seedWorkspace failed for --use-branch ${opts.useBranch}; cleaning up the box`);\n await execa('docker', ['rm', '-f', containerName], { reject: false });\n // Drop the provisional record written after runBox so we don't leave\n // a dangling state.json entry pointing at the now-removed container.\n await removeBoxRecord(id);\n for (const w of gitWorktreeRecords) {\n await removeInBoxWorktree({\n hostMainRepo: w.hostMainRepo,\n gitWorktreePath: w.gitWorktreePath,\n });\n }\n } else {\n log(`seedWorkspace failed; leaving ${containerName} running so you can inspect it`);\n }\n throw err;\n }\n } else {\n const source = snapshotDir ?? workspace;\n await seedWorkspaceFromDir({ container: containerName, hostSource: source, onLog: log });\n }\n } else if (restoreWorktreePlans.length > 0) {\n // gitWorktreeRecords was populated above (pre-`docker run`) with FRESH\n // per-box branches/paths, so the .git bind-mounts in extraVolumes are\n // wired. The container is now running, so regenerate each baked worktree\n // onto its fresh branch (rename + fresh metadata + reindex), then apply the\n // /workspace bind mount(s) onto the fresh paths.\n await regenerateRestoredWorktrees({\n container: containerName,\n plans: restoreWorktreePlans,\n fromBranch: opts.fromBranch,\n onLog: log,\n });\n await bindWorktrees(\n containerName,\n gitWorktreeRecords.map((w) => ({\n kind: w.kind,\n containerPath: w.containerPath,\n gitWorktreePath: w.gitWorktreePath,\n })),\n log,\n );\n log('re-bound /workspace from checkpoint image (fresh per-box worktree)');\n // Each fresh branch was forked from the host's base ref, and\n // regenerateRestoredWorktrees already `reset --hard`ed the tracked tree to\n // it (the checkpoint's stale tracked deviations are dropped; gitignored warm\n // artifacts like node_modules are kept). Resync then merges the host's\n // current branch in + overlays the host's uncommitted/untracked changes, so\n // the box matches a fresh create from HEAD (box wins on conflict).\n if (opts.resyncOnStart !== false) {\n resyncResult = await sync.resyncWorkspace(syncCtx, gitWorktreeRecords);\n }\n } else {\n log('using /workspace from checkpoint image (no worktrees recorded; no rebind)');\n }\n\n await repairIdeOwnership(containerName);\n log('.vscode-server + .cursor-server ownership verified');\n\n // dockerd: always-on, mirrors launchVncDaemon. Launched (and awaited ready)\n // BEFORE the ctl supervisor: the supervisor starts agentbox.yaml services as\n // soon as it's up, so a `docker run`/`docker compose` service must not race a\n // not-yet-ready /var/run/docker.sock. launchDockerdDaemon blocks until the\n // socket is accept()-able. Best-effort — a slow start shouldn't fail box\n // creation; `agentbox start` will relaunch on restart (the daemon dies with\n // the container). The storage driver is selected at runtime by\n // agentbox-dockerd-start (overlay2, with a fuse-overlayfs fallback) — see\n // /var/log/agentbox/dockerd.log inside the box.\n const dockerd = await launchDockerdDaemon(containerName);\n if (dockerd.up) {\n log(`dockerd up (data root=${dockerVolume})`);\n } else {\n log(`dockerd did not become ready: ${dockerd.reason}`);\n }\n\n const ctl = await launchCtlDaemon(containerName, socketPath);\n if (ctl.up) log('agentbox-ctl daemon up');\n else log(`agentbox-ctl daemon did not become reachable: ${ctl.reason}`);\n\n if (opts.withPlaywright) {\n log('installing @playwright/cli@latest (--with-playwright)');\n const result = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n containerName,\n 'bash',\n '-lc',\n 'npm install -g @playwright/cli@latest 2>&1',\n ],\n { reject: false },\n );\n for (const line of (result.stdout ?? '').split('\\n')) {\n if (line.trim().length > 0) log(`[playwright] ${line}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(\n `failed to install @playwright/cli (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n );\n }\n log('@playwright/cli installed');\n }\n\n if (opts.withEnv) {\n log('copying host env/config files into /workspace (--with-env)');\n const { copied } = await sync.seedEnvFiles(syncCtx, DEFAULT_ENV_PATTERNS);\n log(copied > 0 ? `copied ${String(copied)} env/config file(s)` : 'no env/config files found');\n }\n\n if (opts.envFilesToImport && opts.envFilesToImport.length > 0) {\n log(`copying ${String(opts.envFilesToImport.length)} selected env/config file(s) into /workspace`);\n const { copied } = await copyHostFilesToBox({\n container: containerName,\n workspaceDir: workspace,\n files: opts.envFilesToImport,\n onLog: log,\n });\n if (copied !== opts.envFilesToImport.length) {\n log(`copied ${String(copied)}/${String(opts.envFilesToImport.length)} selected env/config file(s)`);\n }\n }\n\n // carry: from agentbox.yaml — resolved and approved by the host CLI, then\n // threaded in here. Runs after the env-file copies and before the supervisor\n // launches so the first task can already see e.g. ~/.agentbox/secrets.env.\n let carrySummary: BoxRecord['carry'] | undefined;\n if (opts.carry && opts.carry.length > 0) {\n log(`carry: copying ${String(opts.carry.length)} host path(s) into the box`);\n const result = await sync.applyCarry(syncCtx, opts.carry);\n log(`carry: copied ${String(result.copied)}/${String(opts.carry.length)} entry/entries`);\n for (const err of result.errors) log(`carry: ${err}`);\n if (result.applied.length > 0) {\n carrySummary = { count: result.applied.length, entries: result.applied };\n }\n }\n\n // VNC daemon (Xvnc + websockify). Best-effort, like launchCtlDaemon. The\n // host port mapping was wired into runBox above (hostPort=0 → random); we\n // resolve the assigned port here for storage. If the daemon fails to come\n // up we still record vncEnabled so `agentbox start` will retry the launch.\n let vncHostPort: number | null = null;\n if (vncEnabled) {\n const vnc = await launchVncDaemon(containerName);\n if (vnc.up) log('vnc stack up (Xvnc + websockify + noVNC)');\n else log(`vnc stack did not become reachable: ${vnc.reason}`);\n vncHostPort = await publishedHostPort(containerName, VNC_CONTAINER_PORT);\n if (vncHostPort) log(`vnc web on host 127.0.0.1:${String(vncHostPort)}`);\n }\n\n const webHostPort = await publishedHostPort(containerName, WEB_CONTAINER_PORT);\n if (webHostPort) {\n log(\n `web port reserved on host 127.0.0.1:${String(webHostPort)} ` +\n `(forwards to the web service once agentbox.yaml sets a service expose:)`,\n );\n }\n\n // sshd: mint the per-box key under the box dir's ssh/, install it into the\n // box's authorized_keys, launch sshd, resolve the loopback host port. The key\n // dir lives inside boxDir so `destroy` (which rm -rf's boxRunDirFor) wipes the\n // private key with it. Best-effort — a failed bring-up leaves the box usable\n // over `docker exec`, just without `agentbox open`/SSH.\n const ssh = await setUpBoxSshd(\n containerName,\n join(boxDir, 'ssh'),\n `agentbox-${name}-${id}`,\n );\n if (ssh.up && ssh.sshHostPort) {\n log(`sshd up on host 127.0.0.1:${String(ssh.sshHostPort)} (loopback-only)`);\n } else {\n log(`sshd did not come up: ${ssh.reason ?? 'unknown'} (open/SSH unavailable; docker exec still works)`);\n }\n\n // Portless: register `https://<box-name>.localhost -> 127.0.0.1:<webHostPort>`\n // and a parallel `https://vnc-<box-name>.localhost -> 127.0.0.1:<vncHostPort>`\n // for the noVNC viewer. Best-effort — Portless is user-installed and never\n // required; any failure here just leaves the box on its loopback URL.\n // Skipped on OrbStack (which already has <container>.orb.local).\n let portlessAliasName: string | undefined;\n let portlessUrl: string | undefined;\n let portlessVncAliasName: string | undefined;\n let portlessVncUrl: string | undefined;\n if (opts.portless === true && (webHostPort || (vncEnabled && vncHostPort))) {\n try {\n const engine = await detectEngine();\n if (engine === 'orbstack') {\n log('portless: skipped (OrbStack already provides <container>.orb.local)');\n } else {\n const portless = await detectPortless();\n if (!portless.installed) {\n log('portless not installed — run `npm install -g portless` for a <name>.localhost URL');\n } else {\n if (webHostPort) {\n if (await portlessAlias(name, webHostPort)) {\n portlessAliasName = name;\n // Resolve the real URL from the proxy: scheme + port depend on how\n // the proxy was started (http://…:1355 no-TLS, or https://… on :443).\n portlessUrl = await portlessGetUrl(name);\n log(`portless alias ${portlessUrl} -> 127.0.0.1:${String(webHostPort)}`);\n // When the host proxy is TLS, the in-box VNC Chromium / Playwright\n // hit `https://<name>.localhost` (via host.docker.internal) and\n // reject the host's self-signed CA. The CA is already bind-mounted\n // at /home/vscode/.portless/ca.pem (PORTLESS_STATE_DIR); trust it\n // in the box (system store + vscode NSS db) and point Node at it.\n // agent-browser already gets IGNORE_HTTPS_ERRORS via portlessEnv;\n // this covers everything else. http (no-TLS :1355) has no cert.\n if (portlessUrl.startsWith('https://')) {\n await trustInBoxPortlessCa(containerName, log);\n }\n } else {\n log('portless alias failed (best-effort) — box still reachable on the loopback URL');\n }\n }\n if (vncEnabled && vncHostPort) {\n const vncAlias = `vnc-${name}`;\n if (await portlessAlias(vncAlias, vncHostPort)) {\n portlessVncAliasName = vncAlias;\n portlessVncUrl = await portlessGetUrl(vncAlias);\n log(`portless alias ${portlessVncUrl} -> 127.0.0.1:${String(vncHostPort)}`);\n } else {\n log('portless vnc alias failed (best-effort) — VNC still reachable on the loopback URL');\n }\n }\n if (!portless.proxyRunning && (portlessAliasName || portlessVncAliasName)) {\n log(`portless proxy not running — start it with \\`${portlessStartHint()}\\``);\n }\n }\n }\n } catch (err) {\n log(`portless: ${err instanceof Error ? err.message : String(err)} (best-effort, ignored)`);\n }\n }\n\n // Final record: the provisional base plus the fields only known after the\n // container was up (published host ports, portless aliases, applied carry).\n const record: BoxRecord = {\n ...baseRecord,\n carry: carrySummary,\n vncHostPort: vncHostPort ?? undefined,\n webHostPort: webHostPort ?? undefined,\n sshHostPort: ssh.sshHostPort ?? undefined,\n // Only advertise an ssh-config alias when sshd actually bound (`up`). Docker\n // publishes the -p 0:22 host port regardless, so gating on the port alone\n // would point `~/.ssh/config` at a dead loopback port when sshd failed to\n // start. A later `start`/`open` re-runs setUpBoxSshd and records it once up.\n ssh:\n ssh.up && ssh.sshHostPort\n ? { host: '127.0.0.1', user: 'vscode', identityFile: ssh.identityFile, port: ssh.sshHostPort }\n : undefined,\n portlessAlias: portlessAliasName,\n portlessUrl,\n portlessVncAlias: portlessVncAliasName,\n portlessVncUrl,\n };\n await recordBox(record);\n // Regenerate `~/.agentbox/ssh/config` so `ssh <box>`, `agentbox open` (sshfs)\n // and the Codex launcher have a live alias. Reads state.json (just written) —\n // best-effort, never fail create over the ssh-config write.\n if (record.ssh) {\n try {\n await syncAgentboxSshConfig();\n } catch (err) {\n log(`ssh-config sync failed (best-effort): ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return { record, imageBuilt: built, resync: resyncResult };\n}\n","import { execInBox } from './docker.js';\n\nexport interface DockerdLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Shared image-cache volume across boxes. When a box is created with\n * `dockerCacheShared=true`, its in-box dockerd's data root is this volume\n * instead of the per-box `agentbox-docker-<id>` volume. Mutually exclusive at\n * runtime: only one box can hold the lock on `/var/lib/docker` at a time —\n * dockerd's own boltdb lock will refuse a second start. This is a power-user\n * feature for users who run boxes serially and want pulled layers to persist\n * across recreations; documented as such on the CLI flag.\n */\nexport const SHARED_DOCKER_CACHE_VOLUME = 'agentbox-docker-cache';\n\nexport function dockerVolumeName(boxId: string, shared: boolean): string {\n return shared ? SHARED_DOCKER_CACHE_VOLUME : `agentbox-docker-${boxId}`;\n}\n\n/**\n * Spawn the in-container dockerd via `/usr/local/bin/agentbox-dockerd-start`\n * detached, then poll for `/var/run/docker.sock` to become accept()-able.\n * Best-effort, mirroring {@link launchVncDaemon} — failure is logged but\n * doesn't fail box creation. Default timeout 30s: first start has to\n * initialize iptables + the storage graphdriver, which is slower than the\n * VNC stack.\n */\nexport async function launchDockerdDaemon(\n container: string,\n timeoutMs = 30_000,\n): Promise<DockerdLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-dockerd-start'], {\n user: 'root',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n [\n 'bash',\n '-lc',\n '[ -S /var/run/docker.sock ] && docker -H unix:///var/run/docker.sock info >/dev/null 2>&1',\n ],\n { user: 'root' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 200));\n }\n return { up: false, reason: `dockerd did not become ready within ${String(timeoutMs)}ms` };\n}\n","import { randomBytes } from 'node:crypto';\nimport { execInBox } from './docker.js';\n\nexport interface VncLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Spawn the in-container VNC supervisor (`/usr/local/bin/agentbox-vnc-start`)\n * detached, then poll the container's TCP 6080 to confirm websockify is up.\n * Best-effort, mirroring {@link launchCtlDaemon} — failure is logged but\n * doesn't fail box creation. The password reaches the script through the\n * container's AGENTBOX_VNC_PASSWORD env, set at `docker run` time, so we don't\n * need `-e` on the exec (and the re-launch path on `agentbox start` works\n * without it too).\n */\nexport async function launchVncDaemon(\n container: string,\n timeoutMs = 5000,\n): Promise<VncLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-vnc-start'], {\n user: 'vscode',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n ['bash', '-lc', '(echo > /dev/tcp/127.0.0.1/6080) 2>/dev/null'],\n { user: 'vscode' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 150));\n }\n return { up: false, reason: `websockify did not bind 6080 within ${String(timeoutMs)}ms` };\n}\n\nconst VNC_PASSWORD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n\n/**\n * 8-char password from a 62-symbol alphabet. The 8-char cap is a real RFB\n * protocol limit — VncAuth truncates at compare time, so longer passwords give\n * no security gain. 62^8 ≈ 47 bits; adequate for the loopback-bound surface\n * we expose (host port pinned to 127.0.0.1 + OrbStack's name-based routing,\n * neither of which is reachable from off-host without explicit tunnelling).\n */\nexport function generateVncPassword(): string {\n const bytes = randomBytes(8);\n let out = '';\n for (let i = 0; i < 8; i++) {\n out += VNC_PASSWORD_ALPHABET[bytes[i]! % VNC_PASSWORD_ALPHABET.length];\n }\n return out;\n}\n\n/**\n * Container port the VNC web client (noVNC) binds inside the box. Fixed today;\n * stored on BoxRecord for future-proofing if we ever support multiple displays.\n */\nexport const VNC_CONTAINER_PORT = 6080;\n\nexport interface VncUrls {\n /** OrbStack name-based URL, e.g. http://agentbox-foo.orb.local:6080/... Present only on OrbStack hosts. */\n orbUrl?: string;\n /** Loopback URL via the auto-allocated host port, e.g. http://127.0.0.1:54321/... Present whenever vncHostPort is known. */\n loopbackUrl?: string;\n /** Portless URL, e.g. https://vnc-mybox.localhost/vnc.html?... Present when `portlessVncAlias` is set on the record. */\n portlessUrl?: string;\n}\n\n/**\n * Build the noVNC URLs for a box, given the box record + (host engine).\n * `engine === 'orbstack'` triggers the `<container>.orb.local:6080` route;\n * a stored Portless alias gives `vnc-<name>.localhost`; either engine\n * produces the loopback URL when the host port is resolved.\n * Returns an empty object when VNC isn't enabled or the password isn't known.\n */\nexport function buildVncUrls(\n record: {\n container?: string;\n vncEnabled?: boolean;\n vncHostPort?: number;\n vncContainerPort?: number;\n vncPassword?: string;\n portlessVncAlias?: string;\n portlessVncUrl?: string;\n },\n engine: 'orbstack' | 'docker-desktop' | 'other',\n): VncUrls {\n if (!record.vncEnabled || !record.vncPassword) return {};\n const containerPort = record.vncContainerPort ?? VNC_CONTAINER_PORT;\n const qs = `autoconnect=1&password=${encodeURIComponent(record.vncPassword)}`;\n const urls: VncUrls = {};\n if (engine === 'orbstack' && record.container) {\n urls.orbUrl = `http://${record.container}.orb.local:${String(containerPort)}/vnc.html?${qs}`;\n }\n if (record.vncHostPort) {\n urls.loopbackUrl = `http://127.0.0.1:${String(record.vncHostPort)}/vnc.html?${qs}`;\n }\n if (record.portlessVncAlias) {\n const base = record.portlessVncUrl ?? `https://${record.portlessVncAlias}.localhost`;\n urls.portlessUrl = `${base}/vnc.html?${qs}`;\n }\n return urls;\n}\n","import { execa } from 'execa';\nimport { mintSshKey } from '@agentbox/sandbox-core';\nimport { execInBox, publishedHostPort } from './docker.js';\n\n/**\n * Container port the in-box sshd binds. Fixed; the host publishes it on an\n * ephemeral `127.0.0.1:<hostPort>` (`docker run -p 127.0.0.1:0:22`) so it's\n * loopback-only. Stored on the BoxRecord as `sshContainerPort` for symmetry\n * with the VNC/web ports.\n */\nexport const SSH_CONTAINER_PORT = 22;\n\nexport interface SshLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * Spawn the in-container sshd (`/usr/local/bin/agentbox-sshd-start`) detached as\n * root, then poll container TCP 22 to confirm it bound. Mirrors\n * {@link launchVncDaemon} — best-effort, failure is logged but doesn't fail box\n * creation, and it's idempotent so `agentbox start` can call it blindly. Runs\n * as root (sshd manages /run/sshd + host keys), unlike the vscode-run VNC stack.\n */\nexport async function launchSshdDaemon(\n container: string,\n timeoutMs = 5000,\n): Promise<SshLaunchResult> {\n const result = await execInBox(container, ['/usr/local/bin/agentbox-sshd-start'], {\n user: 'root',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const probe = await execInBox(\n container,\n ['bash', '-lc', '(echo > /dev/tcp/127.0.0.1/22) 2>/dev/null'],\n { user: 'vscode' },\n );\n if (probe.exitCode === 0) return { up: true };\n await new Promise((r) => setTimeout(r, 150));\n }\n return { up: false, reason: `sshd did not bind 22 within ${String(timeoutMs)}ms` };\n}\n\n/**\n * Install `publicKey` as vscode's sole authorized_keys entry so the host's\n * per-box private key can SSH in. Written as root (chown to vscode, 0700 dir /\n * 0600 file) — mirrors {@link writeBoxEnvFile}. Overwrites rather than appends:\n * one box, one key, and a fresh key each create means no stale entries linger.\n */\nexport async function installAuthorizedKey(\n container: string,\n publicKey: string,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n const script =\n 'set -e; ' +\n 'install -d -m 700 -o vscode -g vscode /home/vscode/.ssh; ' +\n 'cat > /home/vscode/.ssh/authorized_keys; ' +\n 'chown vscode:vscode /home/vscode/.ssh/authorized_keys; ' +\n 'chmod 600 /home/vscode/.ssh/authorized_keys';\n const result = await execa(\n 'docker',\n ['exec', '--user', 'root', '-i', container, 'sh', '-c', script],\n { input: publicKey.endsWith('\\n') ? publicKey : `${publicKey}\\n`, reject: false },\n );\n if (result.exitCode !== 0) {\n return {\n ok: false,\n reason: `docker exec failed (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n };\n }\n return { ok: true };\n}\n\nexport interface BoxSshSetup {\n /** Ephemeral loopback host port Docker mapped to container :22, or null. */\n sshHostPort: number | null;\n /** Absolute path to the per-box private key (the ssh-config IdentityFile). */\n identityFile: string;\n up: boolean;\n reason?: string;\n}\n\n/**\n * End-to-end sshd bring-up for a box: mint (or reuse) the per-box key under\n * `sshDir`, install its public half into the box's authorized_keys, launch\n * sshd, and resolve the published loopback host port. Used on both create and\n * `agentbox start` — `mintSshKey` reuses an existing key and the install +\n * launch are idempotent, so the restart path just re-resolves the (reallocated)\n * host port. Best-effort: a failure surfaces via `up`/`reason`, never throws.\n */\nexport async function setUpBoxSshd(\n container: string,\n sshDir: string,\n comment: string,\n): Promise<BoxSshSetup> {\n const key = await mintSshKey(sshDir, comment);\n const installed = await installAuthorizedKey(container, key.publicKey);\n if (!installed.ok) {\n return { sshHostPort: null, identityFile: key.privatePath, up: false, reason: installed.reason };\n }\n const launch = await launchSshdDaemon(container);\n const sshHostPort = await publishedHostPort(container, SSH_CONTAINER_PORT);\n return { sshHostPort, identityFile: key.privatePath, up: launch.up, reason: launch.reason };\n}\n","/**\n * The single container port AgentBox reserves + publishes for a box's web\n * service. The `-p 127.0.0.1:0:80` mapping is created unconditionally at\n * `create` (immutable after `docker run`); the in-box supervisor forwards :80\n * to the `expose:`-flagged service's port once `agentbox.yaml` is set. Mirrors\n * `VNC_CONTAINER_PORT`. Must equal `RESERVED_WEB_PORT` in @agentbox/ctl.\n */\nexport const WEB_CONTAINER_PORT = 80;\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { CheckResult } from '@agentbox/sandbox-core';\n\n/**\n * Portless (https://portless.sh) — a host reverse-proxy that maps\n * `portless alias <name> <port>` to a stable https://<name>.localhost URL.\n *\n * AgentBox uses it to give a box a friendly web URL on the host. Two\n * providers consume these helpers today:\n * - sandbox-docker: aliases the docker port-published web port\n * (`<name>.localhost -> 127.0.0.1:<webHostPort>`). In-box browser\n * remaps `<name>.localhost` to `host.docker.internal` because the box\n * is in a separate net namespace.\n * - sandbox-hetzner: aliases the SSH-forwarded loopback port for the\n * remote VPS's WebProxy. In-box browser remaps to `127.0.0.1` because\n * the box (= VPS) has no separate net namespace.\n *\n * The file lives in sandbox-docker for historical reasons but is shared via\n * a re-export from `@agentbox/sandbox-cloud` (Phase 1 of the hetzner work).\n * The dep direction is `sandbox-cloud → sandbox-docker`, so this is the\n * canonical home; we can't move it the other way without cycle-fixing\n * package.json wiring.\n *\n * Portless is user-installed; AgentBox never bundles, installs, or starts\n * it — every function here is best-effort and must never throw: a Portless\n * failure degrades to the loopback URL.\n */\n\n/**\n * The Portless CLI surface AgentBox depends on. Pinned here so a rename in a\n * future Portless release is a one-line fix. Verified against portless 0.13.0.\n */\nconst PORTLESS_BIN = 'portless';\nconst SUB_VERSION = ['--version'];\nconst SUB_ALIAS = 'alias';\nconst SUB_ALIAS_REMOVE = '--remove';\nconst SUB_GET = 'get';\n\n/**\n * Port AgentBox starts the Portless proxy on when it sets one up itself.\n * A port >= 1024 needs no root (Portless's own documented no-sudo port);\n * combined with `--no-tls` the whole setup runs without a single prompt.\n */\nexport const PORTLESS_PROXY_PORT = 1355;\n\nexport interface PortlessState {\n /** `portless` resolved on PATH and answered `--version`. */\n installed: boolean;\n /** Portless version string, when installed. */\n version?: string;\n /**\n * A live proxy daemon was found. Note `portless alias` writes the route\n * regardless — the proxy only has to be up for the URL to actually resolve.\n * `false` also covers \"could not tell\".\n */\n proxyRunning: boolean;\n}\n\nlet cached: PortlessState | null = null;\n\n/**\n * Probe the host for Portless. Cached per-process like `detectEngine` — the\n * install state cannot change mid-command and the proxy state is only used\n * for a soft hint.\n */\nexport async function detectPortless(): Promise<PortlessState> {\n if (cached !== null) return cached;\n try {\n const ver = await execa(PORTLESS_BIN, SUB_VERSION, { reject: false });\n if (ver.exitCode !== 0) {\n cached = { installed: false, proxyRunning: false };\n return cached;\n }\n cached = {\n installed: true,\n version: (ver.stdout ?? '').trim() || undefined,\n proxyRunning: await isProxyRunning(),\n };\n } catch {\n cached = { installed: false, proxyRunning: false };\n }\n return cached;\n}\n\n/**\n * Drop the per-process probe cache so the next `detectPortless()` re-probes.\n * Called after an install / proxy-start changes the host state, and by tests.\n */\nexport function resetPortlessCache(): void {\n cached = null;\n}\n\n/**\n * Register (or re-point) a static route so the proxy serves\n * https://<name>.localhost -> 127.0.0.1:<port>. Returns whether Portless\n * accepted it. The route is written even when the proxy is down.\n */\nexport async function portlessAlias(name: string, port: number): Promise<boolean> {\n try {\n const r = await execa(PORTLESS_BIN, [SUB_ALIAS, name, String(port)], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/** Remove a static route registered by `portlessAlias`. */\nexport async function portlessUnalias(name: string): Promise<boolean> {\n try {\n const r = await execa(PORTLESS_BIN, [SUB_ALIAS, SUB_ALIAS_REMOVE, name], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve the user-facing URL for a registered route. Falls back to the\n * deterministic `https://<name>.localhost` when `portless get` is unavailable\n * (proxy down, route not yet registered, Portless missing).\n */\nexport async function portlessGetUrl(name: string): Promise<string> {\n const fallback = `https://${name}.localhost`;\n try {\n const r = await execa(PORTLESS_BIN, [SUB_GET, name], { reject: false });\n const out = (r.stdout ?? '').trim();\n if (r.exitCode === 0 && /^https?:\\/\\//.test(out)) return out;\n } catch {\n // fall through\n }\n return fallback;\n}\n\n/** Command the user should run to install Portless. */\nexport function portlessInstallHint(): string {\n return 'npm install -g portless';\n}\n\n/** Command the user should run to bring the Portless proxy up. */\nexport function portlessStartHint(): string {\n return 'portless proxy start';\n}\n\n/**\n * A `doctor` row (see `@agentbox/sandbox-core`'s `CheckResult`) for a provider\n * that benefits from a host Portless proxy — docker on plain Docker Desktop /\n * Linux engine (OrbStack serves `.orb.local` natively, so its `doctorChecks`\n * skips this) and hetzner (the SSH-forwarded loopback only becomes a\n * `<box>.localhost` alias with host Portless). Pure — the caller passes the\n * already-probed state so this stays offline and testable.\n */\nexport function portlessDoctorRow(state: PortlessState): CheckResult {\n if (!state.installed) {\n return {\n label: 'portless',\n status: 'warn',\n detail: 'not installed — box web URLs fall back to raw loopback ports',\n hint: `recommended: \\`${portlessInstallHint()}\\` for https://<box>.localhost URLs`,\n };\n }\n if (!state.proxyRunning) {\n return {\n label: 'portless',\n status: 'warn',\n detail: 'installed, proxy not running',\n hint: `start it: \\`${portlessStartHint()}\\``,\n };\n }\n return {\n label: 'portless',\n status: 'ok',\n detail: state.version ? `running · v${state.version}` : 'running',\n };\n}\n\nexport interface PortlessBrowserEnvOptions {\n /**\n * Where Chromium should resolve `<box-name>.localhost` to when running\n * inside the box. Docker boxes pass `host.docker.internal` (the host\n * gateway baked into every container's `/etc/hosts`). Hetzner boxes —\n * where the box *is* the VPS and WebProxy listens on the VPS's loopback —\n * pass `127.0.0.1`.\n */\n mapTarget: string;\n}\n\n/**\n * Box env that makes the in-box browser (agent-browser → Chromium) load the\n * box's Portless `<name>.localhost` URL via the *host* Portless proxy — so the\n * web app is reachable on the exact URL the host browser uses.\n *\n * Chromium hard-codes `*.localhost` → loopback and ignores `/etc/hosts`, so\n * `--host-resolver-rules` (passed through agent-browser's `AGENT_BROWSER_ARGS`)\n * remaps the box's hostname to `opts.mapTarget` — the address that, from\n * inside the box, actually reaches the host Portless proxy.\n * `IGNORE_HTTPS_ERRORS` covers a TLS host proxy whose self-signed CA the box\n * doesn't trust.\n */\nexport function portlessBrowserEnv(\n boxName: string,\n opts: PortlessBrowserEnvOptions,\n): Record<string, string> {\n return {\n AGENT_BROWSER_ARGS: `--host-resolver-rules=MAP ${boxName}.localhost ${opts.mapTarget}`,\n AGENT_BROWSER_IGNORE_HTTPS_ERRORS: '1',\n };\n}\n\n/** Install the Portless CLI globally (`npm install -g portless`). Never throws. */\nexport async function installPortless(): Promise<boolean> {\n try {\n const r = await execa('npm', ['install', '-g', 'portless'], { reject: false });\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Start a Portless proxy with no TLS on the no-root port (`PORTLESS_PROXY_PORT`)\n * — `portless proxy start --no-tls -p <port>`. No sudo, no CA-trust prompt.\n * Idempotent: Portless reports \"already running\" (exit 0) if one is already up.\n * Never throws.\n */\nexport async function startPortlessProxy(): Promise<boolean> {\n try {\n const r = await execa(\n PORTLESS_BIN,\n ['proxy', 'start', '--no-tls', '-p', String(PORTLESS_PROXY_PORT)],\n { reject: false },\n );\n return r.exitCode === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Absolute path to the `portless` binary. Needed because the macOS elevation\n * shell (`osascript … with administrator privileges`) runs with a minimal PATH\n * (`/usr/bin:/bin:/usr/sbin:/sbin`) that misses nvm / user npm prefixes where\n * `portless` usually lives. Falls back to the bare name when it can't resolve.\n */\nasync function resolvePortlessBin(): Promise<string> {\n try {\n // `command -v` resolves PATH the same way the shell would for the current\n // (login) environment, unlike the stripped-down elevated shell.\n const r = await execa('command', ['-v', PORTLESS_BIN], { reject: false, shell: true });\n const out = (r.stdout ?? '').trim();\n if (r.exitCode === 0 && out.startsWith('/')) return out;\n } catch {\n // fall through\n }\n return PORTLESS_BIN;\n}\n\n/** Result of a root proxy-start attempt. */\nexport type RootProxyStartResult =\n | 'started' // proxy is up on :443 (or was already)\n | 'cancelled' // user dismissed the elevation prompt — caller should fall back\n | 'failed'; // elevation ran but the proxy did not come up\n\n/** Quote a string for embedding inside an AppleScript double-quoted literal. */\nfunction escapeForAppleScript(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Single-quote a string for `/bin/sh`. Needed for the resolved portless path,\n * which can live under a home dir with spaces (`/Users/Jo Smith/.nvm/…`) that\n * the elevated shell would otherwise word-split. Single quotes survive the\n * outer AppleScript double-quoted literal untouched.\n */\nfunction shellSingleQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Start the default Portless proxy — HTTPS on :443 — which requires root.\n * Portless self-elevates via its own `sudo`, so all we do is run\n * `portless proxy start && portless trust` once, as root, surfacing a single\n * password prompt. `trust` is bundled so the host browser trusts the\n * self-signed CA (otherwise 443 shows cert warnings); it is idempotent.\n *\n * On macOS the prompt is the native GUI dialog (`osascript … with administrator\n * privileges`); elsewhere we inherit the terminal so Portless's own `sudo`\n * prompt is answerable. Never throws. Returns `'cancelled'` when the user\n * dismisses the dialog so the caller can fall back to the no-root port.\n */\nexport async function startPortlessProxyRoot(): Promise<RootProxyStartResult> {\n const bin = await resolvePortlessBin();\n try {\n if (process.platform === 'darwin') {\n // Both commands run in one elevated shell so the user is asked once.\n const q = shellSingleQuote(bin);\n const shellCmd = `${q} proxy start && ${q} trust`;\n const script =\n `do shell script \"${escapeForAppleScript(shellCmd)}\" ` +\n `with administrator privileges ` +\n `with prompt \"AgentBox wants to start the Portless proxy on port 443.\"`;\n const r = await execa('osascript', ['-e', script], { reject: false });\n if (r.exitCode === 0) return 'started';\n // osascript reports \"User canceled. (-128)\" when the dialog is dismissed.\n if (/User canceled|-128/i.test(r.stderr ?? '')) return 'cancelled';\n return 'failed';\n }\n // Non-macOS: let Portless's own sudo prompt reach the terminal.\n const r = await execa(bin, ['proxy', 'start'], { reject: false, stdio: 'inherit' });\n if (r.exitCode !== 0) return 'failed';\n await execa(bin, ['trust'], { reject: false, stdio: 'inherit' });\n return 'started';\n } catch {\n return 'failed';\n }\n}\n\n/**\n * Candidate Portless state directories. `$PORTLESS_STATE_DIR` wins outright;\n * otherwise Portless keeps state in `~/.portless` — even for the root :443\n * proxy, whose `proxy.pid` there stays owned by the invoking user (verified\n * against portless 0.13.0). `/tmp/portless` is retained as a legacy fallback.\n */\nfunction portlessStateDirCandidates(): string[] {\n const env = process.env['PORTLESS_STATE_DIR'];\n if (env && env.trim().length > 0) return [env.trim()];\n return ['/tmp/portless', join(homedir(), '.portless')];\n}\n\n/**\n * Whether `pid` names a live process. `process.kill(pid, 0)` succeeds for a\n * process we own; it throws `EPERM` for one owned by another user (the proxy\n * runs as root when bound to :443 via sudo) — that still means it is alive.\n * Only `ESRCH` (\"no such process\") is a dead pid.\n */\nfunction pidAlive(pid: number): boolean {\n if (!Number.isFinite(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0); // signal 0 = existence/permission check only\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Read `<dir>/proxy.pid`, returning the pid or null when absent/garbage. */\nasync function readProxyPid(dir: string): Promise<number | null> {\n try {\n const raw = await readFile(join(dir, 'proxy.pid'), 'utf8');\n const pid = Number.parseInt(raw.trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The Portless state directory whose `proxy.pid` names a live process — i.e.\n * where the *running* proxy keeps its route registry. `null` when no proxy is\n * up. This is the authoritative way to pick between `/tmp/portless` and\n * `~/.portless` (they can both exist; only one has the live proxy).\n */\nasync function findLivePortlessStateDir(): Promise<string | null> {\n for (const dir of portlessStateDirCandidates()) {\n const pid = await readProxyPid(dir);\n if (pid !== null && pidAlive(pid)) return dir;\n }\n return null;\n}\n\n/**\n * Resolve the host Portless state directory to bind-mount into a box (so the\n * in-box `portless` CLI shares the host's route registry). Precedence:\n * 1. an explicit override — the `portless.stateDir` config key;\n * 2. `$PORTLESS_STATE_DIR`;\n * 3. the directory of the *running* proxy (authoritative);\n * 4. whichever of `~/.portless` / `/tmp/portless` already exists;\n * 5. `~/.portless` as the final fallback.\n * Does not create the directory.\n */\nexport async function resolvePortlessHostStateDir(override?: string): Promise<string> {\n if (override && override.trim().length > 0) return override.trim();\n const env = process.env['PORTLESS_STATE_DIR'];\n if (env && env.trim().length > 0) return env.trim();\n const live = await findLivePortlessStateDir();\n if (live) return live;\n const home = join(homedir(), '.portless');\n if (existsSync(home)) return home;\n if (existsSync('/tmp/portless')) return '/tmp/portless';\n return home;\n}\n\n/**\n * Best-effort: is a Portless proxy currently running on the host. A daemonized\n * proxy writes a live `proxy.pid`, but a `--foreground` proxy (and some daemon\n * modes) does not — so we also scan the process table. Either signal counts.\n */\nasync function isProxyRunning(): Promise<boolean> {\n if ((await findLivePortlessStateDir()) !== null) return true;\n try {\n const r = await execa('pgrep', ['-f', 'portless proxy'], { reject: false });\n return r.exitCode === 0 && (r.stdout ?? '').trim().length > 0;\n } catch {\n return false;\n }\n}\n","import { execa } from 'execa';\nimport { mkdir, readdir, rm, stat } from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { sanitizeMnemonic } from '@agentbox/config';\n\n/**\n * Directories whose contents are either platform-specific (built native modules,\n * compiled outputs) or large enough to be wasteful to include in a frozen\n * workspace snapshot. Pruned from the snapshot tree *after* the APFS clone\n * — removing CoW-cloned entries is essentially free.\n */\nexport const EXCLUDE_DIRS: ReadonlySet<string> = new Set([\n 'node_modules',\n '.next',\n '.nuxt',\n '.turbo',\n '.svelte-kit',\n 'dist',\n 'build',\n 'out',\n 'target',\n '.venv',\n '__pycache__',\n '.cache',\n '.parcel-cache',\n]);\n\nexport const SNAPSHOTS_ROOT = join(homedir(), '.agentbox', 'snapshots');\n\n/**\n * `<id>-<n>-<mnemonic>` when `projectIndex` is set (post-feature boxes — all\n * new boxes), else `<id>-<mnemonic>` (legacy pre-feature fallback). Mirrors\n * `boxDirSegment` in `host-export.ts` — kept structurally compatible so the\n * snapshot dir can be looked up alongside its box dir.\n */\nexport function snapshotPathFor(box: { id: string; name: string; projectIndex?: number }): string {\n const mnemonic = sanitizeMnemonic(box.name);\n const n = box.projectIndex;\n const segment =\n typeof n === 'number' && Number.isFinite(n) && n > 0\n ? `${box.id}-${String(n)}-${mnemonic}`\n : `${box.id}-${mnemonic}`;\n return join(SNAPSHOTS_ROOT, segment);\n}\n\n/**\n * Walk a directory tree and return absolute paths of every directory whose\n * basename matches `EXCLUDE_DIRS`. Does not descend into a matched directory.\n * Pure (modulo `fs.readdir`) — easy to unit-test against a fixture tree.\n */\nexport async function findExcludedDirs(\n root: string,\n excluded: ReadonlySet<string> = EXCLUDE_DIRS,\n): Promise<string[]> {\n const matches: string[] = [];\n const walk = async (dir: string): Promise<void> => {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const abs = join(dir, entry.name);\n if (excluded.has(entry.name)) {\n matches.push(abs);\n continue; // do not descend\n }\n await walk(abs);\n }\n };\n await walk(root);\n return matches;\n}\n\nexport interface CreateSnapshotOptions {\n source: string;\n destination: string;\n excluded?: ReadonlySet<string>;\n}\n\nexport interface CreateSnapshotResult {\n destination: string;\n prunedPaths: string[];\n}\n\n/**\n * Create a frozen workspace snapshot. On macOS (APFS) this is an instant CoW\n * clone via `cp -cR`; on other platforms it falls back to plain `cp -R`\n * (slow, but functional — the production fallback will be `rsync --exclude`).\n *\n * After the copy, prune all `EXCLUDE_DIRS` directories so the snapshot is free\n * of platform-specific artifacts before it becomes the overlay's lower layer.\n */\nexport async function createSnapshot(opts: CreateSnapshotOptions): Promise<CreateSnapshotResult> {\n const source = resolve(opts.source);\n const destination = resolve(opts.destination);\n const excluded = opts.excluded ?? EXCLUDE_DIRS;\n\n await mkdir(SNAPSHOTS_ROOT, { recursive: true });\n\n // `cp -c` only exists on macOS and is the APFS clone flag.\n const cpArgs = platform() === 'darwin' ? ['-cR'] : ['-R'];\n await execa('cp', [...cpArgs, `${source}/`, destination]);\n\n const toPrune = await findExcludedDirs(destination, excluded);\n await Promise.all(toPrune.map((p) => rm(p, { recursive: true, force: true })));\n\n return { destination, prunedPaths: toPrune };\n}\n\n/** Guard used by tests + by `create.ts` when we don't want to clobber a path. */\nexport async function snapshotExists(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n","import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { execa } from 'execa';\nimport {\n hashProjectPath,\n projectDirSegment,\n sanitizeMnemonic,\n setConfigValue,\n} from '@agentbox/config';\nimport { readCliStamp } from '@agentbox/sandbox-core';\nimport { execInBox, removeImage } from './docker.js';\nimport { DEFAULT_BOX_IMAGE } from './image.js';\nimport {\n computeDockerContextFingerprint,\n readPreparedDockerState,\n} from './prepared-state.js';\nimport type { BoxRecord, GitWorktreeRecord } from './state.js';\n\nexport const CHECKPOINTS_ROOT = join(homedir(), '.agentbox', 'checkpoints');\n\n/**\n * All per-project checkpoint *image* tags share this prefix. `prune --all`\n * allowlists by it (parallel to the old volume prefix) and `agentbox status`\n * /`inspect` recognizes a box's image as a checkpoint from this prefix.\n */\nexport const CHECKPOINT_IMAGE_PREFIX = 'agentbox-ckpt-';\n\nexport type CheckpointType = 'layered' | 'flattened';\n\n/**\n * Deterministic image tag for a project checkpoint. The repository segment is\n * keyed on the project root (same hash the per-project config dir uses) and\n * carries a mnemonic suffix so `docker images` reads self-describing. The\n * mnemonic is joined with `_` (not `-`) so the leading 16 hex chars remain\n * unambiguous and the existing `agentbox-ckpt-*` prune glob still matches.\n * Pure — unit-tested directly.\n */\nexport function checkpointImageTag(projectRoot: string, name: string): string {\n const mnemonic = sanitizeMnemonic(basename(projectRoot));\n return `${CHECKPOINT_IMAGE_PREFIX}${hashProjectPath(projectRoot)}_${mnemonic}:${name}`;\n}\n\nexport interface CheckpointManifest {\n /**\n * Schema history:\n * 2 — original fields (image, parents, base, worktrees, source*, createdAt)\n * 3 — adds `baseProvider`, `baseFingerprint`, `cliVersion`. A checkpoint\n * captured before the rebuild that produced the *current* base\n * image will have a stale `baseFingerprint`; the restore path warns\n * loudly so the user knows the box won't see the new base layers\n * until the checkpoint is removed and recaptured.\n */\n schema: 2 | 3;\n name: string;\n type: CheckpointType;\n /** Local Docker image tag this checkpoint resolves to (`agentbox-ckpt-<hash>:<name>`). */\n image: string;\n /**\n * For a `layered` checkpoint, the older checkpoint refs this commit stacks\n * on — i.e. the chain the *source* box was built from (upper-most first,\n * base-most last). `[]` for a `flattened` checkpoint (self-contained,\n * exported+rebuilt as a single layer) or a layered checkpoint taken from a\n * box that itself started from bare host code.\n */\n parents: string[];\n base: 'worktree' | 'workspace';\n sourceBoxId: string;\n sourceBoxName: string;\n /**\n * Source box's per-worktree paths so a restored box can re-bind\n * `/workspace` (and `/workspace/<sub>`) without rerunning `seedWorkspace`.\n * `docker commit` does NOT capture bind-mounted content, so the captured\n * image's `/workspace` is empty — the actual worktree files live under\n * `gitWorktreePath` (preserved in the image's writable layer). On restore,\n * `bindWorktrees` reads these to wire the binds back. Absent only for\n * no-git boxes (their `seedWorkspaceFromDir` puts files directly in\n * `/workspace`, which the bind logic doesn't touch).\n */\n worktrees?: GitWorktreeRecord[];\n /**\n * Provider whose base-image fingerprint this checkpoint was captured\n * against. Schema-3+ only. Always `'docker'` today (docker is the only\n * provider with local checkpoints); cloud-provider checkpoints will set\n * it accordingly when they land.\n */\n baseProvider?: 'docker' | 'daytona' | 'hetzner';\n /**\n * Build-context fingerprint of the base image at the time the checkpoint\n * was captured. Schema-3+ only. Missing → schema 2 → \"unknown\n * fingerprint\" (caller surfaces a softer \"this checkpoint predates\n * versioning\" warning).\n */\n baseFingerprint?: string;\n /** CLI version that captured the checkpoint. Schema-3+ only. */\n cliVersion?: string;\n createdAt: string;\n}\n\nexport interface CheckpointInfo {\n name: string;\n /** Host dir holding `manifest.json` (`~/.agentbox/checkpoints/<hash>/<name>`). */\n dir: string;\n manifest: CheckpointManifest;\n}\n\nexport function projectCheckpointsDir(projectRoot: string): string {\n return join(CHECKPOINTS_ROOT, projectDirSegment(projectRoot));\n}\n\nfunction checkpointDir(projectRoot: string, name: string): string {\n return join(projectCheckpointsDir(projectRoot), name);\n}\n\nasync function readManifest(dir: string): Promise<CheckpointManifest | null> {\n try {\n const raw = await readFile(join(dir, 'manifest.json'), 'utf8');\n const m = JSON.parse(raw) as CheckpointManifest;\n // Accept schema 2 (legacy — no baseFingerprint, restore warns softly)\n // and schema 3 (current — full versioning). Anything else is treated\n // as unreadable so an opaque file can't break list/resolve.\n if (m.schema !== 2 && m.schema !== 3) return null;\n return m;\n } catch {\n return null;\n }\n}\n\n/**\n * Read every valid checkpoint manifest directly under `root` (a project's\n * `<hash>-<mnemonic>` dir), sorted by `createdAt`. Shared by the scoped and\n * global listers. Missing root / unreadable manifests are skipped.\n */\nasync function listCheckpointsInDir(root: string): Promise<CheckpointInfo[]> {\n let entries: string[];\n try {\n entries = (await readdir(root, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CheckpointInfo[] = [];\n for (const name of entries) {\n const dir = join(root, name);\n const manifest = await readManifest(dir);\n if (manifest) out.push({ name, dir, manifest });\n }\n out.sort((a, b) => a.manifest.createdAt.localeCompare(b.manifest.createdAt));\n return out;\n}\n\nexport async function listCheckpoints(projectRoot: string): Promise<CheckpointInfo[]> {\n return listCheckpointsInDir(projectCheckpointsDir(projectRoot));\n}\n\nexport interface CheckpointProjectGroup {\n /** `<hash>-<mnemonic>` dir name under CHECKPOINTS_ROOT. */\n segment: string;\n items: CheckpointInfo[];\n}\n\n/**\n * Every project's docker checkpoints, one group per project dir. Mirrors\n * `listAllCheckpointImages`' two-level scan but returns the full manifests so\n * `checkpoints -g` can render them. Best-effort: missing root / unreadable\n * project dirs are skipped, and segments with zero valid manifests are dropped.\n */\nexport async function listAllCheckpoints(): Promise<CheckpointProjectGroup[]> {\n let segments: string[];\n try {\n segments = (await readdir(CHECKPOINTS_ROOT, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out: CheckpointProjectGroup[] = [];\n for (const segment of segments) {\n const items = await listCheckpointsInDir(join(CHECKPOINTS_ROOT, segment));\n if (items.length > 0) out.push({ segment, items });\n }\n return out;\n}\n\nexport async function resolveCheckpoint(\n projectRoot: string,\n ref: string,\n): Promise<CheckpointInfo | null> {\n const dir = checkpointDir(projectRoot, ref);\n const manifest = await readManifest(dir);\n if (!manifest) return null;\n return { name: ref, dir, manifest };\n}\n\n/**\n * Walk every per-project checkpoint manifest under CHECKPOINTS_ROOT and\n * return the union of their `image` tags. Used by `pruneBoxes({ all: true })`\n * to keep an image alive as long as any manifest on disk points at it —\n * destroy leaves the checkpoint behind by design, and the user expects to\n * still be able to start a new box from it long after the source box is gone.\n *\n * Best-effort, matching listSnapshotDirs / listBoxDirs in lifecycle.ts:\n * missing root, unreadable / non-schema-2 manifests, and non-directory\n * entries at any level are all skipped silently.\n */\nexport async function listAllCheckpointImages(): Promise<string[]> {\n let projectDirs: string[];\n try {\n projectDirs = (await readdir(CHECKPOINTS_ROOT, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n return [];\n }\n const out = new Set<string>();\n for (const proj of projectDirs) {\n const projPath = join(CHECKPOINTS_ROOT, proj);\n let names: string[];\n try {\n names = (await readdir(projPath, { withFileTypes: true }))\n .filter((e) => e.isDirectory())\n .map((e) => e.name);\n } catch {\n continue;\n }\n for (const name of names) {\n const manifest = await readManifest(join(projPath, name));\n if (manifest) out.add(manifest.image);\n }\n }\n return Array.from(out);\n}\n\nexport async function removeCheckpoint(projectRoot: string, ref: string): Promise<boolean> {\n const dir = checkpointDir(projectRoot, ref);\n const manifest = await readManifest(dir);\n if (!manifest) return false;\n await rm(dir, { recursive: true, force: true });\n // Image is the durable artifact; best-effort because nothing else references\n // it once the manifest is gone. `-f` so a stale tag without containers is\n // dropped even if Docker considers it \"in use\" via dangling layers.\n await removeImage(manifest.image, { force: true });\n return true;\n}\n\n/**\n * Next `<boxName>-<n>` given the names already present. Monotonic per\n * box-name; gaps from deleted checkpoints are skipped (max+1, never\n * recycled). Pure — unit-tested directly.\n */\nexport function computeNextCheckpointName(existingNames: string[], boxName: string): string {\n const re = new RegExp(`^${boxName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}-(\\\\d+)$`);\n let max = 0;\n for (const n of existingNames) {\n const m = re.exec(n);\n if (m) max = Math.max(max, Number(m[1]));\n }\n return `${boxName}-${String(max + 1)}`;\n}\n\nasync function nextCheckpointName(projectRoot: string, boxName: string): Promise<string> {\n const existing = await listCheckpoints(projectRoot);\n return computeNextCheckpointName(\n existing.map((c) => c.name),\n boxName,\n );\n}\n\nfunction chainDepth(box: BoxRecord): number {\n return box.checkpointSource?.chain.length ?? 0;\n}\n\nexport interface CreateCheckpointOptions {\n box: BoxRecord;\n projectRoot: string;\n name?: string;\n /** Force a flattened (export+`FROM scratch` rebuild) capture. */\n merged?: boolean;\n setDefault?: boolean;\n /**\n * If an existing checkpoint has the same name, delete it (manifest + image)\n * before capturing. Without this, name collisions throw `CheckpointError`.\n * Useful for idempotent re-runs from the in-box agent (`agentbox-ctl\n * checkpoint --replace`), e.g. when the previous invocation's stdout was\n * lost mid-flight and the agent can't tell whether it succeeded.\n */\n replace?: boolean;\n /** checkpoint.maxLayers — auto-flatten when the source chain is at/over this. */\n maxLayers: number;\n onLog?: (line: string) => void;\n}\n\n/**\n * Run the pre-commit cleanup in the box. Script is image-baked at\n * /usr/local/bin/agentbox-checkpoint-cleanup. Best-effort: a non-zero exit\n * from the cleanup logs but does not abort the capture (the script itself\n * is also `set +e` for the same reason).\n */\nasync function runCleanup(container: string, log: (line: string) => void): Promise<void> {\n const r = await execInBox(container, ['/usr/local/bin/agentbox-checkpoint-cleanup'], {\n user: 'root',\n });\n if (r.exitCode !== 0) {\n log(`warning: checkpoint cleanup exited ${String(r.exitCode)}: ${r.stderr.slice(0, 200)}`);\n }\n}\n\n/**\n * Read the base image's Config block so the flatten step can replay\n * Env/Cmd/Entrypoint/WorkingDir/User/ExposedPorts on the `FROM scratch`\n * rebuild. (`docker export` discards every Config field.)\n */\nasync function inspectImageConfig(imageRef: string): Promise<DockerImageConfig> {\n const r = await execa('docker', ['image', 'inspect', imageRef], { reject: false });\n if (r.exitCode !== 0) {\n throw new CheckpointError(`docker image inspect ${imageRef} failed`, r.stdout, r.stderr);\n }\n const parsed = JSON.parse(r.stdout) as Array<{ Config: DockerImageConfig }>;\n if (!Array.isArray(parsed) || parsed.length === 0 || !parsed[0]?.Config) {\n throw new CheckpointError(`unexpected docker image inspect shape for ${imageRef}`, r.stdout, '');\n }\n return parsed[0].Config;\n}\n\ninterface DockerImageConfig {\n Env?: string[];\n Cmd?: string[];\n Entrypoint?: string[] | null;\n WorkingDir?: string;\n User?: string;\n ExposedPorts?: Record<string, unknown>;\n}\n\n/**\n * Per-instance env keys that `docker commit` picks up from the running\n * container's Config and that must NOT be baked into a project-shared\n * checkpoint image. `runBox -e` sets these per launch; persisting them\n * would leak another box's relay token / VNC password / box-id into every\n * future box restored from this checkpoint.\n */\nconst RUNTIME_ENV_BLOCKLIST = new Set([\n 'AGENTBOX',\n 'AGENTBOX_BOX_ID',\n 'AGENTBOX_BOX_NAME',\n 'AGENTBOX_HOST_WORKSPACE',\n 'AGENTBOX_PROJECT_ROOT',\n 'AGENTBOX_PROJECT_INDEX',\n 'AGENTBOX_RELAY_URL',\n 'AGENTBOX_RELAY_TOKEN',\n 'AGENTBOX_VNC_PASSWORD',\n 'CLAUDE_EFFORT',\n 'CLAUDE_CODE_OAUTH_TOKEN',\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_MODEL',\n]);\n\n/**\n * Render the Dockerfile lines that replay an image's Config on top of a\n * `FROM scratch\\nADD rootfs.tar /` base. Each Env entry becomes its own ENV\n * line (the Dockerfile `ENV KEY=value` form is the only one that safely\n * handles `=` in values). Per-instance env keys (RUNTIME_ENV_BLOCKLIST) are\n * stripped — those come from `docker run -e` at the source box's launch and\n * must not leak into a project-shared checkpoint image.\n * Cmd/Entrypoint are emitted in their JSON exec form.\n */\nfunction renderConfigDirectives(cfg: DockerImageConfig): string[] {\n const lines: string[] = [];\n for (const kv of cfg.Env ?? []) {\n const eq = kv.indexOf('=');\n if (eq <= 0) continue;\n const k = kv.slice(0, eq);\n if (RUNTIME_ENV_BLOCKLIST.has(k)) continue;\n const v = kv.slice(eq + 1);\n lines.push(`ENV ${k}=${dockerfileQuote(v)}`);\n }\n if (cfg.WorkingDir) lines.push(`WORKDIR ${cfg.WorkingDir}`);\n if (cfg.User) lines.push(`USER ${cfg.User}`);\n for (const p of Object.keys(cfg.ExposedPorts ?? {})) lines.push(`EXPOSE ${p.replace('/tcp', '')}`);\n if (cfg.Entrypoint && cfg.Entrypoint.length > 0) {\n lines.push(`ENTRYPOINT ${JSON.stringify(cfg.Entrypoint)}`);\n }\n if (cfg.Cmd && cfg.Cmd.length > 0) {\n lines.push(`CMD ${JSON.stringify(cfg.Cmd)}`);\n }\n return lines;\n}\n\n/** Dockerfile-safe quoting for ENV values (handles spaces and quotes). */\nfunction dockerfileQuote(v: string): string {\n if (/^[A-Za-z0-9._/:+@,=-]+$/.test(v)) return v;\n return `\"${v.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * Capture a box's accumulated state as a project checkpoint.\n *\n * - `layered`: `docker exec /usr/local/bin/agentbox-checkpoint-cleanup` then\n * `docker commit <container> <tag>`. Captures everything the container has\n * written *and* the inherited image layers; the new image's parent is the\n * container's current image (i.e. the previous checkpoint or the base).\n * - `flattened`: same prelude, then `docker export | docker build` against\n * a tiny `FROM scratch` Dockerfile that ADDs the rootfs tar and replays\n * the base image's Env/Cmd/Entrypoint/WorkingDir/User/ExposedPorts. The\n * resulting image is a single layer.\n *\n * Flattened is chosen when `--merged` is passed or the source box's chain is\n * already `>= maxLayers` deep (caps image-layer growth and reset lineage).\n */\nexport async function createCheckpoint(opts: CreateCheckpointOptions): Promise<CheckpointInfo> {\n const log = opts.onLog ?? (() => {});\n const { box } = opts;\n\n const type: CheckpointType =\n opts.merged === true || chainDepth(box) >= opts.maxLayers ? 'flattened' : 'layered';\n const name = opts.name ?? (await nextCheckpointName(opts.projectRoot, box.name));\n const dir = checkpointDir(opts.projectRoot, name);\n const existing = await readManifest(dir);\n if (existing) {\n if (opts.replace) {\n log(`replacing existing checkpoint ${name} (created ${existing.createdAt})`);\n await removeCheckpoint(opts.projectRoot, name);\n } else {\n // Surface the existing checkpoint's createdAt so a caller whose previous\n // stdout was lost (e.g. the in-box agent's harness wiping output) can\n // immediately tell whether their prior attempt succeeded. Same `rm`\n // hint, plus a `--replace` shortcut for idempotent re-runs.\n throw new CheckpointError(\n `checkpoint ${name} already exists (created ${existing.createdAt}; rm it or pass --replace to recapture)`,\n '',\n '',\n );\n }\n }\n const tag = checkpointImageTag(opts.projectRoot, name);\n await mkdir(dir, { recursive: true });\n\n log(`running pre-commit cleanup in ${box.container}`);\n await runCleanup(box.container, log);\n\n if (type === 'layered') {\n log(`docker commit ${box.container} -> ${tag} (layered)`);\n const r = await execa('docker', ['commit', box.container, tag], { reject: false });\n if (r.exitCode !== 0) {\n throw new CheckpointError(`docker commit failed for ${box.container}`, r.stdout, r.stderr);\n }\n } else {\n log(`docker commit ${box.container} -> <intermediate> (flattened path)`);\n // Two-step: commit first (so we can `docker export` from the resulting\n // image without disturbing the live container), then export+build.\n const intermediate = `${tag}-intermediate`;\n const commit = await execa('docker', ['commit', box.container, intermediate], {\n reject: false,\n });\n if (commit.exitCode !== 0) {\n throw new CheckpointError(`docker commit (intermediate) failed`, commit.stdout, commit.stderr);\n }\n try {\n await flattenImage(intermediate, tag, log);\n } finally {\n // The intermediate is layered (commits don't squash); replaced by the\n // flattened tag. -f because dangling tags would otherwise pin the\n // layered intermediate forever.\n await removeImage(intermediate, { force: true });\n }\n }\n\n const base: 'worktree' | 'workspace' = (box.gitWorktrees ?? []).some((w) => w.kind === 'root')\n ? 'worktree'\n : 'workspace';\n // Capture the base-image fingerprint so a future `create --checkpoint`\n // can detect a stale checkpoint pinned to a now-rebuilt base. Prefer the\n // recorded prepared state (cheap, no I/O on the build context), but fall\n // back to recomputing if the prepared file is missing. Both paths may\n // yield `null` (partial dev rebuild) — the manifest then omits the\n // field and restore degrades to a softer warning.\n const prepared = readPreparedDockerState();\n let baseFingerprint: string | undefined = prepared?.base?.contextSha256;\n if (!baseFingerprint) {\n const fp = await computeDockerContextFingerprint();\n baseFingerprint = fp?.contextSha256;\n }\n const stamp = readCliStamp();\n const manifest: CheckpointManifest = {\n schema: 3,\n name,\n type,\n image: tag,\n // Layered carries lineage forward; flattened is self-contained.\n parents: type === 'layered' ? (box.checkpointSource?.chain ?? []) : [],\n base,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n worktrees: box.gitWorktrees,\n baseProvider: 'docker',\n baseFingerprint,\n cliVersion: stamp.cliVersion,\n createdAt: new Date().toISOString(),\n };\n await writeFile(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\\n', 'utf8');\n\n if (opts.setDefault) {\n // Pin the docker-specific default so a `agentbox create --provider daytona`\n // in the same project doesn't trip over a docker image ref it can't load.\n await setConfigValue('project', 'box.defaultCheckpointDocker', name, opts.projectRoot);\n log(`set project default checkpoint (box.defaultCheckpointDocker) -> ${name}`);\n }\n\n return { name, dir, manifest };\n}\n\n/**\n * Flatten a layered image: export its rootfs as a tar, wrap it in a tiny\n * `FROM scratch` Dockerfile that replays the source image's Config block,\n * and build the result. Leaves the source image alone (caller removes it).\n */\nasync function flattenImage(\n sourceTag: string,\n destTag: string,\n log: (line: string) => void,\n): Promise<void> {\n // `docker export` needs a *container*, so create one without running it.\n const tmpName = `agentbox-flatten-${Date.now().toString(36)}`;\n const create = await execa(\n 'docker',\n ['create', '--name', tmpName, sourceTag, 'sleep', '0'],\n { reject: false },\n );\n if (create.exitCode !== 0) {\n throw new CheckpointError(`docker create for flatten failed`, create.stdout, create.stderr);\n }\n const scratch = await mkdtemp(join(tmpdir(), 'agentbox-flatten-'));\n try {\n const rootfsPath = join(scratch, 'rootfs.tar');\n log(`exporting rootfs of ${sourceTag} to ${rootfsPath}`);\n const exp = await execa('docker', ['export', '-o', rootfsPath, tmpName], { reject: false });\n if (exp.exitCode !== 0) {\n throw new CheckpointError(`docker export failed`, exp.stdout, exp.stderr);\n }\n\n // The Config block to replay is the *source* image's — that's what the\n // running container saw, and `docker commit` carries it through\n // unmodified. `docker export` drops it, which is the only reason we need\n // to inspect+replay here.\n const cfg = await inspectImageConfig(sourceTag);\n const lines = [\n 'FROM scratch',\n // ADD untars during build (Docker's documented behavior for local tars).\n 'ADD rootfs.tar /',\n ...renderConfigDirectives(cfg),\n ];\n await writeFile(join(scratch, 'Dockerfile'), lines.join('\\n') + '\\n', 'utf8');\n\n log(`building flattened ${destTag} from rootfs.tar (FROM scratch)`);\n const build = await execa(\n 'docker',\n ['build', '-t', destTag, '-f', join(scratch, 'Dockerfile'), scratch],\n { reject: false },\n );\n if (build.exitCode !== 0) {\n throw new CheckpointError(`flatten docker build failed`, build.stdout, build.stderr);\n }\n } finally {\n await execa('docker', ['rm', '-f', tmpName], { reject: false });\n await rm(scratch, { recursive: true, force: true });\n }\n}\n\nexport class CheckpointError extends Error {\n constructor(\n message: string,\n public readonly stdout: string,\n public readonly stderr: string,\n ) {\n super(`${message}${stderr ? `: ${stderr.trim()}` : ''}`);\n this.name = 'CheckpointError';\n }\n}\n\n/** Kept for the type-only import in `image.ts`'s self-update path. */\nexport const _DEFAULT_BASE_IMAGE_REF = DEFAULT_BOX_IMAGE;\n","import { stat } from 'node:fs/promises';\nimport { execInBox } from './docker.js';\n\nexport interface CtlLaunchResult {\n up: boolean;\n reason?: string;\n}\n\n/**\n * In-box path the daemon's stdout/stderr are redirected to. `docker exec -d`\n * discards stdio, so without this redirect a crash on startup leaves no trace\n * — the unix socket file lingers (Node doesn't auto-unlink on exit) and any\n * later `agentbox-ctl <op>` connect gets ECONNREFUSED with no log to explain\n * why. The file lives in the container's writable layer; it survives\n * stop/start and is wiped on destroy.\n */\nconst CTL_DAEMON_LOG = '/var/log/agentbox/ctl-daemon.log';\n\n/**\n * Spawn `agentbox-ctl daemon` detached inside the container and wait briefly\n * for the unix socket to appear on the host-mounted path. Best-effort —\n * failure is logged but doesn't fail box creation, since a missing or empty\n * agentbox.yaml is a perfectly valid state.\n */\nexport async function launchCtlDaemon(\n container: string,\n hostSocketPath: string,\n timeoutMs = 3000,\n): Promise<CtlLaunchResult> {\n // Wrap in `sh -c` so the daemon's stdio lands in a log file we can read\n // after a crash. The log dir is pre-created in the image (Dockerfile.box\n // mkdir+chown vscode); `mkdir -p` is a cheap belt-and-braces. `exec` lets\n // the shell replace itself with the daemon for a clean process tree.\n //\n // Idempotent: skip the spawn when a daemon is already running — a normal\n // `start` runs on a freshly-started container (daemon dead, so this no-ops),\n // but `reconnect` (and `start` on an already-running container) would\n // otherwise launch a duplicate. Anchor the pattern at end-of-cmdline so it\n // matches the daemon (`node …/agentbox-ctl daemon`) but not this `sh -c`\n // wrapper, whose argv ends in the log redirect, not \"daemon\".\n const logDir = CTL_DAEMON_LOG.replace(/\\/[^/]*$/, '');\n const wrapped =\n `mkdir -p ${logDir} && ` +\n `{ pgrep -f 'agentbox-ctl daemon$' >/dev/null 2>&1 && exit 0; }; ` +\n `exec agentbox-ctl daemon >>${CTL_DAEMON_LOG} 2>&1`;\n const result = await execInBox(container, ['sh', '-c', wrapped], {\n user: 'vscode',\n detach: true,\n });\n if (result.exitCode !== 0) {\n return { up: false, reason: `docker exec failed: ${result.stderr || result.stdout}` };\n }\n\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await pathExists(hostSocketPath)) return { up: true };\n await new Promise((r) => setTimeout(r, 100));\n }\n return {\n up: false,\n reason: `socket ${hostSocketPath} did not appear within ${String(timeoutMs)}ms`,\n };\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n","import { execa } from 'execa';\n\n/**\n * Writes /etc/agentbox/box.env inside the container as a POSIX-sourceable\n * key='value' file. Paired with /etc/profile.d/agentbox.sh (baked in the\n * image), which `set -a; . /etc/agentbox/box.env; set +a`s it on login.\n *\n * Best-effort: failure is logged by the caller; an unwritable file just\n * means interactive shells lose the AGENTBOX_* vars (the env vars baked\n * into docker run still survive).\n */\nexport async function writeBoxEnvFile(\n container: string,\n env: Record<string, string>,\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n const body = formatBoxEnvBody(env);\n const result = await execa(\n 'docker',\n ['exec', '--user', 'root', '-i', container, 'sh', '-c', 'umask 022 && cat > /etc/agentbox/box.env'],\n { input: body, reject: false },\n );\n if (result.exitCode !== 0) {\n return {\n ok: false,\n reason: `docker exec failed (exit ${String(result.exitCode)}): ${(result.stderr ?? '').toString().slice(0, 400)}`,\n };\n }\n return { ok: true };\n}\n\n// Single-quote each value and escape embedded single quotes as '\\''. Avoids\n// double-quoted form because `. ` would expand $foo / `cmd` at source time.\nexport function formatBoxEnvBody(env: Record<string, string>): string {\n const lines: string[] = [];\n for (const [k, v] of Object.entries(env)) {\n lines.push(`${k}=${shellSingleQuote(v)}`);\n }\n return lines.join('\\n') + '\\n';\n}\n\nfunction shellSingleQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n","import { execa } from 'execa';\n\n/**\n * Re-own any root-owned file under /home/vscode to the uid-1000 `vscode`\n * user. Root-run `docker exec` steps (checkpoint cleanup, dockerd setup) and\n * any `sudo` the in-box agent runs can leave home-dir files owned by root;\n * since the box's shell and agent both run as `vscode`, those files become\n * silently unwritable (the original symptom: a root-owned `.bash_history`\n * dropping all shell history). Boxes are throwaway dev sandboxes, so healing\n * the whole home dir in one sweep beats per-file whack-a-mole.\n *\n * `--from=root` is load-bearing: it limits the chown to files actually owned\n * by root and skips the (vast) vscode-owned majority. A plain `chown -R`\n * issues a chown syscall per file, which on the box's overlay rootfs forces\n * a copy-up of every image-layer file into the writable layer — ~10s and\n * needless disk bloat. `--from` keeps it a fast (~1s) targeted heal.\n *\n * Best-effort, idempotent: runs at every create + start. A few files are\n * legitimately unfixable (a read-only `.gitconfig` bind-mount, git pack\n * files) — chown's per-file errors are harmless and ignored.\n */\nexport async function ensureHomeOwnedByVscode(container: string): Promise<void> {\n await execa(\n 'docker',\n [\n 'exec',\n '--user',\n 'root',\n container,\n 'chown',\n '-R',\n '--from=root',\n 'vscode:vscode',\n '/home/vscode',\n ],\n { reject: false },\n );\n}\n","import { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { existsSync, openSync } from 'node:fs';\nimport { cp, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { createRequire } from 'node:module';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { fileURLToPath } from 'node:url';\nimport {\n DEFAULT_RELAY_PORT,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n type BoxWorktree,\n} from '@agentbox/relay';\nimport { containerExists, removeContainer } from './docker.js';\nimport type { GitWorktreeRecord } from './state.js';\n\nconst STATE_DIR = join(homedir(), '.agentbox');\nconst PID_FILE = join(STATE_DIR, 'relay.pid');\nconst LOG_FILE = join(STATE_DIR, 'relay.log');\nconst RELAY_HOME_DIR = join(STATE_DIR, 'relay');\n\nexport interface RelayEndpoint {\n /** URL boxes use to reach the relay from inside the container. */\n url: string;\n /** URL host-side processes (the CLI itself) use. */\n hostUrl: string;\n port: number;\n}\n\nconst PORT = DEFAULT_RELAY_PORT;\nconst ENDPOINT: RelayEndpoint = {\n // host.docker.internal is the Docker Desktop / OrbStack-supplied alias for\n // the host's loopback as seen from inside a container. The corresponding\n // `--add-host=host.docker.internal:host-gateway` flag in runBox makes the\n // resolution work on Linux native Docker too.\n url: `http://host.docker.internal:${String(PORT)}`,\n hostUrl: `http://127.0.0.1:${String(PORT)}`,\n port: PORT,\n};\n\nexport interface EnsureRelayOptions {\n onLog?: (line: string) => void;\n}\n\n/** The subset of /healthz the relay-reuse decision needs. */\nexport interface RelayReuseHealth {\n cliEntry?: boolean;\n version?: string;\n}\n\n/**\n * Decide whether an already-alive relay must be reclaimed + respawned. Pure (no\n * fs/network) so it's unit-testable. Two independent gates, OR'd:\n * - capability (existing): `cliEntry === false` → the relay can't run\n * cp/download/checkpoint and would 64 forever, so reclaim it.\n * - version (new): both sides report a known non-empty version that DIFFERS →\n * the relay was spawned by a different agentbox install (a stale npx cache\n * entry, say) and must be replaced so the relay's code matches the CLI.\n * Either version unknown → reuse (don't churn relays predating the field). Match\n * on VERSION only, never commit, so dev rebuilds ('0.0.0-dev' constant) never\n * cycle the relay every build.\n */\nexport function shouldReclaimForVersion(\n health: RelayReuseHealth,\n currentVersion: string | undefined,\n): boolean {\n if (health.cliEntry === false) return true;\n if (\n typeof health.version === 'string' &&\n health.version.length > 0 &&\n typeof currentVersion === 'string' &&\n currentVersion.length > 0 &&\n health.version !== currentVersion\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Idempotently bring up the host relay. Spawns the bundled `agentbox-relay`\n * bin as a detached node process bound to 0.0.0.0:8787 (so boxes can reach\n * it via host.docker.internal, and the CLI via 127.0.0.1). Best-effort:\n * failures throw and the caller treats it as \"relay not reachable\".\n *\n * If a legacy relay container from a previous version of agentbox is still\n * around, it's removed first so its bound DNS name doesn't shadow the new\n * host process for any old boxes that happen to still be running.\n */\nexport async function ensureRelay(opts: EnsureRelayOptions = {}): Promise<RelayEndpoint> {\n const log = opts.onLog ?? (() => {});\n await mkdir(STATE_DIR, { recursive: true });\n\n // Migration: kill the old in-docker relay if it's around. The host process\n // wants the same port; the container did NOT publish to host:8787, so there\n // is no actual port collision. We still remove it to avoid confusion (it'd\n // show up in `docker ps -a` forever otherwise).\n if (await containerExists(RELAY_CONTAINER_NAME)) {\n await removeContainer(RELAY_CONTAINER_NAME);\n log(`removed legacy relay container ${RELAY_CONTAINER_NAME}`);\n }\n\n const currentVersion = process.env.AGENTBOX_CLI_VERSION;\n const health = await fetchHealthz(500);\n if (health !== null) {\n // A relay is answering on the port. Reuse it unless it's either incapable\n // (no AGENTBOX_CLI_ENTRY → 64s every cp/download/checkpoint for its whole\n // lifetime, undetectable by bare liveness) or version-mismatched (spawned\n // by a different agentbox install — e.g. a stale npx cache entry — so its\n // code may not match this CLI). See shouldReclaimForVersion for the gates.\n if (!shouldReclaimForVersion(health, currentVersion)) {\n return ENDPOINT;\n }\n if (health.cliEntry === false) {\n log('relay is alive but lacks AGENTBOX_CLI_ENTRY (cp/download/checkpoint would fail) — reclaiming');\n } else {\n log(\n `relay was spawned by agentbox ${health.version ?? '?'} but this CLI is ` +\n `${currentVersion ?? '?'} — reclaiming to keep the relay version-consistent`,\n );\n }\n await reclaimRelay(health.pid, log);\n // fall through to a fresh spawn below\n } else {\n const existingPid = await readPidFile();\n if (existingPid !== null && (await processAlive(existingPid))) {\n // Pid exists but healthz isn't responding yet — give it a beat to finish\n // startup. If it stays unresponsive, leave it alone (someone might be\n // debugging it) and let downstream POSTs fail as best-effort.\n for (let i = 0; i < 10; i++) {\n if (await pingHealthz(300)) return ENDPOINT;\n await delay(200);\n }\n log(`relay pid ${String(existingPid)} alive but /healthz unresponsive — proceeding anyway`);\n return ENDPOINT;\n }\n if (existingPid !== null) {\n await unlink(PID_FILE).catch(() => {});\n }\n }\n\n // Prefer a stable ~/.agentbox/relay/<version>/ home so the long-lived relay's\n // code (and the CLI entry it shells back into) survive npx cache GC. Falls\n // back to the bundle-relative resolvers in dev / on any staging failure.\n const staged = await stageRelayHome(currentVersion ?? '', log).catch(() => null);\n const relayBin = staged?.relayBin ?? resolveRelayBin();\n // The relay shells back into this CLI entry for the cp / download /\n // checkpoint host actions (it only knows the box id; the CLI resolves the\n // rest). Resolve it BEFORE spawning and fail loud if missing: a relay\n // without it answers /healthz fine but 64s every such action, and the\n // capability gate above would just keep reclaiming + respawning it. A null\n // here almost always means the CLI dist is mid-rebuild — surface that\n // instead of producing a half-working relay.\n const cliEntry = staged?.cliEntry ?? resolveCliEntry();\n if (cliEntry === null) {\n throw new Error(\n 'cannot start the host relay: agentbox CLI entry not found ' +\n '(is the build complete / dist present?). Set AGENTBOX_CLI_ENTRY to override.',\n );\n }\n return spawnRelay(relayBin, cliEntry, log);\n}\n\n/**\n * Stop a relay we don't want to reuse (missing AGENTBOX_CLI_ENTRY, or spawned by\n * a different agentbox version) so a fresh one can take the port. Tries the pid\n * the relay reported via /healthz first, then the pidfile pid. Fails loud if the\n * port is still held afterward — a silent \"couldn't reclaim\" would just resurrect\n * the original broken-relay bug.\n */\nasync function reclaimRelay(reportedPid: number | undefined, log: (line: string) => void): Promise<void> {\n const pidFromFile = await readPidFile();\n const seen = new Set<number>();\n for (const pid of [reportedPid, pidFromFile]) {\n if (typeof pid !== 'number' || pid <= 0 || seen.has(pid)) continue;\n seen.add(pid);\n if (!(await processAlive(pid))) continue;\n log(`stopping crippled relay pid ${String(pid)}`);\n await killPid(pid);\n }\n await unlink(PID_FILE).catch(() => {});\n // Confirm the port actually freed; if a relay still answers we'd reuse the\n // broken one again on the next call. Surface it rather than loop silently.\n if (await pingHealthz(300)) {\n throw new Error(\n `a relay is still listening on :${String(PORT)} and could not be ` +\n `stopped (reported pid ${String(reportedPid ?? 'unknown')}); kill it manually and retry`,\n );\n }\n}\n\n/** SIGTERM, wait for exit, then SIGKILL — same escalation as {@link stopRelay}. */\nexport async function killPid(pid: number): Promise<void> {\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n return; // already gone\n }\n for (let i = 0; i < 20; i++) {\n if (!(await processAlive(pid))) return;\n await delay(100);\n }\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // best-effort\n }\n}\n\n/** Spawn the detached relay process wired with AGENTBOX_CLI_ENTRY, then wait for it to come up. */\nasync function spawnRelay(\n relayBin: string,\n cliEntry: string,\n log: (line: string) => void,\n): Promise<RelayEndpoint> {\n const logFd = openSync(LOG_FILE, 'a');\n const child = spawn(\n process.execPath,\n [relayBin, 'serve', '--port', String(PORT), '--host', '0.0.0.0'],\n {\n detached: true,\n stdio: ['ignore', logFd, logFd],\n env: {\n ...process.env,\n AGENTBOX_CLI_ENTRY: cliEntry,\n },\n },\n );\n child.unref();\n if (typeof child.pid === 'number') {\n await writeFile(PID_FILE, String(child.pid), 'utf8');\n log(`spawned relay host process (pid ${String(child.pid)}, port ${String(PORT)})`);\n }\n\n for (let i = 0; i < 25; i++) {\n if (await pingHealthz(300)) {\n log(`relay reachable on ${ENDPOINT.hostUrl}`);\n return ENDPOINT;\n }\n await delay(200);\n }\n throw new Error(\n `relay did not become reachable on ${ENDPOINT.hostUrl} within 5s; see ${LOG_FILE}`,\n );\n}\n\n/**\n * Locate the `agentbox-relay` bin spawned as a child process. Layouts:\n * 0. env override: `AGENTBOX_RELAY_BIN`\n * 1. bundled CLI (dev + published `agent-box`): this module is bundled into\n * the CLI at `<root>/dist/index.js`, the stage step puts the bin at\n * `<root>/runtime/relay/bin.cjs` (sibling of dist/ in both layouts)\n * 2. legacy workspace: `<repo>/packages/sandbox-docker/dist` ↔ `<repo>/packages/relay/dist/bin.cjs`\n * 3. legacy externalized install: `<...>/node_modules/@agentbox/relay/dist/bin.cjs`\n */\nexport function resolveRelayBin(): string {\n const override = process.env.AGENTBOX_RELAY_BIN;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '..', 'runtime', 'relay', 'bin.cjs'),\n resolve(here, '..', '..', 'relay', 'dist', 'bin.cjs'),\n resolve(here, '..', '..', '..', '@agentbox', 'relay', 'dist', 'bin.cjs'),\n resolve(here, '..', '..', 'node_modules', '@agentbox', 'relay', 'dist', 'bin.cjs'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n throw new Error(\n `could not locate @agentbox/relay bin; tried:\\n ${candidates.join('\\n ')}`,\n );\n}\n\n/**\n * Locate the agentbox CLI entry the relay spawns for `checkpoint.create`.\n * Mirrors {@link resolveRelayBin}'s two layouts:\n * 1. workspace dev: `<repo>/packages/sandbox-docker/dist` ↔ `<repo>/apps/cli/dist/index.js`\n * 2. installed: `<...>/agentbox/node_modules/@agentbox/sandbox-docker/dist` ↔ `<...>/agentbox/dist/index.js`\n * Best-effort: returns null when not found (relay reports a clear error).\n */\nexport function resolveCliEntry(): string | null {\n const override = process.env.AGENTBOX_CLI_ENTRY;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n // Bundled CLI (dev + published): this module IS bundled into the CLI\n // entry, so the entry is index.js next to this file.\n resolve(here, 'index.js'),\n resolve(here, '..', '..', '..', 'apps', 'cli', 'dist', 'index.js'),\n resolve(here, '..', '..', '..', '..', 'dist', 'index.js'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n return null;\n}\n\ninterface StagedRelay {\n relayBin: string;\n cliEntry: string;\n}\n\n/**\n * Stage the relay's code into a stable `~/.agentbox/relay/<version>/` home so\n * the long-lived relay process AND the `AGENTBOX_CLI_ENTRY` it shells back into\n * for cp/download/checkpoint/git-push don't depend on the volatile npx cache\n * path (`~/.npm/_npx/<hash>/...`), which can be garbage-collected while the\n * relay is still alive — host actions fire even when no foreground CLI is\n * running, so a vanished entry path would break them.\n *\n * Copies the CLI package tree (`dist/` + `runtime/` + `share/`) PLUS the\n * externalized npm deps (`node_modules/`): the CLI bundle is not self-contained\n * (apps/cli/tsup.config.ts keeps commander/execa/@daytonaio/sdk/... external).\n * The staged tree mirrors the package layout exactly, so the bundled entry's\n * own sibling-relative resolvers and its external `require`s all resolve inside\n * the home.\n *\n * Returns null (caller falls back to the bundle-relative resolvers, unchanged)\n * when the version is dev/empty, an `AGENTBOX_RELAY_BIN`/`AGENTBOX_CLI_ENTRY`\n * override is set, the layout/dep root can't be resolved, or any copy fails.\n */\nasync function stageRelayHome(version: string, log: (line: string) => void): Promise<StagedRelay | null> {\n // Dev is a moving target ('0.0.0-dev' regardless of code) — pinning it would\n // serve a stale bundle. Overrides must flow through untouched.\n if (!version || version === '0.0.0-dev') return null;\n if (process.env.AGENTBOX_RELAY_BIN || process.env.AGENTBOX_CLI_ENTRY) return null;\n\n const cliRoot = findCliRoot(dirname(fileURLToPath(import.meta.url)));\n if (cliRoot === null) return null;\n\n const homeDir = join(RELAY_HOME_DIR, version);\n const stagedEntry = join(homeDir, 'dist', 'index.js');\n const stagedBin = join(homeDir, 'runtime', 'relay', 'bin.cjs');\n // Warm path: already staged for this version → two existsSync checks, no I/O.\n if (existsSync(stagedEntry) && existsSync(stagedBin)) {\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n }\n\n const nodeModules = resolveDepRoot(join(cliRoot, 'dist', 'index.js'));\n if (nodeModules === null) return null;\n\n // Stage into a per-pid tmp dir then atomic-rename, so a crash mid-copy never\n // leaves a homeDir that passes the existsSync gate above but is incomplete.\n const tmpDir = `${homeDir}.tmp-${String(process.pid)}`;\n try {\n await mkdir(RELAY_HOME_DIR, { recursive: true });\n await rm(tmpDir, { recursive: true, force: true });\n await mkdir(tmpDir, { recursive: true });\n for (const sub of ['dist', 'runtime', 'share']) {\n const src = join(cliRoot, sub);\n if (existsSync(src)) await cp(src, join(tmpDir, sub), { recursive: true });\n }\n // dereference so a symlinked dep tree (rare in published installs) lands as\n // real files in the portable home.\n await cp(nodeModules, join(tmpDir, 'node_modules'), { recursive: true, dereference: true });\n await rm(homeDir, { recursive: true, force: true });\n await rename(tmpDir, homeDir);\n } catch (err) {\n await rm(tmpDir, { recursive: true, force: true }).catch(() => {});\n // A concurrent invocation may have won the rename onto homeDir; if the home\n // is complete now, use it. Otherwise fall back to bundle-relative resolvers.\n if (existsSync(stagedEntry) && existsSync(stagedBin)) {\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n }\n log(`relay home staging failed (${err instanceof Error ? err.message : String(err)}); using bundle paths`);\n return null;\n }\n\n log(`staged relay home for ${version} at ${homeDir}`);\n await gcOldRelayHomes(version).catch(() => {});\n return { relayBin: stagedBin, cliEntry: stagedEntry };\n}\n\n/**\n * Walk up from the bundled module dir to the CLI package root (the dir holding\n * `dist/index.js` next to `runtime/`). The module is bundled into the CLI's\n * dist/, so it sits one level under the root (chunked builds keep it in dist/).\n */\nfunction findCliRoot(moduleDir: string): string | null {\n for (const root of [resolve(moduleDir, '..'), resolve(moduleDir, '..', '..')]) {\n if (existsSync(join(root, 'dist', 'index.js')) && existsSync(join(root, 'runtime', 'relay', 'bin.cjs'))) {\n return root;\n }\n }\n return null;\n}\n\n/**\n * Locate the flat `node_modules` dir the externalized CLI deps resolve from.\n * Uses commander (a guaranteed external dep) as the probe and ascends to its\n * enclosing node_modules — handles npm/npx hoisting where the deps live above\n * the package dir.\n *\n * Returns null for a non-flat (pnpm) store: there the probe resolves into a\n * `.pnpm/<pkg>/node_modules` path, and a wholesale recursive copy of that would\n * silently miss transitive deps and produce a broken staged CLI entry. Only a\n * flat npm/npx tree — the actual npx-cache scenario this staging targets — is\n * safe to copy. A pnpm workspace dev tree falls back to bundle-relative paths\n * (current behavior, no regression).\n */\nfunction resolveDepRoot(fromFile: string): string | null {\n try {\n const req = createRequire(fromFile);\n // Resolve the package MAIN, not '<pkg>/package.json' — modern packages with\n // an `exports` map (commander included) block deep package.json resolution\n // with ERR_PACKAGE_PATH_NOT_EXPORTED. The main always resolves.\n const main = req.resolve('commander');\n if (main.includes(`${sep}.pnpm${sep}`)) return null;\n const marker = `${sep}node_modules${sep}`;\n const idx = main.lastIndexOf(marker);\n if (idx === -1) return null;\n const nm = main.slice(0, idx + marker.length - 1); // \".../node_modules\"\n return existsSync(join(nm, 'commander')) ? nm : null;\n } catch {\n return null;\n }\n}\n\n/** Remove stale relay homes (other versions + leftover .tmp dirs), keeping the current version. */\nasync function gcOldRelayHomes(keepVersion: string): Promise<void> {\n let entries: string[];\n try {\n entries = await readdir(RELAY_HOME_DIR);\n } catch {\n return;\n }\n for (const name of entries) {\n if (name === keepVersion) continue;\n await rm(join(RELAY_HOME_DIR, name), { recursive: true, force: true }).catch(() => {});\n }\n}\n\nexport interface StopRelayResult {\n /** True when a live relay process was signalled (and the pidfile cleared). */\n stopped: boolean;\n /** The pid that was found in the pidfile, if any. */\n pid: number | null;\n}\n\n/**\n * Stop the host relay process and clear its pidfile. SIGTERM first, then\n * SIGKILL if it's still alive after a short grace period. Idempotent: a\n * missing/stale pidfile is not an error (returns `{ stopped: false }`).\n *\n * Used by `agentbox update` to reload the relay; the next box command brings\n * it back via {@link ensureRelay} (running the freshly-installed bin).\n */\nexport async function stopRelay(): Promise<StopRelayResult> {\n const pid = await readPidFile();\n if (pid === null) {\n return { stopped: false, pid: null };\n }\n if (!(await processAlive(pid))) {\n await unlink(PID_FILE).catch(() => {});\n return { stopped: false, pid };\n }\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n // already gone between the liveness check and the signal\n }\n for (let i = 0; i < 20; i++) {\n if (!(await processAlive(pid))) break;\n await delay(100);\n }\n if (await processAlive(pid)) {\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // best-effort\n }\n }\n await unlink(PID_FILE).catch(() => {});\n return { stopped: true, pid };\n}\n\nexport interface RelayStatus {\n /** True when /healthz responded with a 2xx. */\n running: boolean;\n /** Pidfile contents (null when missing/unparseable). */\n pid: number | null;\n /** Signal-0 probe on `pid` (false when `pid` is null). */\n pidAlive: boolean;\n /** Configured port (same value as endpoint.port). */\n port: number;\n /** URLs boxes / host-side callers use to reach the relay. */\n endpoint: RelayEndpoint;\n /** Parsed /healthz body; null when the relay isn't responding. */\n health: { boxes: number; events: number; version?: string; commit?: string } | null;\n /** Absolute path to the pidfile. */\n pidFile: string;\n /** Absolute path to the process log. */\n logFile: string;\n}\n\n/**\n * Read-only snapshot of the host relay's liveness. Combines the two probes the\n * lifecycle code uses internally: pidfile + signal-0 + a short /healthz GET.\n * Three terminal states callers care about:\n * - running: true — healthz ok\n * - running: false, pidAlive: true — zombie (process up, healthz silent)\n * - running: false, pidAlive: false — truly down\n */\nexport async function getRelayStatus(): Promise<RelayStatus> {\n const pid = await readPidFile();\n const pidAlive = pid !== null && (await processAlive(pid));\n const health = await fetchHealthz(300);\n return {\n running: health !== null,\n pid,\n pidAlive,\n port: PORT,\n endpoint: ENDPOINT,\n health:\n health === null\n ? null\n : { boxes: health.boxes, events: health.events, version: health.version, commit: health.commit },\n pidFile: PID_FILE,\n logFile: LOG_FILE,\n };\n}\n\nexport function pingHealthz(timeoutMs: number): Promise<boolean> {\n return new Promise<boolean>((resolveP) => {\n const req = httpRequest(\n { host: '127.0.0.1', port: PORT, method: 'GET', path: '/healthz', timeout: timeoutMs },\n (res) => {\n res.resume();\n const status = res.statusCode ?? 0;\n resolveP(status >= 200 && status < 300);\n },\n );\n req.on('error', () => resolveP(false));\n req.on('timeout', () => {\n req.destroy();\n resolveP(false);\n });\n req.end();\n });\n}\n\nexport interface HealthzBody {\n ok: boolean;\n boxes: number;\n events: number;\n /** The relay's own pid (for reclaiming). Absent on relays predating this field. */\n pid?: number;\n /** True when a Next UI is delegated (the embedded hub) vs a bare relay. Absent on old relays. */\n ui?: boolean;\n /** Whether the relay has AGENTBOX_CLI_ENTRY (can run cp/download/checkpoint). Absent on old relays. */\n cliEntry?: boolean;\n /** The agentbox version that spawned the relay. Absent on relays predating this field. */\n version?: string;\n /** The agentbox short commit that spawned the relay (observability only). Absent on old relays. */\n commit?: string;\n}\n\nexport function fetchHealthz(timeoutMs: number): Promise<HealthzBody | null> {\n return new Promise<HealthzBody | null>((resolveP) => {\n const req = httpRequest(\n { host: '127.0.0.1', port: PORT, method: 'GET', path: '/healthz', timeout: timeoutMs },\n (res) => {\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n res.resume();\n resolveP(null);\n return;\n }\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n try {\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Partial<HealthzBody>;\n if (\n typeof parsed.ok === 'boolean' &&\n typeof parsed.boxes === 'number' &&\n typeof parsed.events === 'number'\n ) {\n resolveP({\n ok: parsed.ok,\n boxes: parsed.boxes,\n events: parsed.events,\n pid: typeof parsed.pid === 'number' ? parsed.pid : undefined,\n ui: typeof parsed.ui === 'boolean' ? parsed.ui : undefined,\n cliEntry: typeof parsed.cliEntry === 'boolean' ? parsed.cliEntry : undefined,\n version:\n typeof parsed.version === 'string' && parsed.version.length > 0\n ? parsed.version\n : undefined,\n commit:\n typeof parsed.commit === 'string' && parsed.commit.length > 0\n ? parsed.commit\n : undefined,\n });\n } else {\n resolveP(null);\n }\n } catch {\n resolveP(null);\n }\n });\n res.on('error', () => resolveP(null));\n },\n );\n req.on('error', () => resolveP(null));\n req.on('timeout', () => {\n req.destroy();\n resolveP(null);\n });\n req.end();\n });\n}\n\nasync function readPidFile(): Promise<number | null> {\n try {\n const text = await readFile(PID_FILE, 'utf8');\n const pid = Number.parseInt(text.trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\nexport async function processAlive(pid: number): Promise<boolean> {\n try {\n // Signal 0 is the existence probe: throws if no such process.\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function generateRelayToken(): string {\n return randomBytes(32).toString('hex');\n}\n\nexport interface RegisterBoxArgs {\n boxId: string;\n token: string;\n name: string;\n /**\n * Sandbox backend. Defaults to 'docker'. 'cloud' tells the host relay to\n * spawn a `CloudBoxPoller` for this box (which requires `previewUrl` +\n * `bridgeToken` to be set).\n */\n kind?: 'docker' | 'cloud';\n /**\n * For cloud boxes: which cloud backend to drive (e.g. 'daytona'). The\n * relay's executor lazy-imports `@agentbox/sandbox-{backend}` to do\n * host-only RPCs like git push.\n */\n backend?: string;\n /** Docker container name; lets the relay `docker pause` the box for auto-pause. */\n containerName?: string;\n /** ISO-8601 box-creation time (BoxRecord.createdAt); auto-pause tie-break. */\n createdAt?: string;\n /**\n * 1-based per-project box index. Forwarded so the relay's status-store\n * builds the same `<id>-<n>-<mnemonic>` dir segment the host's\n * `boxRunDirFor` uses. Absent for legacy boxes.\n */\n projectIndex?: number;\n /**\n * Subset of BoxRecord.gitWorktrees the relay needs to dispatch git RPCs.\n * Empty/omitted for boxes without git repos.\n */\n worktrees?: GitWorktreeRecord[];\n /** Required for `kind === 'cloud'`: preview URL of the in-sandbox relay's `/bridge/*`. */\n previewUrl?: string;\n /** Provider-proxy token for `previewUrl` (Daytona `x-daytona-preview-token`). */\n previewToken?: string;\n /** Required for `kind === 'cloud'`: bearer for the in-sandbox relay's `/bridge/*`. */\n bridgeToken?: string;\n /**\n * Mirrors `box.autoApproveHostActions`. When true the relay auto-resolves\n * this box's host-action confirms (git push, cp, gh writes, …) to `y`\n * without a prompt, recording each bypass as a relay event.\n */\n autoApproveHostActions?: boolean;\n /**\n * Mirrors `box.autoApproveSafeHostActions` (default true). When not `false`,\n * the SAFE subset of host actions auto-resolves without a prompt. Absent →\n * enabled; only an explicit `false` restores the always-prompt behavior.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box repo's origin remote URL. The hosted control plane resolves\n * owner/repo from this when leasing a GitHub-App push token. Absent for\n * boxes without a git origin.\n */\n originUrl?: string;\n}\n\nexport async function registerBoxWithRelay(args: RegisterBoxArgs): Promise<void> {\n const worktrees: BoxWorktree[] = (args.worktrees ?? []).map((w) => ({\n containerPath: w.containerPath,\n hostMainRepo: w.hostMainRepo,\n branch: w.branch,\n ...(w.sanctionedBranch ? { sanctionedBranch: w.sanctionedBranch } : {}),\n }));\n await adminPost('/admin/register-box', {\n boxId: args.boxId,\n token: args.token,\n name: args.name,\n kind: args.kind ?? 'docker',\n backend: args.backend,\n containerName: args.containerName,\n createdAt: args.createdAt,\n projectIndex: args.projectIndex,\n worktrees,\n previewUrl: args.previewUrl,\n previewToken: args.previewToken,\n bridgeToken: args.bridgeToken,\n autoApproveHostActions: args.autoApproveHostActions,\n autoApproveSafeHostActions: args.autoApproveSafeHostActions,\n originUrl: args.originUrl,\n });\n}\n\nexport async function forgetBoxFromRelay(boxId: string): Promise<void> {\n try {\n await adminPost('/admin/forget-box', { boxId });\n } catch {\n // best-effort\n }\n}\n\n/**\n * Best-effort: register an informational notice for a box so attached\n * `agentbox claude` footers / the dashboard show it (e.g. a spinner while a\n * checkpoint freezes the box). Returns the notice id, or null when the relay\n * is unreachable / too old to know the route — the caller treats a null id\n * as \"nothing to clear later\". Never throws: a missing notice must not fail\n * the operation it was decorating.\n */\nexport async function setRelayNotice(\n boxId: string,\n kind: string,\n message: string,\n ttlMs?: number,\n): Promise<string | null> {\n try {\n const body = await adminPostForJson('/admin/notices/set', {\n boxId,\n kind,\n message,\n ...(typeof ttlMs === 'number' ? { ttlMs } : {}),\n });\n const id = (body as { id?: unknown } | null)?.id;\n return typeof id === 'string' && id.length > 0 ? id : null;\n } catch {\n return null;\n }\n}\n\n/** Best-effort: clear a notice previously set via {@link setRelayNotice}. */\nexport async function clearRelayNotice(boxId: string, id: string): Promise<void> {\n try {\n await adminPost('/admin/notices/clear', { boxId, id });\n } catch {\n // best-effort\n }\n}\n\n/**\n * Mint a one-time host-initiated token from the host relay, scoped to\n * `(boxId, method, paramsHash)`. The caller passes the returned token to\n * `agentbox-ctl` via `--host-initiated-token`, which forwards it in the RPC\n * params; the relay re-hashes the incoming params and only skips the confirm\n * prompt on a full scope+hash match. Binding to paramsHash prevents a box\n * that harvests the token from agentbox-ctl's argv from replaying it with\n * mutated args (e.g. `--force` on push, modified `--title`/`--body` on PR).\n *\n * The endpoint is loopback-only, so the box cannot mint these directly. If\n * the relay is unreachable / too old to know the route, returns null and the\n * caller falls back to the wrapper-side prompt path.\n *\n * Pass `paramsHash: null` to opt out of params binding (no current call\n * sites do this; the host CLI always binds).\n */\nexport async function mintHostInitiatedToken(\n boxId: string,\n method: string,\n paramsHash: string | null,\n ttlMs?: number,\n): Promise<string | null> {\n try {\n const body = await adminPostForJson('/admin/host-initiated/mint', {\n boxId,\n method,\n paramsHash,\n ...(typeof ttlMs === 'number' ? { ttlMs } : {}),\n });\n const token = (body as { token?: unknown } | null)?.token;\n return typeof token === 'string' && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\nasync function adminPost(path: string, body: unknown): Promise<void> {\n const json = JSON.stringify(body);\n await new Promise<void>((resolveP, rejectP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: PORT,\n method: 'POST',\n path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(json).toString(),\n },\n timeout: 3000,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) {\n resolveP();\n } else {\n const text = Buffer.concat(chunks).toString('utf8');\n rejectP(new Error(`relay ${path} → ${String(status)}: ${text}`));\n }\n });\n },\n );\n req.on('error', rejectP);\n req.on('timeout', () => {\n req.destroy();\n rejectP(new Error(`relay ${path} timeout`));\n });\n req.write(json);\n req.end();\n });\n}\n\n/** Like {@link adminPost} but resolves with the parsed JSON response body. */\nasync function adminPostForJson(path: string, body: unknown): Promise<unknown> {\n const json = JSON.stringify(body);\n return new Promise<unknown>((resolveP, rejectP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: PORT,\n method: 'POST',\n path,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(json).toString(),\n },\n timeout: 3000,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n rejectP(new Error(`relay ${path} → ${String(status)}`));\n return;\n }\n const text = Buffer.concat(chunks).toString('utf8');\n try {\n resolveP(text.length > 0 ? JSON.parse(text) : {});\n } catch (err) {\n rejectP(err instanceof Error ? err : new Error(String(err)));\n }\n });\n res.on('error', rejectP);\n },\n );\n req.on('error', rejectP);\n req.on('timeout', () => {\n req.destroy();\n rejectP(new Error(`relay ${path} timeout`));\n });\n req.write(json);\n req.end();\n });\n}\n\nexport interface BoxWithToken {\n id: string;\n name: string;\n /** Sandbox backend the box runs on. Defaults to 'docker' when absent. */\n provider?: 'docker' | 'cloud' | string;\n container?: string;\n createdAt?: string;\n relayToken?: string;\n projectIndex?: number;\n gitWorktrees?: GitWorktreeRecord[];\n /** Cloud-only: which backend (e.g. 'daytona') drives this box. */\n cloudBackend?: string;\n /** Cloud-only: in-sandbox /bridge URL + tokens (from BoxRecord.cloud). */\n relayPreviewUrl?: string;\n relayPreviewToken?: string;\n bridgeToken?: string;\n /** Mirrors `BoxRecord.autoApproveHostActions`; re-registered on rehydrate. */\n autoApproveHostActions?: boolean;\n /** Mirrors `BoxRecord.autoApproveSafeHostActions`; re-registered on rehydrate. */\n autoApproveSafeHostActions?: boolean;\n}\n\n/**\n * Re-push every known (id, token) to the relay's in-memory registry. Called\n * after `ensureRelay()` so a fresh / restarted relay learns about boxes that\n * were created in a previous CLI invocation — and, for cloud boxes,\n * restarts the host-side `CloudBoxPoller`.\n */\nexport async function rehydrateRelayRegistry(boxes: BoxWithToken[]): Promise<void> {\n for (const b of boxes) {\n if (!b.relayToken) continue;\n const kind = b.provider === 'docker' || b.provider === undefined ? 'docker' : 'cloud';\n try {\n await registerBoxWithRelay({\n boxId: b.id,\n token: b.relayToken,\n name: b.name,\n kind,\n backend: kind === 'cloud' ? b.cloudBackend : undefined,\n containerName: b.container,\n createdAt: b.createdAt,\n projectIndex: b.projectIndex,\n worktrees: b.gitWorktrees,\n previewUrl: b.relayPreviewUrl,\n previewToken: b.relayPreviewToken,\n bridgeToken: b.bridgeToken,\n autoApproveHostActions: b.autoApproveHostActions,\n autoApproveSafeHostActions: b.autoApproveSafeHostActions,\n });\n } catch {\n // best-effort\n }\n }\n}\n\nexport { RELAY_CONTAINER_NAME, RELAY_NETWORK_NAME, RELAY_IMAGE_REF, DEFAULT_RELAY_PORT };\n","import { ensureVolume, execInBox, type DockerExecResult } from './docker.js';\n\nexport type IdeFlavor = 'vscode' | 'cursor';\n\ninterface IdeProfile {\n /** Container path the IDE's server installs into. */\n serverDir: string;\n /** Container path of the extensions subdir under serverDir. */\n extensionsDir: string;\n /** Per-box volume name = perBoxVolumePrefix + boxId. */\n perBoxVolumePrefix: string;\n /** Shared extensions volume name (never auto-removed). */\n sharedExtensionsVolume: string;\n /** Host CLI binary that opens this IDE (`code` / `cursor`). */\n cli: string;\n /** Human-readable label used in CLI output. */\n displayName: string;\n /** macOS protocol scheme for the `open` fallback (no trailing colon). */\n protocolScheme: string;\n}\n\nconst PROFILES: Record<IdeFlavor, IdeProfile> = {\n vscode: {\n serverDir: '/home/vscode/.vscode-server',\n extensionsDir: '/home/vscode/.vscode-server/extensions',\n perBoxVolumePrefix: 'agentbox-vscode-server-',\n sharedExtensionsVolume: 'agentbox-vscode-extensions',\n cli: 'code',\n displayName: 'VS Code',\n protocolScheme: 'vscode',\n },\n cursor: {\n serverDir: '/home/vscode/.cursor-server',\n extensionsDir: '/home/vscode/.cursor-server/extensions',\n perBoxVolumePrefix: 'agentbox-cursor-server-',\n sharedExtensionsVolume: 'agentbox-cursor-extensions',\n cli: 'cursor',\n displayName: 'Cursor',\n protocolScheme: 'cursor',\n },\n};\n\nexport const IDE_FLAVORS: readonly IdeFlavor[] = ['vscode', 'cursor'];\n\nexport function ideProfile(flavor: IdeFlavor): IdeProfile {\n return PROFILES[flavor];\n}\n\n/**\n * Shared across all boxes. Holds downloaded VS Code extensions so the second\n * box onward doesn't re-download them. Never auto-removed by destroy/prune\n * (parallel to SHARED_CLAUDE_VOLUME).\n */\nexport const SHARED_VSCODE_EXTENSIONS_VOLUME = PROFILES.vscode.sharedExtensionsVolume;\n\n/** Same idea for Cursor's downloaded extensions. */\nexport const SHARED_CURSOR_EXTENSIONS_VOLUME = PROFILES.cursor.sharedExtensionsVolume;\n\n/** Per-box VS Code server volume name. Holds server binary + TS cache + workspace state. */\nexport function vscodeServerVolumeName(boxId: string): string {\n return ideServerVolumeName('vscode', boxId);\n}\n\n/** Per-box Cursor server volume name. */\nexport function cursorServerVolumeName(boxId: string): string {\n return ideServerVolumeName('cursor', boxId);\n}\n\nexport function ideServerVolumeName(flavor: IdeFlavor, boxId: string): string {\n return `${PROFILES[flavor].perBoxVolumePrefix}${boxId}`;\n}\n\nexport interface IdeMounts {\n /** Volume names to ensure() before runBox. */\n volumes: string[];\n /** `-v` arg values to pass to runBox. */\n extraVolumes: string[];\n}\n\n/**\n * Build the volume mounts for one IDE flavor: per-box `.vscode-server` (or\n * `.cursor-server`) mounts first, then the shared extensions volume layered\n * over its `extensions` subdir.\n */\nexport function buildFlavorMounts(flavor: IdeFlavor, boxId: string): IdeMounts {\n const profile = PROFILES[flavor];\n const perBox = ideServerVolumeName(flavor, boxId);\n return {\n volumes: [perBox, profile.sharedExtensionsVolume],\n extraVolumes: [\n `${perBox}:${profile.serverDir}`,\n `${profile.sharedExtensionsVolume}:${profile.extensionsDir}`,\n ],\n };\n}\n\n/** VS Code subset — kept for callers that only want the VS Code mounts. */\nexport function buildVscodeMounts(boxId: string): IdeMounts {\n return buildFlavorMounts('vscode', boxId);\n}\n\n/**\n * All IDE flavors' mounts unioned together. This is what createBox uses so\n * any existing box can be opened with either IDE without recreating.\n */\nexport function buildIdeMounts(boxId: string): IdeMounts {\n const merged: IdeMounts = { volumes: [], extraVolumes: [] };\n for (const f of IDE_FLAVORS) {\n const m = buildFlavorMounts(f, boxId);\n merged.volumes.push(...m.volumes);\n merged.extraVolumes.push(...m.extraVolumes);\n }\n return merged;\n}\n\n/** Ensure VS Code's volumes exist. */\nexport async function ensureVscodeVolumes(boxId: string): Promise<void> {\n for (const v of buildFlavorMounts('vscode', boxId).volumes) await ensureVolume(v);\n}\n\n/** Ensure every IDE flavor's volumes exist. */\nexport async function ensureIdeVolumes(boxId: string): Promise<void> {\n for (const v of buildIdeMounts(boxId).volumes) await ensureVolume(v);\n}\n\n/**\n * Belt-and-suspenders chown of the server trees after the named volumes are\n * mounted. The Dockerfile pre-creates these dirs so first-mount inherits\n * vscode:vscode ownership, but a shared extensions volume might already exist\n * from a box created against an older image where the dirs weren't seeded —\n * in that case the volume is root-owned and the Dev Containers extension\n * fails with \"mkdir: cannot create directory '<server>/bin': Permission\n * denied\". One docker exec fixes it idempotently for both flavors.\n */\nexport async function repairVscodeServerOwnership(container: string): Promise<void> {\n await execInBox(container, ['chown', '-R', 'vscode:vscode', PROFILES.vscode.serverDir], {\n user: 'root',\n });\n}\n\nexport async function repairIdeOwnership(container: string): Promise<void> {\n for (const flavor of IDE_FLAVORS) {\n await execInBox(container, ['chown', '-R', 'vscode:vscode', PROFILES[flavor].serverDir], {\n user: 'root',\n });\n }\n}\n\nexport interface AttachedContainerUriOptions {\n /** Active Docker context (e.g. \"desktop-linux\" / \"orbstack\"). Embedded in\n * the URI's `settings.context` so the Dev Containers extension queries the\n * same daemon agentbox created the container in. Omitted → the extension\n * falls back to its own default context. */\n dockerContext?: string;\n /** Folder opened inside the container (default `/workspace`). */\n workspacePath?: string;\n}\n\n/**\n * Resource URI for an attached container, consumed by `code --folder-uri` /\n * `cursor --folder-uri` (Cursor is a VS Code fork — same URI scheme).\n *\n * The modern Dev Containers extension expects the `attached-container+<hex>`\n * authority to decode to a JSON payload, not a bare name:\n *\n * attached-container+hex({\"containerName\":\"/<name>\",\"settings\":{\"context\":\"<ctx>\"}})\n *\n * `containerName` keeps the leading slash docker's own `.Name` field carries.\n * `settings.context` pins the Docker context — without it, after switching\n * engines (OrbStack ⇄ Docker Desktop) the extension probes the wrong daemon\n * and reports the container as non-existent (\"…because it no longer exists\").\n *\n * Note: the `vscode://vscode-remote/...` protocol-handler form looks similar\n * but goes through macOS `open`, which percent-encodes the `+` authority\n * separator into `%2B` and the extension then fails to resolve it. Use\n * `<cli> --folder-uri <this>` to bypass that.\n */\nexport function attachedContainerUri(\n containerName: string,\n opts: AttachedContainerUriOptions = {},\n): string {\n const workspacePath = opts.workspacePath ?? '/workspace';\n const payload: { containerName: string; settings?: { context: string } } = {\n containerName: containerName.startsWith('/') ? containerName : `/${containerName}`,\n };\n if (opts.dockerContext) payload.settings = { context: opts.dockerContext };\n const hex = Buffer.from(JSON.stringify(payload), 'utf8').toString('hex');\n return `vscode-remote://attached-container+${hex}${workspacePath}`;\n}\n\n/**\n * agentbox-managed `.vscode/tasks.json` lives in the overlay's upper layer so\n * it doesn't pollute the host's working tree. The sentinel comment lets us\n * detect our own file and regenerate it on every `agentbox code` invocation\n * without overwriting a user-authored one. The file lives at `.vscode/` —\n * Cursor reads the same path (VS Code fork), so no per-IDE variant needed.\n */\nconst SENTINEL =\n '// agentbox-managed: regenerated on `agentbox code`; remove this header to take ownership';\n\nexport type ServiceTailHint = { name: string };\n\nexport interface EnsureTasksFileResult {\n status: 'wrote' | 'skipped-user-owned' | 'skipped-no-services';\n}\n\n/**\n * Write (or skip) `/workspace/.vscode/tasks.json` inside the container. Each\n * service in `services` gets a background task that tails its log so the IDE\n * shows a dedicated terminal panel on attach.\n *\n * - File absent → write.\n * - File present with our sentinel → overwrite.\n * - File present without sentinel → skip (user owns it). Caller can force\n * by setting `regen: true`.\n */\nexport async function ensureAgentboxTasksFile(\n container: string,\n services: ServiceTailHint[],\n opts: { regen?: boolean } = {},\n): Promise<EnsureTasksFileResult> {\n if (services.length === 0) return { status: 'skipped-no-services' };\n\n const existing = await execInBox(container, ['cat', '/workspace/.vscode/tasks.json'], {\n user: 'vscode',\n });\n if (existing.exitCode === 0 && !opts.regen && !existing.stdout.includes(SENTINEL)) {\n return { status: 'skipped-user-owned' };\n }\n\n const tasks = services.map((s) => ({\n label: `agentbox: ${s.name}`,\n type: 'shell',\n command: `tail -F /var/log/agentbox/${s.name}.log`,\n isBackground: true,\n presentation: { panel: 'dedicated', reveal: 'always', echo: false },\n runOptions: { runOn: 'folderOpen' },\n problemMatcher: [] as unknown[],\n }));\n const body =\n `${SENTINEL}\\n` +\n JSON.stringify(\n {\n version: '2.0.0',\n tasks,\n },\n null,\n 2,\n ) +\n '\\n';\n\n await execInBox(container, ['mkdir', '-p', '/workspace/.vscode'], { user: 'vscode' });\n const write = await writeFileInBox(container, '/workspace/.vscode/tasks.json', body);\n if (write.exitCode !== 0) {\n throw new Error(`failed to write tasks.json in ${container}: ${write.stderr || write.stdout}`);\n }\n return { status: 'wrote' };\n}\n\nasync function writeFileInBox(\n container: string,\n path: string,\n content: string,\n): Promise<DockerExecResult> {\n const { execa } = await import('execa');\n const result = await execa(\n 'docker',\n ['exec', '-i', '--user', 'vscode', container, 'sh', '-c', `cat > ${shellQuote(path)}`],\n { input: content, reject: false },\n );\n return {\n exitCode: result.exitCode ?? -1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nfunction shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Backward-compat alias for the previous mount type name.\nexport type VscodeMounts = IdeMounts;\n","import { execa } from 'execa';\nimport { readdir, rm, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { BoxState, ResyncResult } from '@agentbox/core';\nimport { AmbiguousBoxError, BoxNotFoundError } from '@agentbox/core';\nimport type {\n AgentActivityState,\n BoxStatus,\n ClaudeActivityState,\n ClaudeQuestionPayload,\n} from '@agentbox/ctl';\nimport { claudeSessionInfo, SHARED_CLAUDE_VOLUME, type ClaudeSessionInfo } from './sync/agents/claude.js';\nimport { codexSessionInfo, SHARED_CODEX_VOLUME, type CodexSessionInfo } from './sync/agents/codex.js';\nimport { SHARED_AGENTS_VOLUME } from './sync/agents/skills.js';\nimport {\n opencodeSessionInfo,\n SHARED_OPENCODE_VOLUME,\n type OpencodeSessionInfo,\n} from './sync/agents/opencode.js';\nimport { listShellSessions, type ShellSessionSummary } from './shell-session.js';\nimport { bindWorktrees, removeInBoxWorktree, resyncWorkspaceFromHost } from './sync/in-box-git.js';\nimport {\n cursorServerVolumeName,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n vscodeServerVolumeName,\n} from './vscode.js';\nimport {\n BOXES_ROOT,\n boxRunDirFor,\n detectEngine,\n getHostPaths,\n openInFinder,\n readBoxStatus,\n type HostPaths,\n type OpenOptions,\n type OpenResult,\n} from './sync/host-export.js';\nimport {\n inspectContainer,\n inspectContainerStatus,\n listAgentboxContainers,\n listAgentboxVolumes,\n pauseContainer,\n publishedHostPort,\n removeContainer,\n removeImage,\n removeNetwork,\n removeVolume,\n startContainer,\n stopContainer,\n unpauseContainer,\n} from './docker.js';\nimport { CHECKPOINT_IMAGE_PREFIX, listAllCheckpointImages } from './checkpoint.js';\nimport { launchCtlDaemon } from './ctl.js';\nimport { ensureHomeOwnedByVscode } from './home-ownership.js';\nimport { launchDockerdDaemon, SHARED_DOCKER_CACHE_VOLUME } from './dockerd.js';\nimport { launchVncDaemon, VNC_CONTAINER_PORT } from './vnc.js';\nimport { setUpBoxSshd } from './ssh.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\nimport { syncAgentboxSshConfig } from '@agentbox/sandbox-core';\nimport { detectPortless, portlessAlias, portlessGetUrl, portlessUnalias } from './portless.js';\nimport { getBoxEndpoints, type BoxEndpoint, type BoxEndpoints } from './endpoints.js';\nimport {\n ensureRelay,\n forgetBoxFromRelay,\n registerBoxWithRelay,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n} from './relay.js';\nimport { SNAPSHOTS_ROOT } from './snapshot.js';\nimport {\n findBox,\n readState,\n recordBox,\n removeBoxRecord,\n type BoxRecord,\n type FindBoxResult,\n} from './state.js';\n\nexport interface ListedBox extends BoxRecord {\n state: BoxState;\n endpoints: BoxEndpoints;\n /** From the persisted status file; undefined for pre-feature/never-pushed boxes. */\n claudeActivity?: ClaudeActivityState;\n /** Sanitized in-box terminal title Claude set; undefined when none. */\n claudeSessionTitle?: string;\n /** Last captured `AskUserQuestion` payload — present only when\n * `claudeActivity === 'question'`. Surfaced to the dashboard so it can paint\n * the agent's question into the alert band above the footer. */\n claudeQuestion?: ClaudeQuestionPayload;\n /** Codex activity from the persisted status file (Codex hooks); undefined when none. */\n codexActivity?: AgentActivityState;\n /** Sanitized in-box terminal title the Codex/OpenCode TUI set; undefined when none. */\n codexSessionTitle?: string;\n opencodeSessionTitle?: string;\n /** Live shell tmux sessions; `[]` for non-running boxes (can't `docker exec`). */\n shellSessions: ShellSessionSummary[];\n /** Live probe of the Codex tmux session; null when the box isn't running. */\n codexSession: CodexSessionInfo | null;\n /** Live probe of the OpenCode tmux session; null when the box isn't running. */\n opencodeSession: OpencodeSessionInfo | null;\n}\n\nexport async function listBoxes(): Promise<ListedBox[]> {\n const { boxes } = await readState();\n const engine = await detectEngine();\n return Promise.all(\n boxes.map(async (b): Promise<ListedBox> => {\n // Cloud boxes don't have a host Docker container — skip every Docker\n // probe (inspect / exec / shell-session). State is the last host-driven\n // lifecycle state persisted on `cloud.lastState` (create/start/resume ->\n // running, pause/stop/checkpoint -> paused), so `list` stays instant with\n // no SDK round-trip; `agentbox list --live` probes for the authoritative\n // state. Pre-feature records (no lastState) fall back to 'running'.\n // Endpoints come from the cloud.previewUrls map populated at create/start;\n // agent activity rides the persisted status snapshot the host poller\n // mirrors from the in-sandbox relay.\n if (b.provider && b.provider !== 'docker') {\n const persisted = await readBoxStatus(b);\n const webPort = b.cloud?.webPort ?? 0;\n // Prefer the stable Portless URL when one was registered (Hetzner\n // gets it by default; Daytona naturally skips because its URL isn't\n // loopback). Falls back to the ephemeral `127.0.0.1:<random>`\n // preview URL when Portless isn't in play.\n const portlessWebUrl =\n b.portlessAlias !== undefined\n ? (b.portlessUrl ?? `https://${b.portlessAlias}.localhost`)\n : undefined;\n const cachedWebUrl = webPort > 0 ? b.cloud?.previewUrls?.[webPort] : undefined;\n const webUrl = portlessWebUrl ?? cachedWebUrl;\n const portlessVncBase =\n b.portlessVncAlias !== undefined\n ? (b.portlessVncUrl ?? `https://${b.portlessVncAlias}.localhost`)\n : undefined;\n const vncUrl =\n portlessVncBase && b.vncPassword\n ? `${portlessVncBase}/vnc.html?autoconnect=1&password=${encodeURIComponent(b.vncPassword)}`\n : undefined;\n const cloudEndpoints: BoxEndpoint[] = [];\n if (webUrl) {\n cloudEndpoints.push({\n kind: 'web',\n name: 'web',\n containerPort: webPort,\n url: webUrl,\n reachable: true,\n });\n }\n if (b.vncEnabled && b.vncPassword) {\n cloudEndpoints.push({\n kind: 'vnc',\n name: 'vnc',\n containerPort: b.vncContainerPort ?? 6080,\n ...(vncUrl ? { url: vncUrl, reachable: true } : { reachable: false }),\n });\n }\n const endpoints: BoxEndpoints = {\n domain: webUrl ? safeHost(webUrl) : '',\n domainIsOrb: false,\n endpoints: cloudEndpoints,\n };\n return {\n ...b,\n state: b.cloud?.lastState ?? 'running',\n endpoints,\n claudeActivity: persisted?.claude.state,\n claudeSessionTitle: persisted?.claude.sessionTitle,\n claudeQuestion:\n persisted?.claude.state === 'question' ? persisted.claude.question : undefined,\n codexActivity: persisted?.codex?.state,\n codexSessionTitle: persisted?.codex?.sessionTitle,\n opencodeSessionTitle: persisted?.opencode?.sessionTitle,\n shellSessions: [],\n codexSession: null,\n opencodeSession: null,\n };\n }\n const state = await inspectContainerStatus(b.container);\n const persisted = await readBoxStatus(b);\n const endpoints = await getBoxEndpoints(b, engine, persisted);\n // Shell sessions + the codex session probe are live tmux state — only a\n // running container is reachable via `docker exec`; paused/stopped report\n // none. (Claude activity rides the persisted status snapshot instead, so\n // it needs no live probe.)\n const shellSessions =\n state === 'running' ? await listShellSessions(b.container) : [];\n const codexSession =\n state === 'running' ? await codexSessionInfo(b.container) : null;\n const opencodeSession =\n state === 'running' ? await opencodeSessionInfo(b.container) : null;\n return {\n ...b,\n state,\n endpoints,\n claudeActivity: persisted?.claude.state,\n claudeSessionTitle: persisted?.claude.sessionTitle,\n claudeQuestion:\n persisted?.claude.state === 'question' ? persisted.claude.question : undefined,\n codexActivity: persisted?.codex?.state,\n codexSessionTitle: persisted?.codex?.sessionTitle,\n opencodeSessionTitle: persisted?.opencode?.sessionTitle,\n shellSessions,\n codexSession,\n opencodeSession,\n };\n }),\n );\n}\n\n/** Extract host from a URL string; empty when unparseable. */\nfunction safeHost(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return '';\n }\n}\n\n// The box-resolution error classes are provider-neutral; they live in\n// @agentbox/core. Imported for local `throw`s below and re-exported so existing\n// `@agentbox/sandbox-docker` consumers keep importing them from here.\nexport { AmbiguousBoxError, BoxNotFoundError };\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function resolveBox(idOrName: string): Promise<BoxRecord> {\n const state = await readState();\n const result: FindBoxResult = findBox(idOrName, state);\n switch (result.kind) {\n case 'ok':\n return result.box;\n case 'none':\n throw new BoxNotFoundError(idOrName);\n case 'ambiguous':\n throw new AmbiguousBoxError(idOrName, result.matches);\n }\n}\n\nexport async function pauseBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await pauseContainer(box.container);\n return box;\n}\n\nexport async function unpauseBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await unpauseContainer(box.container);\n return box;\n}\n\nexport async function stopBox(idOrName: string): Promise<BoxRecord> {\n const box = await resolveBox(idOrName);\n await stopContainer(box.container);\n return box;\n}\n\nexport interface StartedBox {\n record: BoxRecord;\n}\n\n/**\n * Resync a box's worktrees with the host: merge the host's current branch into\n * each per-box branch and overlay the host's uncommitted/untracked changes,\n * keeping the box's version on conflict. Returns the conflicts so the CLI can\n * warn the agent. No-op (empty result) for boxes with no git worktrees. The\n * caller is responsible for gating (config + \"no live agent session\"); this\n * mutates the worktree and must not run under a running agent.\n */\nexport async function resyncBox(\n idOrName: string,\n onLog?: (line: string) => void,\n): Promise<ResyncResult> {\n const box = await resolveBox(idOrName);\n const worktrees = box.gitWorktrees ?? [];\n if (worktrees.length === 0) return { repos: [], hadConflicts: false };\n const repos = await resyncWorkspaceFromHost({ container: box.container, worktrees, onLog });\n const hadConflicts = repos.some((r) => r.mergeConflicts.length > 0 || r.overlaySkipped.length > 0);\n return { repos, hadConflicts };\n}\n\n/**\n * Re-start a stopped box.\n *\n * /workspace is just the container's writable filesystem now, so there's no\n * overlay to remount — `docker start` brings everything back. The in-box\n * supervisor, dockerd, and Xvnc all die with the container, so we relaunch\n * them via the same exec-d helpers `create` used. Ephemeral host ports for\n * VNC + web get re-allocated by Docker on `start`, so we re-resolve and\n * persist those too.\n */\n/**\n * Ensure the box's localhost sshd is up and its recorded loopback port is\n * current, then re-sync `~/.agentbox/ssh/config`. Called on `start` (the daemon\n * died with the container) AND before any `agentbox open`/`--in codex` on a box\n * that is *already running* — Docker reallocates the ephemeral `-p 0:22` host\n * port whenever the container restarts, and a `docker restart` (or daemon\n * restart) outside `agentbox start` leaves the recorded `Port` stale. Idempotent:\n * `mintSshKey` reuses the on-disk key, install + launch are no-ops when up, and\n * we only re-persist + re-sync when the resolved port actually changed.\n * Best-effort — mutates and returns `box`.\n */\nexport async function refreshBoxSshd(box: BoxRecord): Promise<BoxRecord> {\n if (!box.sshEnabled) return box;\n const ssh = await setUpBoxSshd(\n box.container,\n join(boxRunDirFor(box), 'ssh'),\n `agentbox-${box.name}-${box.id}`,\n );\n // Only (re)write the alias when sshd actually bound. If it didn't come up we\n // leave the last-known target untouched rather than pointing `~/.ssh/config` at\n // a dead loopback port (matches the create-time gate) — a later retry records\n // it once sshd is healthy.\n if (!ssh.up || !ssh.sshHostPort) return box;\n const port = ssh.sshHostPort;\n const changed = port !== box.sshHostPort || box.ssh?.port !== port;\n box.sshHostPort = port;\n box.ssh = { host: '127.0.0.1', user: 'vscode', identityFile: ssh.identityFile, port };\n if (changed) {\n await recordBox(box);\n try {\n await syncAgentboxSshConfig();\n } catch {\n /* best-effort */\n }\n }\n return box;\n}\n\nexport async function startBox(idOrName: string): Promise<StartedBox> {\n const box = await resolveBox(idOrName);\n // .git bind-mounts are baked into the container at create time; if a host\n // main repo's .git/ has been deleted out from under us, restart fails with\n // an opaque mount error. Surface it loudly.\n for (const w of box.gitWorktrees ?? []) {\n if (!(await pathExists(join(w.hostMainRepo, '.git')))) {\n throw new Error(\n `main repo for box worktree missing: ${join(w.hostMainRepo, '.git')} (recreate the box)`,\n );\n }\n }\n await startContainer(box.container);\n\n // /workspace bind mounts don't survive `docker stop` (the mount namespace\n // is recreated on start). Re-bind each registered worktree before any\n // daemon comes up — the supervisor and dockerd may resolve paths under\n // /workspace and would see the image's empty dir without this.\n if ((box.gitWorktrees ?? []).length > 0) {\n await bindWorktrees(\n box.container,\n (box.gitWorktrees ?? []).map((w) => ({\n kind: w.kind,\n containerPath: w.containerPath,\n gitWorktreePath: w.gitWorktreePath,\n })),\n );\n }\n\n // Re-own /home/vscode to vscode in case root-run steps left files behind\n // (see ensureHomeOwnedByVscode). Best-effort; safe to repeat.\n await ensureHomeOwnedByVscode(box.container);\n\n if (box.dockerVolume) {\n // The daemon died with the container; relaunch it BEFORE the ctl supervisor\n // (mirrors create.ts) so a docker-based agentbox.yaml service doesn't race a\n // not-yet-ready socket on restart. launchDockerdDaemon blocks until ready.\n await launchDockerdDaemon(box.container);\n }\n if (box.socketPath) {\n // The daemon died with the container; relaunch it. Best-effort, same as\n // create.ts — a missing config or other startup issue shouldn't block\n // resumption of the box itself.\n await launchCtlDaemon(box.container, box.socketPath);\n }\n if (box.vncEnabled) {\n // Xvnc + websockify both die with the container. The password is already\n // in the container env (set at `docker run` time and preserved across\n // start/stop), so we don't need to forward it here.\n await launchVncDaemon(box.container);\n // Docker re-allocates an ephemeral host port for `-p 0:6080` on every\n // `start`. Re-resolve and persist; the orb.local URL is name-based and\n // unaffected. Best-effort — a failed resolve just leaves the record as-is.\n const freshHostPort = await publishedHostPort(box.container, VNC_CONTAINER_PORT);\n if (freshHostPort && freshHostPort !== box.vncHostPort) {\n box.vncHostPort = freshHostPort;\n await recordBox(box);\n }\n }\n // Same ephemeral-reallocation story for the reserved web port. Gated on\n // webContainerPort so pre-feature boxes (no `-p 0:80` mapping) are skipped.\n if (box.webContainerPort !== undefined) {\n const freshWebPort = await publishedHostPort(\n box.container,\n box.webContainerPort ?? WEB_CONTAINER_PORT,\n );\n if (freshWebPort && freshWebPort !== box.webHostPort) {\n box.webHostPort = freshWebPort;\n await recordBox(box);\n }\n }\n // sshd died with the container; relaunch it, re-resolve the (reallocated)\n // loopback host port, and regenerate `~/.agentbox/ssh/config`.\n await refreshBoxSshd(box);\n // Docker reallocated the ephemeral host ports above, so both Portless\n // routes now point at stale ports — re-register them. Best-effort and\n // silent (startBox has no onLog); if the proxy/Portless is gone the box\n // still works on loopback.\n if ((box.portlessAlias && box.webHostPort) || (box.portlessVncAlias && box.vncHostPort)) {\n try {\n const portless = await detectPortless();\n if (portless.installed) {\n let dirty = false;\n if (box.portlessAlias && box.webHostPort) {\n await portlessAlias(box.portlessAlias, box.webHostPort);\n // The proxy's scheme/port can change between sessions — re-resolve.\n const url = await portlessGetUrl(box.portlessAlias);\n if (url !== box.portlessUrl) {\n box.portlessUrl = url;\n dirty = true;\n }\n }\n if (box.portlessVncAlias && box.vncHostPort) {\n await portlessAlias(box.portlessVncAlias, box.vncHostPort);\n const url = await portlessGetUrl(box.portlessVncAlias);\n if (url !== box.portlessVncUrl) {\n box.portlessVncUrl = url;\n dirty = true;\n }\n }\n if (dirty) await recordBox(box);\n }\n } catch {\n /* best-effort */\n }\n }\n // Relay's in-memory registry may have been lost if the relay restarted\n // between create and now (or this is the first start after a host reboot).\n // Re-ensure + re-register so outbound push from the box keeps working.\n if (box.relayToken) {\n try {\n await ensureRelay();\n await registerBoxWithRelay({\n boxId: box.id,\n token: box.relayToken,\n name: box.name,\n containerName: box.container,\n createdAt: box.createdAt,\n projectIndex: box.projectIndex,\n worktrees: box.gitWorktrees,\n autoApproveHostActions: box.autoApproveHostActions,\n autoApproveSafeHostActions: box.autoApproveSafeHostActions,\n });\n } catch {\n // best-effort\n }\n }\n return { record: box };\n}\n\nexport interface OpenedBox extends OpenResult {\n record: BoxRecord;\n}\n\nexport async function openBoxInFinder(idOrName: string, opts: OpenOptions): Promise<OpenedBox> {\n const box = await resolveBox(idOrName);\n const result = await openInFinder(box, opts);\n return { ...result, record: box };\n}\n\nexport async function getBoxHostPaths(\n idOrName: string,\n): Promise<{ record: BoxRecord; paths: HostPaths }> {\n const box = await resolveBox(idOrName);\n const paths = await getHostPaths(box);\n return { record: box, paths };\n}\n\nexport interface InspectedBox {\n record: BoxRecord;\n state: BoxState;\n snapshotSizeBytes: number | null;\n dockerInspect: unknown;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'claude' session. */\n claudeSession: ClaudeSessionInfo | null;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'codex' session. */\n codexSession: CodexSessionInfo | null;\n /** Null when the container isn't running; otherwise best-effort probe of the tmux 'opencode' session. */\n opencodeSession: OpencodeSessionInfo | null;\n /** Live shell tmux sessions; `[]` when the container isn't running. */\n shellSessions: ShellSessionSummary[];\n /** Persisted status snapshot (services/tasks/ports/claude); null when none. */\n persistedStatus: BoxStatus | null;\n /** Host paths for `agentbox open`. */\n hostPaths: HostPaths;\n /** Box network surface: domain + VNC + service ports. */\n endpoints: BoxEndpoints;\n}\n\nasync function dirSizeBytes(path: string): Promise<number | null> {\n try {\n const result = await execa('du', ['-sk', path], { reject: false });\n if (result.exitCode !== 0) return null;\n const sizeKb = Number.parseInt((result.stdout ?? '').split(/\\s+/)[0] ?? '', 10);\n if (Number.isNaN(sizeKb)) return null;\n return sizeKb * 1024;\n } catch {\n return null;\n }\n}\n\nexport async function inspectBox(idOrName: string): Promise<InspectedBox> {\n const record = await resolveBox(idOrName);\n const state = await inspectContainerStatus(record.container);\n const snapshotSizeBytes = record.snapshotDir ? await dirSizeBytes(record.snapshotDir) : null;\n const dockerJson = await inspectContainer(record.container);\n\n let claudeSession: ClaudeSessionInfo | null = null;\n let codexSession: CodexSessionInfo | null = null;\n let opencodeSession: OpencodeSessionInfo | null = null;\n let shellSessions: ShellSessionSummary[] = [];\n if (state === 'running') {\n try {\n claudeSession = await claudeSessionInfo(record.container);\n } catch {\n claudeSession = null;\n }\n try {\n codexSession = await codexSessionInfo(record.container);\n } catch {\n codexSession = null;\n }\n try {\n opencodeSession = await opencodeSessionInfo(record.container);\n } catch {\n opencodeSession = null;\n }\n shellSessions = await listShellSessions(record.container);\n }\n\n const hostPaths = await getHostPaths(record);\n const engine = await detectEngine();\n const persistedStatus = await readBoxStatus(record);\n const endpoints = await getBoxEndpoints(record, engine, persistedStatus);\n\n return {\n record,\n state,\n snapshotSizeBytes,\n dockerInspect: dockerJson,\n claudeSession,\n codexSession,\n opencodeSession,\n shellSessions,\n persistedStatus,\n hostPaths,\n endpoints,\n };\n}\n\nexport interface DestroyOptions {\n keepSnapshot?: boolean;\n}\n\nexport interface DestroyResult {\n record: BoxRecord;\n removedContainer: boolean;\n removedVolumes: string[];\n removedSnapshot: string | null;\n}\n\nexport async function destroyBox(\n idOrName: string,\n opts: DestroyOptions = {},\n): Promise<DestroyResult> {\n const box = await resolveBox(idOrName);\n\n // Each step is best-effort. We collect what actually went away so the CLI\n // can show a truthful summary even if e.g. the container was gone already.\n if (box.relayToken) {\n try {\n await forgetBoxFromRelay(box.id);\n } catch {\n // best-effort — relay may be down or already wiped the entry\n }\n }\n // Remove the Portless routes so they don't dangle in the user's proxy\n // config. Web alias + VNC alias are independent — drop whichever was set.\n if (box.portlessAlias) {\n try {\n await portlessUnalias(box.portlessAlias);\n } catch {\n // best-effort — Portless may be uninstalled or the route already gone\n }\n }\n if (box.portlessVncAlias) {\n try {\n await portlessUnalias(box.portlessVncAlias);\n } catch {\n // best-effort\n }\n }\n // Deregister each in-container worktree from the host main repo. Skip\n // Every docker box — including checkpoint-restored ones — now owns a FRESH,\n // per-box worktree + branch (checkpoint restore mints its own via\n // regenerateRestoredWorktrees rather than reusing the source's), so the host\n // `.git/worktrees/<name>` registration is this box's to clean up. Skipping it\n // (the old `!checkpointImage` gate, from when restores shared the source's\n // worktree) would leak a registration per restore. Best-effort + container-\n // only paths, so it resolves to a `git worktree prune` on the host.\n for (const w of box.gitWorktrees ?? []) {\n try {\n await removeInBoxWorktree({\n hostMainRepo: w.hostMainRepo,\n gitWorktreePath: w.gitWorktreePath,\n });\n } catch {\n // best-effort\n }\n }\n const beforeContainer = await inspectContainerStatus(box.container);\n await removeContainer(box.container);\n const afterContainer = await inspectContainerStatus(box.container);\n const removedContainer = beforeContainer !== 'missing' && afterContainer === 'missing';\n\n const removedVolumes: string[] = [];\n // Per-box claude config volumes are box-private — safe to remove. The shared\n // SHARED_CLAUDE_VOLUME holds user identity (auth, skills, plugins) across\n // every box, so never auto-remove it; users delete it manually if they want.\n if (box.claudeConfigVolume && box.claudeConfigVolume !== SHARED_CLAUDE_VOLUME) {\n await removeVolume(box.claudeConfigVolume);\n removedVolumes.push(box.claudeConfigVolume);\n }\n // Same reasoning for the codex-config volume: per-box variants are private\n // and removed here; the shared SHARED_CODEX_VOLUME holds the user's Codex\n // auth across boxes and is never auto-removed.\n if (box.codexConfigVolume && box.codexConfigVolume !== SHARED_CODEX_VOLUME) {\n await removeVolume(box.codexConfigVolume);\n removedVolumes.push(box.codexConfigVolume);\n }\n // Same for the opencode-config volume.\n if (box.opencodeConfigVolume && box.opencodeConfigVolume !== SHARED_OPENCODE_VOLUME) {\n await removeVolume(box.opencodeConfigVolume);\n removedVolumes.push(box.opencodeConfigVolume);\n }\n // Per-box `.vscode-server` and `.cursor-server` volumes. The shared\n // SHARED_*_EXTENSIONS_VOLUMEs are never auto-removed (parallel reasoning to\n // the shared claude volume).\n const perBoxIdeVolumes = [\n box.vscodeServerVolume ?? vscodeServerVolumeName(box.id),\n box.cursorServerVolume ?? cursorServerVolumeName(box.id),\n ];\n for (const v of perBoxIdeVolumes) {\n await removeVolume(v);\n removedVolumes.push(v);\n }\n // Per-box dockerd data root. Skip when this box used the shared cache —\n // wiping it would also remove image layers other boxes (or future ones)\n // depend on. The shared volume is allowlisted in `pruneBoxes --all` too.\n if (box.dockerVolume && !box.dockerCacheShared) {\n await removeVolume(box.dockerVolume);\n removedVolumes.push(box.dockerVolume);\n }\n\n let removedSnapshot: string | null = null;\n if (box.snapshotDir && !opts.keepSnapshot) {\n try {\n await rm(box.snapshotDir, { recursive: true, force: true });\n removedSnapshot = box.snapshotDir;\n } catch {\n removedSnapshot = null;\n }\n }\n\n // The per-box runtime dir holds the ctl socket plus the workspace export\n // dir used by `agentbox open`. Wipe the whole thing so destroy leaves no\n // residue under ~/.agentbox/boxes/.\n try {\n await rm(boxRunDirFor(box), { recursive: true, force: true });\n } catch {\n // best-effort\n }\n\n await removeBoxRecord(box.id);\n // Drop this box's `~/.agentbox/ssh/config` alias (regenerated from state, which\n // no longer lists it). Best-effort — a stale alias is harmless (points at a\n // dead loopback port) but confusing. No-op for boxes that never had sshd.\n if (box.ssh) {\n try {\n await syncAgentboxSshConfig();\n } catch {\n /* best-effort */\n }\n }\n\n return { record: box, removedContainer, removedVolumes, removedSnapshot };\n}\n\nexport interface PruneOptions {\n dryRun?: boolean;\n all?: boolean;\n}\n\nexport interface PruneResult {\n removedRecords: string[];\n removedContainers: string[];\n removedVolumes: string[];\n removedSnapshotDirs: string[];\n removedBoxDirs: string[];\n removedCheckpointImages: string[];\n dryRun: boolean;\n}\n\nasync function listSnapshotDirs(): Promise<string[]> {\n try {\n const entries = await readdir(SNAPSHOTS_ROOT, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => join(SNAPSHOTS_ROOT, e.name));\n } catch {\n return [];\n }\n}\n\nasync function listBoxDirs(): Promise<string[]> {\n try {\n const entries = await readdir(BOXES_ROOT, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => join(BOXES_ROOT, e.name));\n } catch {\n return [];\n }\n}\n\n/**\n * Local Docker image *tags* that look like checkpoint images\n * (`agentbox-ckpt-<projectHash>:<name>`). Used by `prune --all` to find\n * candidates for reaping. An image is reapable only when **both** of these\n * are true: no surviving box's `checkpointImage` points at it, **and** no\n * on-disk manifest under `~/.agentbox/checkpoints/<projectHash>/<name>/`\n * names it as its `image` (see `listAllCheckpointImages`) — otherwise a\n * `destroy` + `prune --all` would silently break checkpoints the user still\n * intends to start new boxes from. Best-effort: returns empty on docker\n * errors.\n */\nasync function listCheckpointImageTags(): Promise<string[]> {\n const r = await execa(\n 'docker',\n ['image', 'ls', '--format', '{{.Repository}}:{{.Tag}}', `${CHECKPOINT_IMAGE_PREFIX}*`],\n { reject: false },\n );\n if (r.exitCode !== 0) return [];\n return (r.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(CHECKPOINT_IMAGE_PREFIX));\n}\n\nexport async function pruneBoxes(opts: PruneOptions = {}): Promise<PruneResult> {\n const dryRun = opts.dryRun ?? false;\n const all = opts.all ?? false;\n\n const { boxes } = await readState();\n\n // Step 1: missing-state records.\n const stateChecks = await Promise.all(\n boxes.map(async (b) => ({ box: b, status: await inspectContainerStatus(b.container) })),\n );\n const missingRecords = stateChecks.filter((c) => c.status === 'missing').map((c) => c.box);\n\n // Step 2 (only with --all): orphan docker containers / volumes / snapshot\n // dirs / per-box dirs / unreferenced checkpoint images.\n let orphanContainers: string[] = [];\n let orphanVolumes: string[] = [];\n let orphanSnapshots: string[] = [];\n let orphanBoxDirs: string[] = [];\n let orphanCheckpointImages: string[] = [];\n\n if (all) {\n const liveContainers = await listAgentboxContainers();\n const liveVolumes = await listAgentboxVolumes();\n const liveSnapshotDirs = await listSnapshotDirs();\n const liveBoxDirs = await listBoxDirs();\n const liveCheckpointImages = await listCheckpointImageTags();\n // Manifests on disk are the durable source of truth for \"this checkpoint\n // exists\" — `destroyBox` leaves them alone on purpose, so an image whose\n // source box was destroyed is still pinned as long as its manifest is\n // there.\n const manifestPinnedImages = await listAllCheckpointImages();\n // The state we'd have AFTER step 1 runs: missing-state records gone.\n const survivingBoxes = boxes.filter((b) => !missingRecords.some((m) => m.id === b.id));\n const expectedContainers = new Set<string>([\n ...survivingBoxes.map((b) => b.container),\n // The relay no longer runs as a container; leftovers are collected\n // below.\n ]);\n const expectedVolumes = new Set<string>([\n ...survivingBoxes\n .map((b) => b.claudeConfigVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.codexConfigVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.opencodeConfigVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.vscodeServerVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.cursorServerVolume)\n .filter((v): v is string => typeof v === 'string'),\n ...survivingBoxes\n .map((b) => b.dockerVolume)\n .filter((v): v is string => typeof v === 'string'),\n // The shared claude-config volume holds user identity across every box;\n // never reap it via prune even if no surviving box currently references it.\n SHARED_CLAUDE_VOLUME,\n // The shared codex-config volume — same reasoning (holds Codex auth).\n SHARED_CODEX_VOLUME,\n // The shared agents-config volume — holds the cross-agent ~/.agents skills.\n SHARED_AGENTS_VOLUME,\n // The shared opencode-config volume — same reasoning (holds OpenCode auth).\n SHARED_OPENCODE_VOLUME,\n // Shared across boxes: downloaded IDE extensions. Same reasoning.\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n // Shared in-box docker image cache — opt-in via `box.dockerCacheShared`,\n // never auto-removed (image layers may be reused by future boxes).\n SHARED_DOCKER_CACHE_VOLUME,\n ]);\n const expectedSnapshots = new Set(\n survivingBoxes\n .filter((b): b is BoxRecord & { snapshotDir: string } =>\n typeof b.snapshotDir === 'string',\n )\n .map((b) => b.snapshotDir),\n );\n const expectedBoxDirs = new Set(survivingBoxes.map((b) => boxRunDirFor(b)));\n // Checkpoint images: keep any tag that either a surviving box's\n // `checkpointImage` points at, or that any on-disk manifest still claims\n // as its `image`. The manifest case is the one that matters most after\n // destroy: the source box is gone but the user still wants to seed new\n // boxes from the checkpoint. The surviving-box case stays as a fallback\n // for the edge where someone `rm -rf`'d a manifest dir while a box\n // restored from it is still running.\n const expectedCheckpointImages = new Set<string>([\n ...survivingBoxes\n .map((b) => b.checkpointImage)\n .filter((v): v is string => typeof v === 'string'),\n ...manifestPinnedImages,\n ]);\n orphanContainers = liveContainers.filter((c) => !expectedContainers.has(c));\n orphanVolumes = liveVolumes.filter((v) => !expectedVolumes.has(v));\n orphanSnapshots = liveSnapshotDirs.filter((d) => !expectedSnapshots.has(d));\n orphanBoxDirs = liveBoxDirs.filter((d) => !expectedBoxDirs.has(d));\n orphanCheckpointImages = liveCheckpointImages.filter(\n (t) => !expectedCheckpointImages.has(t),\n );\n }\n\n if (dryRun) {\n return {\n removedRecords: missingRecords.map((b) => b.id),\n removedContainers: orphanContainers,\n removedVolumes: orphanVolumes,\n removedSnapshotDirs: orphanSnapshots,\n removedBoxDirs: orphanBoxDirs,\n removedCheckpointImages: orphanCheckpointImages,\n dryRun: true,\n };\n }\n\n for (const b of missingRecords) await removeBoxRecord(b.id);\n for (const c of orphanContainers) await removeContainer(c);\n for (const v of orphanVolumes) await removeVolume(v);\n for (const d of orphanSnapshots) {\n try {\n await rm(d, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n }\n for (const d of orphanBoxDirs) {\n try {\n await rm(d, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n }\n for (const img of orphanCheckpointImages) {\n await removeImage(img, { force: true });\n }\n\n // Migration sweep: the relay used to be a docker container on a dedicated\n // network with its own image. None of those exist after this version of\n // agentbox; drop any leftovers from previous installs. Idempotent and\n // best-effort — these calls succeed silently if the objects are already\n // gone.\n if (all) {\n try {\n await removeContainer(RELAY_CONTAINER_NAME);\n } catch {\n // best-effort\n }\n try {\n await execa('docker', ['image', 'rm', RELAY_IMAGE_REF], { reject: false });\n } catch {\n // best-effort\n }\n try {\n await removeNetwork(RELAY_NETWORK_NAME);\n } catch {\n // best-effort\n }\n }\n\n return {\n removedRecords: missingRecords.map((b) => b.id),\n removedContainers: orphanContainers,\n removedVolumes: orphanVolumes,\n removedSnapshotDirs: orphanSnapshots,\n removedBoxDirs: orphanBoxDirs,\n removedCheckpointImages: orphanCheckpointImages,\n dryRun: false,\n };\n}\n\n// Help vitest / unit tests get to the snapshot-root constant without pulling\n// the whole snapshot module surface.\nexport { SNAPSHOTS_ROOT };\n\n// Re-export the file existence helper for inspect output; useful guard for\n// callers that want to know if a snapshot dir was ever created.\nexport async function snapshotPresent(path: string | null): Promise<boolean> {\n if (!path) return false;\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n","import { execa } from 'execa';\nimport { buildTermSafeTmuxExec, buildTmuxSessionArgs, CONTAINER_USER } from './sync/agents/claude.js';\n\n/** Default tmux session name for `agentbox shell` (the box's first shell). */\nexport const DEFAULT_SHELL_SESSION = 'shell';\n\n/** Reserved prefix for non-default shell sessions: `shell-2`, `shell-build`, … */\nexport const SHELL_SESSION_PREFIX = `${DEFAULT_SHELL_SESSION}-`;\n\nexport interface StartShellSessionOptions {\n container: string;\n sessionName?: string;\n /** In-container user (default vscode). The tmux server is per-user, so every\n * helper here must agree on it. */\n user?: string;\n /** Pass `-l` to bash so the login profile loads (default true). */\n login?: boolean;\n}\n\nexport interface ShellSessionInfo {\n running: boolean;\n sessionName: string;\n}\n\nexport interface ShellSessionSummary {\n /** User-facing label: `shell` for the default, else the suffix (`2`, `build`). */\n label: string;\n /** Underlying tmux session name. */\n sessionName: string;\n /** Whether at least one client is attached. */\n attached: boolean;\n /** ISO-8601 creation time, or null when tmux didn't report it. */\n createdAt: string | null;\n}\n\n/**\n * Map a user-facing shell label to its tmux session name. The default shell\n * (`undefined` / empty / `shell`) is the bare `shell`; everything else is\n * `shell-<label>`, so every shell session shares the `shell` prefix.\n */\nexport function shellSessionName(label?: string): string {\n const l = (label ?? '').trim();\n if (l === '' || l === DEFAULT_SHELL_SESSION) return DEFAULT_SHELL_SESSION;\n return `${SHELL_SESSION_PREFIX}${l}`;\n}\n\n/** Inverse of {@link shellSessionName}: the user-facing label for a session. */\nexport function shellLabel(sessionName: string): string {\n return sessionName === DEFAULT_SHELL_SESSION\n ? DEFAULT_SHELL_SESSION\n : sessionName.slice(SHELL_SESSION_PREFIX.length);\n}\n\n/**\n * True iff a tmux session name belongs to a shell (vs the `claude` agent\n * session or a dashboard `*-dash` grouped sibling). Pure string rule — no\n * config dependency, never collides with the agent session.\n */\nexport function isShellSessionName(name: string): boolean {\n if (name === DEFAULT_SHELL_SESSION) return true;\n return name.startsWith(SHELL_SESSION_PREFIX) && !name.endsWith('-dash');\n}\n\n/**\n * Pick the lowest-free shell session name given the ones that already exist:\n * `shell`, then `shell-2`, `shell-3`, … (never recycles a name that is in use).\n */\nexport function allocateShellSessionName(existing: readonly string[]): string {\n const taken = new Set(existing);\n if (!taken.has(DEFAULT_SHELL_SESSION)) return DEFAULT_SHELL_SESSION;\n for (let n = 2; ; n++) {\n const candidate = `${SHELL_SESSION_PREFIX}${String(n)}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n\n/**\n * Parse the tab-separated output of `tmux list-sessions -F\n * '#{session_name}\\t#{session_created}\\t#{session_attached}'`, keeping only\n * shell sessions. Default `shell` sorts first, the rest by creation time.\n */\nexport function parseShellSessionList(stdout: string): ShellSessionSummary[] {\n const out: ShellSessionSummary[] = [];\n for (const line of stdout.split('\\n')) {\n if (line.trim() === '') continue;\n const [name, created, attached] = line.split('\\t');\n if (name === undefined || !isShellSessionName(name)) continue;\n let createdAt: string | null = null;\n const secs = Number.parseInt((created ?? '').trim(), 10);\n if (Number.isFinite(secs) && secs > 0) createdAt = new Date(secs * 1000).toISOString();\n out.push({\n label: shellLabel(name),\n sessionName: name,\n attached: Number.parseInt((attached ?? '0').trim(), 10) > 0,\n createdAt,\n });\n }\n out.sort((a, b) => {\n if (a.sessionName === DEFAULT_SHELL_SESSION) return -1;\n if (b.sessionName === DEFAULT_SHELL_SESSION) return 1;\n return (a.createdAt ?? '').localeCompare(b.createdAt ?? '');\n });\n return out;\n}\n\n/**\n * Enumerate a box's shell tmux sessions. Best-effort: a missing tmux server,\n * a stopped/paused container, or any error surfaces as `[]`.\n */\nexport async function listShellSessions(\n container: string,\n user?: string,\n): Promise<ShellSessionSummary[]> {\n const res = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n user ?? CONTAINER_USER,\n container,\n 'tmux',\n 'list-sessions',\n '-F',\n // Literal tabs reach tmux verbatim (execa array args, no host shell).\n '#{session_name}\\t#{session_created}\\t#{session_attached}',\n ],\n { reject: false },\n );\n if (res.exitCode !== 0) return [];\n return parseShellSessionList(res.stdout ?? '');\n}\n\n/**\n * Start a detached tmux session running `bash` inside the container — the shell\n * counterpart of `startClaudeSession`. The session survives client disconnects;\n * reattach with {@link buildShellSessionAttachArgv}.\n *\n * We forward the host's TERM (default xterm-256color) so the in-container tmux\n * picks the right terminal-overrides at session creation time — without this,\n * docker exec defaults TERM to `xterm` and tmux can't declare 24-bit color.\n */\nexport async function startShellSession(opts: StartShellSessionOptions): Promise<void> {\n const sessionName = opts.sessionName ?? DEFAULT_SHELL_SESSION;\n const user = opts.user ?? CONTAINER_USER;\n const login = opts.login !== false;\n const term = process.env['TERM'] ?? 'xterm-256color';\n // tmux runs a single-arg shell-command via `/bin/sh -c`; `bash -l` / `bash`\n // need no quoting.\n const cmd = login ? 'bash -l' : 'bash';\n const result = await execa(\n 'docker',\n [\n 'exec',\n '-e',\n `TERM=${term}`,\n '--user',\n user,\n opts.container,\n 'tmux',\n 'new-session',\n '-d',\n '-s',\n sessionName,\n cmd,\n ...buildTmuxSessionArgs(sessionName),\n ],\n { reject: false },\n );\n if (result.exitCode === 0) return;\n const stderr = (result.stderr ?? '').toString();\n if (result.exitCode === 127 || /command not found|tmux: not found/i.test(stderr)) {\n throw new Error(\n `tmux is missing from the box image. Rebuild with: docker rmi agentbox/box:dev && retry.`,\n );\n }\n throw new Error(\n `failed to start shell session in ${opts.container}: ${\n stderr.trim() || `exit ${String(result.exitCode)}`\n }`,\n );\n}\n\n/**\n * The `docker` argv that attaches an interactive terminal to a box's shell\n * tmux session. `user` must match the user the session was started as (the\n * tmux server is per-user). Handed to the node-pty wrapper by `agentbox shell`.\n */\nexport function buildShellSessionAttachArgv(\n container: string,\n sessionName?: string,\n user?: string,\n): string[] {\n const name = sessionName ?? DEFAULT_SHELL_SESSION;\n return buildTermSafeTmuxExec({\n container,\n user: user ?? CONTAINER_USER,\n tmuxScript: 'exec tmux attach -t \"$1\"',\n positionals: [name],\n });\n}\n\n/**\n * Best-effort: returns `{ running: false }` for any non-zero exit from\n * `tmux has-session` (covers \"no server running\" and \"no such session\").\n */\nexport async function shellSessionInfo(\n container: string,\n sessionName?: string,\n user?: string,\n): Promise<ShellSessionInfo> {\n const name = sessionName ?? DEFAULT_SHELL_SESSION;\n const has = await execa(\n 'docker',\n ['exec', '--user', user ?? CONTAINER_USER, container, 'tmux', 'has-session', '-t', name],\n { reject: false },\n );\n return { running: has.exitCode === 0, sessionName: name };\n}\n\n/**\n * Kill a box's shell tmux session (`tmux kill-session`). Returns true on a\n * clean kill, false when the session was already gone / no tmux server.\n */\nexport async function killShellSession(\n container: string,\n sessionName: string,\n user?: string,\n): Promise<boolean> {\n const res = await execa(\n 'docker',\n [\n 'exec',\n '--user',\n user ?? CONTAINER_USER,\n container,\n 'tmux',\n 'kill-session',\n '-t',\n sessionName,\n ],\n { reject: false },\n );\n return res.exitCode === 0;\n}\n","import { join } from 'node:path';\nimport { loadConfig } from '@agentbox/ctl';\nimport type { BoxStatus } from '@agentbox/ctl';\nimport type { BoxEndpoint, BoxEndpoints, BoxRecord } from '@agentbox/core';\nimport type { DockerEngine } from './sync/host-export.js';\nimport { buildVncUrls, VNC_CONTAINER_PORT } from './vnc.js';\nimport { WEB_CONTAINER_PORT } from './web.js';\n\n// BoxEndpoint / BoxEndpoints are the provider-neutral network-surface shape;\n// they live in @agentbox/core. Re-exported so existing consumers are unchanged.\nexport type { BoxEndpoint, BoxEndpoints };\n\n/**\n * Build the box's user-facing network surface. Pure host-side: no docker exec,\n * no network — safe to call from `agentbox list` in a tight loop.\n *\n * Service ports come from the persisted status snapshot when available\n * (`~/.agentbox/boxes/<id>/status.json`, pushed by the in-box supervisor via\n * the relay). That snapshot resolves `ready_when.port` *inside the box*, so it\n * works even when `agentbox.yaml` lives only in the box and was never pulled to\n * the host. Falls back to parsing the host's `agentbox.yaml` for pre-relay\n * boxes (or ones that never pushed a snapshot).\n *\n * Missing config + no snapshot is non-fatal: the VNC entry (if any) is still\n * returned. Engine drives reachability — OrbStack auto-routes\n * `<container>.orb.local:<port>` for any in-box port; other engines see only\n * what we explicitly publish via `docker run -p`, which today is just VNC.\n */\nexport async function getBoxEndpoints(\n record: BoxRecord,\n engine: DockerEngine,\n persisted?: BoxStatus | null,\n): Promise<BoxEndpoints> {\n const domainIsOrb = engine === 'orbstack';\n const domain = domainIsOrb ? `${record.container}.orb.local` : '127.0.0.1';\n\n const endpoints: BoxEndpoint[] = [];\n\n if (record.vncEnabled && record.vncPassword) {\n const vncUrls = buildVncUrls(record, engine);\n // Preference: portless (stable name) > orb.local > loopback. Mirrors the\n // web endpoint's choice below and `agentbox screen`'s default.\n const url =\n engine === 'orbstack'\n ? (vncUrls.orbUrl ?? vncUrls.loopbackUrl)\n : (vncUrls.portlessUrl ?? vncUrls.loopbackUrl);\n endpoints.push({\n kind: 'vnc',\n name: 'vnc',\n containerPort: VNC_CONTAINER_PORT,\n url,\n reachable: Boolean(url),\n });\n }\n\n // The single `expose:`-flagged service, from the snapshot first (works when\n // agentbox.yaml lives only in the box), else the host yaml.\n let webServiceName: string | null = null;\n const persistedWeb = persisted?.services.find((s) => s.expose);\n if (persistedWeb) {\n webServiceName = persistedWeb.name;\n }\n\n const pushService = (name: string, port: number): void => {\n // The web service is surfaced as the dedicated `web` endpoint below;\n // don't also list it as a generic service.\n if (name === webServiceName) return;\n endpoints.push({\n kind: 'service',\n name,\n containerPort: port,\n // Only OrbStack auto-routes arbitrary in-box ports; on other engines we\n // don't publish service ports, so the URL isn't host-reachable.\n ...(domainIsOrb\n ? { url: `http://${domain}:${String(port)}`, reachable: true }\n : { reachable: false }),\n });\n };\n\n const persistedServices = persisted?.services.filter(\n (s): s is typeof s & { port: number } => typeof s.port === 'number',\n );\n if (persistedServices && persistedServices.length > 0) {\n for (const svc of persistedServices) pushService(svc.name, svc.port);\n } else {\n try {\n const cfg = await loadConfig(join(record.workspacePath, 'agentbox.yaml'));\n if (!webServiceName) {\n webServiceName = cfg.services.find((s) => s.expose)?.name ?? null;\n }\n for (const svc of cfg.services) {\n if (svc.readyWhen?.kind !== 'port') continue;\n pushService(svc.name, svc.readyWhen.port);\n }\n } catch {\n // No persisted snapshot and no host agentbox.yaml — skip service\n // endpoints. The VNC entry, if any, is unaffected.\n }\n }\n\n // Web endpoint: only for boxes that reserved container :80 at create. The\n // URL is the published loopback host port — uniform across engines, NOT\n // gated on OrbStack (requirement: don't rely on orb auto-DNS). No url until\n // both a service declares `expose:` and the host port is resolved; until\n // then it renders as \"reserved\".\n if (record.webContainerPort !== undefined) {\n const hasTarget = webServiceName !== null && record.webHostPort !== undefined;\n // A registered Portless alias gives the box a stable <name>.localhost URL\n // on non-OrbStack engines. `portlessUrl` is the real URL resolved from the\n // proxy at create/start (scheme + port vary); fall back to the https form\n // for records written before that field existed. No `portless` shell-out\n // here — this runs in a tight loop for `agentbox list`.\n const usePortless = record.portlessAlias !== undefined && engine !== 'orbstack';\n const webUrl = usePortless\n ? (record.portlessUrl ?? `https://${record.portlessAlias}.localhost`)\n : `http://127.0.0.1:${String(record.webHostPort)}`;\n endpoints.push({\n kind: 'web',\n name: webServiceName ?? 'web',\n containerPort: record.webContainerPort ?? WEB_CONTAINER_PORT,\n ...(hasTarget ? { url: webUrl, reachable: true } : { reachable: false }),\n });\n }\n\n return { domain, domainIsOrb, endpoints };\n}\n","import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { BoxResourceLimits, BoxResourceStats } from '@agentbox/core';\nimport { CHECKPOINT_IMAGE_PREFIX, checkpointImageTag } from './checkpoint.js';\nimport {\n inspectContainer,\n inspectContainerStatus,\n inspectVolumeMountpoint,\n} from './docker.js';\nimport { detectEngine } from './sync/host-export.js';\nimport type { BoxRecord } from './state.js';\n\n/**\n * Parse one of Docker's human-formatted size tokens (`512MiB`, `1.2kB`,\n * `3.4GB`, `0B`, `--`). Returns null when unparseable. Docker mixes binary\n * (`KiB/MiB/GiB`) and decimal (`kB/MB/GB`) suffixes depending on the column, so\n * we handle both.\n */\nexport function parseDockerSize(raw: string): number | null {\n const s = raw.trim();\n if (!s || s === '--' || s === 'N/A') return null;\n const m = /^([\\d.]+)\\s*([A-Za-z]*)$/.exec(s);\n if (!m) return null;\n const n = Number(m[1]);\n if (!Number.isFinite(n)) return null;\n const unit = (m[2] ?? '').toLowerCase();\n const mult: Record<string, number> = {\n '': 1,\n b: 1,\n kb: 1e3,\n mb: 1e6,\n gb: 1e9,\n tb: 1e12,\n kib: 1024,\n mib: 1024 ** 2,\n gib: 1024 ** 3,\n tib: 1024 ** 4,\n };\n const factor = mult[unit];\n return factor === undefined ? null : n * factor;\n}\n\nfunction parsePercent(raw: string | undefined): number | null {\n if (!raw) return null;\n const n = Number(raw.replace('%', '').trim());\n return Number.isFinite(n) ? n : null;\n}\n\n/** Split Docker's \"<a> / <b>\" pair columns (MemUsage, NetIO, BlockIO). */\nfunction splitPair(raw: string | undefined): [string, string] | null {\n if (!raw) return null;\n const parts = raw.split('/');\n if (parts.length !== 2) return null;\n return [parts[0]!.trim(), parts[1]!.trim()];\n}\n\nasync function duBytes(path: string): Promise<number | null> {\n const result = await execa('du', ['-sk', path], { reject: false });\n if (result.exitCode !== 0) return null;\n const kb = Number.parseInt((result.stdout ?? '').split(/\\s+/)[0] ?? '', 10);\n return Number.isNaN(kb) ? null : kb * 1024;\n}\n\n/**\n * Best-effort on-host byte size of a Docker named volume. Fastest path first:\n * 1. OrbStack exposes volumes live at ~/OrbStack/docker/volumes/<name>/.\n * 2. `docker system df -v` (cheap-walked once; may report \"N/A\").\n * 3. The reported mountpoint, only when host-readable (Linux native Docker).\n * Returns null when no path is reachable from the host (the macOS VM case\n * where `system df` also has no number).\n */\nexport async function volumeSizeBytes(name: string): Promise<number | null> {\n if (!name) return null;\n const engine = await detectEngine();\n if (engine === 'orbstack') {\n const live = join(homedir(), 'OrbStack', 'docker', 'volumes', name);\n const sz = await duBytes(live);\n if (sz !== null) return sz;\n }\n const df = await execa(\n 'docker',\n ['system', 'df', '-v', '--format', '{{json .Volumes}}'],\n { reject: false },\n );\n if (df.exitCode === 0) {\n try {\n const vols = JSON.parse(df.stdout || '[]') as Array<{ Name?: string; Size?: string }>;\n const hit = vols.find((v) => v.Name === name);\n const parsed = hit?.Size ? parseDockerSize(hit.Size) : null;\n if (parsed !== null) return parsed;\n } catch {\n // fall through to mountpoint\n }\n }\n const mp = await inspectVolumeMountpoint(name);\n if (mp && !mp.startsWith('/var/lib/docker')) {\n return duBytes(mp);\n }\n return null;\n}\n\n/**\n * On-host byte size of a Docker image (sum of its own layer sizes — what\n * `docker images` reports). Null on docker errors.\n */\nasync function imageBytes(tag: string): Promise<number | null> {\n const r = await execa('docker', ['image', 'inspect', tag, '--format', '{{.Size}}'], {\n reject: false,\n });\n if (r.exitCode !== 0) return null;\n const n = Number.parseInt((r.stdout ?? '').trim(), 10);\n return Number.isFinite(n) ? n : null;\n}\n\n/**\n * Size of a project's most-recent checkpoint image (the head of the lineage,\n * resolved via the `checkpointImageTag` helper from a checkpoint *name*). The\n * caller passes the name because we don't enumerate manifests from this\n * module — that lives in checkpoint.ts. Null when the image isn't present.\n */\nexport async function projectCheckpointImageBytes(\n projectRoot: string,\n name: string,\n): Promise<number | null> {\n return imageBytes(checkpointImageTag(projectRoot, name));\n}\n\n/**\n * Total on-host bytes of every checkpoint image (the durable, cross-box\n * warm-state assets). Walks every image tag under `CHECKPOINT_IMAGE_PREFIX`.\n * Null when none exist.\n */\nexport async function allCheckpointImagesBytes(): Promise<number | null> {\n const r = await execa(\n 'docker',\n [\n 'image',\n 'ls',\n '--format',\n '{{.Repository}}:{{.Tag}}\\t{{.Size}}',\n `${CHECKPOINT_IMAGE_PREFIX}*`,\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) return null;\n const lines = (r.stdout ?? '')\n .split('\\n')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (lines.length === 0) return null;\n let total = 0;\n let any = false;\n for (const line of lines) {\n const [, size] = line.split('\\t');\n const n = size ? parseDockerSize(size) : null;\n if (n !== null) {\n total += n;\n any = true;\n }\n }\n return any ? total : null;\n}\n\n/** On-host byte size of the whole ~/.agentbox state/runtime directory. */\nexport async function agentboxHomeBytes(): Promise<number | null> {\n return duBytes(join(homedir(), '.agentbox'));\n}\n\nfunction limitsFromRecord(record: BoxRecord): BoxResourceLimits {\n const r = record.resourceLimits;\n return {\n memoryBytes: r?.memoryBytes && r.memoryBytes > 0 ? r.memoryBytes : null,\n cpus: r?.cpus && r.cpus > 0 ? r.cpus : null,\n pidsLimit: r?.pidsLimit && r.pidsLimit > 0 ? r.pidsLimit : null,\n disk: r?.disk || null,\n };\n}\n\n/**\n * Cross-check persisted limits against the live container's HostConfig so an\n * externally `docker update`d box still reports the truth. The persisted\n * record stays the fallback when the container is gone.\n */\nfunction reconcileLimits(persisted: BoxResourceLimits, dockerJson: unknown): BoxResourceLimits {\n const hc = (dockerJson as { HostConfig?: Record<string, unknown> } | null)?.HostConfig;\n if (!hc) return persisted;\n const mem = typeof hc.Memory === 'number' && hc.Memory > 0 ? hc.Memory : null;\n const nano = typeof hc.NanoCpus === 'number' && hc.NanoCpus > 0 ? hc.NanoCpus : null;\n const pids = typeof hc.PidsLimit === 'number' && hc.PidsLimit > 0 ? hc.PidsLimit : null;\n return {\n memoryBytes: mem ?? persisted.memoryBytes,\n cpus: nano ? nano / 1e9 : persisted.cpus,\n pidsLimit: pids ?? persisted.pidsLimit,\n disk: persisted.disk,\n };\n}\n\ninterface DockerStatsLine {\n CPUPerc?: string;\n MemUsage?: string;\n MemPerc?: string;\n PIDs?: string;\n NetIO?: string;\n BlockIO?: string;\n}\n\n/**\n * Container writable-layer size from `docker ps --size`. With the overlay\n * gone, `/workspace` lives here (not in a named volume), so this is the\n * box's primary writable-surface number.\n */\nasync function containerWritableBytes(container: string): Promise<number | null> {\n const r = await execa(\n 'docker',\n ['ps', '-a', '--filter', `name=^${container}$`, '--format', '{{.Size}}', '--size'],\n { reject: false },\n );\n if (r.exitCode !== 0) return null;\n // `--size` produces `<rw> (virtual <total>)`; we want the first number.\n const first = (r.stdout ?? '').split('\\n')[0]?.trim();\n if (!first) return null;\n const m = /^([^()]+?)(?:\\s*\\(.*\\))?$/.exec(first);\n const sz = m ? m[1]!.trim() : first;\n return parseDockerSize(sz);\n}\n\n/**\n * Provider-agnostic resource snapshot for a box. CPU/mem/pids/IO come from\n * `docker stats --no-stream` (point-in-time sample; only when the container is\n * running). Disk is the container's writable layer (where `/workspace` lives\n * now that the overlay is gone) plus the in-box dockerd's data-root volume;\n * the per-box host snapshot dir and the checkpoint image lineage are\n * reported on their own fields.\n */\nexport async function boxResourceStats(record: BoxRecord): Promise<BoxResourceStats> {\n const warnings: string[] = [];\n const dockerJson = await inspectContainer(record.container);\n const limits = reconcileLimits(limitsFromRecord(record), dockerJson);\n\n const [diskContainer, diskDocker, snapshotDiskBytes, checkpointImageBytesValue] =\n await Promise.all([\n containerWritableBytes(record.container),\n record.dockerVolume ? volumeSizeBytes(record.dockerVolume) : Promise.resolve(null),\n record.snapshotDir ? duBytes(record.snapshotDir) : Promise.resolve(null),\n record.checkpointImage ? imageBytes(record.checkpointImage) : Promise.resolve(null),\n ]);\n const diskUsedBytes =\n diskContainer === null && diskDocker === null\n ? null\n : (diskContainer ?? 0) + (diskDocker ?? 0);\n if (diskUsedBytes === null) {\n warnings.push('disk usage unavailable on this engine');\n }\n\n const base: BoxResourceStats = {\n source: 'docker',\n live: false,\n cpuPercent: null,\n memUsedBytes: null,\n memLimitBytes: limits.memoryBytes,\n memPercent: null,\n pids: null,\n diskUsedBytes,\n snapshotDiskBytes,\n checkpointVolumeBytes: checkpointImageBytesValue,\n netRxBytes: null,\n netTxBytes: null,\n blockReadBytes: null,\n blockWriteBytes: null,\n limits,\n warnings,\n };\n\n if ((await inspectContainerStatus(record.container)) !== 'running') {\n return base;\n }\n\n const proc = await execa(\n 'docker',\n ['stats', '--no-stream', '--format', '{{json .}}', record.container],\n { reject: false },\n );\n if (proc.exitCode !== 0 || !proc.stdout.trim()) {\n return base;\n }\n let line: DockerStatsLine;\n try {\n line = JSON.parse(proc.stdout.trim().split('\\n')[0]!) as DockerStatsLine;\n } catch {\n return base;\n }\n\n const memPair = splitPair(line.MemUsage);\n const memUsedBytes = memPair ? parseDockerSize(memPair[0]) : null;\n const memEngineTotal = memPair ? parseDockerSize(memPair[1]) : null;\n const netPair = splitPair(line.NetIO);\n const blkPair = splitPair(line.BlockIO);\n\n return {\n ...base,\n live: true,\n cpuPercent: parsePercent(line.CPUPerc),\n memUsedBytes,\n // The applied limit when set; otherwise docker stats' own denominator\n // (the engine/host total).\n memLimitBytes: limits.memoryBytes ?? memEngineTotal,\n memPercent: parsePercent(line.MemPerc),\n pids: line.PIDs ? Number.parseInt(line.PIDs, 10) || null : null,\n netRxBytes: netPair ? parseDockerSize(netPair[0]) : null,\n netTxBytes: netPair ? parseDockerSize(netPair[1]) : null,\n blockReadBytes: blkPair ? parseDockerSize(blkPair[0]) : null,\n blockWriteBytes: blkPair ? parseDockerSize(blkPair[1]) : null,\n };\n}\n","/**\n * The docker provider's uniform `ProviderModule` surface (see\n * `@agentbox/sandbox-core`'s `ProviderModule`). Docker is the local provider:\n * no cloud backend, no credentials/login, no base-snapshot fingerprint — just\n * the provider plus its doctor probes (moved here from apps/cli so the CLI\n * dispatches to it generically).\n */\n\nimport { execa } from 'execa';\nimport { errSummary, type CheckResult, type ProviderModule } from '@agentbox/sandbox-core';\nimport { dockerProvider } from './docker-provider.js';\nimport { DEFAULT_BOX_IMAGE, imageInfo } from './image.js';\nimport { volumeExists } from './docker.js';\nimport { detectEngine } from './sync/host-export.js';\nimport { detectPortless, portlessDoctorRow } from './portless.js';\nimport { SHARED_CLAUDE_VOLUME } from './sync/agents/claude.js';\nimport { SHARED_CODEX_VOLUME } from './sync/agents/codex.js';\nimport { SHARED_OPENCODE_VOLUME } from './sync/agents/opencode.js';\n\nasync function probeVersion(bin: string, args: string[] = ['--version']): Promise<string | null> {\n try {\n const r = await execa(bin, args, { reject: false });\n if (r.exitCode !== 0) return null;\n const out = `${r.stdout ?? ''}${r.stderr ?? ''}`.trim().split('\\n')[0] ?? '';\n return out.length > 0 ? out : bin;\n } catch {\n return null;\n }\n}\n\n/** Local, offline-safe docker health probes for `agentbox doctor`. */\nexport async function dockerChecks(): Promise<CheckResult[]> {\n const linux = process.platform === 'linux';\n const cli = await probeVersion('docker');\n if (!cli) {\n return [\n {\n label: 'docker cli',\n status: 'warn',\n detail: 'not found',\n hint: linux\n ? 'install docker engine: https://docs.docker.com/engine/install/'\n : 'install Docker Desktop, OrbStack, or docker engine',\n },\n ];\n }\n const cliRes: CheckResult = { label: 'docker cli', status: 'ok', detail: cli };\n\n // Daemon reachability via `docker info`. On Linux the most common failure is\n // not a stopped daemon but the user missing from the `docker` group — `docker\n // info` then exits non-zero with \"permission denied\" on the socket.\n const info = await execa('docker', ['info'], { reject: false });\n if (info.exitCode !== 0) {\n const permDenied = `${info.stderr ?? ''}`.toLowerCase().includes('permission denied');\n let hint: string;\n if (permDenied && linux) {\n hint =\n 'add your user to the docker group: `sudo usermod -aG docker $USER`, then log out/in (or run `newgrp docker`)';\n } else if (linux) {\n hint = 'start Docker: `sudo systemctl start docker` (install docker engine if missing)';\n } else {\n hint = 'start Docker (Desktop / OrbStack)';\n }\n return [\n cliRes,\n {\n label: 'docker daemon',\n status: 'warn',\n detail: permDenied ? 'permission denied' : 'unreachable',\n hint,\n },\n ];\n }\n const daemonRes: CheckResult = { label: 'docker daemon', status: 'ok', detail: 'reachable' };\n\n let imgRes: CheckResult;\n try {\n const img = await imageInfo(DEFAULT_BOX_IMAGE);\n imgRes = img.exists\n ? { label: 'box image', status: 'ok', detail: `${DEFAULT_BOX_IMAGE} built` }\n : {\n label: 'box image',\n status: 'warn',\n detail: `${DEFAULT_BOX_IMAGE} not built`,\n hint: 'run `agentbox prepare --provider docker` (or let the wizard do it)',\n };\n } catch (err) {\n imgRes = { label: 'box image', status: 'warn', detail: errSummary(err) };\n }\n\n const volNames = [SHARED_CLAUDE_VOLUME, SHARED_CODEX_VOLUME, SHARED_OPENCODE_VOLUME];\n const vols = await Promise.all(\n volNames.map(async (n) => ({ name: n, exists: await volumeExists(n).catch(() => false) })),\n );\n const present = vols.filter((v) => v.exists).length;\n const volRes: CheckResult = {\n label: 'shared volumes',\n status: 'ok',\n detail: `${String(present)}/${String(vols.length)} present (seeded lazily)`,\n };\n\n const results = [cliRes, daemonRes, imgRes, volRes];\n // OrbStack serves per-box .orb.local URLs natively; Portless only matters on\n // plain Docker Desktop / Linux docker engine.\n if ((await detectEngine().catch(() => 'other')) !== 'orbstack') {\n results.push(portlessDoctorRow(await detectPortless()));\n }\n return results;\n}\n\nexport const providerModule: ProviderModule = {\n provider: dockerProvider,\n doctorChecks: dockerChecks,\n};\n","/**\n * Docker implementations of the settings-propagate seams\n * (`@agentbox/sandbox-core` `agent-propagate.ts`): stage items *from* a config\n * volume and write items *into* a config volume, both via throwaway helper\n * containers so they work regardless of any box's run state (a shared-volume\n * write covers every docker box on that volume, running or paused).\n */\n\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport type { SettingsTarget, StagedItem } from '@agentbox/sandbox-core';\n\nconst posixDirname = (rel: string) => {\n const d = dirname(rel);\n return d === '.' ? '' : d;\n};\n\n/**\n * Copy `items` from a config volume into `stagingDir` (volume-style layout).\n * One helper-container run; `rsync --exclude=node_modules` for dirs (the box\n * carries platform binaries useless off-box), `cp -a` for files. Staged files\n * are chowned to the host user so the CLI can read/push them.\n */\nexport async function stageItemsFromVolume(\n volume: string,\n image: string,\n items: StagedItem[],\n stagingDir: string,\n): Promise<void> {\n if (items.length === 0) return;\n for (const item of items) {\n const parent = posixDirname(item.rel);\n if (parent) await mkdir(join(stagingDir, parent), { recursive: true });\n }\n const uid = process.getuid?.() ?? 0;\n const gid = process.getgid?.() ?? 0;\n const cmds = items.map((item) =>\n item.kind === 'dir'\n ? `mkdir -p '/stage/${item.rel}' && rsync -a --exclude=node_modules '/src/${item.rel}/' '/stage/${item.rel}/'`\n : `cp -a '/src/${item.rel}' '/stage/${item.rel}'`,\n );\n cmds.push(`chown -R ${String(uid)}:${String(gid)} /stage`);\n const r = await execa(\n 'docker',\n [\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/src:ro`,\n '-v',\n `${stagingDir}:/stage`,\n image,\n 'sh',\n '-c',\n cmds.join(' && '),\n ],\n { reject: false },\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to stage items from volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n}\n\n/**\n * A `SettingsTarget` over a docker config volume. Every op is a helper\n * container; writes chown to the in-box uid 1000 (`vscode` in the box image).\n */\nexport function volumeSettingsTarget(volume: string, image: string, label: string): SettingsTarget {\n const run = (args: string[], input?: string) =>\n execa('docker', args, { reject: false, ...(input === undefined ? {} : { input }) });\n return {\n label,\n async exists(rel: string): Promise<boolean> {\n const r = await run(['run', '--rm', '-v', `${volume}:/dst:ro`, image, 'test', '-e', `/dst/${rel}`]);\n return r.exitCode === 0;\n },\n async readText(rel: string): Promise<string | null> {\n const r = await run([\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${volume}:/dst:ro`,\n image,\n 'cat',\n `/dst/${rel}`,\n ]);\n return r.exitCode === 0 ? String(r.stdout ?? '') : null;\n },\n async writeText(rel: string, content: string, opts?: { mode?: number }): Promise<void> {\n const parent = posixDirname(rel);\n const chmod = opts?.mode !== undefined ? ` && chmod ${opts.mode.toString(8)} '/dst/${rel}'` : '';\n const r = await run(\n [\n 'run',\n '--rm',\n '-i',\n '--user',\n '0',\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n `${parent ? `mkdir -p '/dst/${parent}' && ` : ''}cat > '/dst/${rel}' && chown 1000:1000 '/dst/${rel}'${chmod}`,\n ],\n content,\n );\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to write ${rel} into volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n },\n async copyIn(stagingAbs: string, rel: string, kind: 'dir' | 'file'): Promise<void> {\n const parent = posixDirname(rel);\n const script =\n `${parent ? `mkdir -p '/dst/${parent}' && ` : ''}` +\n (kind === 'dir'\n ? `mkdir -p '/dst/${rel}' && rsync -a --ignore-existing '/stage-item/' '/dst/${rel}/'`\n : `cp -a /stage-item '/dst/${rel}'`) +\n ` && chown -R 1000:1000 '/dst/${rel}'`;\n const r = await run([\n 'run',\n '--rm',\n '--user',\n '0',\n '-v',\n `${stagingAbs}:/stage-item:ro`,\n '-v',\n `${volume}:/dst`,\n image,\n 'sh',\n '-c',\n script,\n ]);\n if (r.exitCode !== 0) {\n throw new Error(\n `failed to copy ${rel} into volume ${volume}: ${(r.stderr ?? '').toString().trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n },\n };\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync, openSync } from 'node:fs';\nimport { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { fileURLToPath } from 'node:url';\nimport { DEFAULT_RELAY_PORT } from '@agentbox/relay';\nimport { detectPortless, portlessAlias, portlessGetUrl, portlessUnalias } from './portless.js';\nimport {\n fetchHealthz,\n killPid,\n pingHealthz,\n processAlive,\n resolveCliEntry,\n shouldReclaimForVersion,\n} from './relay.js';\nimport { detectEngine } from './sync/host-export.js';\nimport { BUILD_CONTEXT_DIR } from './image.js';\n\n/**\n * `agentbox hub` lifecycle. The hub is the embedded relay + Next UI in ONE\n * process on the relay port (8787) — a superset of the lean `agentbox-relay`.\n * The two are mutually exclusive on the port, so:\n * - starting the hub reclaims any lean relay already holding 8787;\n * - a running hub answers /healthz with `ui:true`, so the create path's\n * `ensureRelay()` reuses it (it also sets AGENTBOX_CLI_ENTRY so the capability\n * gate is satisfied and it's never reclaimed for that reason).\n *\n * Shares the low-level probes (fetchHealthz/pingHealthz/killPid/processAlive) and\n * the version-reclaim gate with relay.ts; keeps its own pid/log files so its\n * status is independent of the lean relay's.\n */\n\nconst STATE_DIR = join(homedir(), '.agentbox');\nconst HUB_PID_FILE = join(STATE_DIR, 'hub.pid');\nconst HUB_LOG_FILE = join(STATE_DIR, 'hub.log');\nconst HUB_TOKEN_FILE = join(STATE_DIR, 'hub', 'token');\nconst PORT = DEFAULT_RELAY_PORT;\nconst HOST = '127.0.0.1';\n\n/**\n * Portless alias for the hub itself. Unlike a box (a container that OrbStack can\n * reach at `<container>.orb.local`), the hub is a host loopback process, so\n * Portless is the only way to give it a friendly host URL. Fixed name → the URL\n * is always `https://agentbox.localhost` (kept static so the Next server-actions\n * origin allowlist can hard-code it). The resolved URL is cached to\n * `HUB_PORTLESS_FILE` so `getHubStatus` (read-only) knows the alias is actually\n * live — `portlessGetUrl` alone returns the deterministic fallback either way.\n */\nconst HUB_PORTLESS_ALIAS = 'agentbox';\nconst HUB_PORTLESS_FILE = join(STATE_DIR, 'hub', 'portless-url');\n\n/** Minimum Node for the hub server (node:sqlite in password mode + Next 16). */\nconst NODE_MIN = { major: 22, minor: 5 };\n\nexport interface HubEndpoint {\n /** Base URL the browser opens (127.0.0.1:8787). */\n hostUrl: string;\n /** Full open URL including `?token=` when the token gate is on. */\n openUrl: string;\n port: number;\n /** The token gate secret, when auth is on (localhost token mode). */\n token: string | null;\n}\n\nexport interface EnsureHubOptions {\n onLog?: (line: string) => void;\n /**\n * Effective `portless.enabled`. When not `false` (and Portless is installed on\n * a non-OrbStack host) the hub registers `https://agentbox.localhost`. Pass\n * `false` to force teardown. Undefined → register best-effort.\n */\n portlessEnabled?: boolean | undefined;\n}\n\nfunction nodeVersion(): { major: number; minor: number } {\n const [major, minor] = process.versions.node.split('.').map((n) => Number.parseInt(n, 10));\n return { major: major ?? 0, minor: minor ?? 0 };\n}\n\n/** Throw a clear error below the hub's Node floor (the CLI floor is lower). */\nfunction assertNodeSupported(): void {\n const v = nodeVersion();\n if (v.major < NODE_MIN.major || (v.major === NODE_MIN.major && v.minor < NODE_MIN.minor)) {\n throw new Error(\n `agentbox hub needs Node >= ${NODE_MIN.major}.${NODE_MIN.minor} (running ${process.versions.node}). ` +\n 'Upgrade Node, or run the lean relay with `agentbox relay start`.',\n );\n }\n}\n\n/**\n * Node flags for the hub spawn. `node:sqlite` (better-auth on the password\n * profile) is behind `--experimental-sqlite` on Node 22.5–23; unflagged on 24+.\n */\nfunction nodeFlags(): string[] {\n const v = nodeVersion();\n return v.major < 24 ? ['--experimental-sqlite'] : [];\n}\n\nasync function readPid(file: string): Promise<number | null> {\n try {\n const pid = Number.parseInt((await readFile(file, 'utf8')).trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\nasync function readToken(): Promise<string | null> {\n try {\n const t = (await readFile(HUB_TOKEN_FILE, 'utf8')).trim();\n return t.length > 0 ? t : null;\n } catch {\n return null;\n }\n}\n\nasync function endpointFor(portlessUrl?: string): Promise<HubEndpoint> {\n const token = await readToken();\n // Prefer the friendly Portless URL when one is registered; else the loopback.\n const hostUrl = portlessUrl ?? `http://${HOST}:${String(PORT)}`;\n return {\n hostUrl,\n openUrl: token ? `${hostUrl}/?token=${token}` : hostUrl,\n port: PORT,\n token,\n };\n}\n\n/** The Portless URL cached by a prior `syncHubPortless`, or null when unregistered. */\nasync function readHubPortlessUrl(): Promise<string | null> {\n try {\n const u = (await readFile(HUB_PORTLESS_FILE, 'utf8')).trim();\n return u.length > 0 ? u : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Register (or tear down) the hub's `agentbox.localhost` Portless alias and\n * return its resolved URL. Best-effort and never throws — a Portless failure\n * just leaves the hub on its loopback URL, exactly like the box path.\n *\n * Registers whenever Portless is installed and the engine isn't OrbStack, unless\n * `enabled === false` (explicit opt-out). `undefined` (never prompted) still\n * registers — the hub URL is a pure host-side convenience.\n */\nasync function syncHubPortless(enabled: boolean | undefined): Promise<string | undefined> {\n const teardown = async (): Promise<undefined> => {\n await portlessUnalias(HUB_PORTLESS_ALIAS).catch(() => {});\n await unlink(HUB_PORTLESS_FILE).catch(() => {});\n return undefined;\n };\n try {\n if (enabled === false) return await teardown();\n // The hub is a host process, so OrbStack's container-only .orb.local can't\n // reach it — and OrbStack users typically run no Portless proxy. Skip.\n if ((await detectEngine()) === 'orbstack') return await teardown();\n const portless = await detectPortless();\n if (!portless.installed) return await teardown();\n await portlessAlias(HUB_PORTLESS_ALIAS, PORT);\n const url = await portlessGetUrl(HUB_PORTLESS_ALIAS);\n await mkdir(dirname(HUB_PORTLESS_FILE), { recursive: true });\n await writeFile(HUB_PORTLESS_FILE, url, 'utf8');\n return url;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Locate the built hub server (`server.js`) the CLI spawns. Mirrors\n * relay.ts:resolveRelayBin. Layouts:\n * 0. env override: AGENTBOX_HUB_BIN\n * 1. bundled CLI: <root>/runtime/hub/apps/hub/server.js (sibling of dist/)\n * 2. workspace dev: <repo>/apps/hub/dist-standalone/apps/hub/server.js\n */\nexport function resolveHubServer(): string {\n const override = process.env.AGENTBOX_HUB_BIN;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '..', 'runtime', 'hub', 'apps', 'hub', 'server.js'),\n resolve(here, '..', '..', '..', 'apps', 'hub', 'dist-standalone', 'apps', 'hub', 'server.js'),\n resolve(here, '..', '..', 'apps', 'hub', 'dist-standalone', 'apps', 'hub', 'server.js'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n throw new Error(\n 'could not locate the built hub server; run `pnpm --filter @agentbox/hub build:standalone` ' +\n `(dev), or set AGENTBOX_HUB_BIN. Tried:\\n ${candidates.join('\\n ')}`,\n );\n}\n\n/** Kill whatever holds the port (a lean relay or a stale hub) and confirm it freed. */\nasync function reclaimPort(reportedPid: number | undefined, log: (line: string) => void): Promise<void> {\n const pidFromFile = await readPid(HUB_PID_FILE);\n const seen = new Set<number>();\n for (const pid of [reportedPid, pidFromFile]) {\n if (typeof pid !== 'number' || pid <= 0 || seen.has(pid)) continue;\n seen.add(pid);\n if (!(await processAlive(pid))) continue;\n log(`stopping process on :${String(PORT)} (pid ${String(pid)})`);\n await killPid(pid);\n }\n await unlink(HUB_PID_FILE).catch(() => {});\n if (await pingHealthz(300)) {\n throw new Error(\n `something is still listening on :${String(PORT)} and could not be stopped ` +\n `(reported pid ${String(reportedPid ?? 'unknown')}); kill it manually and retry`,\n );\n }\n}\n\n/**\n * Idempotently bring up the embedded hub on 8787. Reuses an already-running hub\n * (`ui:true`, version match); reclaims a lean relay or a version-mismatched hub\n * first. Best-effort like ensureRelay: failures throw.\n */\nexport async function ensureHub(opts: EnsureHubOptions = {}): Promise<HubEndpoint> {\n const log = opts.onLog ?? (() => {});\n assertNodeSupported();\n await mkdir(STATE_DIR, { recursive: true });\n\n const currentVersion = process.env.AGENTBOX_CLI_VERSION;\n const health = await fetchHealthz(500);\n if (health !== null) {\n if (health.ui === true && !shouldReclaimForVersion(health, currentVersion)) {\n return endpointFor(await syncHubPortless(opts.portlessEnabled)); // a hub already runs here\n }\n log(\n health.ui === true\n ? 'a hub from a different agentbox version holds :8787 — reclaiming'\n : 'a lean relay holds :8787 — reclaiming to start the hub',\n );\n await reclaimPort(health.pid, log);\n // fall through to spawn\n } else {\n const pid = await readPid(HUB_PID_FILE);\n if (pid !== null && (await processAlive(pid))) {\n // A hub process exists but isn't answering /healthz yet — give startup a\n // beat before deciding it's wedged.\n for (let i = 0; i < 10; i++) {\n if (await pingHealthz(300)) return endpointFor(await syncHubPortless(opts.portlessEnabled));\n await delay(200);\n }\n // Still unresponsive after ~2s: replace it rather than report a false\n // \"running\" for a hub that never came up.\n log(`hub pid ${String(pid)} alive but /healthz unresponsive — restarting it`);\n await reclaimPort(pid, log);\n // fall through to a fresh spawn\n } else if (pid !== null) {\n await unlink(HUB_PID_FILE).catch(() => {});\n }\n }\n\n const hubServer = resolveHubServer();\n const cliEntry = resolveCliEntry();\n if (cliEntry === null) {\n throw new Error(\n 'cannot start the hub: agentbox CLI entry not found (is the build complete?). ' +\n 'Set AGENTBOX_CLI_ENTRY to override.',\n );\n }\n return spawnHub(hubServer, cliEntry, log, opts.portlessEnabled);\n}\n\nasync function spawnHub(\n hubServer: string,\n cliEntry: string,\n log: (line: string) => void,\n portlessEnabled: boolean | undefined,\n): Promise<HubEndpoint> {\n const logFd = openSync(HUB_LOG_FILE, 'a');\n const child = spawn(process.execPath, [...nodeFlags(), hubServer], {\n detached: true,\n stdio: ['ignore', logFd, logFd],\n env: {\n ...process.env,\n // The staged hub is a production Next build; force production so server.ts\n // takes the standalone path (dev mode would load webpack, which the\n // standalone build prunes).\n NODE_ENV: 'production',\n AGENTBOX_CLI_ENTRY: cliEntry,\n // The hub is the localhost profile (token gate); bind loopback.\n AGENTBOX_HUB_HOST: HOST,\n // The hub bundle ships no staged docker build context of its own, so its\n // in-process docker base-freshness check couldn't fingerprint (degrading\n // to 'unknown'). Hand it the CLI's resolved context so hub-side\n // fingerprints match what the create/prepare workers compute.\n AGENTBOX_DOCKER_CONTEXT: BUILD_CONTEXT_DIR,\n },\n });\n child.unref();\n // Note when the child dies before it ever answers /healthz. The common cause is\n // a startup crash (e.g. a missing runtime dep) whose stack the child already\n // wrote to HUB_LOG_FILE — we surface that tail rather than making the user wait\n // out the full timeout and then go read the log by hand.\n let exit: { code: number | null; signal: NodeJS.Signals | null } | null = null;\n child.on('exit', (code, signal) => {\n exit = { code, signal };\n });\n if (typeof child.pid === 'number') {\n await writeFile(HUB_PID_FILE, String(child.pid), 'utf8');\n log(`spawned hub process (pid ${String(child.pid)}, port ${String(PORT)})`);\n }\n // Next prepare takes a beat longer than the lean relay; give it ~25s.\n for (let i = 0; i < 50; i++) {\n if (await pingHealthz(300)) {\n log(`hub reachable on http://${HOST}:${String(PORT)}`);\n const purl = await syncHubPortless(portlessEnabled);\n if (purl) log(`hub also reachable on ${purl}`);\n return endpointFor(purl);\n }\n if (exit !== null) {\n await unlink(HUB_PID_FILE).catch(() => {});\n // Let the child flush its last stderr line into the log before we tail it.\n await delay(150);\n throw new Error(await hubStartupError(`hub process exited (${describeExit(exit)}) during startup`));\n }\n await delay(200);\n }\n throw new Error(await hubStartupError(`hub did not become reachable on http://${HOST}:${String(PORT)} within ~25s`));\n}\n\nfunction describeExit(exit: { code: number | null; signal: NodeJS.Signals | null }): string {\n if (exit.signal !== null) return `killed by ${exit.signal}`;\n return `exit code ${String(exit.code ?? 'unknown')}`;\n}\n\n/** Build a startup-failure message with the tail of the hub log inlined. */\nasync function hubStartupError(headline: string): Promise<string> {\n const tail = await tailFile(HUB_LOG_FILE, 20);\n const suffix = tail ? `\\n--- last lines of ${HUB_LOG_FILE} ---\\n${tail}` : `; see ${HUB_LOG_FILE}`;\n return `${headline}${suffix}`;\n}\n\n/** Last `maxLines` non-empty lines of a file, or '' when unreadable/empty. */\nasync function tailFile(file: string, maxLines: number): Promise<string> {\n try {\n const lines = (await readFile(file, 'utf8')).split('\\n').filter((l) => l.trim().length > 0);\n return lines.slice(-maxLines).join('\\n');\n } catch {\n return '';\n }\n}\n\nexport interface StopHubResult {\n stopped: boolean;\n pid: number | null;\n}\n\n/** Best-effort teardown of the hub's Portless alias + its cached URL file. */\nasync function unregisterHubPortless(): Promise<void> {\n await portlessUnalias(HUB_PORTLESS_ALIAS).catch(() => {});\n await unlink(HUB_PORTLESS_FILE).catch(() => {});\n}\n\n/** Stop the hub process + clear its pidfile. SIGTERM then SIGKILL. Idempotent. */\nexport async function stopHub(): Promise<StopHubResult> {\n const pid = await readPid(HUB_PID_FILE);\n if (pid === null) {\n await unregisterHubPortless();\n return { stopped: false, pid: null };\n }\n if (!(await processAlive(pid))) {\n await unlink(HUB_PID_FILE).catch(() => {});\n await unregisterHubPortless();\n return { stopped: false, pid };\n }\n await killPid(pid);\n await unlink(HUB_PID_FILE).catch(() => {});\n await unregisterHubPortless();\n return { stopped: true, pid };\n}\n\nexport interface HubStatus {\n /** /healthz responded. */\n running: boolean;\n /** /healthz reported a delegated Next UI (vs a bare relay on the port). */\n ui: boolean;\n pid: number | null;\n pidAlive: boolean;\n port: number;\n hostUrl: string;\n openUrl: string;\n token: string | null;\n pidFile: string;\n logFile: string;\n}\n\n/** Read-only snapshot of the hub's liveness (mirrors getRelayStatus). */\nexport async function getHubStatus(): Promise<HubStatus> {\n const pid = await readPid(HUB_PID_FILE);\n const pidAlive = pid !== null && (await processAlive(pid));\n const health = await fetchHealthz(300);\n const ep = await endpointFor((await readHubPortlessUrl()) ?? undefined);\n return {\n running: health !== null,\n ui: health?.ui === true,\n pid,\n pidAlive,\n port: PORT,\n hostUrl: ep.hostUrl,\n openUrl: ep.openUrl,\n token: ep.token,\n pidFile: HUB_PID_FILE,\n logFile: HUB_LOG_FILE,\n };\n}\n","export { dockerProvider, type DockerCreateOptions } from './docker-provider.js';\nexport { providerModule, dockerChecks } from './provider-module.js';\nexport { downloadFromBox, uploadToBox, type BoxCpResult } from './box-cp.js';\nexport { createDockerSyncTransport, type DockerSyncTransportInit } from './sync/sync-transport.js';\nexport { stageItemsFromVolume, volumeSettingsTarget } from './sync/settings-propagate.js';\nexport { makeDockerSync, type DockerSyncHandle } from './sync/docker-sync.js';\n\nexport {\n attachClaudeSession,\n formatDetachNotice,\n buildClaudeAttachArgv,\n buildDashboardAttachArgv,\n buildClaudeLoginRunArgv,\n buildClaudeMounts,\n buildTmuxSessionArgs,\n buildTmuxConfigShellSnippet,\n TERM_FALLBACK_SNIPPET,\n buildShellArgv,\n CLAUDE_FORWARDED_ENV_KEYS,\n ClaudeSessionError,\n claudeSessionInfo,\n CONTAINER_USER,\n DEFAULT_CLAUDE_SESSION,\n ensureClaudeVolume,\n pullClaudeExtras,\n rebuildPluginNativeDeps,\n resolveClaudeVolume,\n runInteractiveClaudeLogin,\n scanPluginCacheForRebuild,\n seedSetupSkillIntoVolume,\n SHARED_CLAUDE_VOLUME,\n startClaudeSession,\n waitForTmuxPaneContent,\n warmUpClaudeCredentials,\n type ClaudeConfigSpec,\n type ClaudeMountResult,\n type ClaudeSessionInfo,\n type EnsureClaudeVolumeOptions,\n type EnsureClaudeVolumeResult,\n type PullClaudeOptions,\n type PullClaudeResult,\n type RebuildPluginNativeDepsResult,\n type StartClaudeSessionOptions,\n type WarmUpClaudeResult,\n} from './sync/agents/claude.js';\nexport {\n CREDENTIALS_BACKUP_FILE,\n CODEX_CREDENTIALS_BACKUP_FILE,\n OPENCODE_CREDENTIALS_BACKUP_FILE,\n hostBackupHasCredentials,\n hostClaudeBackupExpired,\n isRealAgentCredential,\n parseSyncResult,\n parseExtractResult,\n parseVolumeClaudeCredentials,\n volumeClaudeCredentials,\n syncClaudeCredentials,\n extractVolumeAuthToBackup,\n extractCodexCredentials,\n extractOpencodeCredentials,\n type CredentialAgentKind,\n type CredentialSyncDirection,\n type SyncClaudeCredentialsResult,\n type VolumeClaudeCredentials,\n} from './sync/claude-credentials.js';\nexport {\n BOX_SYSTEM_PROMPT_PATH,\n buildCodexAgentsOverrideScript,\n CODEX_OVERRIDE_WROTE_MARKER,\n buildCodexAttachArgv,\n buildCodexLoginRunArgv,\n buildCodexMounts,\n CODEX_FORWARDED_ENV_KEYS,\n CodexSessionError,\n codexSessionInfo,\n DEFAULT_CODEX_SESSION,\n ensureCodexInstalled,\n ensureCodexVolume,\n pullCodexConfig,\n resolveCodexVolume,\n runInteractiveCodexLogin,\n seedCodexAgentsOverride,\n seedCodexHooks,\n SHARED_CODEX_VOLUME,\n startCodexSession,\n volumeHasCodexAuth,\n type CodexConfigSpec,\n type CodexMountResult,\n type CodexSessionInfo,\n type EnsureCodexInstalledResult,\n type EnsureCodexVolumeOptions,\n type EnsureCodexVolumeResult,\n type PullCodexOptions,\n type PullCodexResult,\n type StartCodexSessionOptions,\n} from './sync/agents/codex.js';\nexport {\n buildAgentsMounts,\n ensureAgentsVolume,\n resolveAgentsVolume,\n SHARED_AGENTS_VOLUME,\n type AgentsConfigSpec,\n type AgentsMountResult,\n type EnsureAgentsVolumeOptions,\n type EnsureAgentsVolumeResult,\n} from './sync/agents/skills.js';\nexport {\n buildOpencodeAttachArgv,\n buildOpencodeLoginRunArgv,\n buildOpencodeMounts,\n DEFAULT_OPENCODE_SESSION,\n ensureOpencodeInstalled,\n ensureOpencodeVolume,\n seedOpencodePlugin,\n OPENCODE_FORWARDED_ENV_KEYS,\n OpencodeSessionError,\n opencodeSessionInfo,\n pullOpencodeConfig,\n resolveOpencodeVolume,\n runInteractiveOpencodeLogin,\n SHARED_OPENCODE_VOLUME,\n startOpencodeSession,\n volumeHasOpencodeAuth,\n type EnsureOpencodeInstalledResult,\n type EnsureOpencodeVolumeOptions,\n type EnsureOpencodeVolumeResult,\n type OpencodeConfigSpec,\n type OpencodeMountResult,\n type OpencodeSessionInfo,\n type PullOpencodeOptions,\n type PullOpencodeResult,\n type StartOpencodeSessionOptions,\n} from './sync/agents/opencode.js';\nexport { createBox, type CreateBoxOptions, type CreatedBox } from './create.js';\nexport {\n agentboxHomeBytes,\n allCheckpointImagesBytes,\n boxResourceStats,\n parseDockerSize,\n projectCheckpointImageBytes,\n volumeSizeBytes,\n} from './stats.js';\nexport { getBoxEndpoints, type BoxEndpoint, type BoxEndpoints } from './endpoints.js';\nexport { execInBox, removeImage, type DockerExecResult } from './docker.js';\nexport {\n detectGitRepos,\n GitWorktreeError,\n pickFreshBranch,\n type DetectedGitRepo,\n} from './git-worktree.js';\nexport {\n bindWorktrees,\n collectRepoCarryOver,\n gitWorktreePathFor,\n removeInBoxWorktree,\n seedWorkspace,\n seedWorkspaceFromDir,\n WORKTREE_ROOT,\n type RepoCarryOver,\n type SeedWorkspaceOptions,\n type WorktreeBindSpec,\n} from './sync/in-box-git.js';\nexport {\n DEFAULT_BOX_IMAGE,\n BOX_IMAGE_REGISTRY,\n registryRefForSha,\n ensureImage,\n classifyDockerBaseFreshness,\n evaluateDockerBaseFreshness,\n type DockerBaseFreshness,\n pullOrBuild,\n pullImage,\n tagImage,\n imageExists,\n imageInfo,\n type ImageInfo,\n type EnsureImageOptions,\n type PullOrBuildOptions,\n} from './image.js';\nexport {\n computeDockerContextFingerprint,\n preparedMatches,\n readPreparedDockerState,\n resolveContextFiles,\n writePreparedDockerState,\n type PreparedDockerState,\n type ResolvedFingerprint,\n} from './prepared-state.js';\nexport { volumeExists } from './docker.js';\nexport {\n clearRelayNotice,\n DEFAULT_RELAY_PORT,\n ensureRelay,\n forgetBoxFromRelay,\n generateRelayToken,\n getRelayStatus,\n mintHostInitiatedToken,\n registerBoxWithRelay,\n rehydrateRelayRegistry,\n resolveRelayBin,\n RELAY_CONTAINER_NAME,\n RELAY_IMAGE_REF,\n RELAY_NETWORK_NAME,\n setRelayNotice,\n stopRelay,\n type EnsureRelayOptions,\n type RegisterBoxArgs,\n type RelayEndpoint,\n type RelayStatus,\n type StopRelayResult,\n} from './relay.js';\nexport {\n ensureHub,\n getHubStatus,\n resolveHubServer,\n stopHub,\n type EnsureHubOptions,\n type HubEndpoint,\n type HubStatus,\n type StopHubResult,\n} from './hub.js';\n// The host-config stage producers now live in the provider-neutral sync layer\n// (`@agentbox/sandbox-core`); cloud consumers import them from there. The claude\n// per-project path helpers + Stage types stay re-exported here (from core) for\n// existing `@agentbox/sandbox-docker` importers.\nexport {\n encodeClaudeProjectsKey,\n resolveClaudeMemoryDir,\n BOX_CLAUDE_PROJECT_DIR,\n type StageClaudeOptions,\n type StageCodexOptions,\n type StageOpencodeOptions,\n type StageResult,\n} from '@agentbox/sandbox-core';\nexport {\n BOX_WORKFLOWS_DIR,\n BOX_MEMORY_DIR,\n BOX_DYNAMIC_SYNC_MANIFEST,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncManifest,\n type DynamicSyncSet,\n type DynamicSyncSetName,\n type DynamicSyncDelta,\n type DynamicSyncUpload,\n type DynamicSyncDeletion,\n type HostSyncManifest,\n type StagedTarball,\n} from './sync/dynamic-sync.js';\nexport { EXCLUDE_DIRS, SNAPSHOTS_ROOT, snapshotPathFor } from './snapshot.js';\nexport {\n CHECKPOINTS_ROOT,\n CHECKPOINT_IMAGE_PREFIX,\n CheckpointError,\n checkpointImageTag,\n computeNextCheckpointName,\n createCheckpoint,\n listAllCheckpointImages,\n listAllCheckpoints,\n listCheckpoints,\n projectCheckpointsDir,\n removeCheckpoint,\n resolveCheckpoint,\n type CheckpointInfo,\n type CheckpointProjectGroup,\n type CheckpointManifest,\n type CheckpointType,\n type CreateCheckpointOptions,\n} from './checkpoint.js';\nexport {\n STATE_DIR,\n STATE_FILE,\n allocateProjectIndex,\n autoPickProjectBox,\n findBox,\n readState,\n recordBox,\n recordLastAgent,\n removeBoxRecord,\n resolveBoxRef,\n type BoxRecord,\n type FindBoxResult,\n type GitWorktreeRecord,\n type StateFile,\n} from './state.js';\nexport {\n attachedContainerUri,\n buildFlavorMounts,\n buildIdeMounts,\n buildVscodeMounts,\n cursorServerVolumeName,\n ensureAgentboxTasksFile,\n ensureIdeVolumes,\n ensureVscodeVolumes,\n ideProfile,\n IDE_FLAVORS,\n ideServerVolumeName,\n repairIdeOwnership,\n repairVscodeServerOwnership,\n SHARED_CURSOR_EXTENSIONS_VOLUME,\n SHARED_VSCODE_EXTENSIONS_VOLUME,\n vscodeServerVolumeName,\n type EnsureTasksFileResult,\n type IdeFlavor,\n type IdeMounts,\n type ServiceTailHint,\n type VscodeMounts,\n} from './vscode.js';\nexport {\n BOXES_ROOT,\n boxRunDirFor,\n boxStatusPathFor,\n readBoxStatus,\n buildHostEnvFindArgs,\n CONTAINER_EXPORT_MERGED,\n copyHostEnvFilesToBox,\n copyHostFilesToBox,\n orbstackVolumePath,\n DEFAULT_ENV_PATTERNS,\n carrySourceHash,\n copyCarryPathsToBox,\n detectEngine,\n getDockerContext,\n ExportError,\n getHostPaths,\n openInFinder,\n pullToHost,\n refreshExport,\n scanHostEnvFiles,\n setEngineOverride,\n type CopyCarryOptions,\n type CopyCarryResult,\n type DockerEngine,\n type HostPaths,\n type CopyHostEnvOptions,\n type CopyHostFilesOptions,\n type OpenOptions,\n type OpenResult,\n type PullOptions,\n type PullResult,\n type RefreshOptions,\n type RefreshResult,\n} from './sync/host-export.js';\nexport {\n detectPortless,\n installPortless,\n portlessBrowserEnv,\n portlessAlias,\n portlessUnalias,\n portlessGetUrl,\n portlessInstallHint,\n portlessStartHint,\n portlessDoctorRow,\n PORTLESS_PROXY_PORT,\n resetPortlessCache,\n resolvePortlessHostStateDir,\n startPortlessProxy,\n startPortlessProxyRoot,\n type PortlessBrowserEnvOptions,\n type PortlessState,\n type RootProxyStartResult,\n} from './portless.js';\nexport {\n AmbiguousBoxError,\n BoxNotFoundError,\n destroyBox,\n getBoxHostPaths,\n inspectBox,\n listBoxes,\n openBoxInFinder,\n pauseBox,\n pruneBoxes,\n refreshBoxSshd,\n resyncBox,\n snapshotPresent,\n startBox,\n stopBox,\n unpauseBox,\n type DestroyOptions,\n type DestroyResult,\n type InspectedBox,\n type ListedBox,\n type OpenedBox,\n type PruneOptions,\n type PruneResult,\n type StartedBox,\n} from './lifecycle.js';\nexport {\n buildVncUrls,\n generateVncPassword,\n launchVncDaemon,\n VNC_CONTAINER_PORT,\n type VncLaunchResult,\n type VncUrls,\n} from './vnc.js';\nexport {\n installAuthorizedKey,\n launchSshdDaemon,\n setUpBoxSshd,\n SSH_CONTAINER_PORT,\n type BoxSshSetup,\n type SshLaunchResult,\n} from './ssh.js';\nexport {\n browserSessionActive,\n ensureBoxBrowser,\n ensureBoxBrowserShowingApp,\n type BoxBrowserAppResult,\n type BoxBrowserResult,\n} from './browser.js';\nexport {\n allocateShellSessionName,\n buildShellSessionAttachArgv,\n DEFAULT_SHELL_SESSION,\n isShellSessionName,\n killShellSession,\n listShellSessions,\n parseShellSessionList,\n SHELL_SESSION_PREFIX,\n shellLabel,\n shellSessionInfo,\n shellSessionName,\n startShellSession,\n type ShellSessionInfo,\n type ShellSessionSummary,\n type StartShellSessionOptions,\n} from './shell-session.js';\nexport {\n dockerVolumeName,\n launchDockerdDaemon,\n SHARED_DOCKER_CACHE_VOLUME,\n type DockerdLaunchResult,\n} from './dockerd.js';\n\n// The new `dockerProvider` (implementing the provider-neutral `Provider`\n// interface from @agentbox/core) is exported from ./docker-provider.js at the\n// top of this file. The CLI resolves it via apps/cli/src/provider/registry.ts.\n","/**\n * Incremental host -> box seed of Claude Code's *dynamic* config (global\n * `~/.claude/workflows/` scripts + the current project's `memory/` tree).\n *\n * The logic moved to the shared sync layer (`@agentbox/sandbox-core`'s\n * `sync/concerns/dynamic`) so the cloud `seedDynamicConfig` reuses it without\n * importing this package — the dependency leak the sync refactor closes. This\n * module re-exports it verbatim so existing `@agentbox/sandbox-docker` import\n * sites (the docker index, the dynamic-sync test) keep working.\n */\n\nexport {\n BOX_WORKFLOWS_DIR,\n BOX_DYNAMIC_SYNC_MANIFEST,\n BOX_MEMORY_DIR,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncSetName,\n type DynamicSyncSet,\n type DynamicSyncManifest,\n type HostSyncManifest,\n type DynamicSyncUpload,\n type DynamicSyncDeletion,\n type DynamicSyncDelta,\n type StagedTarball,\n} from '@agentbox/sandbox-core';\n","import { execInBox } from './docker.js';\nimport { readBoxStatus } from './sync/host-export.js';\n\nexport interface BoxBrowserResult {\n up: boolean;\n /** True when a session was already active, so we left the agent's browser untouched. */\n alreadyRunning?: boolean;\n reason?: string;\n}\n\n/**\n * Decide whether `agent-browser session list` reports a live session. Pure so\n * it can be unit-tested without docker. `agent-browser` exits 0 and prints\n * \"No active sessions\" when nothing is running; any other exit-0 output lists\n * one or more sessions (a persistent Chromium is up).\n */\nexport function browserSessionActive(stdout: string, exitCode: number): boolean {\n return exitCode === 0 && !/no active sessions/i.test(stdout);\n}\n\n/**\n * Ensure the box's in-box browser (agent-browser's persistent default-session\n * Chromium) is running, so the VNC view shows a browser instead of a blank X\n * screen. Idempotent: if a session is already active we do nothing — the agent\n * may be mid-task and we must not navigate its page away. Otherwise we open\n * `targetUrl` (default `about:blank`) **headed** (agent-browser defaults to\n * headless — a headless Chromium renders nothing on the VNC display, defeating\n * the whole point), so the agent's subsequent `agent-browser open <url>` reuses\n * the same visible window (it just navigates it). `agentbox screen` passes the\n * box's own web-service URL (`http://localhost:<expose.port>`) so the app is\n * shown *inside* the VNC desktop rather than popped open on the host.\n *\n * Best-effort, mirroring {@link import('./vnc.js').launchVncDaemon} — the\n * caller warns on failure but never aborts (the noVNC client still connects).\n * `DISPLAY=:1` + `AGENT_BROWSER_EXECUTABLE_PATH` are image-baked env so the\n * exec inherits them; runs as `vscode` like the other in-box launches.\n *\n * When `targetUrl` is the box's Portless `<name>.localhost` URL, the in-box\n * Chromium routes it back out to the host Portless proxy — the box's\n * `AGENT_BROWSER_ARGS` env (set at create, see `portlessBrowserEnv`) carries\n * the `--host-resolver-rules` that makes that work.\n */\nexport async function ensureBoxBrowser(\n container: string,\n timeoutMs = 8000,\n targetUrl = 'about:blank',\n): Promise<BoxBrowserResult> {\n const list = await execInBox(container, ['agent-browser', 'session', 'list'], {\n user: 'vscode',\n timeoutMs,\n });\n if (browserSessionActive(list.stdout, list.exitCode)) {\n return { up: true, alreadyRunning: true };\n }\n\n const open = await execInBox(container, ['agent-browser', 'open', '--headed', targetUrl], {\n user: 'vscode',\n timeoutMs,\n });\n if (open.exitCode === 0) return { up: true };\n return {\n up: false,\n reason: `agent-browser open failed: ${open.stderr || open.stdout || `exit ${String(open.exitCode)}`}`,\n };\n}\n\nexport interface BoxBrowserAppResult extends BoxBrowserResult {\n /** URL the in-box browser was pointed at (`about:blank` when no web service). */\n target: string;\n}\n\n/**\n * {@link ensureBoxBrowser} with the target derived from the box itself: the\n * box's exposed web service (Portless URL preferred, in-box loopback port as\n * fallback), or `about:blank` when nothing is exposed. This is the whole\n * \"the VNC desktop shows the app, not a blank X screen\" step — shared by\n * `agentbox screen`, the dashboard, and the hub's open-VNC action so every\n * surface that opens the VNC viewer gets a populated desktop.\n */\nexport async function ensureBoxBrowserShowingApp(box: {\n container: string;\n id: string;\n name: string;\n projectIndex?: number;\n portlessUrl?: string;\n}): Promise<BoxBrowserAppResult> {\n const persisted = await readBoxStatus(box);\n const exposePort = persisted?.services.find((s) => s.expose)?.expose?.port;\n const target =\n exposePort !== undefined\n ? (box.portlessUrl ?? `http://localhost:${String(exposePort)}`)\n : 'about:blank';\n const res = await ensureBoxBrowser(box.container, undefined, target);\n return { ...res, target };\n}\n","export type ServiceState =\n | 'pending'\n | 'waiting'\n | 'starting'\n | 'running'\n | 'ready'\n | 'unhealthy'\n | 'crashed'\n | 'backoff'\n | 'stopped';\n\nexport type TaskState = 'pending' | 'waiting' | 'running' | 'done' | 'failed' | 'skipped';\n\nexport interface ServiceStatus {\n name: string;\n state: ServiceState;\n pid: number | null;\n restarts: number;\n lastExitCode: number | null;\n startedAt: string | null;\n readyAt: string | null;\n nextRetryAt: string | null;\n blockedOn: string[];\n command: string;\n}\n\nexport interface StatusReply {\n services: ServiceStatus[];\n tasks: TaskStatus[];\n ports: BoxStatusPort[];\n}\n\nexport interface WaitReadyArgs {\n timeoutMs?: number;\n units?: string[];\n}\n\nexport type WaitReadyReply =\n | { ready: true }\n | { ready: false; timedOut: string[]; failed: string[] };\n\nexport interface TaskStatus {\n name: string;\n state: TaskState;\n pid: number | null;\n lastExitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n command: string;\n}\n\nexport interface LogEvent {\n service: string;\n ts: string;\n stream: 'stdout' | 'stderr';\n line: string;\n}\n\nexport interface ReloadResult {\n added: string[];\n removed: string[];\n changed: string[];\n}\n\n/**\n * Coarse activity state of the in-box Claude Code session, fed by Claude Code\n * hooks via `agentbox-ctl claude-state <state>`. `unknown` is the initial value\n * before any hook has fired (or for boxes whose image predates the hooks).\n *\n * `end-plan` and `question` are PreToolUse-driven fine-grained states: Claude\n * is about to call ExitPlanMode (plan finished, awaiting human approval) or\n * AskUserQuestion (interactive prompt shown). The matching PostToolUse hook\n * clears them back to `working`. The hook also pipes the tool input JSON to\n * the daemon so `agentbox agent get-plan-question` can read the plan body or\n * the questions[] array without scraping the terminal.\n *\n * `compacting` is fed by Claude's PreCompact hook (the conversation is being\n * summarized to free context space). PostCompact clears it via\n * `working --clear-pending`. `error` is fed by StopFailure (a turn ended with\n * an unrecoverable failure); the next UserPromptSubmit / Stop naturally\n * supersedes it.\n *\n * The same union is reused for Codex and OpenCode via {@link AgentActivityState}.\n */\nexport type ClaudeActivityState =\n | 'working'\n | 'idle'\n | 'waiting'\n | 'end-plan'\n | 'question'\n | 'compacting'\n | 'error'\n | 'unknown';\n\nexport const CLAUDE_ACTIVITY_STATES: readonly ClaudeActivityState[] = [\n 'working',\n 'idle',\n 'waiting',\n 'end-plan',\n 'question',\n 'compacting',\n 'error',\n 'unknown',\n];\n\n/** Body shape extracted from the ExitPlanMode hook payload. */\nexport interface ClaudePlanPayload {\n /** Markdown plan body — Claude Code's `plan` tool input field. */\n plan: string;\n /** ISO-8601 timestamp the hook fired. */\n capturedAt: string;\n}\n\n/** Body shape extracted from the AskUserQuestion hook payload. */\nexport interface ClaudeQuestionPayload {\n /** Each entry is one question Claude is asking; usually length 1. */\n questions: Array<{\n question: string;\n header?: string;\n multiSelect?: boolean;\n options: Array<{ label: string; description?: string }>;\n }>;\n capturedAt: string;\n}\n\n/**\n * Same coarse activity union, reused for any agent. Codex feeds it via\n * `agentbox-ctl codex-state <state>` (Codex lifecycle hooks); the value space\n * is identical to {@link ClaudeActivityState}.\n */\nexport type AgentActivityState = ClaudeActivityState;\n\nexport interface BoxStatusServiceEntry {\n name: string;\n state: ServiceState;\n /** Configured `ready_when` port for this service, else null. */\n port: number | null;\n /**\n * Whether the service declares a `ready_when` probe (port OR log_match). A\n * probed service stays in `running` until its probe passes and only then\n * becomes `ready`, so `running` does NOT mean \"up\" for it — readers should\n * treat a probed `running` service as still warming up. Additive field:\n * absent (older snapshots) means treat as unprobed (i.e. `running` is up).\n */\n probed?: boolean;\n /**\n * The service's `expose:` mapping (container `as` → in-box `port`) when it is\n * the designated web service, else absent. Additive field — snapshots written\n * before this existed simply lack it (schema stays 1; treat absent as none).\n */\n expose?: { port: number; as: number };\n}\n\nexport interface BoxStatusTaskEntry {\n name: string;\n state: TaskState;\n}\n\nexport interface BoxStatusPort {\n port: number;\n /** Name of the service whose `ready_when` port matches, else null (ad-hoc). */\n service: string | null;\n}\n\nexport interface BoxStatusClaude {\n state: ClaudeActivityState;\n /** ISO-8601 time the last claude-state hook fired, or null if none yet. */\n updatedAt: string | null;\n /** Whether the claude tmux session was present at snapshot time. */\n sessionRunning: boolean;\n /**\n * Human-readable title Claude Code set on its terminal (the in-box tmux\n * pane title), sanitized. Additive field — snapshots written before this\n * existed simply lack it (schema stays 1; treat absent as no title).\n */\n sessionTitle?: string;\n /**\n * Last captured plan body — populated when `state === 'end-plan'`. The\n * matching PostToolUse hook clears it. Additive — older snapshots lack it.\n */\n plan?: ClaudePlanPayload;\n /**\n * Last captured AskUserQuestion content — populated when `state === 'question'`.\n * Cleared on the matching PostToolUse hook. Additive.\n */\n question?: ClaudeQuestionPayload;\n}\n\n/**\n * Codex session status — parallel to {@link BoxStatusClaude}. `state` is fed by\n * Codex lifecycle hooks via `agentbox-ctl codex-state <state>`.\n */\nexport interface BoxStatusCodex {\n state: AgentActivityState;\n /** ISO-8601 time the last codex-state hook fired, or null if none yet. */\n updatedAt: string | null;\n /** Whether the codex tmux session was present at snapshot time. */\n sessionRunning: boolean;\n /** Sanitized in-box tmux pane title, when the Codex TUI set one. */\n sessionTitle?: string;\n}\n\n/**\n * OpenCode session status — parallel to {@link BoxStatusClaude} /\n * {@link BoxStatusCodex}. `state` is fed by the agentbox OpenCode plugin\n * (seeded into `~/.config/opencode/plugin/agentbox-state.js`) which\n * subscribes to OpenCode's event bus and shells `agentbox-ctl opencode-state`\n * for each lifecycle transition.\n */\nexport interface BoxStatusOpencode {\n state: AgentActivityState;\n /** ISO-8601 time the last opencode-state hook fired, or null if none yet. */\n updatedAt: string | null;\n /** Whether the opencode tmux session was present at snapshot time. */\n sessionRunning: boolean;\n /** Sanitized in-box tmux pane title, when the OpenCode TUI set one. */\n sessionTitle?: string;\n}\n\n/**\n * Durable snapshot of a box's runtime status. The in-box daemon builds it and\n * pushes it to the host relay, which persists it to\n * `~/.agentbox/boxes/<id>/status.json` so `agentbox status` / `list` /\n * `inspect` can show it even when the box is paused or stopped.\n */\nexport interface BoxStatus {\n /** Schema version; bump on incompatible changes so old readers can reject. */\n schema: 1;\n boxId: string;\n /** ISO-8601 time the daemon built this snapshot. */\n timestamp: string;\n services: BoxStatusServiceEntry[];\n tasks: BoxStatusTaskEntry[];\n /** Live-discovered listening TCP ports inside the box. */\n ports: BoxStatusPort[];\n claude: BoxStatusClaude;\n /**\n * Codex / OpenCode session status. Additive + optional — present only when\n * that agent's tmux session is running (or, for codex, a hook has fired);\n * a claude-only box's snapshot simply omits them (schema stays 1).\n */\n codex?: BoxStatusCodex;\n opencode?: BoxStatusOpencode;\n}\n\nexport const BOX_STATUS_SCHEMA = 1 as const;\n\n/** Relay event type carrying a `BoxStatus` payload. */\nexport const BOX_STATUS_EVENT = 'box-status';\n\n/**\n * Relay event type carrying a refreshed agent credential blob (the\n * credentials watcher's payload). The host relay mirrors this constant\n * (`packages/relay/src/server.ts`, like `box-status`) — it special-cases the\n * type so the secret payload never lands in the event ring buffer.\n */\nexport const CREDENTIALS_UPDATED_EVENT = 'credentials-updated';\n\nexport type CtlRequest =\n | { op: 'status' }\n | { op: 'task-status' }\n | { op: 'wait-ready'; timeoutMs?: number; units?: string[] }\n | { op: 'run-task'; name: string; force?: boolean }\n | { op: 'logs'; service: string; tail?: number; follow?: boolean }\n | { op: 'restart'; service: string }\n | { op: 'stop'; service: string }\n | { op: 'start'; service: string }\n | { op: 'reload' }\n | { op: 'ping' }\n | { op: 'claude-session'; sessionName?: string }\n | {\n op: 'claude-state';\n state: ClaudeActivityState;\n /**\n * Optional payload from a PreToolUse hook. For `end-plan` carries the\n * plan body; for `question` carries the AskUserQuestion params. Cleared\n * when the matching PostToolUse hook fires with `state: 'working'` and\n * `clearPending: true`.\n */\n plan?: ClaudePlanPayload;\n question?: ClaudeQuestionPayload;\n /**\n * Set by the matching PostToolUse hook (`claude-state working\n * --clear-pending`) to force-exit a sticky end-plan/question state. The\n * catchall PreToolUse `working` hook races with the matcher-specific\n * `end-plan`/`question` hook on the same tool invocation; sticky\n * semantics in the reporter swallow that race, and `clearPending`\n * marks the legitimate post-tool transition out.\n */\n clearPending?: boolean;\n }\n | { op: 'codex-state'; state: AgentActivityState }\n | { op: 'opencode-state'; state: AgentActivityState };\n\nexport type CtlResponse = { ok: true; data: unknown } | { ok: false; error: string };\n\n/**\n * Status of the in-container tmux session running Claude Code. The daemon\n * doesn't own this session lifecycle — it probes via `tmux has-session` and\n * `tmux display-message`. Missing tmux server / missing session both surface\n * as `running: false`.\n */\nexport interface ClaudeSessionStatus {\n running: boolean;\n sessionName: string;\n /** ISO-8601 timestamp from tmux's `#{session_created}`, or null when not running. */\n startedAt: string | null;\n /**\n * Sanitized tmux `#{pane_title}` (the title Claude Code set on its\n * terminal), or null when not running / no meaningful title.\n */\n title: string | null;\n}\n\nexport const DEFAULT_SOCKET_PATH = '/run/agentbox/ctl.sock';\nexport const DEFAULT_CONFIG_PATH = '/workspace/agentbox.yaml';\nexport const DEFAULT_LOG_DIR = '/var/log/agentbox';\n// Where run_once task completion markers live. On the box rootfs (survives\n// pause/stop/start and is captured by `docker commit` checkpoints) but NOT under\n// /workspace, so markers never show up as untracked git changes.\nexport const DEFAULT_STATE_DIR = '/var/lib/agentbox';\nexport const DEFAULT_CLAUDE_SESSION_NAME = 'claude';\nexport const DEFAULT_CODEX_SESSION_NAME = 'codex';\nexport const DEFAULT_OPENCODE_SESSION_NAME = 'opencode';\n","import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { createConnection, type Socket } from 'node:net';\nimport type {\n ClaudeActivityState,\n ClaudePlanPayload,\n ClaudeQuestionPayload,\n ClaudeSessionStatus,\n CtlRequest,\n CtlResponse,\n LogEvent,\n ReloadResult,\n ServiceStatus,\n StatusReply,\n TaskStatus,\n WaitReadyArgs,\n WaitReadyReply,\n} from './types.js';\n\nexport interface ConnectOptions {\n socketPath: string;\n /** Default 3000 ms. */\n timeoutMs?: number;\n}\n\ninterface NodeErrno extends Error {\n code?: string;\n}\n\n/**\n * Best-effort daemon respawn when the unix socket is dead. `docker exec -d`\n * leaves no log when the daemon crashes on startup and Node doesn't unlink\n * unix sockets on exit, so an orphaned file is the symptom we see most often.\n * Spawning the bin detached and polling for a fresh listener recovers without\n * needing host involvement — mirrors `ensureRelay()` on the host side.\n *\n * Gated on `AGENTBOX=1` (set on every box at `docker run`) so unit tests on\n * the host — which start an ephemeral server with no `agentbox-ctl` bin\n * anywhere on PATH — don't accidentally spawn anything.\n */\nasync function tryReviveDaemon(socketPath: string): Promise<boolean> {\n if (process.env.AGENTBOX !== '1') return false;\n try {\n const child = spawn('agentbox-ctl', ['daemon'], {\n detached: true,\n stdio: 'ignore',\n });\n child.unref();\n } catch {\n return false;\n }\n // The daemon `unlink`s any stale socket file before `listen()`, so once the\n // file reappears it's bound to a live listener.\n for (let i = 0; i < 50; i++) {\n await new Promise((r) => setTimeout(r, 100));\n if (existsSync(socketPath)) return true;\n }\n return false;\n}\n\nasync function connectOnce(opts: ConnectOptions): Promise<Socket> {\n const sock = createConnection(opts.socketPath);\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n sock.destroy();\n reject(new Error(`connect ${opts.socketPath} timed out`));\n }, opts.timeoutMs ?? 3000);\n sock.once('connect', () => {\n clearTimeout(timer);\n resolve();\n });\n sock.once('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n });\n return sock;\n}\n\nasync function connect(opts: ConnectOptions): Promise<Socket> {\n try {\n return await connectOnce(opts);\n } catch (err) {\n // Only ECONNREFUSED (stale socket file, no listener) and ENOENT (no file\n // at all) suggest a missing daemon. Anything else (EACCES, ETIMEDOUT, …)\n // is a real failure we shouldn't try to paper over.\n const code = (err as NodeErrno).code;\n if (code !== 'ECONNREFUSED' && code !== 'ENOENT') throw err;\n const revived = await tryReviveDaemon(opts.socketPath);\n if (!revived) throw err;\n return await connectOnce(opts);\n }\n}\n\nasync function sendOneShot<T>(opts: ConnectOptions, req: CtlRequest): Promise<T> {\n const sock = await connect(opts);\n sock.write(`${JSON.stringify(req)}\\n`);\n let buf = '';\n sock.setEncoding('utf8');\n for await (const chunk of sock) {\n buf += chunk as string;\n const idx = buf.indexOf('\\n');\n if (idx !== -1) {\n const line = buf.slice(0, idx);\n sock.end();\n return parseResponse<T>(line);\n }\n }\n // Connection closed before we got a full line.\n if (buf.length > 0) return parseResponse<T>(buf);\n throw new Error('connection closed with no response');\n}\n\nfunction parseResponse<T>(line: string): T {\n const parsed = JSON.parse(line) as CtlResponse;\n if (parsed.ok) return parsed.data as T;\n throw new Error(parsed.error);\n}\n\nexport async function ping(opts: ConnectOptions): Promise<'pong'> {\n return sendOneShot<'pong'>(opts, { op: 'ping' });\n}\n\nexport async function status(opts: ConnectOptions): Promise<StatusReply> {\n return sendOneShot<StatusReply>(opts, { op: 'status' });\n}\n\nexport async function taskStatus(opts: ConnectOptions): Promise<TaskStatus[]> {\n return sendOneShot<TaskStatus[]>(opts, { op: 'task-status' });\n}\n\nexport async function waitReady(\n opts: ConnectOptions,\n args: WaitReadyArgs = {},\n): Promise<WaitReadyReply> {\n return sendOneShot<WaitReadyReply>(opts, {\n op: 'wait-ready',\n timeoutMs: args.timeoutMs,\n units: args.units,\n });\n}\n\nexport async function runTask(\n opts: ConnectOptions,\n name: string,\n force?: boolean,\n): Promise<TaskStatus> {\n return sendOneShot<TaskStatus>(opts, { op: 'run-task', name, force });\n}\n\nexport async function restart(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'restart', service });\n}\n\nexport async function stop(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'stop', service });\n}\n\nexport async function start(opts: ConnectOptions, service: string): Promise<ServiceStatus> {\n return sendOneShot<ServiceStatus>(opts, { op: 'start', service });\n}\n\nexport async function reload(opts: ConnectOptions): Promise<ReloadResult> {\n return sendOneShot<ReloadResult>(opts, { op: 'reload' });\n}\n\nexport async function claudeSession(\n opts: ConnectOptions & { sessionName?: string },\n): Promise<ClaudeSessionStatus> {\n return sendOneShot<ClaudeSessionStatus>(opts, {\n op: 'claude-session',\n sessionName: opts.sessionName,\n });\n}\n\nexport async function claudeState(\n opts: ConnectOptions,\n state: ClaudeActivityState,\n payload?: {\n plan?: ClaudePlanPayload;\n question?: ClaudeQuestionPayload;\n clearPending?: boolean;\n },\n): Promise<'ok'> {\n return sendOneShot<'ok'>(opts, {\n op: 'claude-state',\n state,\n ...(payload?.plan ? { plan: payload.plan } : {}),\n ...(payload?.question ? { question: payload.question } : {}),\n ...(payload?.clearPending ? { clearPending: true } : {}),\n });\n}\n\nexport async function codexState(\n opts: ConnectOptions,\n state: ClaudeActivityState,\n): Promise<'ok'> {\n return sendOneShot<'ok'>(opts, { op: 'codex-state', state });\n}\n\nexport async function opencodeState(\n opts: ConnectOptions,\n state: ClaudeActivityState,\n): Promise<'ok'> {\n return sendOneShot<'ok'>(opts, { op: 'opencode-state', state });\n}\n\nexport interface LogsResult {\n initial: LogEvent[];\n /**\n * When `follow: true` was passed, this async iterator yields further events\n * until the caller breaks out (which closes the socket).\n */\n follow?: AsyncIterableIterator<LogEvent>;\n}\n\nexport async function logs(\n opts: ConnectOptions,\n args: { service: string; tail?: number; follow?: boolean },\n): Promise<LogsResult> {\n const sock = await connect(opts);\n sock.write(`${JSON.stringify({ op: 'logs', ...args })}\\n`);\n\n const lines = createLineIterator(sock);\n const first = await lines.next();\n if (first.done) {\n sock.end();\n throw new Error('connection closed with no response');\n }\n const parsed = JSON.parse(first.value) as CtlResponse;\n if (!parsed.ok) {\n sock.end();\n throw new Error(parsed.error);\n }\n const data = parsed.data as { events: LogEvent[]; follow: boolean };\n if (!data.follow) {\n sock.end();\n return { initial: data.events };\n }\n\n const followGen = (async function* () {\n try {\n for await (const line of lines) {\n const p = JSON.parse(line) as CtlResponse;\n if (p.ok && p.data && typeof p.data === 'object' && 'event' in p.data) {\n yield (p.data as { event: LogEvent }).event;\n }\n }\n } finally {\n sock.end();\n }\n })();\n\n return { initial: data.events, follow: followGen };\n}\n\nasync function* createLineIterator(sock: Socket): AsyncIterableIterator<string> {\n let buf = '';\n sock.setEncoding('utf8');\n for await (const chunk of sock) {\n buf += chunk as string;\n let idx = buf.indexOf('\\n');\n while (idx !== -1) {\n yield buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n idx = buf.indexOf('\\n');\n }\n }\n if (buf.length > 0) yield buf;\n}\n","import type { BoxStatusPort, ServiceStatus, TaskStatus } from './types.js';\n\nexport function renderStatusTable(rows: ServiceStatus[]): string {\n if (rows.length === 0) return '(no services configured)';\n const headers = ['NAME', 'STATE', 'PID', 'RESTARTS', 'LAST EXIT', 'BLOCKED ON', 'COMMAND'];\n const data: string[][] = rows.map((r) => [\n r.name,\n r.state,\n r.pid === null ? '-' : String(r.pid),\n String(r.restarts),\n r.lastExitCode === null ? '-' : String(r.lastExitCode),\n r.blockedOn.length === 0 ? '-' : r.blockedOn.join(','),\n truncate(r.command, 40),\n ]);\n return renderTable(headers, data);\n}\n\nexport function renderTaskTable(rows: TaskStatus[]): string {\n if (rows.length === 0) return '(no tasks configured)';\n const headers = ['NAME', 'STATE', 'EXIT', 'STARTED', 'FINISHED', 'COMMAND'];\n const data: string[][] = rows.map((r) => [\n r.name,\n r.state,\n r.lastExitCode === null ? '-' : String(r.lastExitCode),\n r.startedAt ?? '-',\n r.finishedAt ?? '-',\n truncate(r.command, 40),\n ]);\n return renderTable(headers, data);\n}\n\nexport function renderPortsTable(rows: BoxStatusPort[]): string {\n if (rows.length === 0) return '(no ports listening)';\n const named = rows.filter((r) => r.service);\n const other = rows\n .filter((r) => !r.service)\n .map((r) => r.port)\n .sort((a, b) => a - b);\n const lines: string[] = [];\n if (named.length > 0) {\n lines.push(\n renderTable(\n ['PORT', 'SERVICE'],\n named.map((r) => [`:${String(r.port)}`, r.service ?? '-']),\n ),\n );\n }\n // Collapse the unattributed ports (VNC, dev-tool worker IPC, multi-port\n // services like inngest) into one line so they don't drown the real services.\n if (other.length > 0) {\n lines.push(`other (${other.length}): ${other.join(', ')}`);\n }\n return lines.join('\\n');\n}\n\nfunction renderTable(headers: string[], data: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...data.map((row) => (row[i] ?? '').length)),\n );\n const fmt = (row: string[]): string =>\n row.map((cell, i) => cell.padEnd(widths[i] ?? cell.length)).join(' ');\n return [fmt(headers), ...data.map(fmt)].join('\\n');\n}\n\nfunction truncate(s: string, n: number): string {\n if (s.length <= n) return s;\n return s.slice(0, n - 1) + '…';\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport { parseReplacements, type ReplaceRule } from './replace.js';\n\nexport type RestartPolicy = 'always' | 'on-failure' | 'never';\nexport type ProbeOnTimeout = 'kill' | 'mark_unhealthy';\n\nexport interface BackoffSpec {\n initialMs: number;\n maxMs: number;\n factor: number;\n}\n\nexport interface PortProbe {\n kind: 'port';\n port: number;\n host: string;\n intervalMs: number;\n initialDelayMs: number;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport interface LogMatchProbe {\n kind: 'log_match';\n pattern: RegExp;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport interface HttpProbe {\n kind: 'http';\n url: string;\n expectStatus?: number;\n intervalMs: number;\n initialDelayMs: number;\n timeoutMs: number;\n onTimeout: ProbeOnTimeout;\n}\n\nexport type ReadyProbe = PortProbe | LogMatchProbe | HttpProbe;\n\nexport interface ExposeSpec {\n /** The port this service listens on inside the box. */\n port: number;\n /** Container port forwarded to it. Only 80 is reserved/published today. */\n as: number;\n}\n\n/**\n * Declarative \"run once\" for a task. The supervisor re-runs every task from\n * `pending` on each box start; `run_once` lets it skip a task that has already\n * succeeded.\n *\n * - `{ kind: 'marker' }` (from `run_once: true`) — the supervisor stores a\n * marker keyed by a hash of the resolved command; a warm boot skips while the\n * hash matches, and editing the command re-runs.\n * - `{ kind: 'check', command }` (from `run_once: { check: ... }`) — run the\n * probe before launching; exit 0 means already satisfied (skip). No marker:\n * the probe is the source of truth (right for data that lives outside the\n * checkpointed filesystem, e.g. a containerized DB).\n */\nexport type RunOnceSpec = { kind: 'marker' } | { kind: 'check'; command: string };\n\nexport interface TaskSpec {\n name: string;\n command: string | string[];\n cwd?: string;\n env?: Record<string, string>;\n needs: string[];\n runOnce?: RunOnceSpec;\n}\n\nexport interface ServiceSpec {\n name: string;\n command: string | string[];\n cwd?: string;\n env?: Record<string, string>;\n autostart: boolean;\n restart: RestartPolicy;\n backoff: BackoffSpec;\n needs: string[];\n readyWhen?: ReadyProbe;\n /** When set, container port `expose.as` forwards to `127.0.0.1:expose.port`. */\n expose?: ExposeSpec;\n /**\n * Declarative docker sidecar. When set, `command` is synthesized into a\n * `docker start`-or-`run` shell (the in-box dockerd container is reused by\n * name across restarts). Mutually exclusive with a user `command`. The other\n * `*image*` fields below are kept for introspection; `env` is baked into the\n * container's `-e` flags and not set as the process env.\n */\n image?: string;\n /** Port publishes (\"<host>:<container>\" or \"<port>\"); image services only. */\n ports?: string[];\n /** Extra args appended after the image (shell-tokenized); image services only. */\n args?: string;\n /** Container name (default = service name); image services only. */\n containerName?: string;\n}\n\nexport interface CtlConfig {\n services: ServiceSpec[];\n tasks: TaskSpec[];\n /** Named reusable replacement rule-sets (top-level `replacements:` block). */\n replacements: Record<string, ReplaceRule[]>;\n}\n\nexport const DEFAULT_BACKOFF: BackoffSpec = {\n initialMs: 500,\n maxMs: 30_000,\n factor: 2,\n};\n\nexport const DEFAULT_PROBE_INTERVAL_MS = 500;\nexport const DEFAULT_PROBE_INITIAL_DELAY_MS = 0;\nexport const DEFAULT_PROBE_TIMEOUT_MS = 60_000;\nexport const DEFAULT_PROBE_HOST = '127.0.0.1';\nexport const DEFAULT_PROBE_ON_TIMEOUT: ProbeOnTimeout = 'kill';\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigError';\n }\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction parseEnv(raw: unknown, where: string): Record<string, string> | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.env must be a mapping of string → string`);\n }\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(raw)) {\n if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {\n throw new ConfigError(`${where}.env.${k} must be a scalar`);\n }\n out[k] = String(v);\n }\n return out;\n}\n\nfunction parseCommand(raw: unknown, where: string): string | string[] {\n if (typeof raw === 'string') {\n if (raw.trim().length === 0) {\n throw new ConfigError(`${where}.command must not be empty`);\n }\n return raw;\n }\n if (Array.isArray(raw)) {\n if (raw.length === 0) {\n throw new ConfigError(`${where}.command array must not be empty`);\n }\n const argv: string[] = [];\n for (const [i, item] of raw.entries()) {\n if (typeof item !== 'string') {\n throw new ConfigError(`${where}.command[${String(i)}] must be a string`);\n }\n argv.push(item);\n }\n return argv;\n }\n throw new ConfigError(`${where}.command must be a string or array of strings`);\n}\n\nfunction parseRestart(raw: unknown, where: string): RestartPolicy {\n if (raw === undefined) return 'on-failure';\n if (raw === 'always' || raw === 'on-failure' || raw === 'never') return raw;\n throw new ConfigError(`${where}.restart must be one of: always, on-failure, never`);\n}\n\nconst BACKOFF_KEYS = new Set(['initial_ms', 'max_ms', 'factor']);\n\nfunction parseBackoff(raw: unknown, where: string): BackoffSpec {\n if (raw === undefined) return { ...DEFAULT_BACKOFF };\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.backoff must be a mapping`);\n }\n rejectUnknownKeys(raw, BACKOFF_KEYS, `${where}.backoff`);\n const initialMs = parseNonNegativeInt(\n raw.initial_ms,\n `${where}.backoff.initial_ms`,\n DEFAULT_BACKOFF.initialMs,\n );\n const maxMs = parseNonNegativeInt(raw.max_ms, `${where}.backoff.max_ms`, DEFAULT_BACKOFF.maxMs);\n const factor = parseFactor(raw.factor, `${where}.backoff.factor`, DEFAULT_BACKOFF.factor);\n if (maxMs < initialMs) {\n throw new ConfigError(`${where}.backoff.max_ms must be >= initial_ms`);\n }\n return { initialMs, maxMs, factor };\n}\n\nfunction rejectUnknownKeys(\n obj: Record<string, unknown>,\n allowed: Set<string>,\n where: string,\n): void {\n for (const key of Object.keys(obj)) {\n if (!allowed.has(key)) {\n throw new ConfigError(`${where} has unknown key \"${key}\"`);\n }\n }\n}\n\nfunction parseNonNegativeInt(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 0) {\n throw new ConfigError(`${where} must be a non-negative number`);\n }\n return Math.floor(raw);\n}\n\nfunction parsePositiveInt(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) {\n throw new ConfigError(`${where} must be a positive integer`);\n }\n return Math.floor(raw);\n}\n\nfunction parseFactor(raw: unknown, where: string, fallback: number): number {\n if (raw === undefined) return fallback;\n if (typeof raw !== 'number' || !Number.isFinite(raw) || raw < 1) {\n throw new ConfigError(`${where} must be a number >= 1`);\n }\n return raw;\n}\n\nfunction parseOnTimeout(raw: unknown, where: string): ProbeOnTimeout {\n if (raw === undefined) return DEFAULT_PROBE_ON_TIMEOUT;\n if (raw === 'kill' || raw === 'mark_unhealthy') return raw;\n throw new ConfigError(`${where} must be one of: kill, mark_unhealthy`);\n}\n\nfunction parseNeeds(raw: unknown, where: string): string[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) {\n throw new ConfigError(`${where} must be an array of unit names`);\n }\n const seen = new Set<string>();\n const out: string[] = [];\n for (const [i, item] of raw.entries()) {\n if (typeof item !== 'string') {\n throw new ConfigError(`${where}[${String(i)}] must be a string`);\n }\n if (!/^[A-Za-z0-9_-]+$/.test(item)) {\n throw new ConfigError(`${where}[${String(i)}] \"${item}\" must match [A-Za-z0-9_-]+`);\n }\n if (seen.has(item)) continue;\n seen.add(item);\n out.push(item);\n }\n return out;\n}\n\nconst PROBE_KEYS = new Set([\n 'port',\n 'host',\n 'log_match',\n 'http',\n 'expect_status',\n 'interval_ms',\n 'initial_delay_ms',\n 'timeout_ms',\n 'on_timeout',\n]);\n\nfunction parseReadyWhen(raw: unknown, where: string): ReadyProbe | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.ready_when must be a mapping`);\n }\n rejectUnknownKeys(raw, PROBE_KEYS, `${where}.ready_when`);\n\n const kinds: Array<'port' | 'log_match' | 'http'> = [];\n if (raw.port !== undefined) kinds.push('port');\n if (raw.log_match !== undefined) kinds.push('log_match');\n if (raw.http !== undefined) kinds.push('http');\n if (kinds.length === 0) {\n throw new ConfigError(\n `${where}.ready_when must declare exactly one of: port, log_match, http`,\n );\n }\n if (kinds.length > 1) {\n throw new ConfigError(\n `${where}.ready_when may declare only one of: port, log_match, http (got ${kinds.join(', ')})`,\n );\n }\n\n const timeoutMs = parsePositiveInt(\n raw.timeout_ms,\n `${where}.ready_when.timeout_ms`,\n DEFAULT_PROBE_TIMEOUT_MS,\n );\n const onTimeout = parseOnTimeout(raw.on_timeout, `${where}.ready_when.on_timeout`);\n\n const kind = kinds[0]!;\n if (kind === 'log_match') {\n if (raw.host !== undefined || raw.expect_status !== undefined || raw.interval_ms !== undefined || raw.initial_delay_ms !== undefined) {\n throw new ConfigError(\n `${where}.ready_when.log_match cannot be combined with host/expect_status/interval_ms/initial_delay_ms`,\n );\n }\n const pat = assertString(raw.log_match, `${where}.ready_when.log_match`);\n let pattern: RegExp;\n try {\n pattern = new RegExp(pat);\n } catch (err) {\n throw new ConfigError(\n `${where}.ready_when.log_match is not a valid regex: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return { kind: 'log_match', pattern, timeoutMs, onTimeout };\n }\n\n const intervalMs = parsePositiveInt(\n raw.interval_ms,\n `${where}.ready_when.interval_ms`,\n DEFAULT_PROBE_INTERVAL_MS,\n );\n const initialDelayMs = parseNonNegativeInt(\n raw.initial_delay_ms,\n `${where}.ready_when.initial_delay_ms`,\n DEFAULT_PROBE_INITIAL_DELAY_MS,\n );\n\n if (kind === 'port') {\n if (raw.expect_status !== undefined) {\n throw new ConfigError(`${where}.ready_when.expect_status only applies to http probes`);\n }\n const port = parsePositiveInt(raw.port, `${where}.ready_when.port`, 0);\n if (port < 1 || port > 65535) {\n throw new ConfigError(`${where}.ready_when.port must be between 1 and 65535`);\n }\n const host =\n raw.host === undefined\n ? DEFAULT_PROBE_HOST\n : assertString(raw.host, `${where}.ready_when.host`);\n return { kind: 'port', port, host, intervalMs, initialDelayMs, timeoutMs, onTimeout };\n }\n\n if (raw.host !== undefined) {\n throw new ConfigError(`${where}.ready_when.host only applies to port probes`);\n }\n const url = assertString(raw.http, `${where}.ready_when.http`);\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new ConfigError(`${where}.ready_when.http must be a valid URL`);\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new ConfigError(`${where}.ready_when.http must use http(s):// (got ${parsed.protocol})`);\n }\n let expectStatus: number | undefined;\n if (raw.expect_status !== undefined) {\n expectStatus = parsePositiveInt(raw.expect_status, `${where}.ready_when.expect_status`, 0);\n if (expectStatus < 100 || expectStatus > 599) {\n throw new ConfigError(`${where}.ready_when.expect_status must be between 100 and 599`);\n }\n }\n return { kind: 'http', url, expectStatus, intervalMs, initialDelayMs, timeoutMs, onTimeout };\n}\n\n/**\n * The only container port AgentBox reserves + publishes for a web service today\n * (see `WEB_CONTAINER_PORT` host-side in @agentbox/sandbox-docker). A service's\n * `expose.as` must equal this — any other value would parse fine but be\n * unreachable from the host, so we reject it loudly.\n */\nexport const RESERVED_WEB_PORT = 80;\n\nconst SERVICE_KEYS = new Set([\n 'command',\n 'cwd',\n 'env',\n 'autostart',\n 'restart',\n 'backoff',\n 'needs',\n 'ready_when',\n 'expose',\n 'ide',\n 'image',\n]);\n\n// The container config nested under a service's `image:` (when it's a mapping).\nconst IMAGE_KEYS = new Set(['name', 'ports', 'env', 'args', 'container_name']);\n\n// Minimal POSIX single-quote escaping for values baked into a generated\n// `bash -c` docker command. (sandbox-cloud has an equivalent quoteShellArg, but\n// ctl can't depend on it — wrong direction.)\nfunction shQuote(s: string): string {\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s)) return s;\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction parsePorts(raw: unknown, where: string): string[] | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!Array.isArray(raw)) {\n throw new ConfigError(`${where}.ports must be a list of \"<host>:<container>\" strings`);\n }\n const out: string[] = [];\n for (const [i, v] of raw.entries()) {\n const s = typeof v === 'number' ? String(v) : v;\n if (typeof s !== 'string' || !/^\\d+(:\\d+)?$/.test(s.trim())) {\n throw new ConfigError(\n `${where}.ports[${String(i)}] must be \"<host>\" or \"<host>:<container>\" (got ${JSON.stringify(v)})`,\n );\n }\n out.push(s.trim());\n }\n return out.length > 0 ? out : undefined;\n}\n\n// `args` is a string (appended raw, bash word-splits) or a list of strings\n// (joined with spaces, then bash word-splits) — so both `args: \"-c x=1\"` and\n// `args: [\"-c\", \"x=1\"]` produce the same docker invocation.\nfunction parseArgs(raw: unknown, where: string): string | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw === 'string') return raw.trim().length > 0 ? raw : undefined;\n if (Array.isArray(raw)) {\n const parts: string[] = [];\n for (const [i, v] of raw.entries()) {\n if (typeof v !== 'string') throw new ConfigError(`${where}.args[${String(i)}] must be a string`);\n parts.push(v);\n }\n const joined = parts.join(' ').trim();\n return joined.length > 0 ? joined : undefined;\n }\n throw new ConfigError(`${where}.args must be a string or a list of strings`);\n}\n\n// Build the start-or-run shell for an `image:` service. Reuses the existing\n// container by name across restarts (data lives in the per-box /var/lib/docker);\n// a config change needs a manual `docker rm <name>`.\nfunction synthesizeImageCommand(opts: {\n image: string;\n name: string;\n ports?: string[];\n env?: Record<string, string>;\n args?: string;\n}): string {\n const name = shQuote(opts.name);\n const run = ['docker', 'run', '--name', name];\n for (const p of opts.ports ?? []) run.push('-p', shQuote(p));\n for (const [k, v] of Object.entries(opts.env ?? {})) run.push('-e', `${k}=${shQuote(v)}`);\n run.push(shQuote(opts.image));\n let runLine = run.join(' ');\n if (opts.args) runLine += ` ${opts.args}`; // raw — bash word-splits\n return [\n 'set -e',\n `if docker container inspect ${name} >/dev/null 2>&1; then`,\n ` docker start ${name} >/dev/null`,\n ` exec docker logs -f ${name}`,\n 'else',\n ` exec ${runLine}`,\n 'fi',\n ].join('\\n');\n}\n\ninterface ParsedImage {\n name: string;\n ports?: string[];\n env?: Record<string, string>;\n args?: string;\n containerName: string;\n}\n\n// Parse a service's `image:` — either a bare ref string (shorthand) or a mapping\n// `{ name, ports?, env?, args?, container_name? }`. `defaultName` (the service\n// name) is the default container name.\nfunction parseImage(raw: unknown, where: string, defaultName: string): ParsedImage {\n if (typeof raw === 'string') {\n const name = raw.trim();\n if (name.length === 0) throw new ConfigError(`${where}.image must not be empty`);\n return { name, containerName: defaultName };\n }\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.image must be an image ref string or a mapping`);\n }\n rejectUnknownKeys(raw, IMAGE_KEYS, `${where}.image`);\n const name = assertString(raw.name, `${where}.image.name`).trim();\n if (name.length === 0) throw new ConfigError(`${where}.image.name must not be empty`);\n const ports = parsePorts(raw.ports, `${where}.image`);\n const args = parseArgs(raw.args, `${where}.image`);\n const env = parseEnv(raw.env, `${where}.image`);\n const containerName =\n raw.container_name === undefined\n ? defaultName\n : assertString(raw.container_name, `${where}.image.container_name`).trim();\n if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(containerName)) {\n throw new ConfigError(\n `${where}.image.container_name \"${containerName}\" is not a valid docker container name`,\n );\n }\n const out: ParsedImage = { name, containerName };\n if (ports !== undefined) out.ports = ports;\n if (env !== undefined) out.env = env;\n if (args !== undefined) out.args = args;\n return out;\n}\n\nconst EXPOSE_KEYS = new Set(['port', 'as']);\n\nfunction parseExpose(raw: unknown, where: string): ExposeSpec | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where}.expose must be a mapping`);\n }\n rejectUnknownKeys(raw, EXPOSE_KEYS, `${where}.expose`);\n if (raw.port === undefined) {\n throw new ConfigError(`${where}.expose.port is required`);\n }\n const port = parsePortNumber(raw.port, `${where}.expose.port`);\n const as = raw.as === undefined ? RESERVED_WEB_PORT : parsePortNumber(raw.as, `${where}.expose.as`);\n if (as !== RESERVED_WEB_PORT) {\n throw new ConfigError(\n `${where}.expose.as must be ${String(RESERVED_WEB_PORT)} (the only container port AgentBox publishes)`,\n );\n }\n return { port, as };\n}\n\nfunction parsePortNumber(raw: unknown, where: string): number {\n if (typeof raw !== 'number' || !Number.isInteger(raw) || raw < 1 || raw > 65535) {\n throw new ConfigError(`${where} must be an integer between 1 and 65535`);\n }\n return raw;\n}\n\nfunction parseService(name: string, raw: unknown): ServiceSpec {\n const where = `services.${name}`;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where} must be a mapping`);\n }\n rejectUnknownKeys(raw, SERVICE_KEYS, where);\n\n const hasImage = raw.image !== undefined && raw.image !== null;\n const hasCommand = raw.command !== undefined && raw.command !== null;\n if (hasImage && hasCommand) {\n throw new ConfigError(`${where} sets both command and image — use exactly one`);\n }\n if (!hasImage && !hasCommand) {\n throw new ConfigError(`${where} must set either command or image`);\n }\n\n const cwd = raw.cwd === undefined ? undefined : assertString(raw.cwd, `${where}.cwd`);\n const autostart =\n raw.autostart === undefined ? true : assertBool(raw.autostart, `${where}.autostart`);\n const restart = parseRestart(raw.restart, where);\n const backoff = parseBackoff(raw.backoff, where);\n const needs = parseNeeds(raw.needs, `${where}.needs`);\n const readyWhen = parseReadyWhen(raw.ready_when, where);\n const expose = parseExpose(raw.expose, where);\n\n if (hasImage) {\n if (raw.env !== undefined) {\n throw new ConfigError(`${where}.env is not valid for an image service — use image.env`);\n }\n const img = parseImage(raw.image, where, name);\n const command = synthesizeImageCommand({\n image: img.name,\n name: img.containerName,\n ports: img.ports,\n env: img.env,\n args: img.args,\n });\n const spec: ServiceSpec = {\n name,\n command,\n cwd,\n autostart,\n restart,\n backoff,\n needs,\n readyWhen,\n expose,\n image: img.name,\n containerName: img.containerName,\n };\n if (img.ports !== undefined) spec.ports = img.ports;\n if (img.args !== undefined) spec.args = img.args;\n return spec;\n }\n\n const command = parseCommand(raw.command, where);\n const env = parseEnv(raw.env, where);\n return { name, command, cwd, env, autostart, restart, backoff, needs, readyWhen, expose };\n}\n\nconst TASK_KEYS = new Set(['command', 'cwd', 'env', 'needs', 'run_once']);\n\nfunction parseRunOnce(raw: unknown, where: string): RunOnceSpec | undefined {\n if (raw === undefined || raw === null || raw === false) return undefined;\n if (raw === true) return { kind: 'marker' };\n if (isPlainObject(raw)) {\n const keys = Object.keys(raw);\n if (keys.length !== 1 || keys[0] !== 'check') {\n throw new ConfigError(`${where}.run_once object form must be exactly { check: <command> }`);\n }\n const check = raw.check;\n if (typeof check !== 'string' || check.trim().length === 0) {\n throw new ConfigError(`${where}.run_once.check must be a non-empty command string`);\n }\n return { kind: 'check', command: check };\n }\n throw new ConfigError(`${where}.run_once must be true or { check: <command> }`);\n}\n\nfunction parseTask(name: string, raw: unknown): TaskSpec {\n const where = `tasks.${name}`;\n if (!isPlainObject(raw)) {\n throw new ConfigError(`${where} must be a mapping`);\n }\n rejectUnknownKeys(raw, TASK_KEYS, where);\n const command = parseCommand(raw.command, where);\n const cwd = raw.cwd === undefined ? undefined : assertString(raw.cwd, `${where}.cwd`);\n const env = parseEnv(raw.env, where);\n const needs = parseNeeds(raw.needs, `${where}.needs`);\n const runOnce = parseRunOnce(raw.run_once, where);\n const spec: TaskSpec = { name, command, cwd, env, needs };\n if (runOnce !== undefined) spec.runOnce = runOnce;\n return spec;\n}\n\nfunction assertString(raw: unknown, where: string): string {\n if (typeof raw !== 'string') throw new ConfigError(`${where} must be a string`);\n return raw;\n}\n\nfunction assertBool(raw: unknown, where: string): boolean {\n if (typeof raw !== 'boolean') throw new ConfigError(`${where} must be a boolean`);\n return raw;\n}\n\n// `defaults` is the host-side config layer (read by @agentbox/config) — the\n// supervisor doesn't touch it, but we accept it here so `ctl validate` doesn't\n// flag it as unknown. Strict typo-detection still applies (top-level keys\n// outside this set are rejected).\n// `carry` is the host-side declarative file-carry block (read by the apps/cli\n// layer via @agentbox/ctl/carry, applied at create time). The supervisor never\n// reads it — listing it here only suppresses the unknown-key error so a project\n// yaml that declares `carry:` still parses cleanly inside the box.\n// `replacements` is the top-level reusable replacement-rule block, consumed by\n// the in-box `agentbox-ctl render` CLI and host-side `carry:` rule refs. We\n// parse + validate it here (regex compile-check) so a typo fails loud in-box.\nconst TOP_LEVEL_KEYS = new Set(['services', 'tasks', 'ide', 'defaults', 'carry', 'replacements']);\n\nfunction validateUnitGraph(tasks: TaskSpec[], services: ServiceSpec[]): void {\n const names = new Set<string>();\n for (const t of tasks) {\n if (names.has(t.name)) {\n throw new ConfigError(`unit name \"${t.name}\" declared more than once (task vs service collision)`);\n }\n names.add(t.name);\n }\n for (const s of services) {\n if (names.has(s.name)) {\n throw new ConfigError(`unit name \"${s.name}\" declared more than once (task vs service collision)`);\n }\n names.add(s.name);\n }\n\n const deps = new Map<string, string[]>();\n for (const t of tasks) deps.set(t.name, t.needs);\n for (const s of services) deps.set(s.name, s.needs);\n\n for (const [unit, list] of deps) {\n for (const dep of list) {\n if (!names.has(dep)) {\n throw new ConfigError(`unit \"${unit}\" needs unknown unit \"${dep}\"`);\n }\n if (dep === unit) {\n throw new ConfigError(`unit \"${unit}\" cannot depend on itself`);\n }\n }\n }\n\n // DFS with three-color marking; record the cycle path in the error.\n const WHITE = 0, GRAY = 1, BLACK = 2;\n const color = new Map<string, number>();\n for (const name of deps.keys()) color.set(name, WHITE);\n const stack: string[] = [];\n\n function visit(name: string): void {\n color.set(name, GRAY);\n stack.push(name);\n for (const dep of deps.get(name)!) {\n const c = color.get(dep) ?? WHITE;\n if (c === GRAY) {\n const startIdx = stack.indexOf(dep);\n const cycle = stack.slice(startIdx).concat(dep).join(' → ');\n throw new ConfigError(`cyclic dependency: ${cycle}`);\n }\n if (c === WHITE) visit(dep);\n }\n stack.pop();\n color.set(name, BLACK);\n }\n\n for (const name of deps.keys()) {\n if (color.get(name) === WHITE) visit(name);\n }\n}\n\nexport function parseConfig(text: string): CtlConfig {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new ConfigError(`yaml parse error: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (doc === null || doc === undefined) return { services: [], tasks: [], replacements: {} };\n if (!isPlainObject(doc)) {\n throw new ConfigError('top-level config must be a mapping');\n }\n rejectUnknownKeys(doc, TOP_LEVEL_KEYS, '(root)');\n\n const services: ServiceSpec[] = [];\n const servicesRaw = doc.services;\n if (servicesRaw !== undefined && servicesRaw !== null) {\n if (!isPlainObject(servicesRaw)) {\n throw new ConfigError('services must be a mapping of name → service');\n }\n for (const [name, raw] of Object.entries(servicesRaw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ConfigError(`service name \"${name}\" must match [A-Za-z0-9_-]+`);\n }\n services.push(parseService(name, raw));\n }\n }\n\n const tasks: TaskSpec[] = [];\n const tasksRaw = doc.tasks;\n if (tasksRaw !== undefined && tasksRaw !== null) {\n if (!isPlainObject(tasksRaw)) {\n throw new ConfigError('tasks must be a mapping of name → task');\n }\n for (const [name, raw] of Object.entries(tasksRaw)) {\n if (!/^[A-Za-z0-9_-]+$/.test(name)) {\n throw new ConfigError(`task name \"${name}\" must match [A-Za-z0-9_-]+`);\n }\n tasks.push(parseTask(name, raw));\n }\n }\n\n // ide: parsed only enough to confirm it's an object; contents are host-side\n // and the supervisor doesn't touch them. Schema is permissive here too.\n if (doc.ide !== undefined && doc.ide !== null && !isPlainObject(doc.ide)) {\n throw new ConfigError('ide must be a mapping');\n }\n\n // defaults: host-side layered-config block. We only require it to be a\n // mapping here; @agentbox/config validates the leaves strictly when the\n // host loads the file. Letting ctl deep-validate would force a circular\n // dependency on the host-only @agentbox/config package — see CLAUDE.md.\n if (doc.defaults !== undefined && doc.defaults !== null && !isPlainObject(doc.defaults)) {\n throw new ConfigError('defaults must be a mapping');\n }\n\n validateUnitGraph(tasks, services);\n\n const exposed = services.filter((s) => s.expose);\n if (exposed.length > 1) {\n throw new ConfigError(\n `at most one service may set expose: (got: ${exposed.map((s) => s.name).join(', ')})`,\n );\n }\n\n let replacements: Record<string, ReplaceRule[]>;\n try {\n replacements = parseReplacements(doc.replacements);\n } catch (err) {\n throw new ConfigError(err instanceof Error ? err.message : String(err));\n }\n\n return { services, tasks, replacements };\n}\n\nexport async function loadConfig(path: string): Promise<CtlConfig> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { services: [], tasks: [], replacements: {} };\n }\n throw err;\n }\n return parseConfig(text);\n}\n\nexport function describeCommand(cmd: string | string[]): string {\n return Array.isArray(cmd) ? cmd.join(' ') : cmd;\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport { parseReplacements, ReplaceError, type ReplaceRule } from '@agentbox/core';\n\n// Re-export the pure engine (defined in @agentbox/core so the host carry path\n// can share it without a dependency cycle) so in-box code keeps importing from\n// a single `./replace.js` surface.\nexport {\n applyReplacements,\n substitutePlaceholders,\n placeholderContextFromEnv,\n parseReplaceRule,\n parseReplaceRules,\n parseReplacements,\n resolveRuleRefs,\n parseRuleArg,\n PLACEHOLDER_KEYS,\n ReplaceError,\n} from '@agentbox/core';\nexport type { ReplaceRule, ApplyReplacementsOptions, PlaceholderKey } from '@agentbox/core';\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Parse the top-level `replacements:` block out of raw agentbox.yaml text. */\nexport function parseReplacementsSection(text: string): Record<string, ReplaceRule[]> {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new ReplaceError(`yaml parse error: ${err instanceof Error ? err.message : String(err)}`);\n }\n if (doc === null || doc === undefined) return {};\n if (!isPlainObject(doc)) throw new ReplaceError('top-level config must be a mapping');\n return parseReplacements(doc.replacements);\n}\n\n/** Load the `replacements:` block from an agentbox.yaml path (missing → {}). */\nexport async function loadReplacementsSection(\n path: string,\n): Promise<Record<string, ReplaceRule[]>> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw err;\n }\n return parseReplacementsSection(text);\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport { parseReplaceRules, type ReplaceRule } from './replace.js';\n\n/**\n * One entry from the host-side `carry:` block in `agentbox.yaml`.\n *\n * Paths are kept user-facing (still containing `~/` or `./`) — resolution to\n * absolute paths, project-root anchoring, and safety checks happen in the\n * apps/cli resolver, not here. This package is shipped inside the box and\n * must stay free of host-only assumptions.\n */\nexport interface CarryItem {\n src: string;\n dest: string;\n mode?: number;\n /**\n * Numeric uid that should own the carried file inside the box. When unset,\n * the copy step defaults to 1000 (the `vscode` user every box runs as) so\n * the carried files are always agent-readable. Set 0 to keep root-owned.\n */\n user?: number;\n /**\n * Extra paths to drop when carrying a directory (tar glob like `*​/cache` or a\n * bare dir name). Additive on top of the host CLI's default heavy-dir excludes\n * (`.git`, `node_modules`, ...). Ignored for file entries.\n */\n exclude?: string[];\n optional: boolean;\n /**\n * Substitute `{{AGENTBOX_*}}` whitelist placeholders in the file content\n * host-side before copying. File entries only.\n */\n replaceEnvs?: boolean;\n /** Inline replacement rules applied (in order) before copying. File only. */\n replace?: ReplaceRule[];\n /** Names of top-level `replacements:` rule-sets to apply. File only. */\n rules?: string[];\n}\n\nexport class CarryConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CarryConfigError';\n }\n}\n\nconst ITEM_KEYS = new Set([\n 'src',\n 'dest',\n 'mode',\n 'user',\n 'exclude',\n 'optional',\n 'replaceEnvs',\n 'replace',\n 'rules',\n]);\n\n// Parse a YAML field into a list of trimmed non-empty strings (undefined when\n// empty/absent). Shared by `exclude` and `rules`; `desc` names the element kind\n// in the error message.\nfunction parseStringList(raw: unknown, where: string, desc: string): string[] | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (!Array.isArray(raw)) {\n throw new CarryConfigError(`${where} must be a list of ${desc}`);\n }\n const out: string[] = [];\n for (const [i, v] of raw.entries()) {\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new CarryConfigError(`${where}[${String(i)}] must be a non-empty string`);\n }\n out.push(v.trim());\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction parseUser(raw: unknown, where: string): number | undefined {\n if (raw === undefined || raw === null) return undefined;\n let n: number;\n if (typeof raw === 'number') {\n if (!Number.isInteger(raw) || raw < 0) {\n throw new CarryConfigError(`${where}.user must be a non-negative integer uid (got ${String(raw)})`);\n }\n n = raw;\n } else if (typeof raw === 'string') {\n const trimmed = raw.trim();\n if (!/^[0-9]+$/.test(trimmed)) {\n throw new CarryConfigError(\n `${where}.user \"${raw}\" must be a numeric uid (e.g. 1000). Usernames not supported — look up the uid first.`,\n );\n }\n n = parseInt(trimmed, 10);\n } else {\n throw new CarryConfigError(`${where}.user must be a non-negative integer uid`);\n }\n if (n > 65535) {\n throw new CarryConfigError(`${where}.user must be between 0 and 65535 (got ${String(n)})`);\n }\n return n;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction assertSrcShape(src: string, where: string): void {\n if (src.length === 0) {\n throw new CarryConfigError(`${where}.src must not be empty`);\n }\n if (!src.startsWith('/') && !src.startsWith('~/') && !src.startsWith('./')) {\n throw new CarryConfigError(\n `${where}.src \"${src}\" must start with /, ~/, or ./ (bare relative paths are rejected to avoid surprises)`,\n );\n }\n}\n\nfunction assertDestShape(dest: string, where: string): void {\n if (dest.length === 0) {\n throw new CarryConfigError(`${where}.dest must not be empty`);\n }\n if (!dest.startsWith('/') && !dest.startsWith('~/')) {\n throw new CarryConfigError(\n `${where}.dest \"${dest}\" must start with / or ~/ (relative box-side paths are not allowed)`,\n );\n }\n}\n\nfunction parseMode(raw: unknown, where: string): number | undefined {\n if (raw === undefined || raw === null) return undefined;\n let n: number;\n if (typeof raw === 'number') {\n if (!Number.isInteger(raw) || raw < 0) {\n throw new CarryConfigError(`${where}.mode must be a non-negative integer (got ${String(raw)})`);\n }\n n = raw;\n } else if (typeof raw === 'string') {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new CarryConfigError(`${where}.mode must not be empty`);\n }\n // Accept \"0600\", \"600\", \"0o600\". Always interpreted as octal.\n const cleaned = trimmed.startsWith('0o') || trimmed.startsWith('0O') ? trimmed.slice(2) : trimmed;\n if (!/^[0-7]+$/.test(cleaned)) {\n throw new CarryConfigError(\n `${where}.mode \"${raw}\" must be an octal number (e.g. 0o600, \"0600\", \"600\")`,\n );\n }\n n = parseInt(cleaned, 8);\n } else {\n throw new CarryConfigError(`${where}.mode must be a number or octal string`);\n }\n if (n < 0 || n > 0o7777) {\n throw new CarryConfigError(`${where}.mode must be between 0 and 0o7777 (got ${n.toString(8)})`);\n }\n return n;\n}\n\nfunction parseShorthand(raw: string, where: string): CarryItem {\n // Split on first '=', so values containing '=' survive in dest.\n const eq = raw.indexOf('=');\n let src: string;\n let dest: string;\n if (eq === -1) {\n src = raw;\n dest = raw;\n } else {\n src = raw.slice(0, eq);\n dest = raw.slice(eq + 1);\n }\n src = src.trim();\n dest = dest.trim();\n assertSrcShape(src, where);\n if (eq === -1) {\n // Shorthand without explicit dest: src must be absolute or ~/ so dest\n // can mirror it. `./relative` shorthand has no meaningful in-box dest.\n if (src.startsWith('./')) {\n throw new CarryConfigError(\n `${where} shorthand \"${raw}\" must specify an explicit dest (use \"src=dest\") when src starts with ./`,\n );\n }\n }\n assertDestShape(dest, where);\n return { src, dest, optional: false };\n}\n\nfunction parseMapping(raw: Record<string, unknown>, where: string): CarryItem {\n for (const key of Object.keys(raw)) {\n if (!ITEM_KEYS.has(key)) {\n throw new CarryConfigError(`${where} has unknown key \"${key}\"`);\n }\n }\n const srcRaw = raw.src;\n if (typeof srcRaw !== 'string') {\n throw new CarryConfigError(`${where}.src must be a string`);\n }\n const src = srcRaw.trim();\n assertSrcShape(src, where);\n\n let dest: string;\n if (raw.dest === undefined || raw.dest === null) {\n if (src.startsWith('./')) {\n throw new CarryConfigError(\n `${where}.dest is required when src starts with ./ (no sensible in-box default)`,\n );\n }\n dest = src;\n } else {\n if (typeof raw.dest !== 'string') {\n throw new CarryConfigError(`${where}.dest must be a string`);\n }\n dest = raw.dest.trim();\n }\n assertDestShape(dest, where);\n\n const mode = parseMode(raw.mode, where);\n const user = parseUser(raw.user, where);\n const exclude = parseStringList(raw.exclude, `${where}.exclude`, 'glob/name strings');\n\n let optional = false;\n if (raw.optional !== undefined && raw.optional !== null) {\n if (typeof raw.optional !== 'boolean') {\n throw new CarryConfigError(`${where}.optional must be a boolean`);\n }\n optional = raw.optional;\n }\n\n let replaceEnvs: boolean | undefined;\n if (raw.replaceEnvs !== undefined && raw.replaceEnvs !== null) {\n if (typeof raw.replaceEnvs !== 'boolean') {\n throw new CarryConfigError(`${where}.replaceEnvs must be a boolean`);\n }\n replaceEnvs = raw.replaceEnvs;\n }\n let replace: ReplaceRule[] | undefined;\n if (raw.replace !== undefined && raw.replace !== null) {\n try {\n const rules = parseReplaceRules(raw.replace, `${where}.replace`);\n if (rules.length > 0) replace = rules;\n } catch (err) {\n throw new CarryConfigError(err instanceof Error ? err.message : String(err));\n }\n }\n const rules = parseStringList(raw.rules, `${where}.rules`, 'replacements rule-set names');\n\n const out: CarryItem = { src, dest, optional };\n if (mode !== undefined) out.mode = mode;\n if (user !== undefined) out.user = user;\n if (exclude !== undefined) out.exclude = exclude;\n if (replaceEnvs !== undefined) out.replaceEnvs = replaceEnvs;\n if (replace !== undefined) out.replace = replace;\n if (rules !== undefined) out.rules = rules;\n return out;\n}\n\nexport function parseCarryRaw(raw: unknown): CarryItem[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) {\n throw new CarryConfigError('carry must be a list of strings or mappings');\n }\n const out: CarryItem[] = [];\n for (const [i, item] of raw.entries()) {\n const where = `carry[${String(i)}]`;\n if (typeof item === 'string') {\n out.push(parseShorthand(item, where));\n } else if (isPlainObject(item)) {\n out.push(parseMapping(item, where));\n } else {\n throw new CarryConfigError(`${where} must be a string or mapping`);\n }\n }\n return out;\n}\n\nexport function parseCarrySection(text: string): CarryItem[] {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new CarryConfigError(\n `yaml parse error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (doc === null || doc === undefined) return [];\n if (!isPlainObject(doc)) {\n throw new CarryConfigError('top-level config must be a mapping');\n }\n return parseCarryRaw(doc.carry);\n}\n\nexport async function loadCarrySection(path: string): Promise<CarryItem[]> {\n let text: string;\n try {\n text = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n return parseCarrySection(text);\n}\n","// DownloadKind's canonical decision home is `@agentbox/core`'s sync/files.ts;\n// imported here so DownloadRpcParams below can reference it, re-exported below\n// so existing `./types.js` importers stay unchanged.\nimport type { DownloadKind } from '@agentbox/core';\n\nexport const DEFAULT_RELAY_PORT = 8787;\n/**\n * In-box relay port — distinct from {@link DEFAULT_RELAY_PORT} so a nested\n * agentbox run (developing agentbox inside a box) can bind its own host\n * relay on 8787 inside the outer box without colliding with the in-box\n * supervisor's relay. ctl always binds this port — as a real `mode: 'box'`\n * relay in cloud sandboxes, or a transparent forwarder to the host relay in\n * docker boxes. Override with `AGENTBOX_BOX_RELAY_PORT`.\n */\nexport const DEFAULT_BOX_RELAY_PORT = 8788;\nexport const RELAY_CONTAINER_NAME = 'agentbox-relay';\nexport const RELAY_NETWORK_NAME = 'agentbox-net';\nexport const RELAY_IMAGE_REF = 'agentbox/relay:dev';\nexport const RELAY_EVENT_RING_SIZE = 1000;\n\nexport type BoxKind = 'docker' | 'cloud';\n\nexport interface BoxRegistration {\n boxId: string;\n token: string;\n name: string;\n /** ISO-8601 time the relay received this registration. */\n registeredAt: string;\n /**\n * Which sandbox backend the box runs on. Drives whether the host relay\n * spawns a `CloudBoxPoller` for it. Absent on legacy registrations →\n * treated as 'docker'.\n */\n kind?: BoxKind;\n /**\n * For `kind === 'cloud'`: which cloud backend the executor must resolve\n * (e.g. 'daytona'). The host action executor lazy-imports\n * `@agentbox/sandbox-{backend}` to drive the in-sandbox channel.\n */\n backend?: string;\n /** Docker container name; the relay needs it to `docker pause` an idle box. */\n containerName?: string;\n /** ISO-8601 box-creation time (BoxRecord.createdAt); used as a tie-break in auto-pause ordering. */\n createdAt?: string;\n /**\n * 1-based per-project box index (`agentbox list`'s `N` column). When set,\n * the relay writes status.json under `~/.agentbox/boxes/<id>-<n>-<mnemonic>/`\n * to match the host's `boxDirSegment` helper. Absent for legacy\n * (pre-feature) boxes; absent registrations fall back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n /**\n * Container-path → host-worktree-dir mapping the host uses to resolve\n * git.pull/git.push RPCs. Empty when the box has no git repos.\n */\n worktrees?: BoxWorktree[];\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface. Set by cloud\n * registrations; the host's `CloudBoxPoller` long-polls it for status +\n * queued host-only RPCs.\n */\n previewUrl?: string;\n /**\n * Provider-proxy token for `previewUrl` (e.g. Daytona's\n * `x-daytona-preview-token`). The host poller attaches it as a header so\n * Daytona's preview proxy lets the request reach the in-sandbox relay.\n */\n previewToken?: string;\n /**\n * Bearer secret authenticating the host poller to `/bridge/*` on the\n * in-sandbox relay. Distinct from `token` (which the in-box agent sees)\n * so a compromised agent can't impersonate the host.\n */\n bridgeToken?: string;\n /**\n * When true, host-action confirm prompts for this box (git push, cp,\n * gh writes, checkpoint, browser.open) resolve to `y` without a human/orchestrator\n * answering. Set at registration from `box.autoApproveHostActions`. Off by\n * default; every auto-approval still emits a `host-action-auto-approved`\n * relay event so the bypass is auditable.\n */\n autoApproveHostActions?: boolean;\n /**\n * Mirrors `box.autoApproveSafeHostActions` (default true). When not `false`,\n * the SAFE subset of host actions (open PR, PR/review comments,\n * sanctioned-branch push, contained non-secret file copy/download, CI rerun,\n * checkpoint, integration writes) auto-resolves without a prompt — each\n * still emits a `host-action-auto-approved` event. Absent → enabled.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box repo's origin remote URL (any git URL shape). The hosted control\n * plane resolves owner/repo from THIS registered value when leasing a\n * GitHub-App token (never from box-supplied RPC params). Absent for boxes\n * without a git origin.\n */\n originUrl?: string;\n}\n\nexport interface BoxWorktree {\n /** Path inside the container (e.g. /workspace, /workspace/app). */\n containerPath: string;\n /**\n * Absolute host path of the main repo whose `.git/` is shared with the\n * container. `git push/fetch` RPCs run with `git -C <hostMainRepo>` — the\n * worktree's working tree lives inside the container's writable layer, but\n * refs/objects are in this shared `.git/`, so push from the main repo dir\n * sees the in-container commits.\n */\n hostMainRepo: string;\n /** Branch the in-container worktree was created on (`agentbox/<box-name>`). */\n branch: string;\n /**\n * Last branch the HOST sanctioned for this box (create-time `branch`, updated\n * by host `agentbox git checkout`/`branch`/`pull <branch>`). The push gate\n * auto-approves only a scratch branch or this value; absent → treated as\n * `branch`.\n */\n sanctionedBranch?: string;\n}\n\nexport interface RelayEvent {\n /** Monotonic per-relay-process id, useful for `since=` polling. */\n id: number;\n /** Box id that posted the event. */\n boxId: string;\n /** Free-form event type, e.g. 'service-state', 'task-state', 'notify'. */\n type: string;\n /** ISO-8601 timestamp the relay assigned on receipt. */\n receivedAt: string;\n /** ISO-8601 client-supplied timestamp, if any. */\n ts?: string;\n /** Arbitrary JSON payload. */\n payload?: unknown;\n}\n\nexport interface PostEventBody {\n type: string;\n ts?: string;\n payload?: unknown;\n}\n\nexport interface PostRpcBody {\n method: string;\n params?: unknown;\n}\n\nexport interface RegisterBoxBody {\n boxId: string;\n token: string;\n name: string;\n /** Sandbox backend kind. Defaults to 'docker' when absent (legacy). */\n kind?: BoxKind;\n /** For cloud boxes: which backend (e.g. 'daytona'). Drives executor lazy-import. */\n backend?: string;\n containerName?: string;\n createdAt?: string;\n /**\n * 1-based per-project box index. Optional — additive; older boxes and\n * legacy (pre-feature) records register without it and the status path\n * falls back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n worktrees?: BoxWorktree[];\n /** Required when `kind === 'cloud'`: in-sandbox relay's /bridge URL. */\n previewUrl?: string;\n /** When the cloud provider's proxy needs a token (Daytona) — attached as a header. */\n previewToken?: string;\n /** Required when `kind === 'cloud'`: bearer for /bridge/* auth. */\n bridgeToken?: string;\n /**\n * Mirrors `box.autoApproveHostActions`: when true, host-action confirm\n * prompts auto-resolve to `y` (audited via a relay event).\n */\n autoApproveHostActions?: boolean;\n /** Mirrors `box.autoApproveSafeHostActions` (default true; absent → enabled). */\n autoApproveSafeHostActions?: boolean;\n /** The box repo's origin remote URL (for GitHub-App lease repo resolution). */\n originUrl?: string;\n}\n\n/**\n * A host-only RPC the in-sandbox relay (box mode) parked while waiting for\n * the host poller to drain, execute on the host, and post back a result.\n * Equivalent of an in-flight `/rpc` call queued through the bridge.\n */\nexport interface HostAction {\n /** Server-generated uuid; the host poller echoes it back in the result. */\n id: string;\n /** Box that initiated the in-sandbox `/rpc`. */\n boxId: string;\n /** Original `/rpc` method (e.g. 'git.push', 'cp.toHost'). */\n method: string;\n /** Original `/rpc` params payload, opaque to the queue. */\n params: unknown;\n /** ISO-8601 enqueue time. */\n createdAt: string;\n}\n\nexport interface HostActionResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Response shape for `GET /bridge/poll`. */\nexport interface BridgePollResponse {\n /** Newly-queued host actions the poller hasn't drained yet. */\n actions: HostAction[];\n /** Events appended since `?since=<id>`. */\n events: RelayEvent[];\n /** Latest box-status snapshot, when one has been pushed. */\n status: unknown | null;\n /** Highest event id seen — the poller's next `?since=`. */\n cursor: number;\n}\n\n/** Body of `POST /bridge/action-result`. */\nexport interface BridgeActionResultBody {\n id: string;\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// GitRpcParams's canonical wire-type home is `@agentbox/core`'s sync/git-refs.ts\n// (shared with the in-box ctl); re-exported here so `./types.js` importers stay unchanged.\nexport type { GitRpcParams } from '@agentbox/core';\n\nexport interface GitRpcResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface CheckpointRpcParams {\n /** Checkpoint name; defaults host-side to `<box-name>-<next>`. */\n name?: string;\n /** Flatten lower+upper into one tree instead of a layered delta. */\n merged?: boolean;\n /** Mark the new checkpoint as the project default. */\n setDefault?: boolean;\n /**\n * If a checkpoint with the same name exists, rm it (manifest + image)\n * before capturing. Makes the call safe to retry — useful when the\n * agent's harness lost the previous invocation's stdout and can't tell\n * whether it succeeded.\n */\n replace?: boolean;\n}\n\n/**\n * First-cut prompt UX is a y/N confirmation in the host wrapper's footer.\n * `select` / `text` are reserved for a follow-up that grows the footer to\n * two rows; keeping the kind in the wire from day one means the host\n * wrapper can ignore unknown kinds gracefully when an older box hits a\n * newer relay (and vice-versa).\n */\nexport type PromptKind = 'confirm';\n\nexport interface PromptContext {\n /** Short label, e.g. \"git push\" or \"cp toHost: /workspace/x -> ~/dl/x\". */\n command?: string;\n /** Container path of the calling cwd, when known. */\n cwd?: string;\n /** Full argv; wrapper truncates for the footer. */\n argv?: string[];\n}\n\n/**\n * The shape pushed over SSE on `event: prompt-ask`. Also the shape the\n * relay-internal `askPrompt()` helper produces. Not a /rpc method — the\n * relay generates these itself when it is about to take a host-side\n * action; the in-box ctl never asks for prompts directly.\n */\nexport interface PromptAskEvent {\n /** Relay-generated UUIDv4 (the wrapper echoes it back in the answer). */\n id: string;\n kind: PromptKind;\n /** Primary question; wrapper truncates to footer width. */\n message: string;\n /** Optional second-line context; wrapper may show or skip. */\n detail?: string;\n /** Default when the user just hits Enter; default 'n' so y/N is the safe shape. */\n defaultAnswer?: 'y' | 'n';\n context?: PromptContext;\n}\n\n/** Body of `POST /admin/prompts/answer`. */\nexport interface PromptAnswerBody {\n id: string;\n answer: 'y' | 'n';\n /** Set when the user dismissed the prompt (Esc / Ctrl-c); treated as 'n'. */\n cancelled?: boolean;\n}\n\n/**\n * Notice kinds. `checkpoint` is the first — a box is transiently frozen\n * while a checkpoint is captured (`docker commit` pauses the container).\n * Kept open-ended like {@link PromptKind} so an older wrapper degrades\n * gracefully (renders the message) when a newer relay sends a new kind.\n */\nexport type NoticeKind = 'checkpoint';\n\n/**\n * The shape pushed over SSE on `event: notice-set`. Unlike a prompt, a\n * notice is purely informational — there is no answer and the box's RPC\n * is not blocked on it. The host wrapper renders it as an animated footer\n * line so the user knows the box is busy, not stuck. Cleared by a\n * `notice-clear` event carrying `{ id }`.\n */\nexport interface BoxNoticeEvent {\n /** Relay-generated UUIDv4. */\n id: string;\n kind: NoticeKind;\n /** Warning text; the wrapper truncates to footer width. */\n message: string;\n}\n\n/** Body of `POST /admin/notices/set`; the response is `{ id }`. */\nexport interface SetNoticeBody {\n boxId: string;\n kind: NoticeKind;\n message: string;\n /** Auto-expiry backstop in ms; defaults relay-side. */\n ttlMs?: number;\n}\n\n/** Body of `POST /admin/notices/clear`. */\nexport interface ClearNoticeBody {\n boxId: string;\n id: string;\n}\n\nexport interface CpRpcParams {\n /**\n * Source path(s): box paths for `cp.toHost`, host paths for `cp.fromHost`.\n * The host CLI side is what carries the `<box>:` prefix when re-shelled.\n */\n sources?: string[];\n /** Destination path: host path for `cp.toHost`, box path for `cp.fromHost`. */\n dest?: string;\n /**\n * Legacy single-source wire shape (older in-box `agentbox-ctl` baked into a\n * box image before multi-source support). The relay normalizes these into\n * `sources`/`dest`. `boxPath` is the container path; `hostPath` the host path\n * (dst for toHost, src for fromHost).\n */\n boxPath?: string;\n hostPath?: string;\n /** Defaults true; relay always uses `docker exec tar` (recursive). */\n recursive?: boolean;\n /** tar glob patterns / bare dir names to exclude, forwarded to `agentbox cp --exclude`. */\n exclude?: string[];\n /** false → forward `--no-default-excludes` (keep heavy dirs the host CLI drops). */\n defaultExcludes?: boolean;\n /** true → forward `--yes` (copy past the host's size limit). */\n yes?: boolean;\n}\n\nexport interface BrowserOpenRpcParams {\n /** Absolute http(s) URL to open in the host's default browser. */\n url: string;\n}\n\nexport type { DownloadKind };\n\nexport interface DownloadRpcParams {\n kind: DownloadKind;\n /**\n * Host destination override. Reserved — the v1 relay ignores it and uses\n * the host CLI's defaults (`box.workspacePath`, or `~/.claude`). Kept in\n * the wire so a later upgrade can land without bumping the type.\n */\n hostPath?: string;\n /** Reserved for per-kind flags (e.g. workspace: includeNodeModules). */\n options?: Record<string, unknown>;\n}\n","import type { BoxRegistration, RelayEvent } from './types.js';\nimport { RELAY_EVENT_RING_SIZE } from './types.js';\n\nexport class BoxRegistry {\n private readonly map = new Map<string, BoxRegistration>();\n\n register(reg: BoxRegistration): void {\n this.map.set(reg.boxId, reg);\n }\n\n forget(boxId: string): boolean {\n return this.map.delete(boxId);\n }\n\n /** Returns the registration whose token matches, or null. */\n authenticate(token: string): BoxRegistration | null {\n if (token.length === 0) return null;\n for (const reg of this.map.values()) {\n if (reg.token === token) return reg;\n }\n return null;\n }\n\n get(boxId: string): BoxRegistration | undefined {\n return this.map.get(boxId);\n }\n\n list(): BoxRegistration[] {\n return [...this.map.values()];\n }\n\n size(): number {\n return this.map.size;\n }\n}\n\nexport class EventBuffer {\n private readonly buf: RelayEvent[] = [];\n private nextId = 1;\n constructor(private readonly capacity: number = RELAY_EVENT_RING_SIZE) {}\n\n append(input: Omit<RelayEvent, 'id' | 'receivedAt'>): RelayEvent {\n const ev: RelayEvent = {\n id: this.nextId++,\n receivedAt: new Date().toISOString(),\n ...input,\n };\n this.buf.push(ev);\n if (this.buf.length > this.capacity) this.buf.shift();\n return ev;\n }\n\n /** Returns events with id > since. If `box` is given, filters to that box. */\n since(since: number, box?: string): RelayEvent[] {\n const out: RelayEvent[] = [];\n for (const ev of this.buf) {\n if (ev.id <= since) continue;\n if (box && ev.boxId !== box) continue;\n out.push(ev);\n }\n return out;\n }\n\n all(): RelayEvent[] {\n return this.buf.slice();\n }\n\n size(): number {\n return this.buf.length;\n }\n}\n","import { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * A box status snapshot as received from the in-box daemon. The relay treats\n * it structurally (it has no dep on `@agentbox/ctl`); the rich type lives in\n * `@agentbox/ctl` (`BoxStatus`) and is what the host CLI parses back.\n */\nexport type BoxStatusSnapshot = Record<string, unknown>;\n\n/**\n * Mirrors `sanitizeMnemonic` in @agentbox/config — duplicated here so the relay\n * stays dep-free. Two source-of-truth files; the schema-drift-style guarantee\n * is that boxes only land in `<id>-<mnemonic>/` if both impls agree.\n */\nfunction sanitizeMnemonic(raw: string): string {\n return (\n raw\n .toLowerCase()\n .replace(/-/g, '_')\n .replace(/[^a-z0-9_]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 32) || 'unnamed'\n );\n}\n\n/**\n * Mirrors `boxRunDirFor` / `boxDirSegment` in @agentbox/sandbox-docker — kept\n * in sync by hand. When `projectIndex` (`agentbox list`'s `N`) is set the\n * segment is `<id>-<n>-<mnemonic>` so directories sort cleanly within a\n * project; legacy (pre-feature) boxes register without it and fall back to\n * the original `<id>-<mnemonic>` shape.\n */\nfunction boxRunDirFor(boxId: string, name: string, projectIndex?: number): string {\n const mnemonic = sanitizeMnemonic(name);\n const segment =\n typeof projectIndex === 'number' && Number.isFinite(projectIndex) && projectIndex > 0\n ? `${boxId}-${String(projectIndex)}-${mnemonic}`\n : `${boxId}-${mnemonic}`;\n return join(homedir(), '.agentbox', 'boxes', segment);\n}\n\nfunction boxStatusPathFor(boxId: string, name: string, projectIndex?: number): string {\n return join(boxRunDirFor(boxId, name, projectIndex), 'status.json');\n}\n\n/**\n * Structural guard: a valid box-status payload is an object with `schema === 1`\n * and a non-empty `boxId` string. The relay persists it verbatim; the host\n * reader does the strict typing.\n */\nexport function isValidBoxStatus(payload: unknown): payload is BoxStatusSnapshot {\n if (typeof payload !== 'object' || payload === null) return false;\n const o = payload as Record<string, unknown>;\n return o.schema === 1 && typeof o.boxId === 'string' && o.boxId.length > 0;\n}\n\n/**\n * In-memory latest-status map plus a durable per-box file at\n * `~/.agentbox/boxes/<id>/status.json`. The relay is a single process so it is\n * the single writer; the atomic tmp+rename means the host CLI never reads a\n * torn file. The on-disk copy is what makes status survive box pause/stop,\n * relay restart, and host reboot.\n */\nexport class BoxStatusStore {\n private readonly map = new Map<string, BoxStatusSnapshot>();\n\n get(boxId: string): BoxStatusSnapshot | undefined {\n return this.map.get(boxId);\n }\n\n /**\n * Update the in-memory entry and best-effort persist it to disk. `name` is\n * the box's user-facing name (from the registry); `projectIndex` is the\n * 1-based per-project `N`. Together they form the on-disk dir\n * `~/.agentbox/boxes/<id>-<n>-<mnemonic>/status.json` (or\n * `<id>-<mnemonic>/` if N is absent — legacy boxes).\n */\n async set(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n this.map.set(boxId, status);\n const target = boxStatusPathFor(boxId, name, projectIndex);\n const tmp = `${target}.${String(process.pid)}.tmp`;\n try {\n await mkdir(boxRunDirFor(boxId, name, projectIndex), { recursive: true });\n await writeFile(tmp, JSON.stringify(status), 'utf8');\n await rename(tmp, target);\n } catch {\n await rm(tmp, { force: true }).catch(() => {});\n }\n }\n\n /** Drop the in-memory entry (the on-disk file is wiped with the box dir). */\n delete(boxId: string): void {\n this.map.delete(boxId);\n }\n}\n","import { BoxRegistry, EventBuffer } from '../registry.js';\nimport { BoxStatusStore } from '../status-store.js';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\nexport interface MemoryStoreParts {\n registry?: BoxRegistry;\n events?: EventBuffer;\n statusStore?: BoxStatusStore;\n}\n\n/**\n * In-memory {@link Store} — the laptop loopback relay default and the test\n * default. It wraps the original `BoxRegistry` / `EventBuffer` /\n * `BoxStatusStore` instances verbatim, so it is behaviorally identical to the\n * pre-seam relay (status still persists to `~/.agentbox/boxes/<id>/status.json`\n * via `BoxStatusStore.set`). The wrapped instances are exposed so the relay\n * handle can keep handing them to the autopause / queue loops and the unit\n * tests, which read them synchronously.\n */\nexport class MemoryStore implements Store {\n readonly registry: BoxRegistry;\n readonly events: EventBuffer;\n readonly statusStore: BoxStatusStore;\n private readonly prompts = new Map<string, PromptRow>();\n private readonly createJobs = new Map<string, CreateJobRow>();\n\n constructor(parts: MemoryStoreParts = {}) {\n this.registry = parts.registry ?? new BoxRegistry();\n this.events = parts.events ?? new EventBuffer();\n this.statusStore = parts.statusStore ?? new BoxStatusStore();\n }\n\n registerBox(reg: BoxRegistration): Promise<void> {\n this.registry.register(reg);\n return Promise.resolve();\n }\n\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return Promise.resolve(this.registry.get(boxId));\n }\n\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return Promise.resolve(this.registry.authenticate(token));\n }\n\n listBoxes(): Promise<BoxRegistration[]> {\n return Promise.resolve(this.registry.list());\n }\n\n forgetBox(boxId: string): Promise<boolean> {\n return Promise.resolve(this.registry.forget(boxId));\n }\n\n countBoxes(): Promise<number> {\n return Promise.resolve(this.registry.size());\n }\n\n appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n return Promise.resolve(this.events.append(input));\n }\n\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return Promise.resolve(this.events.since(since, boxId));\n }\n\n countEvents(): Promise<number> {\n return Promise.resolve(this.events.size());\n }\n\n setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n return this.statusStore.set(boxId, name, projectIndex, status);\n }\n\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return Promise.resolve(this.statusStore.get(boxId));\n }\n\n deleteStatus(boxId: string): Promise<void> {\n this.statusStore.delete(boxId);\n return Promise.resolve();\n }\n\n createPrompt(row: PromptRow): Promise<void> {\n this.prompts.set(row.id, { ...row });\n return Promise.resolve();\n }\n\n getPrompt(promptId: string): Promise<PromptRow | null> {\n const row = this.prompts.get(promptId);\n return Promise.resolve(row ? { ...row } : null);\n }\n\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const row = this.prompts.get(promptId);\n if (!row || row.status !== 'pending') return Promise.resolve(false);\n row.status = 'answered';\n row.answer = answer;\n row.cancelled = cancelled;\n return Promise.resolve(true);\n }\n\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const out: PromptRow[] = [];\n for (const row of this.prompts.values()) {\n if (row.boxId === boxId && row.status === 'pending') out.push({ ...row });\n }\n return Promise.resolve(out);\n }\n\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const row = this.prompts.get(promptId);\n if (row) row.result = result;\n return Promise.resolve();\n }\n\n enqueueCreateJob(job: CreateJobRow): Promise<void> {\n this.createJobs.set(job.id, { ...job });\n return Promise.resolve();\n }\n\n getCreateJob(id: string): Promise<CreateJobRow | null> {\n const job = this.createJobs.get(id);\n return Promise.resolve(job ? { ...job } : null);\n }\n\n claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n // Oldest queued first; single-process so no real concurrency to guard.\n const queued = [...this.createJobs.values()]\n .filter((j) => j.status === 'queued')\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n const job = queued[0];\n if (!job) return Promise.resolve(null);\n job.status = 'running';\n job.claimedBy = workerId;\n job.startedAt = new Date().toISOString();\n return Promise.resolve({ ...job });\n }\n\n completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const job = this.createJobs.get(id);\n if (job) {\n job.status = status;\n job.result = result;\n job.finishedAt = new Date().toISOString();\n }\n return Promise.resolve();\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { ServerResponse } from 'node:http';\nimport type { PromptAnswerBody, PromptAskEvent } from './types.js';\n\n/**\n * Resolution shape passed back through `askPrompt`'s Promise. Mirrors the\n * shape the wrapper POSTs to `/admin/prompts/answer` minus the id (the\n * caller already knows it).\n */\nexport interface PromptResolution {\n answer: 'y' | 'n';\n cancelled?: boolean;\n}\n\ninterface PendingPromptEntry {\n ev: PromptAskEvent;\n boxId: string;\n resolve: (r: PromptResolution) => void;\n createdAt: string;\n}\n\n/**\n * In-memory pending prompts map. The relay's host-action handlers (git push,\n * cp.*, download.*) put a pending entry here and await the Promise; the\n * wrapper's POST to `/admin/prompts/answer` resolves it. Entries live for\n * however long the user takes — per the design we block indefinitely until\n * a wrapper attaches and answers.\n */\n/**\n * Per-box auto-approve policy, wired by the relay server once the registry +\n * event buffer are available. `shouldAutoApprove` reflects the box's\n * `autoApproveHostActions` registration flag; `audit` records the bypass to\n * the relay event ring buffer so it stays observable. Lives on\n * {@link PendingPrompts} because that instance is already threaded into every\n * `askPrompt` call site (host + cloud), so no handler signatures change.\n */\nexport interface AutoApprovePolicy {\n shouldAutoApprove(boxId: string): boolean;\n audit(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason?: string): void;\n}\n\n/** A pending approval, flattened for listing across all boxes (hub UI). */\nexport interface PendingApproval {\n id: string;\n boxId: string;\n ev: PromptAskEvent;\n createdAt: string;\n}\n\nexport class PendingPrompts {\n private readonly entries = new Map<string, PendingPromptEntry>();\n private autoApprove: AutoApprovePolicy | null = null;\n private onChange: (() => void) | null = null;\n\n /** Install the per-box auto-approve policy (relay server, once at startup). */\n setAutoApprovePolicy(policy: AutoApprovePolicy): void {\n this.autoApprove = policy;\n }\n\n /**\n * Install a change hook fired whenever the pending set is mutated (add /\n * resolve). Wired by the relay server to the hub notifier so the embedded UI\n * pushes an update to connected browsers.\n */\n setOnChange(fn: () => void): void {\n this.onChange = fn;\n }\n\n /**\n * True when this box opted into `box.autoApproveHostActions`. Records the\n * bypass to the audit sink as a side effect so the caller short-circuits\n * with a trail. Returns false when no policy is installed.\n */\n consumeAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>): boolean {\n if (!this.autoApprove || !this.autoApprove.shouldAutoApprove(boxId)) return false;\n this.autoApprove.audit(boxId, params);\n return true;\n }\n\n /**\n * Record a *safe-subset* auto-approval (opening a PR, a contained file copy,\n * a sanctioned-branch push, …) to the audit sink WITHOUT the blanket\n * `autoApproveHostActions` opt-in. The handler already decided the action is\n * safe under `box.autoApproveSafeHostActions`; this just leaves the same\n * `host-action-auto-approved` trail a full opt-in would, tagged with `reason`.\n * No-op when no policy is installed (e.g. the stateless poll plane).\n */\n noteAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason: string): void {\n this.autoApprove?.audit(boxId, params, reason);\n }\n\n add(boxId: string, ev: PromptAskEvent): Promise<PromptResolution> {\n return new Promise<PromptResolution>((resolve) => {\n this.entries.set(ev.id, {\n ev,\n boxId,\n resolve,\n createdAt: new Date().toISOString(),\n });\n this.onChange?.();\n });\n }\n\n /**\n * Idempotent: returns true if a pending entry was found + resolved, false\n * otherwise. The /admin/prompts/answer handler uses the bool to decide\n * 204 vs 404 — the wrapper treats both as \"we're done.\"\n */\n resolve(id: string, answer: 'y' | 'n', cancelled?: boolean): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n this.entries.delete(id);\n entry.resolve({ answer, cancelled });\n this.onChange?.();\n return true;\n }\n\n /**\n * Snapshot of all pending prompts for a given box; used to flush the\n * backlog to a newly-attached SSE subscriber.\n */\n forBox(boxId: string): PromptAskEvent[] {\n const out: PromptAskEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n /**\n * Snapshot of every pending prompt across all boxes, with its boxId and\n * enqueue time — the hub's Approvals view lists these.\n */\n all(): PendingApproval[] {\n const out: PendingApproval[] = [];\n for (const entry of this.entries.values()) {\n out.push({ id: entry.ev.id, boxId: entry.boxId, ev: entry.ev, createdAt: entry.createdAt });\n }\n return out;\n }\n\n /** boxId that owns a pending prompt id, or null when unknown. */\n boxFor(id: string): string | null {\n const entry = this.entries.get(id);\n return entry ? entry.boxId : null;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Tracks the set of host-side wrappers (SSE clients) currently subscribed\n * per box. `broadcast` writes to every subscriber so the user can answer\n * from whichever attached window they happen to be in.\n */\nexport class PromptSubscribers {\n private readonly byBox = new Map<string, Set<ServerResponse>>();\n\n add(boxId: string, res: ServerResponse): void {\n let set = this.byBox.get(boxId);\n if (!set) {\n set = new Set();\n this.byBox.set(boxId, set);\n }\n set.add(res);\n }\n\n remove(boxId: string, res: ServerResponse): void {\n const set = this.byBox.get(boxId);\n if (!set) return;\n set.delete(res);\n if (set.size === 0) this.byBox.delete(boxId);\n }\n\n forBox(boxId: string): ServerResponse[] {\n const set = this.byBox.get(boxId);\n return set ? Array.from(set) : [];\n }\n\n /**\n * Fire-and-forget broadcast. SSE writes that fail (closed socket) are\n * swallowed — the `res.on('close')` handler in the server route already\n * deregisters the dead subscriber.\n */\n broadcast(boxId: string, event: string, data: unknown): void {\n const set = this.byBox.get(boxId);\n if (!set) return;\n const payload = `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n for (const res of set) {\n try {\n res.write(payload);\n } catch {\n /* dead socket; close handler will deregister */\n }\n }\n }\n}\n\n/**\n * Internal API used by handleGitRpc / handleCpRpc / handleDownloadRpc and the\n * `browser.open` host-mirror offer. Generates a UUID, adds a pending entry,\n * broadcasts the SSE event, and awaits the answer. Respects\n * `process.env.AGENTBOX_PROMPT === 'off'` — auto-accepts without broadcasting\n * (useful for headless scripts and tests) — and the per-box\n * `box.autoApproveHostActions` policy (auto-accepts with an audit event).\n *\n * `opts.ttlMs` makes the prompt auto-expire: if no answer arrives in time it\n * resolves to its `defaultAnswer` (cancelled) and a `prompt-resolved` event is\n * broadcast so attached wrappers clear it. Used for optional, non-blocking\n * prompts that must not linger when nobody answers; omit it for the\n * block-until-answered prompts that gate a paused in-box RPC.\n */\nexport async function askPrompt(\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n boxId: string,\n params: Omit<PromptAskEvent, 'id'>,\n opts?: { ttlMs?: number },\n): Promise<PromptResolution> {\n if (process.env.AGENTBOX_PROMPT === 'off') {\n return { answer: 'y' };\n }\n // Per-box opt-in: `box.autoApproveHostActions` resolves the confirm to 'y'\n // without surfacing a prompt, but records an audit event (inside\n // consumeAutoApprove) so the bypass is never silent.\n if (prompts.consumeAutoApprove(boxId, params)) {\n return { answer: 'y' };\n }\n const ev: PromptAskEvent = { id: randomUUID(), ...params };\n const promise = prompts.add(boxId, ev);\n subscribers.broadcast(boxId, 'prompt-ask', ev);\n if (opts?.ttlMs !== undefined && opts.ttlMs > 0) {\n const timer = setTimeout(() => {\n if (prompts.resolve(ev.id, params.defaultAnswer ?? 'n', true)) {\n subscribers.broadcast(boxId, 'prompt-resolved', { id: ev.id });\n }\n }, opts.ttlMs);\n if (typeof timer.unref === 'function') timer.unref();\n void promise.then(() => {\n clearTimeout(timer);\n });\n }\n return promise;\n}\n\n/** Helper for the answer body — used by the relay server to validate. */\nexport function isPromptAnswerBody(v: unknown): v is PromptAnswerBody {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n if (typeof o.id !== 'string' || o.id.length === 0) return false;\n if (o.answer !== 'y' && o.answer !== 'n') return false;\n if (o.cancelled !== undefined && typeof o.cancelled !== 'boolean') return false;\n return true;\n}\n","import { randomUUID } from 'node:crypto';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport type { Store } from './store/store.js';\nimport type { PromptAskEvent } from './types.js';\n\n/**\n * How the relay obtains host-action approval:\n * - 'block' — the laptop loopback relay (a long-lived process): the `/rpc`\n * handler blocks on an in-process `PendingPrompts` Promise until the human\n * answers (today's behavior, unchanged).\n * - 'poll' — the hosted control plane (serverless / stateless per request):\n * the gate parks a prompt row in the Store and returns immediately; `/rpc`\n * replies `202 {promptId}` and the box polls `/rpc/status/:id` for the\n * verdict + result.\n */\nexport type PromptMode = 'block' | 'poll';\n\nexport type ApprovalGate =\n | { kind: 'allow' }\n | { kind: 'deny' }\n | { kind: 'pending'; promptId: string };\n\nexport interface GateDeps {\n mode: PromptMode;\n store: Store;\n /** Required for block mode (the in-process blocking wait). */\n prompts?: PendingPrompts;\n /** Optional: SSE fan-out to an attached human dashboard. Absent on the stateless plane. */\n subscribers?: PromptSubscribers;\n}\n\n/**\n * Decide whether a host action may proceed. The caller has already cleared the\n * fast paths that never prompt at all (agentbox/* branch, valid host-initiated\n * token, read-only op). `promptParams` is the confirm to show the human;\n * `method`/`params` are persisted on the poll-mode row so the approved action\n * can be re-dispatched when the box polls.\n *\n * - 'block': returns allow/deny once the human answers (or AGENTBOX_PROMPT=off\n * / autoApprove resolves it). Behaviorally identical to the pre-poll relay.\n * - 'poll': returns allow when no human is needed (AGENTBOX_PROMPT=off /\n * autoApprove, audited), else parks a pending row and returns its promptId.\n */\nexport async function gateApproval(\n deps: GateDeps,\n boxId: string,\n method: string,\n params: unknown,\n promptParams: Omit<PromptAskEvent, 'id'>,\n): Promise<ApprovalGate> {\n if (deps.mode === 'block') {\n // askPrompt handles AGENTBOX_PROMPT=off + autoApprove (with audit) + the\n // blocking wait, exactly as before. Block mode requires in-process state.\n if (!deps.prompts || !deps.subscribers) return { kind: 'deny' };\n const verdict = await askPrompt(deps.prompts, deps.subscribers, boxId, promptParams);\n return verdict.answer === 'y' && !verdict.cancelled ? { kind: 'allow' } : { kind: 'deny' };\n }\n // poll mode: store-based fast paths (works on the stateless hosted plane, no\n // in-process registry/prompts), then park a row the box will poll for.\n if (process.env.AGENTBOX_PROMPT === 'off') return { kind: 'allow' };\n const box = await deps.store.getBox(boxId);\n if (box?.autoApproveHostActions) {\n // Audited bypass — still observable in the event feed.\n await deps.store.appendEvent({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: promptParams.context?.command,\n argv: promptParams.context?.argv,\n message: promptParams.message,\n },\n });\n return { kind: 'allow' };\n }\n const promptId = randomUUID();\n const ev: PromptAskEvent = { id: promptId, ...promptParams };\n await deps.store.createPrompt({\n id: promptId,\n boxId,\n ev,\n method,\n params,\n status: 'pending',\n createdAt: new Date().toISOString(),\n });\n // Best-effort SSE for an attached human dashboard (no-op when none / on the\n // stateless plane); the box itself never relies on SSE — it polls /rpc/status.\n deps.subscribers?.broadcast(boxId, 'prompt-ask', ev);\n return { kind: 'pending', promptId };\n}\n","import type { BoxRegistration, BoxWorktree } from './types.js';\n\n/**\n * Resolve `containerPath` (a path inside the box) to the registered worktree\n * whose `hostMainRepo` + `branch` the relay should act on. `/workspace` maps to\n * the root repo; `/workspace/<sub>` maps to a nested repo when registered\n * (longest prefix wins). Pure — shared by the node relay (server.ts) and the\n * hosted-plane handler (core/handler.ts).\n */\nexport function resolveWorktree(reg: BoxRegistration, containerPath: string): BoxWorktree | null {\n const trees = reg.worktrees ?? [];\n if (trees.length === 0) return null;\n const exact = trees.find((w) => w.containerPath === containerPath);\n if (exact) return exact;\n const prefixMatches = trees\n .filter(\n (w) => containerPath === w.containerPath || containerPath.startsWith(w.containerPath + '/'),\n )\n .sort((a, b) => b.containerPath.length - a.containerPath.length);\n return prefixMatches[0] ?? trees.find((w) => w.containerPath === '/workspace') ?? null;\n}\n","/**\n * Pure GitHub remote-URL helpers: parse a remote, rewrite it to carry a token\n * over HTTPS, and derive the `gh --repo` slug. Shared by the control plane's\n * GitHub-App token leasing (`lease.ts`) and the cloud git.push path.\n */\n\n/**\n * Parse any GitHub remote URL (scp-like `git@host:owner/repo`, `ssh://…`, or\n * `https://…`, with or without embedded creds) into `{ host, path }`. Throws on\n * an unrecognized shape.\n */\nexport function parseGitRemote(origin: string): { host: string; path: string } {\n const trimmed = origin.trim();\n if (trimmed.length === 0) throw new Error('empty git remote URL');\n\n // URL form first: scheme://[user@]host[:port]/path. Matching this before the\n // scp branch avoids misreading `https://github.com/...` as scp `https:...`.\n const urlForm = /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^@/]+@)?([^/:]+)(?::\\d+)?\\/(.+)$/i.exec(trimmed);\n const scpForm = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);\n let host: string;\n let path: string;\n if (urlForm) {\n host = urlForm[1]!;\n path = urlForm[2]!;\n } else if (scpForm && !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed)) {\n host = scpForm[1]!;\n path = scpForm[2]!;\n } else {\n throw new Error(`unrecognized git remote URL: ${origin}`);\n }\n return { host, path: path.replace(/^\\/+/, '') };\n}\n\n/**\n * Rewrite any GitHub remote URL into an HTTPS URL carrying the PAT as\n * `x-access-token`. Throws on an unrecognized shape.\n */\nexport function toAuthedHttpsUrl(origin: string, token: string): string {\n const { host, path } = parseGitRemote(origin);\n return `https://x-access-token:${token}@${host}/${path}`;\n}\n\n/**\n * The `[HOST/]OWNER/REPO` slug `gh --repo` expects, derived from a remote URL.\n * github.com is implicit (just `OWNER/REPO`); enterprise hosts are prefixed.\n */\nexport function repoSlugFromRemote(origin: string): string {\n const { host, path } = parseGitRemote(origin);\n const repo = path.replace(/\\.git$/, '');\n return host.toLowerCase() === 'github.com' ? repo : `${host}/${repo}`;\n}\n","import { parseGitRemote, repoSlugFromRemote, toAuthedHttpsUrl } from './git-pat.js';\nimport type { GitHubAppLeaser } from './github-app.js';\nimport type { BoxRegistration, GitRpcResult } from './types.js';\n\n/**\n * Mint a repo-scoped GitHub-App installation token for a box and package it as\n * a `{exitCode,stdout,stderr}` result whose `stdout` is the lease JSON\n * (`{ token, expiresAt, remoteUrl, repo }`). Shared by the node relay\n * (server.ts) and the hosted-plane handler (core/handler.ts).\n *\n * The repo is resolved from the box's REGISTERED origin URL — never from\n * box-supplied params — so a box can only ever lease a token for its own repo.\n */\nexport async function leaseTokenResult(\n leaser: GitHubAppLeaser | null,\n reg: BoxRegistration,\n): Promise<GitRpcResult> {\n if (!leaser) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'git.lease-token: no GitHub App configured on this relay\\n',\n };\n }\n const origin = reg.originUrl;\n if (!origin) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `git.lease-token: box ${reg.boxId} has no registered origin URL\\n`,\n };\n }\n let owner = '';\n let repo = '';\n let slug = '';\n try {\n const { path } = parseGitRemote(origin);\n const [o, r] = path.replace(/\\.git$/, '').split('/');\n owner = o ?? '';\n repo = r ?? '';\n slug = repoSlugFromRemote(origin);\n } catch {\n return { exitCode: 65, stdout: '', stderr: `git.lease-token: unrecognized origin ${origin}\\n` };\n }\n if (!owner || !repo) {\n return {\n exitCode: 65,\n stdout: '',\n stderr: `git.lease-token: cannot derive owner/repo from ${origin}\\n`,\n };\n }\n try {\n const leased = await leaser.leaseRepoToken(owner, repo);\n const payload = {\n token: leased.token,\n expiresAt: leased.expiresAt,\n remoteUrl: toAuthedHttpsUrl(origin, leased.token),\n repo: slug,\n };\n return { exitCode: 0, stdout: JSON.stringify(payload), stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `git.lease-token: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n","import { createSign } from 'node:crypto';\n\n/**\n * GitHub App token leasing for the hosted control plane.\n *\n * The control plane holds only the App's private key + id — never a long-lived\n * PAT and never a box's repo. On an approved push it mints a short-lived\n * **installation access token** scoped to the SINGLE box repo (minimal perms)\n * and hands it to the box, which pushes to GitHub directly. GitHub installation\n * tokens always expire in ≤1h and are repo-scoped, so a compromised box yields\n * at most a 1h single-repo credential. The token is never persisted (in-memory\n * cache only; re-minted on a cold start — two cheap API calls).\n *\n * `fetch` (Node 20+) is used directly — no SDK dependency.\n */\n\nexport interface GitHubAppConfig {\n appId: string;\n privateKeyPem: string;\n /** API base; defaults to https://api.github.com (override for GHES). */\n apiBaseUrl?: string;\n}\n\nexport interface LeasedToken {\n token: string;\n /** ISO-8601 expiry as returned by GitHub. */\n expiresAt: string;\n}\n\n/**\n * Load the App config from the environment, or null when not configured.\n * `GITHUB_APP_PRIVATE_KEY` may be a raw PEM or base64-encoded PEM (env-friendly).\n */\nexport function loadGitHubAppConfig(): GitHubAppConfig | null {\n const appId = process.env.GITHUB_APP_ID;\n let key = process.env.GITHUB_APP_PRIVATE_KEY;\n if (!appId || !key) return null;\n if (!key.includes('BEGIN')) {\n try {\n key = Buffer.from(key, 'base64').toString('utf8');\n } catch {\n return null;\n }\n }\n const apiBaseUrl = process.env.GITHUB_API_URL || undefined;\n return { appId, privateKeyPem: key, apiBaseUrl };\n}\n\nfunction b64url(input: string | Buffer): string {\n return Buffer.from(input).toString('base64url');\n}\n\n/**\n * Mint the App JWT (RS256). `exp` is well under GitHub's 10-minute ceiling;\n * `iat` is backdated 60s to tolerate clock skew. Exported for unit testing.\n */\nexport function appJwt(cfg: GitHubAppConfig, nowMs: number = Date.now()): string {\n const now = Math.floor(nowMs / 1000);\n const header = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));\n const payload = b64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: cfg.appId }));\n const signingInput = `${header}.${payload}`;\n const signature = createSign('RSA-SHA256').update(signingInput).sign(cfg.privateKeyPem);\n return `${signingInput}.${b64url(signature)}`;\n}\n\ntype FetchLike = typeof fetch;\n\nexport interface GitHubAppLeaserOptions {\n /** Inject a fetch impl (tests). Defaults to the global fetch. */\n fetchImpl?: FetchLike;\n /** Inject a clock (tests). Defaults to Date.now. */\n now?: () => number;\n}\n\ninterface CacheEntry {\n token: string;\n expiresAt: string;\n expiresAtMs: number;\n}\n\nconst RENEW_BEFORE_MS = 5 * 60 * 1000; // re-mint when <5 min of life remains\n\n/**\n * Leases (and caches) repo-scoped installation tokens. One instance per relay\n * server. The cache key is `owner/repo`; a token is reused until it is within\n * RENEW_BEFORE_MS of expiry.\n */\nexport class GitHubAppLeaser {\n private readonly cfg: GitHubAppConfig;\n private readonly fetchImpl: FetchLike;\n private readonly now: () => number;\n private readonly apiBase: string;\n private readonly cache = new Map<string, CacheEntry>();\n private readonly installationIds = new Map<string, number>();\n\n constructor(cfg: GitHubAppConfig, opts: GitHubAppLeaserOptions = {}) {\n this.cfg = cfg;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.now = opts.now ?? Date.now;\n this.apiBase = (cfg.apiBaseUrl ?? 'https://api.github.com').replace(/\\/$/, '');\n }\n\n private headers(jwt: string): Record<string, string> {\n return {\n Authorization: `Bearer ${jwt}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'agentbox-relay',\n };\n }\n\n /**\n * Resolve the installation id for `owner/repo`, or null when the App is not\n * installed on it (404). Caches positive lookups. Non-404 errors throw.\n */\n private async lookupInstallationId(owner: string, repo: string): Promise<number | null> {\n const key = `${owner}/${repo}`;\n const cached = this.installationIds.get(key);\n if (cached !== undefined) return cached;\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(`${this.apiBase}/repos/${owner}/${repo}/installation`, {\n headers: this.headers(jwt),\n });\n if (res.status === 404) return null;\n if (!res.ok) {\n throw new Error(`GET installation for ${key} → ${String(res.status)}`);\n }\n const body = (await res.json()) as { id?: number };\n if (typeof body.id !== 'number') throw new Error('installation response missing id');\n this.installationIds.set(key, body.id);\n return body.id;\n }\n\n private async installationId(owner: string, repo: string): Promise<number> {\n const id = await this.lookupInstallationId(owner, repo);\n if (id === null) throw new Error(`GitHub App is not installed on ${owner}/${repo}`);\n return id;\n }\n\n /** Whether the App is installed on `owner/repo` — no token is minted. */\n async isRepoInstalled(owner: string, repo: string): Promise<boolean> {\n return (await this.lookupInstallationId(owner, repo)) !== null;\n }\n\n /**\n * Mint (or return a cached) installation token scoped to the single repo with\n * `contents: write` + `pull_requests: write`. Throws on any GitHub error.\n */\n async leaseRepoToken(owner: string, repo: string): Promise<LeasedToken> {\n const key = `${owner}/${repo}`;\n const cached = this.cache.get(key);\n if (cached && cached.expiresAtMs - this.now() > RENEW_BEFORE_MS) {\n return { token: cached.token, expiresAt: cached.expiresAt };\n }\n const id = await this.installationId(owner, repo);\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(`${this.apiBase}/app/installations/${String(id)}/access_tokens`, {\n method: 'POST',\n headers: { ...this.headers(jwt), 'Content-Type': 'application/json' },\n body: JSON.stringify({\n repositories: [repo],\n permissions: { contents: 'write', pull_requests: 'write' },\n }),\n });\n if (!res.ok) {\n throw new Error(`failed to mint installation token for ${key} (→ ${String(res.status)})`);\n }\n const body = (await res.json()) as { token?: string; expires_at?: string };\n if (!body.token || !body.expires_at) throw new Error('access_tokens response missing token/expires_at');\n this.cache.set(key, {\n token: body.token,\n expiresAt: body.expires_at,\n expiresAtMs: Date.parse(body.expires_at),\n });\n return { token: body.token, expiresAt: body.expires_at };\n }\n}\n","import type { CreateJobRequest, Store } from './store/store.js';\n\n/**\n * The actual box-creation step, injected by the deploy target. On a self-host\n * worker / Vercel cron this provisions a cloud box and seeds its workspace by\n * cloning `request.repoUrl` with a leased GitHub-App token (origin-clone — no\n * host bundle). Kept injectable so the worker loop is unit-testable without a\n * live cloud, and so the heavy provider wiring lives outside the relay core.\n */\nexport type CreateBoxFn = (request: CreateJobRequest, jobId: string) => Promise<{ boxId: string }>;\n\n/**\n * Claim + run ONE queued create job. Returns the processed job id, or null when\n * the queue is empty (or the store has no create-job support). A throwing\n * `createBox` marks the job failed (never throws out of here).\n */\nexport async function drainOneCreateJob(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n): Promise<string | null> {\n if (!store.claimNextCreateJob || !store.completeCreateJob) return null;\n const job = await store.claimNextCreateJob(workerId);\n if (!job) return null;\n try {\n const { boxId } = await createBox(job.request, job.id);\n await store.completeCreateJob(job.id, 'done', { boxId });\n } catch (err) {\n await store.completeCreateJob(job.id, 'failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return job.id;\n}\n\n/**\n * Drain queued create jobs until the queue is empty or `max` is hit. Used by\n * the self-host worker loop and a Vercel cron tick. Returns the count processed.\n */\nexport async function drainCreateJobs(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n max = 10,\n): Promise<number> {\n let processed = 0;\n while (processed < max) {\n const id = await drainOneCreateJob(store, createBox, workerId);\n if (!id) break;\n processed++;\n }\n return processed;\n}\n","import type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { PromptRow, Store } from './store.js';\n\n/**\n * A tiny RPC envelope over the {@link Store} interface, so a federated laptop\n * relay can back its state with a remote (hosted) Store over HTTP. The hosted\n * plane exposes `POST /admin/store` (admin-gated) and applies the op via\n * {@link applyStoreOp}; {@link RemoteStore} is the client that posts these.\n *\n * Generic-but-typed: a single switch keeps the dispatch type-safe (no `any`)\n * and the method names are an explicit allow-list — the endpoint can never\n * invoke an arbitrary property of the store object.\n */\nexport interface StoreRpcRequest {\n method: string;\n args: unknown[];\n}\n\nexport interface StoreRpcResponse {\n /** Method return value (already JSON-safe — every Store method returns plain data). */\n result: unknown;\n}\n\n/** True when `method` is a dispatchable Store op. */\nexport function isStoreRpcMethod(method: string): boolean {\n return STORE_RPC_METHODS.has(method);\n}\n\nconst STORE_RPC_METHODS = new Set<string>([\n 'registerBox',\n 'getBox',\n 'authenticateBox',\n 'listBoxes',\n 'forgetBox',\n 'countBoxes',\n 'appendEvent',\n 'listEvents',\n 'countEvents',\n 'setStatus',\n 'getStatus',\n 'deleteStatus',\n 'createPrompt',\n 'getPrompt',\n 'answerPrompt',\n 'listPendingPrompts',\n 'setPromptResult',\n]);\n\n/** Apply a store op by name with typed argument coercion. Throws on unknown method. */\nexport function applyStoreOp(store: Store, method: string, args: unknown[]): Promise<unknown> {\n switch (method) {\n case 'registerBox':\n return store.registerBox(args[0] as BoxRegistration);\n case 'getBox':\n return store.getBox(args[0] as string);\n case 'authenticateBox':\n return store.authenticateBox(args[0] as string);\n case 'listBoxes':\n return store.listBoxes();\n case 'forgetBox':\n return store.forgetBox(args[0] as string);\n case 'countBoxes':\n return store.countBoxes();\n case 'appendEvent':\n return store.appendEvent(args[0] as Omit<RelayEvent, 'id' | 'receivedAt'>);\n case 'listEvents':\n return store.listEvents(args[0] as number, args[1] as string | undefined);\n case 'countEvents':\n return store.countEvents();\n case 'setStatus':\n return store.setStatus(\n args[0] as string,\n args[1] as string,\n args[2] as number | undefined,\n args[3] as BoxStatusSnapshot,\n );\n case 'getStatus':\n return store.getStatus(args[0] as string);\n case 'deleteStatus':\n return store.deleteStatus(args[0] as string);\n case 'createPrompt':\n return store.createPrompt(args[0] as PromptRow);\n case 'getPrompt':\n return store.getPrompt(args[0] as string);\n case 'answerPrompt':\n return store.answerPrompt(\n args[0] as string,\n args[1] as 'y' | 'n',\n args[2] as boolean | undefined,\n );\n case 'listPendingPrompts':\n return store.listPendingPrompts(args[0] as string);\n case 'setPromptResult':\n return store.setPromptResult(args[0] as string, args[1] as GitRpcResult);\n default:\n throw new Error(`unknown store op: ${method}`);\n }\n}\n","import { randomUUID, timingSafeEqual } from 'node:crypto';\nimport type { GitHubAppLeaser } from '../github-app.js';\nimport { leaseTokenResult } from '../lease.js';\nimport { gateApproval } from '../permission.js';\nimport { isValidBoxStatus } from '../status-store.js';\nimport type { Store } from '../store/store.js';\nimport { applyStoreOp, isStoreRpcMethod, type StoreRpcRequest } from '../store/store-rpc.js';\nimport { resolveWorktree } from '../worktree.js';\nimport type { CreateJobRequest } from '../store/store.js';\nimport { isScratchBranch } from '@agentbox/core';\nimport type {\n BoxRegistration,\n GitRpcParams,\n PostEventBody,\n PostRpcBody,\n RegisterBoxBody,\n} from '../types.js';\n\n/**\n * Framework-agnostic request/response dispatch for the HOSTED control plane\n * (the Next.js app on Vercel / self-host). It reuses the relay's shared\n * primitives — the {@link Store}, {@link gateApproval}, the GitHub-App leaser —\n * but is decoupled from node:http and from host execution: it never runs git\n * locally (no worktree on the hosted plane) and obtains approvals via the poll\n * mailbox, never by blocking. The long-lived laptop relay keeps using\n * `server.ts` (node:http, host execution, SSE); they share the same core\n * building blocks but not this handler.\n *\n * Host-local RPCs (cp/download/checkpoint, and the docker-style git.push/fetch)\n * are intentionally rejected here — they require a host, which the plane has\n * none of. Cloud boxes push via `git.lease-token` instead.\n */\nexport interface GenericRequest {\n method: string;\n /** URL pathname, e.g. \"/rpc\" or \"/rpc/status/<id>\". */\n path: string;\n query: URLSearchParams;\n /** The Bearer token, already extracted ('' when absent). */\n bearer: string;\n /** Raw request body (already read by the adapter; '' for GET). */\n bodyText: string;\n}\n\nexport interface RelayResponse {\n status: number;\n /** JSON-serializable body (omitted → empty response). */\n body?: unknown;\n}\n\nexport interface ControlPlaneDeps {\n store: Store;\n /** GitHub-App leaser for `git.lease-token`; null → leasing returns a clear error. */\n leaser: GitHubAppLeaser | null;\n /** Admin bearer gating `/admin/*` + `/remote/*`. Required (fail-closed). */\n adminToken: string;\n /**\n * Providers this plane can CREATE boxes on (gates `POST /remote/boxes`).\n * `undefined`/empty → all providers allowed. A serverless plane (Vercel, no\n * worker) sets this to the SDK-native set so it cleanly refuses providers\n * whose `create()` needs host execution (e.g. hetzner).\n */\n createProviders?: string[];\n log?: (line: string) => void;\n}\n\nfunction ok(body: unknown, status = 200): RelayResponse {\n return { status, body };\n}\nfunction err(status: number, error: string): RelayResponse {\n return { status, body: { error } };\n}\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\nconst HOST_LOCAL_METHODS = new Set([\n 'git.push',\n 'git.fetch',\n 'cp.toHost',\n 'cp.fromHost',\n 'download.workspace',\n 'download.env',\n 'download.config',\n 'download.claude',\n 'checkpoint.create',\n]);\n\n/**\n * Dispatch one control-plane request. The hosted plane's gating is fixed:\n * `/admin/*` and `/remote/*` always require the admin bearer (never loopback),\n * and approvals are always poll-mode.\n */\nexport async function handleRelayRequest(\n req: GenericRequest,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n const { store, leaser } = deps;\n const log = deps.log ?? (() => {});\n\n if (deps.adminToken.length === 0) {\n // Fail closed — a hosted plane with no admin token must never serve /admin/*.\n // 503 (not 500): a deploy that hasn't had its secrets set yet is \"not ready\",\n // not crashed. healthz is handled before this in the Web adapter (lib/plane.ts).\n return err(503, 'control plane not configured: admin token unset');\n }\n\n if (req.method === 'GET' && req.path === '/healthz') {\n return ok({\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n controlPlane: true,\n });\n }\n\n const isAdmin = req.path.startsWith('/admin/') || req.path.startsWith('/remote/');\n if (isAdmin && !timingSafeEqualStr(req.bearer, deps.adminToken)) {\n return err(401, 'invalid admin token');\n }\n\n // --- box endpoints (per-box bearer) ---\n if (req.method === 'POST' && req.path === '/events') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostEventBody>(req.bodyText);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n return err(400, 'missing \"type\" string');\n }\n if (body.type === 'box-status') {\n if (!isValidBoxStatus(body.payload)) return err(400, 'invalid box-status payload');\n await store.setStatus(reg.boxId, reg.name, reg.projectIndex, body.payload);\n return ok({ ok: true }, 202);\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n return ok({ id: ev.id }, 202);\n }\n\n if (req.method === 'POST' && req.path === '/rpc') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostRpcBody>(req.bodyText);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n return err(400, 'missing \"method\" string');\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n return dispatchRpc(reg, body.method, body.params, deps);\n }\n\n if (req.method === 'GET' && req.path.startsWith('/rpc/status/')) {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const promptId = decodeURIComponent(req.path.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) return err(404, 'no such prompt');\n if (row.status === 'pending') return ok({ status: 'pending' });\n if (row.answer !== 'y' || row.cancelled) {\n return ok({ status: 'done', result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' } });\n }\n const cached = row.result;\n const result = cached ?? (await runApproved(reg, row.method, leaser));\n if (!cached) await store.setPromptResult(promptId, result);\n return ok({ status: 'done', result });\n }\n\n // --- admin endpoints (admin bearer, checked above) ---\n if (req.method === 'POST' && req.path === '/admin/register-box') {\n const body = parseJson<RegisterBoxBody>(req.bodyText);\n if (!body || !body.boxId || !body.token || typeof body.name !== 'string') {\n return err(400, 'expected {boxId, token, name}');\n }\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind: body.kind === 'cloud' ? 'cloud' : 'docker',\n backend: body.backend || undefined,\n registeredAt: new Date().toISOString(),\n containerName: body.containerName || undefined,\n createdAt: body.createdAt || undefined,\n projectIndex:\n typeof body.projectIndex === 'number' && body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined,\n worktrees: Array.isArray(body.worktrees) ? body.worktrees : undefined,\n previewUrl: body.previewUrl || undefined,\n previewToken: body.previewToken || undefined,\n bridgeToken: body.bridgeToken || undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl: body.originUrl || undefined,\n };\n await store.registerBox(reg);\n log(`registered ${reg.kind ?? 'docker'} box ${reg.boxId} (${reg.name})`);\n return ok(null, 204);\n }\n\n if (req.method === 'POST' && req.path === '/admin/forget-box') {\n const body = parseJson<{ boxId?: string }>(req.bodyText);\n if (!body?.boxId) return err(400, 'expected {boxId}');\n await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n return ok(null, 204);\n }\n\n if (req.method === 'GET' && req.path === '/admin/box-status') {\n const box = req.query.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n return status ? ok(status) : err(404, 'no status for box');\n }\n\n if (req.method === 'GET' && req.path === '/admin/events') {\n const since = Number.parseInt(req.query.get('since') ?? '0', 10) || 0;\n const box = req.query.get('box') ?? undefined;\n return ok({ events: await store.listEvents(since, box ?? undefined) });\n }\n\n if (req.method === 'GET' && req.path === '/admin/app/repo-installed') {\n // Whether the GitHub App is installed on owner/repo — lets a CLI without a\n // local App key (a laptop pointed at this plane) decide whether to prompt\n // the user to authorize the repo. No token is minted.\n if (!leaser) return err(503, 'no GitHub App configured on this control plane');\n const owner = req.query.get('owner') ?? '';\n const repo = req.query.get('repo') ?? '';\n if (!owner || !repo) return err(400, 'missing owner/repo query params');\n try {\n return ok({ installed: await leaser.isRepoInstalled(owner, repo) });\n } catch (e) {\n return err(502, `installation check failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n if (req.method === 'GET' && req.path === '/admin/registry') {\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n kind: r.kind,\n registeredAt: r.registeredAt,\n projectIndex: r.projectIndex,\n originUrl: r.originUrl,\n }));\n return ok({ boxes: redacted });\n }\n\n if (req.method === 'GET' && req.path === '/admin/prompts') {\n const boxId = req.query.get('boxId') ?? '';\n if (boxId.length === 0) return err(400, 'missing boxId query param');\n const pending = (await store.listPendingPrompts(boxId)).map((r) => r.ev);\n return ok({ prompts: pending });\n }\n\n if (req.method === 'POST' && req.path === '/admin/prompts/answer') {\n const body = parseJson<{ id?: string; answer?: string; cancelled?: boolean }>(req.bodyText);\n if (!body?.id || (body.answer !== 'y' && body.answer !== 'n')) {\n return err(400, 'expected {id, answer:\"y\"|\"n\", cancelled?}');\n }\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n return hit ? ok(null, 204) : err(404, 'no pending prompt with that id');\n }\n\n if (req.method === 'POST' && req.path === '/admin/store') {\n // Generic Store RPC for a federated laptop relay's RemoteStore. Admin-gated\n // (checked above); the method name is an explicit allow-list.\n const body = parseJson<StoreRpcRequest>(req.bodyText);\n if (!body || typeof body.method !== 'string' || !Array.isArray(body.args)) {\n return err(400, 'expected {method, args}');\n }\n if (!isStoreRpcMethod(body.method)) return err(400, `unknown store op: ${body.method}`);\n const result = await applyStoreOp(store, body.method, body.args);\n return ok({ result: result ?? null });\n }\n\n if (req.method === 'POST' && req.path === '/remote/boxes') {\n // Enqueue a durable create job; a worker (self-host loop / Vercel cron)\n // drains it and clones the repo into a fresh cloud box via a leased token.\n if (!store.enqueueCreateJob) return err(501, 'create-job queue not available on this store');\n const body = parseJson<CreateJobRequest>(req.bodyText);\n if (!body || typeof body.repoUrl !== 'string' || typeof body.provider !== 'string') {\n return err(400, 'expected {repoUrl, provider, branch?, name?, agent?, prompt?}');\n }\n const allowed = deps.createProviders;\n if (allowed && allowed.length > 0 && !allowed.includes(body.provider)) {\n return err(\n 400,\n `provider '${body.provider}' is not supported by this control plane (allowed: ${allowed.join(', ')})`,\n );\n }\n const id = randomUUID();\n await store.enqueueCreateJob({\n id,\n status: 'queued',\n request: {\n repoUrl: body.repoUrl,\n provider: body.provider,\n branch: body.branch,\n name: body.name,\n agent: body.agent,\n prompt: body.prompt,\n },\n createdAt: new Date().toISOString(),\n });\n log(`enqueued create job ${id} (${body.provider} ${body.repoUrl})`);\n return ok({ jobId: id }, 202);\n }\n\n if (req.method === 'GET' && req.path.startsWith('/remote/boxes/')) {\n if (!store.getCreateJob) return err(501, 'create-job queue not available on this store');\n const id = decodeURIComponent(req.path.slice('/remote/boxes/'.length));\n const job = await store.getCreateJob(id);\n return job ? ok(job) : err(404, 'no such job');\n }\n\n return err(404, 'not found');\n}\n\nasync function dispatchRpc(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n if (method === 'git.lease-token') {\n const p = params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, p?.path ?? '/workspace');\n // Lease-token grants a *repo-scoped* push token — the box can then push any\n // branch with it, so (unlike the relay-driven git.push, where the relay\n // picks the exact branch) the sanctioned-branch auto-approve does NOT apply\n // here. Only the box's own scratch branch bypasses; everything else parks\n // for a human.\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval({ mode: 'poll', store: deps.store }, reg.boxId, method, params, {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: p?.path },\n });\n if (gate.kind === 'pending') return ok({ status: 'pending', promptId: gate.promptId }, 202);\n if (gate.kind === 'deny') {\n return ok({ exitCode: 10, stdout: '', stderr: 'denied by user\\n' }, 500);\n }\n }\n const result = await leaseTokenResult(deps.leaser, reg);\n return ok(result, result.exitCode === 0 ? 200 : 500);\n }\n\n if (method === 'browser.open') {\n // The box already opened it locally; just record the event (no host mirror).\n const p = params as { url?: unknown } | undefined;\n if (typeof p?.url === 'string') {\n await deps.store.appendEvent({ boxId: reg.boxId, type: 'browser-open', payload: { url: p.url } });\n }\n return ok({ exitCode: 0, stdout: '', stderr: '' });\n }\n\n if (HOST_LOCAL_METHODS.has(method)) {\n return ok(\n {\n exitCode: 64,\n stdout: '',\n stderr: `${method}: not available on the hosted control plane (no host). Cloud boxes push via git.lease-token.\\n`,\n },\n 501,\n );\n }\n\n return ok({ error: 'rpc method not implemented', method }, 501);\n}\n\n/** Execute a poll-approved action on the hosted plane. Only leasing is parkable here. */\nasync function runApproved(\n reg: BoxRegistration,\n method: string,\n leaser: GitHubAppLeaser | null,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n if (method === 'git.lease-token') return leaseTokenResult(leaser, reg);\n return { exitCode: 64, stdout: '', stderr: `relay: no approved-action executor for ${method}\\n` };\n}\n","import type { Pool } from 'pg';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport { RELAY_EVENT_RING_SIZE } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\n/**\n * Postgres-backed {@link Store} for the hosted control plane (Vercel-managed\n * Postgres, Neon, or a self-hosted Postgres beside the app). `pg` is loaded\n * via a lazy dynamic import so the laptop relay / CLI bundle — which only ever\n * uses {@link MemoryStore} — never pulls it in (mirrors how host-actions.ts\n * lazy-loads the cloud SDKs; `pg` is in the relay tsup `external` list).\n *\n * Phase 1 covers boxes + events + status (the current {@link Store} surface).\n * The prompt mailbox, host-initiated tokens, and the create-job queue get\n * their tables + methods in their own phases.\n */\n\nconst DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;\n\n/** Idempotent DDL for the tables this store owns. Run by {@link PostgresStore.migrate}. */\nexport const SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS boxes (\n box_id text PRIMARY KEY,\n token text NOT NULL,\n origin_url text,\n data jsonb NOT NULL,\n registered_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);\n\nCREATE TABLE IF NOT EXISTS events (\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n box_id text NOT NULL,\n type text NOT NULL,\n ts text,\n payload jsonb,\n received_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);\n\nCREATE TABLE IF NOT EXISTS box_status (\n box_id text PRIMARY KEY,\n name text,\n project_index int,\n status jsonb NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id text PRIMARY KEY,\n box_id text NOT NULL,\n ev jsonb NOT NULL,\n method text NOT NULL,\n params jsonb,\n status text NOT NULL DEFAULT 'pending',\n answer text,\n cancelled boolean,\n result jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS prompts_box_pending_idx ON prompts (box_id) WHERE status = 'pending';\n\nCREATE TABLE IF NOT EXISTS create_jobs (\n id text PRIMARY KEY,\n status text NOT NULL DEFAULT 'queued',\n request jsonb NOT NULL,\n result jsonb,\n claimed_by text,\n created_at timestamptz NOT NULL DEFAULT now(),\n started_at timestamptz,\n finished_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS create_jobs_queued_idx ON create_jobs (created_at) WHERE status = 'queued';\n`;\n\nexport interface PostgresStoreOptions {\n /** Postgres connection string (e.g. `process.env.POSTGRES_URL`). */\n connectionString?: string;\n /** Inject a pre-built pool (tests / a shared app pool). Takes precedence over connectionString. */\n pool?: Pool;\n /**\n * Global event-row cap, mirroring the in-memory ring. Newest N kept by id;\n * older rows trimmed on append. 0 disables trimming. Default 1000.\n */\n eventCap?: number;\n}\n\nexport class PostgresStore implements Store {\n private readonly eventCap: number;\n private readonly connectionString?: string;\n private injectedPool?: Pool;\n private poolPromise: Promise<Pool> | null = null;\n\n constructor(opts: PostgresStoreOptions = {}) {\n this.connectionString = opts.connectionString;\n this.injectedPool = opts.pool;\n this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;\n }\n\n /** Lazily build (or reuse) the pg Pool. `pg` is imported on first use only. */\n private pool(): Promise<Pool> {\n if (this.injectedPool) return Promise.resolve(this.injectedPool);\n if (!this.poolPromise) {\n this.poolPromise = import('pg').then(({ Pool }) => new Pool({ connectionString: this.connectionString }));\n }\n return this.poolPromise;\n }\n\n private async query<R>(text: string, params?: unknown[]): Promise<R[]> {\n const pool = await this.pool();\n const res = await pool.query(text, params as unknown[]);\n return res.rows as R[];\n }\n\n /** Create the tables if absent. Call once on boot (idempotent). */\n async migrate(): Promise<void> {\n const pool = await this.pool();\n await pool.query(SCHEMA_SQL);\n }\n\n /** Release the pool (tests / graceful shutdown). No-op for an injected pool. */\n async close(): Promise<void> {\n if (this.injectedPool) return;\n if (this.poolPromise) {\n const pool = await this.poolPromise;\n await pool.end();\n this.poolPromise = null;\n }\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n const originUrl = reg.originUrl ?? null;\n await this.query(\n `INSERT INTO boxes (box_id, token, origin_url, data)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (box_id) DO UPDATE\n SET token = EXCLUDED.token, origin_url = EXCLUDED.origin_url, data = EXCLUDED.data`,\n [reg.boxId, reg.token, originUrl, JSON.stringify(reg)],\n );\n }\n\n async getBox(boxId: string): Promise<BoxRegistration | undefined> {\n const rows = await this.query<{ data: BoxRegistration }>(\n `SELECT data FROM boxes WHERE box_id = $1`,\n [boxId],\n );\n return rows[0]?.data;\n }\n\n async authenticateBox(token: string): Promise<BoxRegistration | null> {\n if (token.length === 0) return null;\n const rows = await this.query<{ data: BoxRegistration }>(\n `SELECT data FROM boxes WHERE token = $1 LIMIT 1`,\n [token],\n );\n return rows[0]?.data ?? null;\n }\n\n async listBoxes(): Promise<BoxRegistration[]> {\n const rows = await this.query<{ data: BoxRegistration }>(\n `SELECT data FROM boxes ORDER BY registered_at`,\n );\n return rows.map((r) => r.data);\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const rows = await this.query<{ box_id: string }>(\n `DELETE FROM boxes WHERE box_id = $1 RETURNING box_id`,\n [boxId],\n );\n return rows.length > 0;\n }\n\n async countBoxes(): Promise<number> {\n const rows = await this.query<{ n: string }>(`SELECT count(*)::text AS n FROM boxes`);\n return Number.parseInt(rows[0]?.n ?? '0', 10);\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const rows = await this.query<{ id: string; received_at: Date }>(\n `INSERT INTO events (box_id, type, ts, payload)\n VALUES ($1, $2, $3, $4)\n RETURNING id, received_at`,\n [input.boxId, input.type, input.ts ?? null, input.payload === undefined ? null : JSON.stringify(input.payload)],\n );\n const id = Number(rows[0]!.id);\n if (this.eventCap > 0) {\n // Keep only the newest `eventCap` rows by id, matching the in-memory ring.\n await this.query(`DELETE FROM events WHERE id <= $1`, [id - this.eventCap]);\n }\n return {\n id,\n boxId: input.boxId,\n type: input.type,\n ts: input.ts,\n payload: input.payload,\n receivedAt: new Date(rows[0]!.received_at).toISOString(),\n };\n }\n\n async listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n const rows =\n boxId !== undefined\n ? await this.query<EventRow>(\n `SELECT id, box_id, type, ts, payload, received_at FROM events\n WHERE id > $1 AND box_id = $2 ORDER BY id`,\n [since, boxId],\n )\n : await this.query<EventRow>(\n `SELECT id, box_id, type, ts, payload, received_at FROM events\n WHERE id > $1 ORDER BY id`,\n [since],\n );\n return rows.map(rowToEvent);\n }\n\n async countEvents(): Promise<number> {\n const rows = await this.query<{ n: string }>(`SELECT count(*)::text AS n FROM events`);\n return Number.parseInt(rows[0]?.n ?? '0', 10);\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n await this.query(\n `INSERT INTO box_status (box_id, name, project_index, status, updated_at)\n VALUES ($1, $2, $3, $4, now())\n ON CONFLICT (box_id) DO UPDATE\n SET name = EXCLUDED.name, project_index = EXCLUDED.project_index,\n status = EXCLUDED.status, updated_at = now()`,\n [boxId, name, projectIndex ?? null, JSON.stringify(status)],\n );\n }\n\n async getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n const rows = await this.query<{ status: BoxStatusSnapshot }>(\n `SELECT status FROM box_status WHERE box_id = $1`,\n [boxId],\n );\n return rows[0]?.status;\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n await this.query(`DELETE FROM box_status WHERE box_id = $1`, [boxId]);\n }\n\n /**\n * All box status snapshots in one query (avoids N+1 over listBoxes +\n * per-box getStatus). Used by the hosted hub UI to render every box's live\n * status. Not on the Store interface — only the hosted Postgres path needs it.\n */\n async listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n const rows = await this.query<{ box_id: string; status: BoxStatusSnapshot }>(\n `SELECT box_id, status FROM box_status`,\n );\n return rows.map((r) => ({ boxId: r.box_id, status: r.status }));\n }\n\n // --- prompt mailbox ---\n\n async createPrompt(row: PromptRow): Promise<void> {\n await this.query(\n `INSERT INTO prompts (id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ON CONFLICT (id) DO NOTHING`,\n [\n row.id,\n row.boxId,\n JSON.stringify(row.ev),\n row.method,\n row.params === undefined ? null : JSON.stringify(row.params),\n row.status,\n row.answer ?? null,\n row.cancelled ?? null,\n row.result === undefined ? null : JSON.stringify(row.result),\n row.createdAt,\n row.expiresAt ?? null,\n ],\n );\n }\n\n async getPrompt(promptId: string): Promise<PromptRow | null> {\n const rows = await this.query<PromptDbRow>(\n `SELECT id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at\n FROM prompts WHERE id = $1`,\n [promptId],\n );\n return rows[0] ? rowToPrompt(rows[0]) : null;\n }\n\n async answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const rows = await this.query<{ id: string }>(\n `UPDATE prompts SET status = 'answered', answer = $2, cancelled = $3\n WHERE id = $1 AND status = 'pending' RETURNING id`,\n [promptId, answer, cancelled ?? null],\n );\n return rows.length > 0;\n }\n\n async listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const rows = await this.query<PromptDbRow>(\n `SELECT id, box_id, ev, method, params, status, answer, cancelled, result, created_at, expires_at\n FROM prompts WHERE box_id = $1 AND status = 'pending' ORDER BY created_at`,\n [boxId],\n );\n return rows.map(rowToPrompt);\n }\n\n async setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n await this.query(`UPDATE prompts SET result = $2 WHERE id = $1`, [\n promptId,\n JSON.stringify(result),\n ]);\n }\n\n // --- box-create job queue ---\n\n async enqueueCreateJob(job: CreateJobRow): Promise<void> {\n await this.query(\n `INSERT INTO create_jobs (id, status, request, result, claimed_by, created_at, started_at, finished_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (id) DO NOTHING`,\n [\n job.id,\n job.status,\n JSON.stringify(job.request),\n job.result ? JSON.stringify(job.result) : null,\n job.claimedBy ?? null,\n job.createdAt,\n job.startedAt ?? null,\n job.finishedAt ?? null,\n ],\n );\n }\n\n async getCreateJob(id: string): Promise<CreateJobRow | null> {\n const rows = await this.query<CreateJobDbRow>(\n `SELECT id, status, request, result, claimed_by, created_at, started_at, finished_at\n FROM create_jobs WHERE id = $1`,\n [id],\n );\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n // Atomic claim: lock the oldest queued row, skip ones a sibling worker holds.\n const rows = await this.query<CreateJobDbRow>(\n `UPDATE create_jobs SET status = 'running', claimed_by = $1, started_at = now()\n WHERE id = (\n SELECT id FROM create_jobs WHERE status = 'queued'\n ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1\n )\n RETURNING id, status, request, result, claimed_by, created_at, started_at, finished_at`,\n [workerId],\n );\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n await this.query(\n `UPDATE create_jobs SET status = $2, result = $3, finished_at = now() WHERE id = $1`,\n [id, status, JSON.stringify(result)],\n );\n }\n}\n\ninterface CreateJobDbRow {\n id: string;\n status: CreateJobRow['status'];\n request: CreateJobRow['request'];\n result: CreateJobRow['result'] | null;\n claimed_by: string | null;\n created_at: Date;\n started_at: Date | null;\n finished_at: Date | null;\n}\n\nfunction rowToJob(r: CreateJobDbRow): CreateJobRow {\n return {\n id: r.id,\n status: r.status,\n request: r.request,\n result: r.result ?? undefined,\n claimedBy: r.claimed_by ?? undefined,\n createdAt: new Date(r.created_at).toISOString(),\n startedAt: r.started_at ? new Date(r.started_at).toISOString() : undefined,\n finishedAt: r.finished_at ? new Date(r.finished_at).toISOString() : undefined,\n };\n}\n\ninterface PromptDbRow {\n id: string;\n box_id: string;\n ev: PromptRow['ev'];\n method: string;\n params: unknown;\n status: 'pending' | 'answered';\n answer: 'y' | 'n' | null;\n cancelled: boolean | null;\n result: GitRpcResult | null;\n created_at: Date;\n expires_at: Date | null;\n}\n\nfunction rowToPrompt(r: PromptDbRow): PromptRow {\n return {\n id: r.id,\n boxId: r.box_id,\n ev: r.ev,\n method: r.method,\n params: r.params ?? undefined,\n status: r.status,\n answer: r.answer ?? undefined,\n cancelled: r.cancelled ?? undefined,\n result: r.result ?? undefined,\n createdAt: new Date(r.created_at).toISOString(),\n expiresAt: r.expires_at ? new Date(r.expires_at).toISOString() : undefined,\n };\n}\n\ninterface EventRow {\n id: string;\n box_id: string;\n type: string;\n ts: string | null;\n payload: unknown;\n received_at: Date;\n}\n\nfunction rowToEvent(r: EventRow): RelayEvent {\n return {\n id: Number(r.id),\n boxId: r.box_id,\n type: r.type,\n ts: r.ts ?? undefined,\n payload: r.payload ?? undefined,\n receivedAt: new Date(r.received_at).toISOString(),\n };\n}\n","import { spawn } from 'node:child_process';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport {\n boxCarriedHostPaths,\n boxWorkspacePath,\n executeCloudAction,\n refreshCloudPreviewUrl,\n resolveHostPath,\n} from './host-actions.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { HostActionQueue } from './host-action-queue.js';\nimport { HubNotifier } from './hub-notifier.js';\nimport { BoxNotices } from './notices.js';\nimport { hostOpenCommand } from '@agentbox/sandbox-core';\nimport {\n isSanctionedPushBranch,\n isScratchBranch,\n landRefspec,\n parseDownloadKind,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport { getConnector } from '@agentbox/integrations';\nimport {\n assertGhReady,\n checkoutGuards,\n GH_API_ENDPOINT_REFUSAL,\n GH_PR_READ_ONLY_OPS,\n GH_PR_SAFE_AUTO_APPROVE_OPS,\n GH_RUN_READ_ONLY_OPS,\n injectPrCreateHead,\n isAllowedGhApiEndpoint,\n refuseGhApiCall,\n isGhPrOp,\n isGhRunOp,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateHasExplicitHead,\n prCreateNeedsHead,\n refuseCheckoutByDefault,\n refuseMergeBypass,\n runHostGh,\n type GhApiRpcParams,\n type GhPrOp,\n type GhPrRpcParams,\n type GhRunOp,\n type GhRunRpcParams,\n} from './gh.js';\nimport { hashRpcParams, HostInitiatedTokens } from './host-initiated.js';\nimport {\n assertIntegrationReady,\n makeIntegrationOpRefusal,\n parseIntegrationMethod,\n refuseIfIntegrationDisabled,\n refuseIntegrationCall,\n runHostIntegration,\n type IntegrationRpcParams,\n} from './integrations.js';\nimport { GitHubAppLeaser, loadGitHubAppConfig, type GitHubAppConfig } from './github-app.js';\nimport { leaseTokenResult } from './lease.js';\nimport { gateApproval, type GateDeps, type PromptMode } from './permission.js';\nimport { resolveWorktree } from './worktree.js';\nimport { askPrompt, isPromptAnswerBody, PendingPrompts, PromptSubscribers } from './prompts.js';\nimport { BoxRegistry, EventBuffer } from './registry.js';\nimport { CREDENTIALS_UPDATED_EVENT, CredentialsFanout } from './credentials-fanout.js';\nimport { BoxStatusStore, isValidBoxStatus } from './status-store.js';\nimport { MemoryStore } from './store/memory-store.js';\nimport type { Store } from './store/store.js';\nimport { DEFAULT_BOX_RELAY_PORT } from './types.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams } from './cp-rpc.js';\nimport type {\n BoxRegistration,\n BoxWorktree,\n BridgeActionResultBody,\n BridgePollResponse,\n BrowserOpenRpcParams,\n CheckpointRpcParams,\n ClearNoticeBody,\n CpRpcParams,\n DownloadKind,\n DownloadRpcParams,\n GitRpcParams,\n GitRpcResult,\n HostAction,\n PostEventBody,\n PostRpcBody,\n PromptAnswerBody,\n RegisterBoxBody,\n RelayEvent,\n SetNoticeBody,\n} from './types.js';\n\nexport type RelayMode = 'host' | 'box';\n\nexport interface RelayServerOptions {\n port: number;\n /** Bind address; defaults to '0.0.0.0' so containers can reach the relay across the local docker network OR the Daytona preview proxy can hit the in-sandbox box-mode relay. */\n host?: string;\n logger?: (line: string) => void;\n /**\n * 'host' (default): host relay process; executes host-only RPCs locally\n * via `spawn` and serves `/admin/*` to the CLI / wrapper.\n * 'box': in-sandbox relay; host-only RPCs enqueue on a `HostActionQueue`\n * for the host poller to drain via `/bridge/*`.\n */\n mode?: RelayMode;\n /**\n * Required when `mode === 'box'`: bearer for the box-only `/bridge/*`\n * routes. Distinct from per-box `BoxRegistration.token` so a compromised\n * in-box agent cannot impersonate the host poller.\n */\n bridgeToken?: string;\n /**\n * Persisted-state backend. Defaults to an in-memory store wrapping the\n * relay's historical in-memory structures (the laptop relay + tests). A\n * hosted control plane injects a Postgres-backed store; a federated laptop\n * relay injects a RemoteStore. See `./store/store.ts`.\n */\n store?: Store;\n /**\n * How host-action approvals are obtained. Defaults to 'block' (the\n * long-lived laptop relay blocks on a human). The stateless hosted plane\n * uses 'poll' via its own handler, not this server. See `./permission.ts`.\n */\n promptMode?: PromptMode;\n /**\n * GitHub App config for `git.lease-token` (the hosted plane mints repo-scoped\n * installation tokens and leases them to boxes). Defaults to\n * {@link loadGitHubAppConfig} (`GITHUB_APP_ID` + `GITHUB_APP_PRIVATE_KEY`).\n * Null/absent → `git.lease-token` returns a clear \"not configured\" error.\n */\n githubApp?: GitHubAppConfig | null;\n /**\n * Optional delegate for requests that matched no relay route (e.g. Next's\n * `getRequestHandler()`). Invoked at the top-level 404 fallthrough, so every\n * relay route still matches first and the UI can never shadow `/admin`,\n * `/rpc`, etc. Lets the hub serve Next on the relay's own port.\n */\n uiHandler?: (req: IncomingMessage, res: ServerResponse) => void;\n}\n\nexport interface RelayServerHandle {\n server: Server;\n /** The persisted-state backend the handlers use (memory by default). */\n store: Store;\n registry: BoxRegistry;\n events: EventBuffer;\n statusStore: BoxStatusStore;\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n notices: BoxNotices;\n /** Fan-out for the embedded hub UI's SSE route (pending-approval changes). */\n hubNotifier: HubNotifier;\n /** Present only in `mode === 'box'`: the parking lot for host-only RPCs. */\n hostActions?: HostActionQueue;\n url: string;\n /**\n * Wire a \"kick the queue scheduler now\" callback. Called by\n * `POST /admin/queue/enqueue` so a freshly-submitted background job doesn't\n * wait up to one tick for the relay to notice the new manifest.\n * No-op until set; the queue still picks the job up via the periodic tick.\n */\n setQueuePoke: (fn: () => void) => void;\n /**\n * Kick the queue scheduler in-process (same effect as `POST\n * /admin/queue/enqueue`, without a loopback round-trip). Used by the embedded\n * hub after it enqueues a create job via `enqueueQueueJob`. No-op until\n * `setQueuePoke` has wired the scheduler.\n */\n pokeQueue: () => void;\n close: () => Promise<void>;\n}\n\n/** Event type whose payload is a durable BoxStatus snapshot (persisted, not ringed). */\nconst BOX_STATUS_EVENT = 'box-status';\n\nconst MAX_BODY_BYTES = 1024 * 1024; // 1 MiB hard cap; relay is for control-plane traffic, not payloads.\nconst GIT_RPC_TIMEOUT_MS = 120_000; // git push/pull can be slow on big repos.\nconst CHECKPOINT_RPC_TIMEOUT_MS = 600_000; // capturing node_modules/build trees can be slow.\nconst DOWNLOAD_RPC_TIMEOUT_MS = 600_000; // claude/workspace pulls over rsync can take minutes.\nconst CP_RPC_TIMEOUT_MS = 300_000; // single-file/dir cp; tar pipe through docker exec.\nconst BROWSER_OPEN_RPC_TIMEOUT_MS = 15_000; // `open` hands off to the browser and returns at once.\nconst BROWSER_OPEN_PROMPT_TTL_MS = 25_000; // the \"open on host too?\" offer auto-dismisses if ignored.\nconst SSE_HEARTBEAT_MS = 15_000; // every 15s; wrapper reconnects if it sees no traffic for ~30s.\n\nfunction send(\n res: ServerResponse,\n status: number,\n body: unknown,\n contentType: string = 'application/json',\n): void {\n const text = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);\n res.statusCode = status;\n if (text.length > 0) {\n res.setHeader('Content-Type', contentType);\n res.setHeader('Content-Length', Buffer.byteLength(text).toString());\n res.end(text);\n } else {\n res.end();\n }\n}\n\nasync function readJsonBody<T>(req: IncomingMessage): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > MAX_BODY_BYTES) {\n reject(new Error('request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n if (text.length === 0) {\n resolve({} as T);\n return;\n }\n try {\n resolve(JSON.parse(text) as T);\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n req.on('error', reject);\n });\n}\n\nfunction bearerToken(req: IncomingMessage): string {\n const raw = req.headers.authorization;\n if (typeof raw !== 'string') return '';\n const m = /^Bearer\\s+(.+)$/i.exec(raw.trim());\n return m ? m[1]!.trim() : '';\n}\n\nfunction isLoopbackAddress(addr: string | undefined): boolean {\n if (!addr) return false;\n return (\n addr === '127.0.0.1' ||\n addr === '::1' ||\n addr === '::ffff:127.0.0.1' ||\n addr.startsWith('127.')\n );\n}\n\n/**\n * Build the relay HTTP server. Routes:\n * POST /events — bearer auth (box token), appends to ring buffer.\n * POST /rpc — bearer auth; dispatches git.push/fetch, cp.*, download.*, checkpoint.create on the host.\n * POST /admin/register-box — loopback only.\n * POST /admin/forget-box — loopback only.\n * GET /admin/box-status — loopback only; query `box`; latest snapshot.\n * GET /admin/events — loopback only; query `box`, `since`.\n * GET /admin/registry — loopback only; list registered boxes (token redacted).\n * GET /admin/prompts — loopback only; query `boxId`; one-shot list of pending host-action approvals.\n * GET /admin/prompts/stream — loopback only; SSE; pushes prompt-ask/prompt-resolved/notice-set/notice-clear/ping events.\n * POST /admin/prompts/answer — loopback only; resolves a pending prompt by id.\n * POST /admin/host-initiated/mint — loopback only; mints a one-time token scoped to (boxId, method).\n * POST /admin/notices/set — loopback only; sets an informational box notice (returns {id}).\n * POST /admin/notices/clear — loopback only; clears a box notice by id.\n * GET /healthz — liveness + capability probe (no auth); reports {pid, cliEntry}.\n */\nexport function createRelayServer(opts: RelayServerOptions): RelayServerHandle {\n const log = opts.logger ?? (() => {});\n const registry = new BoxRegistry();\n const events = new EventBuffer();\n const statusStore = new BoxStatusStore();\n const prompts = new PendingPrompts();\n const subscribers = new PromptSubscribers();\n const notices = new BoxNotices(subscribers);\n // Fan-out for the embedded hub UI: every change to the pending-approval set\n // pushes a refresh to browsers subscribed on the hub's SSE route. No-op when\n // no hub is attached (the CLI relay bin never subscribes).\n const hubNotifier = new HubNotifier();\n prompts.setOnChange(() => hubNotifier.notify());\n // The persisted-state seam. Defaults to a MemoryStore wrapping the concrete\n // instances above, so the laptop relay + tests behave exactly as before; a\n // hosted control plane injects a Postgres-backed store instead. Handlers go\n // through `store.*`; the concrete instances stay exposed on the handle for\n // the autopause / queue loops (bin.ts) and the unit tests that read them.\n const store: Store = opts.store ?? new MemoryStore({ registry, events, statusStore });\n // Per-box `box.autoApproveHostActions`: when a box registered with the flag,\n // host-action confirms resolve to 'y' without a prompt, but every bypass\n // lands in the event ring buffer (visible via `/admin/events`) so it's\n // auditable. Reads the concrete registry/events synchronously (not the async\n // store): `askPrompt` broadcasts to SSE subscribers synchronously, so this\n // gate must stay sync. The MemoryStore wraps these same instances, so the\n // sync policy view and the async store view never diverge on the laptop relay.\n prompts.setAutoApprovePolicy({\n shouldAutoApprove: (boxId) => registry.get(boxId)?.autoApproveHostActions === true,\n audit: (boxId, params, reason) => {\n events.append({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: params.context?.command,\n argv: params.context?.argv,\n message: params.message,\n ...(reason ? { reason } : {}),\n },\n });\n log(\n `auto-approved host action for ${boxId}: ${params.context?.command ?? params.message}` +\n (reason ? ` (${reason})` : ''),\n );\n },\n });\n const hostInitiatedTokens = new HostInitiatedTokens();\n let queuePoke: (() => void) | null = null;\n const host = opts.host ?? '0.0.0.0';\n const mode: RelayMode = opts.mode ?? 'host';\n // Box mode parks host-only RPCs until the host poller answers; host mode\n // executes them inline (the historical behavior).\n const hostActions = mode === 'box' ? new HostActionQueue() : null;\n // Host-mode handler for refreshed agent credentials (newest-wins backup\n // write + debounced `agentbox credentials propagate` spawn). In box mode the\n // event rides the local ring buffer to the bridge instead — the host's\n // poller hands it to this handler on the other side.\n const credentialsFanout = mode === 'box' ? null : new CredentialsFanout({ log });\n if (mode === 'box' && (!opts.bridgeToken || opts.bridgeToken.length === 0)) {\n throw new Error(\"relay mode='box' requires a non-empty bridgeToken\");\n }\n const bridgeToken = opts.bridgeToken ?? '';\n // The laptop relay blocks on a human for approvals (today's behavior). The\n // stateless hosted plane uses 'poll' via its own handler, not this server.\n const promptMode: PromptMode = opts.promptMode ?? 'block';\n const gateDeps: GateDeps = { mode: promptMode, store, prompts, subscribers };\n // GitHub App leaser for `git.lease-token` (hosted plane). Off when no App is\n // configured — the laptop relay never needs it (it pushes host-side / cloud\n // boxes reach it via the poller).\n const githubAppConfig = opts.githubApp === undefined ? loadGitHubAppConfig() : opts.githubApp;\n const leaser = githubAppConfig ? new GitHubAppLeaser(githubAppConfig) : null;\n const uiHandler = opts.uiHandler;\n\n // Host-mode pollers for cloud-tagged boxes; started on /admin/register-box,\n // stopped on /admin/forget-box. Lazy import to keep host-mode startup free\n // of cloud-poller deps until actually needed.\n type CloudPollersModule = typeof import('./cloud-poller.js');\n let pollers: InstanceType<CloudPollersModule['CloudBoxPollers']> | null = null;\n async function getPollers(): Promise<InstanceType<CloudPollersModule['CloudBoxPollers']>> {\n if (!pollers) {\n const mod: CloudPollersModule = await import('./cloud-poller.js');\n pollers = new mod.CloudBoxPollers();\n }\n return pollers;\n }\n\n const server = createServer((req, res) => {\n handle(req, res).catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err);\n log(`relay: handler error: ${msg}`);\n if (!res.headersSent) send(res, 500, { error: 'internal error' });\n else res.end();\n });\n });\n\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'relay'}`);\n const route = `${req.method ?? 'GET'} ${url.pathname}`;\n\n if (route === 'GET /healthz') {\n // `cliEntry` and `pid` let the host-side `ensureRelay` distinguish a\n // *capable* relay from one that's merely alive: a relay spawned without\n // AGENTBOX_CLI_ENTRY silently fails every cp/download/checkpoint host\n // action (exit 64) for its whole lifetime. Reporting it here lets the\n // caller reclaim (kill by `pid`) and respawn instead of reusing it.\n send(res, 200, {\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n pid: process.pid,\n // True when a Next UI is delegated here (the embedded hub) vs a bare relay.\n // Lets `agentbox hub` distinguish \"a hub already runs\" from \"a lean relay\n // holds the port\" (reclaim + respawn as the hub).\n ui: Boolean(uiHandler),\n cliEntry: Boolean(process.env.AGENTBOX_CLI_ENTRY),\n // The spawning CLI's version/commit (inherited via env at spawn time).\n // `version` lets host-side ensureRelay reclaim a relay left over from a\n // different agentbox version; `commit` is observability-only.\n version: process.env.AGENTBOX_CLI_VERSION || undefined,\n commit: process.env.AGENTBOX_CLI_COMMIT || undefined,\n });\n return;\n }\n\n // Bridge routes are the host poller's view into an in-sandbox box-mode\n // relay. They are bearer-authed with the per-relay bridgeToken and\n // exist only when mode === 'box'. No loopback check: the Daytona\n // preview proxy reaches them from non-loopback IPs.\n if (url.pathname.startsWith('/bridge/')) {\n if (mode !== 'box' || !hostActions) {\n send(res, 404, { error: 'bridge routes available only in mode=box' });\n return;\n }\n if (bearerToken(req) !== bridgeToken) {\n send(res, 401, { error: 'invalid bridge token' });\n return;\n }\n if (route === 'GET /bridge/healthz') {\n send(res, 200, { ok: true, queued: hostActions.size(), events: events.size() });\n return;\n }\n if (route === 'GET /bridge/poll') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const newEvents = await store.listEvents(since);\n const lastId = newEvents.length > 0 ? newEvents[newEvents.length - 1]!.id : since;\n const actions = hostActions.drain();\n // A box-mode relay only ever has one registered box (itself). The\n // status snapshot — if any has been pushed — belongs to that box.\n const only = (await store.listBoxes())[0];\n const status = only ? (await store.getStatus(only.boxId)) ?? null : null;\n const reply: BridgePollResponse = {\n actions,\n events: newEvents,\n status,\n cursor: lastId,\n };\n send(res, 200, reply);\n return;\n }\n if (route === 'POST /bridge/action-result') {\n const body = await readJsonBody<BridgeActionResultBody>(req);\n if (\n !body ||\n typeof body.id !== 'string' ||\n body.id.length === 0 ||\n typeof body.exitCode !== 'number'\n ) {\n send(res, 400, { error: 'expected {id, exitCode, stdout, stderr}' });\n return;\n }\n const ok = hostActions.resolve(body.id, {\n exitCode: body.exitCode,\n stdout: typeof body.stdout === 'string' ? body.stdout : '',\n stderr: typeof body.stderr === 'string' ? body.stderr : '',\n });\n if (!ok) {\n send(res, 404, { error: 'no parked action with that id' });\n return;\n }\n send(res, 204, null);\n return;\n }\n send(res, 404, { error: 'not found', route });\n return;\n }\n\n // Admin endpoints are reachable from loopback only. The relay binds to\n // 0.0.0.0 so containers can reach /events and /rpc via host.docker.internal,\n // but admin operations (register-box, forget-box, list events, etc.) are\n // for the host CLI and must not be exposed to boxes. `/remote/*` is a\n // hosted-control-plane surface (box creation) served by the Next.js app's\n // handler, not the laptop relay — so it does not exist here.\n if (url.pathname.startsWith('/admin/') || url.pathname.startsWith('/remote/')) {\n if (url.pathname.startsWith('/remote/')) {\n send(res, 404, { error: 'not found', route });\n return;\n }\n if (!isLoopbackAddress(req.socket.remoteAddress)) {\n send(res, 403, { error: 'admin endpoints are loopback-only' });\n return;\n }\n }\n\n if (route === 'POST /events') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostEventBody>(req);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n send(res, 400, { error: 'missing \"type\" string' });\n return;\n }\n // box-status is durable state, not an event: persist the latest snapshot\n // per box and skip the ring buffer (a 15s heartbeat per box would\n // otherwise evict the useful git/service events from the 1000-cap ring).\n if (body.type === BOX_STATUS_EVENT) {\n if (!isValidBoxStatus(body.payload)) {\n send(res, 400, { error: 'invalid box-status payload' });\n return;\n }\n await store.setStatus(reg.boxId, reg.name, reg.projectIndex, body.payload);\n log(`box-status box=${reg.boxId}`);\n send(res, 202, { ok: true });\n return;\n }\n // Refreshed agent credentials: handled out-of-band in host mode — the\n // payload is a secret and must never land in the event ring buffer. In\n // box mode it falls through to the ring so the bridge drains it to the\n // host poller (which routes it to the host relay's handler).\n if (body.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, body.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n send(res, 202, { ok: true, accepted: verdict.accepted });\n return;\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n log(`event ${String(ev.id)} box=${reg.boxId} type=${body.type}`);\n send(res, 202, { id: ev.id });\n return;\n }\n\n if (route === 'POST /rpc') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostRpcBody>(req);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n send(res, 400, { error: 'missing \"method\" string' });\n return;\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n // Box-mode: every host-only RPC (anything except the in-sandbox-local\n // `browser.open` notification) is parked on the HostActionQueue. The\n // host's CloudBoxPoller drains via `/bridge/poll`, executes on the\n // host (with the existing `askPrompt` gate for `git.push`), and POSTs\n // the result back to `/bridge/action-result`, which resolves the\n // awaited Promise here and unblocks the in-box `/rpc` caller.\n if (mode === 'box' && hostActions && body.method !== 'browser.open') {\n const queued = await hostActions.enqueue(reg.boxId, body.method, body.params);\n const status = queued.exitCode === 0 ? 200 : 500;\n send(res, status, queued);\n return;\n }\n if (body.method === 'git.push' || body.method === 'git.fetch') {\n // Cloud box reaching this host-mode relay directly over the forwarder\n // (rather than via the poller): run the cloud bundle pull-back executor,\n // which does its own gating and pushes via the host workspace.\n if (reg.kind === 'cloud') {\n const action: HostAction = {\n id: '',\n boxId: reg.boxId,\n method: body.method,\n params: body.params,\n createdAt: new Date().toISOString(),\n };\n const result = await executeCloudAction(action, {\n backendName: reg.backend ?? '',\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n log,\n });\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n // Only `push` mutates the user's remote; fetch is read-only and noisy.\n // Per-box `agentbox/<name>` branches are the box's own scratch branch\n // — pushes to them are the whole point of agentbox, so they bypass\n // the y/N gate. Any other branch still prompts.\n if (body.method === 'git.push') {\n const hostOnlyParams = body.params as GitRpcParams | undefined;\n if (hostOnlyParams?.hostOnly) {\n // Landing the branch in the host's local repo publishes nothing,\n // so the push-confirm gate doesn't apply. Land and return.\n const saveResult = await handleGitSaveToHost(reg, hostOnlyParams);\n send(res, saveResult.exitCode === 0 ? 200 : 500, saveResult);\n return;\n }\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n // The docker relay always pushes the worktree's host-selected branch\n // (`sanctionedBranch`, falling back to the create-time `branch`) — the\n // in-box agent can't influence which branch is pushed. Key the gate on\n // THAT branch, not the immutable create-time `branch` (which is always\n // `agentbox/*`): after a host `agentbox git checkout main`, the push\n // target is `main`, so it must NOT be treated as a scratch bypass.\n // A scratch target bypasses unconditionally; a non-scratch sanctioned\n // target bypasses only as part of the safe subset (honors\n // `box.autoApproveSafeHostActions`) and leaves an audit trail.\n const dockerPushBranch = worktree?.sanctionedBranch ?? worktree?.branch;\n const isScratch = isScratchBranch(dockerPushBranch);\n const safeApproveOn = reg.autoApproveSafeHostActions !== false;\n // `isSanctionedPushBranch(dockerPushBranch, dockerPushBranch)` is true\n // only for a resolved branch — so a box with no registered worktree\n // (undefined branch) never bypasses and still prompts.\n const isSanctionedNonScratch =\n !isScratch &&\n safeApproveOn &&\n isSanctionedPushBranch(dockerPushBranch, dockerPushBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (isSanctionedNonScratch) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${dockerPushBranch ?? ''} from box ${reg.name}`,\n context: { command: 'git push', cwd: params?.path, argv: params?.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip\n // the confirm prompt — but only if the host CLI minted a valid,\n // unexpired, scope-matched, params-hash-bound token via\n // /admin/host-initiated/mint. If a token is *present* but doesn't\n // validate (wrong scope, mutated params, expired, replayed), reject\n // hard: that's an attack signal (the only way to get a token is to\n // mint one host-side, and a legitimate host call always sends what\n // it minted for). Fall through to the prompt only when no token was\n // claimed — that's the normal agent-initiated path.\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, 'git.push', incomingHash);\n if (!bypassPushGate && tokenClaimed && !hostInitiatedOk) {\n send(res, 500, {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n });\n return;\n }\n if (!bypassPushGate && !hostInitiatedOk) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.push', body.params, {\n kind: 'confirm',\n message: `Allow git push from box ${reg.name}?`,\n detail: `${resolveRemote(params?.remote)} ${(params?.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: {\n command: 'git push',\n cwd: params?.path,\n argv: params?.args,\n },\n });\n // Poll mode: parked — the box polls /rpc/status/<promptId> for the\n // verdict + result (the push runs there, on approval).\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n }\n const result = await handleGitRpc(reg, body.method, body.params as GitRpcParams | undefined);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.lease-token') {\n // The hosted-plane equivalent of git.push: instead of the relay pushing,\n // it leases a repo-scoped GitHub-App token and the box pushes directly.\n // Because that token can push ANY branch (the relay doesn't pick the\n // branch here, unlike git.push), the sanctioned-branch auto-approve does\n // NOT apply — only the box's own scratch branch bypasses; others prompt.\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.lease-token', body.params, {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: params?.path },\n });\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await leaseTokenResult(leaser, reg);\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n if (body.method === 'cp.toHost' || body.method === 'cp.fromHost') {\n const params = body.params as CpRpcParams | undefined;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(body.method, params);\n } catch (err) {\n send(res, 400, { error: err instanceof Error ? err.message : String(err) });\n return;\n }\n if (\n params!.exclude !== undefined &&\n (!Array.isArray(params!.exclude) || params!.exclude.some((p) => typeof p !== 'string'))\n ) {\n send(res, 400, { error: 'cp.* exclude must be an array of strings' });\n return;\n }\n const direction = body.method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path\n // doesn't land under the relay daemon's CWD (whichever project started\n // the relay), and so the consent prompt shows the real destination.\n const workspacePath = await boxWorkspacePath(reg.boxId);\n const { argv: cpArgs, detail, contextArgv } = buildCpArgv({\n method: body.method,\n boxName: reg.name,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(workspacePath, p),\n flags: cpFlags(params!),\n });\n const detailParts = [detail];\n if (params!.exclude && params!.exclude.length > 0) {\n detailParts.push(`exclude: ${params!.exclude.join(', ')}`);\n }\n if (params!.defaultExcludes === false) detailParts.push('(default excludes off)');\n if (params!.yes) detailParts.push('(over size limit — confirmed)');\n // Auto-approve a transfer that stays inside the box's project folder\n // (box->host: check the dest; host->box: check the sources, keeping\n // secret files behind the prompt). Anything else prompts as before.\n const cpHostPaths =\n body.method === 'cp.toHost'\n ? [resolveHostPath(workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: body.method === 'cp.fromHost',\n carried:\n body.method === 'cp.fromHost' ? await boxCarriedHostPaths(reg.boxId) : undefined,\n });\n if (cpAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `cp (${direction}) on ${reg.name}`,\n detail: detailParts.join('\\n'),\n context: { command: body.method, argv: contextArgv },\n },\n body.method === 'cp.toHost' ? 'safe: contained copy to host' : 'safe: contained copy from host',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${reg.name}?`,\n detail: detailParts.join('\\n'),\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: contextArgv,\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleCpRpc(cpArgs, workspacePath);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('gh.pr.')) {\n const op = body.method.slice('gh.pr.'.length);\n if (!isGhPrOp(op)) {\n send(res, 400, { error: `unknown gh.pr.* op: ${op}` });\n return;\n }\n const result = await handleGhPrRpc(\n op,\n reg,\n body.params as GhPrRpcParams | undefined,\n prompts,\n subscribers,\n hostInitiatedTokens,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('gh.run.')) {\n const op = body.method.slice('gh.run.'.length);\n if (!isGhRunOp(op)) {\n send(res, 400, { error: `unknown gh.run.* op: ${op}` });\n return;\n }\n const result = await handleGhRunRpc(\n op,\n reg,\n body.params as GhRunRpcParams | undefined,\n prompts,\n subscribers,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'gh.api') {\n const result = await handleGhApiRpc(reg, body.params as GhApiRpcParams | undefined);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('integration.')) {\n const result = await handleIntegrationRpc(\n body.method,\n reg,\n body.params as IntegrationRpcParams | undefined,\n prompts,\n subscribers,\n hostInitiatedTokens,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.clone' || body.method === 'gh.repo.clone') {\n // Clone bundle-ship-back machinery is deferred to a follow-up PR\n // (see docs/plans/gh-and-git-shims-host-only.md → Deferred follow-ups).\n // The shim + ctl plumbing is in place so the next iteration only has\n // to land the relay-side host clone + bundle + box transfer.\n send(res, 501, {\n exitCode: 64,\n stdout: '',\n stderr: `${body.method}: not yet implemented (deferred; see docs/plans/gh-and-git-shims-host-only.md). Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n });\n return;\n }\n if (\n body.method === 'download.workspace' ||\n body.method === 'download.env' ||\n body.method === 'download.config' ||\n body.method === 'download.claude'\n ) {\n const params = body.params as DownloadRpcParams | undefined;\n const kind = parseDownloadKind(body.method);\n // `download.workspace` lands under the box's project folder (contained by\n // construction), so it auto-approves under the safe flag. The env/config/\n // claude kinds land in ~/.agentbox / ~/.claude (outside the project) and\n // keep prompting.\n const dlWorkspace = await boxWorkspacePath(reg.boxId);\n const dlAuto =\n kind === 'workspace' &&\n (await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath: dlWorkspace,\n hostPaths: dlWorkspace ? [dlWorkspace] : [],\n checkSecret: false,\n }));\n if (dlAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${reg.name}`,\n detail: params?.hostPath ?? '(default host location)',\n context: { command: body.method, argv: params?.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${reg.name}?`,\n detail: params?.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: params?.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleDownloadRpc(reg, kind);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'checkpoint.create') {\n const result = await handleCheckpointRpc(\n reg,\n body.params as CheckpointRpcParams | undefined,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'browser.open') {\n const params = body.params as BrowserOpenRpcParams | undefined;\n const url = typeof params?.url === 'string' ? params.url.trim() : '';\n if (!isOpenableUrl(url)) {\n // The scheme guard keeps a box from handing the host's `open` a\n // file path or app instead of a URL.\n send(res, 400, {\n exitCode: 64,\n stdout: '',\n stderr: 'browser.open: only http/https URLs are allowed\\n',\n });\n return;\n }\n // The box already opened the link in its own browser; this RPC is\n // just a notification. Record the event and answer at once — never\n // block the box on the host user's decision.\n await store.appendEvent({ boxId: reg.boxId, type: 'browser-open', payload: { url } });\n send(res, 200, { exitCode: 0, stdout: '', stderr: '' });\n // Offer to mirror the link to the host browser: a non-blocking,\n // auto-expiring confirm prompt in the footer/dashboard. Skipped under\n // AGENTBOX_PROMPT=off so a headless box can't spray the host with\n // browser tabs via askPrompt's auto-'y'.\n if (process.env.AGENTBOX_PROMPT !== 'off') {\n if (mode === 'box' && hostActions) {\n // Cloud: the in-sandbox relay has no SSE subscribers (the host\n // wrapper attaches to the host relay, not the in-sandbox one).\n // Queue a `browser.open.mirror` host action — the host poller\n // drains it, executes the prompt + open against host\n // subscribers, and resolves the parked entry. We don't await;\n // the host's verdict isn't reported back to the in-box agent\n // and `HostActionQueue.maxAgeMs` GCs the entry if it lingers.\n void hostActions.enqueue(reg.boxId, 'browser.open.mirror', { url });\n } else {\n void askPrompt(\n prompts,\n subscribers,\n reg.boxId,\n {\n kind: 'confirm',\n message: `Open link from box ${reg.name} on the host?`,\n detail: url,\n defaultAnswer: 'n',\n context: { command: 'browser.open', argv: [url] },\n },\n { ttlMs: BROWSER_OPEN_PROMPT_TTL_MS },\n )\n .then((verdict) => {\n if (verdict.answer === 'y' && !verdict.cancelled) {\n void runHostCommand([hostOpenCommand(), url], BROWSER_OPEN_RPC_TIMEOUT_MS);\n }\n })\n .catch(() => {\n /* best-effort */\n });\n }\n }\n return;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: 'rpc-unknown',\n payload: { method: body.method },\n });\n send(res, 501, { error: 'rpc method not implemented', method: body.method });\n return;\n }\n\n // Poll-mode verdict + result for a parked approval (see ./permission.ts).\n // The box polls this after a `/rpc` returned `202 {promptId}`:\n // - pending → keep polling\n // - denied/cancelled → exit 10\n // - approved → run the action once, cache the result, return it\n if (req.method === 'GET' && url.pathname.startsWith('/rpc/status/')) {\n const reg = await authBox(req, res);\n if (!reg) return;\n const promptId = decodeURIComponent(url.pathname.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) {\n send(res, 404, { error: 'no such prompt', promptId });\n return;\n }\n if (row.status === 'pending') {\n send(res, 200, { status: 'pending' });\n return;\n }\n if (row.answer !== 'y' || row.cancelled) {\n send(res, 200, {\n status: 'done',\n result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' },\n });\n return;\n }\n // Approved. Idempotent: a cached result short-circuits re-polls; the box\n // polls sequentially so there is no concurrent first-execute race here.\n const cached = row.result;\n const result = cached ?? (await dispatchApprovedAction(reg, row.method, row.params));\n if (!cached) await store.setPromptResult(promptId, result);\n send(res, 200, { status: 'done', result });\n return;\n }\n\n if (route === 'POST /admin/register-box') {\n const body = await readJsonBody<RegisterBoxBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n typeof body.token !== 'string' ||\n typeof body.name !== 'string' ||\n body.boxId.length === 0 ||\n body.token.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, token, name}' });\n return;\n }\n const worktrees = sanitizeWorktrees(body.worktrees);\n // Only accept a finite positive integer; everything else (including the\n // common `undefined` from legacy boxes) drops to `undefined` and the\n // status-store falls back to the `<id>-<mnemonic>` segment shape.\n const projectIndex =\n typeof body.projectIndex === 'number' &&\n Number.isFinite(body.projectIndex) &&\n body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined;\n const kind = body.kind === 'cloud' ? 'cloud' : 'docker';\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind,\n backend:\n typeof body.backend === 'string' && body.backend.length > 0\n ? body.backend\n : undefined,\n registeredAt: new Date().toISOString(),\n containerName:\n typeof body.containerName === 'string' && body.containerName.length > 0\n ? body.containerName\n : undefined,\n createdAt:\n typeof body.createdAt === 'string' && body.createdAt.length > 0\n ? body.createdAt\n : undefined,\n projectIndex,\n worktrees,\n previewUrl:\n typeof body.previewUrl === 'string' && body.previewUrl.length > 0\n ? body.previewUrl\n : undefined,\n previewToken:\n typeof body.previewToken === 'string' && body.previewToken.length > 0\n ? body.previewToken\n : undefined,\n bridgeToken:\n typeof body.bridgeToken === 'string' && body.bridgeToken.length > 0\n ? body.bridgeToken\n : undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n // Default on: only an explicit `false` disables the safe subset, so an\n // older wire body without the field stays relaxed.\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl:\n typeof body.originUrl === 'string' && body.originUrl.length > 0\n ? body.originUrl\n : undefined,\n };\n await store.registerBox(reg);\n log(\n `registered ${kind} box ${reg.boxId} (${reg.name})` +\n (worktrees && worktrees.length > 0 ? ` with ${String(worktrees.length)} worktree(s)` : ''),\n );\n // Cloud boxes get a host-side poller so the host relay can mirror their\n // status into its BoxStatusStore (and, once the executor is wired,\n // drain queued host-only RPCs and post results back).\n if (kind === 'cloud' && reg.previewUrl && reg.bridgeToken) {\n try {\n const set = await getPollers();\n set.start(reg.boxId, {\n boxId: reg.boxId,\n previewUrl: reg.previewUrl,\n bridgeToken: reg.bridgeToken,\n previewToken: reg.previewToken,\n onEvents: async (evs) => {\n for (const ev of evs) {\n // Credential updates carry a secret blob — route to the\n // fan-out handler, never into the host event ring buffer.\n if (ev.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, ev.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n continue;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: ev.type,\n payload: ev.payload,\n ts: ev.ts,\n });\n }\n },\n onStatus: (status) => {\n if (isValidBoxStatus(status)) {\n void store.setStatus(reg.boxId, reg.name, reg.projectIndex, status);\n }\n },\n // Drained host-only RPCs (git.push, …) run on the host via the\n // executor and the result is POSTed back to /bridge/action-result.\n // No backend name → no executor; the poller's default respond\n // already returns a \"no executor\" error so the box unblocks.\n onAction: reg.backend\n ? async (action, respond) => {\n try {\n const result = await executeCloudAction(action, {\n backendName: reg.backend!,\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n log,\n });\n await respond(result);\n } catch (err) {\n await respond({\n exitCode: 1,\n stdout: '',\n stderr: `host executor failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n });\n }\n }\n : undefined,\n // Self-heal a dead preview transport (hetzner SSH `-L` after a\n // ControlMaster death). The relay strips the `cloud:` prefix\n // the cloud-provider tags onto BoxRecord.container — what the\n // backend's `get(sandboxId)` expects is the bare sandbox id.\n recoverPreviewUrl: reg.backend\n ? async () => refreshCloudPreviewUrl(reg.backend!, reg.boxId, DEFAULT_BOX_RELAY_PORT)\n : undefined,\n logger: log,\n });\n } catch (err) {\n log(\n `failed to start cloud poller for ${reg.boxId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/forget-box') {\n const body = await readJsonBody<{ boxId?: string }>(req);\n if (!body || typeof body.boxId !== 'string' || body.boxId.length === 0) {\n send(res, 400, { error: 'expected {boxId}' });\n return;\n }\n const existed = await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n if (pollers) await pollers.stop(body.boxId);\n log(`forgot box ${body.boxId} (existed=${String(existed)})`);\n send(res, 204, null);\n return;\n }\n\n if (route === 'GET /admin/box-status') {\n const box = url.searchParams.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n if (!status) {\n send(res, 404, { error: 'no status for box', box });\n return;\n }\n send(res, 200, status);\n return;\n }\n\n if (route === 'GET /admin/events') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const box = url.searchParams.get('box') ?? undefined;\n const list = await store.listEvents(since, box ?? undefined);\n send(res, 200, { events: list });\n return;\n }\n\n if (route === 'GET /admin/registry') {\n // Redact tokens; callers on the admin path don't need them and we don't\n // want them showing up in logs if someone curls this.\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n registeredAt: r.registeredAt,\n containerName: r.containerName,\n createdAt: r.createdAt,\n projectIndex: r.projectIndex,\n worktrees: r.worktrees ?? [],\n }));\n send(res, 200, { boxes: redacted });\n return;\n }\n\n if (route === 'GET /admin/prompts') {\n // One-shot snapshot of pending host-action approvals for a box. The SSE\n // `/stream` variant is for long-lived wrappers; this is for an\n // orchestrator (or `agentbox agent approvals`) that wants to inspect the\n // backlog, answer via /admin/prompts/answer, and move on without holding\n // a stream open. `boxId=` required, same as /stream.\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n // Poll mode parks prompts in the store; block mode keeps them in-process.\n const pending =\n promptMode === 'poll'\n ? (await store.listPendingPrompts(boxId)).map((r) => r.ev)\n : prompts.forBox(boxId);\n send(res, 200, { prompts: pending });\n return;\n }\n\n if (route === 'GET /admin/prompts/stream') {\n // Per-box SSE channel. The wrapper (apps/cli/src/wrapped-pty) subscribes\n // and stays connected; we push prompt-ask events on broadcast and a\n // periodic ping so the wrapper can detect a dead socket without traffic.\n // `boxId=` is required so a host with multiple boxes only sees its own\n // box's prompts (the wrapper attaches per-box anyway).\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n // Helps with proxies (e.g. nginx) that would otherwise buffer the\n // chunked response. The relay binds to loopback so this is belt-and-\n // suspenders, but the cost is one extra header.\n res.setHeader('X-Accel-Buffering', 'no');\n if (typeof res.flushHeaders === 'function') res.flushHeaders();\n res.write(': connected\\n\\n');\n subscribers.add(boxId, res);\n // Flush any prompts that arrived while no wrapper was attached — per\n // the design we block indefinitely on the in-box RPC, so a backlog can\n // build up between detach and reattach.\n for (const ev of prompts.forBox(boxId)) {\n res.write(`event: prompt-ask\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n // Then any active notices, so a wrapper attaching mid-checkpoint still\n // sees the in-progress warning (prompts first — they outrank notices).\n for (const ev of notices.forBox(boxId)) {\n res.write(`event: notice-set\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n const heartbeat = setInterval(() => {\n try {\n res.write(`event: ping\\ndata: {\"ts\":\"${new Date().toISOString()}\"}\\n\\n`);\n } catch {\n /* dead socket; close handler below removes */\n }\n }, SSE_HEARTBEAT_MS);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n res.on('close', () => {\n clearInterval(heartbeat);\n subscribers.remove(boxId, res);\n });\n return;\n }\n\n if (route === 'POST /admin/prompts/answer') {\n const body = await readJsonBody<PromptAnswerBody>(req);\n if (!isPromptAnswerBody(body)) {\n send(res, 400, { error: 'expected {id, answer:\"y\"|\"n\", cancelled?}' });\n return;\n }\n // Poll mode: the answer lands on the store row; the box's /rpc/status\n // poll picks it up and runs (or denies) the parked action.\n if (promptMode === 'poll') {\n const row = await store.getPrompt(body.id);\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n if (!hit) {\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (row) subscribers.broadcast(row.boxId, 'prompt-resolved', { id: body.id });\n send(res, 204, null);\n return;\n }\n // Block mode: resolve the in-process pending Promise (the parked /rpc\n // call unblocks and runs/denies inline). Find the owning box first so we\n // can target the prompt-resolved broadcast (other wrappers clear their\n // stale footer).\n const targetBox = prompts.boxFor(body.id);\n const hit = prompts.resolve(body.id, body.answer, body.cancelled);\n if (!hit) {\n // Already answered (idempotent) or never existed.\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (targetBox) {\n subscribers.broadcast(targetBox, 'prompt-resolved', { id: body.id });\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/host-initiated/mint') {\n // Host CLI mints a one-time token before invoking `agentbox-ctl` in a\n // box for a credentialed RPC. The token is scoped to\n // (boxId, method, paramsHash) and consumed on first use.\n // See ./host-initiated.ts for rationale.\n //\n // paramsHash is mandatory in practice — without it a box that\n // harvests the token from agentbox-ctl's /proc/<pid>/cmdline could\n // replay it with mutated args. Accept `null` only for callers that\n // intentionally opt out (none today).\n const body = await readJsonBody<{\n boxId?: string;\n method?: string;\n paramsHash?: string | null;\n ttlMs?: number;\n }>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.method !== 'string' ||\n body.method.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, method, paramsHash, ttlMs?}' });\n return;\n }\n // Allow `paramsHash: null` (explicit opt-out) or a hex string.\n let paramsHash: string | null;\n if (body.paramsHash === null || body.paramsHash === undefined) {\n paramsHash = null;\n } else if (typeof body.paramsHash === 'string' && /^[0-9a-f]{64}$/.test(body.paramsHash)) {\n paramsHash = body.paramsHash;\n } else {\n send(res, 400, { error: 'paramsHash must be a 64-hex sha256 string or null' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const token = hostInitiatedTokens.mint(body.boxId, body.method, paramsHash, ttlMs);\n log(`host-initiated-mint box=${body.boxId} method=${body.method} paramsBound=${paramsHash !== null}`);\n send(res, 200, { token });\n return;\n }\n\n if (route === 'POST /admin/notices/set') {\n const body = await readJsonBody<SetNoticeBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.kind !== 'string' ||\n body.kind.length === 0 ||\n typeof body.message !== 'string' ||\n body.message.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, kind, message}' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const id = notices.set(body.boxId, body.kind, body.message, ttlMs);\n log(`notice-set box=${body.boxId} kind=${body.kind} id=${id}`);\n send(res, 200, { id });\n return;\n }\n\n if (route === 'POST /admin/queue/enqueue') {\n // The CLI's `submitQueueJob` writes the manifest first, then POSTs here\n // so the relay's scheduler runs immediately instead of waiting for the\n // next periodic tick. Body is informational — the source of truth is\n // the manifest on disk.\n const body = await readJsonBody<{ id?: string }>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {id}' });\n return;\n }\n log(`queue-enqueue id=${body.id}`);\n queuePoke?.();\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/notices/clear') {\n const body = await readJsonBody<ClearNoticeBody>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {boxId, id}' });\n return;\n }\n notices.clear(body.id);\n log(`notice-clear id=${body.id}`);\n send(res, 204, null);\n return;\n }\n\n if (uiHandler) {\n uiHandler(req, res);\n return;\n }\n send(res, 404, { error: 'not found', route });\n }\n\n /**\n * Run a host action that has already cleared its approval gate (poll mode:\n * the box reached `/rpc/status` after a `y`). No re-gating here. Extended per\n * method as the hosted plane grows.\n */\n async function dispatchApprovedAction(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n ): Promise<GitRpcResult> {\n if (method === 'git.push' || method === 'git.fetch') {\n return handleGitRpc(reg, method, params as GitRpcParams | undefined);\n }\n if (method === 'git.lease-token') {\n return leaseTokenResult(leaser, reg);\n }\n return {\n exitCode: 64,\n stdout: '',\n stderr: `relay: no approved-action executor for ${method}\\n`,\n };\n }\n\n async function authBox(\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<BoxRegistration | null> {\n const token = bearerToken(req);\n if (token.length === 0) {\n send(res, 401, { error: 'missing bearer token' });\n return null;\n }\n const match = await store.authenticateBox(token);\n if (!match) {\n send(res, 401, { error: 'unknown box token' });\n return null;\n }\n return match;\n }\n\n return {\n server,\n store,\n registry,\n events,\n statusStore,\n prompts,\n subscribers,\n notices,\n hubNotifier,\n hostActions: hostActions ?? undefined,\n url: `http://${host}:${String(opts.port)}`,\n setQueuePoke: (fn) => {\n queuePoke = fn;\n },\n pokeQueue: () => {\n queuePoke?.();\n },\n close: async () => {\n if (pollers) await pollers.stopAll();\n await new Promise<void>((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n },\n };\n}\n\n\nfunction sanitizeWorktrees(input: BoxWorktree[] | undefined): BoxWorktree[] | undefined {\n if (!Array.isArray(input)) return undefined;\n const out: BoxWorktree[] = [];\n for (const w of input) {\n if (\n w &&\n typeof w.containerPath === 'string' &&\n typeof w.hostMainRepo === 'string' &&\n typeof w.branch === 'string'\n ) {\n out.push({\n containerPath: w.containerPath,\n hostMainRepo: w.hostMainRepo,\n branch: w.branch,\n ...(typeof w.sanctionedBranch === 'string' && w.sanctionedBranch.length > 0\n ? { sanctionedBranch: w.sanctionedBranch }\n : {}),\n });\n }\n }\n return out;\n}\n\n/**\n * git.push --host-only: make the box's branch available in the host's *local*\n * repo without pushing to any remote. Docker boxes commit against the\n * bind-mounted `.git/`, so the box's branch ref already lives in the host repo;\n * we just copy it to the requested destination ref via a self-fetch (which\n * enforces fast-forward and works even though the source branch is checked out\n * in the worktree). When the destination equals the source branch this is a\n * no-op success — the branch is already on the host.\n */\nasync function handleGitSaveToHost(\n reg: BoxRegistration,\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // Land the branch the box is actually on (its host-sanctioned branch, updated\n // by `agentbox git checkout`), matching what `git.push` publishes — not the\n // stale create-time scratch ref.\n const src = worktree.sanctionedBranch ?? worktree.branch;\n const dest = resolveLandDest(src, params?.as);\n if (dest === src) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} already available in ${worktree.hostMainRepo}\\n`,\n stderr: '',\n };\n }\n const refspec = landRefspec(src, dest, params?.force);\n const result = await runHostCommand([\n 'git',\n '-C',\n worktree.hostMainRepo,\n 'fetch',\n '.',\n refspec,\n ]);\n if (result.exitCode === 0) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${worktree.hostMainRepo}\\n${result.stdout}`,\n stderr: result.stderr,\n };\n }\n return result;\n}\n\n/**\n * git.push / git.fetch: run `git -C <hostMainRepo> <op> <remote> <branch>\n * [args]` on the host with the user's creds. The in-container worktree's\n * working tree isn't on the host, so we operate on the shared `.git/` from\n * the main repo dir — refs already point at the in-container commits\n * (committed there against the bind-mounted .git).\n *\n * git.pull is intentionally NOT handled here: a pull merges into the\n * working tree, which lives inside the container. The in-box\n * `agentbox-ctl git pull` calls git.fetch via RPC, then runs a local merge.\n */\nasync function handleGitRpc(\n reg: BoxRegistration,\n method: 'git.push' | 'git.fetch',\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const op = method === 'git.push' ? 'push' : 'fetch';\n const remote = resolveRemote(params?.remote);\n // Operate on the host-sanctioned branch (updated by `agentbox git checkout`),\n // falling back to the create-time `branch` for records without the field.\n // The agent can't influence this — the relay picks the branch — so pushing\n // it is always host-controlled.\n const pushBranch = worktree.sanctionedBranch ?? worktree.branch;\n const argv = ['git', '-C', worktree.hostMainRepo, op, remote, pushBranch];\n argv.push(...sanitizeGitArgs(params?.args));\n const result = await runHostCommand(argv);\n // After a successful push, mirror what `git push -u` would have left behind:\n // make the branch track `origin/<branch>` so the in-box `git status` /\n // Claude Code's PR badge see an upstream. Skip per-box scratch branches\n // (`agentbox/<name>`) — they're local-only by design. Docker shares .git/\n // with the box, so update-ref of the remote-tracking ref already happened\n // during the push; only the upstream config is missing.\n if (method === 'git.push' && result.exitCode === 0 && !isScratchBranch(pushBranch)) {\n await runHostCommand([\n 'git',\n '-C',\n worktree.hostMainRepo,\n 'branch',\n `--set-upstream-to=${upstreamRef(remote, pushBranch)}`,\n pushBranch,\n ]);\n }\n return result;\n}\n\n/**\n * gh.pr.<op>: shell to the host's `gh` CLI (with the user's gh auth) to drive\n * a PR operation requested from inside the box. Read-only ops (`view`,\n * `list`) bypass the confirm prompt; everything else surfaces an\n * `askPrompt` to the host wrapper before running. `merge` and `checkout`\n * have additional opt-in env guards — see `refuseMergeBypass` and\n * `refuseCheckoutByDefault` in `./gh.ts`.\n *\n * Runs `gh` with `cwd = worktree.hostMainRepo` so `gh` infers the repo from\n * the host repo's `git remote -v`. The box's worktree branch is registered\n * (used to refuse `checkout` against the active per-box branch).\n */\nasync function handleGhPrRpc(\n op: GhPrOp,\n reg: BoxRegistration,\n params: GhPrRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n hostInitiatedTokens: HostInitiatedTokens,\n): Promise<GitRpcResult> {\n // Env-only refusals first — cheap, deterministic, no fs/process calls.\n const mergeBypass = refuseMergeBypass(op);\n if (mergeBypass) return mergeBypass;\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n if (op === 'checkout') {\n // Guard against the host repo checking out onto ANY branch a box currently\n // occupies — its create-time scratch ref AND its host-sanctioned branch\n // (the box's live HEAD after `agentbox git checkout`), either of which the\n // bind-mounted `.git/HEAD` would corrupt.\n const branches = (reg.worktrees ?? []).flatMap((w) =>\n w.sanctionedBranch && w.sanctionedBranch !== w.branch\n ? [w.branch, w.sanctionedBranch]\n : [w.branch],\n );\n const guard = await checkoutGuards(worktree.hostMainRepo, branches);\n if (guard) return guard;\n }\n\n // Host-initiated `gh pr <op>` (from `agentbox git pr <op> <box>`) skips\n // the confirm prompt — but only with a valid scope-matched, params-hash-\n // bound one-time token. If a token is *present* but invalid (mutated\n // params, replayed, etc.) we reject hard — that's an attack signal. Only\n // fall through to the prompt when no token was claimed. The\n // `refuseMergeBypass` / `refuseCheckoutByDefault` guards above still run.\n const tokenClaimedGh = typeof params?.hostInitiated === 'string';\n const incomingHashGh = hashRpcParams(params);\n const hostInitiatedOk =\n !GH_PR_READ_ONLY_OPS.has(op) &&\n tokenClaimedGh &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, `gh.pr.${op}`, incomingHashGh);\n if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGh && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n // Safe subset: open-PR + PR comment auto-approve under the flag (audited);\n // review/close/reopen/merge/checkout keep prompting. A `create` with an\n // EXPLICIT `--head` is excluded — that head could name any branch (e.g.\n // `main`), so it falls back to the prompt; a headless `create` has its head\n // forced to the box's sanctioned branch below, so it stays scoped.\n const ghSafeAuto =\n GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) &&\n reg.autoApproveSafeHostActions !== false &&\n !prCreateHasExplicitHead(op, args);\n if (ghSafeAuto && !hostInitiatedOk) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `gh pr ${op} from box ${reg.name}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh pr ${op}`, cwd: containerPath, argv: args },\n },\n `safe: gh pr ${op}`,\n );\n }\n if (!GH_PR_READ_ONLY_OPS.has(op) && !ghSafeAuto && !hostInitiatedOk) {\n const detail = args.join(' ').slice(0, 200);\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow gh pr ${op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: {\n command: `gh pr ${op}`,\n cwd: containerPath,\n argv: args,\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n\n // Default `--head` to the box's branch for `create` (the host repo cwd isn't\n // on the box branch, so gh can't infer it). Done after token validation —\n // which hashes the incoming `params`, not this post-injection argv.\n // Inject the box's SANCTIONED branch (updated by `agentbox git checkout`),\n // matching what `git.push` publishes — so a headless PR targets the branch\n // the box's work is actually on, not the stale create-time scratch ref.\n const finalArgs = injectPrCreateHead(op, worktree.sanctionedBranch ?? worktree.branch, args);\n // Never let `gh` fall back to the host repo's checked-out branch.\n if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;\n return runHostGh(['pr', op, ...finalArgs], worktree.hostMainRepo);\n}\n\n/**\n * `gh.run.<op>` (list / view / rerun). Runs `gh run …` in the host main repo\n * so gh infers the GitHub repo from its remotes. `list` / `view` are read-only;\n * `rerun` re-triggers CI and goes through the host confirm prompt. No\n * host-initiated token path — this is an in-box-only surface.\n */\nasync function handleGhRunRpc(\n op: GhRunOp,\n reg: BoxRegistration,\n params: GhRunRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n if (!GH_RUN_READ_ONLY_OPS.has(op)) {\n const detail = args.join(' ').slice(0, 200);\n if (reg.autoApproveSafeHostActions !== false) {\n // `gh run rerun` only re-triggers the project's own CI — safe subset.\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `gh run ${op} from box ${reg.name}`,\n detail,\n context: { command: `gh run ${op}`, cwd: containerPath, argv: args },\n },\n `safe: gh run ${op}`,\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow gh run ${op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: { command: `gh run ${op}`, cwd: containerPath, argv: args },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n return runHostGh(['run', op, ...args], worktree.hostMainRepo);\n}\n\n/**\n * `gh.api`: allowlisted REST calls. Runs `gh api <endpoint> …` in the host main\n * repo. The endpoint must match `GH_API_ALLOWED_ENDPOINTS`; `refuseGhApiCall`\n * then enforces the method policy (GET anywhere on the allowlist, POST only on\n * the comment endpoints). No prompt — reads and comment POSTs are both silent.\n */\nasync function handleGhApiRpc(\n reg: BoxRegistration,\n params: GhApiRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const endpoint = typeof params?.endpoint === 'string' ? params.endpoint : '';\n if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const callRefusal = refuseGhApiCall(endpoint, args);\n if (callRefusal) return callRefusal;\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n return runHostGh(['api', endpoint, ...args], worktree.hostMainRepo);\n}\n\n/**\n * `integration.<service>.<op>`: generic dispatch for any connector\n * registered in `@agentbox/integrations`. Mirrors the `gh.pr.<op>` flow\n * (worktree resolve → `assertReady` → host-initiated token / askPrompt for\n * writes → shell out). Reads bypass the prompt; writes are always gated.\n * Op-level `refuseCall` (e.g. `notion.api`'s GET-only check) runs after\n * worktree resolve but before any host process is touched.\n *\n * All failures return the same `{exitCode, stdout, stderr}` envelope as\n * `handleGhPrRpc` — including unknown-method/service shapes (exit 64) —\n * so the cloud and docker paths emit identical wire shapes per the\n * \"fix across all providers\" rule.\n */\nasync function handleIntegrationRpc(\n method: string,\n reg: BoxRegistration,\n params: IntegrationRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n hostInitiatedTokens: HostInitiatedTokens,\n): Promise<GitRpcResult> {\n const parsed = parseIntegrationMethod(method);\n if (!parsed) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration method shape: ${method}\\n`,\n };\n }\n const connector = getConnector(parsed.service);\n if (!connector) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration service: ${parsed.service}\\n`,\n };\n }\n const opDesc = connector.ops[parsed.op];\n if (!opDesc) {\n return makeIntegrationOpRefusal(\n parsed.service,\n parsed.op,\n connector.hostBin,\n Object.keys(connector.ops),\n );\n }\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const callRefusal = refuseIntegrationCall(opDesc, args);\n if (callRefusal) return callRefusal;\n\n // Layered enablement gate — the in-box shim and ctl both transparently\n // forward to here, so this one check covers every caller. Reads the\n // worktree's project config so a single project can opt in without\n // flipping it globally. Placed after `refuseIntegrationCall` so the\n // ordering matches the cloud handler (`runIntegrationRpc` in\n // host-actions.ts) — keeps the wire envelope identical across providers\n // for the malformed-args-to-disabled-integration edge case. Runs before\n // `assertIntegrationReady`, the prompt, and the host spawn so a disabled\n // integration is never user-visible as a permission prompt.\n const enableRefusal = await refuseIfIntegrationDisabled(\n parsed.service,\n worktree.hostMainRepo,\n );\n if (enableRefusal) return enableRefusal;\n\n const ready = await assertIntegrationReady(connector);\n if (ready) return ready;\n\n // Host-initiated calls (from a host CLI mint) skip the prompt — but only\n // with a valid scope-matched, params-hash-bound one-time token. Hard\n // reject a *present-but-invalid* token (attack signal). Only fall through\n // to the prompt when no token was claimed. Reads never need a token.\n if (opDesc.write) {\n if (reg.autoApproveSafeHostActions !== false) {\n // Integration writes hit the connected external service (not the host) —\n // safe subset, audited, no prompt.\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `${parsed.service} ${parsed.op} from box ${reg.name}`,\n detail: args.join(' ').slice(0, 200),\n context: {\n command: `integration ${parsed.service} ${parsed.op}`,\n cwd: containerPath,\n argv: args,\n },\n },\n `safe: integration ${parsed.service} ${parsed.op}`,\n );\n } else {\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const tokenOk =\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, method, incomingHash);\n if (tokenClaimed && !tokenOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (!tokenOk) {\n const detail = args.join(' ').slice(0, 200);\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow ${parsed.service} ${parsed.op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: {\n command: `integration ${parsed.service} ${parsed.op}`,\n cwd: containerPath,\n argv: args,\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n }\n\n return runHostIntegration(connector, opDesc, args, worktree.hostMainRepo);\n}\n\n/**\n * cp.toHost / cp.fromHost: copy a file/dir between box and host. Shells\n * out to the installed agentbox CLI's `cp` subcommand — that command\n * already knows how to handle the docker exec tar pipe + chown + auto-\n * unpause; duplicating that here would drift. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n *\n * Caller (the /rpc route) already gated this with askPrompt and rejected\n * non-'y' answers; we never reach this code without consent.\n */\nasync function handleCpRpc(cpArgs: string[], cwd?: string): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side',\n };\n }\n // Re-shell the installed `agentbox cp` (it owns the tar pipe, excludes, the\n // size guard, and provider routing). `cpArgs` is the fully-built argv from\n // buildCpArgv (box side prefixed with `<name>:`, host paths absolute); `cwd`\n // (the box workspace) makes the host CLI's project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n return runHostCommand(argv, CP_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * download.{workspace,env,config,claude}: ask the installed agentbox CLI\n * to pull box contents to the host. Same decoupling rationale as cp — the\n * CLI owns rsync exclude lists, gitignore handling, claude registry\n * merging. The relay passes `-y` so the host CLI doesn't try to prompt\n * (we already did, via the host wrapper, before reaching this handler).\n */\nasync function handleDownloadRpc(\n reg: BoxRegistration,\n kind: DownloadKind,\n): Promise<GitRpcResult> {\n // params.hostPath is reserved in the wire shape; the v1 relay ignores it\n // and lets the host CLI use its defaults (box.workspacePath or ~/.claude).\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run download host-side',\n };\n }\n const argv = [process.execPath, entry, 'download'];\n // `workspace` is the default download (no subcommand); the other three\n // are subcommands of `download`.\n if (kind !== 'workspace') argv.push(kind);\n argv.push(reg.name, '-y');\n // Run from the box's host workspace so the host CLI's project-config lookup\n // is box-correct (the destination already defaults to box.workspacePath).\n const cwd = await boxWorkspacePath(reg.boxId);\n return runHostCommand(argv, DOWNLOAD_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * Capture a checkpoint host-side by shelling out to the installed agentbox\n * CLI (same decoupling philosophy as `handleGitRpc` spawning `git`). The\n * relay only knows the box id; the CLI resolves the BoxRecord (project root,\n * checkpoint config, snapshot storage) from it. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n */\nasync function handleCheckpointRpc(\n reg: BoxRegistration,\n params: CheckpointRpcParams | undefined,\n): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side',\n };\n }\n const argv = [process.execPath, entry, 'checkpoint', 'create', reg.boxId];\n if (params?.name) argv.push('--name', params.name);\n if (params?.merged === true) argv.push('--merged');\n if (params?.setDefault === true) argv.push('--set-default');\n if (params?.replace === true) argv.push('--replace');\n return runHostCommand(argv, CHECKPOINT_RPC_TIMEOUT_MS);\n}\n\n/**\n * Guard for the `browser.open` RPC: only absolute http/https URLs may be\n * handed to the host's `open`. Rejecting every other scheme (`file:`,\n * `javascript:`, bare paths) keeps an in-box agent from opening host files\n * or apps under the guise of \"opening a link\".\n */\nexport function isOpenableUrl(value: string): boolean {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\nfunction runHostCommand(\n argv: string[],\n timeoutMs: number = GIT_RPC_TIMEOUT_MS,\n cwd?: string,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const [cmd, ...rest] = argv;\n if (!cmd) {\n resolve({ exitCode: 64, stdout: '', stderr: 'empty command' });\n return;\n }\n const child = spawn(cmd, rest, {\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Default to the relay daemon's CWD when unset (legacy behaviour); callers\n // that know the box pass its workspace so relative host paths + project\n // config resolve against the box, not whatever dir launched the relay.\n ...(cwd ? { cwd } : {}),\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\nexport async function startRelayServer(opts: RelayServerOptions): Promise<RelayServerHandle> {\n const handle = createRelayServer(opts);\n await new Promise<void>((resolve, reject) => {\n handle.server.once('error', reject);\n handle.server.listen(opts.port, opts.host ?? '0.0.0.0', () => {\n handle.server.removeListener('error', reject);\n resolve();\n });\n });\n return handle;\n}\n\nexport type { BoxRegistration, RelayEvent };\n","/**\n * Host-side executor for actions parked by the in-sandbox `box-mode` relay\n * and drained by the `CloudBoxPoller`. This is where the host actually does\n * the work an in-box `agentbox-ctl git push` needs done — with host SSH\n * creds, in the host repo, without ever sending secrets into the box.\n *\n * v0 implements `git.push` and `git.fetch` via the git-bundle pull-back\n * pattern: the in-sandbox `git bundle create` is fetched into a host tmp\n * file, the host repo `git fetch`es the per-box branch from it (always a\n * fast-forward — the per-box branch only ever moves forward), then runs\n * the real `git push origin` / `git fetch origin`. `cp.*`, `download.*`,\n * `checkpoint.create`, `browser.open` are stubbed with a clear \"not yet\n * supported for cloud boxes\" error so the in-box command unblocks instead\n * of hanging. Filling each in is localized to this file.\n */\n\nimport { execa } from 'execa';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n isResolvedBranch,\n isScratchBranch,\n isSanctionedPushBranch,\n landRefspec,\n parseDownloadKind,\n realpathSafe,\n remoteTrackingRef,\n resolveHostPath,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport {\n findBox,\n hostOpenCommand,\n isSupportedApiVersion,\n pluginForProvider,\n readState,\n} from '@agentbox/sandbox-core';\nimport {\n assertGhReady,\n checkoutGuards,\n GH_API_ENDPOINT_REFUSAL,\n GH_PR_READ_ONLY_OPS,\n GH_PR_SAFE_AUTO_APPROVE_OPS,\n GH_RUN_READ_ONLY_OPS,\n injectPrCreateHead,\n isAllowedGhApiEndpoint,\n isGhPrOp,\n isGhRunOp,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateHasExplicitHead,\n prCreateNeedsHead,\n refuseCheckoutByDefault,\n refuseGhApiCall,\n refuseMergeBypass,\n runHostGh,\n type GhApiRpcParams,\n type GhPrRpcParams,\n type GhRunRpcParams,\n} from './gh.js';\nimport { hashRpcParams, type HostInitiatedTokens } from './host-initiated.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams, type CpMethod } from './cp-rpc.js';\nimport {\n assertIntegrationReady,\n makeIntegrationOpRefusal,\n parseIntegrationMethod,\n refuseIfIntegrationDisabled,\n refuseIntegrationCall,\n runHostIntegration,\n type IntegrationRpcParams,\n} from './integrations.js';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { getConnector } from '@agentbox/integrations';\nimport type {\n CheckpointRpcParams,\n CpRpcParams,\n DownloadRpcParams,\n GitRpcParams,\n HostAction,\n HostActionResult,\n} from './types.js';\n\nexport interface CloudActionExecutorDeps {\n /** From BoxRegistration.backend (e.g. 'daytona'). */\n backendName: string;\n /** From BoxRegistration.boxId. Used to look up the BoxRecord in ~/.agentbox/state.json. */\n boxId: string;\n /** Friendly box name — used in confirm-prompt messages. Falls back to boxId. */\n boxName?: string;\n /** Host relay's pending-prompts queue, for gating destructive ops like git push. */\n prompts?: PendingPrompts;\n /** Host wrapper SSE subscribers — the prompt UX feeds through them. */\n subscribers?: PromptSubscribers;\n /** Host CLI one-time tokens; presence + scope-match skips the confirm prompt. */\n hostInitiatedTokens?: HostInitiatedTokens;\n /**\n * Mirrors `box.autoApproveSafeHostActions` from the registration (default\n * on). When not `false`, the SAFE subset of host actions auto-resolves; only\n * an explicit `false` restores the always-prompt behavior. Undefined is\n * treated as enabled so callers that don't know the flag stay relaxed.\n */\n autoApproveSafeHostActions?: boolean;\n /** Best-effort logger. */\n log?: (line: string) => void;\n}\n\n/**\n * Lazy backend resolver. Hardcoded for the providers we ship; future cloud\n * backends slot in here. Dynamic import keeps the relay process from loading\n * cloud SDKs (heavy CJS trees) until a cloud box is actually registered.\n *\n * ## Runtime contract (the relay→sandbox-* dependency story)\n *\n * The import path is a computed string on purpose — a literal would make\n * esbuild eager-resolve the package at bundle time, and the relay tsup\n * configs intentionally don't depend on the per-backend packages (to avoid\n * a `sandbox-daytona → sandbox-cloud → sandbox-docker → relay` cycle in\n * package.json deps).\n *\n * **At runtime the parent process is responsible for making\n * `@agentbox/sandbox-daytona` (and `@agentbox/sandbox-cloud` for the cp /\n * download / browser-open executors) resolvable from `node_modules` next\n * to the relay bin.** The `@madarco/agentbox` CLI satisfies this by\n * carrying both packages in its build, bundled via `tsup` with\n * `noExternal: [/^@agentbox\\//]`. The published `agent-box` npm package\n * ships them inlined; the workspace setup hits the same path via\n * pnpm-symlinked `node_modules`.\n *\n * If you embed `@agentbox/relay` standalone in a different host (no\n * agentbox CLI around), you MUST install `@agentbox/sandbox-daytona`\n * yourself for cloud executors to work — otherwise this throws a clear\n * `MODULE_NOT_FOUND` error and the in-box `/rpc` will see exit 1 with the\n * \"no host executor\" message above.\n */\nexport async function resolveCloudBackend(name: string): Promise<CloudBackend> {\n // NB: the `'@agentbox/sandbox-' + '<name>'` specifiers are written as literal\n // concatenations (not `+ name`) on purpose — esbuild constant-folds them so\n // the bundler can statically resolve + inline each provider package\n // (`noExternal: [/^@agentbox\\//]`, see above). A runtime variable specifier\n // would defeat that and MODULE_NOT_FOUND in the published CLI. Only the\n // error-handling is shared (via `loadCloudBackend`).\n if (name === 'daytona') {\n const pkg = '@agentbox/sandbox-' + 'daytona';\n return loadCloudBackend(pkg, async () => ((await import(pkg)) as { daytonaBackend: CloudBackend }).daytonaBackend);\n }\n if (name === 'hetzner') {\n const pkg = '@agentbox/sandbox-' + 'hetzner';\n return loadCloudBackend(pkg, async () => ((await import(pkg)) as { hetznerBackend: CloudBackend }).hetznerBackend);\n }\n if (name === 'vercel') {\n const pkg = '@agentbox/sandbox-' + 'vercel';\n return loadCloudBackend(pkg, async () => ((await import(pkg)) as { vercelBackend: CloudBackend }).vercelBackend);\n }\n if (name === 'e2b') {\n const pkg = '@agentbox/sandbox-' + 'e2b';\n return loadCloudBackend(pkg, async () => ((await import(pkg)) as { e2bBackend: CloudBackend }).e2bBackend);\n }\n if (name === 'digitalocean') {\n const pkg = '@agentbox/sandbox-' + 'digitalocean';\n return loadCloudBackend(pkg, async () => ((await import(pkg)) as { digitaloceanBackend: CloudBackend }).digitaloceanBackend);\n }\n // External provider plugins: not bundle-inlined, so resolve from the same\n // `~/.agentbox/plugins.json` registry the CLI writes and `import()` the\n // recorded entry with a TRUE variable specifier. The relay runs on the host\n // (same ~/.agentbox), so the registry + the installed package are reachable.\n const plugin = pluginForProvider(name);\n if (plugin) {\n if (!isSupportedApiVersion(plugin.apiVersion)) {\n throw new Error(\n `relay: plugin '${plugin.packageName}' targets provider SDK v${String(plugin.apiVersion)}, which this AgentBox does not support`,\n );\n }\n return loadCloudBackend(plugin.packageName, async () => {\n const mod = (await import(pathToFileURL(plugin.resolvedEntry).href)) as {\n providerModule?: { provider?: { name?: string }; backend?: CloudBackend };\n providerModules?: { provider?: { name?: string }; backend?: CloudBackend }[];\n };\n const all = mod.providerModules ?? (mod.providerModule ? [mod.providerModule] : []);\n // Strict name match — never fall back to all[0] (wrong-backend hazard).\n const pm = all.find((m) => m.provider?.name === name);\n if (!pm?.backend) {\n throw new Error(`plugin '${plugin.packageName}' exposes no cloud backend for '${name}'`);\n }\n return pm.backend;\n });\n }\n throw new Error(`no host executor for cloud backend '${name}'`);\n}\n\n/**\n * Run a provider's dynamic import, turning a missing-module failure into the\n * actionable \"install it alongside @agentbox/relay\" error (other errors\n * propagate unchanged). Shared by every branch of `resolveCloudBackend`.\n */\nasync function loadCloudBackend(\n pkg: string,\n load: () => Promise<CloudBackend>,\n): Promise<CloudBackend> {\n try {\n return await load();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/cannot find module|MODULE_NOT_FOUND/i.test(msg)) {\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — install it alongside @agentbox/relay (the @madarco/agentbox CLI normally provides this dependency). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Re-mint the preview URL for a cloud box's `port` after a transport-level\n * failure (the host CloudBoxPoller saw ECONNREFUSED on the local port).\n * Hetzner reopens its SSH ControlMaster + `-L` forward; Daytona's permanent\n * CloudFront alias doesn't need refresh and this returns null.\n *\n * Takes the agentbox `boxId` (the one the relay knows), resolves it to the\n * backend's sandboxId via `~/.agentbox/state.json` the same way\n * `executeCloudAction` does, then asks the backend to refresh.\n *\n * Best-effort: any error during resolve/refresh returns null and the\n * poller stays on the (broken) URL — the next poll will trip the same\n * recovery hook on the next ECONNREFUSED. Throwing here would crash the\n * poller; we'd rather keep retrying.\n */\nexport async function refreshCloudPreviewUrl(\n backendName: string,\n boxId: string,\n port: number,\n): Promise<string | null> {\n try {\n const backend = await resolveCloudBackend(backendName);\n if (!backend.refreshPreviewUrl) return null;\n const lookup = await lookupCloudBox(boxId);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const url = await backend.refreshPreviewUrl(handle, port);\n return url.url;\n } catch {\n return null;\n }\n}\n\nexport async function executeCloudAction(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const log = deps.log ?? (() => {});\n log(`executing ${action.method} for box ${deps.boxId}`);\n\n if (action.method === 'git.push' || action.method === 'git.fetch') {\n return runGitRpc(action, deps);\n }\n if (action.method === 'cp.toHost' || action.method === 'cp.fromHost') {\n return runCpRpc(action, deps);\n }\n if (\n action.method === 'download.workspace' ||\n action.method === 'download.env' ||\n action.method === 'download.config' ||\n action.method === 'download.claude'\n ) {\n return runDownloadRpc(action, deps);\n }\n if (action.method === 'checkpoint.create') {\n return runCheckpointRpc(action, deps);\n }\n if (action.method === 'browser.open.mirror') {\n return runBrowserOpenMirror(action, deps);\n }\n if (action.method.startsWith('gh.pr.')) {\n return runGhPrRpc(action, deps);\n }\n if (action.method.startsWith('gh.run.')) {\n return runGhRunRpc(action, deps);\n }\n if (action.method === 'gh.api') {\n return runGhApiRpc(action, deps);\n }\n if (action.method.startsWith('integration.')) {\n return runIntegrationRpc(action, deps);\n }\n if (action.method === 'git.clone' || action.method === 'gh.repo.clone') {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${action.method}: not yet implemented (deferred; see docs/plans/gh-and-git-shims-host-only.md). Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n };\n }\n return {\n exitCode: 1,\n stdout: '',\n stderr: `host executor for '${action.method}' is not yet supported for cloud boxes\\n`,\n };\n}\n\n/**\n * Cloud `gh.pr.<op>` executor. Simpler than `runGitRpc` because nothing\n * needs to round-trip into the sandbox — `gh` only needs the host repo\n * (already at the right remote in `lookup.workspacePath`).\n *\n * Mirrors the docker handler's confirmation matrix exactly: `view` / `list`\n * are silent, write ops go through `askPrompt`, `checkout` is opt-in via\n * `AGENTBOX_GH_PR_CHECKOUT=allow`, and `merge` refuses `AGENTBOX_PROMPT=off`\n * bypass unless `AGENTBOX_GH_FORCE=1`. When no SSE subscriber is attached,\n * write-op behavior is gated by `AGENTBOX_GH_NO_SUB` (`deny` default,\n * `allow`, or `prompt`) — same shape as `AGENTBOX_GIT_PUSH_NO_SUB`.\n */\nasync function runGhPrRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const op = action.method.slice('gh.pr.'.length);\n if (!isGhPrOp(op)) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown gh.pr.* op: ${op}\\n`,\n };\n }\n // Env-only refusals first — cheap, deterministic, no fs/process calls.\n const mergeBypass = refuseMergeBypass(op);\n if (mergeBypass) return mergeBypass;\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n\n const params = (action.params ?? {}) as GhPrRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const lookup = await lookupCloudBox(deps.boxId);\n\n if (op === 'checkout') {\n // The cloud host repo isn't bind-mounted by anything; the only \"branch\n // we must not stomp\" concern is the host's own current branch, which is\n // a generic dirty-tree / \"already on this branch\" question gh itself\n // surfaces. We still refuse a dirty tree.\n const guard = await checkoutGuards(lookup.workspacePath, []);\n if (guard) return guard;\n }\n\n // Host-initiated `gh pr <op>` (from `agentbox git pr <op> <box>`) skips\n // the confirm prompt — but only with a valid scope-matched, params-hash-\n // bound one-time token. If a token is *present* but invalid, reject\n // hard: attack signal. Only fall through to the prompt when no token was\n // claimed. Destructive-op env opt-ins above still apply.\n const tokenClaimedGhCloud = typeof params.hostInitiated === 'string';\n const incomingHashGhCloud = hashRpcParams(params);\n const hostInitiatedGhOk =\n !GH_PR_READ_ONLY_OPS.has(op) &&\n tokenClaimedGhCloud &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n `gh.pr.${op}`,\n incomingHashGhCloud,\n ) ?? false);\n if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGhCloud && !hostInitiatedGhOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n // Safe subset: opening a PR (relay forces `--head <box-branch>`) and PR\n // comments auto-approve under the flag, audited. merge/checkout/review/close\n // keep prompting.\n // A `create` with an EXPLICIT `--head` is excluded from the safe subset — that\n // head could name any branch (e.g. `main`); it falls back to the prompt. A\n // headless `create` has its head forced to the box's sanctioned branch below.\n const ghSafeAuto =\n GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) &&\n deps.autoApproveSafeHostActions !== false &&\n !prCreateHasExplicitHead(op, args);\n if (ghSafeAuto && !hostInitiatedGhOk) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh pr ${op}`, cwd: params.path, argv: args },\n },\n `safe: gh pr ${op}`,\n );\n }\n if (\n !GH_PR_READ_ONLY_OPS.has(op) &&\n !ghSafeAuto &&\n !hostInitiatedGhOk &&\n deps.prompts &&\n deps.subscribers\n ) {\n const detail = args.join(' ').slice(0, 200);\n const ctx = {\n kind: 'confirm' as const,\n message: `Allow gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail,\n defaultAnswer: 'n' as const,\n context: {\n command: `gh pr ${op}`,\n cwd: params.path,\n argv: args,\n },\n };\n const hasSubscriber = deps.subscribers.forBox(deps.boxId).length > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.(`gh.pr.${op} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);\n // fall through\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {\n ttlMs: 5 * 60 * 1000,\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n\n // Default `--head` to the box's branch for `create` (the host repo cwd isn't\n // on the box branch, so gh can't infer it). Probed from the box; a failed\n // probe leaves args unchanged (today's behavior).\n let finalArgs = args;\n const containerPath = params.path ?? '/workspace';\n const needsHeadProbe =\n op === 'create' && !args.some((a) => a === '--head' || a.startsWith('--head='));\n if (needsHeadProbe) {\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const branchProbe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`,\n );\n const branch = branchProbe.exitCode === 0 ? (branchProbe.stdout ?? '').trim() : '';\n // Prefer the host-sanctioned branch so a headless PR targets the box's own\n // work (and matches the safe-auto gate above), not whatever HEAD the agent\n // may have switched to. Fall back to the probed HEAD when unknown.\n finalArgs = injectPrCreateHead(op, lookup.sanctionedBranch ?? branch, finalArgs);\n }\n // Never let `gh` fall back to the host repo's checked-out branch.\n if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;\n return runHostGh(['pr', op, ...finalArgs], lookup.workspacePath);\n}\n\n/**\n * Cloud-side confirm gate for a write op. Mirrors the prompt / no-subscriber\n * handling in `runGhPrRpc` (`AGENTBOX_GH_NO_SUB` deny/allow/prompt). Returns a\n * ready-to-send denial `HostActionResult` to abort, or `null` to proceed.\n */\nasync function cloudWriteConfirm(\n deps: CloudActionExecutorDeps,\n command: string,\n cwd: string | undefined,\n args: string[],\n): Promise<HostActionResult | null> {\n if (!deps.prompts || !deps.subscribers) return null;\n const ctx = {\n kind: 'confirm' as const,\n message: `Allow ${command} from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: args.join(' ').slice(0, 200),\n defaultAnswer: 'n' as const,\n context: { command, cwd, argv: args },\n };\n const hasSubscriber = deps.subscribers.forBox(deps.boxId).length > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.(`${command} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);\n return null;\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {\n ttlMs: 5 * 60 * 1000,\n });\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n}\n\n/**\n * Cloud `gh.run.<op>` executor (list / view / rerun). `list` / `view` are\n * silent reads; `rerun` re-triggers CI and goes through `cloudWriteConfirm`.\n */\nasync function runGhRunRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const op = action.method.slice('gh.run.'.length);\n if (!isGhRunOp(op)) {\n return { exitCode: 64, stdout: '', stderr: `unknown gh.run.* op: ${op}\\n` };\n }\n const params = (action.params ?? {}) as GhRunRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n const lookup = await lookupCloudBox(deps.boxId);\n if (!GH_RUN_READ_ONLY_OPS.has(op)) {\n if (deps.autoApproveSafeHostActions !== false) {\n // `gh run rerun` only re-triggers the project's own CI — safe subset.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `gh run ${op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh run ${op}`, cwd: params.path, argv: args },\n },\n `safe: gh run ${op}`,\n );\n } else {\n const denied = await cloudWriteConfirm(deps, `gh run ${op}`, params.path, args);\n if (denied) return denied;\n }\n }\n return runHostGh(['run', op, ...args], lookup.workspacePath);\n}\n\n/**\n * Cloud `gh.api` executor. Read-only, allowlisted endpoints only — same guards\n * as the docker `handleGhApiRpc`. No prompt (matches `gh pr view`).\n */\nasync function runGhApiRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GhApiRpcParams;\n const endpoint = typeof params.endpoint === 'string' ? params.endpoint : '';\n if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const callRefusal = refuseGhApiCall(endpoint, args);\n if (callRefusal) return callRefusal;\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n const lookup = await lookupCloudBox(deps.boxId);\n return runHostGh(['api', endpoint, ...args], lookup.workspacePath);\n}\n\n/**\n * Cloud `integration.<service>.<op>` executor. Mirrors the docker handler\n * exactly — same descriptor lookup, same read/write gating, same host\n * binary invocation. Reuses the gh-pr `cloudWriteConfirm` helper because\n * the no-subscriber fallback (`AGENTBOX_GH_NO_SUB` env knob) covers every\n * gated host action by design.\n */\nasync function runIntegrationRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const parsed = parseIntegrationMethod(action.method);\n if (!parsed) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration method shape: ${action.method}\\n`,\n };\n }\n const connector = getConnector(parsed.service);\n if (!connector) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration service: ${parsed.service}\\n`,\n };\n }\n const opDesc = connector.ops[parsed.op];\n if (!opDesc) {\n return makeIntegrationOpRefusal(\n parsed.service,\n parsed.op,\n connector.hostBin,\n Object.keys(connector.ops),\n );\n }\n const params = (action.params ?? {}) as IntegrationRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const callRefusal = refuseIntegrationCall(opDesc, args);\n if (callRefusal) return callRefusal;\n\n // Cloud boxes don't register worktrees the same way docker boxes do; the\n // closest analogue is `lookupCloudBox`'s `workspacePath` (the host-side\n // path the cloud provider records as the box's project root). Use it to\n // read the layered config and fire the enablement gate — same envelope\n // shape the docker handler returns. Placed after `refuseIntegrationCall`\n // so the structural / op-level checks (which don't need the box record)\n // still short-circuit cleanly on a malformed registry; the gate runs\n // before `assertIntegrationReady`, the prompt, and the host spawn so a\n // disabled integration is never user-visible as a permission prompt.\n const lookup = await lookupCloudBox(deps.boxId);\n const enableRefusal = await refuseIfIntegrationDisabled(\n parsed.service,\n lookup.workspacePath,\n );\n if (enableRefusal) return enableRefusal;\n\n const ready = await assertIntegrationReady(connector);\n if (ready) return ready;\n\n if (opDesc.write) {\n if (deps.autoApproveSafeHostActions !== false) {\n // Integration writes go to the connected external service (not the\n // host), so they're in the safe subset — audited, no prompt.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `integration ${parsed.service} ${parsed.op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `integration ${parsed.service} ${parsed.op}`, cwd: params.path, argv: args },\n },\n `safe: integration ${parsed.service} ${parsed.op}`,\n );\n } else {\n const tokenClaimed = typeof params.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const tokenOk =\n tokenClaimed &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n action.method,\n incomingHash,\n ) ?? false);\n if (tokenClaimed && !tokenOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (!tokenOk) {\n const denied = await cloudWriteConfirm(\n deps,\n `integration ${parsed.service} ${parsed.op}`,\n params.path,\n args,\n );\n if (denied) return denied;\n }\n }\n }\n\n return runHostIntegration(connector, opDesc, args, lookup.workspacePath);\n}\n\n\n/**\n * Mirror an in-box `browser.open` notification on the host. The action runs\n * detached from the box's `/rpc` (the in-box handler responded 200 long\n * before queuing this), so blocking here doesn't tie up an agent — we can\n * happily wait for the host user's verdict with a TTL fallback.\n *\n * On `y` we spawn `open <url>` on the host. Any other verdict (deny / TTL\n * timeout / no subscribers) silently drops the link. Always resolves\n * exit 0 because the box doesn't observe the result.\n */\nasync function runBrowserOpenMirror(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as { url?: string };\n const url = typeof params.url === 'string' ? params.url.trim() : '';\n if (!url || !/^https?:\\/\\//i.test(url)) {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n if (!deps.prompts || !deps.subscribers) return { exitCode: 0, stdout: '', stderr: '' };\n if (process.env['AGENTBOX_PROMPT'] === 'off') {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n // 90s TTL matches the docker browser.open behavior closely enough that an\n // attached user has plenty of time to answer without leaving a stale\n // prompt indefinitely.\n const TTL_MS = 90_000;\n try {\n const verdict = await askPrompt(\n deps.prompts,\n deps.subscribers,\n deps.boxId,\n {\n kind: 'confirm',\n message: `Open link from cloud box ${deps.boxName ?? deps.boxId} on the host?`,\n detail: url,\n defaultAnswer: 'n',\n context: { command: 'browser.open', argv: [url] },\n },\n { ttlMs: TTL_MS },\n );\n if (verdict.answer === 'y' && !verdict.cancelled) {\n // Open on the host's default handler (`open` on macOS, `xdg-open` on\n // Linux). Spawn detached so the relay loop isn't blocked; the box never\n // observes the outcome.\n const { spawn } = await import('node:child_process');\n const child = spawn(hostOpenCommand(), [url], { stdio: 'ignore', detached: true });\n child.unref();\n }\n } catch (err) {\n deps.log?.(`browser.open.mirror failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n return { exitCode: 0, stdout: '', stderr: '' };\n}\n\ninterface BoxLookup {\n workspacePath: string;\n cloudSandboxId: string;\n /**\n * Branch the host has sanctioned for this box's pushes (defaults to the\n * create-time `workspaceBranch`). The push gate auto-approves a push only to\n * a scratch branch or this value.\n */\n sanctionedBranch?: string;\n}\n\nasync function lookupCloudBox(boxId: string): Promise<BoxLookup> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') {\n throw new Error(`box ${boxId} not in ~/.agentbox/state.json`);\n }\n const sid = hit.box.cloud?.sandboxId;\n if (!sid) {\n throw new Error(`box ${boxId} has no cloud.sandboxId — record is malformed`);\n }\n return {\n workspacePath: hit.box.workspacePath,\n cloudSandboxId: sid,\n sanctionedBranch: hit.box.cloud?.sanctionedBranch ?? hit.box.cloud?.workspaceBranch,\n };\n}\n\n/**\n * The box's registered host workspace (the host dir that mirrors `/workspace`),\n * used as the base for resolving relative host paths in `cp`/`download` RPCs.\n * Returns `undefined` when the box isn't in state. Shared by the docker\n * (server.ts) and cloud handlers so a relative host path never silently\n * resolves against the long-lived relay daemon's CWD (which is arbitrary — one\n * relay serves many boxes/projects).\n */\nexport async function boxWorkspacePath(boxId: string): Promise<string | undefined> {\n const state = await readState();\n const hit = findBox(boxId, state);\n return hit.kind === 'ok' ? hit.box.workspacePath : undefined;\n}\n\n/**\n * The realpath'd host source paths this box already approved via its `carry:`\n * block, so the cp auto-approve gate can exempt a secret file that the user\n * already consented to copy in at create time. Best-effort: empty set on any\n * read failure (→ secret files fall back to prompting). Shared by the docker\n * and cloud cp handlers.\n */\nexport async function boxCarriedHostPaths(boxId: string): Promise<Set<string>> {\n const out = new Set<string>();\n try {\n const state = await readState();\n const hit = findBox(boxId, state);\n const entries = hit.kind === 'ok' ? hit.box.carry?.entries : undefined;\n for (const e of entries ?? []) out.add(await realpathSafe(e.src));\n } catch {\n /* best-effort */\n }\n return out;\n}\n\n// resolveHostPath's pure decision moved to `@agentbox/core`'s sync/files.ts.\n// Re-exported here so `server.ts` (and the cp/download call sites below) keep\n// importing it from `./host-actions.js` unchanged.\nexport { resolveHostPath };\n\n/**\n * Cloud cp helpers live in `@agentbox/sandbox-cloud` — same dynamic-import\n * trick as `resolveCloudBackend` keeps the relay bundle from eagerly pulling\n * the cloud package (and its sandbox-docker transitive). Imports the helpers\n * once and caches; only loaded the first time a cloud box queues `cp.*`.\n *\n * Same runtime contract as `resolveCloudBackend`: the parent process is\n * responsible for making `@agentbox/sandbox-cloud` resolvable next to the\n * relay bin. The @madarco/agentbox CLI bundles it; standalone embedders\n * must install it themselves. See the longer note on `resolveCloudBackend`.\n */\ninterface CloudCpModule {\n pullCloudDirContents(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrc: string,\n hostDst: string,\n ): Promise<{ finalPath: string }>;\n}\n\nlet cloudCpModule: CloudCpModule | undefined;\nasync function loadCloudCp(): Promise<CloudCpModule> {\n if (cloudCpModule) return cloudCpModule;\n // Computed string defeats esbuild's static resolution — see resolveCloudBackend.\n const pkg = '@agentbox/sandbox-' + 'cloud';\n try {\n const mod = (await import(pkg)) as CloudCpModule;\n cloudCpModule = mod;\n return mod;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/cannot find module|MODULE_NOT_FOUND/i.test(msg)) {\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — install it alongside @agentbox/relay (the @madarco/agentbox CLI normally provides this dependency). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\nasync function runCpRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const method = action.method as CpMethod;\n const params = (action.params ?? {}) as CpRpcParams;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(method, params);\n } catch (err) {\n return { exitCode: 64, stdout: '', stderr: `${err instanceof Error ? err.message : String(err)}\\n` };\n }\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side\\n',\n };\n }\n const direction = method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path doesn't\n // land under the relay daemon's CWD (which belongs to whichever project\n // started the relay), and so the consent prompt shows the real destination.\n const lookup = await lookupCloudBox(deps.boxId);\n const boxName = deps.boxName ?? deps.boxId;\n const { argv: cpArgs, detail, contextArgv } = buildCpArgv({\n method,\n boxName,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(lookup.workspacePath, p),\n flags: cpFlags(params),\n });\n // Same askPrompt UX as docker's /rpc handler — keeps the in-box agent from\n // pulling host files / scattering box files without explicit consent. A\n // transfer contained in the box project folder (non-secret for host->box)\n // auto-approves under the safe flag, mirroring the docker handler.\n const cpHostPaths =\n method === 'cp.toHost'\n ? [resolveHostPath(lookup.workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(lookup.workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: method === 'cp.fromHost',\n carried: method === 'cp.fromHost' ? await boxCarriedHostPaths(deps.boxId) : undefined,\n });\n if (cpAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n { kind: 'confirm', message: `cp (${direction}) on ${boxName}`, detail, context: { command: method, argv: contextArgv } },\n method === 'cp.toHost' ? 'safe: contained copy to host' : 'safe: contained copy from host',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${boxName}?`,\n detail,\n defaultAnswer: 'n',\n context: { command: method, argv: contextArgv },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n // Converge on the docker path: re-shell the installed `agentbox cp`. Its\n // `isCloud` branch routes to the cloud provider's uploadPath/downloadPath, so\n // excludes, the size guard, and provider routing are honored identically to a\n // host-typed `agentbox cp` (the old direct-primitive path silently dropped\n // them). cwd = the box workspace makes project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n const result = await execa(argv[0]!, argv.slice(1), {\n reject: false,\n cwd: lookup.workspacePath,\n });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\n/**\n * Capture a checkpoint by shelling out to the installed `agentbox` CLI\n * (same decoupling as the docker handler — the CLI owns checkpoint name\n * allocation, the `--set-default` config write, snapshot store layout, and\n * the cloud-snapshot creation via `provider.checkpoint.create`). The CLI's\n * `checkpoint create` is already provider-aware, so this path works for\n * both backends; we just hand it the box id.\n */\nasync function runCheckpointRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<CheckpointRpcParams>;\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side\\n',\n };\n }\n // Vercel checkpoints stop + reboot the box: `sb.snapshot()` powers off the\n // microVM (resume is lazy on the next SDK call). When an interactive wrapper\n // is attached, warn + require confirmation before we yank the box out from\n // under it. Other backends snapshot without stopping (docker `docker commit`,\n // hetzner no-pause, daytona), so they stay prompt-free. No attached wrapper →\n // proceed (a headless caller already knows the box will reboot).\n if (\n deps.backendName === 'vercel' &&\n deps.autoApproveSafeHostActions === false &&\n deps.prompts &&\n deps.subscribers &&\n deps.subscribers.forBox(deps.boxId).length > 0\n ) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Create checkpoint on ${deps.boxName ?? deps.boxId}? The vercel box will stop and reboot.`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n defaultAnswer: 'n',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'checkpoint denied by user\\n' };\n }\n } else if (\n deps.backendName === 'vercel' &&\n deps.subscribers &&\n deps.subscribers.forBox(deps.boxId).length > 0\n ) {\n // Checkpoint is a safe subset op (the box's own snapshot); audit the\n // reboot-causing auto-approval so it's still visible in the event feed.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `checkpoint create on ${deps.boxName ?? deps.boxId} (vercel box will stop and reboot)`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n },\n 'safe: checkpoint create',\n );\n }\n\n const argv = [process.execPath, entry, 'checkpoint', 'create', deps.boxId];\n if (params.name) argv.push('--name', params.name);\n // --merged is docker-image-layer specific (flatten). For cloud snapshots\n // it's a no-op; pass it through anyway so the CLI's docker branch sees it\n // and the cloud branch ignores it cleanly.\n if (params.merged === true) argv.push('--merged');\n if (params.setDefault === true) argv.push('--set-default');\n if (params.replace === true) argv.push('--replace');\n const result = await execa(argv[0]!, argv.slice(1), { reject: false });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nasync function runDownloadRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<DownloadRpcParams>;\n const kind = parseDownloadKind(action.method);\n // Only `workspace` lands cleanly on cloud today — env/config/claude live in\n // per-agent volumes and aren't routed yet (Phase 6 follow-up; see backlog\n // 2.2). Surface a clear error instead of pretending to succeed.\n if (kind !== 'workspace') {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download.${kind} is not yet supported for cloud boxes (only download.workspace is)\\n`,\n };\n }\n const lookup = await lookupCloudBox(deps.boxId);\n // params.hostPath is reserved in the wire shape; v1 lands /workspace under\n // box.workspacePath (the host project root), matching docker's default. A\n // relative override resolves against the box workspace, not the relay's CWD.\n const hostDst = typeof params.hostPath === 'string' && params.hostPath.length > 0\n ? resolveHostPath(lookup.workspacePath, params.hostPath)\n : lookup.workspacePath;\n // Auto-approve when the destination stays inside the box project folder\n // (the default does); an escaping override still prompts.\n const dlAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: [hostDst],\n checkSecret: false,\n });\n if (dlAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${deps.boxName ?? deps.boxId}`,\n detail: params.hostPath ?? '(default host location)',\n context: { command: action.method, argv: params.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${deps.boxName ?? deps.boxId}?`,\n detail: params.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: action.method,\n argv: params.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const cp = await loadCloudCp();\n try {\n const result = await cp.pullCloudDirContents(backend, handle, '/workspace', hostDst);\n return { exitCode: 0, stdout: `${result.finalPath}\\n`, stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n\n/**\n * Git RPC executor for cloud boxes. The push direction:\n *\n * 1. In the sandbox, write a bundle of the per-box branch.\n * 2. Download the bundle to the host.\n * 3. Fetch the bundle ref into the host repo (always a fast-forward).\n * 4. Run the real git push from the host repo.\n *\n * Fetch direction is the mirror: host fetches origin, bundles, uploads,\n * sandbox fetches from the bundle, in-box `agentbox-ctl git pull` then\n * does its local merge as today.\n */\nasync function runGitRpc(action: HostAction, deps: CloudActionExecutorDeps): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GitRpcParams;\n const lookup = await lookupCloudBox(deps.boxId);\n const backend = await resolveCloudBackend(deps.backendName);\n const handle = { sandboxId: lookup.cloudSandboxId };\n\n // The in-box ctl sends `params.path = process.cwd()`. When the user runs\n // `agentbox-ctl git push` from anywhere outside /workspace (e.g. $HOME),\n // that path won't be a git repo and `git rev-parse` would fail. Fall back\n // to /workspace whenever the supplied path can't resolve a git dir — the\n // per-box branch only ever lives at /workspace anyway.\n let containerPath = params.path ?? '/workspace';\n if (containerPath !== '/workspace') {\n const probe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --git-dir`,\n );\n if (probe.exitCode !== 0) containerPath = '/workspace';\n }\n\n // 1. Resolve the box's current branch (the per-box `agentbox/<name>`).\n const branchProbe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`,\n );\n const branch = (branchProbe.stdout ?? '').trim();\n if (branchProbe.exitCode !== 0 || !isResolvedBranch(branch)) {\n return {\n exitCode: branchProbe.exitCode || 1,\n stdout: '',\n stderr: `failed to resolve branch in sandbox ${containerPath}: ${branchProbe.stderr || branch}`,\n };\n }\n\n // Host-only landing: copy the box's branch into the host's *local* repo\n // (no remote push, nothing published). This is the push flow's bundle\n // pull-back steps without the final `git push` — so it skips the confirm\n // gate below entirely. Destination defaults to the box's branch name.\n if (params.hostOnly) {\n const dest = resolveLandDest(branch, params.as);\n const stageSave = await mkdtemp(join(tmpdir(), 'agentbox-git-save-'));\n const hostBundleSave = join(stageSave, 'op.bundle');\n const remoteBundleSave = '/tmp/agentbox-rpc-save.bundle';\n try {\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundleSave)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return { exitCode: make.exitCode, stdout: '', stderr: `bundle create failed: ${make.stderr || make.stdout}` };\n }\n await backend.downloadFile(handle, remoteBundleSave, hostBundleSave);\n const refspec = landRefspec(branch, dest, params.force);\n const landed = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'fetch', hostBundleSave, refspec],\n { reject: false },\n );\n if ((landed.exitCode ?? 1) !== 0) {\n return {\n exitCode: landed.exitCode ?? 1,\n stdout: landed.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${landed.stderr ?? ''}`,\n };\n }\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${lookup.workspacePath}\\n${landed.stdout ?? ''}`,\n stderr: landed.stderr ?? '',\n };\n } finally {\n await rm(stageSave, { recursive: true, force: true });\n await backend.exec(handle, `rm -f ${shellQuote(remoteBundleSave)}`).catch(() => {\n /* best-effort */\n });\n }\n }\n\n // Gate `git.push` (and only `git.push`) behind the same host-side confirm\n // prompt the Docker provider already uses. The wrapper's SSE subscriber on\n // /admin/prompts/stream surfaces it as a footer y/N; `askPrompt` returns\n // auto-`y` when AGENTBOX_PROMPT=off (matches Docker behavior).\n // The gate is bypassed for pushes to a *sanctioned* branch: the box's own\n // `agentbox/<name>` scratch branch (always its job), or the branch the host\n // last put the box on (`sanctionedBranch`). A scratch push bypasses\n // unconditionally; the sanctioned-but-non-scratch bypass is part of the safe\n // subset, so it honors `box.autoApproveSafeHostActions` and leaves an audit\n // trail. An agent that self-switches HEAD to another branch still prompts.\n const isScratch = isScratchBranch(branch);\n const safeApproveOn = deps.autoApproveSafeHostActions !== false;\n const isSanctionedNonScratch =\n !isScratch && safeApproveOn && isSanctionedPushBranch(branch, lookup.sanctionedBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (action.method === 'git.push' && isSanctionedNonScratch) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${branch} on ${deps.boxName ?? deps.boxId}`,\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip the\n // confirm prompt — but only with a valid scope-matched, params-hash-bound\n // one-time token. If a token is *present* but invalid (mutated args,\n // replayed, expired), reject hard: that's an attack signal. Only fall\n // through to the prompt when no token was claimed.\n const tokenClaimedGit = typeof params.hostInitiated === 'string';\n const incomingHashGit = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimedGit &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n 'git.push',\n incomingHashGit,\n ) ?? false);\n if (action.method === 'git.push' && !bypassPushGate && tokenClaimedGit && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (\n action.method === 'git.push' &&\n !bypassPushGate &&\n !hostInitiatedOk &&\n deps.prompts &&\n deps.subscribers\n ) {\n // Cloud-specific fallback: when no SSE subscriber is attached the prompt\n // would block indefinitely (the user has nothing to answer in). Choose\n // up-front whether to auto-deny (default) or auto-approve based on env\n // — same env knob shape as `AGENTBOX_PROMPT`. The decision is bounded\n // by `AGENTBOX_GIT_PUSH_NO_SUB`: 'deny' (default), 'allow', or 'prompt'\n // (block anyway, legacy behavior).\n const hasSubscriber = deps.subscribers.forBox(deps.boxId).length > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GIT_PUSH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GIT_PUSH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.('git.push auto-approved (no subscribers, AGENTBOX_GIT_PUSH_NO_SUB=allow)');\n // Fall through to the actual push.\n } else {\n // 'prompt' or anything else: legacy blocking behavior with a TTL so\n // a never-attaching user doesn't wedge the executor forever.\n const verdict = await askPrompt(\n deps.prompts,\n deps.subscribers,\n deps.boxId,\n {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n { ttlMs: 5 * 60 * 1000 },\n );\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-git-rpc-'));\n const hostBundle = join(stage, 'op.bundle');\n const remoteBundle = '/tmp/agentbox-rpc.bundle';\n try {\n if (action.method === 'git.push') {\n // 2a. Bundle the per-box branch inside the sandbox.\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundle)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return { exitCode: make.exitCode, stdout: '', stderr: `bundle create failed: ${make.stderr || make.stdout}` };\n }\n // 2b. Download to host tmp.\n await backend.downloadFile(handle, remoteBundle, hostBundle);\n // 3. Fast-forward the host repo's per-box branch ref to the sandbox tip.\n const fetch = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'fetch', hostBundle, `${branch}:${branch}`],\n { reject: false },\n );\n if (fetch.exitCode !== 0) {\n return {\n exitCode: fetch.exitCode ?? 1,\n stdout: fetch.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${fetch.stderr ?? ''}`,\n };\n }\n // 4. Real push. Args are user-controlled (`agentbox-ctl git push --\n // <args>`); pass them through to git on the host. Remote defaults to\n // 'origin'; the bundle's branch is the explicit refspec.\n const remote = resolveRemote(params.remote);\n const argv = ['-C', lookup.workspacePath, 'push', remote, branch];\n argv.push(...sanitizeGitArgs(params.args));\n const push = await execa('git', argv, { reject: false });\n let pushStderr = push.stderr ?? '';\n // After a successful push, sync the box's view of origin to match what\n // a normal local `git push -u` would have left behind: write the pushed\n // tip into the box's `refs/remotes/origin/<branch>` and set the branch\n // upstream to track it. Without this, Claude Code's PR badge sees no\n // upstream on the branch and doesn't fetch / display the PR. Per-box\n // scratch branches (`agentbox/<name>`) skip the sync — they're\n // local-only by design.\n if ((push.exitCode ?? 1) === 0 && !isScratchBranch(branch)) {\n try {\n const sha = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'rev-parse', branch],\n { reject: false },\n );\n const shaText = (sha.stdout ?? '').trim();\n if (sha.exitCode === 0 && shaText.length > 0) {\n const updateRef = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} update-ref ${remoteTrackingRef(remote, branch)} ${shellQuote(shaText)}`,\n );\n if (updateRef.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box update-ref ${remoteTrackingRef(remote, branch)} failed: ${updateRef.stderr || updateRef.stdout}`;\n }\n const setUpstream = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} branch --set-upstream-to=${upstreamRef(remote, branch)} ${shellQuote(branch)}`,\n );\n if (setUpstream.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box --set-upstream-to=${upstreamRef(remote, branch)} failed: ${setUpstream.stderr || setUpstream.stdout}`;\n }\n } else {\n pushStderr += `\\nrelay: post-push rev-parse ${branch} failed on host; skipping in-box origin/upstream sync`;\n }\n } catch (err) {\n pushStderr += `\\nrelay: post-push in-box origin/upstream sync threw: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n return {\n exitCode: push.exitCode ?? 1,\n stdout: push.stdout ?? '',\n stderr: pushStderr,\n };\n }\n // git.fetch: host fetches origin, bundles, uploads, sandbox fetches.\n const remote = resolveRemote(params.remote);\n const hostFetch = await execa('git', ['-C', lookup.workspacePath, 'fetch', remote], { reject: false });\n if (hostFetch.exitCode !== 0) {\n return {\n exitCode: hostFetch.exitCode ?? 1,\n stdout: hostFetch.stdout ?? '',\n stderr: `host git fetch failed: ${hostFetch.stderr ?? ''}`,\n };\n }\n // Bundle origin's remote-tracking refs so the sandbox sees the updates.\n const bundle = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'bundle', 'create', hostBundle, `--all`],\n { reject: false },\n );\n if (bundle.exitCode !== 0) {\n return {\n exitCode: bundle.exitCode ?? 1,\n stdout: '',\n stderr: `host git bundle create failed: ${bundle.stderr ?? ''}`,\n };\n }\n await backend.uploadFile(handle, hostBundle, remoteBundle);\n const sandboxFetch = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} fetch ${shellQuote(remoteBundle)} '+refs/heads/*:refs/remotes/origin/*' --tags`,\n );\n return {\n exitCode: sandboxFetch.exitCode,\n stdout: sandboxFetch.stdout,\n stderr: sandboxFetch.stderr,\n };\n } finally {\n await rm(stage, { recursive: true, force: true });\n await backend\n .exec(handle, `rm -f ${shellQuote(remoteBundle)}`)\n .catch(() => {\n /* best-effort */\n });\n }\n}\n\n/** Local helper — sandbox-cloud's `quoteShellArg` would be a cross-package import. */\nfunction shellQuote(arg: string): string {\n if (arg.length === 0) return \"''\";\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg)) return arg;\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Host-side helpers for the `gh.pr.*` RPCs (PR create / view / list / comment /\n * review / merge / checkout / close / reopen). The relay reuses the host's\n * `gh` install + auth: the in-box agent has no GitHub token, the host does.\n *\n * Same decoupling philosophy as `handleGitRpc`'s direct `git` spawn — we shell\n * out to `gh` with a known `cwd` (the host main repo) so `gh` infers the\n * GitHub repo from `git remote -v` and uses the user's authenticated gh\n * identity. No new credential plumbing inside the box.\n *\n * Lives in its own file so both `server.ts` (docker path) and `host-actions.ts`\n * (cloud path) can share `assertGhReady` + `runHostGh` + the `checkout`\n * guards without creating an import cycle.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { GitRpcResult } from './types.js';\n\n/** Whitelisted subset of `gh pr` ops exposed via RPC. Keep in sync with the ctl CLI. */\nexport const GH_PR_OPS = [\n 'create',\n 'view',\n 'list',\n 'diff',\n 'checks',\n 'comment',\n 'review',\n 'merge',\n 'checkout',\n 'close',\n 'reopen',\n] as const;\n\nexport type GhPrOp = (typeof GH_PR_OPS)[number];\n\nexport function isGhPrOp(value: string): value is GhPrOp {\n return (GH_PR_OPS as readonly string[]).includes(value);\n}\n\n/** Read-only ops never trigger the host confirmation prompt. */\nexport const GH_PR_READ_ONLY_OPS: ReadonlySet<GhPrOp> = new Set([\n 'view',\n 'list',\n 'diff',\n 'checks',\n]);\n\n/**\n * `gh pr` write ops that auto-approve under `box.autoApproveSafeHostActions`:\n * opening a PR for the box's branch (the relay forces `--head <box-branch>`, so\n * it can only ever target the box's own work) and commenting on a PR. The more\n * consequential writes (`review`, `close`, `reopen`, and especially `merge` /\n * `checkout`) are deliberately excluded — they keep prompting.\n */\nexport const GH_PR_SAFE_AUTO_APPROVE_OPS: ReadonlySet<GhPrOp> = new Set(['create', 'comment']);\n\n/**\n * Whitelisted subset of `gh run` ops exposed via RPC. `list` / `view` are\n * read-only; `rerun` re-triggers CI (a write — gated by the host confirm\n * prompt). `watch` is deliberately absent: it blocks until the run finishes,\n * which doesn't fit the relay's buffered request/response model (the in-box\n * `gh-shim` rejects it and points users at `gh run view`).\n */\nexport const GH_RUN_OPS = ['list', 'view', 'rerun'] as const;\n\nexport type GhRunOp = (typeof GH_RUN_OPS)[number];\n\nexport function isGhRunOp(value: string): value is GhRunOp {\n return (GH_RUN_OPS as readonly string[]).includes(value);\n}\n\n/** Read-only `gh run` ops never trigger the host confirmation prompt. */\nexport const GH_RUN_READ_ONLY_OPS: ReadonlySet<GhRunOp> = new Set(['list', 'view']);\n\n// The PR review-comment endpoints. GET lists inline review comments; POST adds\n// one (the thing `gh pr comment` can't do). `…/comments/:id/replies` replies to\n// a review comment. The optional trailing `(\\?…)` lets agents embed GET query\n// params in the path (e.g. `…/comments?per_page=50`) rather than via field flags.\nconst PR_REVIEW_COMMENT = /^repos\\/[^/]+\\/[^/]+\\/pulls\\/\\d+\\/comments(\\?.*)?$/;\nconst PR_REVIEW_COMMENT_REPLY =\n /^repos\\/[^/]+\\/[^/]+\\/pulls\\/\\d+\\/comments\\/\\d+\\/replies(\\?.*)?$/;\n\n/**\n * `gh api` endpoints on which POST (create a comment) is proxied — unprompted,\n * since comments are low-risk. Kept separate from the read allowlist so adding\n * a read-only endpoint there later doesn't widen the POST surface.\n */\nexport const GH_API_WRITE_ALLOWED_ENDPOINTS: readonly RegExp[] = [\n PR_REVIEW_COMMENT,\n PR_REVIEW_COMMENT_REPLY,\n];\n\n/**\n * Allowlist of `gh api` endpoint patterns the relay will proxy at all (the\n * overall gate). Superset of the write-allowed list; meant to grow one\n * deliberate entry at a time. GET is allowed on every entry; POST only on the\n * write-allowed subset (see `refuseGhApiCall`).\n */\nexport const GH_API_ALLOWED_ENDPOINTS: readonly RegExp[] = [...GH_API_WRITE_ALLOWED_ENDPOINTS];\n\n/** True when `endpoint` matches an allowlisted `gh api` pattern (proxied at all). */\nexport function isAllowedGhApiEndpoint(endpoint: string): boolean {\n return GH_API_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));\n}\n\n/** True when POST is permitted on `endpoint` (the comment endpoints). */\nexport function isWriteAllowedGhApiEndpoint(endpoint: string): boolean {\n return GH_API_WRITE_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));\n}\n\n/** Strip a leading slash so `/repos/...` and `repos/...` both match. */\nfunction normalizeGhApiEndpoint(endpoint: string): string {\n return endpoint.replace(/^\\/+/, '');\n}\n\n/** Ready-to-send refusal when a `gh api` endpoint isn't on the allowlist. */\nexport const GH_API_ENDPOINT_REFUSAL: GitRpcResult = {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh api: endpoint not allowlisted. Proxied: GET on ' +\n 'repos/:owner/:repo/pulls/:number/comments (and /:id/replies); POST to those ' +\n 'endpoints to add a review comment.\\n',\n};\n\n/**\n * Endpoint-aware `gh api` policy. Returns a ready-to-send refusal, or `null`\n * when the call may proceed. The caller has already checked the endpoint is on\n * `GH_API_ALLOWED_ENDPOINTS`.\n *\n * - GET → allowed everywhere on the allowlist.\n * - POST → allowed only on the write-allowed comment endpoints (unprompted).\n * - PATCH/PUT/DELETE/etc. → refused.\n * - `--input` → refused: the host `gh` runs with stdin ignored and a box-side\n * file path wouldn't exist on the host, so it can't cross the relay. Agents\n * pass fields via `-f`/`-F`.\n *\n * `gh` uses Go's pflag, which accepts a short flag's value glued on (`-XPOST`,\n * `-fbody=hi`) and the `=` form (`-X=POST`, `--method=POST`) as well as the\n * space-separated form. The box-side shim is the convenience gate; this relay\n * guard is the security boundary for a direct `agentbox-ctl` call, so it\n * recognizes every spelling.\n */\nexport function refuseGhApiCall(endpoint: string, args: string[]): GitRpcResult | null {\n const refuse = (reason: string): GitRpcResult => ({\n exitCode: 65,\n stdout: '',\n stderr: `gh api: ${reason}\\n`,\n });\n\n let explicitMethod: string | null = null;\n let hasFieldFlag = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n // --method / -X with a separately-tokenized value.\n if (arg === '-X' || arg === '--method') {\n explicitMethod = args[i + 1] ?? '';\n i++; // consumed the value\n continue;\n }\n // --method=VALUE / -X=VALUE / -XVALUE (glued short form).\n if (arg.startsWith('--method=')) {\n explicitMethod = arg.slice('--method='.length);\n continue;\n }\n if (arg.startsWith('-X') && arg.length > 2) {\n explicitMethod = arg.slice(2).replace(/^=/, '');\n continue;\n }\n // `--input` (stdin/file body) can't traverse the relay — refuse outright.\n // Its spaced value (if any) is irrelevant; we return before consuming it.\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\"'--input' (stdin/file body) isn't supported through the relay; use -f/-F fields\");\n }\n // Field flags auto-switch gh api to POST. The SPACED forms take the next\n // token as their value, so consume it — otherwise a method-looking value\n // (e.g. `-f -X=GET`, where pflag binds `-X=GET` as `-f`'s value and POSTs)\n // would be misread as a real `--method` next iteration and downgrade the\n // detected method to GET, slipping a POST past a future read-only endpoint.\n if (arg === '-f' || arg === '-F' || arg === '--field' || arg === '--raw-field') {\n hasFieldFlag = true;\n i++; // consume the value token\n continue;\n }\n // Glued field forms carry their value inline (`-fbody=hi`, `--field=…`). No\n // read-only flag starts with -f / -F, so the prefix match is safe.\n if (arg.startsWith('-f') || arg.startsWith('-F') || arg.startsWith('--field=') || arg.startsWith('--raw-field=')) {\n hasFieldFlag = true;\n }\n }\n\n const method = (explicitMethod ?? (hasFieldFlag ? 'POST' : 'GET')).toUpperCase();\n if (method === 'GET') return null;\n if (method === 'POST') {\n if (isWriteAllowedGhApiEndpoint(endpoint)) return null;\n return refuse(\n `POST is only proxied to PR review-comment endpoints (repos/:o/:r/pulls/:n/comments[/:id/replies]), not '${endpoint}'`,\n );\n }\n return refuse(`method '${method}' is not proxied — only GET, and POST to comment endpoints, are allowed`);\n}\n\n/**\n * Default `gh pr create`'s `--head` to the box's branch so the PR is for the\n * box's work, not whatever the host main repo happens to have checked out\n * (`gh` infers head from the cwd's HEAD, which is the user's own branch — or\n * an untracked one, which aborts with \"you must first push the current branch\n * to a remote, or use the --head flag\"). Only injected for `create`, only when\n * the caller didn't already pass `--head` (or its `-H` shorthand), and only when we resolved a real\n * branch (not empty / detached `HEAD`). The host CLI's `agentbox git pr create`\n * already injects this; the relay covers the in-box `agentbox-ctl git pr` /\n * `gh pr` path, which forwards args verbatim.\n */\nexport function injectPrCreateHead(\n op: GhPrOp,\n branch: string | undefined,\n args: string[],\n): string[] {\n if (op !== 'create') return args;\n if (!branch || branch === 'HEAD') return args;\n if (hasHeadArg(args)) return args;\n return ['--head', branch, ...args];\n}\n\nfunction hasHeadArg(args: string[]): boolean {\n // `gh pr create` accepts `--head`, `--head=<b>`, and the `-H` shorthand in\n // its `-H <b>` / `-H<b>` / `-H=<b>` forms. Recognize all so an explicit head\n // neither gets double-injected nor triggers the no-head refusal.\n return args.some((a) => a === '--head' || a.startsWith('--head=') || a.startsWith('-H'));\n}\n\n/**\n * True when the caller passed an explicit `--head`/`-H` on a `gh pr create`.\n * The safe-subset auto-approve only covers a `create` with NO explicit head:\n * the relay then forces `--head` to the box's sanctioned branch, so the PR can\n * only ever target the box's own work. An explicit head (which could name any\n * branch, e.g. `main`) falls back to the confirm prompt.\n */\nexport function prCreateHasExplicitHead(op: GhPrOp, args: string[]): boolean {\n return op === 'create' && hasHeadArg(args);\n}\n\n/**\n * True when a `gh pr create` would run with no `--head` — i.e. we couldn't\n * resolve the box's branch to inject and the caller didn't pass one. The\n * relay must refuse rather than let `gh` fall back to the host repo's\n * *checked-out* branch, which would open a PR for the wrong branch.\n */\nexport function prCreateNeedsHead(op: GhPrOp, args: string[]): boolean {\n return op === 'create' && !hasHeadArg(args);\n}\n\n/** Ready-to-send refusal for a `create` that has no resolvable `--head`. */\nexport const PR_CREATE_NO_HEAD_REFUSAL: GitRpcResult = {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh pr create: refusing to run without --head — could not resolve this ' +\n \"box's branch, and falling back to the host repo's checked-out branch \" +\n 'would open a PR for the wrong branch. Ensure the box branch is pushed, ' +\n 'or pass --head <branch> explicitly.\\n',\n};\n\n/** Wire params for every `gh.pr.<op>` method. Mirrors the new ctl command surface. */\nexport interface GhPrRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv (`--title`, `--body`, `--label`, `--draft`, `--json`, …). */\n args?: string[];\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking `agentbox git pr <op> <box>`. Validated against the\n * relay's in-memory store, scoped to `(boxId, method=gh.pr.<op>)`;\n * consumed on match and the confirm prompt is skipped. Boxes cannot mint\n * tokens (admin endpoint is loopback-only). `AGENTBOX_GH_FORCE` /\n * `AGENTBOX_GH_PR_CHECKOUT` opt-ins still apply — destructive guards do\n * not weaken when host-initiated.\n */\n hostInitiated?: string;\n}\n\n/** Wire params for every `gh.run.<op>` method. In-box surface only (no token). */\nexport interface GhRunRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv (`--json`, `--limit`, `<run-id>`, …). */\n args?: string[];\n}\n\n/** Wire params for the `gh.api` method. Read-only, allowlisted endpoints. */\nexport interface GhApiRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** The REST endpoint, e.g. `repos/:owner/:repo/pulls/:number/comments`. */\n endpoint?: string;\n /** Pass-through argv (`--jq`, `--paginate`, `-H`, …). */\n args?: string[];\n}\n\nconst GH_RPC_TIMEOUT_MS = 120_000;\nconst GH_READY_CACHE_TTL_MS = 60_000;\n\ninterface GhReadyCache {\n /** null on success; a ready-to-send error envelope when gh isn't usable. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\nlet ghReadyCache: GhReadyCache | undefined;\n\n/**\n * Returns `null` when the host has a usable, authenticated `gh`. Otherwise\n * returns a ready-to-send `{ exitCode, stdout, stderr }` envelope describing\n * what's missing. Cached for ~60s so a burst of PR ops doesn't reprobe gh on\n * every call.\n *\n * - `gh` missing → exit 127 (matches Bash's \"command not found\").\n * - `gh` present but `gh auth status` non-zero → exit 4 (gh's own conventional\n * \"not logged in\" exit code).\n *\n * We don't pass `--hostname github.com` to `auth status` — agents pointed at\n * a GitHub Enterprise host should also pass. Any authed host is good enough.\n */\nexport async function assertGhReady(): Promise<GitRpcResult | null> {\n const now = Date.now();\n if (ghReadyCache && ghReadyCache.expiresAt > now) {\n return ghReadyCache.result;\n }\n const result = await probeGh();\n ghReadyCache = { result, expiresAt: now + GH_READY_CACHE_TTL_MS };\n return result;\n}\n\n/** Test-only: clear the readiness cache between cases. */\nexport function _resetGhReadyCacheForTests(): void {\n ghReadyCache = undefined;\n}\n\nasync function probeGh(): Promise<GitRpcResult | null> {\n const version = await runHostGh(['--version'], process.cwd(), 10_000);\n if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: 'gh not installed on host (https://cli.github.com)\\n',\n };\n }\n if (version.exitCode !== 0) {\n return {\n exitCode: version.exitCode,\n stdout: '',\n stderr: `gh --version failed: ${version.stderr || version.stdout}`.trimEnd() + '\\n',\n };\n }\n // gh authenticates directly from GH_TOKEN/GITHUB_TOKEN in the environment and\n // ignores any stored `gh auth login`. When a token is supplied that way with\n // no stored login, `gh auth status` would falsely report \"not logged in\" even\n // though every API call succeeds. Treat a present token as authenticated.\n if ((process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? '').length > 0) {\n return null;\n }\n const auth = await runHostGh(['auth', 'status'], process.cwd(), 15_000);\n if (auth.exitCode !== 0) {\n return {\n exitCode: 4,\n stdout: '',\n stderr: 'gh not authenticated on host (run `gh auth login`)\\n',\n };\n }\n return null;\n}\n\n/**\n * Spawn `gh` on the host with the given argv inside `cwd`. Returns the\n * standard `{ exitCode, stdout, stderr }` envelope. Self-contained\n * (doesn't call into `server.ts`'s `runHostCommand`) so this module has no\n * import dependency on the server module — keeps the relay's two RPC\n * dispatch paths (docker `/rpc` and cloud `executeCloudAction`) from\n * importing each other.\n */\nexport function runHostGh(\n args: string[],\n cwd: string,\n timeoutMs: number = GH_RPC_TIMEOUT_MS,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('gh', args, {\n cwd,\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: gh command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (gh missing) lands here too; surface as exit 127 to match shell semantics.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/**\n * Pre-flight for `gh.pr.checkout`. Refuses when:\n * - the host repo has uncommitted changes (clobbers WIP), or\n * - HEAD is currently any registered per-box branch (`agentbox/<name>`) —\n * the box's bind-mounted `.git/HEAD` would silently flip with the host.\n *\n * Returns a ready-to-send error envelope on refusal, or `null` to proceed.\n */\nexport async function checkoutGuards(\n hostMainRepo: string,\n registeredBranches: readonly string[],\n): Promise<GitRpcResult | null> {\n const status = await runGitProbe(['-C', hostMainRepo, 'status', '--porcelain']);\n if (status.exitCode !== 0) {\n return {\n exitCode: status.exitCode,\n stdout: '',\n stderr: `gh pr checkout: failed to inspect host repo: ${status.stderr || status.stdout}`.trimEnd() + '\\n',\n };\n }\n if (status.stdout.trim().length > 0) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} has uncommitted changes; refusing to switch branches\\n`,\n };\n }\n const head = await runGitProbe(['-C', hostMainRepo, 'rev-parse', '--abbrev-ref', 'HEAD']);\n if (head.exitCode !== 0) {\n return {\n exitCode: head.exitCode,\n stdout: '',\n stderr: `gh pr checkout: failed to resolve HEAD: ${head.stderr || head.stdout}`.trimEnd() + '\\n',\n };\n }\n const currentBranch = head.stdout.trim();\n if (registeredBranches.includes(currentBranch)) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} is on registered box branch ${currentBranch}; refusing (would corrupt the bind-mounted box HEAD)\\n`,\n };\n }\n return null;\n}\n\nfunction runGitProbe(args: string[]): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('git', args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n resolve({ exitCode: 127, stdout, stderr: stderr + String(err.message ?? err) });\n });\n child.on('close', (code) => {\n resolve({ exitCode: code ?? -1, stdout, stderr });\n });\n });\n}\n\n/**\n * `merge` is the most destructive op. `AGENTBOX_PROMPT=off` auto-`y`s every\n * other prompt in the relay; for `gh pr merge` we refuse that bypass unless\n * the user opted in via `AGENTBOX_GH_FORCE=1`. Returns a ready-to-send envelope\n * when the bypass should be refused; `null` otherwise.\n */\nexport function refuseMergeBypass(op: GhPrOp): GitRpcResult | null {\n if (op !== 'merge') return null;\n if (process.env['AGENTBOX_PROMPT'] !== 'off') return null;\n if (process.env['AGENTBOX_GH_FORCE'] === '1') return null;\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'gh pr merge: AGENTBOX_PROMPT=off bypass requires AGENTBOX_GH_FORCE=1 (merge is irreversible)\\n',\n };\n}\n\n/**\n * `gh pr checkout` is gated behind an explicit opt-in env: it mutates the\n * host main repo's `HEAD`, which the bind-mounted box sees too. Returns a\n * ready-to-send envelope when the op should be refused; `null` otherwise.\n */\nexport function refuseCheckoutByDefault(op: GhPrOp): GitRpcResult | null {\n if (op !== 'checkout') return null;\n if (process.env['AGENTBOX_GH_PR_CHECKOUT'] === 'allow') return null;\n return {\n exitCode: 13,\n stdout: '',\n stderr:\n 'gh pr checkout: disabled by default; set AGENTBOX_GH_PR_CHECKOUT=allow to enable\\n',\n };\n}\n","/**\n * Host-initiated RPC tokens.\n *\n * `agentbox git <op> <box>` runs on the host but ultimately triggers a\n * credentialed RPC (`git.push`, `gh.pr.<op>`, …) on the host-side relay.\n * Those RPCs normally surface a y/N confirm prompt to the user — the box\n * (and the agent inside it) is untrusted, so every push/PR must be approved.\n *\n * For host-initiated calls, the user has already typed the command on the\n * host, so re-prompting is just friction. But \"host-initiated\" must not be\n * something the box can claim by setting a flag — a malicious agent could\n * trivially abuse that. So instead the host CLI:\n *\n * 1. Computes a `paramsHash` of the exact params it's about to send.\n * 2. Mints a one-time token via the relay's loopback-only admin endpoint\n * `POST /admin/host-initiated/mint`, scoped to `(boxId, method, paramsHash)`.\n * 3. Passes the token to `agentbox-ctl` (via `--host-initiated-token`),\n * which forwards it in `params.hostInitiated` on the RPC.\n * 4. The relay re-hashes the incoming params (excluding `hostInitiated`),\n * compares against the minted hash, and only skips the prompt on a\n * full `(boxId, method, paramsHash)` match. The token is then consumed.\n *\n * Tokens are 32 random bytes (256 bits — collision/guessing safety), expire\n * after ~120s, and are one-shot.\n *\n * Failure-mode policy (enforced at each call site, not here):\n *\n * - `params.hostInitiated` absent → no token claimed; the RPC falls\n * through to the normal askPrompt path (the agent-initiated default).\n * - `params.hostInitiated` present but `consume()` returns false →\n * **reject the RPC outright** (exit code 10). The only way to obtain a\n * token is via the loopback-only mint endpoint; a token that doesn't\n * validate (wrong scope, mutated params, replayed, expired) is an\n * attack signal. Falling through to the prompt would (a) leak that the\n * attacker has a token, (b) bait the user into approving a call they\n * didn't initiate. Hard reject.\n *\n * ## Threat model\n *\n * The mint endpoint is loopback-only, so a box cannot mint its own tokens\n * (boxes see the relay on `host.docker.internal` or via cloud bridges,\n * never 127.0.0.1).\n *\n * The token is delivered to the box via `docker exec --argv agentbox-ctl …\n * --host-initiated-token <tok>`. /proc/<pid>/cmdline is world-readable on\n * Linux, so a malicious in-box process polling /proc COULD harvest the\n * token while agentbox-ctl is running. Without paramsHash binding the\n * attacker could then send their own RPC with the same token but *modified\n * args* (`--force` on push, altered `--title`/`--body` on PR create) and\n * win a race against the legit caller. paramsHash binding closes that gap:\n * the relay rejects any incoming params that don't hash to the minted hash,\n * so harvested tokens are only good for the exact params the host CLI\n * already authorized.\n *\n * Optional `paramsHash === undefined` mode exists for forward compatibility\n * (callers that don't need params binding); the production callers\n * (`agentbox git`) always pass a hash.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\n\nconst DEFAULT_TTL_MS = 120_000;\n\ninterface TokenRecord {\n boxId: string;\n method: string;\n /**\n * Hex SHA-256 of the canonicalized params the host CLI committed to\n * sending. Verified against the incoming `/rpc` params in `consume()`.\n * `null` means \"no params binding\" — only safe for calls where the\n * params surface is fully host-controlled (none in practice today).\n */\n paramsHash: string | null;\n expiresAt: number;\n}\n\n/**\n * Compute a stable SHA-256 of the JSON params, with keys sorted and the\n * `hostInitiated` field stripped (so the token-bearing call hashes the same\n * as the at-mint-time intended params). Stable hash regardless of key order\n * in the wire payload, regardless of whether `hostInitiated` is set.\n */\nexport function hashRpcParams(params: unknown): string {\n return createHash('sha256').update(canonicalJson(params)).digest('hex');\n}\n\nfunction canonicalJson(v: unknown): string {\n if (v === null) return 'null';\n if (typeof v === 'undefined') return 'null';\n if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';\n if (typeof v === 'boolean') return v ? 'true' : 'false';\n if (typeof v === 'string') return JSON.stringify(v);\n if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']';\n if (typeof v === 'object') {\n const entries = Object.entries(v as Record<string, unknown>)\n .filter(([k]) => k !== 'hostInitiated')\n .filter(([, val]) => val !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return (\n '{' +\n entries.map(([k, val]) => JSON.stringify(k) + ':' + canonicalJson(val)).join(',') +\n '}'\n );\n }\n return 'null';\n}\n\nexport class HostInitiatedTokens {\n private readonly store = new Map<string, TokenRecord>();\n\n /**\n * Mint a fresh one-time token scoped to (boxId, method, paramsHash).\n * `paramsHash` MUST be supplied for any call surface where the box can\n * influence the eventual RPC params. Pass `null` only when there are no\n * params (no current call sites use this).\n */\n mint(\n boxId: string,\n method: string,\n paramsHash: string | null,\n ttlMs: number = DEFAULT_TTL_MS,\n ): string {\n const token = randomBytes(32).toString('hex');\n this.store.set(token, { boxId, method, paramsHash, expiresAt: Date.now() + ttlMs });\n return token;\n }\n\n /**\n * Returns true exactly once if `token` is a valid, unexpired token for the\n * given `(boxId, method)` AND the supplied `incomingParamsHash` matches\n * the hash bound at mint time. The token is removed on a successful match\n * (one-shot semantics). All failure modes return false — callers fall back\n * to the normal prompt path.\n */\n consume(\n token: string | undefined,\n boxId: string,\n method: string,\n incomingParamsHash: string,\n ): boolean {\n if (!token || typeof token !== 'string') return false;\n const record = this.store.get(token);\n if (!record) return false;\n if (record.expiresAt < Date.now()) {\n this.store.delete(token);\n return false;\n }\n if (record.boxId !== boxId || record.method !== method) return false;\n // paramsHash null = \"no binding\"; otherwise enforce exact match.\n if (record.paramsHash !== null && record.paramsHash !== incomingParamsHash) {\n return false;\n }\n this.store.delete(token);\n return true;\n }\n\n /** Drop expired entries. Cheap; safe to call periodically. */\n gc(): void {\n const now = Date.now();\n for (const [token, record] of this.store) {\n if (record.expiresAt < now) this.store.delete(token);\n }\n }\n\n /** Test-only: number of live tokens. */\n size(): number {\n return this.store.size;\n }\n}\n","/**\n * Shared `cp.toHost` / `cp.fromHost` wire handling for both the docker `/rpc`\n * route (`server.ts`) and the cloud host-action queue (`host-actions.ts`).\n *\n * Both paths converge on the same move: normalize the wire params into\n * sources + destination, then re-shell the installed `agentbox cp` host CLI\n * (which owns the tar pipe, excludes, the size guard, and provider routing).\n * Keeping the argv builder here means the docker and cloud paths can't drift.\n */\n\nimport type { CpRpcParams } from './types.js';\n\nexport type CpMethod = 'cp.toHost' | 'cp.fromHost';\n\n/**\n * Normalize the wire params into `{ sources, dest }`, tolerating the legacy\n * single-source `{ boxPath, hostPath }` shape sent by an older in-box\n * `agentbox-ctl` baked into a box image before multi-source support. Throws a\n * plain `Error` (message is safe to surface) on a malformed payload.\n */\nexport function normalizeCpParams(\n method: CpMethod,\n params: CpRpcParams | undefined,\n): { sources: string[]; dest: string } {\n if (!params) throw new Error('cp.* requires params');\n let sources = params.sources;\n let dest = params.dest;\n // Legacy fallback: derive sources/dest from boxPath/hostPath by direction.\n if (!Array.isArray(sources) || sources.length === 0 || typeof dest !== 'string') {\n if (typeof params.boxPath === 'string' && typeof params.hostPath === 'string') {\n if (method === 'cp.toHost') {\n sources = [params.boxPath];\n dest = params.hostPath;\n } else {\n sources = [params.hostPath];\n dest = params.boxPath;\n }\n }\n }\n if (!Array.isArray(sources) || sources.length === 0 || sources.some((s) => typeof s !== 'string')) {\n throw new Error('cp.* requires a non-empty {sources} string array (or legacy {boxPath, hostPath})');\n }\n if (typeof dest !== 'string') {\n throw new Error('cp.* requires a {dest} string (or legacy {boxPath, hostPath})');\n }\n return { sources, dest };\n}\n\n/** Translate the optional cp flags back into `agentbox cp` argv flags. */\nexport function cpFlags(params: CpRpcParams): string[] {\n const flags: string[] = [];\n for (const pat of params.exclude ?? []) flags.push('--exclude', pat);\n if (params.defaultExcludes === false) flags.push('--no-default-excludes');\n if (params.yes) flags.push('--yes');\n return flags;\n}\n\n/**\n * Build the `agentbox cp <src...> <dst>` argv (leading `cp`, no node/entry) plus\n * a human-facing detail line for the consent prompt. The box side carries the\n * `<boxName>:` prefix; host paths are resolved to absolute via `resolveHost`\n * (against the box workspace) so the prompt shows the real destination and the\n * argv doesn't depend on the re-shelled process's cwd.\n */\nexport function buildCpArgv(opts: {\n method: CpMethod;\n boxName: string;\n sources: string[];\n dest: string;\n resolveHost: (p: string) => string;\n flags: string[];\n}): { argv: string[]; detail: string; contextArgv: string[] } {\n const { method, boxName, sources, dest, resolveHost, flags } = opts;\n if (method === 'cp.toHost') {\n const hostAbs = resolveHost(dest);\n const boxArgs = sources.map((s) => `${boxName}:${s}`);\n return {\n argv: ['cp', ...boxArgs, hostAbs, ...flags],\n detail: `${sources.join(', ')} -> ${hostAbs}`,\n contextArgv: [...sources, hostAbs],\n };\n }\n const hostAbsSrcs = sources.map(resolveHost);\n return {\n argv: ['cp', ...hostAbsSrcs, `${boxName}:${dest}`, ...flags],\n detail: `${hostAbsSrcs.join(', ')} -> ${dest}`,\n contextArgv: [...hostAbsSrcs, dest],\n };\n}\n","/**\n * Generic host-side machinery for the `integration.<service>.<op>` RPCs —\n * the relay-side spine that turns a descriptor in `@agentbox/integrations`\n * into a host-CLI invocation with read/write classification and write\n * gating. Companion to `gh.ts`: same spawn/probe/cache shape, but driven\n * by a descriptor (so each service is one small file in\n * `@agentbox/integrations/connectors/`, not a new pair of files here).\n *\n * Lives in its own file so both `server.ts` (docker `POST /rpc`) and\n * `host-actions.ts` (cloud path) share the same helpers — same cycle-\n * avoidance reasoning as `gh.ts`.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { IntegrationConnector, IntegrationOp } from '@agentbox/integrations';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport type { GitRpcResult } from './types.js';\n\n/** Wire params for every `integration.<service>.<op>` method. Mirrors GhPrRpcParams. */\nexport interface IntegrationRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv forwarded to the host CLI (after `op.buildArgv`). */\n args?: string[];\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking `agentbox-ctl integration <svc> <op>`. Validated against\n * the relay's in-memory store, scoped to `(boxId, method=integration.<svc>.<op>)`\n * and the params-hash; consumed on match and the confirm prompt is\n * skipped. Boxes cannot mint tokens (admin endpoint is loopback-only).\n * Reserved for T1's host-CLI surface (T3+) — agent-initiated ctl calls\n * never pass it; the `askPrompt` gate applies.\n */\n hostInitiated?: string;\n}\n\nconst INTEGRATION_RPC_TIMEOUT_MS = 120_000;\nconst INTEGRATION_READY_CACHE_TTL_MS = 60_000;\n\n/**\n * `integration.<service>.<op>` wire shape:\n * - service: lowercase ASCII, matches IntegrationConnector.service.\n * - op: lowercase ASCII + digits + dots; first char a letter\n * (excludes leading `.` shapes like `integration.notion..api`).\n *\n * Dots are allowed in the op portion so descriptor ops can use a\n * dotted-namespace form (e.g. `page.create`) without colliding with the\n * `integration.<svc>.<op>` delimiter — the parser splits on the FIRST two\n * dots and keeps everything after as the op (so e.g.\n * `integration.notion.page.create` parses to `{service:'notion', op:'page.create'}`).\n */\nconst INTEGRATION_METHOD_RE = /^integration\\.([a-z][a-z0-9]*)\\.([a-z][a-z0-9.]*)$/;\n\nexport interface ParsedIntegrationMethod {\n service: string;\n op: string;\n}\n\n/** Parse `integration.<service>.<op>`; returns null on shape miss. */\nexport function parseIntegrationMethod(method: string): ParsedIntegrationMethod | null {\n const m = INTEGRATION_METHOD_RE.exec(method);\n if (!m) return null;\n const service = m[1]!;\n const op = m[2]!;\n // Disallow a trailing dot (`integration.notion.api.`) or consecutive dots\n // (`integration.notion.page..create`) — the regex's `[a-z0-9.]*` is\n // permissive on purpose; we reject the degenerate shapes here.\n if (op.endsWith('.') || op.includes('..')) return null;\n return { service, op };\n}\n\ninterface IntegrationReadyCacheEntry {\n /** null on success; ready-to-send error envelope when the binary isn't usable. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\nconst integrationReadyCache = new Map<string, IntegrationReadyCacheEntry>();\n\n/**\n * Returns `null` when the host has the connector's binary on PATH;\n * otherwise a ready-to-send `{ exitCode, stdout, stderr }` envelope\n * describing what's missing. Cached per `connector.hostBin` for ~60s so a\n * burst of integration ops doesn't reprobe on every call (same TTL as\n * `assertGhReady`).\n *\n * - binary missing → exit 127 (matches Bash's \"command not found\").\n * - binary present but `--version` non-zero → propagate that exit.\n *\n * Auth-status is intentionally NOT probed here — `ntn` exits non-zero with\n * a clear \"not logged in\" message on every call when unauthed, which\n * surfaces directly through the relay's stdout/stderr passthrough. A\n * dedicated `auth` probe is the `agentbox doctor` flow (T3), not the\n * per-call hot path.\n */\nexport async function assertIntegrationReady(\n connector: IntegrationConnector,\n): Promise<GitRpcResult | null> {\n const now = Date.now();\n const cached = integrationReadyCache.get(connector.hostBin);\n if (cached && cached.expiresAt > now) return cached.result;\n const result = await probeIntegration(connector);\n integrationReadyCache.set(connector.hostBin, {\n result,\n expiresAt: now + INTEGRATION_READY_CACHE_TTL_MS,\n });\n return result;\n}\n\n/** Test-only: clear the readiness cache between cases. */\nexport function _resetIntegrationReadyCacheForTests(): void {\n integrationReadyCache.clear();\n}\n\nasync function probeIntegration(\n connector: IntegrationConnector,\n): Promise<GitRpcResult | null> {\n const version = await runHostBinary(\n connector,\n [...connector.detect.versionArgs],\n process.cwd(),\n 10_000,\n );\n if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: `${connector.hostBin} not installed on host (install the ${connector.service} CLI on the host)\\n`,\n };\n }\n if (version.exitCode !== 0) {\n return {\n exitCode: version.exitCode,\n stdout: '',\n stderr:\n `${connector.hostBin} ${connector.detect.versionArgs.join(' ')} failed: ` +\n (version.stderr || version.stdout).trimEnd() +\n '\\n',\n };\n }\n return null;\n}\n\n/**\n * Spawn the connector's host binary with the given op + user args inside\n * `cwd`. Returns the standard `{ exitCode, stdout, stderr }` envelope.\n * `op.buildArgv` (when supplied) shapes the host CLI's subcommand path;\n * absent, the user args are forwarded verbatim. A connector-declared\n * `<SERVICE>_*` env override (when present — none set today) is merged onto\n * `process.env` via `mergeConnectorEnv`; a descriptor that tries to set an\n * env var outside its `<SERVICE>_*` namespace yields a typed exit-78 envelope\n * (sysexits EX_CONFIG) rather than throwing, so the docker /rpc and\n * cloud paths both surface the misconfiguration as a normal envelope.\n *\n * Self-contained (no import dependency on the rest of the relay), same\n * cycle-avoidance reasoning as `runHostGh` in `gh.ts`.\n */\nexport function runHostIntegration(\n connector: IntegrationConnector,\n op: IntegrationOp,\n args: readonly string[],\n cwd: string,\n timeoutMs: number = INTEGRATION_RPC_TIMEOUT_MS,\n): Promise<GitRpcResult> {\n const argv = op.buildArgv ? op.buildArgv(args) : [...args];\n return runHostBinary(connector, argv, cwd, timeoutMs);\n}\n\n/**\n * Merge the relay's `process.env` with the connector's declared overrides,\n * but only let the connector set env vars whose names are in its\n * `<SERVICE>_…` namespace (or other deliberately-shared names) — never\n * relay-controlled prefixes like `AGENTBOX_*`, `PATH`, `HOME`, etc. A\n * careless future descriptor cannot disable the relay's prompt gate or\n * rewrite PATH by setting `env: { AGENTBOX_PROMPT: 'off' }`.\n */\nfunction mergeConnectorEnv(connector: IntegrationConnector): NodeJS.ProcessEnv {\n if (!connector.env) return process.env;\n const allowedPrefix = `${connector.service.toUpperCase()}_`;\n const env: NodeJS.ProcessEnv = { ...process.env };\n for (const [key, value] of Object.entries(connector.env)) {\n if (!key.startsWith(allowedPrefix)) {\n throw new Error(\n `integration ${connector.service}: env key '${key}' not in '${allowedPrefix}*' namespace; descriptor cannot set it`,\n );\n }\n env[key] = value;\n }\n return env;\n}\n\nfunction runHostBinary(\n connector: IntegrationConnector,\n argv: readonly string[],\n cwd: string,\n timeoutMs: number,\n): Promise<GitRpcResult> {\n let env: NodeJS.ProcessEnv;\n try {\n env = mergeConnectorEnv(connector);\n } catch (err) {\n // Bad descriptor — return a typed envelope so the in-box ctl prints\n // the actual cause instead of an opaque relay \"internal error\" 500.\n return Promise.resolve({\n exitCode: 78,\n stdout: '',\n stderr: `${connector.hostBin}: ${err instanceof Error ? err.message : String(err)}\\n`,\n });\n }\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn(connector.hostBin, [...argv], {\n cwd,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: ${connector.hostBin} command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (binary missing) lands here too; surface as exit 127.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/** Ready-to-send refusal for an op not on the connector's allowlist. */\nexport function makeIntegrationOpRefusal(\n service: string,\n op: string,\n hostBin: string,\n knownOps: readonly string[],\n): GitRpcResult {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `integration ${service}: op '${op}' not on allowlist for ${hostBin}. ` +\n `Available: ${knownOps.join(', ')}\\n`,\n };\n}\n\n/**\n * Run the op's `refuseCall` pre-flight (e.g. `notion.api`'s GET-only check)\n * and lift its `{exitCode, stderr}` shape into the relay's full\n * `GitRpcResult`. Returns null when the call may proceed.\n */\nexport function refuseIntegrationCall(\n op: IntegrationOp,\n args: readonly string[],\n): GitRpcResult | null {\n const refusal = op.refuseCall?.(args);\n if (!refusal) return null;\n return { exitCode: refusal.exitCode, stdout: '', stderr: refusal.stderr };\n}\n\n/**\n * Returns null when the integration is enabled for the box's project (so the\n * dispatch may proceed), else a ready-to-send refusal envelope. Re-reads the\n * layered config fresh on every call so toggling\n * `integrations.<svc>.enabled` takes effect without bouncing the relay —\n * same approach `loadAutopauseConfig` uses for the autopause loop.\n *\n * Layered (cli/workspace/project/global/default) so a single project can opt\n * in without globally enabling Notion. Defaults to disabled — every\n * integration ships in the image but is inert until flipped on.\n *\n * Injectable `loader` keeps unit tests off-disk.\n */\nexport async function refuseIfIntegrationDisabled(\n service: string,\n cwd: string,\n loader: (cwd: string) => Promise<{\n effective: { integrations?: Record<string, { enabled?: boolean } | undefined> };\n }> = loadEffectiveConfig,\n): Promise<GitRpcResult | null> {\n let enabled = false;\n try {\n const cfg = await loader(cwd);\n enabled = cfg.effective.integrations?.[service]?.enabled === true;\n } catch {\n // A malformed config file should fail closed — the box can't do anything\n // useful with a half-loaded config, and the agent gets a clear message\n // either way.\n }\n if (enabled) return null;\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `${service} integration is disabled — enable with ` +\n `\\`agentbox config set --project integrations.${service}.enabled true\\`\\n`,\n };\n}\n","/**\n * Shared decision for auto-approving file transfers between a box and the host\n * under `box.autoApproveSafeHostActions`. Used by both the docker (`server.ts`)\n * and cloud (`host-actions.ts`) cp/download handlers so the containment + secret\n * policy can't drift between the two transports.\n *\n * The rule: a transfer auto-approves only when every host-side path it touches\n * resolves *inside the box's project folder* (`workspacePath`), following\n * symlinks. For a host->box copy, a secret-looking source additionally keeps the\n * prompt unless that exact file was already approved via the `carry:` block.\n * Anything else falls back to the interactive confirm — the prompt is never\n * removed, only skipped when provably safe.\n */\n\nimport { isContainedInWorkspace, looksLikeSecret, realpathSafe } from '@agentbox/core';\n\nexport interface TransferApproveInput {\n /** `box.autoApproveSafeHostActions` (false → always prompt). */\n enabled: boolean;\n /** The box's host project folder; relative paths already resolved against it. */\n workspacePath: string | undefined;\n /**\n * Resolved host-side paths the transfer touches: the *destination* for\n * box->host (cp.toHost / download), the *sources* for host->box (cp.fromHost).\n */\n hostPaths: string[];\n /** Apply the secret-file guard (host->box only). */\n checkSecret: boolean;\n /** realpath'd host sources already approved via `carry:` (secret exemption). */\n carried?: Set<string>;\n}\n\n/**\n * True when the transfer may skip the approval prompt. Conservative: any\n * uncontained path, any not-yet-carried secret source, an unknown workspace, or\n * the feature being disabled all return false (→ the caller prompts).\n */\nexport async function canAutoApproveTransfer(input: TransferApproveInput): Promise<boolean> {\n if (!input.enabled) return false;\n if (!input.workspacePath || input.hostPaths.length === 0) return false;\n for (const p of input.hostPaths) {\n if (!(await isContainedInWorkspace(p, input.workspacePath))) return false;\n if (input.checkSecret && looksLikeSecret(p)) {\n const real = await realpathSafe(p);\n if (!input.carried?.has(real)) return false;\n }\n }\n return true;\n}\n","/**\n * `HostActionQueue` — the box-mode relay's parking lot for host-only RPCs.\n * When the in-sandbox `/rpc` route receives `git.push` / `cp.*` / etc., it\n * cannot execute them locally (no host SSH keys, no host filesystem), so it\n * `enqueue`s and `await`s. The host's `CloudBoxPoller` drains via\n * `/bridge/poll`, executes on the host, and `resolve`s here via\n * `/bridge/action-result` — that resolves the awaited Promise and the\n * in-sandbox `/rpc` finally answers the in-box agent.\n *\n * Lifetime: per in-sandbox relay process; in-memory only. Actions outlive\n * individual polls (the queue is the source of truth, not the wire).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HostAction, HostActionResult } from './types.js';\n\ninterface Pending {\n action: HostAction;\n resolve: (r: HostActionResult) => void;\n /** True once a `/bridge/poll` has handed this action out. */\n delivered: boolean;\n}\n\n/**\n * Default max age for a parked action before it expires (15 minutes).\n * Picked to be longer than any reasonable interactive prompt + a host\n * restart window, but short enough that a forgotten queue doesn't replay\n * stale `git.push` attempts when the host relay rehydrates. Override per\n * queue instance for tests.\n */\nexport const DEFAULT_HOST_ACTION_MAX_AGE_MS = 15 * 60 * 1000;\n\nexport interface HostActionQueueOptions {\n /** Override the per-action expiry. Default {@link DEFAULT_HOST_ACTION_MAX_AGE_MS}. */\n maxAgeMs?: number;\n /** Clock injector (tests). */\n now?: () => number;\n}\n\nexport class HostActionQueue {\n private readonly map = new Map<string, Pending>();\n private readonly maxAgeMs: number;\n private readonly now: () => number;\n\n constructor(opts: HostActionQueueOptions = {}) {\n this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_HOST_ACTION_MAX_AGE_MS;\n this.now = opts.now ?? ((): number => Date.now());\n }\n\n /**\n * Park a host-only RPC and return a Promise that resolves when the host\n * poller posts the result back. Caller should `await` and forward the\n * result to the in-box client; there's intentionally no client-side\n * timeout (matches the existing in-box `postRpc`'s \"block while a prompt\n * is open\" semantics).\n */\n enqueue(boxId: string, method: string, params: unknown): Promise<HostActionResult> {\n const id = randomUUID();\n const action: HostAction = {\n id,\n boxId,\n method,\n params,\n createdAt: new Date(this.now()).toISOString(),\n };\n return new Promise<HostActionResult>((resolve) => {\n this.map.set(id, { action, resolve, delivered: false });\n });\n }\n\n /**\n * Return every action the host hasn't been handed yet, marking them\n * delivered. The poller is expected to execute them and POST back to\n * `/bridge/action-result`. Re-delivery on poller retry isn't needed —\n * the queue holds the Promise until `resolve` is called.\n *\n * Actions older than `maxAgeMs` expire here: their `resolve` is called\n * with an `exitCode: 124, stderr: 'expired'` result so the in-box RPC\n * unblocks, and they don't appear in the drained list. Keeps a host\n * relay restart from replaying a long-forgotten `git.push`.\n */\n drain(): HostAction[] {\n const now = this.now();\n const out: HostAction[] = [];\n for (const [id, p] of this.map) {\n const createdAt = Date.parse(p.action.createdAt);\n if (Number.isFinite(createdAt) && now - createdAt > this.maxAgeMs) {\n this.map.delete(id);\n p.resolve({\n exitCode: 124,\n stdout: '',\n stderr: `host action '${p.action.method}' expired before the host could execute it\\n`,\n });\n continue;\n }\n if (!p.delivered) {\n out.push(p.action);\n p.delivered = true;\n }\n }\n return out;\n }\n\n /**\n * Settle a parked action with the host's result. Idempotent: a duplicate\n * resolve on the same id is a no-op. Returns whether the id matched.\n */\n resolve(id: string, result: HostActionResult): boolean {\n const p = this.map.get(id);\n if (!p) return false;\n this.map.delete(id);\n p.resolve(result);\n return true;\n }\n\n size(): number {\n return this.map.size;\n }\n\n /** Test/diagnostic: get the action with this id (returns undefined when settled). */\n peek(id: string): HostAction | undefined {\n return this.map.get(id)?.action;\n }\n}\n","/**\n * A minimal in-process fan-out for the embedded hub UI. The hub's SSE route\n * (`/api/events`) subscribes; the relay calls `notify()` whenever the pending\n * approvals set changes (via `PendingPrompts.setOnChange`), so connected\n * browsers refresh without polling. No `EventEmitter` dependency — the surface\n * is just subscribe/notify.\n */\nexport class HubNotifier {\n private readonly listeners = new Set<() => void>();\n\n /** Register a listener; returns an unsubscribe fn. */\n subscribe(fn: () => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /** Fire every listener. A throwing listener never blocks the others. */\n notify(): void {\n for (const fn of this.listeners) {\n try {\n fn();\n } catch {\n /* a dead listener must not break the fan-out */\n }\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { PromptSubscribers } from './prompts.js';\nimport type { BoxNoticeEvent, NoticeKind } from './types.js';\n\n/**\n * Default lifespan of a notice when its owner never clears it explicitly.\n * Longer than the relay's checkpoint RPC timeout (600s) so a notice still\n * self-expires even if the host CLI is SIGKILLed before its `finally` runs.\n */\nconst DEFAULT_NOTICE_TTL_MS = 660_000;\n\ninterface NoticeEntry {\n ev: BoxNoticeEvent;\n boxId: string;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * In-memory per-box informational notices, broadcast over the same SSE\n * channel as confirmation prompts. Unlike {@link import('./prompts.js').PendingPrompts}\n * these are fire-and-forget: there is no awaited promise and no answer. A\n * notice marks a box as transiently busy (a checkpoint freezes it via\n * `docker commit`); the host wrapper renders a spinner so the user can\n * tell the box from stuck.\n *\n * Deliberately NOT gated by `AGENTBOX_PROMPT=off` (which `askPrompt`\n * honours): a notice is informational, not a consent gate, so suppressing\n * it would only hide useful feedback.\n */\nexport class BoxNotices {\n /** keyed by notice id. */\n private readonly entries = new Map<string, NoticeEntry>();\n\n constructor(private readonly subscribers: PromptSubscribers) {}\n\n /**\n * Register a notice for `boxId` and broadcast `notice-set`. At most one\n * notice per (box, kind) is kept — a fresh `set` for the same kind\n * replaces the previous one (and cancels its TTL timer so a stale timer\n * can't later fire a `notice-clear` racing the replacement). Returns the\n * generated notice id.\n */\n set(boxId: string, kind: NoticeKind, message: string, ttlMs?: number): string {\n for (const [id, entry] of this.entries) {\n if (entry.boxId === boxId && entry.ev.kind === kind) {\n clearTimeout(entry.timer);\n this.entries.delete(id);\n }\n }\n const ev: BoxNoticeEvent = { id: randomUUID(), kind, message };\n const ttl = typeof ttlMs === 'number' && ttlMs > 0 ? ttlMs : DEFAULT_NOTICE_TTL_MS;\n const timer = setTimeout(() => {\n // Safety net: a notice whose owner died without clearing it self-expires.\n if (this.entries.delete(ev.id)) {\n this.subscribers.broadcast(boxId, 'notice-clear', { id: ev.id });\n }\n }, ttl);\n if (typeof timer.unref === 'function') timer.unref();\n this.entries.set(ev.id, { ev, boxId, timer });\n this.subscribers.broadcast(boxId, 'notice-set', ev);\n return ev.id;\n }\n\n /**\n * Clear a notice by id. Idempotent: returns false when no such notice\n * exists (already cleared / expired). Broadcasts `notice-clear` on a hit.\n */\n clear(id: string): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n clearTimeout(entry.timer);\n this.entries.delete(id);\n this.subscribers.broadcast(entry.boxId, 'notice-clear', { id });\n return true;\n }\n\n /** Snapshot of active notices for a box; replayed to a new SSE subscriber. */\n forBox(boxId: string): BoxNoticeEvent[] {\n const out: BoxNoticeEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n","/**\n * Host-side handler for the ctl credential watcher's `credentials-updated`\n * events (see `packages/ctl/src/credentials-watcher.ts`). Claude's OAuth\n * refresh rotates the refresh token, so the moment one box refreshes, every\n * other copy (host backup, other boxes) is dead — this accepts the freshest\n * blob into `~/.agentbox/<agent>-credentials.json` (newest-wins) and fans it\n * out to all other boxes by spawning the host CLI\n * (`agentbox credentials propagate`), the same decoupling as the relay's\n * checkpoint/cp handlers.\n *\n * The payload carries a secret: callers must never append these events to the\n * event ring buffer (mirrors how `box-status` skips the ring).\n *\n * Concurrency: per-agent debounce (bursts collapse to one fan-out) + a\n * per-agent promise chain (fan-outs never overlap; a fresh accept during an\n * in-flight run schedules one more). The spawned CLI always reads the\n * *current* backup, so collapsed runs lose nothing.\n */\n\nimport { execa } from 'execa';\nimport {\n parseCredentialsUpdate,\n readCredentialBackup,\n shouldAcceptCredentialUpdate,\n writeCredentialBackup,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-core';\n\n/** Mirrors `CREDENTIALS_UPDATED_EVENT` in @agentbox/ctl (like `box-status`). */\nexport const CREDENTIALS_UPDATED_EVENT = 'credentials-updated';\n\nexport interface CredentialsFanoutDeps {\n log: (msg: string) => void;\n /** Debounce before spawning the propagate CLI. Default 3000ms. */\n debounceMs?: number;\n /** Override the fan-out spawn (tests). Default: spawn the host CLI. */\n runPropagate?: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n /** Override the per-agent backup path (tests; default: the registry's). */\n backupPathFor?: (agent: CredentialAgentKind) => string;\n}\n\nexport interface CredentialsHandleResult {\n accepted: boolean;\n reason: string;\n}\n\nexport class CredentialsFanout {\n private readonly log: (msg: string) => void;\n private readonly debounceMs: number;\n private readonly runPropagate: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n private readonly backupPathFor?: (agent: CredentialAgentKind) => string;\n private readonly pending = new Map<CredentialAgentKind, NodeJS.Timeout>();\n private readonly chains = new Map<CredentialAgentKind, Promise<void>>();\n\n constructor(deps: CredentialsFanoutDeps) {\n this.log = deps.log;\n this.debounceMs = deps.debounceMs ?? 3_000;\n this.runPropagate = deps.runPropagate ?? defaultRunPropagate;\n this.backupPathFor = deps.backupPathFor;\n }\n\n /**\n * Validate, newest-wins-gate, persist the host backup, and schedule the\n * fan-out. Fast (no box I/O); the propagate CLI does the slow work detached.\n */\n async handle(sourceBoxId: string, payload: unknown): Promise<CredentialsHandleResult> {\n const update = parseCredentialsUpdate(payload);\n if (!update) return { accepted: false, reason: 'invalid payload' };\n const backupPath = this.backupPathFor?.(update.agent);\n const existing = await readCredentialBackup(update.agent, { backupPath });\n const verdict = shouldAcceptCredentialUpdate(update.agent, update.content, existing);\n if (!verdict.accept) {\n return { accepted: false, reason: verdict.reason };\n }\n await writeCredentialBackup(update.agent, update.content, { backupPath });\n this.log(\n `credentials: accepted ${update.agent} update from box ${sourceBoxId} (${verdict.reason}); fan-out in ${String(this.debounceMs)}ms`,\n );\n this.schedule(update.agent, sourceBoxId);\n return { accepted: true, reason: verdict.reason };\n }\n\n private schedule(agent: CredentialAgentKind, sourceBoxId: string): void {\n const existing = this.pending.get(agent);\n if (existing) clearTimeout(existing);\n const timer = setTimeout(() => {\n this.pending.delete(agent);\n const prev = this.chains.get(agent) ?? Promise.resolve();\n const next = prev\n .then(() => this.runPropagate(agent, sourceBoxId))\n .catch((err: unknown) => {\n this.log(\n `credentials: ${agent} fan-out failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n this.chains.set(agent, next);\n }, this.debounceMs);\n timer.unref();\n this.pending.set(agent, timer);\n }\n\n /** Pending debounce timers + in-flight chain, for tests/shutdown. */\n async flush(): Promise<void> {\n for (const [agent, timer] of this.pending) {\n clearTimeout(timer);\n this.pending.delete(agent);\n void agent;\n }\n await Promise.all([...this.chains.values()]);\n }\n}\n\n/**\n * Spawn `agentbox credentials propagate` via the CLI entry the daemon was\n * started with — the CLI owns provider resolution and per-box transports\n * (same pattern as the checkpoint/cp host actions).\n */\nasync function defaultRunPropagate(\n agent: CredentialAgentKind,\n sourceBoxId: string,\n): Promise<void> {\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n throw new Error('AGENTBOX_CLI_ENTRY not set; cannot run credential propagate host-side');\n }\n const result = await execa(\n process.execPath,\n [entry, 'credentials', 'propagate', '--agent', agent, '--source-box', sourceBoxId],\n { reject: false, timeout: 300_000 },\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `credentials propagate exited ${String(result.exitCode)}: ${String(result.stderr).slice(-300)}`,\n );\n }\n}\n","import { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry, EventBuffer } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport interface AutopauseConfig {\n enabled: boolean;\n maxRunningBoxes: number;\n idleMinutes: number;\n}\n\nexport type ContainerState = 'running' | 'paused' | 'stopped' | 'missing';\nexport type ClaudeState = 'working' | 'idle' | 'waiting' | 'unknown';\n\n/** One box's runtime facts the pure selector reasons about. No I/O, no clock. */\nexport interface BoxScanEntry {\n boxId: string;\n containerName: string;\n /** docker inspect status === 'running'. */\n running: boolean;\n /** Latest reported claude activity, or null when no snapshot exists. */\n claudeState: ClaudeState | null;\n /** ms the box has been idle (now - claude.updatedAt) when idle; else null. */\n idleMs: number | null;\n /** Box creation time as epoch ms; 0 when unknown/unparseable. */\n createdAt: number;\n}\n\n/**\n * Pure selection: given each running box's idle facts and the config, return\n * the boxIds to pause, in pause order. Pauses only enough to bring the running\n * count back to `maxRunningBoxes`, picking provably-idle boxes longest-idle\n * first (tie-break: oldest box, then boxId for determinism).\n */\nexport function selectBoxesToPause(entries: BoxScanEntry[], cfg: AutopauseConfig): string[] {\n if (!cfg.enabled) return [];\n const runningCount = entries.reduce((n, e) => (e.running ? n + 1 : n), 0);\n const excess = runningCount - cfg.maxRunningBoxes;\n if (excess <= 0) return [];\n\n const idleThresholdMs = cfg.idleMinutes * 60_000;\n const candidates = entries.filter(\n (e) => e.running && e.claudeState === 'idle' && e.idleMs != null && e.idleMs >= idleThresholdMs,\n );\n candidates.sort(\n (a, b) =>\n (b.idleMs as number) - (a.idleMs as number) ||\n a.createdAt - b.createdAt ||\n (a.boxId < b.boxId ? -1 : a.boxId > b.boxId ? 1 : 0),\n );\n return candidates.slice(0, excess).map((e) => e.boxId);\n}\n\n/**\n * Global+built-in autopause config. The relay is host-wide (not project\n * scoped), so it deliberately ignores the project/workspace layers that\n * `loadEffectiveConfig` would apply. Re-read every tick so\n * `agentbox config set --global autopause.*` takes effect without a relay\n * restart. A missing or malformed global file falls back to built-in defaults.\n */\nexport async function loadAutopauseConfig(): Promise<AutopauseConfig> {\n const d = BUILT_IN_DEFAULTS.autopause;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT (no global config yet) or a parse error -> built-in defaults.\n }\n const a = global.autopause ?? {};\n return {\n enabled: a.enabled ?? d.enabled,\n maxRunningBoxes: a.maxRunningBoxes ?? d.maxRunningBoxes,\n idleMinutes: a.idleMinutes ?? d.idleMinutes,\n };\n}\n\nexport interface AutopauseLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n events: EventBuffer;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global-config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `docker inspect`. */\n inspectStatus?: (containerName: string) => Promise<ContainerState>;\n /** Injectable for tests; defaults to `docker pause`. */\n pause?: (containerName: string) => Promise<void>;\n intervalMs?: number;\n}\n\nexport interface AutopauseLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n\nexport function startAutopauseLoop(deps: AutopauseLoopDeps): AutopauseLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const inspectStatus = deps.inspectStatus ?? inspectContainerState;\n const pause = deps.pause ?? pauseContainer;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, events, log } = deps;\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function tick(): Promise<void> {\n // A slow tick (many `docker inspect`s) must not overlap the next interval.\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n\n const entries: BoxScanEntry[] = [];\n for (const reg of registry.list()) {\n if (!reg.containerName) continue; // pre-feature box; can't pause it\n const state = await inspectStatus(reg.containerName);\n const active = readPauseState(statusStore.get(reg.boxId));\n const idleMs =\n active.state === 'idle' && active.updatedAt ? msSince(active.updatedAt) : null;\n entries.push({\n boxId: reg.boxId,\n containerName: reg.containerName,\n running: state === 'running',\n claudeState: active.state,\n idleMs,\n createdAt: reg.createdAt ? toEpoch(reg.createdAt) : 0,\n });\n }\n\n const toPause = selectBoxesToPause(entries, cfg);\n if (toPause.length === 0) return;\n\n const byId = new Map(entries.map((e) => [e.boxId, e]));\n const runningBefore = entries.reduce((n, e) => (e.running ? n + 1 : n), 0);\n for (const boxId of toPause) {\n const e = byId.get(boxId);\n if (!e) continue;\n try {\n await pause(e.containerName);\n const mins = e.idleMs != null ? Math.round(e.idleMs / 60_000) : null;\n events.append({\n boxId,\n type: 'autopause',\n payload: {\n containerName: e.containerName,\n action: 'paused',\n idleMs: e.idleMs,\n runningBefore,\n max: cfg.maxRunningBoxes,\n },\n });\n log(\n `autopause: paused box ${boxId} (${e.containerName})` +\n (mins != null ? ` after ~${String(mins)}m idle` : '') +\n `; running ${String(runningBefore)} -> target ${String(cfg.maxRunningBoxes)}`,\n );\n } catch (err) {\n // docker failure is non-fatal: log, record, keep going.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: docker pause ${e.containerName} failed: ${msg}`);\n events.append({\n boxId,\n type: 'autopause',\n payload: { containerName: e.containerName, action: 'pause-failed', error: msg },\n });\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n // The HTTP server keeps the process alive; the timer shouldn't on its own.\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\ninterface ClaudeSnap {\n state: ClaudeState | null;\n updatedAt: string | null;\n}\n\n/**\n * Coarse activity state for the pause decision, across ALL agents\n * (claude/codex/opencode) — not just claude. Reuses the queue loop's\n * multi-agent reader so a box where codex/opencode is working isn't paused\n * because claude happens to be idle or absent. Any active state (working,\n * compacting, waiting, end-plan, question, error) maps to a non-`idle` value,\n * so only a box whose live agent has settled to `idle` becomes a candidate.\n */\nfunction readPauseState(snap: Record<string, unknown> | undefined): ClaudeSnap {\n const active = readActiveAgent(snap);\n return { state: coarsePauseState(active.state), updatedAt: active.updatedAt };\n}\n\nfunction coarsePauseState(s: WorkingAgentState | null): ClaudeState | null {\n switch (s) {\n case 'idle':\n return 'idle';\n case 'waiting':\n return 'waiting';\n case 'working':\n case 'compacting':\n return 'working';\n case null:\n return null;\n // end-plan / question / error / unknown: a live session expecting attention\n // — never auto-pause it (maps to a non-idle, non-candidate state).\n default:\n return 'unknown';\n }\n}\n\nfunction msSince(iso: string): number | null {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nfunction toEpoch(iso: string): number {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n\nconst INSPECT_TIMEOUT_MS = 15_000;\nconst PAUSE_TIMEOUT_MS = 30_000;\n\ninterface DockerResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runDocker(args: string[], timeoutMs: number): Promise<DockerResult> {\n return new Promise<DockerResult>((resolve) => {\n const child = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: docker ${args.join(' ')} timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/** Mirrors `inspectContainerStatus` in @agentbox/sandbox-docker (no dep on it — cycle). */\nasync function inspectContainerState(name: string): Promise<ContainerState> {\n const r = await runDocker(['inspect', '--format', '{{.State.Status}}', name], INSPECT_TIMEOUT_MS);\n if (r.exitCode !== 0) return 'missing';\n switch (r.stdout.trim()) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n case 'created':\n case 'exited':\n case 'dead':\n case 'restarting':\n case 'removing':\n return 'stopped';\n default:\n return 'missing';\n }\n}\n\nasync function pauseContainer(name: string): Promise<void> {\n const r = await runDocker(['pause', name], PAUSE_TIMEOUT_MS);\n if (r.exitCode !== 0) {\n throw new Error(r.stderr.trim() || `docker pause ${name} exited ${String(r.exitCode)}`);\n }\n}\n","import { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport {\n mkdir,\n readdir,\n readFile,\n rename,\n unlink,\n writeFile,\n} from 'node:fs/promises';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport { readState, STATE_DIR, STATE_FILE } from '@agentbox/sandbox-core';\nimport type { BoxRecord, ResolvedCarryEntry } from '@agentbox/core';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport const QUEUE_DIR = join(STATE_DIR, 'queue');\n\n/**\n * Concurrency ceiling for `kind: 'prepare'` (image-bake) jobs — a separate lane\n * from box creation. Serialized to 1: bakes are resource-heavy (a docker build,\n * a booted VPS) and each pins project config on success, so running one at a\n * time avoids contention and write races. A second bake queues behind the first.\n */\nexport const PREPARE_MAX_CONCURRENT = 1;\n\nexport type QueueJobStatus = 'queued' | 'running' | 'done' | 'failed' | 'cancelled';\nexport type QueueAgentKind = 'claude-code' | 'codex' | 'opencode';\n\n/**\n * Host-terminal targeting captured on the submitting host when `queue.openIn`\n * is not `none`, carried on the job so the worker can open a fresh terminal\n * onto the box the moment it is ready. The relay treats this as opaque\n * pass-through; the CLI worker (`_run-queued-job`) is what reads and acts on it.\n *\n * The targeting is captured at submit time because the relay daemon is\n * long-lived and idempotent — its own env reflects whatever terminal first\n * started it, not this submit's terminal.\n */\nexport interface QueueJobOpenTerminal {\n host: 'tmux' | 'cmux' | 'herdr' | 'iterm2';\n mode: 'split' | 'window' | 'tab';\n /** Submitting shell's cwd, so the new pane resolves project-scoped refs. */\n cwd: string;\n /** tmux server socket (`$TMUX`) + the pane to split (`$TMUX_PANE`). */\n tmuxSocket?: string;\n tmuxPane?: string;\n /** cmux control socket (`$CMUX_SOCKET_PATH`) + bundled CLI path. */\n cmuxSocket?: string;\n cmuxBundledCli?: string;\n /** Submitting surface + workspace UUIDs (`$CMUX_SURFACE_ID` /\n * `$CMUX_WORKSPACE_ID`), so the worker can split the original pane (or, failing\n * that, the parent workspace) instead of opening a new top-level workspace. */\n cmuxSurfaceId?: string;\n cmuxWorkspaceId?: string;\n /** Herdr session socket (`$HERDR_SOCKET_PATH`) + submitting pane/workspace ids\n * (`$HERDR_PANE_ID` / `$HERDR_WORKSPACE_ID`), so the worker can split the\n * original pane / add a tab in the parent workspace. */\n herdrSocket?: string;\n herdrPaneId?: string;\n herdrWorkspaceId?: string;\n}\n\n/** On-disk job manifest. Read/written under `~/.agentbox/queue/<id>.json`. */\nexport interface QueueJob {\n id: string;\n /**\n * What the worker does with this job. `create` (default when absent) builds a\n * box. `prepare` bakes a provider's base image — it produces an artifact, not\n * a box, so it is excluded from the box/working concurrency gates and never\n * surfaces as a box in the dashboard. Prepare jobs carry `prepare` (not the\n * agent/create fields, which hold inert placeholders).\n */\n kind?: 'create' | 'prepare';\n agent: QueueAgentKind;\n status: QueueJobStatus;\n /** Friendly box name the worker should create the box under. */\n boxName: string;\n providerName: string;\n /** Original initial-prompt text the user passed via `-i`. */\n prompt: string;\n /** Extra argv tokens passed after `--`. */\n agentArgs: string[];\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). When\n * true the worker builds the box and stops — no agent session, no prompt.\n * `agent` still holds a value (required by the type) but is ignored.\n */\n noAgent?: boolean;\n /**\n * Seed the agent's first turn with the setup-wizard prompt (generate\n * `agentbox.yaml`) — set by the hub when the project has no `agentbox.yaml`\n * and no default snapshot. Inert when `noAgent` (no agent to run it).\n */\n setupWizard?: boolean;\n /** Workspace + create-time options the worker reconstructs from. */\n createOpts: QueueJobCreateOpts;\n /** Per-job concurrency ceiling (--max-running override, else the global). */\n maxConcurrent: number;\n /**\n * Per-job working-agent ceiling (--max-working override, else the global\n * `queue.maxWorking`). Only consulted when the working-agent gate is active\n * (`queue.maxWorking > 0`). Absent → use the global.\n */\n maxWorking?: number;\n /**\n * Box id the worker created for this job, written back to the manifest as\n * soon as `createBox` returns (before the agent session starts). Lets the\n * working-agent counter join a `running` manifest to its live box status and\n * avoid double-counting the in-flight startup slot once the box registers.\n */\n boxId?: string;\n /**\n * Host-terminal targeting for `queue.openIn`. Set at submit time when the\n * submitting shell ran inside a supported terminal; absent → open nothing.\n */\n openTerminal?: QueueJobOpenTerminal;\n createdAt: string;\n startedAt?: string;\n finishedAt?: string;\n /** Per-job log file path the worker writes to. */\n logPath: string;\n /** PID of the running worker. */\n pid?: number;\n /** Free-form context attached on terminal status flips. */\n reason?: string;\n /** Exit code of the worker process (only set on done/failed). */\n exitCode?: number;\n /**\n * Interactive Claude re-login sub-state. Set by the worker when it detects an\n * expired/dead Claude login during create and drives a browser re-login in a\n * throwaway docker container (job stays `running` meanwhile). The hub API/UI\n * read `phase`/`url`/`error` to surface the flow; the code endpoint writes\n * `code` back, which the worker consumes and clears. Absent for the normal\n * (creds-OK) path.\n */\n login?: QueueJobLogin;\n /** Bake options for a `kind: 'prepare'` job (see {@link QueueJobPrepare}). */\n prepare?: QueueJobPrepare;\n}\n\n/**\n * Claude re-login sub-state carried on a create job. Written **only by the create\n * worker** (worker → UI): `phase`/`url`/`error`/`lastError`. The reverse channel\n * (the pasted OAuth code, UI → worker) rides a separate file — see\n * {@link queueLoginCodePath} — so the two sides never read-modify-write the same\n * object and can't lose each other's updates.\n */\nexport interface QueueJobLogin {\n required: boolean;\n phase: 'starting' | 'awaiting-code' | 'exchanging' | 'done' | 'error';\n /** OAuth approval URL the user must open; present from `awaiting-code` onward. */\n url?: string;\n /** Terminal failure reason (with `phase: 'error'`). */\n error?: string;\n /** A recoverable note (e.g. a rejected code) — the flow stays usable. */\n lastError?: string;\n}\n\n/**\n * Options for a `kind: 'prepare'` job: bake a provider's base image. The worker\n * (`_run-queued-prepare`) calls `provider.prepare({ force, claudeInstall, onLog })`\n * directly and streams progress to the job log.\n */\nexport interface QueueJobPrepare {\n /** Rebuild even if the base image/snapshot already exists. */\n force?: boolean;\n /** Bake-time Claude install method (falls back to the effective config). */\n claudeInstall?: 'native' | 'npm';\n}\n\n/**\n * Minimal subset of CLI create flags the queued worker needs to reconstruct\n * the box. Kept narrow on purpose: anything that only changes interactive\n * attach behavior is irrelevant for the background path.\n */\nexport interface QueueJobCreateOpts {\n workspace: string;\n name?: string;\n hostSnapshot?: boolean;\n snapshot?: string;\n /** Base ref the box's per-box `agentbox/<name>` branch forks from (branch / tag\n * / SHA). Absent → the host's HEAD. Mirrors the CLI's `--from-branch`. */\n fromBranch?: string;\n image?: string;\n withPlaywright?: boolean;\n withEnv?: boolean;\n vnc?: boolean;\n /** `--no-resync` → false; resync the box with the host on (checkpoint) create. */\n resync?: boolean;\n sharedDockerCache?: boolean;\n portless?: boolean;\n sessionName?: string;\n /** Per-box override of `<agent>.dangerouslySkipPermissions` (`--no-...`). */\n dangerouslySkipPermissions?: boolean;\n memory?: string;\n cpus?: string;\n pidsLimit?: string;\n disk?: string;\n /**\n * carry: entries the submitter resolved + approved on the host (the same gate\n * the foreground create runs). Plain host-path metadata — serialized into the\n * job and applied by the worker, which reads the host files at create time.\n */\n carry?: ResolvedCarryEntry[];\n}\n\nexport interface QueueConfig {\n enabled: boolean;\n maxConcurrent: number;\n /** Max concurrently-working agents before `-i` jobs queue. 0 = disabled (use the running-box gate). */\n maxWorking: number;\n /** Debounce: ms an agent must stay non-working before it frees its working slot. */\n idleGraceMs: number;\n}\n\n/**\n * Global+built-in queue config (mirrors `loadAutopauseConfig`): re-read every\n * tick so `agentbox config set --global queue.*` takes effect without a relay\n * restart. Project/workspace layers are intentionally ignored — the relay is\n * host-wide.\n */\nexport async function loadQueueConfig(): Promise<QueueConfig> {\n const d = BUILT_IN_DEFAULTS.queue;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT / parse error → built-in defaults.\n }\n const q = global.queue ?? {};\n return {\n enabled: q.enabled ?? d.enabled,\n maxConcurrent: q.maxConcurrent ?? d.maxConcurrent,\n maxWorking: q.maxWorking ?? d.maxWorking,\n idleGraceMs: (q.idleGraceSeconds ?? d.idleGraceSeconds) * 1_000,\n };\n}\n\n/**\n * Atomically write a job manifest. Writes to a sibling `.tmp` file then renames\n * — readers never see a half-written JSON file. Idempotent: missing queue dir\n * is created as needed.\n */\nexport async function writeJob(job: QueueJob): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = join(QUEUE_DIR, `${job.id}.json`);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(job, null, 2) + '\\n', 'utf8');\n await rename(tmp, final);\n}\n\nexport interface EnqueueQueueJobInput {\n agent: QueueAgentKind;\n boxName: string;\n providerName: string;\n prompt: string;\n agentArgs: string[];\n createOpts: QueueJobCreateOpts;\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). The\n * worker runs createBox() then stops — no agent session. `agent` is still\n * required by the type but is ignored by the worker when this is set.\n */\n noAgent?: boolean;\n /** Seed the setup-wizard prompt as the agent's first turn (hub create path). */\n setupWizard?: boolean;\n /** Per-invocation override of queue.maxConcurrent. */\n maxRunningOverride?: number;\n /** Per-invocation override of queue.maxWorking. */\n maxWorkingOverride?: number;\n /** Host-terminal targeting captured at submit time (CLI `queue.openIn`). */\n openTerminal?: QueueJobOpenTerminal;\n}\n\nexport interface EnqueueQueueJobResult {\n job: QueueJob;\n /** Cross-provider running count at the time of enqueue (informational). */\n runningCount: number;\n /** Effective ceiling used for the job (override or global). */\n maxConcurrent: number;\n}\n\n/**\n * Build a queued-job manifest and write it to `~/.agentbox/queue/<id>.json`.\n * Pure + transport-free: it does NOT ensure a relay is running and does NOT\n * poke the scheduler — callers do that (the CLI via `POST /admin/queue/enqueue`\n * after `ensureRelay`; the embedded hub via its in-process queue poke). Kept in\n * `@agentbox/relay` so both the CLI `submitQueueJob` wrapper and the hub backend\n * share one manifest-builder without the hub importing `apps/cli`. The scheduler\n * (`startQueueLoop`) picks the manifest up on its next tick regardless.\n */\nexport async function enqueueQueueJob(\n input: EnqueueQueueJobInput,\n): Promise<EnqueueQueueJobResult> {\n const cfg = await loadQueueConfig();\n const ceiling =\n typeof input.maxRunningOverride === 'number' && input.maxRunningOverride > 0\n ? input.maxRunningOverride\n : cfg.maxConcurrent;\n const maxWorking =\n typeof input.maxWorkingOverride === 'number' && input.maxWorkingOverride > 0\n ? input.maxWorkingOverride\n : undefined;\n\n const id = randomBytes(9).toString('hex');\n const job: QueueJob = {\n id,\n agent: input.agent,\n status: 'queued',\n boxName: input.boxName,\n providerName: input.providerName,\n prompt: input.prompt,\n agentArgs: input.agentArgs,\n ...(input.noAgent ? { noAgent: true } : {}),\n ...(input.setupWizard ? { setupWizard: true } : {}),\n createOpts: input.createOpts,\n maxConcurrent: ceiling,\n ...(maxWorking !== undefined ? { maxWorking } : {}),\n ...(input.openTerminal !== undefined ? { openTerminal: input.openTerminal } : {}),\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n\n let runningCount = 0;\n try {\n runningCount = await defaultCountRunningBoxes();\n } catch {\n runningCount = 0;\n }\n\n return { job, runningCount, maxConcurrent: ceiling };\n}\n\nexport interface EnqueuePrepareJobInput {\n /** Provider to bake (docker | daytona | hetzner | vercel | e2b | plugin). */\n providerName: string;\n /** Rebuild even if the base already exists. */\n force?: boolean;\n /** Bake-time Claude install method (else the effective config decides). */\n claudeInstall?: 'native' | 'npm';\n /** Host dir used for config resolution; the worker defaults it if absent. */\n workspace?: string;\n}\n\n/**\n * Build a `kind: 'prepare'` manifest and write it to the queue. Like\n * {@link enqueueQueueJob} this is transport-free — the caller pokes the\n * scheduler. The agent/create fields carry inert placeholders (the prepare\n * worker only reads `providerName` + `prepare`); the job is scheduled in its own\n * lane (see {@link PREPARE_MAX_CONCURRENT}) and never surfaces as a box.\n */\nexport async function enqueuePrepareJob(\n input: EnqueuePrepareJobInput,\n): Promise<{ job: QueueJob }> {\n const id = randomBytes(9).toString('hex');\n const prepare: QueueJobPrepare = {\n ...(input.force ? { force: true } : {}),\n ...(input.claudeInstall ? { claudeInstall: input.claudeInstall } : {}),\n };\n const job: QueueJob = {\n id,\n kind: 'prepare',\n agent: 'claude-code', // placeholder — ignored for prepare\n status: 'queued',\n boxName: '',\n providerName: input.providerName,\n prompt: '',\n agentArgs: [],\n createOpts: { workspace: input.workspace ?? process.cwd() },\n prepare,\n maxConcurrent: PREPARE_MAX_CONCURRENT,\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n return { job };\n}\n\n/** Read a single job manifest by id. Returns null when missing. */\nexport async function readJob(id: string): Promise<QueueJob | null> {\n try {\n const raw = await readFile(join(QUEUE_DIR, `${id}.json`), 'utf8');\n return JSON.parse(raw) as QueueJob;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n}\n\n/** Best-effort delete of a job manifest. ENOENT is not an error. */\nexport async function deleteJob(id: string): Promise<void> {\n try {\n await unlink(join(QUEUE_DIR, `${id}.json`));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n}\n\n/**\n * Read every job manifest in the queue dir. Skips temp files (atomic-rename\n * leftovers) and entries that fail to parse — the loop must never crash on a\n * malformed file. Sorted by `createdAt` ascending for FIFO selection.\n */\nexport async function loadQueue(): Promise<QueueJob[]> {\n let entries: string[];\n try {\n entries = await readdir(QUEUE_DIR);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: QueueJob[] = [];\n for (const name of entries) {\n if (!name.endsWith('.json')) continue;\n try {\n const raw = await readFile(join(QUEUE_DIR, name), 'utf8');\n out.push(JSON.parse(raw) as QueueJob);\n } catch {\n // skip malformed — surfaced via tick log if it stays put\n }\n }\n out.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));\n return out;\n}\n\n/**\n * Pure selector: pick the oldest queued job that can start given the current\n * cross-provider running count. Per-job `maxConcurrent` ceiling wins (a job\n * with `--max-running 3` starts even when the global cap is 1). Returns null\n * when nothing can start right now.\n */\nexport function selectNextRunnable(jobs: QueueJob[], runningCount: number): QueueJob | null {\n // jobs is FIFO by createdAt already (loadQueue sorts).\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n if (runningCount < j.maxConcurrent) return j;\n }\n return null;\n}\n\n/** Count running prepare jobs (its own concurrency lane). Dead workers skipped. */\nexport function countRunningPrepareJobs(jobs: QueueJob[]): number {\n let n = 0;\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue;\n n += 1;\n }\n return n;\n}\n\n/**\n * Pure selector for the prepare (image-bake) lane: the oldest queued prepare job\n * while under {@link PREPARE_MAX_CONCURRENT}. Independent of the box gates.\n */\nexport function selectNextRunnablePrepare(\n jobs: QueueJob[],\n runningPrepare: number,\n): QueueJob | null {\n if (runningPrepare >= PREPARE_MAX_CONCURRENT) return null;\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'queued') continue;\n return j;\n }\n return null;\n}\n\n// ---- working-agent gate ---------------------------------------------------\n//\n// When `queue.maxWorking > 0` the scheduler caps the number of *working*\n// (quota-consuming) agents instead of running boxes. The signal is each box's\n// live activity state in the relay's BoxStatusStore (fed for docker and cloud\n// alike). A box that has finished thinking and is waiting for the user no\n// longer occupies a slot, so the next queued job starts — without pausing the\n// finished box.\n\n/** Activity union the working gate reasons about (mirrors @agentbox/ctl's `ClaudeActivityState`). */\nexport type WorkingAgentState =\n | 'working'\n | 'idle'\n | 'waiting'\n | 'end-plan'\n | 'question'\n | 'compacting'\n | 'error'\n | 'unknown';\n\nconst WORKING_AGENT_STATES: readonly WorkingAgentState[] = [\n 'working',\n 'idle',\n 'waiting',\n 'end-plan',\n 'question',\n 'compacting',\n 'error',\n 'unknown',\n];\n\nfunction isWorkingAgentState(v: unknown): v is WorkingAgentState {\n return typeof v === 'string' && (WORKING_AGENT_STATES as readonly string[]).includes(v);\n}\n\n/**\n * Boot window during which a freshly-created box (agent not yet reporting a\n * state) still counts as occupying a slot. Must exceed worst-case box\n * create + session launch before the first `working` hook fires, or a burst\n * of queued jobs would over-start before any reports working. Internal\n * constant, not user-tunable (it's a correctness guard, not a preference).\n */\nexport const STARTUP_GRACE_MS = 90_000;\n\n/** One box's facts the pure working-slot predicate reasons about. No I/O, no clock. */\nexport interface WorkingSlotEntry {\n /** boxId (registered box) — for logging/debug only. */\n key: string;\n /** Most-recent active-agent state across claude/codex/opencode, or null when no snapshot. */\n agentState: WorkingAgentState | null;\n /** ms since that agent's `updatedAt` (now - updatedAt), or null. */\n sinceUpdateMs: number | null;\n /** ms since the box was created (now - box.createdAt), or null. */\n sinceCreateMs: number | null;\n}\n\n/**\n * Pure predicate: does this box occupy a working slot right now?\n * - working/compacting → yes (actively consuming quota)\n * - unknown/no-snapshot, booting → yes while within {@link STARTUP_GRACE_MS}\n * - idle/waiting/end-plan/question→ yes only while within the debounce window\n * (`now - updatedAt < idleGraceMs`); this absorbs brief idle flaps between\n * turns so a slot isn't freed-then-reclaimed in a thrash.\n * - error, or anything past its window → no (slot frees).\n */\nexport function occupiesWorkingSlot(e: WorkingSlotEntry, idleGraceMs: number): boolean {\n if (e.agentState === 'working' || e.agentState === 'compacting') return true;\n if (\n (e.agentState === null || e.agentState === 'unknown') &&\n e.sinceCreateMs !== null &&\n e.sinceCreateMs < STARTUP_GRACE_MS\n ) {\n return true;\n }\n if (\n (e.agentState === 'idle' ||\n e.agentState === 'waiting' ||\n e.agentState === 'end-plan' ||\n e.agentState === 'question') &&\n e.sinceUpdateMs !== null &&\n e.sinceUpdateMs < idleGraceMs\n ) {\n return true;\n }\n return false;\n}\n\nexport function countWorkingSlots(entries: WorkingSlotEntry[], idleGraceMs: number): number {\n return entries.reduce((n, e) => (occupiesWorkingSlot(e, idleGraceMs) ? n + 1 : n), 0);\n}\n\n/**\n * Pure selector mirroring {@link selectNextRunnable} but for the working-agent\n * gate: pick the oldest queued job whose effective working ceiling (per-job\n * `maxWorking`, else the global) is above the current working count.\n */\nexport function selectNextRunnableByWorking(\n jobs: QueueJob[],\n workingCount: number,\n globalMaxWorking: number,\n): QueueJob | null {\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n const ceil =\n typeof j.maxWorking === 'number' && j.maxWorking > 0 ? j.maxWorking : globalMaxWorking;\n if (workingCount < ceil) return j;\n }\n return null;\n}\n\n/**\n * Pick the active agent's state from a box-status snapshot. `claude` is always\n * present (codex/opencode are additive), so prefer whichever agent reports a\n * quota-consuming state, else the most-recently-updated one. Returns nulls\n * when no snapshot / no recognizable state.\n */\nexport function readActiveAgent(snap: Record<string, unknown> | undefined): {\n state: WorkingAgentState | null;\n updatedAt: string | null;\n} {\n if (!snap || typeof snap !== 'object') return { state: null, updatedAt: null };\n const candidates: Array<{ state: WorkingAgentState; updatedAt: string | null }> = [];\n for (const key of ['claude', 'codex', 'opencode']) {\n const sub = (snap as Record<string, unknown>)[key];\n if (!sub || typeof sub !== 'object') continue;\n const o = sub as Record<string, unknown>;\n if (!isWorkingAgentState(o.state)) continue;\n candidates.push({\n state: o.state,\n updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : null,\n });\n }\n if (candidates.length === 0) return { state: null, updatedAt: null };\n const active = candidates.find((c) => c.state === 'working' || c.state === 'compacting');\n if (active) return active;\n candidates.sort((a, b) => parseTime(b.updatedAt) - parseTime(a.updatedAt));\n return candidates[0]!;\n}\n\nfunction parseTime(iso: string | null): number {\n if (!iso) return 0;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n\nfunction msSince(iso: string | null | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nexport type RunningCountFn = () => Promise<number>;\nexport type CountWorkingFn = (idleGraceMs: number) => Promise<number>;\n\nexport interface QueueLoopDeps {\n log: (line: string) => void;\n /** Injectable; defaults to global-config loader. */\n loadConfig?: () => Promise<QueueConfig>;\n /** Injectable; defaults to docker inspect + cloud-as-running (see {@link defaultCountRunningBoxes}). */\n countRunning?: RunningCountFn;\n /**\n * Injectable working-agent counter (used when `queue.maxWorking > 0`).\n * Defaults to {@link defaultCountWorkingBoxes} over `registry` + `statusStore`.\n */\n countWorking?: CountWorkingFn;\n /** The relay's box registry; required (with `statusStore`) for the working gate. */\n registry?: Pick<BoxRegistry, 'list'>;\n /** The relay's box-status store; required (with `registry`) for the working gate. */\n statusStore?: Pick<BoxStatusStore, 'get'>;\n /** Injectable; defaults to `spawn detached node <cliEntry> _run-queued-job <id>`. */\n spawnWorker?: (job: QueueJob) => Promise<number | null>;\n /** Hook invoked when a manifest's status flips. Tests inject to assert. */\n onStatusChange?: (job: QueueJob) => void;\n intervalMs?: number;\n}\n\nexport interface QueueLoopHandle {\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 2_000;\n\n/**\n * Periodic queue scheduler. Runs alongside the autopause loop in the host\n * relay: every tick, count running boxes, pick the oldest startable queued\n * job, atomically flip it to `running`, then spawn the worker. Worker\n * crash/reboot recovery: on relay start, any `running` manifest whose PID\n * is no longer alive gets flipped to `failed` (the slot is recouped\n * automatically because we count live provider state, not manifests).\n */\nexport function startQueueLoop(deps: QueueLoopDeps): QueueLoopHandle {\n const loadConfig = deps.loadConfig ?? loadQueueConfig;\n const countRunning = deps.countRunning ?? defaultCountRunningBoxes;\n const spawnWorker = deps.spawnWorker ?? defaultSpawnWorker;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { log, onStatusChange } = deps;\n\n const countWorking: CountWorkingFn | null =\n deps.countWorking ??\n (deps.registry && deps.statusStore\n ? (idleGraceMs) => defaultCountWorkingBoxes(deps.registry!, deps.statusStore!, idleGraceMs)\n : null);\n\n let ticking = false;\n let stopped = false;\n let warnedNoWorkingDeps = false;\n let lastSweepAt = 0;\n let inFlight: Promise<void> = recoverOrphanedWorkers(log, onStatusChange).catch((err) => {\n log(`queue: orphan recovery failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n\n // Throttled hygiene sweep of stale terminal manifests (runs regardless of\n // whether anything is queued, so a finished burst gets cleaned up).\n const now = Date.now();\n if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {\n lastSweepAt = now;\n await sweepTerminalJobs(log, now).catch((err) => {\n log(`queue: sweep failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n }\n\n const jobs = await loadQueue();\n const hasQueued = jobs.some((j) => j.status === 'queued');\n if (!hasQueued) return;\n\n // Working-agent gate when `queue.maxWorking > 0` and the relay wired in\n // its registry + status store; otherwise the legacy running-box gate.\n let gateByWorking = cfg.maxWorking > 0;\n if (gateByWorking && !countWorking) {\n gateByWorking = false;\n if (!warnedNoWorkingDeps) {\n warnedNoWorkingDeps = true;\n log('queue: maxWorking set but registry/statusStore not wired; using running-box gate');\n }\n }\n\n // Start as many slots as we can in one tick — picking one per tick would\n // mean a 2s lag per job after a slot frees, which adds up when a burst\n // of jobs queues against a freshly-cleared pool.\n while (!stopped) {\n let occupancy: number;\n let next: QueueJob | null;\n if (gateByWorking && countWorking) {\n occupancy = await countWorking(cfg.idleGraceMs);\n const fresh = await loadQueue();\n next = selectNextRunnableByWorking(fresh, occupancy, cfg.maxWorking);\n } else {\n occupancy = await countRunning();\n const fresh = await loadQueue();\n next = selectNextRunnable(fresh, occupancy);\n }\n if (!next) break;\n // Atomic claim: re-read to make sure no other process already started\n // it (the relay is the only writer of status: running, but a\n // future-second-relay scenario would clobber here without this read).\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n const ceil = gateByWorking\n ? typeof updated.maxWorking === 'number' && updated.maxWorking > 0\n ? updated.maxWorking\n : cfg.maxWorking\n : updated.maxConcurrent;\n log(\n `queue: started job ${updated.id} (${updated.agent}) as pid ${String(pid)}; ${gateByWorking ? 'working' : 'running'} ${String(occupancy + 1)}/${String(ceil)}`,\n );\n } else {\n log(`queue: started job ${updated.id} (${updated.agent}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for job ${updated.id} failed: ${msg}`);\n }\n }\n\n // Prepare (image-bake) lane — independent of the box/working gates. A bake\n // produces an artifact, not a box, so it neither counts against nor is\n // blocked by running boxes. Serialized to PREPARE_MAX_CONCURRENT.\n while (!stopped) {\n const fresh = await loadQueue();\n const runningPrepare = countRunningPrepareJobs(fresh);\n const next = selectNextRunnablePrepare(fresh, runningPrepare);\n if (!next) break;\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n log(\n `queue: started prepare job ${updated.id} (${updated.providerName}) as pid ${String(pid)}; prepare ${String(runningPrepare + 1)}/${String(PREPARE_MAX_CONCURRENT)}`,\n );\n } else {\n log(`queue: started prepare job ${updated.id} (${updated.providerName}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for prepare job ${updated.id} failed: ${msg}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`queue: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n /** Inject manual ticks (after enqueue HTTP). Caller is fire-and-forget. */\n function poke(): void {\n if (stopped) return;\n inFlight = tick();\n }\n\n // Expose poke on the handle in addition to stop, so the HTTP enqueue route\n // can trigger an immediate scheduling pass without waiting for the timer.\n const handle: QueueLoopHandle & { poke: () => void } = {\n poke,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return handle;\n}\n\n/**\n * Scrub `running` manifests whose PID is no longer alive — usually after a\n * host reboot or a relay crash mid-flight. The slot is recouped automatically\n * because `countRunning` reads live provider state, but the manifest must be\n * advanced or `agentbox queue list` keeps lying about what's in progress.\n */\nasync function recoverOrphanedWorkers(\n log: (line: string) => void,\n onChange?: (job: QueueJob) => void,\n): Promise<void> {\n const jobs = await loadQueue();\n for (const j of jobs) {\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' && processAlive(j.pid)) continue;\n const failed: QueueJob = {\n ...j,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: 'worker-died',\n };\n await writeJob(failed);\n onChange?.(failed);\n log(`queue: recovered orphan job ${j.id} (pid ${String(j.pid ?? '?')} not alive) -> failed`);\n }\n}\n\n/** Terminal job manifests older than this are swept so `queue list` and the\n * scheduler don't accumulate unbounded done/failed/cancelled entries (they\n * never gate concurrency, but they pollute listings and were never cleaned). */\nexport const TERMINAL_RETENTION_MS = 60 * 60 * 1_000;\nconst SWEEP_INTERVAL_MS = 60 * 1_000;\nconst TERMINAL_STATUSES: readonly QueueJobStatus[] = ['done', 'failed', 'cancelled'];\n\n/**\n * Delete terminal (done/failed/cancelled) job manifests whose terminal flip is\n * older than {@link TERMINAL_RETENTION_MS}. Recent terminal jobs are kept so\n * `agentbox queue list` still shows just-finished history. Best-effort: a\n * delete failure is logged-by-omission and retried next sweep.\n */\nasync function sweepTerminalJobs(log: (line: string) => void, now: number): Promise<void> {\n const jobs = await loadQueue();\n let swept = 0;\n for (const j of jobs) {\n if (!TERMINAL_STATUSES.includes(j.status)) continue;\n const since = Date.parse(j.finishedAt ?? j.createdAt);\n if (Number.isNaN(since) || now - since < TERMINAL_RETENTION_MS) continue;\n await deleteJob(j.id);\n swept += 1;\n }\n if (swept > 0) log(`queue: swept ${String(swept)} stale terminal manifest(s)`);\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Count concurrently *working* agents for the working-agent gate. Computed\n * fresh each call from in-memory relay state (no docker shell-out, no cache):\n * - one {@link WorkingSlotEntry} per registered box, from its live status\n * snapshot (`statusStore`) and creation time (`registry`), scored by\n * {@link occupiesWorkingSlot};\n * - plus each `running` queue job whose box hasn't registered yet (in-flight\n * create), so a burst can't over-start before the first box reports. A job\n * whose `boxId` is already in the registry is counted via its box entry\n * (no double count); a job whose worker PID is dead is skipped (the box,\n * if it exists, is counted via the registry).\n */\nexport async function defaultCountWorkingBoxes(\n registry: Pick<BoxRegistry, 'list'>,\n statusStore: Pick<BoxStatusStore, 'get'>,\n idleGraceMs: number,\n): Promise<number> {\n const boxes = registry.list();\n const registeredIds = new Set(boxes.map((b) => b.boxId));\n const entries: WorkingSlotEntry[] = boxes.map((b) => {\n const active = readActiveAgent(statusStore.get(b.boxId));\n return {\n key: b.boxId,\n agentState: active.state,\n sinceUpdateMs: msSince(active.updatedAt),\n sinceCreateMs: msSince(b.createdAt),\n };\n });\n const count = countWorkingSlots(entries, idleGraceMs);\n\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return count;\n }\n return count + countInFlightCreateJobs(jobs, registeredIds);\n}\n\n/**\n * Count `running` queue jobs whose box isn't yet accounted for elsewhere — an\n * in-flight create that occupies a concurrency slot before its box exists.\n * Shared by both gates: the caller passes the set of box ids it already counted\n * (relay registry ids for the working gate, state.json ids for the running\n * gate), so a job is added only while its box is invisible to that source. A\n * job whose worker pid is dead is skipped (its box, if any, is counted directly;\n * the orphan-recovery sweep flips the stale manifest to `failed`).\n */\nexport function countInFlightCreateJobs(jobs: QueueJob[], accountedBoxIds: Set<string>): number {\n let n = 0;\n for (const j of jobs) {\n if (j.kind === 'prepare') continue; // a bake is not a box\n if (j.status !== 'running') continue;\n if (j.boxId && accountedBoxIds.has(j.boxId)) continue; // counted via its box\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue; // dead worker\n n += 1;\n }\n return n;\n}\n\nconst RUNNING_COUNT_CACHE_MS = 3_000;\nlet boxStateCache: { boxCount: number; stateIds: Set<string>; expiresAt: number } | null = null;\n\n/**\n * Cross-provider count of boxes whose runtime state is `running`, plus the\n * in-flight queue jobs whose box isn't in `state.json` yet.\n *\n * The box-state portion reads `~/.agentbox/state.json`, then per-provider:\n * - docker: `docker inspect --format {{.State.Status}}` shell-out (cheap).\n * - non-docker (daytona/hetzner/…): counted as running. Cloud providers\n * don't expose a cheap synchronous probe; the autopause/queue loops would\n * pay an SDK round-trip per box per tick otherwise. Tracked as a v1\n * limitation: a paused cloud box still counts against the slot cap until\n * it's destroyed. Acceptable because cloud pause is rare today.\n * That portion is cached for 3s so multiple slot decisions in one tick share it.\n *\n * The in-flight term is recomputed every call (a cheap `loadQueue` fs read), NOT\n * cached: a job the scheduler just flipped to `running` hasn't created its box\n * yet (~25s on cloud, image pull on docker), so it's absent from `state.json`.\n * Without counting it, the per-tick \"start as many as fit\" loop would re-select\n * the same free slot for the next job and over-start past `--max-running`.\n */\nexport async function defaultCountRunningBoxes(): Promise<number> {\n const { boxCount, stateIds } = await cachedBoxState();\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return boxCount;\n }\n return boxCount + countInFlightCreateJobs(jobs, stateIds);\n}\n\nasync function cachedBoxState(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n const now = Date.now();\n if (boxStateCache && boxStateCache.expiresAt > now) {\n return { boxCount: boxStateCache.boxCount, stateIds: boxStateCache.stateIds };\n }\n const fresh = await uncachedBoxStateCount();\n boxStateCache = { ...fresh, expiresAt: now + RUNNING_COUNT_CACHE_MS };\n return fresh;\n}\n\n/** Running-box count from `state.json` plus the set of those boxes' ids (for\n * in-flight-job dedup). Read errors / no boxes → zero and an empty set. */\nasync function uncachedBoxStateCount(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n let boxes: BoxRecord[];\n try {\n boxes = (await readState(STATE_FILE)).boxes;\n } catch {\n return { boxCount: 0, stateIds: new Set() };\n }\n const stateIds = new Set(boxes.map((b) => b.id));\n if (boxes.length === 0) return { boxCount: 0, stateIds };\n\n let boxCount = 0;\n const dockerBoxes: BoxRecord[] = [];\n for (const b of boxes) {\n const provider = b.provider ?? 'docker';\n if (provider === 'docker') {\n dockerBoxes.push(b);\n } else {\n // Optimistic: count cloud boxes as running. See note on\n // {@link defaultCountRunningBoxes} for why.\n boxCount += 1;\n }\n }\n if (dockerBoxes.length > 0) {\n const states = await Promise.all(dockerBoxes.map((b) => inspectDockerState(b.container)));\n for (const s of states) {\n if (s === 'running') boxCount += 1;\n }\n }\n return { boxCount, stateIds };\n}\n\nfunction inspectDockerState(containerName: string): Promise<'running' | 'other'> {\n return new Promise<'running' | 'other'>((resolveP) => {\n const child = spawn('docker', ['inspect', '--format', '{{.State.Status}}', containerName], {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let out = '';\n let settled = false;\n const finish = (state: 'running' | 'other'): void => {\n if (settled) return;\n settled = true;\n resolveP(state);\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish('other');\n }, 10_000);\n child.stdout?.on('data', (c: Buffer) => {\n out += c.toString('utf8');\n });\n child.on('error', () => {\n clearTimeout(timer);\n finish('other');\n });\n child.on('close', () => {\n clearTimeout(timer);\n finish(out.trim() === 'running' ? 'running' : 'other');\n });\n });\n}\n\n/**\n * Default worker spawner: detached `node <cliEntry> _run-queued-job <id>`,\n * with stdout/stderr appended to the job's `logPath`. The CLI entry is set by\n * `ensureRelay` via `AGENTBOX_CLI_ENTRY` (the same hook checkpoint/cp/download\n * RPCs already use). Returns the worker PID, or null when the spawn produced\n * no PID (treated as a soft failure — the loop's catch turns it into a\n * `failed` manifest).\n */\nasync function defaultSpawnWorker(job: QueueJob): Promise<number | null> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry || !existsSync(entry)) {\n throw new Error(\n `AGENTBOX_CLI_ENTRY not set or missing (${String(entry)}); cannot spawn queue worker`,\n );\n }\n await mkdir(join(STATE_DIR, 'logs'), { recursive: true });\n const fd = openSync(job.logPath, 'a');\n // A prepare (image-bake) job runs a different worker; both stream to logPath.\n const command = job.kind === 'prepare' ? '_run-queued-prepare' : '_run-queued-job';\n const child = spawn(process.execPath, [entry, command, job.id], {\n detached: true,\n stdio: ['ignore', fd, fd],\n env: process.env,\n });\n child.unref();\n // The fd stays open in the child; close our own copy.\n try {\n closeSync(fd);\n } catch {\n /* the child still holds its own fd */\n }\n return typeof child.pid === 'number' ? child.pid : null;\n}\n\n/** Re-export the path for callers (CLI submit helper, tests). */\nexport const QUEUE_LOGS_DIR = join(STATE_DIR, 'logs');\n\n/** Build the per-job log path. Kept here so submit + worker agree on layout. */\nexport function queueLogPath(id: string): string {\n return join(QUEUE_LOGS_DIR, `queue-${id}.log`);\n}\n\n/**\n * The UI → worker channel for a Claude re-login code: a dedicated file next to\n * the manifest. Only the hub writes it ({@link writeQueueLoginCode}); only the\n * worker reads+consumes it ({@link takeQueueLoginCode}). Keeping it out of the\n * job manifest avoids a cross-process read-modify-write race with the worker's\n * `login` (phase/url) writes.\n */\nexport function queueLoginCodePath(id: string): string {\n return join(QUEUE_DIR, `${id}.login-code`);\n}\n\n/** Hub side: deliver the pasted OAuth approval code to a job, written atomically. */\nexport async function writeQueueLoginCode(id: string, code: string): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = queueLoginCodePath(id);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, code.trim(), { mode: 0o600 });\n await rename(tmp, final);\n}\n\n/** Worker side: read + consume the pending code (deleting it); null when none. */\nexport async function takeQueueLoginCode(id: string): Promise<string | null> {\n try {\n const code = (await readFile(queueLoginCodePath(id), 'utf8')).trim();\n await unlink(queueLoginCodePath(id)).catch(() => {});\n return code.length > 0 ? code : null;\n } catch {\n return null;\n }\n}\n\n/** Wait briefly for a file to appear (queue manifest after enqueue HTTP). */\nexport async function waitForFile(path: string, timeoutMs = 1_000): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (existsSync(path)) return true;\n await delay(25);\n }\n return existsSync(path);\n}\n","/**\n * `startCloudKeepaliveLoop` — host-resident loop that renews a cloud box's\n * session-timeout while its in-box agent is active, so a long-running\n * Claude/Codex session isn't killed when the create-time timeout elapses.\n *\n * Sibling to `startAutopauseLoop` (and modeled on it): a host-wide sweep on a\n * timer that reads each box's live agent state from the `BoxStatusStore` and\n * acts. Where autopause *pauses* idle docker boxes, this *keeps alive* active\n * cloud boxes by pushing their death-time out. The window REUSES the autopause\n * idle threshold (`autopause.idleMinutes`) — per the design, there is no\n * separate keepalive knob.\n *\n * - active agent -> hold the death-time a full window ahead of NOW.\n * - idle agent -> let it lapse a window after it went idle, then stop.\n *\n * The additive-vs-absolute SDK split (vercel `extendTimeout` adds to the\n * current deadline and can't read remaining; e2b `setTimeout` sets TTL from\n * now) is resolved by tracking each box's intended deadline in memory and\n * handing the backend BOTH the absolute target and our tracked current\n * deadline. See `CloudBackend.renewTimeout`. The tracked deadline is seeded\n * from the box's RECORDED effective create timeout (`cloud.sessionTimeoutMs`)\n * so a project/workspace override doesn't desync the seed.\n *\n * Plan caps (vercel Hobby ~45m, Pro+ ~5h; e2b team plan) bound how far a box\n * can be extended — a renew past the cap throws and is swallowed here, after\n * which the box is briefly backed off (so we don't hammer the API / log) and\n * lapses normally. The feature mainly benefits Pro+ plans, where the\n * conservative 45-min create default otherwise kills long sessions early.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport type { CloudBackend } from '@agentbox/core';\nimport { findBox, readState } from '@agentbox/sandbox-core';\nimport { loadAutopauseConfig, type AutopauseConfig } from './autopause.js';\nimport { resolveCloudBackend } from './host-actions.js';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\n/** Coarse activity for the renewal decision. `active` = keep the box alive. */\nexport type KeepaliveAgentState = 'active' | 'idle' | null;\n\n/** One box's facts the pure selector reasons about. No I/O, no clock. */\nexport interface KeepaliveScanEntry {\n boxId: string;\n /** Cloud backend name, e.g. 'vercel'. */\n backend: string;\n /** Coarse activity across claude/codex/opencode, or null when no snapshot. */\n agentState: KeepaliveAgentState;\n /** epoch ms of the active agent's `updatedAt`, or null when no snapshot. */\n lastActivityMs: number | null;\n}\n\nexport interface RenewDecision {\n boxId: string;\n backend: string;\n /** Absolute death-time we want this box held at. */\n targetDeadlineEpochMs: number;\n}\n\n/**\n * Pure selection: given each cloud box's activity facts, the window, and the\n * clock, return the boxes to renew with their target death-time.\n *\n * - active agent -> keep alive a full window from NOW (`now + windowMs`).\n * - idle, < window since it went idle -> lapse `window` after it went idle\n * (`lastActivityMs + windowMs`, where `lastActivityMs` is the fresh\n * working->idle transition time).\n * - idle >= window, no agent state, or a wedged agent (error/unknown) -> skip.\n *\n * The active case anchors on `now`, NOT on `lastActivityMs`, and does NOT\n * require `lastActivityMs`: the in-box status reporter bumps `updatedAt` on\n * state changes (per-tool-call), not during a long single `working` op (a\n * 30-min test run), so a stale/absent `updatedAt` must not freeze the target\n * below the tracked deadline — that would kill the box mid-work, the exact\n * failure this feature prevents. The idle case stays `now`-independent so an\n * idle box still lapses.\n */\nexport function selectBoxesToRenew(\n entries: KeepaliveScanEntry[],\n windowMs: number,\n now: number,\n): RenewDecision[] {\n const out: RenewDecision[] = [];\n for (const e of entries) {\n if (e.agentState == null) continue;\n let target: number | null = null;\n if (e.agentState === 'active') {\n target = now + windowMs;\n } else if (\n e.agentState === 'idle' &&\n e.lastActivityMs != null &&\n now - e.lastActivityMs < windowMs\n ) {\n target = e.lastActivityMs + windowMs;\n }\n if (target != null) {\n out.push({ boxId: e.boxId, backend: e.backend, targetDeadlineEpochMs: target });\n }\n }\n return out;\n}\n\n/**\n * Collapse the multi-agent `WorkingAgentState` into the coarse keepalive state.\n * Mirrors autopause's `coarsePauseState`, but here any live session expecting\n * attention (waiting/question/end-plan) counts as `active` so we never let it\n * be killed mid-interaction; only a settled `idle` is the lapse candidate.\n * error/unknown/null → null (don't keep a wedged or unknown box alive forever).\n */\nfunction coarseKeepaliveState(s: WorkingAgentState | null): KeepaliveAgentState {\n switch (s) {\n case 'working':\n case 'compacting':\n case 'waiting':\n case 'question':\n case 'end-plan':\n return 'active';\n case 'idle':\n return 'idle';\n default:\n return null;\n }\n}\n\n/** What the box-record lookup yields for seeding + the renew call. */\nexport interface CloudBoxLookup {\n sandboxId: string;\n /** Box creation time as epoch ms, or null when unparseable. */\n createdAtMs: number | null;\n /** Recorded effective create timeout (ms), or null when not recorded. */\n createTimeoutMs: number | null;\n}\n\nexport interface CloudKeepaliveLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global autopause config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `resolveCloudBackend`. */\n resolveBackend?: (name: string) => Promise<CloudBackend>;\n /** Injectable for tests; defaults to the state.json box lookup. */\n lookupBox?: (boxId: string) => Promise<CloudBoxLookup | null>;\n /** Injectable for tests; fallback create timeout when a record lacks one. */\n fallbackCreateTimeoutMs?: (backend: string) => Promise<number>;\n /** Injectable for tests; defaults to `Date.now`. */\n now?: () => number;\n intervalMs?: number;\n}\n\nexport interface CloudKeepaliveLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n/** After a failed renew, skip the box for this long (avoid cap hammering / log spam). */\nconst FAILURE_BACKOFF_MS = 5 * 60_000;\n\nexport function startCloudKeepaliveLoop(\n deps: CloudKeepaliveLoopDeps,\n): CloudKeepaliveLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const resolveBackend = deps.resolveBackend ?? resolveCloudBackend;\n const lookupBox = deps.lookupBox ?? defaultLookupBox;\n const fallbackCreateTimeoutMs = deps.fallbackCreateTimeoutMs ?? defaultFallbackCreateTimeoutMs;\n const nowFn = deps.now ?? Date.now;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, log } = deps;\n\n // Per-box intended death-time we've pushed the session to. Seeded lazily from\n // the recorded `createdAt + create-timeout`; in-memory only — a relay restart\n // re-seeds (at worst one corrective over-extend, bounded by the plan cap).\n const tracked = new Map<string, number>();\n // Per-box \"don't attempt before\" time, set after a failed renew.\n const backoffUntil = new Map<string, number>();\n // Resolved backends cached across ticks (one dynamic import per provider).\n const backendCache = new Map<string, CloudBackend | null>();\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function resolveCached(name: string): Promise<CloudBackend | null> {\n if (backendCache.has(name)) return backendCache.get(name) ?? null;\n let backend: CloudBackend | null = null;\n try {\n backend = await resolveBackend(name);\n } catch {\n backend = null; // no executor for this backend — skip its boxes\n }\n backendCache.set(name, backend);\n return backend;\n }\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n const windowMs = cfg.idleMinutes * 60_000;\n const now = nowFn();\n\n const live = new Set<string>();\n const entries: KeepaliveScanEntry[] = [];\n for (const reg of registry.list()) {\n if (reg.kind !== 'cloud' || !reg.backend) continue;\n const backend = await resolveCached(reg.backend);\n if (!backend || typeof backend.renewTimeout !== 'function') continue;\n live.add(reg.boxId);\n const active = readActiveAgent(statusStore.get(reg.boxId));\n entries.push({\n boxId: reg.boxId,\n backend: reg.backend,\n agentState: coarseKeepaliveState(active.state),\n lastActivityMs: active.updatedAt ? toEpoch(active.updatedAt) : null,\n });\n }\n\n // Drop per-box state for boxes that are gone (destroyed / forgotten).\n for (const id of [...tracked.keys()]) if (!live.has(id)) tracked.delete(id);\n for (const id of [...backoffUntil.keys()]) if (!live.has(id)) backoffUntil.delete(id);\n\n const decisions = selectBoxesToRenew(entries, windowMs, now);\n for (const d of decisions) {\n const until = backoffUntil.get(d.boxId);\n if (until != null && now < until) continue; // recently failed — wait\n\n const lookup = await lookupBox(d.boxId);\n if (!lookup) continue;\n\n // Seed the tracked deadline from the recorded effective create timeout\n // (falls back to a provider default for pre-feature records).\n let current = tracked.get(d.boxId);\n if (current == null) {\n const createMs = lookup.createdAtMs ?? now;\n const createTimeoutMs =\n lookup.createTimeoutMs ?? (await fallbackCreateTimeoutMs(d.backend));\n current = createMs + createTimeoutMs;\n tracked.set(d.boxId, current);\n }\n // Only renew when the target meaningfully exceeds the tracked deadline,\n // so we don't churn the SDK for sub-tick gains or extend a box still\n // riding its create timeout.\n if (d.targetDeadlineEpochMs <= current + intervalMs) continue;\n\n try {\n const backend = await resolveCached(d.backend);\n if (!backend?.renewTimeout) continue;\n await backend.renewTimeout({ sandboxId: lookup.sandboxId }, d.targetDeadlineEpochMs, current);\n // Only advance the tracked deadline on SUCCESS — a failed extend did\n // not actually move the real deadline, so we must not record it.\n tracked.set(d.boxId, d.targetDeadlineEpochMs);\n backoffUntil.delete(d.boxId);\n log(\n `cloud-keepalive: renewed box ${d.boxId} (${d.backend}) ` +\n `+${String(Math.round((d.targetDeadlineEpochMs - now) / 60_000))}m`,\n );\n } catch (err) {\n // Plan-cap rejection or a transient SDK error. Leave `tracked`\n // unchanged (so we retry once the backoff lapses) and back the box\n // off briefly to avoid hammering the cap / spamming the log.\n backoffUntil.set(d.boxId, now + FAILURE_BACKOFF_MS);\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: renew box ${d.boxId} (${d.backend}) failed: ${msg}`);\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\nfunction toEpoch(iso: string | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : t;\n}\n\n/** Resolve a box's cloud sandboxId + create facts from `~/.agentbox/state.json`. */\nasync function defaultLookupBox(boxId: string): Promise<CloudBoxLookup | null> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') return null;\n const sandboxId = hit.box.cloud?.sandboxId;\n if (!sandboxId) return null;\n return {\n sandboxId,\n createdAtMs: toEpoch(hit.box.createdAt),\n createTimeoutMs: hit.box.cloud?.sessionTimeoutMs ?? null,\n };\n}\n\n/**\n * Fallback create timeout for a box record that predates `sessionTimeoutMs`.\n * Vercel reads the global `box.vercelTimeoutMs`; other backends use the shared\n * 45-min default (matches the backends' `DEFAULT_TIMEOUT_MS`). A close estimate\n * is enough — the renew gate tolerates seed drift and self-corrects.\n */\nasync function defaultFallbackCreateTimeoutMs(backend: string): Promise<number> {\n const generic = 45 * 60_000;\n if (backend !== 'vercel') return generic;\n const fallback = BUILT_IN_DEFAULTS.box.vercelTimeoutMs;\n try {\n const global: Partial<UserConfig> = parseUserConfig(\n await readFile(GLOBAL_CONFIG_FILE, 'utf8'),\n GLOBAL_CONFIG_FILE,\n );\n const v = global.box?.vercelTimeoutMs;\n return typeof v === 'number' && v > 0 ? v : fallback;\n } catch {\n return fallback;\n }\n}\n","import { startRelayServer, type RelayServerHandle, type RelayServerOptions } from './server.js';\nimport { startAutopauseLoop } from './autopause.js';\nimport { startCloudKeepaliveLoop } from './cloud-keepalive.js';\nimport { startQueueLoop } from './queue.js';\n\nexport interface RelayDaemonHandle {\n /** The underlying relay server (url, store, close, …). */\n handle: RelayServerHandle;\n /** Stop the background loops, then close the server. */\n stop: () => Promise<void>;\n}\n\n/**\n * Boot the relay HTTP server plus its background loops (autopause / cloud\n * keepalive / queue) — the daemon that `agentbox-relay serve` runs. Extracted\n * so the hub server can import it, prepare Next, and pass Next's request\n * handler in as `opts.uiHandler` to serve the UI on the relay's own port.\n *\n * Process-owner concerns (the \"listening\" log line, SIGTERM/SIGINT handling)\n * stay with the caller so the same daemon works under both the relay bin and\n * the hub server.\n */\nexport async function startRelayDaemon(opts: RelayServerOptions): Promise<RelayDaemonHandle> {\n const handle = await startRelayServer(opts);\n const log = opts.logger ?? (() => {});\n const autopause = startAutopauseLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n events: handle.events,\n log,\n });\n const cloudKeepalive = startCloudKeepaliveLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n log,\n });\n const queue = startQueueLoop({\n log,\n registry: handle.registry,\n statusStore: handle.statusStore,\n // Refresh the embedded hub UI whenever a background job flips state\n // (queued → running → done/failed), so a create job's box shows up and\n // then transitions creating → running without waiting for the 15s SSE ping.\n onStatusChange: () => handle.hubNotifier.notify(),\n });\n // `poke` isn't on the declared QueueLoopHandle (only `stop` is); same cast bin.ts used.\n handle.setQueuePoke(() => {\n (queue as { poke?: () => void }).poke?.();\n });\n\n return {\n handle,\n stop: async () => {\n await Promise.allSettled([autopause.stop(), cloudKeepalive.stop(), queue.stop()]);\n await handle.close();\n },\n };\n}\n","import type { IntegrationConnector, IntegrationOpRefusal } from '../types.js';\n\n/**\n * Linear connector — wraps `@schpet/linear-cli` (the `linear` binary, v2).\n *\n * The op allowlist is intentionally minimal (start conservative, widen as\n * real agent flows surface needs). Reads cover identity/listing/lookup\n * (`whoami`, `issue list/view/query`, `team list`) plus a GraphQL\n * passthrough (`api`), and writes are limited to issue create/update and a\n * gated comment. The `api` passthrough is query-only —\n * `refuseGraphqlNonQuery` rejects any operation whose first non-whitespace\n * keyword is `mutation` or `subscription`, so the GraphQL endpoint can't\n * be used to slip a write past the read classification (the GraphQL\n * analogue of `notion.api`'s `refuseApiNonGet`).\n *\n * Three subcommands are deliberately absent from the allowlist for\n * security reasons:\n * - `auth token` — PRINTS the raw API token to stdout; proxying it\n * through the relay would expose the host credential to the box.\n * The only `auth` op we expose is `auth whoami` (identity only), via\n * the `whoami` op.\n * - `auth login` / `auth logout` / `auth migrate` / `auth default` —\n * the host owns auth; relaying these would mutate host state.\n * - `issue delete` / `team delete` / `team create` — destructive and\n * unnecessary for the documented agent flows. Add deliberately, as\n * gated writes, only when a real flow needs them.\n *\n * No `env` override is needed (neither connector sets one). Linear stores\n * plaintext credentials at `~/.config/linear/credentials.toml` and keychain\n * mode is opt-in, not the default, so `linear` reads file-based auth on every\n * host without any env shaping. The carry block in `agentbox.yaml` ships that\n * file into nested boxes that run their own relay.\n */\nexport const linearConnector: IntegrationConnector = {\n service: 'linear',\n hostBin: 'linear',\n detect: {\n versionArgs: ['--version'],\n authArgs: ['auth', 'whoami'],\n installHint: 'install @schpet/linear-cli: npm i -g @schpet/linear-cli',\n loginHint: 'linear auth login',\n },\n ops: {\n whoami: {\n write: false,\n buildArgv: (args) => ['auth', 'whoami', ...args],\n },\n 'issue.list': {\n write: false,\n buildArgv: (args) => ['issue', 'list', ...args],\n },\n 'issue.mine': {\n // The v2-native read for \"issues assigned to me\" — the README directs\n // users here in place of the older `issue list --me`. Listed as a\n // separate op so the shim doesn't reject the canonical form.\n write: false,\n buildArgv: (args) => ['issue', 'mine', ...args],\n },\n 'issue.view': {\n write: false,\n buildArgv: (args) => ['issue', 'view', ...args],\n },\n 'issue.query': {\n write: false,\n buildArgv: (args) => ['issue', 'query', ...args],\n },\n 'team.list': {\n write: false,\n buildArgv: (args) => ['team', 'list', ...args],\n },\n api: {\n write: false,\n buildArgv: (args) => ['api', ...args],\n refuseCall: refuseGraphqlNonQuery,\n },\n 'issue.create': {\n write: true,\n buildArgv: (args) => ['issue', 'create', ...args],\n },\n 'issue.update': {\n write: true,\n buildArgv: (args) => ['issue', 'update', ...args],\n },\n 'issue.comment': {\n // Maps to `linear issue comment add` — `@schpet/linear-cli` v2 uses\n // `add` (not `create`); `add`'s sibling subcommands are `list`,\n // `update`, `delete`.\n write: true,\n buildArgv: (args) => ['issue', 'comment', 'add', ...args],\n },\n },\n};\n\n/**\n * Reject any `linear api` call whose GraphQL source declares a `mutation`\n * or `subscription` operation. The Linear `api` op is a single POST that\n * serves both reads and writes — without this guard, the \"read\"\n * classification would be a hole the agent could slip writes through.\n *\n * `linear-cli`'s `api` subcommand takes the GraphQL query as a positional\n * argument and accepts `--variable key=value` (repeatable; the value may\n * be `@/path` to load from a host file — see below), `--variables-json\n * <json>`, `--paginate`, and `--silent`. We:\n *\n * 1. Refuse `--variable key=@<path>` (and the `=` and `--variable=`\n * glued forms) because they would let the box trigger arbitrary\n * host-file reads — the file contents become GraphQL variables and\n * can be echoed back through the response, an exfiltration channel.\n * 2. Refuse `--input` for parity with `refuseApiNonGet`, even though\n * `linear api` doesn't currently accept it — if a future version\n * adds it, the guard pre-empts the stdin/file-body shape.\n * 3. Walk argv consuming value-bearing flags (`--variable`,\n * `--variables-json`) so their JSON/key=value payload isn't\n * misread as an operation keyword.\n * 4. For every remaining positional (non-flag) token, strip leading\n * whitespace + `# …` line comments and reject the call if the\n * first identifier is `mutation` or `subscription`.\n *\n * `query …` and the anonymous `{ … }` shorthand pass. Empty/flag-only\n * argv passes (the host CLI emits its own usage error).\n */\nfunction refuseGraphqlNonQuery(args: readonly string[]): IntegrationOpRefusal | null {\n const refuse = (reason: string): IntegrationOpRefusal => ({\n exitCode: 65,\n stderr: `linear api: ${reason}\\n`,\n });\n // `--variable` and `--variables-json` each take the next argv token as\n // their value — the loop consumes them explicitly below so a JSON\n // payload starting with `mutation`/`subscription` isn't misread as the\n // GraphQL operation. The consume-next branches refuse to swallow the\n // next token if it LOOKS like a flag (`--…`) — otherwise a malformed\n // `--variable --input=/etc/passwd` would silently skip the `--input`\n // refusal one iteration later.\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\"'--input' (stdin/file body) isn't supported through the relay\");\n }\n // `--variable key=@/host/path` reads from a host file — refuse the\n // `@`-prefixed value form regardless of split/glued/equals shape.\n if (arg === '--variable') {\n const next = args[i + 1] ?? '';\n if (variableValueIsFileLoad(next)) {\n return refuse(\n \"'--variable key=@<path>' (host-file load) isn't supported through the relay\",\n );\n }\n // Don't consume a token that's itself a flag — it needs to run\n // through its own per-flag checks (e.g. `--variable --input=/x`).\n if (!next.startsWith('--')) i++;\n continue;\n }\n if (arg.startsWith('--variable=')) {\n if (variableValueIsFileLoad(arg.slice('--variable='.length))) {\n return refuse(\n \"'--variable=key=@<path>' (host-file load) isn't supported through the relay\",\n );\n }\n continue;\n }\n if (arg === '--variables-json') {\n const next = args[i + 1] ?? '';\n if (!next.startsWith('--')) i++;\n continue;\n }\n if (arg.startsWith('--variables-json=')) {\n continue;\n }\n // Only LONG flags (`--…`) skip the keyword check. A bare `-` or a\n // single-dash token like `-mutation` is treated as a positional so\n // it goes through `firstGraphqlOperationKeyword` and the\n // unparseable/mutation cases fail closed.\n if (arg.startsWith('--')) continue;\n const op = firstGraphqlOperationKeyword(arg);\n if (op === 'mutation' || op === 'subscription') {\n return refuse(\n `only GraphQL queries are proxied (use issue.create / issue.update / issue.comment for writes); detected operation '${op}'`,\n );\n }\n // `unparseable` (a positional whose first significant char isn't `{`\n // or an ASCII letter) is refused too. Real queries start with `query`,\n // `mutation`, `subscription`, or `{`. Anything else is a garbage\n // shape that we'd rather not forward — the agent gets a clear refusal\n // instead of an opaque host CLI error.\n if (op === 'unparseable') {\n return refuse(\n `couldn't classify positional argv ${JSON.stringify(arg)} as a GraphQL operation (expected 'query', 'mutation', 'subscription', or '{')`,\n );\n }\n }\n return null;\n}\n\n/**\n * True when a `--variable` value uses linear-cli's `@<path>` host-file load\n * syntax. The standard shape is `key=@<path>`, but we refuse any value\n * that CONTAINS `=@` or a bare leading `@` — guards against:\n * - `key=@<path>` (canonical).\n * - `@<path>` (bare, no `key=` prefix).\n * - `key=name=@<path>` where a `=` appears in the key/name portion.\n * linear-cli's `--variable` parser may split on the FIRST `=` (so the\n * value is `name=@<path>`) or on the LAST `=` (so the value is\n * `@<path>`); we refuse both interpretations by treating any `=@`\n * anywhere in the string as a file-load signal.\n * - Future shape changes: if linear-cli adds escaping or new prefixes,\n * refusing on the literal `=@` substring stays conservative.\n */\nfunction variableValueIsFileLoad(value: string): boolean {\n if (value.startsWith('@')) return true;\n return value.includes('=@');\n}\n\n/**\n * Extract the first GraphQL operation keyword from a source string after\n * stripping leading whitespace and `# …` line comments. Returns the\n * keyword (`query` | `mutation` | `subscription`) when one is found,\n * `'anonymous'` for the `{ … }` shorthand, or `null` for an empty source.\n * Only the prefix matters — the rest of the source is not validated;\n * we're not a GraphQL parser, just a write-shape detector.\n *\n * Returns `'unparseable'` (not null) for sources whose first non-whitespace\n * non-comment character isn't `{` or an ASCII letter — that way an outer\n * gate can decide to fail-CLOSED on shapes it doesn't recognize (BOM,\n * NBSP, stray punctuator, etc.) instead of silently passing them. The\n * caller in `refuseGraphqlNonQuery` is unchanged: it only refuses on\n * `mutation` / `subscription`, so `'unparseable'` still passes — but the\n * sentinel is available for a future stricter mode.\n *\n * The whitespace test uses the JS `\\s` class so Unicode whitespace\n * (U+00A0 NBSP, U+2028, the BOM U+FEFF, etc.) is stripped before the\n * keyword check — otherwise a `'mutation {…}'` source would\n * bypass the gate because `` is not in `[ \\t\\n\\r,]` and not an\n * ASCII letter, so `j === i` and the function returned null.\n */\nfunction firstGraphqlOperationKeyword(source: string): string | null {\n let i = 0;\n const n = source.length;\n while (i < n) {\n const c = source[i]!;\n if (/\\s/.test(c) || c === ',' || c === '') {\n i++;\n continue;\n }\n if (c === '#') {\n while (i < n && source[i] !== '\\n') i++;\n continue;\n }\n break;\n }\n if (i >= n) return null;\n if (source[i] === '{') return 'anonymous';\n let j = i;\n while (j < n) {\n const c = source[j]!;\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {\n j++;\n } else {\n break;\n }\n }\n // No leading ASCII letter and not `{` — the source's first significant\n // character is something we can't classify (stray punctuator, smart\n // quote, control char). Return a sentinel rather than null so the gate\n // can choose to be paranoid in the future.\n if (j === i) return 'unparseable';\n return source.slice(i, j).toLowerCase();\n}\n","import type { IntegrationConnector, IntegrationOpRefusal } from '../types.js';\n\n/**\n * Notion connector — wraps the official `ntn` CLI (beta, first-party).\n *\n * The op allowlist is intentionally minimal (start conservative, widen as\n * real agent flows surface needs). Two read passthroughs (`ntn whoami` and\n * `ntn api …` against the v1 REST surface) plus two gated writes. The `api`\n * passthrough is read-only — `refuseUnsafeApiCall` allows GET to any endpoint\n * and POST only to Notion's read-by-POST endpoints (`v1/search`, database /\n * data-source `/query`), and refuses everything else, so an agent can't slip a\n * write past the \"read\" classification.\n *\n * Comment creation is intentionally absent: `ntn` exposes no top-level\n * `comment` subcommand (the official surface is `api datasources files\n * pages login logout whoami workers`), and Notion's REST POST `/v1/comments`\n * takes a structured JSON body that doesn't trivially map from CLI flags.\n * Adding it is tracked as a focused follow-up — see `docs/notion_backlog.md`.\n *\n * No `env` override: the relay runs the host's `ntn` with its own default\n * auth (the macOS keychain after `ntn login`), matching what `agentbox\n * doctor` probes and what the public docs tell users to do. The carry-based\n * nested-box dev path (a Linux box hosting a relay) needs file-based auth\n * instead; that's an internal-dev concern documented in\n * `docs/development.md`, not something the connector forces on every host.\n */\nexport const notionConnector: IntegrationConnector = {\n service: 'notion',\n hostBin: 'ntn',\n detect: {\n versionArgs: ['--version'],\n authArgs: ['api', 'v1/users/me'],\n installHint: 'install ntn: https://developers.notion.com/reference/notion-cli',\n loginHint: 'ntn login',\n },\n ops: {\n whoami: {\n write: false,\n buildArgv: (args) => ['whoami', ...args],\n },\n api: {\n write: false,\n buildArgv: (args) => ['api', ...args],\n refuseCall: refuseUnsafeApiCall,\n },\n 'page.create': {\n write: true,\n buildArgv: (args) => ['pages', 'create', ...args],\n },\n 'page.update': {\n write: true,\n buildArgv: (args) => ['pages', 'update', ...args],\n },\n },\n};\n\n/**\n * Notion's read-by-POST endpoints — the only POSTs `ntn api` may proxy.\n * Anchored, leading-slash-tolerant, and `[^/?]+` for the id segment so a\n * query string or extra path component can't smuggle a different endpoint.\n */\nconst READ_POST_ENDPOINTS: readonly RegExp[] = [\n /^\\/?v1\\/search$/,\n /^\\/?v1\\/databases\\/[^/?]+\\/query$/,\n /^\\/?v1\\/data_sources\\/[^/?]+\\/query$/,\n];\n\n/**\n * The only flags `ntn api` accepts that take NO value and are safe for a\n * read-only proxy. The gate is fail-closed: every other flag is refused, so an\n * unrecognized value-consuming flag can't have its value misparsed as the\n * endpoint (see `refuseUnsafeApiCall`). Value-consuming flags (`-X/--method`,\n * `-d/--data`, `--notion-version`, `--file`) are handled explicitly before this.\n */\nconst SAFE_API_BOOLEAN_FLAGS: ReadonlySet<string> = new Set([\n '--spec',\n '--docs',\n '-h',\n '--help',\n '-v',\n '--verbose',\n '-V',\n '--version',\n]);\n\n/**\n * Reject any `ntn api` call that isn't a read. A read is: GET to any endpoint,\n * or POST to one of {@link READ_POST_ENDPOINTS} (search + database/data-source\n * `/query` — POST in the Notion API but semantically reads). Everything else —\n * writes (`v1/pages`, `v1/comments`, …), PATCH/PUT/DELETE, POST to a\n * non-read endpoint — is refused; writes go through `page.create`/`page.update`.\n *\n * `ntn api`'s real surface (verified via `ntn api --help`): method is inferred\n * from endpoint + body; `-X`/`--method` overrides; body sources are `-d`/`--data\n * <JSON>` and inline assignments (`path=value`, `path:=json`) — NOT `gh`-style\n * `-f`/`-F` (which `ntn` doesn't have). We classify any body source as non-GET\n * so a write can't slip through as a body-less \"GET\". `--input` (stdin/file\n * body) and `--file` (host-file upload) read host state and can't traverse the\n * relay, so both are refused outright.\n *\n * Kept here (next to the op declaration) — not exported — because the test\n * surface is \"does notion.api refuse this call\", not the parser shape.\n */\nfunction refuseUnsafeApiCall(args: readonly string[]): IntegrationOpRefusal | null {\n const refuse = (reason: string): IntegrationOpRefusal => ({\n exitCode: 65,\n stderr: `notion api: ${reason}\\n`,\n });\n\n let explicitMethod: string | null = null;\n let hasBody = false;\n let endpoint: string | null = null;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n\n // Explicit method (split, glued, or `=`-joined).\n if (arg === '-X' || arg === '--method') {\n explicitMethod = args[i + 1] ?? '';\n i++;\n continue;\n }\n if (arg.startsWith('--method=')) {\n explicitMethod = arg.slice('--method='.length);\n continue;\n }\n if (arg.startsWith('-X') && arg.length > 2) {\n explicitMethod = arg.slice(2).replace(/^=/, '');\n continue;\n }\n\n // Raw JSON body — implies a write-class request unless the endpoint is read.\n if (arg === '-d' || arg === '--data') {\n hasBody = true;\n i++;\n continue;\n }\n if (arg.startsWith('--data=') || (arg.startsWith('-d') && arg.length > 2)) {\n hasBody = true;\n continue;\n }\n\n // Host-file / stdin bodies: can't traverse the relay, and `--file` reads an\n // arbitrary host file. Refuse both regardless of endpoint.\n if (arg === '--file' || arg.startsWith('--file=')) {\n return refuse(\"'--file' (host-file upload) isn't supported through the relay\");\n }\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\"'--input' (stdin/file body) isn't supported through the relay; use -d <JSON>\");\n }\n\n // `--notion-version <VERSION>` — value-consuming; forwarded unchanged.\n if (arg === '--notion-version') {\n i++;\n continue;\n }\n if (arg.startsWith('--notion-version=')) continue;\n\n // Remaining flags are fail-closed: only a known-safe boolean set passes.\n // Anything else is refused rather than ignored, so an unrecognized\n // value-consuming flag — e.g. ntn's global `--workers-config-file <path>`\n // or the hidden `--env <env>`, both accepted after `api` — can't have its\n // value silently misread as the endpoint and smuggle a write past the gate\n // (`api --workers-config-file v1/search v1/pages` POSTs to v1/pages).\n if (arg.startsWith('-')) {\n if (SAFE_API_BOOLEAN_FLAGS.has(arg)) continue;\n return refuse(\n `unsupported option '${arg}' (read-only api accepts a path, inline inputs, ` +\n `-d <JSON>, -X GET/POST, --notion-version, --spec, --docs)`,\n );\n }\n\n // First bare positional is the API path; the rest are inline inputs.\n if (endpoint === null) {\n endpoint = arg;\n continue;\n }\n if (isBodyAssignment(arg)) hasBody = true;\n }\n\n const method = (\n explicitMethod && explicitMethod.length > 0 ? explicitMethod : hasBody ? 'POST' : 'GET'\n ).toUpperCase();\n\n if (method === 'GET') return null;\n if (method !== 'POST') {\n return refuse(\n `only GET and read-only POST are proxied (use page.create / page.update for writes); detected method '${method}'`,\n );\n }\n if (endpoint === null) {\n return refuse('could not determine the API endpoint for a non-GET call');\n }\n // Defense in depth: ntn resolves `.`/`..` before routing, so reject any\n // traversal segment rather than trusting the anchored regexes alone.\n if (endpoint.split('/').some((seg) => seg === '.' || seg === '..')) {\n return refuse(`path traversal segments ('.' / '..') are not allowed in '${endpoint}'`);\n }\n if (READ_POST_ENDPOINTS.some((re) => re.test(endpoint!))) return null;\n return refuse(\n `POST is only proxied for read endpoints (v1/search, v1/databases/{id}/query, ` +\n `v1/data_sources/{id}/query); '${endpoint}' is not one (use page.create / page.update for writes)`,\n );\n}\n\n/**\n * Whether an inline-input token is a request-BODY assignment (so it implies a\n * write-class request). `ntn` inline syntax: `path:=json` (typed body) and\n * `path=value` (string body) are bodies; `name==value` (query param) and\n * `Header:Value` (header) are not.\n */\nfunction isBodyAssignment(token: string): boolean {\n if (token.includes(':=')) return true;\n if (token.includes('==')) return false;\n return token.includes('=');\n}\n","import { linearConnector } from './connectors/linear.js';\nimport { notionConnector } from './connectors/notion.js';\nimport type { IntegrationConnector } from './types.js';\n\n/**\n * All integration connectors known to AgentBox. The relay's dispatcher\n * walks this list to validate `integration.<service>.<op>` calls — anything\n * not present is denied. Mirrors `packages/core/src/provider.ts`'s\n * registry pattern for the provider abstraction.\n */\nexport const ALL_CONNECTORS: readonly IntegrationConnector[] = [notionConnector, linearConnector];\n\n/** Lookup by `IntegrationConnector.service`. Returns `null` for unknown. */\nexport function getConnector(service: string): IntegrationConnector | null {\n for (const c of ALL_CONNECTORS) {\n if (c.service === service) return c;\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEAA,SAAS,iBAAiB;AAC1B,SAAS,WAAAA,UAAS,WAAAC,UAAS,YAAAC,YAAU,MAAAC,KAAI,QAAAC,OAAM,aAAAC,kBAAiB;AAChE,SAAS,WAAAC,UAAS,UAAAC,eAAc;AAChC,SAAS,QAAAC,aAAY;AACrB,SAAS,cAAc,aAAa;AACpC,SAAS,SAAAC,cAAa;ACLtB,SAAS,SAAAC,cAA0B;ACAnC,SAAS,SAAAC,QAAO,YAAAC,WAAU,WAAAC,UAAS,YAAY;AAC/C,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,e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WAAW,CAAC,iBAAiB,WAAW,MAAM,GAAG;IAC5E,MAAM;IACN;EACF,CAAC;AACD,MAAI,qBAAqB,KAAK,QAAQ,KAAK,QAAQ,GAAG;AACpD,WAAO,EAAE,IAAI,MAAM,gBAAgB,KAAK;EAC1C;AAEA,QAAM,OAAO,MAAM,UAAU,WAAW,CAAC,iBAAiB,QAAQ,YAAY,SAAS,GAAG;IACxF,MAAM;IACN;EACF,CAAC;AACD,MAAI,KAAK,aAAa,EAAG,QAAO,EAAE,IAAI,KAAK;AAC3C,SAAO;IACL,IAAI;IACJ,QAAQ,8BAA8B,KAAK,UAAU,KAAK,UAAU,QAAQ,OAAO,KAAK,QAAQ,CAAC,EAAE;EACrG;AACF;AAeA,eAAsB,2BAA2B,KAMhB;AAC/B,QAAM,YAAY,MAAM,cAAc,GAAG;AACzC,QAAM,aAAa,WAAW,SAAS,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ;AACtE,QAAM,SACJ,eAAe,SACV,IAAI,eAAe,oBAAoB,OAAO,UAAU,CAAC,KAC1D;AACN,QAAM,MAAM,MAAM,iBAAiB,IAAI,WAAW,QAAW,MAAM;AACnE,SAAO,EAAE,GAAG,KAAK,OAAO;AAC1B;","names":["mkdtemp","readdir","readFile","rm","stat","writeFile","homedir","tmpdir","join","execa","execa","mkdir","readFile","readdir","createHash","dirname","join","execa","mkdir","basename","join","execa","spawnSync","readFile","stat","homedir","join","execa","homedir","join","spawnSync","stat","homedir","join","execa","execa","mkdir","stat","homedir","basename","join","resolve","execa","readFile","parseYaml","readFile","parseYaml","isPlainObject","name","restart","command","parseYaml","parseReplacements","readFile","rules","randomBytes","execa","existsSync","readFile","homedir","join","execa","execa","mkdir","readdir","rm","stat","homedir","join","resolve","mkdir","mkdtemp","readFile","readdir","rm","writeFile","homedir","tmpdir","basename","join","execa","stat","execa","randomBytes","existsSync","mkdir","readFile","readdir","rename","rm","unlink","writeFile","homedir","dirname","join","resolve","delay","cached","createBox","err","execa","spawn","randomBytes","join","join","join","randomBytes","join","readState","spawn","join","execa","readdir","rm","stat","join","execa","join","homedir","join","execa","mkdir","dirname","join","execa","spawn","existsSync","openSync","readFile","unlink","writeFile","homedir","resolve","delay","fileURLToPath","execa","BOX_HOME","isDir","cp","join","readFile","mkdir","createHash","readdir","dirname","chmod","stat","homedir","mkdtemp","tmpdir","writeFile","rm","shQuote","basename","pathExists","spawnSync","randomBytes","r","existsSync","sanitizeMnemonic","resolve","shellSingleQuote","STATE_DIR","processAlive","delay","unlink","rename","pidAlive","branch","gitWorktreePath","makeSyncContext","loadConfig","persisted","endpoints","syncAgentboxSshConfig","record","posixDirname","PORT","DEFAULT_RELAY_PORT","fileURLToPath","openSync","spawn"]}