@ai-hero/sandcastle 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +3 -2
- package/dist/{chunk-767EAJVT.js → chunk-ATA2V2TC.js} +3 -3
- package/dist/{chunk-767EAJVT.js.map → chunk-ATA2V2TC.js.map} +1 -1
- package/dist/{chunk-4EIVTSOZ.js → chunk-BIF2X6QB.js} +4 -3
- package/dist/chunk-BIF2X6QB.js.map +1 -0
- package/dist/{chunk-XCYK7I45.js → chunk-BVZWLFFT.js} +2 -2
- package/dist/chunk-BVZWLFFT.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/chunk-G2R53CVZ.js +3172 -0
- package/dist/chunk-G2R53CVZ.js.map +1 -0
- package/dist/{chunk-U42XXICG.js → chunk-GCLEXPXG.js} +7 -4
- package/dist/chunk-GCLEXPXG.js.map +1 -0
- package/dist/chunk-H2PEFS4W.js +1244 -0
- package/dist/chunk-H2PEFS4W.js.map +1 -0
- package/dist/{chunk-NMQ5Z6YG.js → chunk-HSXPRZKG.js} +5 -3
- package/dist/chunk-HSXPRZKG.js.map +1 -0
- package/dist/{chunk-J5J5YJ5S.js → chunk-IBK2XNSS.js} +3 -3
- package/dist/{chunk-J5J5YJ5S.js.map → chunk-IBK2XNSS.js.map} +1 -1
- package/dist/chunk-RDW7FNN6.js +792 -0
- package/dist/chunk-RDW7FNN6.js.map +1 -0
- package/dist/{chunk-A4C2FG74.js → chunk-S6UHPTRG.js} +43 -42
- package/dist/chunk-S6UHPTRG.js.map +1 -0
- package/dist/{chunk-LWNC4UTZ.js → chunk-STB2U7BB.js} +5414 -9389
- package/dist/chunk-STB2U7BB.js.map +1 -0
- package/dist/{chunk-XCWKLDH4.js → chunk-VRXR2T3S.js} +3 -3
- package/dist/{chunk-XCWKLDH4.js.map → chunk-VRXR2T3S.js.map} +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +458 -1675
- package/dist/index.js.map +1 -1
- package/dist/main.js +262 -247
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -6
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +179 -135
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +1 -1
- package/dist/sandboxes/docker.js +6 -3
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/podman.d.ts +1 -1
- package/dist/sandboxes/podman.js +6 -3
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +1 -1
- package/dist/sandboxes/seatbelt.js +9 -6
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +198 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +1 -1
- package/dist/sandboxes/vercel.js +1 -1
- package/package.json +30 -2
- package/dist/chunk-4EIVTSOZ.js.map +0 -1
- package/dist/chunk-A4C2FG74.js.map +0 -1
- package/dist/chunk-LWNC4UTZ.js.map +0 -1
- package/dist/chunk-NMQ5Z6YG.js.map +0 -1
- package/dist/chunk-U42XXICG.js.map +0 -1
- package/dist/chunk-XCYK7I45.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/SessionStore.ts","../src/AgentProvider.ts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Content":["/**\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).\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};\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\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.\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.\n if (obj.type === \"message_end\" && obj.message?.role === \"assistant\") {\n const u = obj.message.usage;\n return contextWindowEvent(u?.input, u?.cacheRead, u?.cacheWrite);\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\";\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} -p -`,\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,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import {
|
|
2
|
+
import { resolveUserMounts } from './chunk-G2R53CVZ.js';
|
|
3
|
+
import { FileSystem_exports, CopyError } from './chunk-RDW7FNN6.js';
|
|
4
|
+
import { Effect_exports, Config_exports, Option_exports } from './chunk-STB2U7BB.js';
|
|
3
5
|
import { BoundedTail } from './chunk-6NQPCXSG.js';
|
|
4
6
|
import { dirname, posix } from 'path';
|
|
5
7
|
import { createInterface } from 'readline';
|
|
@@ -144,5 +146,5 @@ var resolveIdentityMounts = (provider, mounts, sandboxHomedir) => resolveUserMou
|
|
|
144
146
|
});
|
|
145
147
|
|
|
146
148
|
export { collectOutput, copyCreatingParents, hostPathToolchainFromEnv, resolveIdentityMounts };
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
148
|
-
//# sourceMappingURL=chunk-
|
|
149
|
+
//# sourceMappingURL=chunk-HSXPRZKG.js.map
|
|
150
|
+
//# sourceMappingURL=chunk-HSXPRZKG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/nativeSandboxIo.ts","../src/hostPathToolchain.ts","../src/identityMounts.ts"],"names":[],"mappings":";;;;;;;;;;AAeO,IAAM,aAAA,GAAgB,CAC3B,IAAA,EACA,MAAA,EACA,YAAA,KAC+C;AAC/C,EAAA,MAAM,YAAY,MAAA,KAAW,MAAA;AAC7B,EAAA,MAAM,MAAA,GAAS,YACX,IAAI,WAAA,CAAY,cAAc,IAAI,CAAA,GAClC,IAAI,WAAA,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MI,IAAM,wBAAA,GAA2B,CAAC,KAAA,KAIvC,cAAA,CAAO,IAAI,aAAa;AACtB,EAAA,MAAM,IAAA,GAAO,OAAO,cAAA,CAAO,MAAA,CAAO,MAAM,EAAE,IAAA,CAAK,cAAA,CAAO,WAAA,CAAY,EAAE,CAAC,CAAA;AACrE,EAAA,OAAO,OAAO,yBAAyB,EAAE,IAAA,EAAM,MAAM,OAAA,EAAQ,EAAG,GAAG,KAAA,EAAO,CAAA;AAC5E,CAAC,CAAA,CAAE,IAAA,CAAK,cAAA,CAAO,KAAK;;;ACrNf,IAAM,qBAAA,GAAwB,CACnC,QAAA,EACA,MAAA,EACA,cAAA,KAEA,iBAAA,CAAkB,MAAA,EAAQ,cAAc,CAAA,CAAE,GAAA,CAAI,CAAC,QAAA,EAAU,CAAA,KAAM;AAC7D,EAAA,IAAI,QAAA,CAAS,WAAA,KAAgB,QAAA,CAAS,QAAA,EAAU;AAC9C,IAAA,MAAM,KAAA,GAAQ,OAAO,CAAC,CAAA;AACtB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,GAAG,QAAQ,CAAA,sFAAA,EACO,KAAA,EAAO,QAAA,IAAY,SAAS,QAAQ,CAAA,cAAA,EAAiB,QAAA,CAAS,QAAQ,qBACnE,KAAA,EAAO,WAAA,IAAe,SAAS,WAAW,CAAA,cAAA,EAAiB,SAAS,WAAW,CAAA,EAAA;AAAA,KACtG;AAAA,EACF;AACA,EAAA,OAAO;AAAA,IACL,UAAU,QAAA,CAAS,QAAA;AAAA,IACnB,QAAA,EAAU,SAAS,QAAA,KAAa;AAAA,GAClC;AACF,CAAC","file":"chunk-HSXPRZKG.js","sourcesContent":["/**\n * Provider-agnostic helpers for the native sandbox providers (`bwrap()`,\n * `seatbelt()`): collecting a child process's output, and copying a file\n * between host paths. Each is purely a function of its inputs.\n */\n\nimport type { ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { BoundedTail } from \"./boundedTail.js\";\nimport { CopyError } from \"./errors.js\";\n\n/** Collects a child's output: streamed line by line with a bounded tail, or whole. */\nexport const collectOutput = (\n proc: ChildProcessWithoutNullStreams,\n onLine: ((line: string) => void) | undefined,\n maxTailChars: number,\n): (() => { stdout: string; stderr: string }) => {\n const streaming = onLine !== undefined;\n const stdout = streaming\n ? new BoundedTail(maxTailChars, \"\\n\")\n : new BoundedTail(Infinity);\n const stderr = new BoundedTail(streaming ? maxTailChars : Infinity);\n if (onLine === undefined) {\n proc.stdout.on(\"data\", (chunk: Buffer) => {\n stdout.push(chunk.toString());\n });\n } else {\n createInterface({ input: proc.stdout }).on(\"line\", (line) => {\n stdout.push(line);\n onLine(line);\n });\n }\n proc.stderr.on(\"data\", (chunk: Buffer) => {\n stderr.push(chunk.toString());\n });\n return () => ({ stdout: stdout.toString(), stderr: stderr.toString() });\n};\n\n/** Copies a file, creating the target's parent dirs. */\nexport const copyCreatingParents = (\n from: string,\n to: string,\n): Effect.Effect<void, CopyError, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs.makeDirectory(dirname(to), { recursive: true });\n yield* fs.copyFile(from, to);\n }).pipe(\n Effect.mapError(\n (e) =>\n new CopyError({\n message: `Couldn't copy ${from} to ${to}: ${e.message}`,\n }),\n ),\n );\n","/**\n * Resolves the host toolchain a native sandbox provider should make readable,\n * from the host `PATH`: every `PATH` dir, plus the install root of each\n * executable symlinked from those dirs (an nvm-installed `codex`, a `claude`\n * symlinked into `~/.local/bin`). A dir equal to the home dir or an ancestor\n * of it is refused, so the toolchain never exposes the whole home, and an\n * install root that holds a `.git` is refused, so it never exposes a repo.\n *\n * Provider-agnostic: it takes paths and returns paths. Shared by the native\n * sandbox providers.\n */\n\nimport { homedir } from \"node:os\";\nimport { posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Config, Effect, Option } from \"effect\";\n\n/** What to resolve the toolchain from. */\nexport interface HostPathToolchainInput {\n /** The host `PATH`. */\n readonly path: string;\n /** The host home dir: it and its ancestors are never made readable. */\n readonly home: string;\n /** Dirs the sandbox already shows: nothing inside them is returned to mount. */\n readonly coveredRoots: readonly string[];\n /** Dirs that must stay hidden: `PATH` dirs and install roots inside them are refused. */\n readonly deniedRoots: readonly string[];\n}\n\n/** The toolchain a sandbox needs, all at host paths. */\nexport interface HostPathToolchain {\n /** The `PATH` for the sandboxed child: the host `PATH` dirs it can see, in order. */\n readonly pathEntries: readonly string[];\n /** Real dirs to make readable at their own paths. */\n readonly readableDirs: readonly string[];\n /** `PATH` dirs that are symlinks on the host, to recreate pointing at their real dir. */\n readonly symlinks: readonly {\n readonly path: string;\n readonly target: string;\n }[];\n}\n\nconst isWithin = (path: string, root: string): boolean =>\n root === \"/\" || path === root || path.startsWith(`${root}/`);\n\nconst isWithinAny = (path: string, roots: readonly string[]): boolean =>\n roots.some((root) => isWithin(path, root));\n\n/** True for the home dir itself and every ancestor of it, `/` included. */\nconst isHomeOrAncestor = (path: string, home: string): boolean =>\n isWithin(home, path);\n\nconst normalizeEntry = (entry: string): string => {\n const normalized = posix.normalize(entry);\n return normalized.length > 1 && normalized.endsWith(\"/\")\n ? normalized.slice(0, -1)\n : normalized;\n};\n\nconst realPathOf = (\n fs: FileSystem.FileSystem,\n path: string,\n): Effect.Effect<Option.Option<string>> => Effect.option(fs.realPath(path));\n\n/** True when `dir` sits inside a `node_modules` tree. */\nconst isInNodeModules = (dir: string): boolean =>\n dir.split(\"/\").includes(\"node_modules\");\n\n/**\n * The install root of an executable's real file: the nearest ancestor holding\n * a `package.json` inside a `node_modules` tree (a globally installed Node\n * package's bin pulls in its own files), else the file's dir. A `package.json`\n * outside `node_modules` (an `npm link`ed checkout, a stray one above a\n * projects dir) is not an install root: mounting it would expose a project.\n * The search stops below the home dir.\n */\nconst installRootOf = (\n fs: FileSystem.FileSystem,\n file: string,\n home: string,\n): Effect.Effect<string> =>\n Effect.gen(function* () {\n const fileDir = posix.dirname(file);\n let dir = fileDir;\n while (isInNodeModules(dir) && !isHomeOrAncestor(dir, home)) {\n const hasPackageJson = yield* fs\n .exists(posix.join(dir, \"package.json\"))\n .pipe(Effect.orElseSucceed(() => false));\n if (hasPackageJson) {\n return dir;\n }\n dir = posix.dirname(dir);\n }\n return fileDir;\n });\n\n/** True when `dir` holds a `.git`: a repo's checkout is never an install root. */\nconst isRepoRoot = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<boolean> =>\n fs.exists(posix.join(dir, \".git\")).pipe(Effect.orElseSucceed(() => false));\n\n/** The real files behind the symlinks directly inside `dir`. */\nconst symlinkTargetsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const names = yield* fs\n .readDirectory(dir)\n .pipe(Effect.orElseSucceed((): string[] => []));\n const targets = yield* Effect.forEach(\n names,\n (name) =>\n Effect.gen(function* () {\n const entry = posix.join(dir, name);\n const link = yield* Effect.option(fs.readLink(entry));\n return Option.isSome(link)\n ? yield* realPathOf(fs, entry)\n : Option.none<string>();\n }),\n { concurrency: 32 },\n );\n return targets.flatMap((t) => (Option.isSome(t) ? [t.value] : []));\n });\n\n/** The rules every resolved path is held to. */\ninterface Rules {\n readonly home: string;\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}\n\nconst isRefused = (path: string, rules: Rules): boolean =>\n isHomeOrAncestor(path, rules.home) || isWithinAny(path, rules.deniedRoots);\n\n/** A `PATH` entry the sandbox may see, and the real dir behind it. */\ninterface AcceptedEntry {\n readonly entry: string;\n readonly real: string;\n}\n\n/** Accepts a `PATH` entry that exists and isn't refused, by itself or by its real dir. */\nconst acceptEntry = (\n fs: FileSystem.FileSystem,\n entry: string,\n rules: Rules,\n): Effect.Effect<Option.Option<AcceptedEntry>> =>\n isRefused(entry, rules)\n ? Effect.succeed(Option.none())\n : realPathOf(fs, entry).pipe(\n Effect.map(Option.filter((real) => !isRefused(real, rules))),\n Effect.map(Option.map((real) => ({ entry, real }))),\n );\n\n/** The install roots of the executables symlinked from `dir` to outside it. */\nconst installRootsIn = (\n fs: FileSystem.FileSystem,\n dir: string,\n rules: Rules,\n): Effect.Effect<string[]> =>\n Effect.gen(function* () {\n const targets = (yield* symlinkTargetsIn(fs, dir)).filter(\n (target) =>\n !isWithin(target, dir) && !isWithinAny(target, rules.coveredRoots),\n );\n const roots = yield* Effect.all(\n targets.map((target) => installRootOf(fs, target, rules.home)),\n );\n return yield* Effect.filter(\n roots.filter((root) => !isRefused(root, rules)),\n (root) => Effect.map(isRepoRoot(fs, root), (isRepo) => !isRepo),\n );\n });\n\n/** Keeps only the dirs not inside another dir of the list. */\nconst outermost = (dirs: readonly string[]): string[] => {\n const unique = [...new Set(dirs)];\n return unique.filter(\n (dir) => !unique.some((other) => other !== dir && isWithin(dir, other)),\n );\n};\n\n/** Resolves the toolchain a sandbox needs from the host `PATH`. */\nexport const resolveHostPathToolchain = (\n input: HostPathToolchainInput,\n): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const rules: Rules = { ...input, home: normalizeEntry(input.home) };\n const entries = [\n ...new Set(\n input.path\n .split(\":\")\n .filter((entry) => entry.startsWith(\"/\"))\n .map((entry) => normalizeEntry(entry)),\n ),\n ];\n const accepted = (yield* Effect.all(\n entries.map((entry) => acceptEntry(fs, entry, rules)),\n )).flatMap((a) => (Option.isSome(a) ? [a.value] : []));\n const uncovered = accepted.filter(\n (a) => !isWithinAny(a.real, rules.coveredRoots),\n );\n const installRoots = yield* Effect.all(\n [...new Set(accepted.map((a) => a.real))].map((dir) =>\n installRootsIn(fs, dir, rules),\n ),\n );\n return {\n pathEntries: accepted.map((a) => a.entry),\n readableDirs: outermost([\n ...uncovered.map((a) => a.real),\n ...installRoots.flat(),\n ]),\n symlinks: uncovered\n .filter(\n (a) =>\n a.real !== a.entry && !isWithinAny(a.entry, rules.coveredRoots),\n )\n .map((a) => ({ path: a.entry, target: a.real })),\n };\n });\n\n/**\n * {@link resolveHostPathToolchain} for this process: the host `PATH` and home\n * dir come from the environment.\n */\nexport const hostPathToolchainFromEnv = (roots: {\n readonly coveredRoots: readonly string[];\n readonly deniedRoots: readonly string[];\n}): Effect.Effect<HostPathToolchain, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const path = yield* Config.string(\"PATH\").pipe(Config.withDefault(\"\"));\n return yield* resolveHostPathToolchain({ path, home: homedir(), ...roots });\n }).pipe(Effect.orDie);\n","/**\n * Identity mounts: the `mounts` option of the native sandbox providers, where\n * every path appears inside the sandbox at its own host path. Provider-agnostic:\n * shared by the native sandbox providers.\n */\n\nimport type { MountConfig } from \"./MountConfig.js\";\nimport { resolveUserMounts } from \"./mountUtils.js\";\n\nexport type { MountConfig } from \"./MountConfig.js\";\n\n/** A resolved mount that appears at its own host path. */\nexport interface IdentityMount {\n readonly hostPath: string;\n readonly readonly: boolean;\n}\n\n/**\n * Resolves `mounts` (tilde and relative paths, as for every provider) and\n * checks each appears at its own host path. Throws, naming `provider`, when a\n * resolved `sandboxPath` differs from its resolved `hostPath`, or when a\n * `hostPath` doesn't exist.\n */\nexport const resolveIdentityMounts = (\n provider: string,\n mounts: readonly MountConfig[],\n sandboxHomedir: string,\n): IdentityMount[] =>\n resolveUserMounts(mounts, sandboxHomedir).map((resolved, i) => {\n if (resolved.sandboxPath !== resolved.hostPath) {\n const given = mounts[i];\n throw new Error(\n `${provider}() mounts appear at their host path, so sandboxPath must equal hostPath: ` +\n `got hostPath ${given?.hostPath ?? resolved.hostPath} (resolved to ${resolved.hostPath}) ` +\n `and sandboxPath ${given?.sandboxPath ?? resolved.sandboxPath} (resolved to ${resolved.sandboxPath}).`,\n );\n }\n return {\n hostPath: resolved.hostPath,\n readonly: resolved.readonly === true,\n };\n });\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { NativeSandboxUnavailableError } from './chunk-
|
|
2
|
+
import { NativeSandboxUnavailableError } from './chunk-S6UHPTRG.js';
|
|
3
3
|
import { spawnSync } from 'child_process';
|
|
4
4
|
import { existsSync } from 'fs';
|
|
5
5
|
import { release } from 'os';
|
|
@@ -46,5 +46,5 @@ var assertSeatbeltUsable = () => {
|
|
|
46
46
|
};
|
|
47
47
|
|
|
48
48
|
export { SANDBOX_EXEC, assertSeatbeltUsable };
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-IBK2XNSS.js.map
|
|
50
|
+
//# sourceMappingURL=chunk-IBK2XNSS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/seatbeltPreflight.ts"],"names":[],"mappings":";;;;;;;AAiBO,IAAM,YAAA,GAAe;AAG5B,IAAM,gBAAA,GAAmB,EAAA;AAEzB,IAAM,UAAA,GAAa,uBAAA;AAGnB,IAAM,QAAQ,MAA0B;AACtC,EAAA,IAAI,CAAC,UAAA,CAAW,YAAY,CAAA,EAAG;AAC7B,IAAA,OAAO,CAAA,yBAAA,EAA4B,YAAY,CAAA,oBAAA,EAAuB,UAAU,CAAA,CAAA;AAAA,EAClF;AACA,EAAA,MAAM,MAAA,GAAS,SAAA;AAAA,IACb,YAAA;AAAA,IACA,CAAC,IAAA,EAAM,4BAAA,EAA8B,IAAA,EAAM,eAAe,CAAA;AAAA,IAC1D,EAAE,KAAA,EAAO,CAAC,QAAA,EAAU,QAAA,EAAU,MAAM,CAAA,EAAG,QAAA,EAAU,MAAA,EAAQ,OAAA,EAAS,GAAA;AAAO,GAC3E;AACA,EAAA,IAAI,MAAA,CAAO,WAAW,CAAA,EAAG;AACvB,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,MAAA,GAAA,CAAU,MAAA,CAAO,MAAA,IAAU,EAAA,EAAI,IAAA,EAAK;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OAAO,uCAAuC,UAAU,CAAA,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,KAAA,EAAM;AACf,CAAA;AAEA,IAAI,OAAA;AAQG,IAAM,uBAAuB,MAAY;AAC9C,EAAA,OAAA,KAAY,EAAE,WAAA,EAAa,KAAA,EAAM,EAAE;AACnC,EAAA,IAAI,OAAA,CAAQ,gBAAgB,MAAA,EAAW;AACrC,IAAA,MAAM,IAAI,6BAAA,CAA8B;AAAA,MACtC,SAAS,OAAA,CAAQ;AAAA,KAClB,CAAA;AAAA,EACH;AACF","file":"chunk-IBK2XNSS.js","sourcesContent":["/**\n * The `seatbelt()` construction check (src/sandboxes/seatbelt.ts): can this\n * host run a Seatbelt sandbox, and if not, why. Runs once per process. Used\n * only by `seatbelt()`.\n *\n * Synchronous on purpose: `seatbelt()` is a synchronous constructor, and it\n * must throw before anything else (a worktree, a temp dir) exists.\n */\n\n/* oxlint-disable node/no-sync -- seatbelt() throws at construction, which is synchronous (allowlisted in scripts/lint-ratchet-config.ts). */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { release } from \"node:os\";\nimport { NativeSandboxUnavailableError } from \"./NativeSandboxUnavailableError.js\";\n\n/** The system `sandbox-exec`, always by absolute path, never one found on `PATH`. */\nexport const SANDBOX_EXEC = \"/usr/bin/sandbox-exec\";\n\n/** Darwin 23 is macOS 14, the oldest macOS `seatbelt()` supports. */\nconst MIN_DARWIN_MAJOR = 23;\n\nconst USE_DOCKER = \"Use docker() instead.\";\n\n/** Runs a trivial profile; returns why it failed, or undefined when it works. */\nconst probe = (): string | undefined => {\n if (!existsSync(SANDBOX_EXEC)) {\n return `seatbelt() needs macOS's ${SANDBOX_EXEC}, and it's missing. ${USE_DOCKER}`;\n }\n const result = spawnSync(\n SANDBOX_EXEC,\n [\"-p\", \"(version 1)(allow default)\", \"--\", \"/usr/bin/true\"],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"], encoding: \"utf8\", timeout: 30_000 },\n );\n if (result.status === 0) {\n return undefined;\n }\n const stderr = (result.stderr ?? \"\").trim();\n const reason =\n stderr === \"\"\n ? (result.error?.message ?? `exit code ${String(result.status)}`)\n : stderr;\n const nested = /Operation not permitted/iu.test(stderr)\n ? \" This process may already be inside a Seatbelt sandbox, and macOS refuses to nest them.\"\n : \"\";\n return `seatbelt() can't start a sandbox: \\`${SANDBOX_EXEC}\\` failed: ${reason}.${nested} ${USE_DOCKER}`;\n};\n\nconst check = (): string | undefined => {\n if (process.platform !== \"darwin\") {\n return \"seatbelt() needs macOS; on Linux or WSL2 use bwrap()\";\n }\n const major = Number(release().split(\".\")[0]);\n if (Number.isFinite(major) && major < MIN_DARWIN_MAJOR) {\n return `seatbelt() needs macOS 14 or later. ${USE_DOCKER}`;\n }\n return probe();\n};\n\nlet outcome: { readonly unavailable: string | undefined } | undefined;\n\n/**\n * Throws `NativeSandboxUnavailableError` when this host can't run a Seatbelt\n * sandbox. There's no install command on macOS, so the error never has a\n * `fixCommand`. Checks on the first call only; later calls give the same\n * answer.\n */\nexport const assertSeatbeltUsable = (): void => {\n outcome ??= { unavailable: check() };\n if (outcome.unavailable !== undefined) {\n throw new NativeSandboxUnavailableError({\n message: outcome.unavailable,\n });\n }\n};\n"]}
|