@ai-hero/sandcastle 0.13.0 → 0.14.1

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 (77) hide show
  1. package/README.md +3 -3
  2. package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
  3. package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
  4. package/dist/chunk-4BB7DNPW.js.map +1 -0
  5. package/dist/chunk-4GZMUHVO.js +60 -0
  6. package/dist/chunk-4GZMUHVO.js.map +1 -0
  7. package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
  8. package/dist/chunk-7JUTKCHL.js.map +1 -0
  9. package/dist/chunk-7PHPLDVS.js +284 -0
  10. package/dist/chunk-7PHPLDVS.js.map +1 -0
  11. package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
  12. package/dist/chunk-BXLS4HRY.js.map +1 -0
  13. package/dist/chunk-EM4QNWKF.js +3161 -0
  14. package/dist/chunk-EM4QNWKF.js.map +1 -0
  15. package/dist/chunk-EXYXBRCX.js +60 -0
  16. package/dist/chunk-EXYXBRCX.js.map +1 -0
  17. package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
  18. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  19. package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
  20. package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
  21. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  22. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  23. package/dist/chunk-SAQXFLO2.js +1268 -0
  24. package/dist/chunk-SAQXFLO2.js.map +1 -0
  25. package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
  26. package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
  27. package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
  28. package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
  29. package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
  30. package/dist/chunk-WYOGXC72.js.map +1 -0
  31. package/dist/chunk-YDQW5IOY.js +799 -0
  32. package/dist/chunk-YDQW5IOY.js.map +1 -0
  33. package/dist/index.d.ts +51 -4
  34. package/dist/index.js +892 -2018
  35. package/dist/index.js.map +1 -1
  36. package/dist/main.js +322 -251
  37. package/dist/main.js.map +1 -1
  38. package/dist/sandboxes/bwrap.d.ts +1 -1
  39. package/dist/sandboxes/bwrap.js +9 -14
  40. package/dist/sandboxes/bwrap.js.map +1 -1
  41. package/dist/sandboxes/daytona.d.ts +1 -1
  42. package/dist/sandboxes/daytona.js +183 -136
  43. package/dist/sandboxes/daytona.js.map +1 -1
  44. package/dist/sandboxes/docker.d.ts +23 -1
  45. package/dist/sandboxes/docker.js +7 -3
  46. package/dist/sandboxes/e2b.d.ts +41 -0
  47. package/dist/sandboxes/e2b.js +202 -0
  48. package/dist/sandboxes/e2b.js.map +1 -0
  49. package/dist/sandboxes/modal.d.ts +78 -0
  50. package/dist/sandboxes/modal.js +171 -0
  51. package/dist/sandboxes/modal.js.map +1 -0
  52. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  53. package/dist/sandboxes/no-sandbox.js +1 -1
  54. package/dist/sandboxes/podman.d.ts +27 -4
  55. package/dist/sandboxes/podman.js +19 -43
  56. package/dist/sandboxes/podman.js.map +1 -1
  57. package/dist/sandboxes/seatbelt.d.ts +2 -2
  58. package/dist/sandboxes/seatbelt.js +10 -7
  59. package/dist/sandboxes/seatbelt.js.map +1 -1
  60. package/dist/sandboxes/sprites.d.ts +54 -0
  61. package/dist/sandboxes/sprites.js +219 -0
  62. package/dist/sandboxes/sprites.js.map +1 -0
  63. package/dist/sandboxes/vercel.d.ts +10 -1
  64. package/dist/sandboxes/vercel.js +74 -46
  65. package/dist/sandboxes/vercel.js.map +1 -1
  66. package/dist/templates/parallel-planner/main.mts +43 -21
  67. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  68. package/dist/templates/sequential-reviewer/main.mts +1 -1
  69. package/package.json +36 -4
  70. package/dist/chunk-4EIVTSOZ.js +0 -93
  71. package/dist/chunk-4EIVTSOZ.js.map +0 -1
  72. package/dist/chunk-7N7AMUYA.js.map +0 -1
  73. package/dist/chunk-A4C2FG74.js.map +0 -1
  74. package/dist/chunk-LWNC4UTZ.js.map +0 -1
  75. package/dist/chunk-NMQ5Z6YG.js.map +0 -1
  76. package/dist/chunk-U42XXICG.js.map +0 -1
  77. package/dist/chunk-XCYK7I45.js.map +0 -1
