@ai-hero/sandcastle 0.14.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.
- package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
- package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
- package/dist/chunk-4BB7DNPW.js.map +1 -0
- package/dist/chunk-4GZMUHVO.js +60 -0
- package/dist/chunk-4GZMUHVO.js.map +1 -0
- package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
- package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
- package/dist/chunk-7PHPLDVS.js +284 -0
- package/dist/chunk-7PHPLDVS.js.map +1 -0
- package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
- package/dist/chunk-BXLS4HRY.js.map +1 -0
- package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
- package/dist/chunk-EM4QNWKF.js.map +1 -0
- package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
- package/dist/chunk-JEQ4IVQM.js.map +1 -0
- package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
- package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
- package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
- package/dist/chunk-PTJEKJPQ.js.map +1 -0
- package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
- package/dist/chunk-SAQXFLO2.js.map +1 -0
- package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
- package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
- package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
- package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
- package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
- package/dist/chunk-WYOGXC72.js.map +1 -0
- package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
- package/dist/chunk-YDQW5IOY.js.map +1 -0
- package/dist/index.d.ts +47 -4
- package/dist/index.js +536 -445
- package/dist/index.js.map +1 -1
- package/dist/main.js +72 -16
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -17
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +82 -79
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +23 -1
- package/dist/sandboxes/docker.js +6 -5
- package/dist/sandboxes/e2b.d.ts +1 -1
- package/dist/sandboxes/e2b.js +4 -4
- package/dist/sandboxes/modal.d.ts +1 -1
- package/dist/sandboxes/modal.js +1 -1
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +1 -1
- package/dist/sandboxes/podman.d.ts +27 -4
- package/dist/sandboxes/podman.js +18 -45
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +2 -2
- package/dist/sandboxes/seatbelt.js +10 -10
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +1 -1
- package/dist/sandboxes/sprites.js +25 -4
- package/dist/sandboxes/sprites.js.map +1 -1
- package/dist/sandboxes/vercel.d.ts +10 -1
- package/dist/sandboxes/vercel.js +74 -46
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +43 -21
- package/dist/templates/parallel-planner-with-review/main.mts +55 -27
- package/dist/templates/sequential-reviewer/main.mts +1 -1
- package/package.json +7 -3
- package/dist/chunk-7N7AMUYA.js.map +0 -1
- package/dist/chunk-BIF2X6QB.js +0 -94
- package/dist/chunk-BIF2X6QB.js.map +0 -1
- package/dist/chunk-BVZWLFFT.js.map +0 -1
- package/dist/chunk-G2R53CVZ.js.map +0 -1
- package/dist/chunk-GCLEXPXG.js.map +0 -1
- package/dist/chunk-H2PEFS4W.js.map +0 -1
- package/dist/chunk-HSXPRZKG.js.map +0 -1
- package/dist/chunk-RDW7FNN6.js.map +0 -1
- package/dist/chunk-STB2U7BB.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { NativeInteractiveNotSupportedError } from './chunk-
|
|
2
|
+
import { NativeInteractiveNotSupportedError } from './chunk-YDQW5IOY.js';
|
|
3
3
|
|
|
4
4
|
createRequire(import.meta.url);
|
|
5
5
|
|
|
@@ -20,5 +20,5 @@ var assertInteractiveSupported = (provider) => {
|
|
|
20
20
|
};
|
|
21
21
|
|
|
22
22
|
export { NativeInteractiveNotSupportedError2 as NativeInteractiveNotSupportedError, assertInteractiveSupported, markNativeSandboxProvider };
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
24
|
-
//# sourceMappingURL=chunk-
|
|
23
|
+
//# sourceMappingURL=chunk-L3BU47F6.js.map
|
|
24
|
+
//# sourceMappingURL=chunk-L3BU47F6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nativeSandboxProvider.ts"],"names":["NativeInteractiveNotSupportedError"],"mappings":";;;;;;AAUA,IAAM,eAAA,uBAAsB,OAAA,EAAyB;AAG9C,IAAM,yBAAA,GAA4B,CACvC,QAAA,KACM;AACN,EAAA,eAAA,CAAgB,IAAI,QAAQ,CAAA;AAC5B,EAAA,OAAO,QAAA;AACT;AA4BO,IAAMA,mCAAAA,GACX;AAGK,IAAM,0BAAA,GAA6B,CACxC,QAAA,KACS;AACT,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,eAAA,CAAgB,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC3D,IAAA,MAAM,IAAIA,mCAAAA,CAAmC;AAAA,MAC3C,OAAA,EACE,CAAA,wDAAA,EAA2D,QAAA,CAAS,IAAI,CAAA,iEAAA,CAAA;AAAA,MAE1E,UAAU,QAAA,CAAS;AAAA,KACpB,CAAA;AAAA,EACH;AACF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/nativeSandboxProvider.ts"],"names":["NativeInteractiveNotSupportedError"],"mappings":";;;;;;AAUA,IAAM,eAAA,uBAAsB,OAAA,EAAyB;AAG9C,IAAM,yBAAA,GAA4B,CACvC,QAAA,KACM;AACN,EAAA,eAAA,CAAgB,IAAI,QAAQ,CAAA;AAC5B,EAAA,OAAO,QAAA;AACT;AA4BO,IAAMA,mCAAAA,GACX;AAGK,IAAM,0BAAA,GAA6B,CACxC,QAAA,KACS;AACT,EAAA,IAAI,QAAA,KAAa,MAAA,IAAa,eAAA,CAAgB,GAAA,CAAI,QAAQ,CAAA,EAAG;AAC3D,IAAA,MAAM,IAAIA,mCAAAA,CAAmC;AAAA,MAC3C,OAAA,EACE,CAAA,wDAAA,EAA2D,QAAA,CAAS,IAAI,CAAA,iEAAA,CAAA;AAAA,MAE1E,UAAU,QAAA,CAAS;AAAA,KACpB,CAAA;AAAA,EACH;AACF","file":"chunk-L3BU47F6.js","sourcesContent":["/**\n * Native sandbox providers: bind-mount sandbox providers that contain the\n * agent with the host OS's own process sandbox (Bubblewrap, Seatbelt) instead\n * of a container. They share the \"bind-mount\" tag, so core knows them by a\n * mark set when the provider is constructed.\n */\n\nimport { NativeInteractiveNotSupportedError as NativeInteractiveNotSupportedErrorImpl } from \"./errors.js\";\nimport type { SandboxProvider } from \"./SandboxProvider.js\";\n\nconst nativeProviders = new WeakSet<SandboxProvider>();\n\n/** Marks `provider` as a native sandbox provider, and returns it. */\nexport const markNativeSandboxProvider = <P extends SandboxProvider>(\n provider: P,\n): P => {\n nativeProviders.add(provider);\n return provider;\n};\n\n/**\n * `interactive()` was called with a native sandbox provider (`bwrap()`,\n * `seatbelt()`). Native providers don't run interactive sessions: use `run()`,\n * or pass `docker()` or `noSandbox()` to `interactive()`.\n *\n * Public-facing type for `NativeInteractiveNotSupportedError`. The runtime\n * class is the same `Data.TaggedError` from `errors.ts`, re-declared here as a\n * plain `Error` subclass so that Effect's types stay out of Sandcastle's\n * published `.d.ts` files.\n */\nexport interface NativeInteractiveNotSupportedError extends Error {\n readonly _tag: \"NativeInteractiveNotSupportedError\";\n readonly message: string;\n /** The native sandbox provider `interactive()` was called with. */\n readonly provider: string;\n}\n\ninterface NativeInteractiveNotSupportedErrorConstructor {\n new (args: {\n readonly message: string;\n readonly provider: string;\n }): NativeInteractiveNotSupportedError;\n readonly prototype: NativeInteractiveNotSupportedError;\n}\n\n/** `interactive()` was called with a native sandbox provider. */\nexport const NativeInteractiveNotSupportedError: NativeInteractiveNotSupportedErrorConstructor =\n NativeInteractiveNotSupportedErrorImpl;\n\n/** Throws `NativeInteractiveNotSupportedError` when `provider` is a native sandbox provider. */\nexport const assertInteractiveSupported = (\n provider: SandboxProvider | undefined,\n): void => {\n if (provider !== undefined && nativeProviders.has(provider)) {\n throw new NativeInteractiveNotSupportedError({\n message:\n `interactive() is not supported on native providers (got ${provider.name}()). ` +\n `Use run(), or pass docker() or noSandbox() to interactive().`,\n provider: provider.name,\n });\n }\n};\n"]}
|
|
@@ -259,7 +259,7 @@ var streamLines = (onLine, maxTailChars) => (proc) => {
|
|
|
259
259
|
onLine(line);
|
|
260
260
|
});
|
|
261
261
|
proc.stderr.on("data", (chunk) => {
|
|
262
|
-
stderrTail.push(chunk
|
|
262
|
+
stderrTail.push(chunk);
|
|
263
263
|
});
|
|
264
264
|
return () => ({
|
|
265
265
|
stdout: stdoutTail.toString(),
|
|
@@ -270,10 +270,10 @@ var bufferAll = (proc) => {
|
|
|
270
270
|
const stdoutChunks = [];
|
|
271
271
|
const stderrChunks = [];
|
|
272
272
|
proc.stdout.on("data", (chunk) => {
|
|
273
|
-
stdoutChunks.push(chunk
|
|
273
|
+
stdoutChunks.push(chunk);
|
|
274
274
|
});
|
|
275
275
|
proc.stderr.on("data", (chunk) => {
|
|
276
|
-
stderrChunks.push(chunk
|
|
276
|
+
stderrChunks.push(chunk);
|
|
277
277
|
});
|
|
278
278
|
return () => ({
|
|
279
279
|
stdout: stdoutChunks.join(""),
|
|
@@ -284,6 +284,8 @@ var waitForExec = async (proc, collect) => new Promise((resolve, reject) => {
|
|
|
284
284
|
proc.on("error", (error) => {
|
|
285
285
|
reject(new Error(`exec failed: ${error.message}`));
|
|
286
286
|
});
|
|
287
|
+
proc.stdout.setEncoding("utf8");
|
|
288
|
+
proc.stderr.setEncoding("utf8");
|
|
287
289
|
const output = collect(proc);
|
|
288
290
|
proc.on("close", (code) => {
|
|
289
291
|
resolve({ ...output(), exitCode: code ?? 0 });
|
|
@@ -349,5 +351,5 @@ var noSandbox = (options) => ({
|
|
|
349
351
|
});
|
|
350
352
|
|
|
351
353
|
export { noSandbox };
|
|
352
|
-
//# sourceMappingURL=chunk-
|
|
353
|
-
//# sourceMappingURL=chunk-
|
|
354
|
+
//# sourceMappingURL=chunk-PTJEKJPQ.js.map
|
|
355
|
+
//# sourceMappingURL=chunk-PTJEKJPQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandboxes/posixSimpleCommand.ts","../src/sandboxes/windowsCommand.ts","../src/sandboxes/no-sandbox.ts"],"names":[],"mappings":";;;;;;;;;;AAaA,IAAM,QAAA,GAAW,2BAAA;AAOjB,IAAM,gBAAA,GAAmB,yBAAA;AAGzB,IAAM,UAAA,GAAa,KAAA;AAGnB,IAAM,sBAAA,GAAyB,OAAA;AAQ/B,IAAM,gBAAA,GAAmB,CAAC,CAAA,EAAW,KAAA,KAAqC;AACxE,EAAA,MAAM,GAAA,GAAM,CAAA,CAAE,OAAA,CAAQ,GAAA,EAAK,QAAQ,CAAC,CAAA;AACpC,EAAA,OAAO,GAAA,KAAQ,EAAA,GACX,MAAA,G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AM,EAAE,cAAa,GAAI,aAAA;AACzB,IAAA,MAAM,OAAA,GAAuB;AAAA,MAC3B,YAAA;AAAA,MACA,YAAY,EAAE,GAAG,QAAQ,GAAA,EAAK,GAAG,cAAc,GAAA,EAAI;AAAA,MACnD,kBAAA,EAAoB,SAAS,kBAAA,IAAsB;AAAA,KACrD;AAEA,IAAA,MAAM,MAAA,GAA0B;AAAA,MAC9B,YAAA;AAAA,MACA,MAAM,OAAO,OAAA,EAAiB,SAC5B,OAAA,CAAQ,OAAA,EAAS,MAAM,OAAO,CAAA;AAAA,MAChC,iBAAiB,OACf,IAAA,EACA,SAEA,kBAAA,CAAmB,IAAA,EAAM,MAAM,OAAO,CAAA;AAAA,MACxC,OAAO,YAA2B;AAAA,MAElC;AAAA,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA","file":"chunk-PTJEKJPQ.js","sourcesContent":["/**\n * @internal Splits a POSIX shell command back into the argv it stands for,\n * when it is a simple command. noSandbox uses it on Windows (issue #940),\n * where there is no `sh` to do this, so the program can be spawned directly\n * instead of handing POSIX quoting to cmd.exe. See `windowsCommand.ts`.\n */\n\n/** A POSIX simple command: leading `export NAME=value;` statements, then argv. */\nexport interface SimpleCommand {\n readonly env: Record<string, string>;\n readonly argv: readonly string[];\n}\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;\n\n/**\n * Characters that make an unquoted word mean something to a POSIX shell\n * (operators, expansions, globs) or look like cmd.exe syntax (`%`, `^`).\n * A command containing one is not simple, and keeps the old cmd.exe path.\n */\nconst UNQUOTED_SPECIAL = \"|&<>()$`*?[]{}~#!%^\\n\\r\";\n\n/** Ends the current word without being part of one. */\nconst SEPARATORS = \" \\t;\";\n\n/** Characters a backslash escapes inside POSIX double quotes. */\nconst DOUBLE_QUOTE_ESCAPABLE = '\"\\\\$`';\n\n/** A run of characters read from the command, and where reading stops. */\ninterface Piece {\n readonly text: string;\n readonly next: number;\n}\n\nconst readSingleQuoted = (s: string, start: number): Piece | undefined => {\n const end = s.indexOf(\"'\", start + 1);\n return end === -1\n ? undefined\n : { text: s.slice(start + 1, end), next: end + 1 };\n};\n\nconst readDoubleQuoted = (s: string, start: number): Piece | undefined => {\n let text = \"\";\n let i = start + 1;\n while (i < s.length) {\n const c = s.charAt(i);\n const next = s.charAt(i + 1);\n if (c === '\"') {\n return { text, next: i + 1 };\n }\n if (c === \"$\" || c === \"`\" || (c === \"\\\\\" && next === \"\\n\")) {\n return undefined;\n }\n if (c === \"\\\\\" && next !== \"\" && DOUBLE_QUOTE_ESCAPABLE.includes(next)) {\n text += next;\n i += 2;\n } else {\n text += c;\n i += 1;\n }\n }\n return undefined;\n};\n\nconst readBare = (s: string, start: number): Piece => {\n let i = start;\n while (\n i < s.length &&\n !SEPARATORS.includes(s.charAt(i)) &&\n !UNQUOTED_SPECIAL.includes(s.charAt(i)) &&\n !\"'\\\"\\\\\".includes(s.charAt(i))\n ) {\n i += 1;\n }\n return { text: s.slice(start, i), next: i };\n};\n\n/** Read the next piece of a word, or undefined if the command isn't simple. */\nconst readPiece = (s: string, start: number): Piece | undefined => {\n const c = s.charAt(start);\n if (c === \"'\") {\n return readSingleQuoted(s, start);\n }\n if (c === '\"') {\n return readDoubleQuoted(s, start);\n }\n if (c === \"\\\\\") {\n // Only the `\\'` that shellEscape emits. Any other bare backslash is more\n // likely a Windows path than a POSIX escape: leave it to cmd.exe.\n return s.charAt(start + 1) === \"'\"\n ? { text: \"'\", next: start + 2 }\n : undefined;\n }\n if (UNQUOTED_SPECIAL.includes(c)) {\n return undefined;\n }\n return readBare(s, start);\n};\n\n/** Split into statements (on `;`), each a list of words. */\nconst splitStatements = (s: string): string[][] | undefined => {\n const statements: string[][] = [[]];\n let word: string | undefined;\n const endWord = () => {\n if (word !== undefined) {\n statements.at(-1)?.push(word);\n }\n word = undefined;\n };\n let i = 0;\n while (i < s.length) {\n const c = s.charAt(i);\n const piece = SEPARATORS.includes(c) ? undefined : readPiece(s, i);\n if (piece !== undefined) {\n word = (word ?? \"\") + piece.text;\n i = piece.next;\n } else if (SEPARATORS.includes(c)) {\n endWord();\n if (c === \";\") {\n statements.push([]);\n }\n i += 1;\n } else {\n return undefined;\n }\n }\n endWord();\n return statements;\n};\n\n/** The env an `export NAME=value …` statement sets, or undefined. */\nconst exportedEnv = (\n statement: readonly string[],\n): Record<string, string> | undefined => {\n const [keyword, ...assignments] = statement;\n if (keyword !== \"export\" || assignments.length === 0) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const assignment of assignments) {\n const eq = assignment.indexOf(\"=\");\n const name = assignment.slice(0, eq);\n if (eq === -1 || !ENV_NAME.test(name)) {\n return undefined;\n }\n env[name] = assignment.slice(eq + 1);\n }\n return env;\n};\n\n/**\n * Split a POSIX shell command into argv, when it is a simple command.\n *\n * Understands exactly what Sandcastle produces: bare words, `'single'`\n * quotes, `\"double\"` quotes with POSIX backslash escapes, the `\\'` that\n * `shellEscape` emits between quoted runs, and leading `export NAME=value;`\n * statements (the agent env prefix from `createSandbox`). Returns undefined\n * for anything else.\n */\nexport const parseSimpleCommand = (\n command: string,\n): SimpleCommand | undefined => {\n const statements = splitStatements(command);\n const argv = statements?.pop();\n const [program] = argv ?? [];\n if (\n statements === undefined ||\n argv === undefined ||\n program === undefined ||\n program === \"\" ||\n program.includes(\"=\")\n ) {\n return undefined;\n }\n const env: Record<string, string> = {};\n for (const statement of statements) {\n const exported = exportedEnv(statement);\n if (exported === undefined) {\n return undefined;\n }\n Object.assign(env, exported);\n }\n return { env, argv };\n};\n","/**\n * @internal How noSandbox runs a command on Windows (issue #940).\n *\n * Sandcastle builds every exec command as a POSIX shell string (agent print\n * commands quote their values with `shellEscape`), because docker, podman,\n * vercel and daytona all run it with `sh -c`. Windows has no `sh`, and cmd.exe\n * does not understand POSIX quoting, so handing that string to cmd.exe\n * delivers `'claude-fable-5'`, quotes and all.\n *\n * Instead of re-quoting the string for cmd.exe, noSandbox splits it back into\n * the argv it stands for and launches the program directly:\n *\n * - an `.exe` gets the argv array with no shell at all; Node's own argv\n * quoting handles spaces, quotes, `%`, `^`, `&`, `|` and newlines;\n * - a `.cmd`/`.bat` (how npm installs agent CLIs on Windows) can only run\n * under cmd.exe, so its command line is escaped with the standard rules\n * for a batch file that forwards `%*` (as cross-spawn does);\n * - anything that is not a simple command (pipes, redirects, `$VAR`, cmd.exe\n * builtins, Windows-style `%VAR%`) goes to cmd.exe unchanged, as before.\n */\nimport { stat } from \"node:fs/promises\";\nimport { win32 } from \"node:path\";\nimport { parseSimpleCommand } from \"./posixSimpleCommand.js\";\n\n/** How to spawn a command: `file` with `args`, no shell. */\nexport interface SpawnPlan {\n readonly file: string;\n readonly args: readonly string[];\n readonly windowsVerbatimArguments: boolean;\n}\n\ntype Env = Record<string, string | undefined>;\n\n/**\n * Read an env var the way Windows does: names are case-insensitive, and when\n * an env object holds two spellings (`Path` and `PATH`), Node's spawn uses\n * the lexicographically first, so this does too.\n */\nconst getEnv = (env: Env, name: string): string | undefined => {\n const key = Object.keys(env)\n .filter((k) => k.toUpperCase() === name)\n .reduce<string | undefined>(\n (first, k) => (first === undefined || k < first ? k : first),\n undefined,\n );\n return key === undefined ? undefined : env[key];\n};\n\nconst isFile = async (path: string): Promise<boolean> => {\n try {\n const stats = await stat(path);\n return stats.isFile();\n } catch {\n return false;\n }\n};\n\n/** The paths Windows would try for `program`, in order. */\nconst candidatePaths = (program: string, env: Env, cwd: string): string[] => {\n const pathExt = (getEnv(env, \"PATHEXT\") ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .filter((ext) => ext !== \"\")\n .map((ext) => ext.toLowerCase());\n const hasExt = pathExt.includes(win32.extname(program).toLowerCase());\n const withExts = (base: string) =>\n hasExt ? [base] : pathExt.map((ext) => `${base}${ext}`);\n\n if (/[\\\\/]/u.test(program) || win32.isAbsolute(program)) {\n return withExts(win32.resolve(cwd, program));\n }\n return (getEnv(env, \"PATH\") ?? \"\")\n .split(\";\")\n .map((dir) => dir.replaceAll('\"', \"\").trim())\n .filter((dir) => dir !== \"\")\n .flatMap((dir) => withExts(win32.join(dir, program)));\n};\n\n/**\n * Find the file Windows would run for `program`: an explicit path (relative\n * to `cwd`), or the first PATH directory holding `program` with a PATHEXT\n * extension. Returns undefined when nothing matches (cmd.exe builtins such\n * as `echo`, or a program that isn't installed).\n */\nexport const resolveWindowsProgram = async (\n program: string,\n env: Env,\n cwd: string,\n): Promise<string | undefined> => {\n const candidates = candidatePaths(program, env, cwd);\n const found = await Promise.all(candidates.map(async (p) => isFile(p)));\n return candidates[found.indexOf(true)];\n};\n\n/** cmd.exe metacharacters, escaped with `^` (the set cross-spawn uses). */\nconst CMD_META = /(?<meta>[()\\][%!^\"`<>&|;, *?])/gu;\n\n/** The longest command line cmd.exe accepts. */\nexport const CMD_MAX_COMMAND_LINE = 8191;\n\nconst escapeCmdMeta = (s: string): string => s.replaceAll(CMD_META, \"^$<meta>\");\n\n/**\n * Quote one argument for a batch file run through `cmd.exe /d /s /c`.\n *\n * First quote it for the program the batch file ends up launching (the\n * Windows argv rules: backslashes double only before a quote or the end),\n * then `^`-escape every cmd.exe metacharacter twice: once for cmd.exe\n * reading the `/c` line, and once for the batch file's own `%*` line, which\n * cmd.exe parses again.\n */\nconst escapeBatchArgument = (arg: string): string => {\n const quoted = arg\n .replaceAll(/(?<bs>\\\\*)\"/gu, String.raw`$<bs>$<bs>\\\"`)\n .replace(/(?<bs>\\\\*)$/u, \"$<bs>$<bs>\");\n return escapeCmdMeta(escapeCmdMeta(`\"${quoted}\"`));\n};\n\n/** Plan a batch file run under cmd.exe, refusing what cmd.exe can't carry. */\nconst planBatch = (\n program: string,\n file: string,\n { args, comspec }: { args: readonly string[]; comspec: string },\n): SpawnPlan => {\n const name = win32.basename(file);\n if (args.some((arg) => /[\\r\\n]/u.test(arg))) {\n throw new Error(\n `${program} is a batch file (${name}), which runs under cmd.exe, and cmd.exe cannot pass an argument containing a newline. Pass that text on stdin instead.`,\n );\n }\n const commandLine = [\n escapeCmdMeta(file),\n ...args.map((arg) => escapeBatchArgument(arg)),\n ].join(\" \");\n if (commandLine.length > CMD_MAX_COMMAND_LINE) {\n throw new Error(\n `The command line for ${program} (${name}) is too long for cmd.exe: ${commandLine.length} characters once escaped, over the ${CMD_MAX_COMMAND_LINE}-character limit. Pass long text on stdin instead.`,\n );\n }\n return {\n file: comspec,\n args: [\"/d\", \"/s\", \"/c\", `\"${commandLine}\"`],\n windowsVerbatimArguments: true,\n };\n};\n\n/**\n * Plan how to spawn `argv` on Windows without re-quoting it by hand where\n * that can be avoided. Resolves undefined when the program can't be found\n * on PATH, so the caller keeps its old cmd.exe behaviour.\n *\n * Rejects when a batch file would be handed an argument cmd.exe cannot carry\n * (a newline, or a command line over 8191 characters), rather than letting\n * cmd.exe silently cut the command short.\n */\nexport const planWindowsSpawn = async (\n argv: readonly string[],\n env: Env,\n cwd: string,\n): Promise<SpawnPlan | undefined> => {\n const [program, ...args] = argv;\n if (program === undefined) {\n return undefined;\n }\n const file = await resolveWindowsProgram(program, env, cwd);\n if (file === undefined) {\n return undefined;\n }\n const ext = win32.extname(file).toLowerCase();\n if (ext === \".cmd\" || ext === \".bat\") {\n return planBatch(program, file, {\n args,\n comspec: getEnv(env, \"COMSPEC\") ?? \"cmd.exe\",\n });\n }\n return { file, args, windowsVerbatimArguments: false };\n};\n\n/**\n * Plan how noSandbox's `exec` runs a command string on Windows: as a direct\n * spawn when it is a simple command whose program is on PATH, otherwise\n * through `cmd.exe /d /s /c` unchanged (the behaviour before #940).\n */\nexport const planWindowsExec = async (\n command: string,\n env: Env,\n cwd: string,\n): Promise<SpawnPlan & { readonly env: Env }> => {\n const simple = parseSimpleCommand(command);\n if (simple !== undefined) {\n const commandEnv = { ...env, ...simple.env };\n const plan = await planWindowsSpawn(simple.argv, commandEnv, cwd);\n if (plan !== undefined) {\n return { ...plan, env: commandEnv };\n }\n }\n return {\n file: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", command],\n windowsVerbatimArguments: true,\n env,\n };\n};\n","/**\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 } from \"node:child_process\";\nimport type { ChildProcessByStdio, StdioOptions } from \"node:child_process\";\nimport { createInterface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport type {\n NoSandboxProvider,\n NoSandboxHandle,\n ExecResult,\n InteractiveExecOptions,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { planWindowsExec, planWindowsSpawn } from \"./windowsCommand.js\";\nimport type { SpawnPlan } from \"./windowsCommand.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\ntype ProcessEnv = Record<string, string | undefined>;\n\n/** A spawn plan for `exec`, with the env the command runs under. */\ntype ExecPlan = SpawnPlan & { readonly env: ProcessEnv };\n\ninterface ExecOptions {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n}\n\n/** What a handle's `exec` and `interactiveExec` share. */\ninterface HostContext {\n readonly worktreePath: string;\n readonly processEnv: ProcessEnv;\n readonly maxOutputTailChars: number;\n}\n\n/** A spawned `exec` process: stdout and stderr are always piped. */\ntype ExecProcess = ChildProcessByStdio<Writable | null, Readable, Readable>;\n\n/**\n * Attaches output listeners to a process whose stdout and stderr emit UTF-8\n * strings; call the result on close for the output.\n */\ntype OutputCollector = (proc: ExecProcess) => () => {\n stdout: string;\n stderr: string;\n};\n\nconst planExec = async (\n command: string,\n env: ProcessEnv,\n cwd: string,\n): Promise<ExecPlan> =>\n // Windows has no `sh`, and cmd.exe doesn't understand the POSIX\n // quoting in Sandcastle's commands (#940): run simple commands as a\n // direct spawn of their argv, and only the rest through cmd.exe.\n process.platform === \"win32\"\n ? planWindowsExec(command, env, cwd)\n : {\n file: \"sh\",\n args: [\"-c\", command],\n windowsVerbatimArguments: false,\n env,\n };\n\nconst spawnExec = (\n plan: ExecPlan,\n cwd: string,\n stdin: string | undefined,\n): ExecProcess => {\n const spawnOptions = {\n cwd,\n env: plan.env,\n windowsVerbatimArguments: plan.windowsVerbatimArguments,\n };\n // Two literal `stdio` tuples, so the types know stdout and stderr\n // are always piped.\n if (stdin === undefined) {\n return spawn(plan.file, plan.args, {\n ...spawnOptions,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n }\n const proc = spawn(plan.file, plan.args, {\n ...spawnOptions,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n proc.stdin.write(stdin);\n proc.stdin.end();\n return proc;\n};\n\n/** Streams stdout to `onLine` line by line, keeping only a bounded tail. */\nconst streamLines =\n (onLine: (line: string) => void, maxTailChars: number): OutputCollector =>\n (proc) => {\n const stdoutTail = new BoundedTail(maxTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxTailChars, \"\");\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: string) => {\n stderrTail.push(chunk);\n });\n return () => ({\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n });\n };\n\n/** Buffers all of stdout and stderr. */\nconst bufferAll: OutputCollector = (proc) => {\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n proc.stdout.on(\"data\", (chunk: string) => {\n stdoutChunks.push(chunk);\n });\n proc.stderr.on(\"data\", (chunk: string) => {\n stderrChunks.push(chunk);\n });\n return () => ({\n stdout: stdoutChunks.join(\"\"),\n stderr: stderrChunks.join(\"\"),\n });\n};\n\nconst waitForExec = async (\n proc: ExecProcess,\n collect: OutputCollector,\n): Promise<ExecResult> =>\n new Promise((resolve, reject) => {\n proc.on(\"error\", (error: Error) => {\n reject(new Error(`exec failed: ${error.message}`));\n });\n // Decode as UTF-8 streams, so a multi-byte character split across two\n // chunks is joined back up instead of becoming replacement characters.\n proc.stdout.setEncoding(\"utf8\");\n proc.stderr.setEncoding(\"utf8\");\n const output = collect(proc);\n proc.on(\"close\", (code: number | null) => {\n resolve({ ...output(), exitCode: code ?? 0 });\n });\n });\n\nconst runExec = async (\n command: string,\n opts: ExecOptions | undefined,\n context: HostContext,\n): Promise<ExecResult> => {\n // sudo is a no-op for no-sandbox — the user is already on the host\n const cwd = opts?.cwd ?? context.worktreePath;\n const plan = await planExec(command, context.processEnv, cwd);\n const proc = spawnExec(plan, cwd, opts?.stdin);\n const collect = opts?.onLine\n ? streamLines(opts.onLine, context.maxOutputTailChars)\n : bufferAll;\n return waitForExec(proc, collect);\n};\n\nconst runInteractiveExec = async (\n args: string[],\n opts: InteractiveExecOptions,\n context: HostContext,\n): Promise<{ exitCode: number }> => {\n const { processEnv } = context;\n const cwd = opts.cwd ?? context.worktreePath;\n const stdio = [opts.stdin, opts.stdout, opts.stderr] as StdioOptions;\n // On Windows, spawn the resolved program with its argv (escaped for\n // cmd.exe only when it is a `.cmd`/`.bat` npm shim, #940). If it\n // isn't on PATH, fall back to `shell: true` so cmd.exe can try.\n const plan =\n process.platform === \"win32\"\n ? await planWindowsSpawn(args, processEnv, cwd)\n : undefined;\n return new Promise((resolve, reject) => {\n const [cmd, ...rest] = args;\n if (cmd === undefined) {\n reject(new Error(\"interactiveExec needs a command to run\"));\n return;\n }\n const proc = plan\n ? spawn(plan.file, plan.args, {\n cwd,\n env: processEnv,\n stdio,\n windowsVerbatimArguments: plan.windowsVerbatimArguments,\n })\n : spawn(cmd, rest, {\n cwd,\n env: processEnv,\n stdio,\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/**\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;\n const context: HostContext = {\n worktreePath,\n processEnv: { ...process.env, ...createOptions.env },\n maxOutputTailChars: options?.maxOutputTailChars ?? MAX_TAIL_CHARS,\n };\n\n const handle: NoSandboxHandle = {\n worktreePath,\n exec: async (command: string, opts?: ExecOptions): Promise<ExecResult> =>\n runExec(command, opts, context),\n interactiveExec: async (\n args: string[],\n opts: InteractiveExecOptions,\n ): Promise<{ exitCode: number }> =>\n runInteractiveExec(args, opts, context),\n close: async (): Promise<void> => {\n // No-op — no container to tear down\n },\n };\n\n return handle;\n },\n});\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { ForkNotSupportedError } from './chunk-
|
|
2
|
+
import { ForkNotSupportedError } from './chunk-YDQW5IOY.js';
|
|
3
3
|
import { createHash } from 'crypto';
|
|
4
4
|
import { readdir, mkdir, writeFile, readFile, access, rm } from 'fs/promises';
|
|
5
5
|
import { join, posix, dirname, relative } from 'path';
|
|
@@ -331,7 +331,8 @@ var TOOL_ARG_FIELDS = {
|
|
|
331
331
|
Bash: "command",
|
|
332
332
|
WebSearch: "query",
|
|
333
333
|
WebFetch: "url",
|
|
334
|
-
Agent: "description"
|
|
334
|
+
Agent: "description",
|
|
335
|
+
Skill: "skill"
|
|
335
336
|
};
|
|
336
337
|
var messageField = (value) => typeof value === "object" && value !== null && "message" in value && typeof value.message === "string" ? value.message : void 0;
|
|
337
338
|
var extractErrorMessage = (obj) => {
|
|
@@ -756,6 +757,25 @@ var parsePiAgentEnd = (messages) => {
|
|
|
756
757
|
);
|
|
757
758
|
return texts.length > 0 ? [{ type: "result", result: texts.join("") }] : [];
|
|
758
759
|
};
|
|
760
|
+
var parsePiUsage = (u) => {
|
|
761
|
+
if (typeof u !== "object" || u === null) {
|
|
762
|
+
return void 0;
|
|
763
|
+
}
|
|
764
|
+
const field = (key) => Reflect.get(u, key);
|
|
765
|
+
const input = field("input");
|
|
766
|
+
const output = field("output");
|
|
767
|
+
const cacheRead = field("cacheRead");
|
|
768
|
+
const cacheWrite = field("cacheWrite");
|
|
769
|
+
if (typeof input !== "number" || typeof output !== "number" || typeof cacheRead !== "number" || typeof cacheWrite !== "number") {
|
|
770
|
+
return void 0;
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
inputTokens: input,
|
|
774
|
+
cacheCreationInputTokens: cacheWrite,
|
|
775
|
+
cacheReadInputTokens: cacheRead,
|
|
776
|
+
outputTokens: output
|
|
777
|
+
};
|
|
778
|
+
};
|
|
759
779
|
var parsePiStreamLine = (line) => {
|
|
760
780
|
if (!line.startsWith("{")) return [];
|
|
761
781
|
try {
|
|
@@ -765,7 +785,11 @@ var parsePiStreamLine = (line) => {
|
|
|
765
785
|
}
|
|
766
786
|
if (obj.type === "message_end" && obj.message?.role === "assistant") {
|
|
767
787
|
const u = obj.message.usage;
|
|
768
|
-
|
|
788
|
+
const usage = parsePiUsage(u);
|
|
789
|
+
return [
|
|
790
|
+
...contextWindowEvent(u?.input, u?.cacheRead, u?.cacheWrite),
|
|
791
|
+
...usage ? [{ type: "usage", usage }] : []
|
|
792
|
+
];
|
|
769
793
|
}
|
|
770
794
|
if (obj.type === "message_update" && obj.assistantMessageEvent) {
|
|
771
795
|
const evt = obj.assistantMessageEvent;
|
|
@@ -1181,7 +1205,7 @@ var buildClaudePrintCommand = (model, options, {
|
|
|
1181
1205
|
const resumeFlag = resumeSession ? ` --resume ${shellEscape(resumeSession)}` : "";
|
|
1182
1206
|
const forkFlag = resumeSession && forkSession ? " --fork-session" : "";
|
|
1183
1207
|
return {
|
|
1184
|
-
command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag}
|
|
1208
|
+
command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag}`,
|
|
1185
1209
|
stdin: prompt
|
|
1186
1210
|
};
|
|
1187
1211
|
};
|
|
@@ -1240,5 +1264,5 @@ var claudeCode = (model, options) => ({
|
|
|
1240
1264
|
});
|
|
1241
1265
|
|
|
1242
1266
|
export { claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, opencode, pi, shellEscape, transferClaudeSession, transferCodexSession };
|
|
1243
|
-
//# sourceMappingURL=chunk-
|
|
1244
|
-
//# sourceMappingURL=chunk-
|
|
1267
|
+
//# sourceMappingURL=chunk-SAQXFLO2.js.map
|
|
1268
|
+
//# sourceMappingURL=chunk-SAQXFLO2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/SessionStore.ts","../src/AgentProvider.ts"],"names":["result","join","readFile","writeFile","posix","mkdir","dirname"],"mappings":";;;;;;;;AAgBO,IAAM,OAAA,GAAU,MAAc,OAAA,CAAQ,GAAA,CAAI,IAAA,IAAQ,GAAA;AAoBlD,IAAM,iBAAA,GAAoB,OAC/B,KAAA,KACgC;AAChC,EAAA,MAAM,CAAC,IAAA,EAAM,GAAG,IAAI,CAAA,GAAI,KAAA;AACxB,EAAA,IAAI,SAAS,MAAA,EAAW;AACtB,IAAA,OAAO,MAAA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qB,OAAA,CAAQ,cAAc,CAAA;AAAA,IACvD,WAAW,0BAAA,EAA4B;AACrC,MAAA,IAAA,CAAK,KAAK,gCAAgC,CAAA;AAAA,IAC5C;AACA,IAAA,IAAA,CAAK,IAAA,CAAK,WAAW,KAAK,CAAA;AAC1B,IAAA,IAAI,SAAS,MAAA,EAAQ,IAAA,CAAK,IAAA,CAAK,UAAA,EAAY,QAAQ,MAAM,CAAA;AACzD,IAAA,IAAI,MAAA,EAAQ,IAAA,CAAK,IAAA,CAAK,MAAM,CAAA;AAC5B,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAAA,EAEA,gBAAgB,IAAA,EAAmC;AACjD,IAAA,OAAO,CAAC,GAAG,mBAAA,CAAoB,IAAI,GAAG,GAAG,wBAAA,CAAyB,IAAI,CAAC,CAAA;AAAA,EACzE,CAAA;AAAA,EAEA,kBAAkB,OAAA,EAA6C;AAC7D,IAAA,OAAO,wBAAwB,OAAO,CAAA;AAAA,EACxC;AACF,CAAA","file":"chunk-SAQXFLO2.js","sourcesContent":["/**\n * Session JSONL transfer primitives.\n *\n * The transfer functions are pure: they take a JSONL string and the source/\n * target cwds, and return the rewritten JSONL string. Call sites do their own\n * file I/O (reading the source, writing the destination). Per ADR 0012, the\n * cwd rewrite is specific to each agent's JSONL format, so each agent owns\n * its own transfer function.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { access, mkdir, readFile, readdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join, posix } from \"node:path\";\nimport type { BindMountSandboxHandle, ExecResult } from \"./SandboxProvider.js\";\n\n/** The host user's home directory, where every agent keeps its sessions. */\nexport const homeDir = (): string => process.env.HOME ?? \"~\";\n\n// ---------------------------------------------------------------------------\n// Host session lookup\n// ---------------------------------------------------------------------------\n\n/**\n * Result of locating a session on the host by its unique id, independent of any\n * cwd-derived path encoding.\n */\nexport interface HostSessionLookup {\n /** Absolute path to the located session file, or `undefined` when no session\n * with this id exists anywhere under the searched root. */\n readonly path: string | undefined;\n /** The host directory that was scanned — surfaced in not-found errors so the\n * user knows where Sandcastle looked. */\n readonly searchedRoot: string;\n}\n\n/** The first of `paths` that exists, checked in order, or `undefined`. */\nexport const firstExistingPath = async (\n paths: readonly string[],\n): Promise<string | undefined> => {\n const [head, ...rest] = paths;\n if (head === undefined) {\n return undefined;\n }\n return (await pathExists(head)) ? head : firstExistingPath(rest);\n};\n\n/** Whether a file or directory exists at `path`. */\nexport const pathExists = async (path: string): Promise<boolean> => {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Claude Code session paths and transfer\n// ---------------------------------------------------------------------------\n\n/** Longest project directory name Claude Code writes before it truncates. */\nconst MAX_PROJECT_DIR_LENGTH = 200;\n\n/** Claude Code's 32-bit string hash, in base 36, for truncated names. */\nconst claudePathHash = (value: string): string => {\n // Over UTF-16 code units, wrapping to a signed 32-bit int as Claude Code\n // does; Math.imul does the wrap.\n const hash = value\n .split(\"\")\n .reduce((acc, unit) => Math.imul(31, acc) + (unit.codePointAt(0) ?? 0), 0);\n return Math.abs(Math.imul(hash, 1)).toString(36);\n};\n\n/**\n * Encode a cwd into the Claude Code `~/.claude/projects/<encoded>/` layout,\n * matching Claude Code's own naming: every character that isn't an ASCII\n * letter or digit becomes a hyphen (so `/`, `\\`, `:` and `.` all do), and a\n * name longer than 200 characters is cut to 200 and suffixed with a hash of\n * the full path. A trailing path separator is ignored.\n */\nexport const encodeProjectPath = (cwd: string): string => {\n const isRoot = cwd === \"/\" || /^[A-Za-z]:[\\\\/]?$/u.test(cwd);\n const normalized = isRoot ? cwd : cwd.replace(/[\\\\/]+$/u, \"\");\n const encoded = normalized.replaceAll(/[^A-Za-z0-9]/gu, \"-\");\n if (encoded.length <= MAX_PROJECT_DIR_LENGTH) {\n return encoded;\n }\n return `${encoded.slice(0, MAX_PROJECT_DIR_LENGTH)}-${claudePathHash(normalized)}`;\n};\n\n/**\n * The agent's home and temp dir inside a sandbox, as commands running there\n * see them. Commands Sandcastle runs inside the sandbox build their paths\n * from these, never from a literal `/home/agent` or `/tmp`.\n */\nexport interface SandboxDirs {\n readonly home: string;\n readonly tmp: string;\n}\n\n/** The Docker image layout, for a handle that doesn't report its dirs. */\nconst DEFAULT_SANDBOX_DIRS: SandboxDirs = { home: \"/home/agent\", tmp: \"/tmp\" };\n\n/** The home and temp dir a sandbox handle reports, or the image defaults. */\nexport const sandboxDirsOf = (\n handle: Pick<BindMountSandboxHandle, \"sandboxHomedir\" | \"sandboxTmpdir\">,\n): SandboxDirs => ({\n home: handle.sandboxHomedir ?? DEFAULT_SANDBOX_DIRS.home,\n tmp: handle.sandboxTmpdir ?? DEFAULT_SANDBOX_DIRS.tmp,\n});\n\n/** Absolute host path to a Claude session JSONL file. */\nexport const claudeHostSessionPath = (\n cwd: string,\n id: string,\n projectsDir?: string,\n): string => {\n const base = projectsDir ?? join(homeDir(), \".claude\", \"projects\");\n return join(base, encodeProjectPath(cwd), `${id}.jsonl`);\n};\n\n/** Sandbox-side path to a Claude session JSONL file (always POSIX separators). */\nexport const claudeSandboxSessionPath = (\n cwd: string,\n id: string,\n projectsDir: string,\n): string => posix.join(projectsDir, encodeProjectPath(cwd), `${id}.jsonl`);\n\n/**\n * Sandbox-side path to the directory holding subagent / workflow transcripts\n * for a given Claude Code session, following Claude Code's\n * `<projectsDir>/<encoded-cwd>/<sessionId>/subagents/` layout. POSIX\n * separators so it works on Windows hosts driving Linux containers.\n */\nexport const claudeSubagentsDirInSandbox = (\n cwd: string,\n id: string,\n projectsDir: string,\n): string => posix.join(projectsDir, encodeProjectPath(cwd), id, \"subagents\");\n\n/**\n * Host-side path to the directory holding subagent / workflow transcripts for\n * a given Claude Code session. Defaults to `~/.claude/projects` when no\n * `projectsDir` is provided.\n */\nexport const claudeSubagentsDirOnHost = (\n cwd: string,\n id: string,\n projectsDir?: string,\n): string => {\n const base = projectsDir ?? join(homeDir(), \".claude\", \"projects\");\n return join(base, encodeProjectPath(cwd), id, \"subagents\");\n};\n\n/**\n * Enumerate Claude Code subagent / workflow transcripts living under\n * `<projectsDir>/<encoded-cwd>/<sessionId>/subagents/` inside the sandbox.\n * Returns the absolute sandbox-side paths of every `agent-*.jsonl` file\n * (matched at any depth so future per-workflow subdirs still surface).\n *\n * Never throws — a missing `subagents/` directory is the normal case for a\n * session that didn't spawn any subagents, and `find` over an absent path\n * also exits non-zero. Both collapse to `[]`.\n */\nexport const listClaudeSubagentSessionsInSandbox = async (\n cwd: string,\n id: string,\n handle: Pick<BindMountSandboxHandle, \"exec\">,\n sandboxProjectsDir: string,\n): Promise<string[]> => {\n const dir = claudeSubagentsDirInSandbox(cwd, id, sandboxProjectsDir);\n const result = await handle.exec(\n `find ${JSON.stringify(dir)} -type f -name ${JSON.stringify(\"agent-*.jsonl\")} 2>/dev/null`,\n );\n if (result.exitCode !== 0) {\n return [];\n }\n const stdout = result.stdout.trim();\n if (stdout === \"\") {\n return [];\n }\n return stdout.split(\"\\n\").filter((line) => line !== \"\");\n};\n\n/**\n * Locate a Claude Code session JSONL on the host by its unique id, scanning each\n * `~/.claude/projects/<encoded-cwd>/` directory rather than reconstructing the\n * cwd encoding. The session id is globally unique, so the first match wins.\n */\nexport const findClaudeSessionOnHost = async (\n id: string,\n projectsDir?: string,\n): Promise<HostSessionLookup> => {\n const root = projectsDir ?? join(homeDir(), \".claude\", \"projects\");\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return { path: undefined, searchedRoot: root };\n }\n const candidates = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => join(root, entry.name, `${id}.jsonl`));\n return { path: await firstExistingPath(candidates), searchedRoot: root };\n};\n\n/**\n * Point one session entry at `toCwd`: its own `cwd`, and the `payload.cwd` of\n * a Codex `session_meta` entry, when either is `fromCwd`.\n */\nconst rewriteEntryCwd = (\n entry: Record<string, unknown>,\n fromCwd: string,\n toCwd: string,\n): void => {\n if (typeof entry.cwd === \"string\" && entry.cwd === fromCwd) {\n entry.cwd = toCwd;\n }\n if (\n entry.type === \"session_meta\" &&\n isRecord(entry.payload) &&\n typeof entry.payload.cwd === \"string\" &&\n entry.payload.cwd === fromCwd\n ) {\n entry.payload.cwd = toCwd;\n }\n};\n\nconst rewriteSessionCwd = (\n content: string,\n fromCwd: string,\n toCwd: string,\n): string => {\n if (content === \"\") {\n return \"\";\n }\n return content\n .split(\"\\n\")\n .map((line) => {\n if (line === \"\") {\n return line;\n }\n // A torn final line (writer killed mid-flush) must not abort the whole\n // transfer — preserve it verbatim so the rest of the session survives.\n try {\n const entry: unknown = JSON.parse(line);\n if (!isRecord(entry)) {\n return line;\n }\n rewriteEntryCwd(entry, fromCwd, toCwd);\n return JSON.stringify(entry);\n } catch {\n return line;\n }\n })\n .join(\"\\n\");\n};\n\n/**\n * Rewrite a Claude Code session JSONL string, replacing `cwd` fields that\n * match `fromCwd` with `toCwd`. Pure function — no file I/O.\n */\nexport const transferClaudeSession = (\n jsonl: string,\n fromCwd: string,\n toCwd: string,\n): string => rewriteSessionCwd(jsonl, fromCwd, toCwd);\n\n// ---------------------------------------------------------------------------\n// Codex session paths and transfer\n// ---------------------------------------------------------------------------\n\nconst isCodexSessionFilename = (filename: string, id: string): boolean =>\n filename.startsWith(\"rollout-\") && filename.endsWith(`-${id}.jsonl`);\n\n/**\n * Locate a Codex session rollout file on the host by its id, scanning the\n * date-nested `YYYY/MM/DD/` directories depth-first.\n */\nexport const findCodexSessionOnHost = async (\n id: string,\n sessionsDir?: string,\n): Promise<HostSessionLookup> => {\n const root = sessionsDir ?? join(homeDir(), \".codex\", \"sessions\");\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return { path: undefined, searchedRoot: root };\n }\n for (const entry of entries) {\n const child = join(root, entry.name);\n if (entry.isFile() && isCodexSessionFilename(entry.name, id)) {\n return { path: child, searchedRoot: root };\n }\n if (entry.isDirectory()) {\n const { path } = await findCodexSessionOnHost(id, child);\n if (path !== undefined) {\n return { path, searchedRoot: root };\n }\n }\n }\n return { path: undefined, searchedRoot: root };\n};\n\n/**\n * The path of a session found on the host, or a not-found error naming the\n * directory searched. For resume, where the precheck already found it.\n */\nexport const requireHostSessionPath = (\n found: HostSessionLookup,\n id: string,\n): string => {\n if (found.path === undefined) {\n throw new Error(`session ${id} not found in ${found.searchedRoot}`);\n }\n return found.path;\n};\n\n/** A session file found in the sandbox, with its path relative to the sessions dir. */\nexport interface SandboxSessionLocation {\n readonly path: string;\n readonly relativePath: string;\n}\n\n/**\n * Locate a session file in the sandbox by its file-name glob (codex:\n * `rollout-*-<id>.jsonl`, pi: `*_<id>.jsonl`), scanning `sessionsDir`.\n */\nexport const locateSandboxSessionFile = async (\n handle: Pick<BindMountSandboxHandle, \"exec\">,\n sessionsDir: string,\n nameGlob: string,\n): Promise<SandboxSessionLocation> => {\n const result = await handle.exec(\n `find ${JSON.stringify(sessionsDir)} -type f -name ${JSON.stringify(nameGlob)} -print -quit`,\n );\n const [path = \"\"] = result.stdout.trim().split(\"\\n\");\n if (result.exitCode !== 0 || path === \"\") {\n throw new Error(`session ${nameGlob} not found in ${sessionsDir}`);\n }\n return { path, relativePath: posix.relative(sessionsDir, path) };\n};\n\n/**\n * Rewrite a Codex session JSONL string, replacing `cwd` fields (both top-level\n * and `session_meta.payload.cwd`) that match `fromCwd` with `toCwd`. Pure\n * function — no file I/O.\n */\nexport const transferCodexSession = (\n jsonl: string,\n fromCwd: string,\n toCwd: string,\n): string => rewriteSessionCwd(jsonl, fromCwd, toCwd);\n\n// ---------------------------------------------------------------------------\n// Pi session paths and transfer\n// ---------------------------------------------------------------------------\n\n/**\n * Encode a cwd into pi's `~/.pi/agent/sessions/<encoded>/` layout. Pi strips the\n * leading separator and replaces path separators / drive colons with `-`, then\n * wraps the result in `--` markers. Mirrors `@mariozechner/pi-agent-core`'s\n * `SessionManager` directory encoding (verified against pi 0.73.1 and 1.5.0).\n */\nexport const encodePiSessionDir = (cwd: string): string => {\n const stripped = cwd.replace(/^[/\\\\]/u, \"\");\n const replaced = stripped.replaceAll(/[/\\\\:]/gu, \"-\");\n return `--${replaced}--`;\n};\n\n/** Absolute host path to the pi session directory for a given cwd. */\nexport const piSessionDirPath = (cwd: string, sessionsDir?: string): string => {\n const base = sessionsDir ?? join(homeDir(), \".pi\", \"agent\", \"sessions\");\n return join(base, encodePiSessionDir(cwd));\n};\n\nconst isPiSessionFilename = (filename: string, id: string): boolean =>\n filename.endsWith(`_${id}.jsonl`);\n\n/**\n * Locate a pi session JSONL on the host by its id, scanning each\n * `--<encoded-cwd>--/` directory under `~/.pi/agent/sessions/`.\n */\nexport const findPiSessionOnHost = async (\n id: string,\n sessionsDir?: string,\n): Promise<HostSessionLookup> => {\n const root = sessionsDir ?? join(homeDir(), \".pi\", \"agent\", \"sessions\");\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return { path: undefined, searchedRoot: root };\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) {\n continue;\n }\n const dirAbs = join(root, entry.name);\n let files;\n try {\n files = await readdir(dirAbs);\n } catch {\n continue;\n }\n const match = files.find((name) => isPiSessionFilename(name, id));\n if (match !== undefined) {\n return { path: join(dirAbs, match), searchedRoot: root };\n }\n }\n return { path: undefined, searchedRoot: root };\n};\n\n/**\n * Rewrite a pi session JSONL string, replacing the `cwd` field on the header\n * `session` entry (the only line in pi's JSONL that carries the working\n * directory) when it matches `fromCwd`. Pure function — no file I/O.\n *\n * Pi loads sessions with `assertSessionCwdExists`; in print/json mode a missing\n * cwd terminates the process. The header rewrite is therefore load-bearing for\n * resume, not cosmetic.\n */\nexport const transferPiSession = (\n jsonl: string,\n fromCwd: string,\n toCwd: string,\n): string => {\n if (jsonl === \"\") {\n return \"\";\n }\n return jsonl\n .split(\"\\n\")\n .map((line) => {\n if (line === \"\") {\n return line;\n }\n try {\n const entry: unknown = JSON.parse(line);\n if (\n isRecord(entry) &&\n entry.type === \"session\" &&\n typeof entry.cwd === \"string\" &&\n entry.cwd === fromCwd\n ) {\n entry.cwd = toCwd;\n return JSON.stringify(entry);\n }\n return line;\n } catch {\n return line;\n }\n })\n .join(\"\\n\");\n};\n\n/** A parsed JSON value that is an object (or array), so its fields can be read. */\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\n// ---------------------------------------------------------------------------\n// Copilot session paths and transfer\n// ---------------------------------------------------------------------------\n\n/**\n * Copilot keeps each session in `~/.copilot/session-state/<id>/`, keyed by id\n * alone. Its `events.jsonl` is the whole conversation: `copilot --resume=<id>`\n * replays it with no other file present, not even the `session-store.db`\n * index beside it (verified with Copilot CLI 1.0.105).\n */\nexport const copilotSessionPath = (sessionsDir: string, id: string): string =>\n posix.join(sessionsDir, id, \"events.jsonl\");\n\n/** The host's default Copilot `session-state` directory. */\nexport const copilotHostSessionsDir = (): string =>\n join(homeDir(), \".copilot\", \"session-state\");\n\n/** Rewrite one event's `data.context.cwd` / `gitRoot`; the line itself when untouched. */\nconst rewriteCopilotEvent = (\n line: string,\n fromCwd: string,\n toCwd: string,\n): string => {\n let entry: unknown;\n try {\n entry = JSON.parse(line);\n } catch {\n return line;\n }\n const data = isRecord(entry) ? entry[\"data\"] : undefined;\n const context = isRecord(data) ? data[\"context\"] : undefined;\n if (!isRecord(context)) {\n return line;\n }\n const keys = [\"cwd\", \"gitRoot\"].filter((key) => context[key] === fromCwd);\n for (const key of keys) {\n context[key] = toCwd;\n }\n return keys.length > 0 ? JSON.stringify(entry) : line;\n};\n\n/**\n * Rewrite a Copilot `events.jsonl` string, replacing the structured\n * `data.context.cwd` / `data.context.gitRoot` fields that match `fromCwd` with\n * `toCwd`. Free text (the system prompt names the cwd too) is left alone, and\n * a torn line is kept verbatim. Pure function — no file I/O.\n */\nexport const transferCopilotSession = (\n jsonl: string,\n fromCwd: string,\n toCwd: string,\n): string =>\n jsonl\n .split(\"\\n\")\n .map((line) =>\n line === \"\" ? line : rewriteCopilotEvent(line, fromCwd, toCwd),\n )\n .join(\"\\n\");\n\n// ---------------------------------------------------------------------------\n// Cursor session paths\n// ---------------------------------------------------------------------------\n\n/**\n * Cursor keeps each chat in `~/.cursor/chats/<md5 of the cwd>/<chat id>/`.\n * Its `store.db` (SQLite) is the whole conversation: `agent --resume <id>`\n * replays it with no other file present, and rebuilds `meta.json` itself\n * (verified with Cursor Agent CLI 2026.10.22).\n */\nexport const cursorChatDirName = (cwd: string): string =>\n createHash(\"md5\").update(cwd).digest(\"hex\");\n\n/** The host's default Cursor `chats` directory. */\nexport const cursorHostChatsDir = (): string =>\n join(homeDir(), \".cursor\", \"chats\");\n\n// ---------------------------------------------------------------------------\n// OpenCode session paths\n// ---------------------------------------------------------------------------\n\n/**\n * OpenCode keeps sessions in its SQLite database (`opencode.db`), so there is\n * no per-session file to copy. Sandcastle moves the session as the JSON of\n * `opencode export <id>` instead, and keeps it on the host here, where\n * `opencode import <file>` also reads it.\n */\nexport const opencodeHostSessionsDir = (): string =>\n join(homeDir(), \".local\", \"share\", \"opencode\", \"sandcastle-sessions\");\n\n/** OpenCode's own database on the host, where a no-sandbox run keeps its sessions. */\nexport const opencodeHostDatabase = (): string =>\n join(homeDir(), \".local\", \"share\", \"opencode\", \"opencode.db\");\n\n// ---------------------------------------------------------------------------\n// Session storage for agents that keep each session in one file\n// ---------------------------------------------------------------------------\n\n/**\n * Where an agent keeps a session that lives in one file whose path follows\n * from the cwd and the session id, on the host and in the sandbox.\n */\nexport interface SessionFileLayout {\n /** The host directory searched by id; named in not-found errors. */\n readonly hostRoot: string;\n /** Absolute host path of the session file for a cwd. */\n readonly hostPath: (cwd: string, id: string) => string;\n /**\n * Where the session file may be on the host, found by id alone (the\n * no-sandbox precheck, where the cwd the agent used is unknown). Given the\n * names of `hostRoot`'s subdirectories, for agents that key them by cwd.\n */\n readonly hostPathsById: (\n id: string,\n hostRootSubdirs: readonly string[],\n ) => readonly string[];\n /**\n * Sandbox path of the session file for a cwd (POSIX separators), under the\n * sandbox's own home or temp dir.\n */\n readonly sandboxPath: (cwd: string, id: string, dirs: SandboxDirs) => string;\n /**\n * For an agent whose sessions live in its own database: the sandbox command\n * that writes session `id` to `sandboxPath` before capture, run in the\n * sandbox repo.\n */\n readonly sandboxExport?: (id: string, sandboxPath: string) => string;\n /** The sandbox command that loads `sandboxPath` back after resume, run in the sandbox repo. */\n readonly sandboxImport?: (id: string, sandboxPath: string) => string;\n /** Rewrite the session's own record of its cwd when it moves. Omit to copy verbatim. */\n readonly rewrite?: (\n content: string,\n fromCwd: string,\n toCwd: string,\n ) => string;\n}\n\ninterface SessionTransfer {\n readonly hostCwd: string;\n readonly sandboxCwd: string;\n readonly sessionId: string;\n readonly handle: BindMountSandboxHandle;\n}\n\n/** The error for a sandbox command that exited non-zero, with its stderr. */\nconst sandboxCommandError = (command: string, result: ExecResult): Error =>\n new Error(\n `\\`${command}\\` exited with code ${result.exitCode}: ${result.stderr.trim()}`,\n );\n\n/** Copy a session file out of the sandbox to the host, then rewrite it. */\nconst captureSessionFile =\n (layout: SessionFileLayout) =>\n async (transfer: SessionTransfer): Promise<void> => {\n const { hostCwd, sandboxCwd, sessionId, handle } = transfer;\n const source = layout.sandboxPath(\n sandboxCwd,\n sessionId,\n sandboxDirsOf(handle),\n );\n if (layout.sandboxExport !== undefined) {\n const command = layout.sandboxExport(sessionId, source);\n const result = await handle.exec(command, { cwd: sandboxCwd });\n if (result.exitCode !== 0) {\n throw sandboxCommandError(command, result);\n }\n }\n const target = layout.hostPath(hostCwd, sessionId);\n await mkdir(dirname(target), { recursive: true });\n await handle.copyFileOut(source, target);\n if (layout.rewrite !== undefined) {\n const content = await readFile(target, \"utf8\");\n await writeFile(target, layout.rewrite(content, sandboxCwd, hostCwd));\n }\n };\n\n/** Copy a session file from the host into the sandbox, rewritten on the way. */\nconst resumeSessionFile =\n (layout: SessionFileLayout) =>\n async (transfer: SessionTransfer): Promise<void> => {\n const { hostCwd, sandboxCwd, sessionId, handle } = transfer;\n const source = layout.hostPath(hostCwd, sessionId);\n const target = layout.sandboxPath(\n sandboxCwd,\n sessionId,\n sandboxDirsOf(handle),\n );\n const dir = JSON.stringify(posix.dirname(target));\n if (layout.rewrite === undefined) {\n await handle.exec(`mkdir -p ${dir}`);\n await handle.copyFileIn(source, target);\n if (layout.sandboxImport !== undefined) {\n const command = layout.sandboxImport(sessionId, target);\n const result = await handle.exec(command, { cwd: sandboxCwd });\n if (result.exitCode !== 0) {\n throw sandboxCommandError(command, result);\n }\n }\n return;\n }\n const content = await readFile(source, \"utf8\");\n const result = await handle.exec(\n `mkdir -p ${dir} && cat > ${JSON.stringify(target)}`,\n { stdin: layout.rewrite(content, hostCwd, sandboxCwd) },\n );\n if (result.exitCode !== 0) {\n throw new Error(`writing ${target} failed: ${result.stderr}`);\n }\n };\n\n/**\n * The session storage operations for a {@link SessionFileLayout}: the file is\n * copied between host and sandbox as is, and rewritten only when the layout\n * says how. Binary files (an SQLite store) survive when `rewrite` is omitted.\n */\nexport const makeSessionFileStorage = (layout: SessionFileLayout) => ({\n hostSessionFilePath: (cwd: string, id: string): string =>\n layout.hostPath(cwd, id),\n existsOnHost: async (cwd: string, id: string): Promise<boolean> =>\n pathExists(layout.hostPath(cwd, id)),\n readHostSession: async (\n cwd: string,\n id: string,\n ): Promise<string | undefined> => {\n const path = layout.hostPath(cwd, id);\n return (await pathExists(path)) ? readFile(path, \"utf8\") : undefined;\n },\n findByIdOnHost: async (id: string): Promise<HostSessionLookup> => {\n let subdirs: string[] = [];\n try {\n subdirs = await readdir(layout.hostRoot);\n } catch {\n // No store yet: only paths outside hostRoot can match.\n }\n return {\n path: await firstExistingPath(layout.hostPathsById(id, subdirs)),\n searchedRoot: layout.hostRoot,\n };\n },\n captureToHost: captureSessionFile(layout),\n resumeIntoSandbox: resumeSessionFile(layout),\n});\n","import { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { dirname, join, posix, relative } from \"node:path\";\nimport { tmpdir } from \"node:os\";\nimport {\n claudeHostSessionPath,\n claudeSandboxSessionPath,\n claudeSubagentsDirOnHost,\n copilotHostSessionsDir,\n copilotSessionPath,\n cursorChatDirName,\n cursorHostChatsDir,\n encodePiSessionDir,\n findClaudeSessionOnHost,\n findCodexSessionOnHost,\n findPiSessionOnHost,\n homeDir,\n listClaudeSubagentSessionsInSandbox,\n locateSandboxSessionFile,\n makeSessionFileStorage,\n opencodeHostDatabase,\n opencodeHostSessionsDir,\n pathExists,\n piSessionDirPath,\n requireHostSessionPath,\n sandboxDirsOf,\n transferClaudeSession,\n transferCodexSession,\n transferCopilotSession,\n transferPiSession,\n} from \"./SessionStore.js\";\nimport type { HostSessionLookup } from \"./SessionStore.js\";\nimport type { BindMountSandboxHandle } from \"./SandboxProvider.js\";\nimport type { ContextWindow } from \"./ContextWindow.js\";\nimport { ForkNotSupportedError } from \"./errors.js\";\n\nexport type ParsedStreamEvent =\n | { type: \"text\"; text: string }\n /**\n * The input side of ONE model call (cache included), emitted once per call.\n * The Orchestrator keeps the last one per iteration; see ContextWindow.\n */\n | { type: \"context_window\"; contextWindow: ContextWindow }\n | { type: \"result\"; result: string }\n | { type: \"tool_call\"; name: string; args: string }\n | { type: \"session_id\"; sessionId: string }\n | { type: \"usage\"; usage: IterationUsage }\n /**\n * The agent reported a failure in its own stream (an API rejection, a\n * failed turn). Some agents exit 0 after one, so the Orchestrator fails the\n * run on it whatever the exit code.\n */\n | { type: \"error\"; message: string };\n\n/** @internal Single-quote a string for safe use in a POSIX shell command. */\nexport const shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/**\n * Build a `context_window` event from ONE model call's input-side buckets\n * (uncached input plus each cache bucket the agent reports separately).\n * Returns nothing when the input is missing or the call reports zero tokens,\n * so a malformed or failed call cannot replace a real figure.\n */\nconst contextWindowEvent = (\n input: unknown,\n ...cacheBuckets: unknown[]\n): ParsedStreamEvent[] => {\n if (typeof input !== \"number\") return [];\n let tokens = input;\n for (const n of cacheBuckets) if (typeof n === \"number\") tokens += n;\n return tokens > 0\n ? [{ type: \"context_window\", contextWindow: { tokens } }]\n : [];\n};\n\n/**\n * Claude Code: each `assistant` line carries its API call's `message.usage`\n * (lines split from one call repeat it), so the last one is the last call.\n * Subagent lines (`parent_tool_use_id` set) belong to another context and are\n * skipped. The `result` line's usage is summed over every call of the turn\n * and is deliberately never used.\n */\nconst parseClaudeContextWindow = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n if (obj.type !== \"assistant\" || obj.parent_tool_use_id) return [];\n const u = obj.message?.usage;\n return contextWindowEvent(\n u?.input_tokens,\n u?.cache_creation_input_tokens,\n u?.cache_read_input_tokens,\n );\n } catch {\n return [];\n }\n};\n\n/** Maps allowlisted tool names to the input field containing the display arg */\nconst TOOL_ARG_FIELDS: Record<string, string> = {\n Bash: \"command\",\n WebSearch: \"query\",\n WebFetch: \"url\",\n Agent: \"description\",\n Skill: \"skill\",\n};\n\n/** `value.message` when `value` is an object whose `message` is a string. */\nconst messageField = (value: unknown): string | undefined =>\n typeof value === \"object\" &&\n value !== null &&\n \"message\" in value &&\n typeof value.message === \"string\"\n ? value.message\n : undefined;\n\n/**\n * Extract an error message from a parsed JSON error event.\n * Handles { error: \"string\" }, { error: { message: \"string\" } },\n * { error: { data: { message: \"string\" } } }, and { message: \"string\" }.\n */\nconst extractErrorMessage = (obj: unknown): string | undefined => {\n if (typeof obj !== \"object\" || obj === null) {\n return undefined;\n }\n const err = \"error\" in obj ? obj.error : undefined;\n if (typeof err === \"string\") {\n return err;\n }\n if (typeof err === \"object\" && err !== null) {\n const nested =\n messageField(err) ?? (\"data\" in err ? messageField(err.data) : undefined);\n if (nested !== undefined) {\n return nested;\n }\n }\n return messageField(obj);\n};\n\n/** A content block of a Claude `assistant` stream-json event. */\ninterface ClaudeContentBlock {\n type: string;\n text?: string;\n name?: string;\n input?: Record<string, unknown>;\n}\n\n/** The tool_call event for an allowlisted tool_use block, if it is one. */\nconst toolCallFromClaudeBlock = (\n block: ClaudeContentBlock,\n): ParsedStreamEvent | undefined => {\n if (\n block.type !== \"tool_use\" ||\n typeof block.name !== \"string\" ||\n block.input === undefined\n ) {\n return undefined;\n }\n const argField = TOOL_ARG_FIELDS[block.name];\n if (argField === undefined) {\n return undefined; // not allowlisted\n }\n const argValue = block.input[argField];\n if (typeof argValue !== \"string\") {\n return undefined; // missing/wrong arg field\n }\n return { type: \"tool_call\", name: block.name, args: argValue };\n};\n\n/** Joins each run of consecutive text events into one text event. */\nconst mergeAdjacentText = (\n events: readonly ParsedStreamEvent[],\n): ParsedStreamEvent[] => {\n const merged: ParsedStreamEvent[] = [];\n for (const event of events) {\n const last = merged.at(-1);\n if (event.type === \"text\" && last?.type === \"text\") {\n merged[merged.length - 1] = {\n type: \"text\",\n text: last.text + event.text,\n };\n } else {\n merged.push(event);\n }\n }\n return merged;\n};\n\n/**\n * Turns a Claude assistant message's content blocks into events, in order:\n * consecutive text blocks are joined into one text event, and allowlisted\n * tool_use blocks become tool_call events. Other blocks are dropped.\n */\nconst parseClaudeAssistantContent = (\n content: readonly ClaudeContentBlock[],\n): ParsedStreamEvent[] =>\n mergeAdjacentText(\n content.flatMap((block): ParsedStreamEvent[] => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return [{ type: \"text\", text: block.text }];\n }\n const toolCall = toolCallFromClaudeBlock(block);\n return toolCall === undefined ? [] : [toolCall];\n }),\n );\n\nconst parseStreamJsonLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n if (obj.type === \"assistant\" && Array.isArray(obj.message?.content)) {\n return parseClaudeAssistantContent(\n obj.message.content as ClaudeContentBlock[],\n );\n }\n if (obj.type === \"result\" && typeof obj.result === \"string\") {\n if (obj.is_error === true) {\n return [{ type: \"error\", message: obj.result }];\n }\n return [{ type: \"result\", result: obj.result }];\n }\n if (\n obj.type === \"system\" &&\n obj.subtype === \"init\" &&\n typeof obj.session_id === \"string\"\n ) {\n return [{ type: \"session_id\", sessionId: obj.session_id }];\n }\n } catch {\n // Not valid JSON — skip\n }\n return [];\n};\n\n/**\n * Cursor Agent CLI print mode passes the prompt as a positional argv argument; stdin is not\n * documented for delivering the prompt. Linux enforces a per-argument limit (~128 KiB, ARG_MAX\n * stack). Stay slightly under so users get a clear error instead of spawn E2BIG.\n */\nconst CURSOR_PRINT_PROMPT_MAX_BYTES = 120 * 1024;\n\nconst assertCursorPrintPromptFitsArgv = (prompt: string): void => {\n const n = Buffer.byteLength(prompt, \"utf8\");\n if (n > CURSOR_PRINT_PROMPT_MAX_BYTES) {\n throw new Error(\n `Cursor print-mode prompt is ${n} bytes (max ${CURSOR_PRINT_PROMPT_MAX_BYTES} bytes). The Cursor CLI accepts the prompt only as a command-line argument; shorten the prompt or split the work. Other Sandcastle providers use stdin for large prompts.`,\n );\n }\n};\n\n/** Reads `<kind>ToolCall.args[field]` when it is a string. */\nconst cursorToolCallArg = (\n toolCall: unknown,\n field: string,\n): string | undefined => {\n if (typeof toolCall !== \"object\" || toolCall === null) {\n return undefined;\n }\n const args: unknown = Reflect.get(toolCall, \"args\");\n if (typeof args !== \"object\" || args === null) {\n return undefined;\n }\n const value: unknown = Reflect.get(args, field);\n return typeof value === \"string\" ? value : undefined;\n};\n\n/**\n * Cursor's typed tool calls: `<kind>ToolCall` → display name and the arg it\n * shows. Newer Cursor CLIs (verified 2026-10-31, composer-2) run shell\n * commands as `shellToolCall` and write files as `editToolCall`.\n */\nconst CURSOR_TYPED_TOOL_CALLS: readonly {\n readonly kind: string;\n readonly name: string;\n readonly field: string;\n}[] = [\n { kind: \"readToolCall\", name: \"Read\", field: \"path\" },\n { kind: \"writeToolCall\", name: \"Write\", field: \"path\" },\n { kind: \"editToolCall\", name: \"Edit\", field: \"path\" },\n { kind: \"shellToolCall\", name: \"Bash\", field: \"command\" },\n];\n\n/** Cursor's older `function` tool call: `{ name, arguments: \"<json>\" }`. */\nconst parseCursorFunctionToolCall = (fn: unknown): ParsedStreamEvent[] => {\n if (typeof fn !== \"object\" || fn === null) {\n return [];\n }\n const name: unknown = Reflect.get(fn, \"name\");\n if (typeof name !== \"string\") {\n return [];\n }\n const rawArguments: unknown = Reflect.get(fn, \"arguments\");\n const rawArgs = typeof rawArguments === \"string\" ? rawArguments : \"\";\n if (rawArgs === \"\") {\n return [{ type: \"tool_call\", name, args: \"\" }];\n }\n try {\n const parsedArgs = JSON.parse(rawArgs) as unknown;\n const command: unknown =\n typeof parsedArgs === \"object\" && parsedArgs !== null\n ? Reflect.get(parsedArgs, \"command\")\n : undefined;\n if (typeof command === \"string\") {\n return [{ type: \"tool_call\", name: \"Bash\", args: command }];\n }\n } catch {\n // Use raw arguments string for display.\n }\n return [{ type: \"tool_call\", name, args: rawArgs }];\n};\n\n/** Cursor stream-json emits top-level `tool_call` events (see Cursor CLI output-format docs). */\nconst parseCursorToolCallStarted = (\n obj: Record<string, unknown>,\n): ParsedStreamEvent[] => {\n if (obj.type !== \"tool_call\" || obj.subtype !== \"started\") {\n return [];\n }\n const toolCall = obj.tool_call;\n if (typeof toolCall !== \"object\" || toolCall === null) {\n return [];\n }\n for (const { kind, name, field } of CURSOR_TYPED_TOOL_CALLS) {\n const args = cursorToolCallArg(Reflect.get(toolCall, kind), field);\n if (args !== undefined) {\n return [{ type: \"tool_call\", name, args }];\n }\n }\n return parseCursorFunctionToolCall(Reflect.get(toolCall, \"function\"));\n};\n\n/**\n * Cursor emits no `context_window` events on purpose. Its only token figures\n * are on the `result` line, summed over every model call of the turn (verified\n * 2026-10-31: `cacheReadTokens` grew ~5.5x with five calls over the same\n * content). With no per-call figure, no line beats a wrong one.\n */\nconst parseCursorStreamLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n let obj: Record<string, unknown>;\n try {\n obj = JSON.parse(line) as Record<string, unknown>;\n } catch {\n // Not valid JSON — skip\n return [];\n }\n if (obj.type === \"tool_call\") {\n return parseCursorToolCallStarted(obj);\n }\n return parseStreamJsonLine(line);\n};\n\n/** Options passed to buildPrintCommand and buildInteractiveArgs. */\nexport interface AgentCommandOptions {\n readonly prompt: string;\n readonly dangerouslySkipPermissions: boolean;\n /** When set, the agent should resume the given session ID instead of starting fresh. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, the agent should fork the session\n * instead of mutating it — Claude's `--fork-session`, pi's `--fork`, Codex's\n * `codex exec fork`. The parent session JSONL is left intact and the agent\n * writes a new session under a fresh id.\n */\n readonly forkSession?: boolean;\n}\n\n/** Return type of buildPrintCommand — command string plus optional stdin content.\n * When `stdin` is set, the sandbox pipes it to the child process's stdin\n * instead of inlining the prompt in argv, avoiding the Linux 128 KB per-arg limit. */\nexport interface PrintCommand {\n readonly command: string;\n readonly stdin?: string;\n}\n\n/** Per-iteration token usage snapshot extracted from the agent session. */\nexport interface IterationUsage {\n readonly inputTokens: number;\n readonly cacheCreationInputTokens: number;\n readonly cacheReadInputTokens: number;\n readonly outputTokens: number;\n}\n\nexport interface AgentSessionStorage {\n /** Transfer a session JSONL from the sandbox into the host store. */\n captureToHost(args: {\n hostCwd: string;\n sandboxCwd: string;\n sessionId: string;\n handle: BindMountSandboxHandle;\n }): Promise<void>;\n /** Transfer a session JSONL from the host store into the sandbox. */\n resumeIntoSandbox(args: {\n hostCwd: string;\n sandboxCwd: string;\n sessionId: string;\n handle: BindMountSandboxHandle;\n }): Promise<void>;\n /** Read a captured session JSONL from the host store. Returns undefined when absent. */\n readHostSession(cwd: string, sessionId: string): Promise<string | undefined>;\n /** Whether a session with the given id exists in the host store keyed on cwd. */\n existsOnHost(cwd: string, sessionId: string): Promise<boolean>;\n /** Absolute host path where a session would be stored (for not-found error messages). */\n hostSessionFilePath(cwd: string, sessionId: string): string | undefined;\n /**\n * Locate a session on the host by its unique id, independent of cwd encoding.\n * Used by the no-sandbox resume precheck, where the agent runs on the host and\n * writes the session in place under a cwd-derived directory Sandcastle cannot\n * reliably reconstruct. Returns the located path (or `undefined`) plus the\n * directory that was searched (for not-found errors).\n */\n findByIdOnHost(sessionId: string): Promise<HostSessionLookup>;\n /**\n * `false` when the agent's CLI can resume a session but has no native fork:\n * `.fork()` then throws `ForkNotSupportedError` before any sandbox starts.\n * Omitted means the agent forks.\n */\n readonly canFork?: boolean;\n}\n\nexport interface AgentProvider {\n readonly name: string;\n /** Environment variables injected by this agent provider. Merged at launch time with env resolver and sandbox provider env. */\n readonly env: Record<string, string>;\n /** When true, session capture is enabled for this provider. Default: true for Claude Code, false for others. */\n readonly captureSessions: boolean;\n /** Provider-owned storage and transfer behavior for resumable agent sessions. */\n readonly sessionStorage?: AgentSessionStorage;\n buildPrintCommand(options: AgentCommandOptions): PrintCommand;\n buildInteractiveArgs?(options: AgentCommandOptions): string[];\n parseStreamLine(line: string): ParsedStreamEvent[];\n /** Parse token usage from the captured session JSONL content. Only implemented by Claude Code. */\n parseSessionUsage?(content: string): IterationUsage | undefined;\n /**\n * Parse the last model call's context window from the captured session\n * JSONL. For agents whose stream has no per-call figure (codex). Overrides\n * the stream's `context_window` events when it returns a value.\n */\n parseSessionContextWindow?(content: string): ContextWindow | undefined;\n}\n\nexport const DEFAULT_MODEL = \"claude-opus-4-8\";\n\n// ---------------------------------------------------------------------------\n// Session storage helpers — file I/O lives here so callers (Orchestrator,\n// resumePrecheck) work against the high-level AgentSessionStorage interface\n// and tests can exercise transferClaudeSession / transferCodexSession as\n// pure string functions.\n// ---------------------------------------------------------------------------\n\nconst readSandboxFile = async (\n handle: Pick<BindMountSandboxHandle, \"copyFileOut\">,\n sandboxPath: string,\n tag: string,\n): Promise<string> => {\n const tmpPath = join(\n tmpdir(),\n `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`,\n );\n await handle.copyFileOut(sandboxPath, tmpPath);\n try {\n return await readFile(tmpPath, \"utf8\");\n } finally {\n await rm(tmpPath, { force: true }).catch(() => {});\n }\n};\n\n/** A file to write into the sandbox; `tag` names its host temp file. */\ninterface SandboxFileWrite {\n readonly sandboxPath: string;\n readonly content: string;\n readonly tag: string;\n}\n\nconst writeSandboxFile = async (\n handle: Pick<BindMountSandboxHandle, \"copyFileIn\" | \"exec\">,\n { sandboxPath, content, tag }: SandboxFileWrite,\n): Promise<void> => {\n const tmpPath = join(\n tmpdir(),\n `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`,\n );\n await writeFile(tmpPath, content);\n try {\n await handle.exec(`mkdir -p ${JSON.stringify(posix.dirname(sandboxPath))}`);\n await handle.copyFileIn(tmpPath, sandboxPath);\n } finally {\n await rm(tmpPath, { force: true }).catch(() => {});\n }\n};\n\n/**\n * Read a Claude JSONL out of the sandbox, rewrite its `cwd` fields from\n * `fromCwd` → `toCwd`, and write the result to `destPath` on the host. Used\n * by `captureToHost` for both the main session file and each subagent /\n * workflow transcript — the read→rewrite→ensure-dir→write sequence is\n * identical, only the source/dest paths differ.\n */\nconst copyClaudeSessionFile = async ({\n handle,\n sourcePath,\n fromCwd,\n toCwd,\n destPath,\n tag,\n}: {\n handle: Pick<BindMountSandboxHandle, \"copyFileOut\">;\n sourcePath: string;\n fromCwd: string;\n toCwd: string;\n destPath: string;\n tag: string;\n}): Promise<void> => {\n const jsonl = await readSandboxFile(handle, sourcePath, tag);\n const rewritten = transferClaudeSession(jsonl, fromCwd, toCwd);\n await mkdir(dirname(destPath), { recursive: true });\n await writeFile(destPath, rewritten);\n};\n\n/** A Claude session to copy out of the sandbox, and where it goes. */\ninterface ClaudeSessionCapture {\n handle: BindMountSandboxHandle;\n hostCwd: string;\n sandboxCwd: string;\n sessionId: string;\n sandboxProjectsDir: string;\n hostProjectsDir: string | undefined;\n}\n\n/**\n * Subagent / workflow transcripts: best-effort. A missing `subagents/`\n * dir is the normal case (no Agent-tool / Workflow usage this run);\n * an individual subagent failing to copy must not abort siblings or\n * the (already-successful) main capture.\n */\nconst captureClaudeSubagents = async ({\n handle,\n hostCwd,\n sandboxCwd,\n sessionId,\n sandboxProjectsDir,\n hostProjectsDir,\n}: ClaudeSessionCapture): Promise<void> => {\n const subagentSandboxPaths = await listClaudeSubagentSessionsInSandbox(\n sandboxCwd,\n sessionId,\n handle,\n sandboxProjectsDir,\n );\n const hostSubagentsDir = claudeSubagentsDirOnHost(\n hostCwd,\n sessionId,\n hostProjectsDir,\n );\n for (const sandboxSubagentPath of subagentSandboxPaths) {\n try {\n await copyClaudeSessionFile({\n handle,\n sourcePath: sandboxSubagentPath,\n fromCwd: sandboxCwd,\n toCwd: hostCwd,\n destPath: join(hostSubagentsDir, posix.basename(sandboxSubagentPath)),\n tag: \"claude-sub\",\n });\n } catch (error) {\n console.error(\n `sandcastle: failed to capture Claude subagent transcript ${sandboxSubagentPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n};\n\n/** What `resumeIntoSandbox` is given. */\ntype SessionTransfer = Parameters<AgentSessionStorage[\"resumeIntoSandbox\"]>[0];\n\n/** Where an agent keeps its sessions, on the host and in the sandbox. */\ninterface SessionDirs {\n readonly hostSessionsDir: string | undefined;\n readonly sandboxSessionsDir: string;\n}\n\nconst resumeClaudeIntoSandbox = async (\n { hostCwd, sandboxCwd, sessionId, handle }: SessionTransfer,\n dirs: {\n readonly hostProjectsDir: string | undefined;\n readonly sandboxProjectsDir: string;\n },\n): Promise<void> => {\n const hostPath = claudeHostSessionPath(\n hostCwd,\n sessionId,\n dirs.hostProjectsDir,\n );\n const jsonl = await readFile(hostPath, \"utf8\");\n await writeSandboxFile(handle, {\n sandboxPath: claudeSandboxSessionPath(\n sandboxCwd,\n sessionId,\n dirs.sandboxProjectsDir,\n ),\n content: transferClaudeSession(jsonl, hostCwd, sandboxCwd),\n tag: \"claude-res\",\n });\n};\n\n/**\n * Copies a Claude session out of the sandbox: the main session file, then\n * its subagent / workflow transcripts.\n */\nconst captureClaudeSession = (capture: ClaudeSessionCapture): Promise<void> =>\n // Main session: failure is fatal — the user expects their session.\n copyClaudeSessionFile({\n handle: capture.handle,\n sourcePath: claudeSandboxSessionPath(\n capture.sandboxCwd,\n capture.sessionId,\n capture.sandboxProjectsDir,\n ),\n fromCwd: capture.sandboxCwd,\n toCwd: capture.hostCwd,\n destPath: claudeHostSessionPath(\n capture.hostCwd,\n capture.sessionId,\n capture.hostProjectsDir,\n ),\n tag: \"claude-cap\",\n }).then(() => captureClaudeSubagents(capture));\n\nconst makeClaudeSessionStorage = (\n options?: ClaudeCodeOptions,\n): AgentSessionStorage => {\n const hostProjectsDir = options?.sessionStorage?.hostProjectsDir;\n const sandboxProjectsDirOf = (handle: BindMountSandboxHandle): string =>\n options?.sessionStorage?.sandboxProjectsDir ??\n posix.join(sandboxDirsOf(handle).home, \".claude\", \"projects\");\n\n return {\n hostSessionFilePath: (cwd, id) =>\n claudeHostSessionPath(cwd, id, hostProjectsDir),\n existsOnHost: (cwd, id) =>\n pathExists(claudeHostSessionPath(cwd, id, hostProjectsDir)),\n readHostSession: async (cwd, id) => {\n const path = claudeHostSessionPath(cwd, id, hostProjectsDir);\n if (!(await pathExists(path))) return undefined;\n return readFile(path, \"utf8\");\n },\n captureToHost: ({ hostCwd, sandboxCwd, sessionId, handle }) =>\n captureClaudeSession({\n handle,\n hostCwd,\n sandboxCwd,\n sessionId,\n sandboxProjectsDir: sandboxProjectsDirOf(handle),\n hostProjectsDir,\n }),\n resumeIntoSandbox: (transfer) =>\n resumeClaudeIntoSandbox(transfer, {\n hostProjectsDir,\n sandboxProjectsDir: sandboxProjectsDirOf(transfer.handle),\n }),\n findByIdOnHost: (id) => findClaudeSessionOnHost(id, hostProjectsDir),\n };\n};\n\nconst resumeCodexIntoSandbox = async (\n { hostCwd, sandboxCwd, sessionId, handle }: SessionTransfer,\n dirs: SessionDirs,\n): Promise<void> => {\n const found = await findCodexSessionOnHost(sessionId, dirs.hostSessionsDir);\n const path = requireHostSessionPath(found, sessionId);\n const jsonl = await readFile(path, \"utf8\");\n await writeSandboxFile(handle, {\n sandboxPath: posix.join(\n dirs.sandboxSessionsDir,\n ...relative(found.searchedRoot, path).split(/[\\\\/]/u),\n ),\n content: transferCodexSession(jsonl, hostCwd, sandboxCwd),\n tag: \"codex-res\",\n });\n};\n\n/**\n * Codex sessions live at YYYY/MM/DD/rollout-*-<id>.jsonl — the path is not\n * derivable from (cwd, id) alone, so we cache the path written by\n * captureToHost for hostSessionFilePath to surface on the IterationResult.\n */\nconst makeCodexSessionStorage = (\n options?: CodexOptions,\n): AgentSessionStorage => {\n const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;\n const sandboxSessionsDirOf = (handle: BindMountSandboxHandle): string =>\n options?.sessionStorage?.sandboxSessionsDir ??\n posix.join(sandboxDirsOf(handle).home, \".codex\", \"sessions\");\n const capturedPaths = new Map<string, string>();\n\n return {\n hostSessionFilePath: (_cwd, id) => capturedPaths.get(id),\n existsOnHost: async (_cwd, id) => {\n const found = await findCodexSessionOnHost(id, hostSessionsDir);\n return found.path !== undefined;\n },\n readHostSession: async (_cwd, id) => {\n const found = await findCodexSessionOnHost(id, hostSessionsDir);\n if (!found.path) return undefined;\n return readFile(found.path, \"utf8\");\n },\n captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {\n const located = await locateSandboxSessionFile(\n handle,\n sandboxSessionsDirOf(handle),\n `rollout-*-${sessionId}.jsonl`,\n );\n const jsonl = await readSandboxFile(handle, located.path, \"codex-cap\");\n const rewritten = transferCodexSession(jsonl, sandboxCwd, hostCwd);\n const root = hostSessionsDir ?? join(homeDir(), \".codex\", \"sessions\");\n const target = join(root, located.relativePath);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, rewritten);\n capturedPaths.set(sessionId, target);\n },\n resumeIntoSandbox: (transfer) =>\n resumeCodexIntoSandbox(transfer, {\n hostSessionsDir,\n sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle),\n }),\n findByIdOnHost: (id) => findCodexSessionOnHost(id, hostSessionsDir),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Pi agent provider\n// ---------------------------------------------------------------------------\n\n/**\n * Where a captured pi session lands on the host. Pi resolves `--session <id>`\n * against the *current project's* encoded directory first; a transferred file\n * in any other directory hits the \"fork session?\" prompt, which hangs in\n * print/json mode. So we land the file in `--<enc-host-cwd>--/<filename>`, not\n * the sandbox's encoded dir.\n */\nconst piHostCaptureTarget = (\n hostCwd: string,\n sandboxPath: string,\n hostSessionsDir: string | undefined,\n): string =>\n join(piSessionDirPath(hostCwd, hostSessionsDir), posix.basename(sandboxPath));\n\nconst resumePiIntoSandbox = async (\n { hostCwd, sandboxCwd, sessionId, handle }: SessionTransfer,\n dirs: SessionDirs,\n): Promise<void> => {\n const found = await findPiSessionOnHost(sessionId, dirs.hostSessionsDir);\n const path = requireHostSessionPath(found, sessionId);\n const jsonl = await readFile(path, \"utf8\");\n const filename = posix.basename(path.replaceAll(\"\\\\\", \"/\"));\n await writeSandboxFile(handle, {\n sandboxPath: posix.join(\n dirs.sandboxSessionsDir,\n encodePiSessionDir(sandboxCwd),\n filename,\n ),\n content: transferPiSession(jsonl, hostCwd, sandboxCwd),\n tag: \"pi-res\",\n });\n};\n\n// Pi names its JSONL `<timestamp>_<id>.jsonl`, so the file is not derivable\n// from (cwd, id). captureToHost remembers what it wrote, so the iteration's\n// sessionFilePath is the JSONL itself. Before capture (the resume precheck's\n// not-found message) the best we can name is the directory.\nconst makePiSessionStorage = (options?: PiOptions): AgentSessionStorage => {\n const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;\n const sandboxSessionsDirOf = (handle: BindMountSandboxHandle): string =>\n options?.sessionStorage?.sandboxSessionsDir ??\n posix.join(sandboxDirsOf(handle).home, \".pi\", \"agent\", \"sessions\");\n const capturedPaths = new Map<string, string>();\n return {\n hostSessionFilePath: (cwd, id) =>\n capturedPaths.get(id) ?? piSessionDirPath(cwd, hostSessionsDir),\n existsOnHost: async (_cwd, id) => {\n const found = await findPiSessionOnHost(id, hostSessionsDir);\n return found.path !== undefined;\n },\n readHostSession: async (_cwd, id) => {\n const { path } = await findPiSessionOnHost(id, hostSessionsDir);\n return path === undefined ? undefined : readFile(path, \"utf8\");\n },\n captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {\n const located = await locateSandboxSessionFile(\n handle,\n sandboxSessionsDirOf(handle),\n `*_${sessionId}.jsonl`,\n );\n const jsonl = await readSandboxFile(handle, located.path, \"pi-cap\");\n const rewritten = transferPiSession(jsonl, sandboxCwd, hostCwd);\n const target = piHostCaptureTarget(\n hostCwd,\n located.path,\n hostSessionsDir,\n );\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, rewritten);\n capturedPaths.set(sessionId, target);\n },\n resumeIntoSandbox: (transfer) =>\n resumePiIntoSandbox(transfer, {\n hostSessionsDir,\n sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle),\n }),\n findByIdOnHost: (id) => findPiSessionOnHost(id, hostSessionsDir),\n };\n};\n\n/** A message in pi's `agent_end` event. */\ninterface PiAgentEndMessage {\n role: string;\n content: { type: string; text?: string }[];\n stopReason?: string;\n errorMessage?: string;\n}\n\n/** The last assistant message, or null if there is none. */\nconst lastAssistantMessage = (\n messages: readonly (PiAgentEndMessage | null)[],\n): PiAgentEndMessage | null => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg?.role === \"assistant\") {\n return msg;\n }\n }\n return null;\n};\n\n/**\n * Reads pi's final answer from its `agent_end` messages: the last assistant\n * message's text as a result, or an error if that message stopped on error.\n */\nconst parsePiAgentEnd = (\n messages: readonly (PiAgentEndMessage | null)[],\n): ParsedStreamEvent[] => {\n const msg = lastAssistantMessage(messages);\n if (msg === null) {\n return [];\n }\n // When the model call fails (e.g. an API 400), pi puts the error on\n // the last assistant message and still exits 0.\n if (msg.stopReason === \"error\") {\n return [\n {\n type: \"error\",\n message:\n typeof msg.errorMessage === \"string\" && msg.errorMessage\n ? msg.errorMessage\n : 'pi stopped with stopReason \"error\"',\n },\n ];\n }\n const texts = msg.content.flatMap((block) =>\n block.type === \"text\" && typeof block.text === \"string\" ? [block.text] : [],\n );\n return texts.length > 0 ? [{ type: \"result\", result: texts.join(\"\") }] : [];\n};\n\n/**\n * Map one pi message's `usage` (`input`, `output`, `cacheRead` and\n * `cacheWrite` are separate buckets) to IterationUsage.\n */\nconst parsePiUsage = (u: unknown): IterationUsage | undefined => {\n if (typeof u !== \"object\" || u === null) {\n return undefined;\n }\n const field = (key: string): unknown => Reflect.get(u, key);\n const input = field(\"input\");\n const output = field(\"output\");\n const cacheRead = field(\"cacheRead\");\n const cacheWrite = field(\"cacheWrite\");\n if (\n typeof input !== \"number\" ||\n typeof output !== \"number\" ||\n typeof cacheRead !== \"number\" ||\n typeof cacheWrite !== \"number\"\n ) {\n return undefined;\n }\n return {\n inputTokens: input,\n cacheCreationInputTokens: cacheWrite,\n cacheReadInputTokens: cacheRead,\n outputTokens: output,\n };\n};\n\nconst parsePiStreamLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n // The first line of pi's --mode json stdout stream is a `session` header\n // carrying the UUID; subsequent stream entries (model_change,\n // thinking_level_change, message, ...) do not. Verified against\n // @mariozechner/pi-coding-agent 0.73.1 and @earendil-works/pi-coding-agent 1.5.0.\n if (obj.type === \"session\" && typeof obj.id === \"string\") {\n return [{ type: \"session_id\", sessionId: obj.id }];\n }\n // Each assistant message_end is one model call with its own usage. Not\n // agent_end, whose messages[] repeat every call's usage. The Orchestrator\n // keeps the last event of each kind, so both report the last call.\n if (obj.type === \"message_end\" && obj.message?.role === \"assistant\") {\n const u = obj.message.usage;\n const usage = parsePiUsage(u);\n return [\n ...contextWindowEvent(u?.input, u?.cacheRead, u?.cacheWrite),\n ...(usage ? [{ type: \"usage\" as const, usage }] : []),\n ];\n }\n if (obj.type === \"message_update\" && obj.assistantMessageEvent) {\n const evt = obj.assistantMessageEvent as {\n type: string;\n delta?: string;\n };\n if (evt.type === \"text_delta\" && typeof evt.delta === \"string\") {\n return [{ type: \"text\", text: evt.delta }];\n }\n return [];\n }\n if (obj.type === \"tool_execution_start\") {\n const rawName = obj.toolName;\n if (typeof rawName !== \"string\") return [];\n // Pi's built-in tools are lowercase (`bash`); match the shared allowlist\n // case-insensitively and display its canonical name (`Bash`).\n const toolName = Object.keys(TOOL_ARG_FIELDS).find(\n (name) => name.toLowerCase() === rawName.toLowerCase(),\n );\n if (toolName === undefined) return [];\n const argField = TOOL_ARG_FIELDS[toolName];\n if (argField === undefined) return [];\n const args = obj.args as Record<string, unknown> | undefined;\n if (!args) return [];\n const argValue = args[argField];\n if (typeof argValue !== \"string\") return [];\n return [{ type: \"tool_call\", name: toolName, args: argValue }];\n }\n // Pi emits agent_error / error events on stdout (not stderr) for auth\n // failures, rate limits, and API errors.\n if (obj.type === \"agent_error\" || obj.type === \"error\") {\n const msg = extractErrorMessage(obj);\n return msg ? [{ type: \"error\", message: msg }] : [];\n }\n if (obj.type === \"agent_end\" && Array.isArray(obj.messages)) {\n return parsePiAgentEnd(obj.messages as (PiAgentEndMessage | null)[]);\n }\n } catch {\n // Not valid JSON — skip\n }\n return [];\n};\n\n/** Options for the pi agent provider. */\nexport interface PiOptions {\n /**\n * Reasoning effort level. Maps to the CLI's --thinking flag. When omitted,\n * no flag is passed and pi uses its own default (`medium`), which some\n * models reject: with pi 0.73.1, `anthropic/claude-haiku-5-5` returns a 400.\n * Pass `\"off\"` for those.\n */\n readonly thinking?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override pi session directories for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostSessionsDir?: string;\n readonly sandboxSessionsDir?: string;\n };\n}\n\nexport const pi = (\n model: string,\n options?: PiOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"pi\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makePiSessionStorage(options),\n\n buildPrintCommand({\n prompt,\n resumeSession,\n forkSession,\n }: AgentCommandOptions): PrintCommand {\n const thinkingFlag = options?.thinking\n ? ` --thinking ${options.thinking}`\n : \"\";\n // Pi persists print-mode sessions by default; `--session <id>` resolves an\n // existing session and appends to it in place. Drop the legacy\n // `--no-session` flag so fresh runs also persist and can be resumed later.\n // `--fork <id>` instead copies the session into a new file under a fresh\n // id (reported on the stream's `session` header line), leaving the parent\n // untouched. Pi rejects `--fork` combined with `--session`.\n const sessionFlag = resumeSession\n ? ` --${forkSession ? \"fork\" : \"session\"} ${shellEscape(resumeSession)}`\n : \"\";\n return {\n command: `pi -p --mode json --model ${shellEscape(model)}${thinkingFlag}${sessionFlag}`,\n stdin: prompt,\n };\n },\n\n buildInteractiveArgs({ prompt }: AgentCommandOptions): string[] {\n const args = [\"pi\", \"--model\", model];\n if (prompt) args.push(prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return parsePiStreamLine(line);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Codex agent provider\n// ---------------------------------------------------------------------------\n\n/**\n * Map a Codex `turn.completed` usage object to the Claude-shaped IterationUsage.\n *\n * OpenAI/Codex usage is `{ input_tokens, cached_input_tokens, output_tokens }`,\n * where `input_tokens` is the *total* prompt tokens and `cached_input_tokens` is\n * a subset already included in that total. There is no cache-creation concept.\n * To avoid double-counting cached tokens in the context-window display (which\n * sums input + cacheCreation + cacheRead), the cached portion maps to\n * `cacheReadInputTokens` and the remainder to `inputTokens`.\n */\nconst parseCodexUsage = (usage: unknown): IterationUsage | undefined => {\n if (typeof usage !== \"object\" || usage === null) return undefined;\n const u = usage as Record<string, unknown>;\n if (\n typeof u.input_tokens !== \"number\" ||\n typeof u.cached_input_tokens !== \"number\" ||\n typeof u.output_tokens !== \"number\"\n ) {\n return undefined;\n }\n return {\n inputTokens: u.input_tokens - u.cached_input_tokens,\n cacheCreationInputTokens: 0,\n cacheReadInputTokens: u.cached_input_tokens,\n outputTokens: u.output_tokens,\n };\n};\n\n/**\n * Codex's `exec --json` stream has no per-request usage: `turn.completed`\n * sums every request of the session (#898). The rollout JSONL does: each\n * `token_count` event has `last_token_usage` (one request; its `input_tokens`\n * already includes cached and cache-write tokens) and the model's\n * `model_context_window`. The last one is the last request.\n */\nconst parseCodexSessionContextWindow = (\n content: string,\n): ContextWindow | undefined => {\n const lines = content.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i]!;\n if (!line.startsWith(\"{\")) continue;\n try {\n const obj = JSON.parse(line);\n if (obj.type !== \"event_msg\" || obj.payload?.type !== \"token_count\") {\n continue;\n }\n const { info } = obj.payload;\n const tokens = info?.last_token_usage?.input_tokens;\n if (typeof tokens !== \"number\" || tokens <= 0) continue;\n const limit = info.model_context_window;\n return typeof limit === \"number\" && limit > 0\n ? { tokens, limit }\n : { tokens };\n } catch {\n // Not valid JSON — skip\n }\n }\n return undefined;\n};\n\nconst parseCodexStreamLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n\n if (obj.type === \"thread.started\" && typeof obj.thread_id === \"string\") {\n return [{ type: \"session_id\", sessionId: obj.thread_id }];\n }\n\n // item.completed with agent_message → text + result\n if (\n obj.type === \"item.completed\" &&\n obj.item?.type === \"agent_message\" &&\n typeof obj.item.text === \"string\"\n ) {\n const { text } = obj.item;\n return [\n { type: \"text\", text },\n { type: \"result\", result: text },\n ];\n }\n\n // item.started with command_execution → tool call\n if (\n obj.type === \"item.started\" &&\n obj.item?.type === \"command_execution\" &&\n typeof obj.item.command === \"string\"\n ) {\n return [{ type: \"tool_call\", name: \"Bash\", args: obj.item.command }];\n }\n\n // Codex emits error events on stdout (not stderr) for auth failures,\n // rate limits, and API errors. Capture them as result events so the\n // Orchestrator's stderr-empty fallback can surface them to the user.\n if (obj.type === \"error\") {\n const msg = extractErrorMessage(obj);\n return msg ? [{ type: \"result\", result: msg }] : [];\n }\n\n // turn.failed is codex's terminal failure for the turn.\n if (obj.type === \"turn.failed\") {\n const msg = extractErrorMessage(obj);\n return [{ type: \"error\", message: msg ?? \"codex turn failed\" }];\n }\n\n // turn.completed carries token usage for the turn.\n if (obj.type === \"turn.completed\") {\n const usage = parseCodexUsage(obj.usage);\n return usage ? [{ type: \"usage\", usage }] : [];\n }\n } catch {\n // Not valid JSON — skip\n }\n return [];\n};\n\n/** Options for the codex agent provider. */\nexport interface CodexOptions {\n readonly effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override Codex session directories for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostSessionsDir?: string;\n readonly sandboxSessionsDir?: string;\n };\n /**\n * Maps to Codex's `approvals_reviewer` config key (set via\n * `-c approvals_reviewer=\"<value>\"`). When set to `\"auto_review\"`, the\n * provider swaps the default `--dangerously-bypass-approvals-and-sandbox`\n * for an interactive approval policy (`-a on-request`) and Codex's most\n * permissive sandbox (`-s danger-full-access`) — auto-review needs\n * something to review, and the safety boundary is the reviewer agent\n * rather than the filesystem sandbox.\n */\n readonly approvalsReviewer?: \"user\" | \"auto_review\";\n}\n\n/** The `codex exec` command for a print-mode run. */\nconst buildCodexPrintCommand = (\n model: string,\n options: CodexOptions | undefined,\n { prompt, resumeSession, forkSession }: AgentCommandOptions,\n): PrintCommand => {\n const effortFlag = options?.effort\n ? ` -c ${shellEscape(`model_reasoning_effort=\"${options.effort}\"`)}`\n : \"\";\n // auto_review only fires on interactive approvals, so the bypass flag is\n // dropped in favour of `-a on-request`. `-s danger-full-access` disables\n // Codex's own filesystem sandbox — Sandcastle owns that boundary, and\n // here the reviewer agent owns the per-action approval boundary.\n const approvalsFlags =\n options?.approvalsReviewer === \"auto_review\"\n ? ` -a on-request -s danger-full-access -c ${shellEscape(`approvals_reviewer=\"auto_review\"`)}`\n : \" --dangerously-bypass-approvals-and-sandbox\";\n // Codex distinguishes fork from resume at the verb level — `codex exec\n // fork <id>` leaves the parent rollout intact; `codex exec resume <id>`\n // appends to it. See ADR 0018.\n let base: string;\n if (resumeSession && forkSession) {\n base = `codex exec fork ${shellEscape(resumeSession)}`;\n } else if (resumeSession) {\n base = `codex exec resume ${shellEscape(resumeSession)}`;\n } else {\n base = \"codex exec\";\n }\n const stdinArg = resumeSession ? \" -\" : \"\";\n return {\n command: `${base} --json${approvalsFlags} -m ${shellEscape(model)}${effortFlag}${stdinArg}`,\n stdin: prompt,\n };\n};\n\nexport const codex = (\n model: string,\n options?: CodexOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"codex\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makeCodexSessionStorage(options),\n\n buildPrintCommand(commandOptions: AgentCommandOptions): PrintCommand {\n return buildCodexPrintCommand(model, options, commandOptions);\n },\n\n buildInteractiveArgs({ prompt }: AgentCommandOptions): string[] {\n const args = [\"codex\", \"--model\", model];\n if (prompt) args.push(prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return parseCodexStreamLine(line);\n },\n\n parseSessionContextWindow(content: string): ContextWindow | undefined {\n return parseCodexSessionContextWindow(content);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Cursor agent provider\n// ---------------------------------------------------------------------------\n\n/** Options for the cursor agent provider. */\nexport interface CursorOptions {\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override Cursor `chats` directories for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostChatsDir?: string;\n readonly sandboxChatsDir?: string;\n };\n}\n\n/**\n * A Cursor chat is one SQLite `store.db` under the chat dir of the cwd it ran\n * in, so it moves as a single binary file, unrewritten. The CLI resumes\n * (`--resume <id>`) but has no fork flag, so the provider declares\n * `canFork: false` (ADR 0021).\n */\nconst makeCursorSessionStorage = (\n options?: CursorOptions,\n): AgentSessionStorage => {\n const hostDir = options?.sessionStorage?.hostChatsDir ?? cursorHostChatsDir();\n const sandboxDirOverride = options?.sessionStorage?.sandboxChatsDir;\n return {\n ...makeSessionFileStorage({\n hostRoot: hostDir,\n hostPath: (cwd, id) =>\n join(hostDir, cursorChatDirName(cwd), id, \"store.db\"),\n hostPathsById: (id, chatDirs) =>\n chatDirs.map((chatDir) => join(hostDir, chatDir, id, \"store.db\")),\n sandboxPath: (cwd, id, dirs) =>\n posix.join(\n sandboxDirOverride ?? posix.join(dirs.home, \".cursor\", \"chats\"),\n cursorChatDirName(cwd),\n id,\n \"store.db\",\n ),\n }),\n canFork: false,\n };\n};\n\nexport const cursor = (\n model: string,\n options?: CursorOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"cursor\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makeCursorSessionStorage(options),\n\n buildPrintCommand({\n prompt,\n dangerouslySkipPermissions,\n resumeSession,\n forkSession,\n }: AgentCommandOptions): PrintCommand {\n if (resumeSession !== undefined && forkSession === true) {\n throw new ForkNotSupportedError({\n message:\n \"cursor cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.\",\n agentProvider: \"cursor\",\n });\n }\n assertCursorPrintPromptFitsArgv(prompt);\n const forceFlag = dangerouslySkipPermissions ? \" --force\" : \"\";\n // `--resume` takes an optional value, so the id is bound with `=`.\n const resumeFlag =\n resumeSession === undefined\n ? \"\"\n : ` --resume=${shellEscape(resumeSession)}`;\n return {\n command: `agent --print --output-format stream-json --model ${shellEscape(model)} ${forceFlag}${resumeFlag} ${shellEscape(prompt)}`,\n };\n },\n\n buildInteractiveArgs({\n prompt,\n dangerouslySkipPermissions,\n }: AgentCommandOptions): string[] {\n const args = [\"agent\", \"--model\", model];\n if (dangerouslySkipPermissions) args.push(\"--force\");\n if (prompt) args.push(prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return parseCursorStreamLine(line);\n },\n});\n\n// ---------------------------------------------------------------------------\n// OpenCode agent provider\n// ---------------------------------------------------------------------------\n\n/** Maps OpenCode tool names to the input field containing the friendly display\n * arg. Tools not listed here are still surfaced, falling back to a JSON dump of\n * the whole input. The tool name is surfaced as-is (OpenCode's lowercase names). */\nconst OPENCODE_TOOL_ARG_FIELDS: Record<string, string> = {\n bash: \"command\",\n webfetch: \"url\",\n task: \"description\",\n};\n\nconst parseOpenCodeStreamLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n const { part } = obj;\n\n // step_start carries the session ID for the run.\n if (obj.type === \"step_start\" && typeof obj.sessionID === \"string\") {\n return [{ type: \"session_id\", sessionId: obj.sessionID }];\n }\n\n // step_finish is one model call; part.tokens is that call's usage.\n if (obj.type === \"step_finish\" && part?.tokens) {\n const t = part.tokens;\n return contextWindowEvent(t.input, t.cache?.read, t.cache?.write);\n }\n\n // text event → assistant text. Emit both text (for streaming display) and\n // result (final message; the last result wins in the Orchestrator).\n if (\n obj.type === \"text\" &&\n part?.type === \"text\" &&\n typeof part.text === \"string\"\n ) {\n return [\n { type: \"text\", text: part.text },\n { type: \"result\", result: part.text },\n ];\n }\n\n // tool_use event → tool call. Tool name is in part.tool, args in\n // part.state.input. Gate on the completed status so intermediate\n // pending/running states don't surface duplicate tool calls.\n if (obj.type === \"tool_use\" && part?.type === \"tool\") {\n if (typeof part.tool !== \"string\") return [];\n const state = part.state as\n | { status?: string; input?: Record<string, unknown> }\n | undefined;\n if (state?.status !== \"completed\") return [];\n const { input } = state;\n if (!input) return [];\n const argField = OPENCODE_TOOL_ARG_FIELDS[part.tool];\n const argValue = argField === undefined ? undefined : input[argField];\n const args =\n typeof argValue === \"string\" ? argValue : JSON.stringify(input);\n return [{ type: \"tool_call\", name: part.tool, args }];\n }\n\n // OpenCode emits error events on stdout (not stderr) for auth failures,\n // rate limits, and API errors, and still exits 0 (opencode 1.3.13).\n if (obj.type === \"error\") {\n const msg = extractErrorMessage(obj);\n return msg ? [{ type: \"error\", message: msg }] : [];\n }\n\n // tool output, etc. → skip\n } catch {\n // Not valid JSON — skip\n }\n return [];\n};\n\n/** Options for the opencode agent provider. */\nexport interface OpenCodeOptions {\n /** Provider-specific reasoning effort variant (e.g. \"high\", \"max\", \"low\", \"minimal\"). */\n readonly variant?: string;\n /**\n * Named OpenCode agent/mode to run, mapped to OpenCode's own `--agent` flag\n * (e.g. \"build\", \"plan\"). This is distinct from Sandcastle's `--agent`\n * provider selector — it chooses an agent *inside* OpenCode.\n */\n readonly agent?: string;\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override where session exports live, for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostSessionsDir?: string;\n readonly sandboxExportDir?: string;\n };\n}\n\n/**\n * OpenCode's sessions live in its SQLite database, so a session moves as the\n * JSON of `opencode export <id>`, its documented interchange format: exported\n * in the sandbox after a run, and `opencode import`ed from the sandbox repo\n * before a resume (ADR 0022). The import keeps the session id and re-homes the\n * session to the importing project, so no rewrite is needed.\n */\nconst makeOpenCodeSessionStorage = (\n options?: OpenCodeOptions,\n): AgentSessionStorage => {\n const hostDir =\n options?.sessionStorage?.hostSessionsDir ?? opencodeHostSessionsDir();\n const exportDirOverride = options?.sessionStorage?.sandboxExportDir;\n const hostPath = (id: string): string => join(hostDir, `${id}.json`);\n return makeSessionFileStorage({\n hostRoot: hostDir,\n hostPath: (_cwd, id) => hostPath(id),\n // A no-sandbox run resumes from OpenCode's own database, which can't be\n // queried by id from here; OpenCode reports an unknown id itself.\n hostPathsById: (id) => [hostPath(id), opencodeHostDatabase()],\n sandboxPath: (_cwd, id, dirs) =>\n posix.join(exportDirOverride ?? dirs.tmp, `${id}.json`),\n sandboxExport: (id, path) =>\n `opencode export ${shellEscape(id)} > ${shellEscape(path)}`,\n sandboxImport: (_id, path) => `opencode import ${shellEscape(path)}`,\n });\n};\n\nexport const opencode = (\n model: string,\n options?: OpenCodeOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"opencode\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makeOpenCodeSessionStorage(options),\n\n buildPrintCommand({\n prompt,\n dangerouslySkipPermissions,\n resumeSession,\n forkSession,\n }: AgentCommandOptions): PrintCommand {\n const variantFlag = options?.variant\n ? ` --variant ${shellEscape(options.variant)}`\n : \"\";\n const agentFlag = options?.agent\n ? ` --agent ${shellEscape(options.agent)}`\n : \"\";\n const permissionsFlag = dangerouslySkipPermissions\n ? \" --dangerously-skip-permissions\"\n : \"\";\n // `--fork` copies the session to a new id before continuing, leaving the\n // parent untouched; it needs `--session`.\n const sessionFlags =\n resumeSession === undefined\n ? \"\"\n : ` --session ${shellEscape(resumeSession)}${forkSession === true ? \" --fork\" : \"\"}`;\n return {\n command: `opencode run --format json --model ${shellEscape(model)}${variantFlag}${agentFlag}${permissionsFlag}${sessionFlags} ${shellEscape(prompt)}`,\n };\n },\n\n buildInteractiveArgs({ prompt }: AgentCommandOptions): string[] {\n const args = [\"opencode\", \"--model\", model];\n if (options?.agent) args.push(\"--agent\", options.agent);\n // The TUI's seed-prompt flag is `--prompt` (long form only); `-p` is the\n // `opencode run`/`attach` basic-auth password flag, not a prompt seed.\n // Pre-fills the textbox but does not auto-submit (sst/opencode#3937).\n if (prompt) args.push(\"--prompt\", prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return parseOpenCodeStreamLine(line);\n },\n});\n\n// ---------------------------------------------------------------------------\n// GitHub Copilot CLI agent provider\n// ---------------------------------------------------------------------------\n\n/**\n * Copilot CLI print mode passes the prompt as the `-p` argv argument. (The CLI\n * can also read a prompt piped on stdin — `echo \"...\" | copilot` — but we use\n * the `-p` argv form here for parity with the tested print-command path.) Linux\n * enforces a per-argument limit (~128 KiB, ARG_MAX stack). Stay slightly under\n * so users get a clear error instead of spawn E2BIG. Mirrors the Cursor guard.\n */\nconst COPILOT_PRINT_PROMPT_MAX_BYTES = 120 * 1024;\n\nconst assertCopilotPrintPromptFitsArgv = (prompt: string): void => {\n const n = Buffer.byteLength(prompt, \"utf8\");\n if (n > COPILOT_PRINT_PROMPT_MAX_BYTES) {\n throw new Error(\n `Copilot print-mode prompt is ${n} bytes (max ${COPILOT_PRINT_PROMPT_MAX_BYTES} bytes). This provider passes the prompt as a command-line argument; shorten the prompt or split the work. Other Sandcastle providers use stdin for large prompts.`,\n );\n }\n};\n\n/**\n * Parse one line of `copilot --output-format json` JSONL output.\n *\n * Schema (observed via `copilot -p ... --output-format json --model ...`):\n *\n * - `assistant.message_delta` — `{ data: { messageId, deltaContent } }`\n * Streaming chunks of assistant text. Mapped to `text` events.\n *\n * - `assistant.message` — `{ data: { messageId, content, toolRequests, ... } }`\n * The complete assistant message. We surface its `content` as a `result`\n * event so the Orchestrator's \"last result wins\" buffer ends up holding\n * the final assistant text. (Tool calls in `toolRequests` are surfaced\n * separately via `tool.execution_start` events.)\n *\n * - `tool.execution_start` — `{ data: { toolCallId, toolName, arguments } }`\n * Mapped to `tool_call` events for allowlisted tools. Copilot uses lowercase\n * `bash`; we normalise to the existing `Bash` allowlist entry.\n *\n * - `session.usage_checkpoint` — `{ data: { accountingSnapshot } }`\n * `lastCallInputTokens` becomes a `context_window` event.\n *\n * - `result` — `{ sessionId, exitCode, usage }`\n * Terminal event. We surface `sessionId` as a `session_id` event.\n *\n * - `error` / `agent_error` — defensive: surface as an `error` event the same\n * way Pi/OpenCode do, so the Orchestrator fails the run with its message.\n */\nconst parseCopilotStreamLine = (line: string): ParsedStreamEvent[] => {\n if (!line.startsWith(\"{\")) return [];\n try {\n const obj = JSON.parse(line);\n\n // Streaming text deltas\n if (\n obj.type === \"assistant.message_delta\" &&\n typeof obj.data?.deltaContent === \"string\"\n ) {\n return [{ type: \"text\", text: obj.data.deltaContent }];\n }\n\n // Tool execution start → tool_call (allowlisted tools only)\n if (obj.type === \"tool.execution_start\") {\n const rawName = obj.data?.toolName;\n if (typeof rawName !== \"string\") return [];\n // Copilot CLI uses lowercase \"bash\"; normalise to the shared allowlist.\n const toolName = rawName === \"bash\" ? \"Bash\" : rawName;\n const argField = TOOL_ARG_FIELDS[toolName];\n if (argField === undefined) return [];\n const args = obj.data?.arguments as Record<string, unknown> | undefined;\n if (!args) return [];\n const argValue = args[argField];\n if (typeof argValue !== \"string\") return [];\n return [{ type: \"tool_call\", name: toolName, args: argValue }];\n }\n\n // Final assistant message → result. Each assistant turn emits one of\n // these with the complete text; the Orchestrator's resultText is\n // last-write-wins, so the final turn ends up surfaced to callers.\n if (\n obj.type === \"assistant.message\" &&\n typeof obj.data?.content === \"string\" &&\n obj.data.content.length > 0\n ) {\n return [{ type: \"result\", result: obj.data.content }];\n }\n\n // usage_checkpoint comes once near the end of a run. Use the last call's\n // input, never modelMetrics[...].usage.inputTokens, which sums all calls.\n if (obj.type === \"session.usage_checkpoint\") {\n return contextWindowEvent(\n obj.data?.accountingSnapshot?.lastCallInputTokens,\n );\n }\n\n // Terminal result event carries the session id\n if (obj.type === \"result\" && typeof obj.sessionId === \"string\") {\n return [{ type: \"session_id\", sessionId: obj.sessionId }];\n }\n\n // Defensive: surface error events as error events (matches Pi/OpenCode)\n if (obj.type === \"error\" || obj.type === \"agent_error\") {\n const msg = extractErrorMessage(obj);\n return msg ? [{ type: \"error\", message: msg }] : [];\n }\n } catch {\n // Not valid JSON — skip\n }\n return [];\n};\n\n/** Options for the GitHub Copilot CLI agent provider. */\nexport interface CopilotOptions {\n /** Reasoning effort level. Maps to the CLI's --effort flag. */\n readonly effort?: \"low\" | \"medium\" | \"high\";\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override Copilot `session-state` directories for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostSessionsDir?: string;\n readonly sandboxSessionsDir?: string;\n };\n}\n\n/**\n * Copilot's session is one `events.jsonl` keyed by id alone, so it moves as a\n * single file. The CLI resumes (`--resume=<id>`) but has no fork flag, so the\n * provider declares `canFork: false` (ADR 0021).\n */\nconst makeCopilotSessionStorage = (\n options?: CopilotOptions,\n): AgentSessionStorage => {\n const hostDir =\n options?.sessionStorage?.hostSessionsDir ?? copilotHostSessionsDir();\n const sandboxDirOverride = options?.sessionStorage?.sandboxSessionsDir;\n const hostPath = (id: string): string => join(hostDir, id, \"events.jsonl\");\n return {\n ...makeSessionFileStorage({\n hostRoot: hostDir,\n hostPath: (_cwd, id) => hostPath(id),\n hostPathsById: (id) => [hostPath(id)],\n sandboxPath: (_cwd, id, dirs) =>\n copilotSessionPath(\n sandboxDirOverride ??\n posix.join(dirs.home, \".copilot\", \"session-state\"),\n id,\n ),\n rewrite: transferCopilotSession,\n }),\n canFork: false,\n };\n};\n\nexport const copilot = (\n model: string,\n options?: CopilotOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"copilot\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makeCopilotSessionStorage(options),\n\n buildPrintCommand({\n prompt,\n dangerouslySkipPermissions,\n resumeSession,\n forkSession,\n }: AgentCommandOptions): PrintCommand {\n if (resumeSession !== undefined && forkSession === true) {\n throw new ForkNotSupportedError({\n message:\n \"copilot cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.\",\n agentProvider: \"copilot\",\n });\n }\n assertCopilotPrintPromptFitsArgv(prompt);\n const allowAll = dangerouslySkipPermissions ? \" --allow-all-tools\" : \"\";\n const effortFlag = options?.effort ? ` --effort ${options.effort}` : \"\";\n // `--resume` takes an optional value, so the id is bound with `=`.\n const resumeFlag =\n resumeSession === undefined\n ? \"\"\n : ` --resume=${shellEscape(resumeSession)}`;\n return {\n command: `copilot -p ${shellEscape(prompt)} --output-format json --model ${shellEscape(model)}${allowAll}${effortFlag}${resumeFlag}`,\n };\n },\n\n buildInteractiveArgs({ prompt }: AgentCommandOptions): string[] {\n const args = [\"copilot\", \"--model\", model];\n // Seed the interactive session with `-i`/`--interactive`, NOT `-p`. The\n // `-p`/`--prompt` flag runs the prompt programmatically and exits after\n // completion; since interactive() attaches these args to the real TTY,\n // `-p` would print-and-exit instead of launching the TUI. `-i` starts an\n // interactive session and auto-executes the prompt without exiting.\n if (prompt) args.push(\"-i\", prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return parseCopilotStreamLine(line);\n },\n});\n\n// ---------------------------------------------------------------------------\n// Claude Code agent provider\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeCodeOptions {\n readonly effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** Environment variables injected by this agent provider. */\n readonly env?: Record<string, string>;\n /** When false, session capture is disabled. Default: true. */\n readonly captureSessions?: boolean;\n /** Override Claude session directories for tests or non-standard installs. */\n readonly sessionStorage?: {\n readonly hostProjectsDir?: string;\n readonly sandboxProjectsDir?: string;\n };\n /**\n * Maps directly to Claude's `--permission-mode` flag. When set, replaces the\n * default `--dangerously-skip-permissions` Sandcastle passes on AFK runs —\n * the two flags are mutually exclusive on Claude's CLI. Use `\"auto\"` for\n * AI-mediated per-tool approve/deny on unsandboxed host runs.\n */\n readonly permissionMode?:\n | \"default\"\n | \"acceptEdits\"\n | \"plan\"\n | \"auto\"\n | \"dontAsk\"\n | \"bypassPermissions\";\n}\n\n/** The `claude --print` command for a print-mode run. */\nconst buildClaudePrintCommand = (\n model: string,\n options: ClaudeCodeOptions | undefined,\n {\n prompt,\n dangerouslySkipPermissions,\n resumeSession,\n forkSession,\n }: AgentCommandOptions,\n): PrintCommand => {\n // permissionMode and --dangerously-skip-permissions are mutually exclusive\n // on Claude's CLI; an explicit mode on the provider takes precedence over\n // Sandcastle's default bypass.\n const skipPermissionsFlag = dangerouslySkipPermissions\n ? \" --dangerously-skip-permissions\"\n : \"\";\n const permissionFlag = options?.permissionMode\n ? ` --permission-mode ${options.permissionMode}`\n : skipPermissionsFlag;\n const effortFlag = options?.effort ? ` --effort ${options.effort}` : \"\";\n const resumeFlag = resumeSession\n ? ` --resume ${shellEscape(resumeSession)}`\n : \"\";\n // --fork-session is meaningful only alongside --resume; it tells Claude\n // to write the continuation as a new session rather than mutating the\n // resumed one. See ADR 0018.\n const forkFlag = resumeSession && forkSession ? \" --fork-session\" : \"\";\n return {\n command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag}`,\n stdin: prompt,\n };\n};\n\n/** The token usage of the last assistant message in a Claude session JSONL. */\nconst parseClaudeSessionUsage = (\n content: string,\n): IterationUsage | undefined => {\n const lines = content.split(\"\\n\");\n for (let i = lines.length - 1; i >= 0; i--) {\n const line = lines[i]!;\n if (!line.startsWith(\"{\")) continue;\n try {\n const obj = JSON.parse(line);\n if (obj.type === \"assistant\" && obj.message?.usage) {\n const u = obj.message.usage;\n if (\n typeof u.input_tokens === \"number\" &&\n typeof u.cache_creation_input_tokens === \"number\" &&\n typeof u.cache_read_input_tokens === \"number\" &&\n typeof u.output_tokens === \"number\"\n ) {\n return {\n inputTokens: u.input_tokens,\n cacheCreationInputTokens: u.cache_creation_input_tokens,\n cacheReadInputTokens: u.cache_read_input_tokens,\n outputTokens: u.output_tokens,\n };\n }\n }\n } catch {\n // Not valid JSON — skip\n }\n }\n return undefined;\n};\n\nexport const claudeCode = (\n model: string,\n options?: ClaudeCodeOptions,\n): AgentProvider & { readonly sessionStorage: AgentSessionStorage } => ({\n name: \"claude-code\",\n env: options?.env ?? {},\n captureSessions: options?.captureSessions ?? true,\n sessionStorage: makeClaudeSessionStorage(options),\n\n buildPrintCommand(commandOptions: AgentCommandOptions): PrintCommand {\n return buildClaudePrintCommand(model, options, commandOptions);\n },\n\n buildInteractiveArgs({\n prompt,\n dangerouslySkipPermissions,\n }: AgentCommandOptions): string[] {\n const args = [\"claude\"];\n if (options?.permissionMode) {\n args.push(\"--permission-mode\", options.permissionMode);\n } else if (dangerouslySkipPermissions) {\n args.push(\"--dangerously-skip-permissions\");\n }\n args.push(\"--model\", model);\n if (options?.effort) args.push(\"--effort\", options.effort);\n if (prompt) args.push(prompt);\n return args;\n },\n\n parseStreamLine(line: string): ParsedStreamEvent[] {\n return [...parseStreamJsonLine(line), ...parseClaudeContextWindow(line)];\n },\n\n parseSessionUsage(content: string): IterationUsage | undefined {\n return parseClaudeSessionUsage(content);\n },\n});\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { NativeSandboxUnavailableError } from './chunk-
|
|
2
|
+
import { NativeSandboxUnavailableError } from './chunk-7JUTKCHL.js';
|
|
3
3
|
import { spawnSync } from 'child_process';
|
|
4
4
|
import { readFileSync } from 'fs';
|
|
5
5
|
|
|
@@ -108,5 +108,5 @@ var assertBwrapUsable = () => {
|
|
|
108
108
|
};
|
|
109
109
|
|
|
110
110
|
export { assertBwrapUsable };
|
|
111
|
-
//# sourceMappingURL=chunk-
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
111
|
+
//# sourceMappingURL=chunk-TBVRAXYF.js.map
|
|
112
|
+
//# sourceMappingURL=chunk-TBVRAXYF.js.map
|