@ai-hero/sandcastle 0.12.0 → 0.14.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.
- package/README.md +15 -1368
- package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
- package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
- package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
- package/dist/chunk-6NQPCXSG.js.map +1 -0
- package/dist/chunk-7N7AMUYA.js +353 -0
- package/dist/chunk-7N7AMUYA.js.map +1 -0
- package/dist/chunk-ATA2V2TC.js +112 -0
- package/dist/chunk-ATA2V2TC.js.map +1 -0
- package/dist/chunk-BIF2X6QB.js +94 -0
- package/dist/chunk-BIF2X6QB.js.map +1 -0
- package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
- package/dist/chunk-BVZWLFFT.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/chunk-G2R53CVZ.js +3172 -0
- package/dist/chunk-G2R53CVZ.js.map +1 -0
- package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
- package/dist/chunk-GCLEXPXG.js.map +1 -0
- package/dist/chunk-H2PEFS4W.js +1244 -0
- package/dist/chunk-H2PEFS4W.js.map +1 -0
- package/dist/chunk-HSXPRZKG.js +150 -0
- package/dist/chunk-HSXPRZKG.js.map +1 -0
- package/dist/chunk-IBK2XNSS.js +50 -0
- package/dist/chunk-IBK2XNSS.js.map +1 -0
- package/dist/chunk-RDW7FNN6.js +792 -0
- package/dist/chunk-RDW7FNN6.js.map +1 -0
- package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
- package/dist/chunk-S6UHPTRG.js.map +1 -0
- package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
- package/dist/chunk-STB2U7BB.js.map +1 -0
- package/dist/chunk-VRXR2T3S.js +24 -0
- package/dist/chunk-VRXR2T3S.js.map +1 -0
- package/dist/index.d.ts +241 -26
- package/dist/index.js +1082 -1679
- package/dist/index.js.map +1 -1
- package/dist/main.js +1248 -854
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +58 -0
- package/dist/sandboxes/bwrap.js +296 -0
- package/dist/sandboxes/bwrap.js.map +1 -0
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +203 -98
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +18 -4
- package/dist/sandboxes/docker.js +7 -4
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +2 -2
- package/dist/sandboxes/podman.d.ts +18 -4
- package/dist/sandboxes/podman.js +72 -56
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +65 -0
- package/dist/sandboxes/seatbelt.js +425 -0
- package/dist/sandboxes/seatbelt.js.map +1 -0
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +198 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +12 -5
- package/dist/sandboxes/vercel.js +195 -126
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +13 -22
- package/dist/templates/parallel-planner-with-review/main.mts +13 -15
- package/package.json +63 -11
- package/dist/chunk-62WN33RK.js +0 -104
- package/dist/chunk-62WN33RK.js.map +0 -1
- package/dist/chunk-BIWNFKGV.js.map +0 -1
- package/dist/chunk-CP3TYXZA.js.map +0 -1
- package/dist/chunk-DJRHWPEH.js.map +0 -1
- package/dist/chunk-NGBM7T3E.js.map +0 -1
- package/dist/chunk-VOG34SRF.js.map +0 -1
- package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/sandboxes/vercel.ts"],"names":["result"],"mappings":";;;;;;;;;;AAsBA,IAAM,gBAAA,GAAmB,2BAAA;AA+GlB,IAAM,MAAA,GAAS,CAAC,OAAA,KACrB,6BAAA,CAA8B;AAAA,EAC5B,IAAA,EAAM,QAAA;AAAA,EACN,KAAK,OAAA,EAAS,GAAA;AAAA,EACd,MAAA,EAAQ,OAAO,aAAA,KAAkD;AAC/D,IAAA,MAAM,kBAAA,GAAqB,SAAS,kBAAA,IAAsB,cAAA;AAE1D,IAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,MAAM,OAAO,iBAAiB,CAAA;AAElD,IAAA,MAAM,eAAwC,EAAC;AAG/C,IAAA,IAAI,OAAA,EAAS,MAAA,EAAQ,YAAA,CAAa,MAAA,GAAS,OAAA,CAAQ,MAAA;AACnD,IAAA,IAAI,OAAA,EAAS,KAAA,EAAO,YAAA,CAAa,KAAA,GAAQ,OAAA,CAAQ,KAAA;AACjD,IAAA,IAAI,OAAA,EAAS,SAAA,EAAW,YAAA,CAAa,SAAA,GAAY,OAAA,CAAQ,SAAA;AACzD,IAAA,IAAI,OAAA,EAAS,aAAA;AACX,MAAA,YAAA,CAAa,gBAAgB,OAAA,CAAQ,aAAA;AAEvC,IAAA,MAAM,eAAA,GAAkB,OAAA,EAAS,OAAA,IAAW,OAAA,EAAS,QAAA;AACrD,IAAA,IAAI,eAAA,eAA8B,OAAA,GAAU,eAAA;AAG5C,IAAA,MAAM,YAAA,GAAe,OAAA,EAAS,OAAA,IAAW,OAAA,EAAS,SAAA;AAClD,IAAA,IAAI,YAAA,KAAiB,MAAA,EAAW,YAAA,CAAa,OAAA,GAAU,YAAA;AAGvD,IAAA,Y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,YAAA,MAAM,MAAA,CAAO,OAAO,CAAA,CAAE,KAAA,CAAM,MAAM;AAAA,YAAC,CAAC,CAAA;AAAA,UACtC;AAAA,QACF,CAAA,MAAO;AACL,UAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,QAAQ,CAAA;AACvC,UAAA,MAAM,OAAA,CAAQ,WAAW,CAAC,EAAE,MAAM,WAAA,EAAa,OAAA,EAAS,CAAC,CAAA;AAAA,QAC3D;AAAA,MACF,CAAA;AAAA,MAEA,WAAA,EAAa,OACX,WAAA,EACA,QAAA,KACkB;AAClB,QAAA,MAAM,MAAA,GAAS,MAAM,OAAA,CAAQ,gBAAA,CAAiB;AAAA,UAC5C,IAAA,EAAM;AAAA,SACP,CAAA;AACD,QAAA,IAAI,CAAC,MAAA,EAAQ;AACX,UAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,WAAW,CAAA,CAAE,CAAA;AAAA,QACpE;AACA,QAAA,MAAM,MAAM,OAAA,CAAQ,QAAQ,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAClD,QAAA,MAAM,SAAA,CAAU,UAAU,MAAM,CAAA;AAAA,MAClC,CAAA;AAAA,MAEA,OAAO,YAA2B;AAChC,QAAA,MAAM,QAAQ,IAAA,EAAK;AAAA,MACrB;AAAA,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAC","file":"vercel.js","sourcesContent":["/**\n * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.\n *\n * Usage:\n * import { vercel } from \"sandcastle/sandboxes/vercel\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: vercel() });\n */\n\nimport { execSync } from \"node:child_process\";\nimport { readFile, unlink, writeFile, mkdir, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { Writable } from \"node:stream\";\nimport {\n createIsolatedSandboxProvider,\n type ExecResult,\n type IsolatedSandboxHandle,\n type IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\n/** Worktree path inside the Vercel sandbox. */\nconst VERCEL_REPO_PATH = \"/vercel/sandbox/workspace\";\n\n/**\n * Options for creating a Vercel sandbox provider.\n *\n * All `@vercel/sandbox` `Sandbox.create()` options are accepted as pass-through,\n * plus Sandcastle-specific options for auth and branch strategy.\n */\nexport interface VercelOptions {\n /**\n * Vercel access token.\n *\n * Falls back to the SDK's default auth behavior, which reads\n * `VERCEL_OIDC_TOKEN` (recommended for Vercel-hosted environments) or\n * `VERCEL_TOKEN` from the environment.\n */\n readonly token?: string;\n\n // ---- Pass-through @vercel/sandbox Sandbox.create() options ----\n\n /**\n * The source of the sandbox (git repo, tarball, or snapshot).\n * Omit to start an empty sandbox.\n */\n readonly source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n username?: string;\n password?: string;\n }\n | {\n type: \"tarball\";\n url: string;\n }\n | {\n type: \"snapshot\";\n snapshotId: string;\n };\n\n /** Array of port numbers to expose from the sandbox (up to 4). */\n readonly ports?: number[];\n\n /** Timeout in milliseconds before the sandbox auto-terminates. */\n readonly timeout?: number;\n\n /**\n * Resources to allocate to the sandbox.\n * Each vCPU gets 2048 MB of memory.\n */\n readonly resources?: {\n vcpus: number;\n };\n\n /**\n * The runtime of the sandbox (e.g. `\"node24\"`, `\"node22\"`, `\"python3.13\"`).\n * Defaults to `\"node24\"`.\n */\n readonly runtime?: string;\n\n /**\n * Network policy for the sandbox.\n * Defaults to full internet access if not specified.\n */\n readonly networkPolicy?: Record<string, unknown>;\n\n /**\n * Vercel project ID to associate sandbox operations with.\n */\n readonly projectId?: string;\n\n /**\n * Vercel team ID to associate sandbox operations with.\n */\n readonly teamId?: string;\n\n /**\n * Timeout in milliseconds (alias for `timeout`, kept for discoverability).\n */\n readonly timeoutMs?: number;\n\n /**\n * Sandbox template shorthand (e.g. `\"node-22\"`).\n * Maps to the `runtime` option.\n */\n readonly template?: string;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/**\n * Create a Vercel isolated sandbox provider.\n *\n * The returned provider creates Vercel Firecracker microVM sandboxes via\n * the `@vercel/sandbox` SDK. Each sandbox is ephemeral — one sandbox per run.\n *\n * Requires `@vercel/sandbox` to be installed as a peer dependency.\n */\nexport const vercel = (options?: VercelOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"vercel\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n // Dynamic import so the peer dependency is only loaded at runtime\n const { Sandbox } = await import(\"@vercel/sandbox\");\n\n const createParams: Record<string, unknown> = {};\n\n // Pass through SDK options\n if (options?.source) createParams.source = options.source;\n if (options?.ports) createParams.ports = options.ports;\n if (options?.resources) createParams.resources = options.resources;\n if (options?.networkPolicy)\n createParams.networkPolicy = options.networkPolicy;\n // runtime takes precedence over the template convenience alias\n const resolvedRuntime = options?.runtime ?? options?.template;\n if (resolvedRuntime) createParams.runtime = resolvedRuntime;\n\n // Timeout: prefer explicit timeout, fall back to timeoutMs alias\n const timeoutValue = options?.timeout ?? options?.timeoutMs;\n if (timeoutValue !== undefined) createParams.timeout = timeoutValue;\n\n // Merge provider env with Sandcastle env\n createParams.env = createOptions.env;\n\n // Auth: pass token and team/project IDs if provided\n if (options?.token) createParams.token = options.token;\n if (options?.projectId) createParams.projectId = options.projectId;\n if (options?.teamId) createParams.teamId = options.teamId;\n\n const sandbox = await Sandbox.create(\n createParams as Parameters<typeof Sandbox.create>[0],\n );\n\n // Ensure worktree directory exists\n await sandbox.mkDir(VERCEL_REPO_PATH);\n\n const handle: IsolatedSandboxHandle = {\n worktreePath: VERCEL_REPO_PATH,\n\n exec: async (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n },\n ): Promise<ExecResult> => {\n if (opts?.onLine) {\n const onLine = opts.onLine;\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n let partial = \"\";\n\n const stdoutWritable = new Writable({\n write(chunk, _encoding, callback) {\n const text = partial + chunk.toString();\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n callback();\n },\n final(callback) {\n if (partial) {\n stdoutTail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n callback();\n },\n });\n\n const stderrWritable = new Writable({\n write(chunk, _encoding, callback) {\n stderrTail.push(chunk.toString());\n callback();\n },\n });\n\n const result = await sandbox.runCommand({\n cmd: \"sh\",\n args: [\"-c\", command],\n cwd: opts?.cwd ?? VERCEL_REPO_PATH,\n stdout: stdoutWritable,\n stderr: stderrWritable,\n ...(opts?.sudo ? { sudo: true } : {}),\n });\n\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: result.exitCode,\n };\n }\n\n const result = await sandbox.runCommand({\n cmd: \"sh\",\n args: [\"-c\", command],\n cwd: opts?.cwd ?? VERCEL_REPO_PATH,\n ...(opts?.sudo ? { sudo: true } : {}),\n });\n\n const stdout = await result.stdout();\n const stderr = await result.stderr();\n\n return {\n stdout,\n stderr,\n exitCode: result.exitCode,\n };\n },\n\n copyIn: async (\n hostPath: string,\n sandboxPath: string,\n ): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n const tarPath = join(\n tmpdir(),\n `sandcastle-copyin-${Date.now()}.tar.gz`,\n );\n execSync(`tar -czf \"${tarPath}\" -C \"${hostPath}\" .`);\n try {\n const tarContent = await readFile(tarPath);\n const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;\n await sandbox.writeFiles([\n { path: sandboxTarPath, content: tarContent },\n ]);\n await sandbox.runCommand({\n cmd: \"sh\",\n args: [\n \"-c\",\n `mkdir -p \"${sandboxPath}\" && tar -xzf \"${sandboxTarPath}\" -C \"${sandboxPath}\" && rm -f \"${sandboxTarPath}\"`,\n ],\n });\n } finally {\n await unlink(tarPath).catch(() => {});\n }\n } else {\n const content = await readFile(hostPath);\n await sandbox.writeFiles([{ path: sandboxPath, content }]);\n }\n },\n\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> => {\n const buffer = await sandbox.readFileToBuffer({\n path: sandboxPath,\n });\n if (!buffer) {\n throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);\n }\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sandbox.stop();\n },\n };\n\n return handle;\n },\n });\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/sandboxes/vercel.ts"],"names":[],"mappings":";;;;;;;;;;;AAwBA,IAAM,gBAAA,GAAmB,2BAAA;AA+GzB,IAAM,cAAA,GAAiB,CAAC,KAAA,KACtB,KAAA,KAAU,KAAK,MAAA,GAAY,KAAA;AAU7B,IAAM,iBAAA,GAAoB,CACxB,OAAA,KAC4D;AAC5D,EAAA,MAAM,EAAE,KAAI,GAAI,OAAA;AAChB,EAAA,MAAM,WAAA,GAAc,cAAA,CAAe,OAAA,EAAS,KAAK,CAAA;AACjD,EAAA,MAAM,YAAA,GAAe,cAAA,CAAe,OAAA,EAAS,MAAM,CAAA;AACnD,EAAA,MAAM,eAAA,GAAkB,cAAA,CAAe,OAAA,EAAS,SAAS,CAAA;AACzD,EAAA,MAAM,KAAA,GAAQ,WAAA,IAAe,cAAA,CAAe,GAAA,CAAI,YAAY,CAAA;AA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AC,OAAA,KACrB,6BAAA,CAA8B;AAAA,EAC5B,IAAA,EAAM,QAAA;AAAA,EACN,KAAK,OAAA,EAAS,GAAA;AAAA,EACd,MAAA,EAAQ,OAAO,aAAA,KAAkD;AAE/D,IAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,MAAM,OAAO,iBAAiB,CAAA;AAClD,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,MAAA;AAAA,MAC5B,cAAA,CAAe,OAAA,EAAS,aAAA,CAAc,GAAG;AAAA,KAC3C;AACA,IAAA,MAAM,WAAA,CAAY,OAAA,EAAS,YAAY,eAAA,CAAgB,OAAO,CAAC,CAAA;AAC/D,IAAA,OAAO,UAAA,CAAW,OAAA,EAAS,OAAA,EAAS,kBAAA,IAAsB,cAAc,CAAA;AAAA,EAC1E;AACF,CAAC","file":"vercel.js","sourcesContent":["/**\n * Vercel isolated sandbox provider — wraps `@vercel/sandbox` into a SandboxProvider.\n *\n * Usage:\n * import { vercel } from \"sandcastle/sandboxes/vercel\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: vercel() });\n */\n\nimport { execSync } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { readFile, unlink, writeFile, mkdir, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { Writable } from \"node:stream\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\n/** Worktree path inside the Vercel sandbox. */\nconst VERCEL_REPO_PATH = \"/vercel/sandbox/workspace\";\n\n/**\n * Options for creating a Vercel sandbox provider.\n *\n * All `@vercel/sandbox` `Sandbox.create()` options are accepted as pass-through,\n * plus Sandcastle-specific options for auth and branch strategy.\n */\nexport interface VercelOptions {\n /**\n * Vercel access token.\n *\n * Falls back to the `VERCEL_TOKEN` environment variable. A token needs a\n * team and project id too (`teamId`/`VERCEL_TEAM_ID`,\n * `projectId`/`VERCEL_PROJECT_ID`). With no token at all, the SDK's OIDC\n * auth applies, which reads `VERCEL_OIDC_TOKEN`.\n */\n readonly token?: string;\n\n // ---- Pass-through @vercel/sandbox Sandbox.create() options ----\n\n /**\n * The source of the sandbox (git repo, tarball, or snapshot).\n * Omit to start an empty sandbox.\n */\n readonly source?:\n | {\n type: \"git\";\n url: string;\n depth?: number;\n revision?: string;\n username?: string;\n password?: string;\n }\n | {\n type: \"tarball\";\n url: string;\n }\n | {\n type: \"snapshot\";\n snapshotId: string;\n };\n\n /** Array of port numbers to expose from the sandbox (up to 4). */\n readonly ports?: number[];\n\n /** Timeout in milliseconds before the sandbox auto-terminates. */\n readonly timeout?: number;\n\n /**\n * Resources to allocate to the sandbox.\n * Each vCPU gets 2048 MB of memory.\n */\n readonly resources?: {\n vcpus: number;\n };\n\n /**\n * The runtime of the sandbox (e.g. `\"node24\"`, `\"node22\"`, `\"python3.13\"`).\n *\n * Omit it to get Vercel's default image (`vercel/sandbox/universal` as of\n * `@vercel/sandbox` 3.x), which ships coding agent CLIs such as `claude`.\n * The named runtimes ship none: install your agent's CLI in an\n * `onSandboxReady` hook.\n */\n readonly runtime?: string;\n\n /**\n * Network policy for the sandbox.\n * Defaults to full internet access if not specified.\n */\n readonly networkPolicy?: Record<string, unknown>;\n\n /**\n * Vercel project ID to associate sandbox operations with.\n * Falls back to the `VERCEL_PROJECT_ID` environment variable when a token is used.\n */\n readonly projectId?: string;\n\n /**\n * Vercel team ID to associate sandbox operations with.\n * Falls back to the `VERCEL_TEAM_ID` environment variable when a token is used.\n */\n readonly teamId?: string;\n\n /**\n * Timeout in milliseconds (alias for `timeout`, kept for discoverability).\n */\n readonly timeoutMs?: number;\n\n /**\n * Sandbox template shorthand (e.g. `\"node-22\"`).\n * Maps to the `runtime` option.\n */\n readonly template?: string;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** An option or env var counts as unset when it is missing or empty. */\nconst setOrUndefined = (value: string | undefined): string | undefined =>\n value === \"\" ? undefined : value;\n\n/**\n * Resolve the auth params for `Sandbox.create()`.\n *\n * `@vercel/sandbox` only accepts a token as an explicit param, together with\n * `teamId` and `projectId` (all three or none); otherwise it falls back to\n * OIDC. So read `VERCEL_TOKEN`, `VERCEL_TEAM_ID` and `VERCEL_PROJECT_ID`\n * here, explicit options first.\n */\nconst resolveVercelAuth = (\n options: VercelOptions | undefined,\n): { token?: string; teamId?: string; projectId?: string } => {\n const { env } = process;\n const tokenOption = setOrUndefined(options?.token);\n const teamIdOption = setOrUndefined(options?.teamId);\n const projectIdOption = setOrUndefined(options?.projectId);\n const token = tokenOption ?? setOrUndefined(env.VERCEL_TOKEN);\n\n if (token === undefined) {\n // No token: the SDK's OIDC flow, which may use team/project ids as hints.\n return {\n ...(teamIdOption === undefined ? {} : { teamId: teamIdOption }),\n ...(projectIdOption === undefined ? {} : { projectId: projectIdOption }),\n };\n }\n\n const teamId = teamIdOption ?? setOrUndefined(env.VERCEL_TEAM_ID);\n const projectId = projectIdOption ?? setOrUndefined(env.VERCEL_PROJECT_ID);\n const missing = [\n teamId === undefined ? \"VERCEL_TEAM_ID (or the teamId option)\" : null,\n projectId === undefined\n ? \"VERCEL_PROJECT_ID (or the projectId option)\"\n : null,\n ].filter((name): name is string => name !== null);\n\n if (missing.length > 0) {\n const source =\n tokenOption === undefined ? \"VERCEL_TOKEN\" : \"the token option\";\n throw new Error(\n `vercel(): ${source} is set, but a Vercel token also needs a team and project id. ` +\n `Missing: ${missing.join(\", \")}.`,\n );\n }\n\n return { token, teamId, projectId };\n};\n\n/**\n * Run the setup of a sandbox that `create()` has just made. If it fails, stop\n * the sandbox before rethrowing: no handle exists yet, so neither Sandcastle's\n * teardown nor `close()` can reach it, and it would run until Vercel's\n * timeout.\n */\nconst setUpOrStop = async (\n sandbox: { stop: () => Promise<unknown> },\n setUp: () => Promise<void>,\n): Promise<void> => {\n try {\n await setUp();\n } catch (error) {\n try {\n await sandbox.stop();\n } catch {\n // Report the setup error, which says why create() failed.\n }\n throw error;\n }\n};\n\n/** The `Sandbox.create` params: SDK pass-through options, env and auth. */\nconst toCreateParams = (\n options: VercelOptions | undefined,\n env: Record<string, string>,\n): Record<string, unknown> => {\n const o = options ?? {};\n const passThrough: Record<string, unknown> = {\n source: o.source,\n ports: o.ports,\n resources: o.resources,\n networkPolicy: o.networkPolicy,\n // runtime takes precedence over the template convenience alias\n runtime: o.runtime ?? o.template,\n // prefer explicit timeout, fall back to the timeoutMs alias\n timeout: o.timeout ?? o.timeoutMs,\n };\n return {\n // An unset option (or an empty runtime) is left out for the SDK default.\n ...Object.fromEntries(\n Object.entries(passThrough).filter(\n ([, value]) => value !== undefined && value !== \"\",\n ),\n ),\n env,\n ...resolveVercelAuth(options),\n };\n};\n\ntype RunCommandParams = Parameters<SandboxInstance[\"runCommand\"]>[0];\n\n/**\n * The command to run for `exec`. `runCommand` gives a command no stdin\n * unless it is detached: the command reads EOF. So write stdin to a file in\n * the sandbox and redirect it in (a file, not an argument, keeps clear of the\n * per-arg size limit). The redirect opens the file before the group runs, so\n * the group can delete it straight away and leave nothing behind.\n */\nconst withStdin = async (\n sandbox: SandboxInstance,\n command: string,\n stdin: string | undefined,\n): Promise<string> => {\n if (stdin === undefined) {\n return command;\n }\n const stdinPath = `/tmp/sandcastle-stdin-${randomUUID()}`;\n await sandbox.writeFiles([{ path: stdinPath, content: Buffer.from(stdin) }]);\n return `{ rm -f ${stdinPath}; ${command}\\n} < ${stdinPath}`;\n};\n\n/** A stream that hands each stdout line to `onLine` and keeps a bounded tail. */\nconst lineWritable = (\n onLine: (line: string) => void,\n tail: BoundedTail,\n): Writable => {\n let partial = \"\";\n return new Writable({\n write(chunk: Buffer, _encoding, callback) {\n const text = partial + chunk.toString();\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n tail.push(line);\n onLine(line);\n }\n callback();\n },\n final(callback) {\n if (partial) {\n tail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n callback();\n },\n });\n};\n\n/** A stream that only keeps a bounded tail of what is written to it. */\nconst tailWritable = (tail: BoundedTail): Writable =>\n new Writable({\n write(chunk: Buffer, _encoding, callback) {\n tail.push(chunk.toString());\n callback();\n },\n });\n\n/** Run a command, streaming stdout lines to `onLine`; returns bounded tails. */\nconst execStreamed = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n {\n onLine,\n maxOutputTailChars,\n }: {\n readonly onLine: (line: string) => void;\n readonly maxOutputTailChars: number;\n },\n): Promise<ExecResult> => {\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const result = await sandbox.runCommand({\n ...params,\n stdout: lineWritable(onLine, stdoutTail),\n stderr: tailWritable(stderrTail),\n });\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: result.exitCode,\n };\n};\n\n/** Run a command to completion and return its whole output. */\nconst execBuffered = async (\n sandbox: SandboxInstance,\n params: RunCommandParams,\n): Promise<ExecResult> => {\n const result = await sandbox.runCommand(params);\n const stdout = await result.stdout();\n const stderr = await result.stderr();\n return { stdout, stderr, exitCode: result.exitCode };\n};\n\n/** Copy a host directory in as a tarball, unpacked at `sandboxPath`. */\nconst copyDirIn = async (\n sandbox: SandboxInstance,\n hostPath: string,\n sandboxPath: string,\n): Promise<void> => {\n const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);\n execSync(`tar -czf \"${tarPath}\" -C \"${hostPath}\" .`);\n try {\n const tarContent = await readFile(tarPath);\n const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;\n await sandbox.writeFiles([{ path: sandboxTarPath, content: tarContent }]);\n await sandbox.runCommand({\n cmd: \"sh\",\n args: [\n \"-c\",\n `mkdir -p \"${sandboxPath}\" && tar -xzf \"${sandboxTarPath}\" -C \"${sandboxPath}\" && rm -f \"${sandboxTarPath}\"`,\n ],\n });\n } finally {\n await unlink(tarPath).catch(() => undefined);\n }\n};\n\n/**\n * Create the worktree folder with its parents: Vercel's default image has no\n * /vercel/sandbox (its user's home is /vercel), and `mkDir` isn't recursive.\n */\nconst makeWorktreeDir = async (sandbox: SandboxInstance): Promise<void> => {\n const mkdirResult = await sandbox.runCommand({\n cmd: \"mkdir\",\n args: [\"-p\", VERCEL_REPO_PATH],\n });\n if (mkdirResult.exitCode !== 0) {\n const stderr = await mkdirResult.stderr();\n throw new Error(\n `vercel(): could not create ${VERCEL_REPO_PATH}: ${stderr.trim()}`,\n );\n }\n};\n\n/** The Sandcastle handle over a Vercel sandbox whose worktree folder exists. */\nconst makeHandle = (\n sandbox: SandboxInstance,\n maxOutputTailChars: number,\n): IsolatedSandboxHandle => ({\n worktreePath: VERCEL_REPO_PATH,\n // `@vercel/sandbox` 2 renamed the sandbox's id from `sandboxId` to `name`.\n sandboxId: sandbox.name ?? sandbox.sandboxId,\n\n exec: async (command, opts): Promise<ExecResult> => {\n const params: RunCommandParams = {\n cmd: \"sh\",\n args: [\"-c\", await withStdin(sandbox, command, opts?.stdin)],\n cwd: opts?.cwd ?? VERCEL_REPO_PATH,\n ...(opts?.sudo === true ? { sudo: true } : {}),\n };\n return opts?.onLine\n ? execStreamed(sandbox, params, {\n onLine: opts.onLine,\n maxOutputTailChars,\n })\n : execBuffered(sandbox, params);\n },\n\n copyIn: async (hostPath, sandboxPath): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n await copyDirIn(sandbox, hostPath, sandboxPath);\n } else {\n const content = await readFile(hostPath);\n await sandbox.writeFiles([{ path: sandboxPath, content }]);\n }\n },\n\n copyFileOut: async (sandboxPath, hostPath): Promise<void> => {\n const buffer = await sandbox.readFileToBuffer({ path: sandboxPath });\n if (!buffer) {\n throw new Error(`File not found in Vercel sandbox: ${sandboxPath}`);\n }\n await mkdir(dirname(hostPath), { recursive: true });\n await writeFile(hostPath, buffer);\n },\n\n close: async (): Promise<void> => {\n await sandbox.stop();\n },\n});\n\n/**\n * Create a Vercel isolated sandbox provider.\n *\n * The returned provider creates Vercel Firecracker microVM sandboxes via\n * the `@vercel/sandbox` SDK. Each sandbox is ephemeral — one sandbox per run.\n *\n * Requires `@vercel/sandbox` to be installed as a peer dependency.\n */\nexport const vercel = (options?: VercelOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"vercel\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n // Dynamic import so the peer dependency is only loaded at runtime\n const { Sandbox } = await import(\"@vercel/sandbox\");\n const sandbox = await Sandbox.create(\n toCreateParams(options, createOptions.env),\n );\n await setUpOrStop(sandbox, async () => makeWorktreeDir(sandbox));\n return makeHandle(sandbox, options?.maxOutputTailChars ?? MAX_TAIL_CHARS);\n },\n });\n"]}
|
|
@@ -131,33 +131,24 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
|
|
|
131
131
|
),
|
|
132
132
|
);
|
|
133
133
|
|
|
134
|
-
// Log any agents that threw (network error, sandbox crash, etc.)
|
|
135
|
-
|
|
136
|
-
|
|
134
|
+
// Log any agents that threw (network error, sandbox crash, etc.), and
|
|
135
|
+
// only pass branches that actually produced commits to the merge phase.
|
|
136
|
+
// An agent that ran successfully but made no commits has nothing to merge.
|
|
137
|
+
const completedIssues: typeof issues = [];
|
|
138
|
+
for (const [i, issue] of issues.entries()) {
|
|
139
|
+
const outcome = settled[i];
|
|
140
|
+
if (outcome?.status === "rejected") {
|
|
137
141
|
console.error(
|
|
138
|
-
` ✗ ${
|
|
142
|
+
` ✗ ${issue.id} (${issue.branch}) failed: ${outcome.reason}`,
|
|
139
143
|
);
|
|
144
|
+
} else if (
|
|
145
|
+
outcome?.status === "fulfilled" &&
|
|
146
|
+
outcome.value.commits.length > 0
|
|
147
|
+
) {
|
|
148
|
+
completedIssues.push(issue);
|
|
140
149
|
}
|
|
141
150
|
}
|
|
142
151
|
|
|
143
|
-
// Only pass branches that actually produced commits to the merge phase.
|
|
144
|
-
// An agent that ran successfully but made no commits has nothing to merge.
|
|
145
|
-
const completedIssues = settled
|
|
146
|
-
.map((outcome, i) => ({ outcome, issue: issues[i]! }))
|
|
147
|
-
.filter(
|
|
148
|
-
(
|
|
149
|
-
entry,
|
|
150
|
-
): entry is {
|
|
151
|
-
outcome: PromiseFulfilledResult<
|
|
152
|
-
Awaited<ReturnType<typeof sandcastle.run>>
|
|
153
|
-
>;
|
|
154
|
-
issue: (typeof issues)[number];
|
|
155
|
-
} =>
|
|
156
|
-
entry.outcome.status === "fulfilled" &&
|
|
157
|
-
entry.outcome.value.commits.length > 0,
|
|
158
|
-
)
|
|
159
|
-
.map((entry) => entry.issue);
|
|
160
|
-
|
|
161
152
|
const completedBranches = completedIssues.map((i) => i.branch);
|
|
162
153
|
|
|
163
154
|
console.log(
|
|
@@ -161,26 +161,24 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
|
|
|
161
161
|
}),
|
|
162
162
|
);
|
|
163
163
|
|
|
164
|
-
// Log any agents that threw (network error, sandbox crash, etc.)
|
|
165
|
-
|
|
166
|
-
|
|
164
|
+
// Log any agents that threw (network error, sandbox crash, etc.), and
|
|
165
|
+
// only pass branches that actually produced commits to the merge phase.
|
|
166
|
+
// An agent that ran successfully but made no commits has nothing to merge.
|
|
167
|
+
const completedIssues: typeof issues = [];
|
|
168
|
+
for (const [i, issue] of issues.entries()) {
|
|
169
|
+
const outcome = settled[i];
|
|
170
|
+
if (outcome?.status === "rejected") {
|
|
167
171
|
console.error(
|
|
168
|
-
` ✗ ${
|
|
172
|
+
` ✗ ${issue.id} (${issue.branch}) failed: ${outcome.reason}`,
|
|
169
173
|
);
|
|
174
|
+
} else if (
|
|
175
|
+
outcome?.status === "fulfilled" &&
|
|
176
|
+
outcome.value.commits.length > 0
|
|
177
|
+
) {
|
|
178
|
+
completedIssues.push(issue);
|
|
170
179
|
}
|
|
171
180
|
}
|
|
172
181
|
|
|
173
|
-
// Only pass branches that actually produced commits to the merge phase.
|
|
174
|
-
// An agent that ran successfully but made no commits has nothing to merge.
|
|
175
|
-
const completedIssues = settled
|
|
176
|
-
.map((outcome, i) => ({ outcome, issue: issues[i]! }))
|
|
177
|
-
.filter(
|
|
178
|
-
(entry) =>
|
|
179
|
-
entry.outcome.status === "fulfilled" &&
|
|
180
|
-
entry.outcome.value.commits.length > 0,
|
|
181
|
-
)
|
|
182
|
-
.map((entry) => entry.issue);
|
|
183
|
-
|
|
184
182
|
const completedBranches = completedIssues.map((i) => i.branch);
|
|
185
183
|
|
|
186
184
|
console.log(
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-hero/sandcastle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "CLI for orchestrating AI agents in isolated sandbox environments",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -14,6 +14,10 @@
|
|
|
14
14
|
"import": "./dist/sandboxes/docker.js",
|
|
15
15
|
"types": "./dist/sandboxes/docker.d.ts"
|
|
16
16
|
},
|
|
17
|
+
"./sandboxes/e2b": {
|
|
18
|
+
"import": "./dist/sandboxes/e2b.js",
|
|
19
|
+
"types": "./dist/sandboxes/e2b.d.ts"
|
|
20
|
+
},
|
|
17
21
|
"./sandboxes/vercel": {
|
|
18
22
|
"import": "./dist/sandboxes/vercel.js",
|
|
19
23
|
"types": "./dist/sandboxes/vercel.d.ts"
|
|
@@ -26,9 +30,25 @@
|
|
|
26
30
|
"import": "./dist/sandboxes/daytona.js",
|
|
27
31
|
"types": "./dist/sandboxes/daytona.d.ts"
|
|
28
32
|
},
|
|
33
|
+
"./sandboxes/modal": {
|
|
34
|
+
"import": "./dist/sandboxes/modal.js",
|
|
35
|
+
"types": "./dist/sandboxes/modal.d.ts"
|
|
36
|
+
},
|
|
29
37
|
"./sandboxes/no-sandbox": {
|
|
30
38
|
"import": "./dist/sandboxes/no-sandbox.js",
|
|
31
39
|
"types": "./dist/sandboxes/no-sandbox.d.ts"
|
|
40
|
+
},
|
|
41
|
+
"./sandboxes/bwrap": {
|
|
42
|
+
"import": "./dist/sandboxes/bwrap.js",
|
|
43
|
+
"types": "./dist/sandboxes/bwrap.d.ts"
|
|
44
|
+
},
|
|
45
|
+
"./sandboxes/seatbelt": {
|
|
46
|
+
"import": "./dist/sandboxes/seatbelt.js",
|
|
47
|
+
"types": "./dist/sandboxes/seatbelt.d.ts"
|
|
48
|
+
},
|
|
49
|
+
"./sandboxes/sprites": {
|
|
50
|
+
"import": "./dist/sandboxes/sprites.js",
|
|
51
|
+
"types": "./dist/sandboxes/sprites.d.ts"
|
|
32
52
|
}
|
|
33
53
|
},
|
|
34
54
|
"bin": {
|
|
@@ -37,17 +57,28 @@
|
|
|
37
57
|
"scripts": {
|
|
38
58
|
"build": "tsup",
|
|
39
59
|
"postbuild": "rm -rf dist/templates && cp -r src/templates dist/templates && node scripts/check-public-types-effect-free.mjs",
|
|
60
|
+
"pretest": "tsx scripts/ensure-build.ts",
|
|
40
61
|
"test": "vitest run",
|
|
41
62
|
"test:watch": "vitest",
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
63
|
+
"test:local": "vitest run --config vitest.local.config.ts",
|
|
64
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tests/tsconfig.json",
|
|
65
|
+
"prelint": "tsx scripts/ensure-build.ts",
|
|
66
|
+
"lint": "tsc --noEmit -p scripts/tsconfig.json && tsx scripts/lint-ratchet.ts",
|
|
67
|
+
"lint:shrink": "tsx scripts/lint-ratchet.ts --shrink",
|
|
68
|
+
"lint:report": "tsx scripts/lint-ratchet.ts --report",
|
|
69
|
+
"format": "biome format --write .",
|
|
70
|
+
"format:check": "biome format .",
|
|
45
71
|
"prepare": "husky",
|
|
46
72
|
"release": "changeset publish",
|
|
47
73
|
"sandcastle": "npm run build && tsx .sandcastle/run.ts",
|
|
48
74
|
"test-podman": "npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-podman.ts",
|
|
49
75
|
"test-vercel": "npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-vercel.ts",
|
|
50
|
-
"test-interactive": "npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts"
|
|
76
|
+
"test-interactive": "npm run build && tsx --env-file=.sandcastle/.env .sandcastle/test-interactive.ts",
|
|
77
|
+
"verify": "tsx .sandcastle/verify/verify.ts",
|
|
78
|
+
"verify:world": "npm run build >/dev/null && tsx .sandcastle/verify/verify.ts world",
|
|
79
|
+
"coverage:gate": "tsx scripts/coverage-gate.ts",
|
|
80
|
+
"coverage:floor": "tsx scripts/coverage-floor.ts",
|
|
81
|
+
"api:report": "tsx scripts/api-report.ts"
|
|
51
82
|
},
|
|
52
83
|
"keywords": [
|
|
53
84
|
"cli",
|
|
@@ -63,22 +94,31 @@
|
|
|
63
94
|
},
|
|
64
95
|
"license": "MIT",
|
|
65
96
|
"devDependencies": {
|
|
97
|
+
"@biomejs/biome": "2.6.4",
|
|
66
98
|
"@changesets/cli": "^2.30.0",
|
|
67
|
-
"@daytona/sdk": "^0.
|
|
99
|
+
"@daytona/sdk": "^0.227.0",
|
|
68
100
|
"@effect/cli": "^0.74.0",
|
|
101
|
+
"@effect/language-service": "0.87.5",
|
|
69
102
|
"@effect/platform": "^0.95.0",
|
|
70
103
|
"@effect/platform-node": "^0.105.0",
|
|
71
104
|
"@effect/printer": "^0.48.0",
|
|
72
105
|
"@effect/printer-ansi": "^0.48.0",
|
|
106
|
+
"@fly/sprites": "^0.2.4",
|
|
107
|
+
"@microsoft/api-extractor": "^7.60.1",
|
|
73
108
|
"@types/node": "^25.5.0",
|
|
74
|
-
"@typescript/native
|
|
109
|
+
"@typescript/native": "npm:typescript@7.0.2",
|
|
110
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
111
|
+
"dependency-cruiser": "^18.7.0",
|
|
112
|
+
"e2b": "^2.62.0",
|
|
75
113
|
"effect": "^3.20.0",
|
|
76
114
|
"husky": "^9.1.7",
|
|
77
115
|
"lint-staged": "^15.5.1",
|
|
78
|
-
"
|
|
116
|
+
"modal": "^0.11.1",
|
|
117
|
+
"oxlint": "1.90.0",
|
|
118
|
+
"oxlint-tsgolint": "7.0.2005",
|
|
79
119
|
"tsup": "^8.5.1",
|
|
80
120
|
"tsx": "^4.21.0",
|
|
81
|
-
"typescript": "
|
|
121
|
+
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
82
122
|
"vitest": "^3.2.0",
|
|
83
123
|
"zod": "^4.4.3"
|
|
84
124
|
},
|
|
@@ -86,8 +126,11 @@
|
|
|
86
126
|
"@clack/prompts": "^1.1.0"
|
|
87
127
|
},
|
|
88
128
|
"peerDependencies": {
|
|
89
|
-
"@daytona/sdk": "
|
|
90
|
-
"@
|
|
129
|
+
"@daytona/sdk": ">=0.164.0 <1.0.0",
|
|
130
|
+
"@fly/sprites": ">=0.2.4 <1.0.0",
|
|
131
|
+
"@vercel/sandbox": ">=1.0.0",
|
|
132
|
+
"e2b": ">=2.62.0 <3.0.0",
|
|
133
|
+
"modal": ">=0.11.0 <1.0.0"
|
|
91
134
|
},
|
|
92
135
|
"peerDependenciesMeta": {
|
|
93
136
|
"@vercel/sandbox": {
|
|
@@ -95,6 +138,15 @@
|
|
|
95
138
|
},
|
|
96
139
|
"@daytona/sdk": {
|
|
97
140
|
"optional": true
|
|
141
|
+
},
|
|
142
|
+
"@fly/sprites": {
|
|
143
|
+
"optional": true
|
|
144
|
+
},
|
|
145
|
+
"e2b": {
|
|
146
|
+
"optional": true
|
|
147
|
+
},
|
|
148
|
+
"modal": {
|
|
149
|
+
"optional": true
|
|
98
150
|
}
|
|
99
151
|
},
|
|
100
152
|
"files": [
|
package/dist/chunk-62WN33RK.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'node:module';
|
|
2
|
-
import { MAX_TAIL_CHARS, BoundedTail } from './chunk-NGBM7T3E.js';
|
|
3
|
-
import { spawn } from 'child_process';
|
|
4
|
-
import { createInterface } from 'readline';
|
|
5
|
-
|
|
6
|
-
createRequire(import.meta.url);
|
|
7
|
-
var noSandbox = (options) => ({
|
|
8
|
-
tag: "none",
|
|
9
|
-
name: "no-sandbox",
|
|
10
|
-
env: options?.env ?? {},
|
|
11
|
-
create: async (createOptions) => {
|
|
12
|
-
const worktreePath = createOptions.worktreePath;
|
|
13
|
-
const processEnv = { ...process.env, ...createOptions.env };
|
|
14
|
-
const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
|
|
15
|
-
const handle = {
|
|
16
|
-
worktreePath,
|
|
17
|
-
exec: (command, opts) => {
|
|
18
|
-
const cwd = opts?.cwd ?? worktreePath;
|
|
19
|
-
const isWindows = process.platform === "win32";
|
|
20
|
-
const shellCmd = isWindows ? "cmd.exe" : "sh";
|
|
21
|
-
const shellArgs = isWindows ? ["/d", "/s", "/c", command] : ["-c", command];
|
|
22
|
-
return new Promise((resolve, reject) => {
|
|
23
|
-
const proc = spawn(shellCmd, shellArgs, {
|
|
24
|
-
cwd,
|
|
25
|
-
env: processEnv,
|
|
26
|
-
stdio: [
|
|
27
|
-
opts?.stdin !== void 0 ? "pipe" : "ignore",
|
|
28
|
-
"pipe",
|
|
29
|
-
"pipe"
|
|
30
|
-
],
|
|
31
|
-
windowsVerbatimArguments: isWindows
|
|
32
|
-
});
|
|
33
|
-
if (opts?.stdin !== void 0) {
|
|
34
|
-
proc.stdin.write(opts.stdin);
|
|
35
|
-
proc.stdin.end();
|
|
36
|
-
}
|
|
37
|
-
proc.on("error", (error) => {
|
|
38
|
-
reject(new Error(`exec failed: ${error.message}`));
|
|
39
|
-
});
|
|
40
|
-
if (opts?.onLine) {
|
|
41
|
-
const onLine = opts.onLine;
|
|
42
|
-
const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
|
|
43
|
-
const stderrTail = new BoundedTail(maxOutputTailChars, "");
|
|
44
|
-
const rl = createInterface({ input: proc.stdout });
|
|
45
|
-
rl.on("line", (line) => {
|
|
46
|
-
stdoutTail.push(line);
|
|
47
|
-
onLine(line);
|
|
48
|
-
});
|
|
49
|
-
proc.stderr.on("data", (chunk) => {
|
|
50
|
-
stderrTail.push(chunk.toString());
|
|
51
|
-
});
|
|
52
|
-
proc.on("close", (code) => {
|
|
53
|
-
resolve({
|
|
54
|
-
stdout: stdoutTail.toString(),
|
|
55
|
-
stderr: stderrTail.toString(),
|
|
56
|
-
exitCode: code ?? 0
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
} else {
|
|
60
|
-
const stdoutChunks = [];
|
|
61
|
-
const stderrChunks = [];
|
|
62
|
-
proc.stdout.on("data", (chunk) => {
|
|
63
|
-
stdoutChunks.push(chunk.toString());
|
|
64
|
-
});
|
|
65
|
-
proc.stderr.on("data", (chunk) => {
|
|
66
|
-
stderrChunks.push(chunk.toString());
|
|
67
|
-
});
|
|
68
|
-
proc.on("close", (code) => {
|
|
69
|
-
resolve({
|
|
70
|
-
stdout: stdoutChunks.join(""),
|
|
71
|
-
stderr: stderrChunks.join(""),
|
|
72
|
-
exitCode: code ?? 0
|
|
73
|
-
});
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
},
|
|
78
|
-
interactiveExec: (args, opts) => {
|
|
79
|
-
return new Promise((resolve, reject) => {
|
|
80
|
-
const [cmd, ...rest] = args;
|
|
81
|
-
const proc = spawn(cmd, rest, {
|
|
82
|
-
cwd: opts.cwd ?? worktreePath,
|
|
83
|
-
env: processEnv,
|
|
84
|
-
stdio: [opts.stdin, opts.stdout, opts.stderr],
|
|
85
|
-
shell: process.platform === "win32"
|
|
86
|
-
});
|
|
87
|
-
proc.on("error", (error) => {
|
|
88
|
-
reject(new Error(`exec failed: ${error.message}`));
|
|
89
|
-
});
|
|
90
|
-
proc.on("close", (code) => {
|
|
91
|
-
resolve({ exitCode: code ?? 0 });
|
|
92
|
-
});
|
|
93
|
-
});
|
|
94
|
-
},
|
|
95
|
-
close: async () => {
|
|
96
|
-
}
|
|
97
|
-
};
|
|
98
|
-
return handle;
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
export { noSandbox };
|
|
103
|
-
//# sourceMappingURL=chunk-62WN33RK.js.map
|
|
104
|
-
//# sourceMappingURL=chunk-62WN33RK.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sandboxes/no-sandbox.ts"],"names":[],"mappings":";;;;;;AA4CO,IAAM,SAAA,GAAY,CAAC,OAAA,MAAmD;AAAA,EAC3E,GAAA,EAAK,MAAA;AAAA,EACL,IAAA,EAAM,YAAA;AAAA,EACN,GAAA,EAAK,OAAA,EAAS,GAAA,IAAO,EAAC;AAAA,EACtB,MAAA,EAAQ,OAAO,aAAA,KAA4C;AACzD,IAAA,MAAM,eAAe,aAAA,CAAc,YAAA;AACnC,IAAA,MAAM,aAAa,EAAE,GAAG,QAAQ,GAAA,EAAK,GAAG,cAAc,GAAA,EAAI;AAC1D,IAAA,MAAM,kBAAA,GAAqB,SAAS,kBAAA,IAAsB,cAAA;AAE1D,IAAA,MAAM,MAAA,GAA0B;AAAA,MAC9B,YAAA;AAAA,MAEA,IAAA,EAAM,CACJ,OAAA,EACA,IAAA,KAMwB;AAExB,QAAA,MAAM,GAAA,GAAM,MAAM,GAAA,IAAO,YAAA;AACzB,QAAA,MAAM,SAAA,GAAY,QAAQ,QAAA,KAAa,OAAA;AA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A,IAAQ;AAAA,eACnB,CAAA;AAAA,YACH,CAAC,CAAA;AAAA,UACH;AAAA,QACF,CAAC,CAAA;AAAA,MACH,CAAA;AAAA,MAEA,eAAA,EAAiB,CACf,IAAA,EACA,IAAA,KACkC;AAClC,QAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,UAAA,MAAM,CAAC,GAAA,EAAK,GAAG,IAAI,CAAA,GAAI,IAAA;AAIvB,UAAA,MAAM,IAAA,GAAO,KAAA,CAAM,GAAA,EAAM,IAAA,EAAM;AAAA,YAC7B,GAAA,EAAK,KAAK,GAAA,IAAO,YAAA;AAAA,YACjB,GAAA,EAAK,UAAA;AAAA,YACL,OAAO,CAAC,IAAA,CAAK,OAAO,IAAA,CAAK,MAAA,EAAQ,KAAK,MAAM,CAAA;AAAA,YAC5C,KAAA,EAAO,QAAQ,QAAA,KAAa;AAAA,WAC7B,CAAA;AAED,UAAA,IAAA,CAAK,EAAA,CAAG,OAAA,EAAS,CAAC,KAAA,KAAiB;AACjC,YAAA,MAAA,CAAO,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgB,KAAA,CAAM,OAAO,EAAE,CAAC,CAAA;AAAA,UACnD,CAAC,CAAA;AAED,UAAA,IAAA,CAAK,EAAA,CAAG,OAAA,EAAS,CAAC,IAAA,KAAwB;AACxC,YAAA,OAAA,CAAQ,EAAE,QAAA,EAAU,IAAA,IAAQ,CAAA,EAAG,CAAA;AAAA,UACjC,CAAC,CAAA;AAAA,QACH,CAAC,CAAA;AAAA,MACH,CAAA;AAAA,MAEA,OAAO,YAA2B;AAAA,MAElC;AAAA,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA","file":"chunk-62WN33RK.js","sourcesContent":["/**\n * No-sandbox provider — runs the agent directly on the host with no container isolation.\n *\n * Usage:\n * import { noSandbox } from \"sandcastle/sandboxes/no-sandbox\";\n * await interactive({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: noSandbox() });\n *\n * Accepted by `run()`, `interactive()`, and `createSandbox()`. Skips\n * container isolation entirely — the agent executes on the host. Does not\n * pass `--dangerously-skip-permissions` to the agent — the user manages\n * permissions themselves.\n */\n\nimport { spawn, type StdioOptions } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\nimport type {\n NoSandboxProvider,\n NoSandboxHandle,\n ExecResult,\n InteractiveExecOptions,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\nexport interface NoSandboxOptions {\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/**\n * Create a no-sandbox provider.\n *\n * The returned provider runs the agent directly on the host. All three\n * branch strategies are supported (head, merge-to-head, branch),\n * defaulting to head.\n */\nexport const noSandbox = (options?: NoSandboxOptions): NoSandboxProvider => ({\n tag: \"none\",\n name: \"no-sandbox\",\n env: options?.env ?? {},\n create: async (createOptions): Promise<NoSandboxHandle> => {\n const worktreePath = createOptions.worktreePath;\n const processEnv = { ...process.env, ...createOptions.env };\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n\n const handle: NoSandboxHandle = {\n worktreePath,\n\n exec: (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult> => {\n // sudo is a no-op for no-sandbox — the user is already on the host\n const cwd = opts?.cwd ?? worktreePath;\n const isWindows = process.platform === \"win32\";\n // PowerShell and cmd.exe don't ship `sh`, so on Windows route the\n // command string through cmd.exe instead. `/d` skips AutoRun, `/s`\n // preserves the quoted command verbatim, `/c` runs it and exits.\n // `windowsVerbatimArguments` keeps Node from re-quoting our args.\n const shellCmd = isWindows ? \"cmd.exe\" : \"sh\";\n const shellArgs = isWindows\n ? [\"/d\", \"/s\", \"/c\", command]\n : [\"-c\", command];\n\n return new Promise((resolve, reject) => {\n const proc = spawn(shellCmd, shellArgs, {\n cwd,\n env: processEnv,\n stdio: [\n opts?.stdin !== undefined ? \"pipe\" : \"ignore\",\n \"pipe\",\n \"pipe\",\n ],\n windowsVerbatimArguments: isWindows,\n });\n\n if (opts?.stdin !== undefined) {\n proc.stdin!.write(opts.stdin);\n proc.stdin!.end();\n }\n\n proc.on(\"error\", (error) => {\n reject(new Error(`exec failed: ${error.message}`));\n });\n\n if (opts?.onLine) {\n const onLine = opts.onLine;\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const rl = createInterface({ input: proc.stdout! });\n rl.on(\"line\", (line) => {\n stdoutTail.push(line);\n onLine(line);\n });\n proc.stderr!.on(\"data\", (chunk: Buffer) => {\n stderrTail.push(chunk.toString());\n });\n proc.on(\"close\", (code) => {\n resolve({\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: code ?? 0,\n });\n });\n } else {\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n proc.stdout!.on(\"data\", (chunk: Buffer) => {\n stdoutChunks.push(chunk.toString());\n });\n proc.stderr!.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk.toString());\n });\n proc.on(\"close\", (code) => {\n resolve({\n stdout: stdoutChunks.join(\"\"),\n stderr: stderrChunks.join(\"\"),\n exitCode: code ?? 0,\n });\n });\n }\n });\n },\n\n interactiveExec: (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> => {\n return new Promise((resolve, reject) => {\n const [cmd, ...rest] = args;\n // Agent CLIs on Windows are typically installed as `.cmd`/`.ps1`\n // npm wrappers; bare `spawn(\"claude\", …)` only resolves `.exe`\n // without `shell: true`, so let cmd.exe handle PATHEXT lookup.\n const proc = spawn(cmd!, rest, {\n cwd: opts.cwd ?? worktreePath,\n env: processEnv,\n stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,\n shell: process.platform === \"win32\",\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`exec failed: ${error.message}`));\n });\n\n proc.on(\"close\", (code: number | null) => {\n resolve({ exitCode: code ?? 0 });\n });\n });\n },\n\n close: async (): Promise<void> => {\n // No-op — no container to tear down\n },\n };\n\n return handle;\n },\n});\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/SandboxProvider.ts"],"names":[],"mappings":";;;;;AAoTO,IAAM,8BAAA,GAAiC,CAC5C,MAAA,MAC8B;AAAA,EAC9B,GAAA,EAAK,YAAA;AAAA,EACL,MAAM,MAAA,CAAO,IAAA;AAAA,EACb,GAAA,EAAK,MAAA,CAAO,GAAA,IAAO,EAAC;AAAA,EACpB,gBAAgB,MAAA,CAAO,cAAA;AAAA,EACvB,QAAQ,MAAA,CAAO;AACjB,CAAA;AAMO,IAAM,6BAAA,GAAgC,CAC3C,MAAA,MAC6B;AAAA,EAC7B,GAAA,EAAK,UAAA;AAAA,EACL,MAAM,MAAA,CAAO,IAAA;AAAA,EACb,GAAA,EAAK,MAAA,CAAO,GAAA,IAAO,EAAC;AAAA,EACpB,QAAQ,MAAA,CAAO;AACjB,CAAA","file":"chunk-BIWNFKGV.js","sourcesContent":["/**\n * Sandbox provider types — the pluggable interface for sandbox runtimes.\n *\n * Provider authors implement a small Promise-based interface. Sandcastle\n * handles worktree creation, git mount resolution, and commit extraction.\n */\n\n/** Result of executing a command inside a sandbox. */\nexport interface ExecResult {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n}\n\n/** Options for interactiveExec — the streams the provider should wire to the spawned process. */\nexport interface InteractiveExecOptions {\n readonly stdin: NodeJS.ReadableStream;\n readonly stdout: NodeJS.WritableStream;\n readonly stderr: NodeJS.WritableStream;\n readonly cwd?: string;\n}\n\n/** Handle to a running bind-mount sandbox. */\nexport interface BindMountSandboxHandle {\n /** Absolute path to the worktree inside the sandbox. */\n readonly worktreePath: string;\n /**\n * Execute a command in the sandbox.\n *\n * Implementations MUST support line-by-line streaming via `onLine`. This is\n * how Sandcastle delivers live feedback to the user and enforces idle timeouts —\n * without a streaming implementation, neither will work. A buffered/batch\n * implementation that only calls `onLine` after the process exits does NOT\n * satisfy this contract.\n *\n * When `stdin` is set, the implementation pipes the string to the child\n * process's stdin and closes it. This avoids the Linux 128 KB per-arg limit.\n */\n exec(\n command: string,\n options?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult>;\n /**\n * Launch an interactive process inside the sandbox.\n * Optional — providers that support interactive sessions implement this.\n * The provider detects TTY mode from the streams (e.g. stdin.isTTY) and\n * allocates a pseudo-terminal accordingly.\n */\n interactiveExec?(\n args: string[],\n options: InteractiveExecOptions,\n ): Promise<{ exitCode: number }>;\n /** Copy a single file from the host into the sandbox. */\n copyFileIn(hostPath: string, sandboxPath: string): Promise<void>;\n /** Copy a single file from the sandbox to the host. */\n copyFileOut(sandboxPath: string, hostPath: string): Promise<void>;\n /** Tear down the sandbox. */\n close(): Promise<void>;\n}\n\n/** Options passed to a bind-mount provider's `create` function. */\nexport interface BindMountCreateOptions {\n /** Host-side path to the worktree directory. */\n readonly worktreePath: string;\n /** Host-side path to the original repo root. */\n readonly hostRepoPath: string;\n /** Volume mounts to apply (host:sandbox pairs). */\n readonly mounts: Array<{\n hostPath: string;\n sandboxPath: string;\n readonly?: boolean;\n }>;\n /** Environment variables to inject into the sandbox. */\n readonly env: Record<string, string>;\n}\n\n/** Configuration for createBindMountSandboxProvider. */\nexport interface BindMountSandboxProviderConfig {\n /** Human-readable name for this provider (e.g. \"docker\", \"podman\"). */\n readonly name: string;\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Absolute path to the home directory inside the sandbox (e.g. `\"/home/agent\"`).\n * Used to expand `~` in user-provided `sandboxPath` mount configs.\n * Set to `undefined` for providers that do not have a fixed home directory.\n */\n readonly sandboxHomedir?: string;\n /** Create a sandbox handle from the given options. */\n readonly create: (\n options: BindMountCreateOptions,\n ) => Promise<BindMountSandboxHandle>;\n}\n\n/** Handle to a running isolated sandbox (extends bind-mount with file transfer). */\nexport interface IsolatedSandboxHandle {\n /** Absolute path to the worktree inside the sandbox. */\n readonly worktreePath: string;\n /**\n * Execute a command in the sandbox.\n *\n * Implementations MUST support line-by-line streaming via `onLine`. This is\n * how Sandcastle delivers live feedback to the user and enforces idle timeouts —\n * without a streaming implementation, neither will work. A buffered/batch\n * implementation that only calls `onLine` after the process exits does NOT\n * satisfy this contract.\n *\n * When `stdin` is set, the implementation pipes the string to the child\n * process's stdin and closes it. This avoids the Linux 128 KB per-arg limit.\n */\n exec(\n command: string,\n options?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult>;\n /**\n * Launch an interactive process inside the sandbox.\n * Optional — providers that support interactive sessions implement this.\n * The provider detects TTY mode from the streams (e.g. stdin.isTTY) and\n * allocates a pseudo-terminal accordingly.\n */\n interactiveExec?(\n args: string[],\n options: InteractiveExecOptions,\n ): Promise<{ exitCode: number }>;\n /** Copy a file or directory from the host into the sandbox. */\n copyIn(hostPath: string, sandboxPath: string): Promise<void>;\n /** Copy a single file from the sandbox to the host. */\n copyFileOut(sandboxPath: string, hostPath: string): Promise<void>;\n /** Tear down the sandbox. */\n close(): Promise<void>;\n}\n\n/** Options passed to an isolated provider's `create` function. */\nexport interface IsolatedCreateOptions {\n /** Environment variables to inject into the sandbox. */\n readonly env: Record<string, string>;\n}\n\n/** Configuration for createIsolatedSandboxProvider. */\nexport interface IsolatedSandboxProviderConfig {\n /** Human-readable name for this provider (e.g. \"daytona\", \"e2b\"). */\n readonly name: string;\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /** Create an isolated sandbox handle from the given options. */\n readonly create: (\n options: IsolatedCreateOptions,\n ) => Promise<IsolatedSandboxHandle>;\n}\n\n/** A bind-mount sandbox provider. */\nexport interface BindMountSandboxProvider {\n /** @internal Discriminator for internal dispatch. */\n readonly tag: \"bind-mount\";\n /** Human-readable provider name. */\n readonly name: string;\n /** Environment variables injected by this provider. */\n readonly env: Record<string, string>;\n /**\n * Absolute path to the home directory inside the sandbox (e.g. `\"/home/agent\"`).\n * `undefined` when the provider does not declare a sandbox home directory.\n */\n readonly sandboxHomedir: string | undefined;\n /** @internal Create a sandbox handle. */\n readonly create: (\n options: BindMountCreateOptions,\n ) => Promise<BindMountSandboxHandle>;\n}\n\n/** An isolated sandbox provider. */\nexport interface IsolatedSandboxProvider {\n /** @internal Discriminator for internal dispatch. */\n readonly tag: \"isolated\";\n /** Human-readable provider name. */\n readonly name: string;\n /** Environment variables injected by this provider. */\n readonly env: Record<string, string>;\n /** @internal Create an isolated sandbox handle. */\n readonly create: (\n options: IsolatedCreateOptions,\n ) => Promise<IsolatedSandboxHandle>;\n}\n\n/** Handle to a no-sandbox session — runs commands directly on the host. */\nexport interface NoSandboxHandle {\n /** Absolute path to the worktree on the host. */\n readonly worktreePath: string;\n /**\n * Execute a command on the host.\n *\n * Implementations MUST support line-by-line streaming via `onLine`. This is\n * how Sandcastle delivers live feedback to the user and enforces idle timeouts —\n * without a streaming implementation, neither will work.\n *\n * When `stdin` is set, the implementation pipes the string to the child\n * process's stdin and closes it. This avoids the Linux 128 KB per-arg limit.\n */\n exec(\n command: string,\n options?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult>;\n /**\n * Launch an interactive process on the host with inherited stdio.\n */\n interactiveExec(\n args: string[],\n options: InteractiveExecOptions,\n ): Promise<{ exitCode: number }>;\n /** No-op — no container to tear down. */\n close(): Promise<void>;\n}\n\n/** A no-sandbox provider — runs the agent directly on the host with no container isolation. */\nexport interface NoSandboxProvider {\n /** @internal Discriminator for internal dispatch. */\n readonly tag: \"none\";\n /** Human-readable provider name. */\n readonly name: string;\n /** Environment variables injected by this provider. */\n readonly env: Record<string, string>;\n /** @internal Create a no-sandbox handle. */\n readonly create: (options: {\n readonly worktreePath: string;\n readonly env: Record<string, string>;\n }) => Promise<NoSandboxHandle>;\n}\n\n// ---------- Branch strategy types ----------\n\n/** Head strategy: agent writes directly to host working directory. Bind-mount only. */\nexport interface HeadBranchStrategy {\n readonly type: \"head\";\n}\n\n/** Merge-to-head strategy: temp branch, merge back to HEAD, delete temp branch. */\nexport interface MergeToHeadBranchStrategy {\n readonly type: \"merge-to-head\";\n}\n\n/** Branch strategy: commits land on an explicit named branch. */\nexport interface NamedBranchStrategy {\n readonly type: \"branch\";\n readonly branch: string;\n /**\n * Git ref to use as the starting point when creating a new branch.\n * Only used when the branch doesn't already exist — ignored otherwise.\n * Callers are responsible for ensuring the ref is current (e.g. `git fetch`).\n * Defaults to `HEAD` when omitted.\n */\n readonly baseBranch?: string;\n}\n\n/** Branch strategy for bind-mount providers (all three variants). */\nexport type BindMountBranchStrategy =\n | HeadBranchStrategy\n | MergeToHeadBranchStrategy\n | NamedBranchStrategy;\n\n/** Branch strategy for isolated providers (no head — can't write to host). */\nexport type IsolatedBranchStrategy =\n | MergeToHeadBranchStrategy\n | NamedBranchStrategy;\n\n/** Branch strategy for no-sandbox providers (all three — same as bind-mount). */\nexport type NoSandboxBranchStrategy =\n | HeadBranchStrategy\n | MergeToHeadBranchStrategy\n | NamedBranchStrategy;\n\n/** Union of all branch strategy variants. */\nexport type BranchStrategy =\n | BindMountBranchStrategy\n | IsolatedBranchStrategy\n | NoSandboxBranchStrategy;\n\n/**\n * A sandbox provider — the pluggable unit that `run()`, `interactive()`, and\n * `createSandbox()` accept. Tagged for internal dispatch: \"bind-mount\",\n * \"isolated\", or \"none\". When `NoSandboxProvider` is used, the agent runs\n * directly on the host with no container isolation — opt in at your own risk.\n */\nexport type SandboxProvider =\n | BindMountSandboxProvider\n | IsolatedSandboxProvider\n | NoSandboxProvider;\n\n/** @deprecated Use `SandboxProvider` — it now includes `NoSandboxProvider`. */\nexport type AnySandboxProvider = SandboxProvider;\n\n/**\n * Create a bind-mount sandbox provider from a config object.\n * The returned provider can be passed to `run()` or `createSandbox()`.\n */\nexport const createBindMountSandboxProvider = (\n config: BindMountSandboxProviderConfig,\n): BindMountSandboxProvider => ({\n tag: \"bind-mount\",\n name: config.name,\n env: config.env ?? {},\n sandboxHomedir: config.sandboxHomedir,\n create: config.create,\n});\n\n/**\n * Create an isolated sandbox provider from a config object.\n * The returned provider can be passed to `run()` or `createSandbox()`.\n */\nexport const createIsolatedSandboxProvider = (\n config: IsolatedSandboxProviderConfig,\n): IsolatedSandboxProvider => ({\n tag: \"isolated\",\n name: config.name,\n env: config.env ?? {},\n create: config.create,\n});\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/DockerLifecycle.ts","../src/sandboxes/docker.ts"],"names":["resolve","execFile"],"mappings":";;;;;;;;;;AAMA,IAAM,aAAa,CAAC,IAAA,KAClB,cAAA,CAAO,KAAA,CAAM,CAAC,MAAA,KAAW;AACvB,EAAA,QAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,EAAE,SAAA,EAAW,EAAA,GAAK,IAAA,GAAO,IAAA,EAAK;AAAA,IAC9B,CAAC,KAAA,EAAO,MAAA,EAAQ,MAAA,KAAW;AACzB,MAAA,IAAI,KAAA,EAAO;AACT,QAAA,MAAA;AAAA,UACE,cAAA,CAAO,IAAA;AAAA,YACL,IAAI,WAAA,CAAY;AAAA,cACd,OAAA,EAAS,CAAA,OAAA,EAAU,IAAA,CAAK,CAAC,CAAC,YAAY,MAAA,EAAQ,QAAA,EAAS,IAAK,KAAA,CAAM,OAAO,CAAA;AAAA,aAC1E;AAAA;AACH,SACF;AAAA,MACF,CAAA,MAAO;AACL,QAAA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AS,CAAA,qBAAA,EAAwB,QAAQ,CAAA,0BAAA,EACpC,WAAW,mFAEb,QAAQ,CAAA,gCAAA;AAAA;AACrC,SACF;AAAA,MACF,CAAA,MAAO;AACL,QAAAA,QAAAA,EAAQ;AAAA,MACV;AAAA,IACF;AAAA,GACF;AACF,CAAC,CAAA","file":"chunk-CP3TYXZA.js","sourcesContent":["import { Effect } from \"effect\";\nimport { execFile } from \"node:child_process\";\nimport { resolve } from \"node:path\";\nimport { DockerError } from \"./errors.js\";\nimport { formatVolumeMount, type SelinuxLabel } from \"./mountUtils.js\";\n\nconst dockerExec = (args: string[]): Effect.Effect<string, DockerError> =>\n Effect.async((resume) => {\n execFile(\n \"docker\",\n args,\n { maxBuffer: 10 * 1024 * 1024 },\n (error, stdout, stderr) => {\n if (error) {\n resume(\n Effect.fail(\n new DockerError({\n message: `docker ${args[0]} failed: ${stderr?.toString() || error.message}`,\n }),\n ),\n );\n } else {\n resume(Effect.succeed(stdout.toString()));\n }\n },\n );\n });\n\n/**\n * Build the sandcastle Docker image.\n *\n * When `dockerfile` is provided, uses `docker build -f <dockerfile> <cwd>`\n * so COPY instructions resolve relative to the current working directory.\n * Otherwise, uses `docker build <dockerfileDir>` (the default .sandcastle/ directory).\n */\nexport const buildImage = (\n imageName: string,\n dockerfileDir: string,\n options?: {\n readonly dockerfile?: string;\n readonly buildArgs?: Record<string, string>;\n },\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n const buildArgFlags = Object.entries(options?.buildArgs ?? {}).flatMap(\n ([k, v]) => [\"--build-arg\", `${k}=${v}`],\n );\n if (options?.dockerfile) {\n yield* dockerExec([\n \"build\",\n \"-t\",\n imageName,\n ...buildArgFlags,\n \"-f\",\n resolve(options.dockerfile),\n process.cwd(),\n ]);\n } else {\n yield* dockerExec([\n \"build\",\n \"-t\",\n imageName,\n ...buildArgFlags,\n resolve(dockerfileDir),\n ]);\n }\n });\n\nexport interface VolumeMount {\n readonly hostPath: string;\n readonly sandboxPath: string;\n readonly readonly?: boolean;\n}\n\nexport interface StartContainerOptions {\n readonly volumeMounts?: readonly VolumeMount[];\n readonly workdir?: string;\n /** Run the container as this uid:gid instead of the Dockerfile's USER. */\n readonly user?: string;\n /** Docker network(s) to attach the container to. Passed as `--network` flags. */\n readonly network?: string | readonly string[];\n /** Supplementary groups to add the container user to. Passed as `--group-add` flags. */\n readonly groups?: readonly (string | number)[];\n /** Host devices to expose to the container. Passed as `--device` flags. */\n readonly devices?: readonly string[];\n /** Limit CPU resources via `--cpus` (e.g. `1.5`). Fractional values allowed. */\n readonly cpus?: number;\n /**\n * SELinux volume label suffix applied to bind mounts (default `\"z\"`).\n *\n * - `\"z\"` — shared label. No-op on non-SELinux systems.\n * - `\"Z\"` — private label; only this container can access the mount.\n * - `false` — disable labeling entirely.\n */\n readonly selinuxLabel?: SelinuxLabel;\n}\n\n/**\n * Start a new container with environment variables injected.\n */\nexport const startContainer = (\n containerName: string,\n imageName: string,\n env: Record<string, string>,\n options?: StartContainerOptions,\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n // Check if container already exists\n const existing = yield* dockerExec([\n \"ps\",\n \"-a\",\n \"--filter\",\n `name=^${containerName}$`,\n \"--format\",\n \"{{.Names}}\",\n ]);\n\n if (existing.trim() === containerName) {\n yield* Effect.fail(\n new DockerError({\n message: `Container '${containerName}' already exists. Run cleanup first.`,\n }),\n );\n }\n\n const envFlags = Object.entries(env).flatMap(([k, v]) => [\n \"-e\",\n `${k}=${v}`,\n ]);\n\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const volumeFlags = (options?.volumeMounts ?? []).flatMap((mount) => [\n \"-v\",\n formatVolumeMount(mount, selinuxLabel),\n ]);\n\n const workdirFlags = options?.workdir ? [\"-w\", options.workdir] : [];\n const userFlags = options?.user ? [\"--user\", options.user] : [];\n const networks = options?.network\n ? Array.isArray(options.network)\n ? options.network\n : [options.network]\n : [];\n const networkFlags = networks.flatMap((n) => [\"--network\", n]);\n const groupAddFlags = (options?.groups ?? []).flatMap((g) => [\n \"--group-add\",\n String(g),\n ]);\n const deviceFlags = (options?.devices ?? []).flatMap((d) => [\n \"--device\",\n d,\n ]);\n const cpusFlags =\n options?.cpus !== undefined ? [\"--cpus\", String(options.cpus)] : [];\n\n yield* dockerExec([\n \"run\",\n \"-d\",\n \"--name\",\n containerName,\n ...envFlags,\n ...volumeFlags,\n ...workdirFlags,\n ...userFlags,\n ...networkFlags,\n ...groupAddFlags,\n ...deviceFlags,\n ...cpusFlags,\n imageName,\n ]);\n });\n\n/**\n * Stop and remove a container without removing the image.\n */\nexport const removeContainer = (\n containerName: string,\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n // Stop container (ignore errors if already stopped)\n yield* Effect.ignore(dockerExec([\"stop\", containerName]));\n // Remove container (ignore errors if not found)\n yield* Effect.ignore(dockerExec([\"rm\", containerName]));\n });\n\n/**\n * Remove a Docker image.\n */\nexport const removeImage = (\n imageName: string,\n): Effect.Effect<void, DockerError> =>\n Effect.gen(function* () {\n yield* dockerExec([\"rmi\", imageName]);\n });\n","/**\n * Docker sandbox provider — wraps DockerLifecycle into a SandboxProvider.\n *\n * Usage:\n * import { docker } from \"sandcastle/sandboxes/docker\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: docker() });\n */\n\nimport {\n execFile,\n execFileSync,\n spawn,\n type StdioOptions,\n} from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { createInterface } from \"node:readline\";\nimport { Effect } from \"effect\";\nimport { startContainer, removeContainer } from \"../DockerLifecycle.js\";\nimport {\n createBindMountSandboxProvider,\n type SandboxProvider,\n type BindMountCreateOptions,\n type BindMountSandboxHandle,\n type ExecResult,\n type InteractiveExecOptions,\n} from \"../SandboxProvider.js\";\nimport type { MountConfig } from \"../MountConfig.js\";\nimport type { SelinuxLabel } from \"../mountUtils.js\";\nimport {\n defaultImageName,\n resolveUserMounts,\n processFileMountParents,\n} from \"../mountUtils.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { registerShutdown } from \"../shutdownRegistry.js\";\n\nexport interface DockerOptions {\n /** Docker image name (default: derived from repo directory name). */\n readonly imageName?: string;\n /**\n * The UID of the `agent` user inside the container image (default: host UID via `process.getuid()`, or 1000).\n *\n * Must match the UID baked into the image at build time. Used as the `--user` flag value\n * and checked against the image's configured UID in the pre-flight diagnostic.\n */\n readonly containerUid?: number;\n /**\n * The GID of the `agent` user inside the container image (default: host GID via `process.getgid()`, or 1000).\n *\n * Must match the GID baked into the image at build time. Used as the `--user` flag value.\n */\n readonly containerGid?: number;\n /**\n * SELinux volume label suffix applied to bind mounts.\n *\n * - `\"z\"` — shared label (default). No-op on non-SELinux systems.\n * - `\"Z\"` — private label; only this container can access the mount.\n * - `false` — disable labeling entirely.\n */\n readonly selinuxLabel?: SelinuxLabel;\n /**\n * Additional host directories to bind-mount into the sandbox.\n *\n * Each entry specifies a `hostPath` (tilde-expanded) and `sandboxPath`.\n * If `hostPath` does not exist, sandbox creation fails with a clear error.\n */\n readonly mounts?: readonly MountConfig[];\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n /**\n * Docker network(s) to attach the container to.\n *\n * - `\"my-network\"` → `--network my-network`\n * - `[\"net1\", \"net2\"]` → `--network net1 --network net2`\n *\n * When omitted, Docker's default bridge network is used.\n */\n readonly network?: string | readonly string[];\n /**\n * Supplementary groups to add the container user to, via `--group-add`.\n *\n * Accepts group names or numeric GIDs:\n *\n * - `[\"docker\"]` → `--group-add docker`\n * - `[999]` → `--group-add 999`\n * - `[\"docker\", 999]` → `--group-add docker --group-add 999`\n *\n * Useful for granting access to a bind-mounted Docker socket (Docker-outside-of-Docker).\n * When omitted, no `--group-add` flags are added.\n */\n readonly groups?: readonly (string | number)[];\n /**\n * Host devices to expose to the container, via `--device`.\n *\n * Each entry is a full device spec in `host[:container[:permissions]]` form:\n *\n * - `[\"/dev/kvm\"]` → `--device /dev/kvm`\n * - `[\"/dev/sda:/dev/xvda:rwm\"]` → `--device /dev/sda:/dev/xvda:rwm`\n * - `[\"/dev/kvm\", \"/dev/fuse\"]` → `--device /dev/kvm --device /dev/fuse`\n *\n * When omitted, no `--device` flags are added.\n */\n readonly devices?: readonly string[];\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n /**\n * Limit the CPU resources available to the container, via `--cpus`.\n *\n * Maps directly to `docker run --cpus`. Accepts fractional values:\n *\n * - `2` → `--cpus 2` (at most 2 CPUs)\n * - `1.5` → `--cpus 1.5` (at most 1.5 CPUs)\n *\n * When omitted, no `--cpus` flag is added and the container is unconstrained.\n */\n readonly cpus?: number;\n}\n\n/**\n * Create a Docker sandbox provider.\n *\n * The returned provider creates Docker containers with bind-mounts\n * for the worktree and git directories.\n */\nexport const docker = (options?: DockerOptions): SandboxProvider => {\n const configuredImageName = options?.imageName;\n const selinuxLabel = options?.selinuxLabel ?? \"z\";\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const sandboxHomedir = \"/home/agent\";\n const userMounts = options?.mounts\n ? resolveUserMounts(options.mounts, sandboxHomedir)\n : [];\n // Validate file mounts and collect parent dirs to create at container start.\n // Throws at construction time if any file mount parent is outside sandboxHomedir.\n const parentDirsToCreate = processFileMountParents(\n userMounts,\n sandboxHomedir,\n );\n\n return createBindMountSandboxProvider({\n name: \"docker\",\n env: options?.env,\n sandboxHomedir,\n create: async (\n createOptions: BindMountCreateOptions,\n ): Promise<BindMountSandboxHandle> => {\n const containerName = `sandcastle-${randomUUID()}`;\n\n const worktreePath =\n createOptions.mounts.find(\n (m) => m.hostPath === createOptions.worktreePath,\n )?.sandboxPath ?? \"/home/agent/workspace\";\n\n // Build volume mount list (internal mounts + user-provided mounts)\n const allMounts = [...createOptions.mounts, ...userMounts];\n const volumeMounts = allMounts.map((m) => ({\n hostPath: m.hostPath,\n sandboxPath: m.sandboxPath,\n readonly: m.readonly,\n }));\n\n // Resolve image name\n const imageName =\n configuredImageName ?? defaultImageName(createOptions.hostRepoPath);\n\n const containerUid = options?.containerUid ?? process.getuid?.() ?? 1000;\n const containerGid = options?.containerGid ?? process.getgid?.() ?? 1000;\n\n // Pre-flight: verify image exists and UID matches\n await checkImageUid(imageName, containerUid);\n\n // Start container\n await Effect.runPromise(\n startContainer(\n containerName,\n imageName,\n {\n ...createOptions.env,\n HOME: \"/home/agent\",\n },\n {\n volumeMounts,\n workdir: worktreePath,\n user: `${containerUid}:${containerGid}`,\n network: options?.network,\n groups: options?.groups,\n devices: options?.devices,\n cpus: options?.cpus,\n selinuxLabel,\n },\n ),\n );\n\n // Create parent directories for file mounts and chown to the container user\n for (const dir of parentDirsToCreate) {\n await new Promise<void>((resolve, reject) => {\n execFile(\n \"docker\",\n [\n \"exec\",\n \"--user\",\n \"0:0\",\n containerName,\n \"sh\",\n \"-c\",\n `mkdir -p \"$1\" && chown \"$2\" \"$1\"`,\n \"sh\",\n dir,\n `${containerUid}:${containerGid}`,\n ],\n (error) => {\n if (error) {\n reject(\n new Error(\n `Failed to create parent directory '${dir}' in container: ${error.message}`,\n ),\n );\n } else {\n resolve();\n }\n },\n );\n });\n }\n\n // Register synchronous container cleanup via the shared shutdown registry\n // so concurrent sandboxes share a single exit/SIGINT/SIGTERM listener\n // instead of tripping Node's MaxListenersExceededWarning.\n const removeContainerSync = () => {\n try {\n execFileSync(\"docker\", [\"rm\", \"-f\", containerName], {\n stdio: \"ignore\",\n });\n } catch {\n /* best-effort */\n }\n };\n const unregisterShutdown = registerShutdown(removeContainerSync);\n\n const handle: BindMountSandboxHandle = {\n worktreePath,\n\n exec: (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult> => {\n const effectiveCommand = opts?.sudo ? `sudo ${command}` : command;\n const args = [\"exec\"];\n if (opts?.stdin !== undefined) args.push(\"-i\");\n if (opts?.cwd) args.push(\"-w\", opts.cwd);\n args.push(containerName, \"sh\", \"-c\", effectiveCommand);\n\n return new Promise((resolve, reject) => {\n const proc = spawn(\"docker\", args, {\n stdio: [\n opts?.stdin !== undefined ? \"pipe\" : \"ignore\",\n \"pipe\",\n \"pipe\",\n ],\n });\n\n if (opts?.stdin !== undefined) {\n proc.stdin!.write(opts.stdin);\n proc.stdin!.end();\n }\n\n proc.on(\"error\", (error) => {\n reject(new Error(`docker exec failed: ${error.message}`));\n });\n\n if (opts?.onLine) {\n const onLine = opts.onLine;\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n const rl = createInterface({ input: proc.stdout! });\n rl.on(\"line\", (line) => {\n stdoutTail.push(line);\n onLine(line);\n });\n proc.stderr!.on(\"data\", (chunk: Buffer) => {\n stderrTail.push(chunk.toString());\n });\n proc.on(\"close\", (code) => {\n resolve({\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: code ?? 0,\n });\n });\n } else {\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n proc.stdout!.on(\"data\", (chunk: Buffer) => {\n stdoutChunks.push(chunk.toString());\n });\n proc.stderr!.on(\"data\", (chunk: Buffer) => {\n stderrChunks.push(chunk.toString());\n });\n proc.on(\"close\", (code) => {\n resolve({\n stdout: stdoutChunks.join(\"\"),\n stderr: stderrChunks.join(\"\"),\n exitCode: code ?? 0,\n });\n });\n }\n });\n },\n\n interactiveExec: (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> => {\n return new Promise((resolve, reject) => {\n const dockerArgs = [\"exec\"];\n // Allocate a pseudo-terminal when stdin looks like a TTY\n if (\n \"isTTY\" in opts.stdin &&\n (opts.stdin as { isTTY?: boolean }).isTTY\n ) {\n dockerArgs.push(\"-it\");\n } else {\n dockerArgs.push(\"-i\");\n }\n if (opts.cwd) dockerArgs.push(\"-w\", opts.cwd);\n dockerArgs.push(containerName, ...args);\n\n const proc = spawn(\"docker\", dockerArgs, {\n stdio: [opts.stdin, opts.stdout, opts.stderr] as StdioOptions,\n });\n\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`docker exec failed: ${error.message}`));\n });\n\n proc.on(\"close\", (code: number | null) => {\n resolve({ exitCode: code ?? 0 });\n });\n });\n },\n\n copyFileIn: (hostPath: string, sandboxPath: string): Promise<void> =>\n new Promise((resolve, reject) => {\n execFile(\n \"docker\",\n [\"cp\", hostPath, `${containerName}:${sandboxPath}`],\n (error) => {\n if (error) {\n reject(new Error(`docker cp (in) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n copyFileOut: (sandboxPath: string, hostPath: string): Promise<void> =>\n new Promise((resolve, reject) => {\n execFile(\n \"docker\",\n [\"cp\", `${containerName}:${sandboxPath}`, hostPath],\n (error) => {\n if (error) {\n reject(new Error(`docker cp (out) failed: ${error.message}`));\n } else {\n resolve();\n }\n },\n );\n }),\n\n close: async (): Promise<void> => {\n unregisterShutdown();\n await Effect.runPromise(removeContainer(containerName));\n },\n };\n\n return handle;\n },\n });\n};\n\n// Re-export for backwards compatibility\nexport { defaultImageName };\n\nconst checkImageUid = (imageName: string, expectedUid: number): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n execFile(\n \"docker\",\n [\"image\", \"inspect\", imageName, \"--format\", \"{{.Config.User}}\"],\n (error, stdout) => {\n if (error) {\n reject(\n new Error(\n `Image '${imageName}' not found locally. Build it first with 'sandcastle docker build-image'.`,\n ),\n );\n return;\n }\n const imageUser = (stdout ?? \"\").toString().trim();\n if (!imageUser) {\n // No USER directive in image — skip check\n resolve();\n return;\n }\n const uidPart = imageUser.split(\":\")[0]!;\n const imageUid = parseInt(uidPart, 10);\n if (isNaN(imageUid)) {\n // Non-numeric user (e.g. \"agent\") — can't compare, skip check\n resolve();\n return;\n }\n if (imageUid !== expectedUid) {\n reject(\n new Error(\n `UID mismatch: image '${imageName}' was built with UID ${imageUid}, ` +\n `but the expected UID is ${expectedUid}. ` +\n `Rebuild the image with 'sandcastle docker build-image', ` +\n `or pass containerUid: ${imageUid} to docker() to match the image.`,\n ),\n );\n } else {\n resolve();\n }\n },\n );\n });\n"]}
|