@@ -1,15 +1,17 @@
1
1
  import { createRequire } from 'node:module';
2
- import { createIsolatedSandboxProvider } from '../chunk-XCYK7I45.js';
2
+ import { createIsolatedSandboxProvider } from '../chunk-4BB7DNPW.js';
3
3
  import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
4
- import { execSync } from 'child_process';
5
- import { randomUUID } from 'crypto';
4
+ import { spawn } from 'child_process';
5
+ import { once } from 'events';
6
6
  import { mkdir, writeFile, stat, readFile, unlink } from 'fs/promises';
7
7
  import { tmpdir } from 'os';
8
8
  import { dirname, join } from 'path';
9
+ import { randomUUID } from 'crypto';
9
10
  import { Writable } from 'stream';
10
11
 
11
12
  createRequire(import.meta.url);
12
- var VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
13
+
14
+ // src/sandboxes/vercelAuth.ts
13
15
  var setOrUndefined = (value) => value === "" ? void 0 : value;
14
16
  var resolveVercelAuth = (options) => {
15
17
  const { env } = process;
@@ -37,40 +39,6 @@ var resolveVercelAuth = (options) => {
37
39
  }
38
40
  return { token, teamId, projectId };
39
41
  };
40
- var setUpOrStop = async (sandbox, setUp) => {
41
- try {
42
- await setUp();
43
- } catch (error) {
44
- try {
45
- await sandbox.stop();
46
- } catch {
47
- }
48
- throw error;
49
- }
50
- };
51
- var toCreateParams = (options, env) => {
52
- const o = options ?? {};
53
- const passThrough = {
54
- source: o.source,
55
- ports: o.ports,
56
- resources: o.resources,
57
- networkPolicy: o.networkPolicy,
58
- // runtime takes precedence over the template convenience alias
59
- runtime: o.runtime ?? o.template,
60
- // prefer explicit timeout, fall back to the timeoutMs alias
61
- timeout: o.timeout ?? o.timeoutMs
62
- };
63
- return {
64
- // An unset option (or an empty runtime) is left out for the SDK default.
65
- ...Object.fromEntries(
66
- Object.entries(passThrough).filter(
67
- ([, value]) => value !== void 0 && value !== ""
68
- )
69
- ),
70
- env,
71
- ...resolveVercelAuth(options)
72
- };
73
- };
74
42
  var withStdin = async (sandbox, command, stdin) => {
75
43
  if (stdin === void 0) {
76
44
  return command;
@@ -82,7 +50,14 @@ var withStdin = async (sandbox, command, stdin) => {
82
50
  };
83
51
  var lineWritable = (onLine, tail) => {
84
52
  let partial = "";
85
- return new Writable({
53
+ const flush = () => {
54
+ if (partial) {
55
+ tail.push(partial);
56
+ onLine(partial);
57
+ partial = "";
58
+ }
59
+ };
60
+ const stream = new Writable({
86
61
  write(chunk, _encoding, callback) {
87
62
  const text = partial + chunk.toString();
88
63
  const lines = text.split("\n");
@@ -94,14 +69,11 @@ var lineWritable = (onLine, tail) => {
94
69
  callback();
95
70
  },
96
71
  final(callback) {
97
- if (partial) {
98
- tail.push(partial);
99
- onLine(partial);
100
- partial = "";
101
- }
72
+ flush();
102
73
  callback();
103
74
  }
104
75
  });
76
+ return { stream, flush };
105
77
  };
106
78
  var tailWritable = (tail) => new Writable({
107
79
  write(chunk, _encoding, callback) {
@@ -115,11 +87,13 @@ var execStreamed = async (sandbox, params, {
115
87
  }) => {
116
88
  const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
117
89
  const stderrTail = new BoundedTail(maxOutputTailChars, "");
90
+ const stdout = lineWritable(onLine, stdoutTail);
118
91
  const result = await sandbox.runCommand({
119
92
  ...params,
120
- stdout: lineWritable(onLine, stdoutTail),
93
+ stdout: stdout.stream,
121
94
  stderr: tailWritable(stderrTail)
122
95
  });
96
+ stdout.flush();
123
97
  return {
124
98
  stdout: stdoutTail.toString(),
125
99
  stderr: stderrTail.toString(),
@@ -132,9 +106,63 @@ var execBuffered = async (sandbox, params) => {
132
106
  const stderr = await result.stderr();
133
107
  return { stdout, stderr, exitCode: result.exitCode };
134
108
  };
109
+
110
+ // src/sandboxes/vercel.ts
111
+ var VERCEL_REPO_PATH = "/vercel/sandbox/workspace";
112
+ var setUpOrStop = async (sandbox, setUp) => {
113
+ try {
114
+ await setUp();
115
+ } catch (error) {
116
+ try {
117
+ await sandbox.stop();
118
+ } catch {
119
+ }
120
+ throw error;
121
+ }
122
+ };
123
+ var toCreateParams = (options, env) => {
124
+ const o = options ?? {};
125
+ const passThrough = {
126
+ source: o.source,
127
+ ports: o.ports,
128
+ resources: o.resources,
129
+ networkPolicy: o.networkPolicy,
130
+ // runtime takes precedence over the template convenience alias
131
+ runtime: o.runtime ?? o.template,
132
+ // prefer explicit timeout, fall back to the timeoutMs alias
133
+ timeout: o.timeout ?? o.timeoutMs,
134
+ // Vercel defaults to persistent, which snapshots the sandbox on stop().
135
+ persistent: o.persistent ?? false
136
+ };
137
+ return {
138
+ // An unset option (or an empty runtime) is left out for the SDK default.
139
+ ...Object.fromEntries(
140
+ Object.entries(passThrough).filter(
141
+ ([, value]) => value !== void 0 && value !== ""
142
+ )
143
+ ),
144
+ env,
145
+ ...resolveVercelAuth(options)
146
+ };
147
+ };
148
+ var tarDirectory = async (archive, dir) => {
149
+ const tar = spawn("tar", ["-czf", archive, "-C", dir, "."], {
150
+ stdio: ["ignore", "ignore", "pipe"]
151
+ });
152
+ let stderr = "";
153
+ tar.stderr.on("data", (chunk) => {
154
+ stderr += chunk.toString();
155
+ });
156
+ await once(tar, "close");
157
+ if (tar.exitCode !== 0) {
158
+ throw new Error(
159
+ `tar exited with ${String(tar.exitCode)}: ${stderr.trim()}`
160
+ );
161
+ }
162
+ };
135
163
  var copyDirIn = async (sandbox, hostPath, sandboxPath) => {
136
164
  const tarPath = join(tmpdir(), `sandcastle-copyin-${Date.now()}.tar.gz`);
137
- execSync(`tar -czf "${tarPath}" -C "${hostPath}" .`);
165
+ await tarDirectory(tarPath, hostPath);
138
166
  try {
139
167
  const tarContent = await readFile(tarPath);
140
168
  const sandboxTarPath = `/tmp/sandcastle-copyin-${Date.now()}.tar.gz`;
@@ -1 +1 @@
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;AAE5D,EAAA,IAAI,UAAU,MAAA,EAAW;AAEvB,IAAA,OAAO;AAAA,MACL,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,QAAQ,YAAA,EAAa;AAAA,MAC7D,GAAI,eAAA,KAAoB,MAAA,GAAY,EAAC,GAAI,EAAE,WAAW,eAAA;AAAgB,KACxE;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,YAAA,IAAgB,cAAA,CAAe,GAAA,CAAI,cAAc,CAAA;AAChE,EAAA,MAAM,SAAA,GAAY,eAAA,IAAmB,cAAA,CAAe,GAAA,CAAI,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Y,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"]}
1
+ {"version":3,"sources":["../../src/sandboxes/vercelAuth.ts","../../src/sandboxes/vercelExec.ts","../../src/sandboxes/vercel.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAaA,IAAM,cAAA,GAAiB,CAAC,KAAA,KACtB,KAAA,KAAU,KAAK,MAAA,GAAY,KAAA;AAUtB,IAAM,iBAAA,GAAoB,CAC/B,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;AAE5D,EAAA,IAAI,UAAU,MAAA,EAAW;AAEvB,IAAA,OAAO;AAAA,MACL,GAAI,YAAA,KAAiB,MAAA,GAAY,EAAC,GAAI,EAAE,QAAQ,YAAA,EAAa;AAAA,MAC7D,GAAI,eAAA,KAAoB,MAAA,GAAY,EAAC,GAAI,EAAE,WAAW,eAAA;AAAgB,KACxE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AAAA,EAC1E;AACF,CAAC","file":"vercel.js","sourcesContent":["/**\n * Auth for the Vercel sandbox provider (`./vercel.ts`): the token, team and\n * project ids `Sandbox.create()` takes, from options or env vars.\n */\n\n/** The auth options of `VercelOptions`. */\nexport interface VercelAuthOptions {\n readonly token?: string;\n readonly teamId?: string;\n readonly projectId?: string;\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 */\nexport const resolveVercelAuth = (\n options: VercelAuthOptions | 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 * The `exec` of the Vercel sandbox provider (`./vercel.ts`): stdin through a\n * file, live line streaming with bounded tails, or buffered output.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { Writable } from \"node:stream\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport type { ExecResult } from \"../SandboxProvider.js\";\nimport { BoundedTail } from \"../boundedTail.js\";\n\nexport type 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 */\nexport const 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/**\n * A stream that hands each stdout line to `onLine` and keeps a bounded tail.\n * The SDK never ends it, so `final()` never runs: call `flush()` once the\n * command has finished to deliver a last line that has no trailing newline.\n * Flushing twice delivers it once.\n */\nconst lineWritable = (\n onLine: (line: string) => void,\n tail: BoundedTail,\n): { readonly stream: Writable; readonly flush: () => void } => {\n let partial = \"\";\n const flush = (): void => {\n if (partial) {\n tail.push(partial);\n onLine(partial);\n partial = \"\";\n }\n };\n const stream = 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 flush();\n callback();\n },\n });\n return { stream, flush };\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. */\nexport const 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 stdout = lineWritable(onLine, stdoutTail);\n const result = await sandbox.runCommand({\n ...params,\n stdout: stdout.stream,\n stderr: tailWritable(stderrTail),\n });\n stdout.flush();\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. */\nexport const 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 * 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 { spawn } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport { readFile, unlink, writeFile, mkdir, stat } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport type { SandboxInstance } from \"@vercel/sandbox\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { resolveVercelAuth } from \"./vercelAuth.js\";\nimport { execBuffered, execStreamed, withStdin } from \"./vercelExec.js\";\nimport type { RunCommandParams } from \"./vercelExec.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 /**\n * Whether Vercel keeps the sandbox's filesystem when it stops (default:\n * `false`).\n *\n * Vercel snapshots a persistent sandbox each time it stops, and the snapshot\n * counts against your snapshot storage. Sandcastle makes one sandbox per\n * run, so it turns this off unless you set it.\n */\n readonly persistent?: boolean;\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 * 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 // Vercel defaults to persistent, which snapshots the sandbox on stop().\n persistent: o.persistent ?? false,\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\n/** Pack `dir` into a gzipped tarball at `archive` on the host. */\nconst tarDirectory = async (archive: string, dir: string): Promise<void> => {\n const tar = spawn(\"tar\", [\"-czf\", archive, \"-C\", dir, \".\"], {\n stdio: [\"ignore\", \"ignore\", \"pipe\"],\n });\n let stderr = \"\";\n tar.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n await once(tar, \"close\");\n if (tar.exitCode !== 0) {\n throw new Error(\n `tar exited with ${String(tar.exitCode)}: ${stderr.trim()}`,\n );\n }\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 await tarDirectory(tarPath, 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"]}
@@ -6,7 +6,8 @@
6
6
  // with their target branch names.
7
7
  // Phase 2 (Execute): N sonnet agents run in parallel via Promise.allSettled,
8
8
  // each working a single issue on its own branch.
9
- // Phase 3 (Merge): A sonnet agent merges all branches that produced commits.
9
+ // Phase 3 (Merge): A sonnet agent merges every branch that is ahead of the
10
+ // current branch.
10
11
  //
11
12
  // The outer loop repeats up to MAX_ITERATIONS times so that newly unblocked
12
13
  // issues are picked up after each round of merges.
@@ -16,6 +17,8 @@
16
17
  // Or add to package.json:
17
18
  // "scripts": { "sandcastle": "npx tsx .sandcastle/main.mts" }
18
19
 
20
+ import { spawn } from "node:child_process";
21
+ import { once } from "node:events";
19
22
  import * as sandcastle from "@ai-hero/sandcastle";
20
23
  import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
21
24
  import { z } from "zod";
@@ -30,6 +33,23 @@ const planSchema = z.object({
30
33
  ),
31
34
  });
32
35
 
36
+ // True when `branch` has commits the current branch doesn't. The merge phase
37
+ // asks git rather than trusting this cycle's `commits`: a branch an earlier
38
+ // cycle advanced but never merged gets no new commits when its issue comes
39
+ // round again, so gating on `commits.length` would strand it forever.
40
+ const isAheadOfHead = async (branch: string): Promise<boolean> => {
41
+ const git = spawn("git", ["rev-list", "--count", `HEAD..${branch}`], {
42
+ stdio: ["ignore", "pipe", "inherit"],
43
+ });
44
+ const closed = once(git, "close");
45
+ let count = "";
46
+ for await (const chunk of git.stdout) {
47
+ count += String(chunk);
48
+ }
49
+ await closed;
50
+ return git.exitCode === 0 && Number(count.trim()) > 0;
51
+ };
52
+
33
53
  // ---------------------------------------------------------------------------
34
54
  // Configuration
35
55
  // ---------------------------------------------------------------------------
@@ -38,15 +58,18 @@ const planSchema = z.object({
38
58
  // Raise this if your backlog is large; lower it for a quick smoke-test run.
39
59
  const MAX_ITERATIONS = 10;
40
60
 
41
- // Hooks run inside the sandbox before the agent starts each iteration.
42
- // npm install ensures the sandbox always has fresh dependencies.
43
- const hooks = {
61
+ // Install hooks only for worktree phases (execute). Planner and merger
62
+ // bind-mount the real checkout (no branchStrategy), so an `npm install`
63
+ // there would rewrite the host's node_modules — e.g. Linux native binaries
64
+ // on macOS, or packages removed from the host tree.
65
+ const installHooks = {
44
66
  sandbox: { onSandboxReady: [{ command: "npm install" }] },
45
67
  };
46
68
 
47
- // Copy node_modules from the host into the worktree before each sandbox
48
- // starts. Avoids a full npm install from scratch; the hook above handles
49
- // platform-specific binaries and any packages added since the last copy.
69
+ // Copy node_modules from the host into the worktree before each execute
70
+ // sandbox starts. Avoids a full npm install from scratch; the hook above
71
+ // handles platform-specific binaries and any packages added since the last
72
+ // copy. Safe only with a worktree — never pair this with a head bind-mount.
50
73
  const copyToWorktree = ["node_modules"];
51
74
 
52
75
  // ---------------------------------------------------------------------------
@@ -66,7 +89,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
66
89
  // It outputs a <plan> JSON block — Output.object parses and validates it.
67
90
  // -------------------------------------------------------------------------
68
91
  const plan = await sandcastle.run({
69
- hooks,
70
92
  sandbox: docker(),
71
93
  name: "planner",
72
94
  // One iteration is enough: the planner just needs to read and reason,
@@ -108,7 +130,7 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
108
130
  const settled = await Promise.allSettled(
109
131
  issues.map((issue) =>
110
132
  sandcastle.run({
111
- hooks,
133
+ hooks: installHooks,
112
134
  copyToWorktree,
113
135
  // Each agent starts on its own branch via branchStrategy on run().
114
136
  sandbox: docker(),
@@ -132,35 +154,36 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
132
154
  );
133
155
 
134
156
  // 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 = [];
157
+ // only pass branches that are ahead of the current branch to the merge
158
+ // phase, whichever cycle made their commits (see isAheadOfHead).
159
+ const finishedIssues: typeof issues = [];
138
160
  for (const [i, issue] of issues.entries()) {
139
161
  const outcome = settled[i];
140
162
  if (outcome?.status === "rejected") {
141
163
  console.error(
142
164
  ` ✗ ${issue.id} (${issue.branch}) failed: ${outcome.reason}`,
143
165
  );
144
- } else if (
145
- outcome?.status === "fulfilled" &&
146
- outcome.value.commits.length > 0
147
- ) {
148
- completedIssues.push(issue);
166
+ } else if (outcome?.status === "fulfilled") {
167
+ finishedIssues.push(issue);
149
168
  }
150
169
  }
170
+ const ahead = await Promise.all(
171
+ finishedIssues.map(async (issue) => isAheadOfHead(issue.branch)),
172
+ );
173
+ const completedIssues = finishedIssues.filter((_, i) => ahead[i] === true);
151
174
 
152
175
  const completedBranches = completedIssues.map((i) => i.branch);
153
176
 
154
177
  console.log(
155
- `\nExecution complete. ${completedBranches.length} branch(es) with commits:`,
178
+ `\nExecution complete. ${completedBranches.length} branch(es) ahead of HEAD:`,
156
179
  );
157
180
  for (const branch of completedBranches) {
158
181
  console.log(` ${branch}`);
159
182
  }
160
183
 
161
184
  if (completedBranches.length === 0) {
162
- // All agents ran but none made commits — nothing to merge this cycle.
163
- console.log("No commits produced. Nothing to merge.");
185
+ // No branch has work the current branch lacks — nothing to merge.
186
+ console.log("No branches ahead of HEAD. Nothing to merge.");
164
187
  continue;
165
188
  }
166
189
 
@@ -174,7 +197,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
174
197
  // uses to know which branches to merge and which issues to close.
175
198
  // -------------------------------------------------------------------------
176
199
  await sandcastle.run({
177
- hooks,
178
200
  sandbox: docker(),
179
201
  name: "merger",
180
202
  maxIterations: 1,
@@ -6,10 +6,11 @@
6
6
  // listing unblocked issues with branch names.
7
7
  // Phase 2 (Execute + Review): For each issue, a sandbox is created via
8
8
  // createSandbox(). The implementer runs first
9
- // (100 iterations). If it produces commits, a
10
- // reviewer runs in the same sandbox on the same
11
- // branch (1 iteration). All issue pipelines run
12
- // concurrently via Promise.allSettled().
9
+ // (100 iterations). If the branch is then ahead
10
+ // of the current branch, a reviewer runs in the
11
+ // same sandbox on the same branch (1 iteration).
12
+ // All issue pipelines run concurrently via
13
+ // Promise.allSettled().
13
14
  // Phase 3 (Merge): A single agent merges all completed branches
14
15
  // into the current branch.
15
16
  //
@@ -21,6 +22,8 @@
21
22
  // Or add to package.json:
22
23
  // "scripts": { "sandcastle": "npx tsx .sandcastle/main.mts" }
23
24
 
25
+ import { spawn } from "node:child_process";
26
+ import { once } from "node:events";
24
27
  import * as sandcastle from "@ai-hero/sandcastle";
25
28
  import { docker } from "@ai-hero/sandcastle/sandboxes/docker";
26
29
  import { z } from "zod";
@@ -35,6 +38,24 @@ const planSchema = z.object({
35
38
  ),
36
39
  });
37
40
 
41
+ // True when `branch` has commits the current branch doesn't. The review and
42
+ // merge phases ask git rather than trusting this cycle's `commits`: a branch
43
+ // an earlier cycle advanced but never merged gets no new commits when its
44
+ // issue comes round again, so gating on `commits.length` would skip its
45
+ // review and strand it forever.
46
+ const isAheadOfHead = async (branch: string): Promise<boolean> => {
47
+ const git = spawn("git", ["rev-list", "--count", `HEAD..${branch}`], {
48
+ stdio: ["ignore", "pipe", "inherit"],
49
+ });
50
+ const closed = once(git, "close");
51
+ let count = "";
52
+ for await (const chunk of git.stdout) {
53
+ count += String(chunk);
54
+ }
55
+ await closed;
56
+ return git.exitCode === 0 && Number(count.trim()) > 0;
57
+ };
58
+
38
59
  // ---------------------------------------------------------------------------
39
60
  // Configuration
40
61
  // ---------------------------------------------------------------------------
@@ -43,15 +64,18 @@ const planSchema = z.object({
43
64
  // Raise this if your backlog is large; lower it for a quick smoke-test run.
44
65
  const MAX_ITERATIONS = 10;
45
66
 
46
- // Hooks run inside the sandbox before the agent starts each iteration.
47
- // npm install ensures the sandbox always has fresh dependencies.
48
- const hooks = {
67
+ // Install hooks only for worktree phases (execute + review). Planner and
68
+ // merger bind-mount the real checkout (no branch), so an `npm install`
69
+ // there would rewrite the host's node_modules — e.g. Linux native binaries
70
+ // on macOS, or packages removed from the host tree.
71
+ const installHooks = {
49
72
  sandbox: { onSandboxReady: [{ command: "npm install" }] },
50
73
  };
51
74
 
52
- // Copy node_modules from the host into the worktree before each sandbox
53
- // starts. Avoids a full npm install from scratch; the hook above handles
54
- // platform-specific binaries and any packages added since the last copy.
75
+ // Copy node_modules from the host into the worktree before each execute
76
+ // sandbox starts. Avoids a full npm install from scratch; the hook above
77
+ // handles platform-specific binaries and any packages added since the last
78
+ // copy. Safe only with a worktree — never pair this with a head bind-mount.
55
79
  const copyToWorktree = ["node_modules"];
56
80
 
57
81
  // ---------------------------------------------------------------------------
@@ -71,7 +95,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
71
95
  // It outputs a <plan> JSON block — Output.object parses and validates it.
72
96
  // -------------------------------------------------------------------------
73
97
  const plan = await sandcastle.run({
74
- hooks,
75
98
  sandbox: docker(),
76
99
  name: "planner",
77
100
  // One iteration is enough: the planner just needs to read and reason,
@@ -106,7 +129,8 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
106
129
  //
107
130
  // For each issue, create a sandbox via createSandbox() so the implementer
108
131
  // and reviewer share the same sandbox instance per branch. The implementer
109
- // runs first; if it produces commits, the reviewer runs in the same sandbox.
132
+ // runs first; if the branch is ahead of the current branch, the reviewer
133
+ // runs in the same sandbox.
110
134
  //
111
135
  // Promise.allSettled means one failing pipeline doesn't cancel the others.
112
136
  // -------------------------------------------------------------------------
@@ -116,7 +140,7 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
116
140
  const sandbox = await sandcastle.createSandbox({
117
141
  branch: issue.branch,
118
142
  sandbox: docker(),
119
- hooks,
143
+ hooks: installHooks,
120
144
  copyToWorktree,
121
145
  });
122
146
 
@@ -134,8 +158,11 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
134
158
  },
135
159
  });
136
160
 
137
- // Only review if the implementer produced commits
138
- if (implement.commits.length > 0) {
161
+ // Review whenever the branch has work the current branch lacks, not
162
+ // only when this run committed. An earlier cycle may have committed
163
+ // and then failed before or during its review; the merge phase picks
164
+ // that branch up (see isAheadOfHead), so it must be reviewed here first.
165
+ if (await isAheadOfHead(issue.branch)) {
139
166
  const review = await sandbox.run({
140
167
  name: "reviewer",
141
168
  maxIterations: 1,
@@ -162,35 +189,37 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
162
189
  );
163
190
 
164
191
  // 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 = [];
192
+ // only pass branches that are ahead of the current branch to the merge
193
+ // phase, whichever cycle made their commits (see isAheadOfHead). Each one
194
+ // was reviewed in this cycle's Phase 2.
195
+ const finishedIssues: typeof issues = [];
168
196
  for (const [i, issue] of issues.entries()) {
169
197
  const outcome = settled[i];
170
198
  if (outcome?.status === "rejected") {
171
199
  console.error(
172
200
  ` ✗ ${issue.id} (${issue.branch}) failed: ${outcome.reason}`,
173
201
  );
174
- } else if (
175
- outcome?.status === "fulfilled" &&
176
- outcome.value.commits.length > 0
177
- ) {
178
- completedIssues.push(issue);
202
+ } else if (outcome?.status === "fulfilled") {
203
+ finishedIssues.push(issue);
179
204
  }
180
205
  }
206
+ const ahead = await Promise.all(
207
+ finishedIssues.map(async (issue) => isAheadOfHead(issue.branch)),
208
+ );
209
+ const completedIssues = finishedIssues.filter((_, i) => ahead[i] === true);
181
210
 
182
211
  const completedBranches = completedIssues.map((i) => i.branch);
183
212
 
184
213
  console.log(
185
- `\nExecution complete. ${completedBranches.length} branch(es) with commits:`,
214
+ `\nExecution complete. ${completedBranches.length} branch(es) ahead of HEAD:`,
186
215
  );
187
216
  for (const branch of completedBranches) {
188
217
  console.log(` ${branch}`);
189
218
  }
190
219
 
191
220
  if (completedBranches.length === 0) {
192
- // All agents ran but none made commits — nothing to merge this cycle.
193
- console.log("No commits produced. Nothing to merge.");
221
+ // No branch has work the current branch lacks — nothing to merge.
222
+ console.log("No branches ahead of HEAD. Nothing to merge.");
194
223
  continue;
195
224
  }
196
225
 
@@ -204,7 +233,6 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
204
233
  // uses to know which branches to merge and which issues to close.
205
234
  // -------------------------------------------------------------------------
206
235
  await sandcastle.run({
207
- hooks,
208
236
  sandbox: docker(),
209
237
  name: "merger",
210
238
  maxIterations: 1,
@@ -83,7 +83,7 @@ for (let iteration = 1; iteration <= MAX_ITERATIONS; iteration++) {
83
83
  promptFile: "./.sandcastle/implement-prompt.md",
84
84
  });
85
85
 
86
- if (!implement.commits.length) {
86
+ if (implement.commits.length === 0) {
87
87
  // No commits means the backlog is empty or every remaining issue is
88
88
  // blocked — there is nothing left to implement or review, so stop.
89
89
  console.log("Implementation agent made no commits. Stopping.");