@ai-hero/sandcastle 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/{SandboxProvider-Chsi-Zs6.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +2 -39
  2. package/dist/{chunk-BVZWLFFT.js → chunk-4BB7DNPW.js} +3 -3
  3. package/dist/chunk-4BB7DNPW.js.map +1 -0
  4. package/dist/chunk-4GZMUHVO.js +60 -0
  5. package/dist/chunk-4GZMUHVO.js.map +1 -0
  6. package/dist/{chunk-S6UHPTRG.js → chunk-7JUTKCHL.js} +4 -4
  7. package/dist/{chunk-S6UHPTRG.js.map → chunk-7JUTKCHL.js.map} +1 -1
  8. package/dist/chunk-7PHPLDVS.js +284 -0
  9. package/dist/chunk-7PHPLDVS.js.map +1 -0
  10. package/dist/{chunk-HSXPRZKG.js → chunk-BXLS4HRY.js} +15 -6
  11. package/dist/chunk-BXLS4HRY.js.map +1 -0
  12. package/dist/{chunk-G2R53CVZ.js → chunk-EM4QNWKF.js} +695 -706
  13. package/dist/chunk-EM4QNWKF.js.map +1 -0
  14. package/dist/{chunk-STB2U7BB.js → chunk-JEQ4IVQM.js} +384 -264
  15. package/dist/chunk-JEQ4IVQM.js.map +1 -0
  16. package/dist/{chunk-VRXR2T3S.js → chunk-L3BU47F6.js} +3 -3
  17. package/dist/{chunk-VRXR2T3S.js.map → chunk-L3BU47F6.js.map} +1 -1
  18. package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
  19. package/dist/chunk-PTJEKJPQ.js.map +1 -0
  20. package/dist/{chunk-H2PEFS4W.js → chunk-SAQXFLO2.js} +30 -6
  21. package/dist/chunk-SAQXFLO2.js.map +1 -0
  22. package/dist/{chunk-ATA2V2TC.js → chunk-TBVRAXYF.js} +3 -3
  23. package/dist/{chunk-ATA2V2TC.js.map → chunk-TBVRAXYF.js.map} +1 -1
  24. package/dist/{chunk-IBK2XNSS.js → chunk-VUOXFCWO.js} +3 -3
  25. package/dist/{chunk-IBK2XNSS.js.map → chunk-VUOXFCWO.js.map} +1 -1
  26. package/dist/{chunk-GCLEXPXG.js → chunk-WYOGXC72.js} +46 -84
  27. package/dist/chunk-WYOGXC72.js.map +1 -0
  28. package/dist/{chunk-RDW7FNN6.js → chunk-YDQW5IOY.js} +11 -4
  29. package/dist/chunk-YDQW5IOY.js.map +1 -0
  30. package/dist/index.d.ts +47 -4
  31. package/dist/index.js +536 -445
  32. package/dist/index.js.map +1 -1
  33. package/dist/main.js +72 -16
  34. package/dist/main.js.map +1 -1
  35. package/dist/sandboxes/bwrap.d.ts +1 -1
  36. package/dist/sandboxes/bwrap.js +9 -17
  37. package/dist/sandboxes/bwrap.js.map +1 -1
  38. package/dist/sandboxes/daytona.d.ts +1 -1
  39. package/dist/sandboxes/daytona.js +82 -79
  40. package/dist/sandboxes/daytona.js.map +1 -1
  41. package/dist/sandboxes/docker.d.ts +23 -1
  42. package/dist/sandboxes/docker.js +6 -5
  43. package/dist/sandboxes/e2b.d.ts +1 -1
  44. package/dist/sandboxes/e2b.js +4 -4
  45. package/dist/sandboxes/modal.d.ts +1 -1
  46. package/dist/sandboxes/modal.js +1 -1
  47. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  48. package/dist/sandboxes/no-sandbox.js +1 -1
  49. package/dist/sandboxes/podman.d.ts +27 -4
  50. package/dist/sandboxes/podman.js +18 -45
  51. package/dist/sandboxes/podman.js.map +1 -1
  52. package/dist/sandboxes/seatbelt.d.ts +2 -2
  53. package/dist/sandboxes/seatbelt.js +10 -10
  54. package/dist/sandboxes/seatbelt.js.map +1 -1
  55. package/dist/sandboxes/sprites.d.ts +1 -1
  56. package/dist/sandboxes/sprites.js +25 -4
  57. package/dist/sandboxes/sprites.js.map +1 -1
  58. package/dist/sandboxes/vercel.d.ts +10 -1
  59. package/dist/sandboxes/vercel.js +74 -46
  60. package/dist/sandboxes/vercel.js.map +1 -1
  61. package/dist/templates/parallel-planner/main.mts +43 -21
  62. package/dist/templates/parallel-planner-with-review/main.mts +55 -27
  63. package/dist/templates/sequential-reviewer/main.mts +1 -1
  64. package/package.json +7 -3
  65. package/dist/chunk-7N7AMUYA.js.map +0 -1
  66. package/dist/chunk-BIF2X6QB.js +0 -94
  67. package/dist/chunk-BIF2X6QB.js.map +0 -1
  68. package/dist/chunk-BVZWLFFT.js.map +0 -1
  69. package/dist/chunk-G2R53CVZ.js.map +0 -1
  70. package/dist/chunk-GCLEXPXG.js.map +0 -1
  71. package/dist/chunk-H2PEFS4W.js.map +0 -1
  72. package/dist/chunk-HSXPRZKG.js.map +0 -1
  73. package/dist/chunk-RDW7FNN6.js.map +0 -1
  74. package/dist/chunk-STB2U7BB.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resumePrecheck.ts","../src/AgentStreamEmitter.ts","../src/PromptPreprocessor.ts","../src/TextDeltaBuffer.ts","../src/ContextWindow.ts","../src/Orchestrator.ts","../src/PromptResolver.ts","../src/EnvResolver.ts","../src/mergeProviderEnv.ts","../src/PromptArgumentSubstitution.ts","../src/Output.ts","../src/extractStructuredOutput.ts","../src/validateTimeouts.ts","../src/run.ts","../src/raceAbortSignal.ts","../src/interactive.ts","../src/createSandbox.ts","../src/createWorktree.ts","../src/CwdError.ts","../src/SyncOutPathError.ts"],"names":["cursor","text","join","startResult","result","exports","ctx","hostRepoDir","worktreePath","providerHandle","sandbox","sandboxRepoDir","CwdError","SyncOutPathError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,mBAAA,GAAsB,CAAC,QAAA,KAAkC;AACpE,EAAA,IAAI,QAAA,CAAS,cAAA,EAAgB,OAAA,KAAY,KAAA,EAAO;AAC9C,IAAA,MAAM,IAAI,qBAAA,CAAsB;AAAA,MAC9B,OAAA,EAAS,CAAA,EAAG,QAAA,CAAS,IAAI,CAAA,uGAAA,CAAA;AAAA,MACzB,eA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,IAAA;AAAA,IAC3B,WAAA;AAAA,IACA,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,OAAO,IAAA,CAAK,KAAA;AAAA;AAAA;AAAA,IAGZ,gBACE,IAAA,CAAK,OAAA,CAAQ,GAAA,KAAQ,UAAA,GACjB,CAAC,GAAI,OAAA,CAAQ,cAAA,IAAkB,IAAK,GAAI,IAAA,CAAK,kBAAkB,EAAG,IAClE,IAAA,CAAK,cAAA;AAAA,IACX,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,OAAO,IAAA,CAAK;AAAA,GACb,CAAA;AACH,EAAA,OAAO;AAAA,IACL,QAAQ,YAAA,CAAa,MAAA;AAAA,IACrB,cAAc,YAAA,CAAa,IAAA;AAAA,IAC3B,GAAA,EAAK,WAAA;AAAA,IACL,WAAA,EAAa,mBAAA;AAAA,IACb,aAAA,EAAe,qBAAA;AAAA,IACf,KAAA;AAAA,IACA,OAAO,MAAA,CAAO,YAAY,CAAA,GAAI;AAC5B,MAAA,MAAM,KAAA,EAAM;AAAA,IACd;AAAA,GACF;AACF;;;ACrxBO,IAAMU,SAAAA,GAAgC;;;ACMtC,IAAMC,iBAAAA,GACX","file":"index.js","sourcesContent":["import type { AgentProvider } from \"./AgentProvider.js\";\nimport { ForkNotSupportedError } from \"./errors.js\";\nimport type { SandboxProvider } from \"./SandboxProvider.js\";\n\n/**\n * Fail-fast validation, for a run asked to fork its session, that the agent\n * provider can fork. One that resumes but has no native fork declares\n * `sessionStorage.canFork: false` and gets a `ForkNotSupportedError` naming\n * it. A provider with no `sessionStorage` is left to\n * `assertResumeSessionExists`, which rejects any resume.\n */\nexport const assertForkSupported = (provider: AgentProvider): void => {\n if (provider.sessionStorage?.canFork === false) {\n throw new ForkNotSupportedError({\n message: `${provider.name} cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.`,\n agentProvider: provider.name,\n });\n }\n};\n\n/**\n * Fail-fast validation that a resumable agent session exists on the host before\n * launching the agent. Throws a descriptive error when the session is missing.\n *\n * The lookup strategy depends on the sandbox:\n *\n * - **No-sandbox**: the agent runs directly on the host and writes its session\n * in place under a cwd-derived directory; Sandcastle never moves it. The\n * agent's own path encoding (realpath canonicalisation plus\n * non-alphanumeric → hyphen) is fragile and platform-specific to reconstruct,\n * so we locate the file by its globally-unique session id instead.\n * - **Sandboxed (bind-mount)**: Sandcastle's capture transfers the session into\n * the host store keyed on the host repo dir, so for a resumable run the file\n * lives at that exact encoded location — check it directly rather than\n * scanning. (Isolated sandboxes fall here too, but neither capture nor resume\n * transfer is wired for them today, so this is the host-repo-dir check by\n * default.)\n */\nexport const assertResumeSessionExists = async (params: {\n readonly provider: AgentProvider;\n readonly sandboxTag: SandboxProvider[\"tag\"];\n readonly hostRepoDir: string;\n readonly resumeSession: string;\n}): Promise<void> => {\n const { provider, sandboxTag, hostRepoDir, resumeSession } = params;\n\n if (!provider.sessionStorage) {\n throw new Error(`${provider.name} does not support resumeSession`);\n }\n\n if (sandboxTag === \"none\") {\n const found = await provider.sessionStorage.findByIdOnHost(resumeSession);\n if (found.path === undefined) {\n throw new Error(\n `resumeSession \"${resumeSession}\" not found under ${found.searchedRoot}`,\n );\n }\n return;\n }\n\n const exists = await provider.sessionStorage.existsOnHost(\n hostRepoDir,\n resumeSession,\n );\n if (!exists) {\n const sessionPath = provider.sessionStorage.hostSessionFilePath(\n hostRepoDir,\n resumeSession,\n );\n throw new Error(\n sessionPath === undefined\n ? `resumeSession \"${resumeSession}\" not found`\n : `resumeSession \"${resumeSession}\" not found: expected session file at ${sessionPath}`,\n );\n }\n};\n","import { Context, Effect, Layer } from \"effect\";\n\n/**\n * A single event in the agent's output stream, surfaced to callers of `run()`\n * so they can forward it to their own observability system.\n *\n * Emitted only in log-to-file mode when an `onAgentStreamEvent` callback is\n * provided via `logging`. See `run()`.\n *\n * The `\"raw\"` variant carries every stdout line the agent emits, verbatim and\n * before parsing — including lines that the provider's stream parser would\n * otherwise drop (e.g. tool-use blocks for unrecognised tools). Intended for\n * debugging when the typed `\"text\"` / `\"toolCall\"` events don't surface\n * enough detail.\n */\nexport type AgentStreamEvent =\n | {\n readonly type: \"text\";\n readonly message: string;\n readonly iteration: number;\n readonly timestamp: Date;\n }\n | {\n readonly type: \"toolCall\";\n readonly name: string;\n readonly formattedArgs: string;\n readonly iteration: number;\n readonly timestamp: Date;\n }\n | {\n readonly type: \"raw\";\n readonly line: string;\n readonly iteration: number;\n readonly timestamp: Date;\n };\n\nexport interface AgentStreamEmitterService {\n readonly emit: (event: AgentStreamEvent) => Effect.Effect<void>;\n}\n\nexport class AgentStreamEmitter extends Context.Tag(\n \"@ai-hero/sandcastle/AgentStreamEmitter\",\n)<AgentStreamEmitter, AgentStreamEmitterService>() {}\n\n/**\n * Build a layer for the AgentStreamEmitter service.\n *\n * Called with no argument, returns a no-op layer that discards events.\n * Called with a callback, returns a layer that forwards each event to it.\n * The callback is invoked synchronously inside an `Effect.sync`; any error\n * thrown by the callback is caught and discarded so observability failures\n * cannot kill the run.\n */\nexport const agentStreamEmitterLayer = (\n onEvent?: (event: AgentStreamEvent) => void,\n): Layer.Layer<AgentStreamEmitter> =>\n Layer.succeed(AgentStreamEmitter, {\n emit: onEvent\n ? (event) =>\n Effect.sync(() => {\n try {\n onEvent(event);\n } catch {\n // Swallow callback errors — a broken forwarder must not kill the run.\n }\n })\n : () => Effect.void,\n });\n","import { Clock, Duration, Effect, Option } from \"effect\";\nimport { Display } from \"./Display.js\";\nimport { PromptError, PromptExpansionTimeoutError } from \"./errors.js\";\nimport type { ExecError } from \"./errors.js\";\nimport type { SandboxService } from \"./SandboxFactory.js\";\n\nconst PROMPT_EXPANSION_TIMEOUT_MS = 30_000;\n\n/**\n * @internal\n * Marker inserted between `!` and the opening backtick for shell blocks that\n * appear in the raw template. The preprocessor only executes marked blocks, so\n * `!`...`` patterns arriving via argument substitution are treated as data.\n * Used only by `substitutePromptArgs`; not part of the public API.\n */\nexport const SHELL_BLOCK_MARKER = \"\\u0001\";\n\nconst MARKED_SHELL_BLOCK_PATTERN = new RegExp(\n `!${SHELL_BLOCK_MARKER}\\`([^\\`]+)\\``,\n \"gu\",\n);\n\ninterface ShellBlock {\n readonly text: string;\n readonly command: string;\n readonly index: number;\n}\n\n/** Runs one block's command in the sandbox and returns its trimmed stdout. */\nconst expandBlock = (\n block: ShellBlock,\n sandbox: SandboxService,\n cwd: string,\n): Effect.Effect<\n ShellBlock & { readonly output: string },\n ExecError | PromptError | PromptExpansionTimeoutError\n> =>\n Effect.gen(function* () {\n const { command } = block;\n const start = yield* Clock.currentTimeMillis;\n const maybeResult = yield* sandbox\n .exec(command, { cwd })\n .pipe(Effect.timeoutOption(Duration.millis(PROMPT_EXPANSION_TIMEOUT_MS)));\n if (Option.isNone(maybeResult)) {\n const elapsedMs = (yield* Clock.currentTimeMillis) - start;\n return yield* new PromptExpansionTimeoutError({\n message: `Shell expression \\`${command}\\` timed out after ${elapsedMs}ms`,\n timeoutMs: PROMPT_EXPANSION_TIMEOUT_MS,\n expression: command,\n elapsedMs,\n });\n }\n const execResult = maybeResult.value;\n if (execResult.exitCode !== 0) {\n return yield* new PromptError({\n message: `Command \\`${command}\\` exited with code ${execResult.exitCode}: ${execResult.stderr}`,\n exitCode: execResult.exitCode,\n });\n }\n return { ...block, output: execResult.stdout.trimEnd() };\n });\n\n/**\n * Splices each output in place of its block. Blocks are in prompt order and\n * don't overlap, so one forward pass over `prompt` works.\n */\nconst spliceOutputs = (\n prompt: string,\n expanded: readonly (ShellBlock & { readonly output: string })[],\n): string => {\n let result = \"\";\n let cursor = 0;\n for (const { index, text, output } of expanded) {\n result += prompt.slice(cursor, index) + output;\n cursor = index + text.length;\n }\n result += prompt.slice(cursor);\n return result.replaceAll(SHELL_BLOCK_MARKER, \"\");\n};\n\nexport const preprocessPrompt = (\n prompt: string,\n sandbox: SandboxService,\n cwd: string,\n): Effect.Effect<\n string,\n ExecError | PromptError | PromptExpansionTimeoutError,\n Display\n> => {\n // The capture group is required, so the `?? \"\"` fallback never applies.\n const blocks = [...prompt.matchAll(MARKED_SHELL_BLOCK_PATTERN)].map(\n (match): ShellBlock => ({\n text: match[0],\n command: match[1] ?? \"\",\n index: match.index,\n }),\n );\n\n if (blocks.length === 0) {\n return Effect.succeed(prompt.replaceAll(SHELL_BLOCK_MARKER, \"\"));\n }\n\n return Effect.gen(function* () {\n const display = yield* Display;\n return yield* display.taskLog(\"Expanding shell expressions\", (message) =>\n Effect.gen(function* () {\n // Execute all commands in parallel\n const expanded = yield* Effect.all(\n blocks.map((block) => expandBlock(block, sandbox, cwd)),\n { concurrency: \"unbounded\" },\n );\n\n // Log per-command token counts\n for (const { command, output } of expanded) {\n const tokens = Math.ceil(output.length / 4);\n message(`${command} → ~${tokens} tokens`);\n }\n\n return spliceOutputs(prompt, expanded);\n }),\n );\n });\n};\n","const LENGTH_THRESHOLD = 80;\nconst DEBOUNCE_MS = 50;\n\n/**\n * Sentence-boundary pattern: period, exclamation, or question mark followed by a space.\n */\nconst SENTENCE_BOUNDARY_RE = /[.!?] $/u;\n\n/**\n * Buffers streaming text deltas and flushes them as readable multi-word chunks.\n *\n * Flush triggers:\n * - Newline character in the accumulated buffer\n * - Sentence boundary (`. `, `! `, `? ` at end of buffer)\n * - Buffer exceeds ~80 characters\n * - Debounce timer (~50ms of no new writes)\n */\nexport class TextDeltaBuffer {\n private buffer = \"\";\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly onFlush: (text: string) => void;\n\n constructor(onFlush: (text: string) => void) {\n this.onFlush = onFlush;\n }\n\n write(text: string): void {\n if (text.length === 0) {\n return;\n }\n this.buffer += text;\n this.clearTimer();\n\n if (this.shouldFlush()) {\n this.doFlush();\n return;\n }\n\n this.timer = setTimeout(() => {\n this.doFlush();\n }, DEBOUNCE_MS);\n }\n\n /** Force-flush any buffered text. */\n flush(): void {\n this.clearTimer();\n this.doFlush();\n }\n\n /** Flush remaining buffer and clean up. */\n dispose(): void {\n this.flush();\n }\n\n private shouldFlush(): boolean {\n if (this.buffer.includes(\"\\n\")) {\n return true;\n }\n if (SENTENCE_BOUNDARY_RE.test(this.buffer)) {\n return true;\n }\n if (this.buffer.length >= LENGTH_THRESHOLD) {\n return true;\n }\n return false;\n }\n\n private doFlush(): void {\n if (this.buffer.length === 0) {\n return;\n }\n const text = this.buffer;\n this.buffer = \"\";\n this.onFlush(text);\n }\n\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n","/**\n * How full an iteration's context window was: the input side of its LAST\n * model call, cache reads and cache writes included (see ADR 0023).\n *\n * Each model call's input already holds the whole conversation so far, so the\n * last call is the context size. Never sum calls, and never use a total the\n * agent reports for a turn or a session: those grow with every tool\n * round-trip and can exceed the window.\n */\nexport interface ContextWindow {\n /** Input tokens of the last model call, cached and uncached together. */\n readonly tokens: number;\n /** The model's context window size, only when the agent itself reports it. */\n readonly limit?: number;\n}\n\n/**\n * Format a context window as `47k`, or `32k / 258k` when the limit is known.\n * Tokens round up (never understate use); the limit rounds down (never\n * overstate room).\n */\nexport const formatContextWindow = (contextWindow: ContextWindow): string => {\n const used = `${Math.ceil(contextWindow.tokens / 1000)}k`;\n return contextWindow.limit === undefined\n ? used\n : `${used} / ${Math.floor(contextWindow.limit / 1000)}k`;\n};\n\n/**\n * Build `Context window: NNNk` lines, one per iteration that has a context\n * window. Iterations without one (e.g. cursor, which reports no per-call\n * figure) are skipped.\n */\nexport const buildContextWindowLines = (\n iterations: readonly { readonly contextWindow?: ContextWindow }[],\n): string[] =>\n iterations.flatMap((it) =>\n it.contextWindow\n ? [`Context window: ${formatContextWindow(it.contextWindow)}`]\n : [],\n );\n","import { Deferred, Duration, Effect, Fiber, Runtime } from \"effect\";\nimport { AgentStreamEmitter } from \"./AgentStreamEmitter.js\";\nimport { Display } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport {\n AgentError,\n AgentIdleTimeoutError,\n SessionCaptureError,\n} from \"./errors.js\";\nimport type { SandboxError } from \"./errors.js\";\nimport type { SandboxService } from \"./SandboxFactory.js\";\nimport { SandboxFactory } from \"./SandboxFactory.js\";\nimport { withSandboxLifecycle } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type { AgentProvider, IterationUsage } from \"./AgentProvider.js\";\nimport type { Timeouts } from \"./run.js\";\nimport { TextDeltaBuffer } from \"./TextDeltaBuffer.js\";\nimport { buildContextWindowLines } from \"./ContextWindow.js\";\nimport type { ContextWindow } from \"./ContextWindow.js\";\n\nexport type { ParsedStreamEvent, IterationUsage } from \"./AgentProvider.js\";\n\nconst IDLE_WARNING_INTERVAL_MS = 60_000;\n\nconst invokeAgent = (\n sandbox: SandboxService,\n sandboxRepoDir: string,\n prompt: string,\n provider: AgentProvider,\n idleTimeoutMs: number,\n completionTimeoutMs: number,\n completionSignals: readonly string[],\n onText: (text: string) => void,\n onToolCall: (name: string, formattedArgs: string) => void,\n onRawLine: (line: string) => void,\n onIdleWarning: (minutes: number) => void,\n onCompletionTimeout: (timeoutMs: number) => void,\n onContextWindow: (contextWindow: ContextWindow) => void,\n idleWarningIntervalMs: number = IDLE_WARNING_INTERVAL_MS,\n resumeSession?: string,\n forkSession?: boolean,\n signal?: AbortSignal,\n): Effect.Effect<\n { result: string; sessionId?: string; usage?: IterationUsage },\n SandboxError\n> =>\n Effect.gen(function* () {\n let resultText = \"\";\n // Last error the agent reported in its own stream (see ParsedStreamEvent).\n let streamError: string | undefined;\n let sessionId: string | undefined;\n let usage: IterationUsage | undefined;\n // Accumulated text/result output, scanned for the completion signal so a\n // hanging process can be force-completed once the signal is in the buffer\n // (see ADR 0019).\n let accumulatedOutput = \"\";\n\n // Deferred that fails when the idle timer fires (no signal seen).\n const timeoutSignal = yield* Deferred.make<never, AgentIdleTimeoutError>();\n // Deferred that resolves successfully when the completion-grace timer\n // fires (signal seen but process hasn't exited). Resolving lets the race\n // hand control back to the orchestrator with the buffered output, which\n // still contains the signal so the existing completionSignal check works.\n const completionTimeoutDeferred = yield* Deferred.make<{\n result: string;\n sessionId?: string;\n usage?: IterationUsage;\n }>();\n // Timer and abort callbacks fire outside any fiber; they fork onto the\n // surrounding runtime rather than a fresh default one.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n let timeoutFiber: Fiber.RuntimeFiber<unknown, unknown> | null = null;\n let completionDetected = false;\n\n // Periodic idle warning state\n let warningFiber: Fiber.RuntimeFiber<unknown, unknown> | null = null;\n let idleMinuteCounter = 0;\n // Set once the race below settles (success, failure, abort, idle or\n // completion timeout). The losing exec may still be streaming — e.g. a\n // `docker exec` outliving the run — and every line would otherwise fork\n // fresh timer fibers nobody interrupts, keeping the host process alive.\n let settled = false;\n\n const interruptFiber = (\n fiber: Fiber.RuntimeFiber<unknown, unknown> | null,\n ) => {\n if (fiber !== null) {\n runFork(Fiber.interrupt(fiber));\n }\n };\n\n const startWarningInterval = () => {\n interruptFiber(warningFiber);\n idleMinuteCounter = 0;\n warningFiber = runFork(\n Effect.gen(function* () {\n while (true) {\n yield* Effect.sleep(Duration.millis(idleWarningIntervalMs));\n idleMinuteCounter++;\n onIdleWarning(idleMinuteCounter);\n }\n }),\n );\n };\n\n const resetTimer = () => {\n interruptFiber(timeoutFiber);\n if (completionDetected) {\n // Post-signal grace window — successful resolution on expiry.\n timeoutFiber = runFork(\n Effect.gen(function* () {\n yield* Effect.sleep(Duration.millis(completionTimeoutMs));\n onCompletionTimeout(completionTimeoutMs);\n yield* Deferred.succeed(completionTimeoutDeferred, {\n result: resultText || accumulatedOutput,\n sessionId,\n usage,\n });\n }),\n );\n } else {\n // Pre-signal idle window — failure on expiry.\n timeoutFiber = runFork(\n Effect.gen(function* () {\n yield* Effect.sleep(Duration.millis(idleTimeoutMs));\n yield* Deferred.fail(\n timeoutSignal,\n new AgentIdleTimeoutError({\n message: `Agent idle for ${idleTimeoutMs / 1000} seconds — no output received. Increase the idleTimeoutSeconds option to allow longer silences.`,\n timeoutMs: idleTimeoutMs,\n }),\n );\n }),\n );\n // Reset warning interval on activity, idle-phase only.\n startWarningInterval();\n }\n };\n\n // Deferred that will be resolved (as a defect) when the AbortSignal fires.\n // Uses Effect.die so the abort reason propagates as-is to run().\n const abortDeferred = yield* Deferred.make<never>();\n let abortCleanup: (() => void) | null = null;\n if (signal) {\n if (signal.aborted) {\n return yield* Effect.die(signal.reason);\n }\n const onAbort = () => {\n runFork(Deferred.die(abortDeferred, signal.reason));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n abortCleanup = () => {\n signal.removeEventListener(\"abort\", onAbort);\n };\n }\n\n resetTimer();\n\n const execEffect = Effect.gen(function* () {\n const printCmd = provider.buildPrintCommand({\n prompt,\n dangerouslySkipPermissions: true,\n resumeSession,\n forkSession,\n });\n const execResult = yield* sandbox.exec(printCmd.command, {\n onLine: (line) => {\n if (settled) {\n return;\n }\n // Surface the raw line FIRST so verbose mode/forwarders see every\n // stdout line the agent produced, including ones parseStreamLine\n // drops. Errors thrown by the callback are caught by the emitter\n // layer; isolate the parser path here so a broken forwarder cannot\n // skip parsing.\n try {\n onRawLine(line);\n } catch {\n // Swallow — must not skip parsing/timer logic below.\n }\n for (const parsed of provider.parseStreamLine(line)) {\n if (parsed.type === \"text\") {\n onText(parsed.text);\n accumulatedOutput += parsed.text;\n } else if (parsed.type === \"context_window\") {\n onContextWindow(parsed.contextWindow);\n } else if (parsed.type === \"result\") {\n resultText = parsed.result;\n accumulatedOutput += parsed.result;\n } else if (parsed.type === \"tool_call\") {\n onToolCall(parsed.name, parsed.args);\n } else if (parsed.type === \"session_id\") {\n sessionId = parsed.sessionId;\n } else if (parsed.type === \"usage\") {\n usage = parsed.usage;\n } else if (parsed.type === \"error\") {\n streamError = parsed.message;\n }\n }\n // Check for the completion signal AFTER parsing this line so the\n // accumulator contains everything seen so far. Flip to the\n // completion-grace timer the first time the signal appears.\n if (\n !completionDetected &&\n completionSignals.some((sig) => accumulatedOutput.includes(sig))\n ) {\n completionDetected = true;\n interruptFiber(warningFiber);\n warningFiber = null;\n }\n resetTimer();\n },\n cwd: sandboxRepoDir,\n stdin: printCmd.stdin,\n });\n\n if (execResult.exitCode !== 0) {\n // Prefer stderr; fall back to the stream's own error, then resultText\n // (from parsed stream events), then to the tail of raw stdout (last\n // 20 non-empty lines).\n let errorDetail = execResult.stderr;\n if (!errorDetail.trim()) {\n errorDetail = streamError ?? \"\";\n }\n if (!errorDetail.trim()) {\n errorDetail = resultText;\n }\n if (!errorDetail.trim()) {\n const lines = execResult.stdout.split(\"\\n\").filter((l) => l.trim());\n errorDetail = lines.slice(-20).join(\"\\n\");\n }\n return yield* new AgentError({\n message: `${provider.name} exited with code ${execResult.exitCode}:\\n${errorDetail}`,\n });\n }\n\n // Some agents (pi, opencode) exit 0 after reporting a failure in their\n // stream. Treat the reported error as authoritative.\n if (streamError !== undefined) {\n return yield* new AgentError({\n message: `${provider.name} reported an error:\\n${streamError}`,\n });\n }\n\n return { result: resultText || execResult.stdout, sessionId, usage };\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n interruptFiber(timeoutFiber);\n timeoutFiber = null;\n interruptFiber(warningFiber);\n warningFiber = null;\n }),\n ),\n );\n\n let raced: Effect.Effect<\n { result: string; sessionId?: string; usage?: IterationUsage },\n AgentIdleTimeoutError | SandboxError\n > = Effect.raceFirst(execEffect, Deferred.await(timeoutSignal));\n raced = Effect.raceFirst(raced, Deferred.await(completionTimeoutDeferred));\n if (signal) {\n raced = Effect.raceFirst(raced, Deferred.await(abortDeferred));\n }\n\n return yield* raced.pipe(\n Effect.ensuring(\n Effect.sync(() => {\n settled = true;\n abortCleanup?.();\n interruptFiber(timeoutFiber);\n timeoutFiber = null;\n interruptFiber(warningFiber);\n warningFiber = null;\n }),\n ),\n );\n });\n\nconst DEFAULT_COMPLETION_SIGNAL = \"<promise>COMPLETE</promise>\";\nconst DEFAULT_IDLE_TIMEOUT_SECONDS = 10 * 60; // 600 seconds\nconst DEFAULT_COMPLETION_TIMEOUT_SECONDS = 60;\n\nexport interface OrchestrateOptions {\n readonly hostRepoDir: string;\n readonly iterations: number;\n readonly hooks?: SandboxHooks;\n readonly prompt: string;\n readonly branch?: string;\n readonly provider: AgentProvider;\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. If the agent produces no output for this long, it fails with AgentIdleTimeoutError. Default: 600 (10 minutes) */\n readonly idleTimeoutSeconds?: number;\n /**\n * Grace window in seconds after a completion signal is observed in the\n * agent's output. The agent process is expected to exit shortly after\n * emitting the signal; if it does not (because a spawned child is keeping\n * stdout open — see ADR 0019), this timer fires and the iteration resolves\n * successfully with the buffered output. Resets on every subsequent output\n * line, so trailing data (token-usage events, terminal `result` events,\n * structured-output tags) is still captured. Default: 60 seconds.\n */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run, prepended to status messages as [name] */\n readonly name?: string;\n /** @internal Test-only override for the idle warning interval in milliseconds. Default: 60000 (1 minute). */\n readonly _idleWarningIntervalMs?: number;\n /** Resume a prior Claude Code session by ID. Applied to iteration 1 only. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it — the parent JSONL stays intact and the agent writes a new session\n * under a fresh id. Applied to iteration 1 only. See ADR 0018.\n */\n readonly forkSession?: boolean;\n /** An AbortSignal that cancels the orchestration when aborted. */\n readonly signal?: AbortSignal;\n /** When true, skip prompt expansion (shell expression evaluation). Set for dynamic inline prompts. */\n readonly skipPromptExpansion?: boolean;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** Forwarded to `withSandboxLifecycle` — see `SandboxLifecycleOptions.keepSourceBranch`. */\n readonly keepSourceBranch?: boolean;\n}\n\n/** Per-iteration result carrying an optional session ID. */\nexport interface IterationResult {\n /** Claude Code session ID extracted from the init line, or undefined for non-Claude agents. */\n readonly sessionId?: string;\n /** Absolute host path to the captured session JSONL, or undefined when capture is disabled or provider is non-Claude. */\n readonly sessionFilePath?: string;\n /** Token usage snapshot from the last assistant message in the session, or undefined when capture is disabled or provider does not support usage parsing. */\n readonly usage?: IterationUsage;\n /** Input tokens of the iteration's last model call (cache included), plus the model's limit when the agent reports it. Undefined when the agent reports no per-call figure. */\n readonly contextWindow?: ContextWindow;\n}\n\nexport interface OrchestrateResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n readonly stdout: string;\n readonly commits: { sha: string }[];\n readonly branch: string;\n /** Host path to the preserved worktree from the last iteration, set when the worktree was left behind due to uncommitted changes on a successful run. */\n readonly preservedWorktreePath?: string;\n}\n\nexport const orchestrate = (\n options: OrchestrateOptions,\n): Effect.Effect<\n OrchestrateResult,\n SandboxError,\n SandboxFactory | Display | AgentStreamEmitter\n> => {\n const idleTimeoutMs =\n (options.idleTimeoutSeconds ?? DEFAULT_IDLE_TIMEOUT_SECONDS) * 1000;\n const completionTimeoutMs =\n (options.completionTimeoutSeconds ?? DEFAULT_COMPLETION_TIMEOUT_SECONDS) *\n 1000;\n return Effect.gen(function* () {\n const factory = yield* SandboxFactory;\n const display = yield* Display;\n const streamEmitter = yield* AgentStreamEmitter;\n // The agent's stream callbacks fire outside any fiber; they fork their\n // display and emitter effects onto the surrounding runtime.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n const { hostRepoDir, iterations, hooks, prompt, branch, provider } =\n options;\n const { sessionStorage } = provider;\n let completionSignals: string[];\n if (options.completionSignal === undefined) {\n completionSignals = [DEFAULT_COMPLETION_SIGNAL];\n } else if (Array.isArray(options.completionSignal)) {\n completionSignals = options.completionSignal;\n } else {\n completionSignals = [options.completionSignal];\n }\n\n const label = (msg: string): string =>\n options.name !== undefined && options.name !== \"\"\n ? `[${options.name}] ${msg}`\n : msg;\n\n const allCommits: { sha: string }[] = [];\n const allIterations: IterationResult[] = [];\n let allStdout = \"\";\n let resolvedBranch = \"\";\n let iterationPreservedPath: string | undefined;\n\n // Helper: check abort signal and bail via defect so run() can\n // re-throw the signal's reason verbatim (no Sandcastle wrapping).\n const checkAbort = (): Effect.Effect<void> =>\n options.signal?.aborted === true\n ? Effect.die(options.signal.reason)\n : Effect.void;\n\n for (let i = 1; i <= iterations; i++) {\n yield* checkAbort();\n yield* display.status(label(`Iteration ${i}/${iterations}`), \"info\");\n\n const sandboxResult = yield* factory\n .withSandbox(\n (\n { hostWorktreePath, sandboxRepoPath, applyToHost, bindMountHandle },\n sandbox,\n ) =>\n withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: sandboxRepoPath,\n hooks,\n branch,\n hostWorktreePath,\n applyToHost,\n signal: options.signal,\n timeouts: options.timeouts,\n keepSourceBranch: options.keepSourceBranch,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n // Resume session: transfer JSONL from host to sandbox before iteration 1\n const iterationResumeSession =\n i === 1 ? options.resumeSession : undefined;\n const iterationForkSession =\n i === 1 ? options.forkSession : undefined;\n if (\n iterationResumeSession !== undefined &&\n iterationResumeSession !== \"\" &&\n bindMountHandle &&\n sessionStorage\n ) {\n yield* display.status(label(\"Resuming session\"), \"info\");\n yield* Effect.tryPromise({\n try: () =>\n sessionStorage.resumeIntoSandbox({\n hostCwd: hostRepoDir,\n sandboxCwd: ctx.sandboxRepoDir,\n sessionId: iterationResumeSession,\n handle: bindMountHandle,\n }),\n catch: (e) =>\n new SessionCaptureError({\n message: `Session resume failed: ${e instanceof Error ? e.message : String(e)}`,\n sessionId: iterationResumeSession,\n }),\n });\n }\n\n // Preprocess prompt (run !`command` expressions inside sandbox).\n // Inline prompts pass through literally — skip expansion.\n const fullPrompt =\n options.skipPromptExpansion === true\n ? prompt\n : yield* preprocessPrompt(\n prompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n yield* display.status(label(\"Agent started\"), \"success\");\n\n // Invoke the agent — buffer text deltas so Pi's single-token\n // chunks are displayed as readable multi-word lines.\n const textBuffer = new TextDeltaBuffer((chunk) => {\n runFork(display.textChunk(chunk));\n runFork(\n streamEmitter.emit({\n type: \"text\",\n message: chunk,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n });\n const onText = (text: string) => {\n textBuffer.write(text);\n };\n const onToolCall = (name: string, formattedArgs: string) => {\n textBuffer.flush();\n runFork(display.toolCall(name, formattedArgs));\n runFork(\n streamEmitter.emit({\n type: \"toolCall\",\n name,\n formattedArgs,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n };\n const onRawLine = (line: string) => {\n runFork(\n streamEmitter.emit({\n type: \"raw\",\n line,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n };\n const onIdleWarning = (minutes: number) => {\n const msg =\n minutes === 1\n ? \"Agent idle for 1 minute\"\n : `Agent idle for ${minutes} minutes`;\n runFork(display.status(label(msg), \"warn\"));\n };\n const onCompletionTimeout = (timeoutMs: number) => {\n runFork(\n display.status(\n label(\n `Completion signal seen but agent process is hanging — force-completing after ${timeoutMs / 1000}s grace window.`,\n ),\n \"warn\",\n ),\n );\n };\n // Last call wins: each event is one model call, and the last\n // call's input is the context size (see ContextWindow).\n let contextWindow: ContextWindow | undefined;\n const onContextWindow = (cw: ContextWindow) => {\n contextWindow = cw;\n };\n const {\n result: agentOutput,\n sessionId,\n usage: streamUsage,\n } = yield* invokeAgent(\n ctx.sandbox,\n ctx.sandboxRepoDir,\n fullPrompt,\n provider,\n idleTimeoutMs,\n completionTimeoutMs,\n completionSignals,\n onText,\n onToolCall,\n onRawLine,\n onIdleWarning,\n onCompletionTimeout,\n onContextWindow,\n options._idleWarningIntervalMs,\n iterationResumeSession,\n iterationForkSession,\n options.signal,\n );\n\n // Flush any remaining buffered text deltas\n textBuffer.dispose();\n\n yield* display.status(label(\"Agent stopped\"), \"info\");\n\n // Capture session while sandbox is still alive. Usage from the\n // stream (e.g. Codex's turn.completed) is the baseline; a\n // session-parsed value below overrides it when available.\n let sessionFilePath: string | undefined;\n let usage: IterationUsage | undefined = streamUsage;\n if (\n provider.captureSessions &&\n sessionStorage &&\n sessionId !== undefined &&\n sessionId !== \"\" &&\n bindMountHandle\n ) {\n yield* display.status(label(\"Capturing session\"), \"info\");\n yield* Effect.tryPromise({\n try: () =>\n sessionStorage.captureToHost({\n hostCwd: hostRepoDir,\n sandboxCwd: ctx.sandboxRepoDir,\n sessionId,\n handle: bindMountHandle,\n }),\n catch: (e) =>\n new SessionCaptureError({\n message: `Session capture failed: ${e instanceof Error ? e.message : String(e)}`,\n sessionId,\n }),\n });\n sessionFilePath = sessionStorage.hostSessionFilePath(\n hostRepoDir,\n sessionId,\n );\n\n // Parse token usage and the context window from the\n // captured session JSONL\n if (\n provider.parseSessionUsage ||\n provider.parseSessionContextWindow\n ) {\n const content = yield* Effect.promise(() =>\n sessionStorage\n .readHostSession(hostRepoDir, sessionId)\n .catch(() => undefined as string | undefined),\n );\n if (content !== undefined && content !== \"\") {\n const parsedUsage =\n provider.parseSessionUsage?.(content);\n if (parsedUsage) {\n usage = parsedUsage;\n }\n const parsedContextWindow =\n provider.parseSessionContextWindow?.(content);\n if (parsedContextWindow) {\n contextWindow = parsedContextWindow;\n }\n }\n }\n }\n\n // Check completion signal\n const matchedSignal = completionSignals.find((sig) =>\n agentOutput.includes(sig),\n );\n return {\n completionSignal: matchedSignal,\n stdout: agentOutput,\n sessionId,\n sessionFilePath,\n usage,\n contextWindow,\n } as const;\n }),\n ),\n )\n .pipe(\n // A failed iteration ends the run before run() prints the context\n // window lines, so print the completed iterations' lines here.\n Effect.tapError(() =>\n Effect.forEach(buildContextWindowLines(allIterations), (line) =>\n display.text(line),\n ),\n ),\n );\n\n const lifecycleResult = sandboxResult.value;\n iterationPreservedPath = sandboxResult.preservedWorktreePath;\n\n allCommits.push(...lifecycleResult.commits);\n allStdout += lifecycleResult.result.stdout;\n resolvedBranch = lifecycleResult.branch;\n\n allIterations.push({\n sessionId: lifecycleResult.result.sessionId,\n sessionFilePath: lifecycleResult.result.sessionFilePath,\n usage: lifecycleResult.result.usage,\n contextWindow: lifecycleResult.result.contextWindow,\n });\n\n if (lifecycleResult.result.completionSignal !== undefined) {\n yield* display.status(\n label(`Agent signaled completion after ${i} iteration(s).`),\n \"success\",\n );\n return {\n iterations: allIterations,\n completionSignal: lifecycleResult.result.completionSignal,\n stdout: allStdout,\n commits: allCommits,\n branch: resolvedBranch,\n preservedWorktreePath: iterationPreservedPath,\n };\n }\n }\n\n yield* display.status(\n label(`Reached max iterations (${iterations}).`),\n \"info\",\n );\n return {\n iterations: allIterations,\n completionSignal: undefined,\n stdout: allStdout,\n commits: allCommits,\n branch: resolvedBranch,\n preservedWorktreePath: iterationPreservedPath,\n };\n });\n};\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { PromptError } from \"./errors.js\";\n\nexport interface ResolvePromptOptions {\n readonly prompt?: string;\n readonly promptFile?: string;\n}\n\n/**\n * The resolved prompt text plus the source it came from.\n *\n * - `inline`: came from `prompt: \"...\"` — delivered to the agent verbatim.\n * No prompt argument substitution, no prompt expansion, no built-in args.\n * - `template`: came from `promptFile` — eligible for `{{KEY}}` substitution\n * and `` !`command` `` expansion.\n */\nexport interface ResolvedPrompt {\n readonly text: string;\n readonly source: \"inline\" | \"template\";\n}\n\nexport const resolvePrompt = (\n options: ResolvePromptOptions,\n): Effect.Effect<ResolvedPrompt, PromptError, FileSystem.FileSystem> => {\n const { prompt, promptFile } = options;\n\n if (prompt !== undefined && promptFile !== undefined) {\n return Effect.fail(\n new PromptError({\n message: \"Cannot provide both prompt and promptFile\",\n }),\n );\n }\n\n if (prompt !== undefined) {\n return Effect.succeed({ text: prompt, source: \"inline\" });\n }\n\n if (promptFile === undefined) {\n return Effect.fail(\n new PromptError({\n message:\n \"Must provide either prompt or promptFile. Pass prompt: '...' or promptFile: './.sandcastle/prompt.md' to run().\",\n }),\n );\n }\n\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const text = yield* fs.readFileString(promptFile).pipe(\n Effect.mapError(\n (e) =>\n new PromptError({\n message: `Failed to read prompt from ${promptFile}: ${String(e)}`,\n }),\n ),\n );\n return { text, source: \"template\" as const };\n });\n};\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { join } from \"node:path\";\n\nconst ESCAPES: Record<string, string> = {\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n \"\\\\\": \"\\\\\",\n};\n\n/** Strips matching quotes; double-quoted values also expand \\n, \\r, \\t, \\\\. */\nconst unquote = (value: string): string => {\n const isDoubleQuoted =\n value.length >= 2 && value.startsWith('\"') && value.at(-1) === '\"';\n const isSingleQuoted =\n value.length >= 2 && value.startsWith(\"'\") && value.at(-1) === \"'\";\n if (isSingleQuoted) {\n return value.slice(1, -1);\n }\n if (!isDoubleQuoted) {\n return value;\n }\n return value\n .slice(1, -1)\n .replaceAll(/\\\\(?<escape>[nrt\\\\])/gu, (_, ch: string) => ESCAPES[ch] ?? ch);\n};\n\n/** One `KEY=value` line as a pair, or undefined for blanks and comments. */\nconst parseEnvLine = (line: string): [string, string] | undefined => {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) {\n return undefined;\n }\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) {\n return undefined;\n }\n const key = trimmed.slice(0, eqIndex).trim();\n return [key, unquote(trimmed.slice(eqIndex + 1).trim())];\n};\n\nconst parseEnvFile = (\n filePath: string,\n): Effect.Effect<Record<string, string>, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const content = yield* fs\n .readFileString(filePath)\n .pipe(Effect.catchAll(() => Effect.succeed(null)));\n if (content === null) {\n return {};\n }\n const entries = content\n .split(\"\\n\")\n .map((line) => parseEnvLine(line))\n .filter((entry) => entry !== undefined);\n return Object.fromEntries(entries);\n });\n\n/**\n * Resolve all env vars from .env files with process.env fallback.\n *\n * Precedence: .sandcastle/.env > process.env\n * Only keys declared in .sandcastle/.env are resolved from process.env.\n * Repo root .env is not part of the resolution chain.\n */\nexport const resolveEnv = (\n repoDir: string,\n): Effect.Effect<Record<string, string>, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const sandcastleEnv = yield* parseEnvFile(\n join(repoDir, \".sandcastle\", \".env\"),\n );\n\n const result: Record<string, string> = {};\n for (const [key, fileValue] of Object.entries(sandcastleEnv)) {\n const value = fileValue || (process.env[key] ?? \"\");\n if (value) {\n result[key] = value;\n }\n }\n\n return result;\n });\n","/**\n * Merge env vars from the env resolver, agent provider, and sandbox provider.\n *\n * Provider env (agent + sandbox) overrides env resolver output for shared keys.\n * Agent and sandbox provider env must NOT have overlapping keys — if they do,\n * this function throws.\n */\nexport const mergeProviderEnv = (options: {\n readonly resolvedEnv: Record<string, string>;\n readonly agentProviderEnv: Record<string, string>;\n readonly sandboxProviderEnv: Record<string, string>;\n}): Record<string, string> => {\n const { resolvedEnv, agentProviderEnv, sandboxProviderEnv } = options;\n\n // Check for overlapping keys between agent and sandbox provider env\n const agentKeys = Object.keys(agentProviderEnv);\n const sandboxKeys = new Set(Object.keys(sandboxProviderEnv));\n const overlapping = agentKeys.filter((k) => sandboxKeys.has(k));\n\n if (overlapping.length > 0) {\n throw new Error(\n `Overlapping env keys between agent provider and sandbox provider: ${overlapping.join(\", \")}`,\n );\n }\n\n return {\n ...resolvedEnv,\n ...sandboxProviderEnv,\n ...agentProviderEnv,\n };\n};\n","import { Effect } from \"effect\";\nimport { Display } from \"./Display.js\";\nimport { PromptError } from \"./errors.js\";\nimport { SHELL_BLOCK_MARKER } from \"./PromptPreprocessor.js\";\n\nconst SHELL_BLOCK_PATTERN = /!`(?<command>[^`]+)`/gu;\n\n/**\n * A map of named values used for prompt argument substitution.\n * Each key corresponds to a `{{KEY}}` placeholder in the prompt; the value\n * replaces it before the prompt is passed to the agent.\n */\nexport type PromptArgs = Record<string, string | number | boolean>;\n\n/**\n * Prompt argument keys that Sandcastle injects automatically.\n * These cannot be overridden via `promptArgs`.\n */\nexport const BUILT_IN_PROMPT_ARG_KEYS = [\n \"SOURCE_BRANCH\",\n \"TARGET_BRANCH\",\n] as const;\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(?<key>[A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}/gu;\n\n/**\n * The key of every `{{KEY}}` placeholder in `text`, in order, repeats\n * included. The `key` group is required, so the `?? \"\"` never applies.\n */\nconst placeholderKeys = (text: string): string[] =>\n [...text.matchAll(PLACEHOLDER_PATTERN)].map((m) => m.groups?.[\"key\"] ?? \"\");\n\n/**\n * Validates that the user has not provided any built-in prompt argument keys.\n * Fails with a PromptError if any built-in key is found in `args`.\n */\n/**\n * Fails if the user passed any `promptArgs` alongside an inline prompt.\n * Inline prompts are delivered to the agent verbatim, so `promptArgs` would\n * silently do nothing. An empty object is treated as absent.\n */\nexport const validateNoArgsWithInlinePrompt = (\n args: PromptArgs,\n): Effect.Effect<void, PromptError> => {\n if (Object.keys(args).length === 0) {\n return Effect.void;\n }\n return Effect.fail(\n new PromptError({\n message:\n 'promptArgs is only supported with promptFile. Inline prompts (prompt: \"...\") are passed to the agent as-is — interpolate values directly in JavaScript, or switch to promptFile to use {{KEY}} substitution.',\n }),\n );\n};\n\nexport const validateNoBuiltInArgOverride = (\n args: PromptArgs,\n): Effect.Effect<void, PromptError> => {\n for (const key of BUILT_IN_PROMPT_ARG_KEYS) {\n if (key in args) {\n return Effect.fail(\n new PromptError({\n message: `\"${key}\" is a built-in prompt argument and cannot be overridden via promptArgs`,\n }),\n );\n }\n }\n return Effect.void;\n};\n\n/**\n * Scans a prompt for `{{KEY}}` placeholders and returns the keys that are\n * missing from `providedArgs`, excluding built-in keys.\n */\nexport const findMissingPromptArgKeys = (\n prompt: string,\n providedArgs: PromptArgs,\n): string[] => {\n const builtInSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n const seen = new Set<string>();\n const missing: string[] = [];\n\n for (const key of placeholderKeys(prompt)) {\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n if (builtInSet.has(key)) {\n continue;\n }\n if (\n key in providedArgs &&\n providedArgs[key] !== null &&\n providedArgs[key] !== undefined\n ) {\n continue;\n }\n missing.push(key);\n }\n\n return missing;\n};\n\nconst HTML_COMMENT_PATTERN = /<!--[\\s\\S]*?(?:-->|$)/gu;\n\nconst markShellBlocks = (prompt: string): string => {\n const commentRanges = [...prompt.matchAll(HTML_COMMENT_PATTERN)].map(\n (m) => [m.index, m.index + m[0].length] as const,\n );\n return prompt.replaceAll(SHELL_BLOCK_PATTERN, (block, command, offset) =>\n commentRanges.some(([start, end]) => offset >= start && offset < end)\n ? block\n : `!${SHELL_BLOCK_MARKER}\\`${command}\\``,\n );\n};\n\n/** Strips shell-block markers from string arg values so they can't be forged. */\nconst sanitizeArgs = (args: PromptArgs): PromptArgs =>\n Object.fromEntries(\n Object.entries(args).map(([key, value]) => [\n key,\n typeof value === \"string\"\n ? value.replaceAll(SHELL_BLOCK_MARKER, \"\")\n : value,\n ]),\n );\n\n/**\n * Check for missing keys (placeholder in prompt but no matching arg, or\n * a present-but-nullish value supplied by an untyped caller — e.g. an\n * orchestrator building args from JSON.parse).\n */\nconst checkReferencedArgs = (\n referencedKeys: ReadonlySet<string>,\n args: PromptArgs,\n): Effect.Effect<void, PromptError> =>\n Effect.gen(function* () {\n for (const key of referencedKeys) {\n if (!(key in args)) {\n return yield* new PromptError({\n message: `Prompt argument \"{{${key}}}\" has no matching value in promptArgs`,\n });\n }\n const value = args[key];\n if (value === null || value === undefined) {\n return yield* new PromptError({\n message: `Prompt argument \"{{${key}}}\" has value ${value === null ? \"null\" : \"undefined\"} in promptArgs`,\n });\n }\n }\n });\n\n/**\n * Warn about unused keys (arg provided but no matching placeholder).\n * Skip keys listed in silentKeys (e.g. built-in args).\n */\nconst warnUnusedArgs = (\n args: PromptArgs,\n referencedKeys: ReadonlySet<string>,\n silentKeys: ReadonlySet<string> | undefined,\n): Effect.Effect<void, never, Display> =>\n Effect.gen(function* () {\n const display = yield* Display;\n for (const key of Object.keys(args)) {\n if (!referencedKeys.has(key) && silentKeys?.has(key) !== true) {\n yield* display.status(\n `Prompt argument \"${key}\" was provided but not referenced in the prompt`,\n \"warn\",\n );\n }\n }\n });\n\nexport const substitutePromptArgs = (\n prompt: string,\n args: PromptArgs,\n silentKeys?: ReadonlySet<string>,\n): Effect.Effect<string, PromptError, Display> => {\n // Mark shell blocks written in the raw template so the preprocessor can\n // distinguish them from `!`...`` patterns that arrive via arg substitution.\n // Shell blocks inside HTML comments stay unmarked, so commented-out examples\n // never run. Comment ranges come from the raw template, so an arg value\n // can't open or close one. Strip any markers already present in raw input\n // so they can't be forged.\n const markedPrompt = markShellBlocks(\n prompt.replaceAll(SHELL_BLOCK_MARKER, \"\"),\n );\n const sanitizedArgs = sanitizeArgs(args);\n const keys = placeholderKeys(markedPrompt);\n\n if (keys.length === 0 && Object.keys(sanitizedArgs).length === 0) {\n return Effect.succeed(markedPrompt);\n }\n\n return Effect.gen(function* () {\n // Collect all keys referenced in the prompt\n const referencedKeys = new Set(keys);\n yield* checkReferencedArgs(referencedKeys, sanitizedArgs);\n yield* warnUnusedArgs(sanitizedArgs, referencedKeys, silentKeys);\n\n // Replace all placeholders with their values\n // Every key was checked above to have a non-null value.\n return markedPrompt.replaceAll(PLACEHOLDER_PATTERN, (_match, key: string) =>\n String(sanitizedArgs[key]),\n );\n });\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// ---------------------------------------------------------------------------\n// Output definition types (branded values for run() overload discrimination)\n// ---------------------------------------------------------------------------\n\n/** Branded output definition for `Output.object({ tag, schema })`. */\nexport interface OutputObjectDefinition<T> {\n readonly _tag: \"object\";\n readonly tag: string;\n readonly schema: StandardSchemaV1<unknown, T>;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction or validation fails. Each retry resumes the failed run's agent\n * session and feeds back a token-efficient description of the error so the\n * agent can re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Claude Code, Codex, Pi). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Branded output definition for `Output.string({ tag })`. */\nexport interface OutputStringDefinition {\n readonly _tag: \"string\";\n readonly tag: string;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction fails. Each retry resumes the failed run's agent session and\n * feeds back a token-efficient description of the error so the agent can\n * re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Claude Code, Codex, Pi). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Union of all output definition shapes accepted by `run()`. */\nexport type OutputDefinition =\n | OutputObjectDefinition<unknown>\n | OutputStringDefinition;\n\n// ---------------------------------------------------------------------------\n// Output namespace — public API\n// ---------------------------------------------------------------------------\n\n/**\n * Helpers for declaring structured output on `run()`.\n *\n * ```ts\n * import { Output, run } from \"@ai-hero/sandcastle\";\n * import { z } from \"zod\";\n *\n * const result = await run({\n * output: Output.object({ tag: \"result\", schema: z.object({ answer: z.number() }) }),\n * // ...\n * });\n * console.log(result.output.answer); // typed as number\n * ```\n */\nexport const Output = {\n /**\n * Declare an object-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are JSON-parsed (with fence-aware\n * unwrapping) and validated against the provided Standard Schema validator.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction or\n * validation fails. Default: `0` (no retries).\n */\n object: <Schema extends StandardSchemaV1>(opts: {\n tag: string;\n schema: Schema;\n maxRetries?: number;\n }): OutputObjectDefinition<StandardSchemaV1.InferOutput<Schema>> => ({\n _tag: \"object\",\n tag: opts.tag,\n schema: opts.schema,\n maxRetries: opts.maxRetries,\n }),\n\n /**\n * Declare a string-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are whitespace-trimmed and returned\n * as a plain string — no JSON parsing, no schema validation.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction fails.\n * Default: `0` (no retries).\n */\n string: (opts: {\n tag: string;\n maxRetries?: number;\n }): OutputStringDefinition => ({\n _tag: \"string\",\n tag: opts.tag,\n maxRetries: opts.maxRetries,\n }),\n} as const;\n\n// ---------------------------------------------------------------------------\n// StructuredOutputError\n// ---------------------------------------------------------------------------\n\nexport interface StructuredOutputErrorOptions {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n readonly cause?: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Thrown by `run()` when structured output extraction or validation fails.\n *\n * Possible failure modes:\n * - The configured XML tag was not found in stdout (`rawMatched` is `undefined`).\n * - The tag contents failed `JSON.parse` (`cause` carries the parse error).\n * - The parsed JSON failed schema validation (`cause` carries the Standard Schema issues).\n *\n * The error carries `commits`, `branch`, and optionally `preservedWorktreePath`\n * so callers can decide recovery without losing the run's side effects.\n *\n * It also carries `sessionId` (and `sessionFilePath` when the session was\n * captured to the host) of the iteration that produced the bad output, so a\n * caller can resume that same session and ask the agent to re-emit corrected\n * output:\n *\n * ```ts\n * try {\n * return await run({ ...opts, output });\n * } catch (e) {\n * if (e instanceof StructuredOutputError && e.sessionId) {\n * return await run({\n * ...opts,\n * output,\n * resumeSession: e.sessionId,\n * prompt: feedback(e),\n * });\n * }\n * throw e;\n * }\n * ```\n */\nexport class StructuredOutputError extends Error {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n override readonly cause: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n /** Session ID of the iteration that produced the bad output, when available. */\n readonly sessionId?: string;\n /** Host path to the captured session JSONL, when the session was captured. */\n readonly sessionFilePath?: string;\n\n constructor(message: string, options: StructuredOutputErrorOptions) {\n super(message);\n this.name = \"StructuredOutputError\";\n this.tag = options.tag;\n this.rawMatched = options.rawMatched;\n this.cause = options.cause;\n this.commits = options.commits;\n this.branch = options.branch;\n this.preservedWorktreePath = options.preservedWorktreePath;\n this.sessionId = options.sessionId;\n this.sessionFilePath = options.sessionFilePath;\n }\n}\n","import { StructuredOutputError } from \"./Output.js\";\nimport type {\n OutputDefinition,\n OutputObjectDefinition,\n OutputStringDefinition,\n} from \"./Output.js\";\n\ninterface ExtractionContext {\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Extract and validate structured output from the agent's stdout.\n *\n * - Finds the **last** occurrence of `<tag>...</tag>` in stdout.\n * - For `Output.object`: unwraps optional Markdown fences, JSON-parses,\n * and validates against the Standard Schema.\n * - For `Output.string`: trims whitespace only.\n *\n * Throws `StructuredOutputError` on missing tag, invalid JSON, or schema failure.\n */\nexport const extractStructuredOutput = async (\n stdout: string,\n definition: OutputDefinition,\n context: ExtractionContext,\n): Promise<unknown> => {\n if (definition._tag === \"object\") {\n return extractObject(stdout, definition, context);\n }\n return extractString(stdout, definition, context);\n};\n\n// ---------------------------------------------------------------------------\n// Object extraction\n// ---------------------------------------------------------------------------\n\nconst extractObject = async <T>(\n stdout: string,\n definition: OutputObjectDefinition<T>,\n context: ExtractionContext,\n): Promise<T> => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n // Fence-aware unwrap + JSON parse\n const unwrapped = unwrapFences(raw.trim());\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(unwrapped);\n } catch (error) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> contains invalid JSON`,\n { tag: definition.tag, rawMatched: raw, cause: error, ...context },\n );\n }\n\n // Standard Schema validation\n const result = await definition.schema[\"~standard\"].validate(parsed);\n\n if (result.issues) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> failed schema validation`,\n {\n tag: definition.tag,\n rawMatched: raw,\n cause: result.issues,\n ...context,\n },\n );\n }\n\n return result.value;\n};\n\n// ---------------------------------------------------------------------------\n// String extraction\n// ---------------------------------------------------------------------------\n\nconst extractString = (\n stdout: string,\n definition: OutputStringDefinition,\n context: ExtractionContext,\n): string => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n return raw.trim();\n};\n\n// ---------------------------------------------------------------------------\n// Tag extraction — last match wins\n// ---------------------------------------------------------------------------\n\n/**\n * Find the content between the **last** `<tag>` and `</tag>` pair in text.\n * Returns `undefined` if the tag is not found.\n */\nconst findLastTagContent = (text: string, tag: string): string | undefined => {\n const openTag = `<${tag}>`;\n const closeTag = `</${tag}>`;\n\n let lastContent: string | undefined;\n let searchFrom = 0;\n\n while (true) {\n const openIdx = text.indexOf(openTag, searchFrom);\n if (openIdx === -1) {\n break;\n }\n\n const contentStart = openIdx + openTag.length;\n const closeIdx = text.indexOf(closeTag, contentStart);\n if (closeIdx === -1) {\n break;\n }\n\n lastContent = text.slice(contentStart, closeIdx);\n searchFrom = closeIdx + closeTag.length;\n }\n\n return lastContent;\n};\n\n// ---------------------------------------------------------------------------\n// Fence-aware unwrap (object mode only)\n// ---------------------------------------------------------------------------\n\n/**\n * Strip an optional Markdown code fence from text.\n *\n * Recognises:\n * - ` ```json\\n...\\n``` `\n * - ` ```\\n...\\n``` `\n *\n * If no fence is detected, returns the input unchanged (already trimmed by caller).\n */\nconst unwrapFences = (text: string): string => {\n // Match ```json ... ``` or ``` ... ``` (with optional language hint)\n const fenced = /^```(?:json)?\\s*\\n(?<body>[\\s\\S]*?)\\n\\s*```\\s*$/u.exec(text)\n ?.groups?.body;\n if (fenced !== undefined) {\n return fenced.trim();\n }\n return text;\n};\n","import { inspect } from \"node:util\";\nimport type { Timeouts } from \"./run.js\";\n\n/** The timeout-shaped options shared by `run()`, `interactive()`, `createSandbox()`, `createWorktree()` and their handles. */\nexport interface TimeoutOptions {\n readonly idleTimeoutSeconds?: number;\n readonly completionTimeoutSeconds?: number;\n readonly timeouts?: Timeouts;\n}\n\nconst TIMEOUTS_KEYS = [\n \"copyToWorktreeMs\",\n \"gitSetupMs\",\n \"commitCollectionMs\",\n \"mergeToHostMs\",\n] as const satisfies readonly (keyof Timeouts)[];\n\nconst assertPositive = (\n name: string,\n unit: \"seconds\" | \"milliseconds\",\n value: unknown,\n): void => {\n if (value === undefined) {\n return;\n }\n // `!(value > 0)` also rejects NaN. Infinity stays allowed (no timeout).\n if (typeof value !== \"number\" || !(value > 0)) {\n throw new Error(\n `${name} must be a positive number of ${unit}. Received: ${inspect(value)}`,\n );\n }\n};\n\n/**\n * Throw a clear error when a timeout option is zero, negative or NaN.\n *\n * Called at entry, before any worktree or sandbox exists: a non-positive\n * timeout would otherwise fire before the agent's first output (or fail a\n * lifecycle step instantly) with a misleading error.\n */\nexport const validateTimeoutOptions = (options: TimeoutOptions): void => {\n assertPositive(\"idleTimeoutSeconds\", \"seconds\", options.idleTimeoutSeconds);\n assertPositive(\n \"completionTimeoutSeconds\",\n \"seconds\",\n options.completionTimeoutSeconds,\n );\n for (const key of TIMEOUTS_KEYS) {\n assertPositive(`timeouts.${key}`, \"milliseconds\", options.timeouts?.[key]);\n }\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport {\n appendFileSync,\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readSync,\n} from \"node:fs\";\nimport path, { join } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { Effect, Layer } from \"effect\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport {\n assertForkSupported,\n assertResumeSessionExists,\n} from \"./resumePrecheck.js\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display, FileDisplay } from \"./Display.js\";\nimport type { Severity } from \"./Display.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult, OrchestrateResult } from \"./Orchestrator.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport {\n WorktreeDockerSandboxFactory,\n SandboxConfig,\n} from \"./SandboxFactory.js\";\nimport type { SandboxProvider, BranchStrategy } from \"./SandboxProvider.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { formatErrorMessage } from \"./ErrorHandler.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport type { AgentStreamEvent } from \"./AgentStreamEmitter.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { generateTempBranchName, getCurrentBranch } from \"./WorktreeManager.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport type {\n OutputDefinition,\n OutputObjectDefinition,\n OutputStringDefinition,\n} from \"./Output.js\";\nimport { StructuredOutputError } from \"./Output.js\";\nimport type { PromptError } from \"./errors.js\";\nimport { extractStructuredOutput } from \"./extractStructuredOutput.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\nimport { buildContextWindowLines } from \"./ContextWindow.js\";\n\n/**\n * Build the token-efficient feedback prompt sent to the agent when retrying\n * structured output. The agent has already done the work in the resumed\n * session — the only ask is to re-emit a corrected tag.\n *\n * @internal\n */\nconst describeParserCause = (cause: unknown): string => {\n if (cause === undefined) {\n return \"(no parser detail)\";\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n return JSON.stringify(cause, null, 2);\n};\n\nexport const buildStructuredOutputRetryFeedback = (\n error: StructuredOutputError,\n retriesRemaining: number,\n): string => {\n const raw = error.rawMatched ?? \"(no matching tag was emitted)\";\n const cause = describeParserCause(error.cause);\n\n return `Your previous response did not produce valid structured output.\n\nRetries remaining after this attempt: ${retriesRemaining}.\n\nProblem:\n${error.message}\n\nParser detail:\n${cause}\n\nPrevious matched output:\n${raw}\n\nEmit only a corrected <${error.tag}> block. Do not change files or run commands.`;\n};\n\n/** Default maximum number of iterations for a run. */\nexport const DEFAULT_MAX_ITERATIONS = 1;\n\n/** Replace characters that are invalid or problematic in file paths with dashes. */\nexport const sanitizeBranchForFilename = (branch: string): string =>\n branch.replaceAll(/[/\\\\:*?\"<>|]/gu, \"-\");\n\nexport interface FileDisplayStartupOptions {\n readonly logPath: string;\n readonly agentName?: string;\n readonly branch?: string;\n /** Resolved host repo directory. When it differs from `process.cwd()`, the\n * log-file hint is printed as an absolute path so it can be pasted into any\n * terminal. When it equals `process.cwd()` (or is omitted), a relative path\n * is printed instead. */\n readonly hostRepoDir?: string;\n}\n\n/**\n * Print the startup message to the terminal when using file-based logging.\n * Uses styleText for lightweight bold/dim styling — does not use Clack.\n */\nexport const printFileDisplayStartup = (\n options: FileDisplayStartupOptions,\n): void => {\n const name = options.agentName ?? \"Agent\";\n const label = styleText(\"bold\", `[${name}]`);\n const branchPart =\n options.branch !== undefined && options.branch !== \"\"\n ? ` on branch ${options.branch}`\n : \"\";\n const hostRepoDir = options.hostRepoDir ?? process.cwd();\n const displayLogPath =\n hostRepoDir === process.cwd()\n ? path.relative(process.cwd(), options.logPath)\n : options.logPath;\n console.log(`${label} Started${branchPart}`);\n console.log(styleText(\"dim\", ` tail -f ${displayLogPath}`));\n};\n\n/**\n * Build the log filename for a run.\n * When a targetBranch is provided (temp branch mode), prefixes the filename\n * with the sanitized target branch name so developers can identify which\n * branch the run was targeting: `<targetBranch>-<resolvedBranch>.log`\n * When no targetBranch, uses just the resolved branch: `<resolvedBranch>.log`\n * When a name is provided, appends it to avoid collisions in multi-agent workflows.\n */\nexport const buildLogFilename = (\n resolvedBranch: string,\n targetBranch?: string,\n name?: string,\n): string => {\n const sanitized = sanitizeBranchForFilename(resolvedBranch);\n // One dash per UTF-16 unit, as before the `u` flag on the regex below.\n const nameSuffix =\n name !== undefined && name !== \"\"\n ? `-${name.toLowerCase().replaceAll(/[^a-z0-9_.-]/gu, (char) => \"-\".repeat(char.length))}`\n : \"\";\n if (targetBranch !== undefined && targetBranch !== \"\") {\n return `${sanitizeBranchForFilename(targetBranch)}-${sanitized}${nameSuffix}.log`;\n }\n return `${sanitized}${nameSuffix}.log`;\n};\n\nexport interface RunSummaryRowsOptions {\n readonly name?: string;\n readonly agentName: string;\n readonly sandboxName: string;\n readonly maxIterations: number;\n readonly branch: string;\n}\n\n/**\n * Build the summary rows for a run, used in both terminal mode and\n * log-to-file mode. When a custom name is provided it appears as the\n * Agent value instead of the internal provider name.\n */\nexport const buildRunSummaryRows = (\n options: RunSummaryRowsOptions,\n): Record<string, string> => ({\n Agent: options.name ?? options.agentName,\n Sandbox: options.sandboxName,\n \"Max iterations\": String(options.maxIterations),\n Branch: options.branch,\n});\n\n/**\n * Build the completion status message for a run, used in both terminal mode\n * and log-to-file mode to record the final outcome.\n */\nexport const buildCompletionMessage = (\n completionSignal: string | undefined,\n iterationsRun: number,\n): { readonly message: string; readonly severity: Severity } => {\n if (completionSignal !== undefined) {\n return {\n message: `Run complete: agent finished after ${iterationsRun} iteration(s).`,\n severity: \"success\",\n };\n }\n return {\n message: `Run complete: reached ${iterationsRun} iteration(s) without completion signal.`,\n severity: \"warn\",\n };\n};\n\nexport { buildContextWindowLines } from \"./ContextWindow.js\";\n\n/**\n * Controls where Sandcastle writes iteration progress and agent output.\n * Use `\"file\"` (log-to-file mode) to write to a log file on disk, or\n * `\"stdout\"` (terminal mode) to render an interactive UI in the terminal.\n */\nexport type LoggingOption =\n /** Write progress and agent output to a log file at the given path (log-to-file mode). */\n | {\n readonly type: \"file\";\n readonly path: string;\n /**\n * Optional callback invoked for each agent stream event (text chunk,\n * tool call, or raw stdout line) in addition to being written to the\n * log file. Intended for forwarding the agent's output stream to\n * external observability systems. Errors thrown by the callback are\n * swallowed.\n */\n readonly onAgentStreamEvent?: (event: AgentStreamEvent) => void;\n /**\n * When `true`, every raw stdout line the agent emits is appended\n * verbatim to the same log file at `path`, in real time. Includes\n * lines the provider's stream parser would otherwise drop (e.g.\n * tool-use blocks for unrecognised tools). Intended for debugging\n * stuck or unexpected agent behavior — note that the raw JSON is\n * interleaved with the human-readable log output. Default: `false`.\n */\n readonly verbose?: boolean;\n }\n /** Render progress and agent output as an interactive UI in the terminal (terminal mode). */\n | {\n readonly type: \"stdout\";\n /**\n * When `true`, every raw stdout line the agent emits is written\n * verbatim to `process.stdout`, in real time. Includes lines the\n * provider's stream parser would otherwise drop. Intended for\n * debugging stuck or unexpected agent behavior. Note: the raw output\n * is interleaved with the interactive terminal UI. Default: `false`.\n */\n readonly verbose?: boolean;\n };\n\n/**\n * Build the agent-stream event handler for a resolved logging option.\n *\n * Composes the user-provided `onAgentStreamEvent` callback (file mode only)\n * with the verbose raw-line sink: the log file at `path` for file mode, or\n * `process.stdout` for stdout mode. Returns `undefined` when neither\n * verbose mode nor a user callback is set.\n *\n * Raw lines are written synchronously to honor the `onLine` real-time\n * contract — the debugger needs each line as soon as the agent emits it.\n *\n * @internal\n */\nexport const buildAgentStreamHandler = (\n logging: LoggingOption,\n): ((event: AgentStreamEvent) => void) | undefined => {\n const userHandler =\n logging.type === \"file\" ? logging.onAgentStreamEvent : undefined;\n const verboseSink =\n logging.verbose === true ? buildVerboseRawLineSink(logging) : undefined;\n if (!userHandler && !verboseSink) {\n return undefined;\n }\n return (event) => {\n if (userHandler) {\n try {\n userHandler(event);\n } catch {\n // Swallow — a broken forwarder must not stop the verbose sink.\n }\n }\n if (verboseSink && event.type === \"raw\") {\n verboseSink(event.line);\n }\n };\n};\n\n/**\n * Whether the file's last byte is something other than a newline. The log file\n * has two writers: FileDisplay streams agent prose as chunks with no trailing\n * newline, and the verbose sink appends raw lines. Reading the file's actual\n * tail lets the sink start each raw line on a fresh line without sharing state\n * with FileDisplay. A missing or empty file counts as \"not mid-line\".\n */\nconst fileEndsMidLine = (filePath: string): boolean => {\n let fd: number | undefined;\n try {\n fd = openSync(filePath, \"r\");\n const { size } = fstatSync(fd);\n if (size === 0) {\n return false;\n }\n const lastByte = Buffer.alloc(1);\n readSync(fd, lastByte, 0, 1, size - 1);\n return lastByte[0] !== 0x0a;\n } catch {\n return false;\n } finally {\n if (fd !== undefined) {\n closeSync(fd);\n }\n }\n};\n\nconst buildVerboseRawLineSink = (\n logging: LoggingOption,\n): ((line: string) => void) => {\n if (logging.type === \"file\") {\n const logPath = logging.path;\n // Ensure the directory exists; the FileDisplay layer creates it for the\n // primary log file but it hasn't necessarily run by the time the first\n // raw line is flushed.\n try {\n mkdirSync(path.dirname(logPath), { recursive: true });\n } catch {\n // Swallow — appendFileSync below will surface any real I/O error.\n }\n return (line) => {\n try {\n const prefix = fileEndsMidLine(logPath) ? \"\\n\" : \"\";\n appendFileSync(logPath, `${prefix + line}\\n`);\n } catch {\n // Swallow — verbose-mode I/O errors must not kill the run.\n }\n };\n }\n return (line) => {\n process.stdout.write(`${line}\\n`);\n };\n};\n\n/** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\nexport interface Timeouts {\n /** Timeout (ms) for the host-side copy of `copyToWorktree` paths into the worktree. Default: 60_000. */\n readonly copyToWorktreeMs?: number;\n /** Timeout (ms) for each in-sandbox git setup command (safe.directory, user.name/email, branch discovery). Default: 10_000. */\n readonly gitSetupMs?: number;\n /** Timeout (ms) for collecting the commits produced during the run. Default: 30_000. */\n readonly commitCollectionMs?: number;\n /** Timeout (ms) for merging the temp branch back to the host branch (merge-to-head strategy). Default: 30_000. */\n readonly mergeToHostMs?: number;\n}\n\nexport interface RunOptions<A extends AgentProvider = AgentProvider> {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: A;\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, `.sandcastle/logs/`,\n * `.sandcastle/patches/`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Inline prompt string (mutually exclusive with promptFile) */\n readonly prompt?: string;\n /**\n * Path to a prompt file (mutually exclusive with prompt).\n *\n * **Note:** `promptFile` is always resolved against `process.cwd()`, not\n * against the `cwd` option. If you set a custom `cwd`, pass an absolute\n * `promptFile` to avoid ambiguity.\n */\n readonly promptFile?: string;\n /** Maximum iterations to run (default: 1) */\n readonly maxIterations?: number;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Logging mode (default: { type: 'file' } with auto-generated path under .sandcastle/logs/) */\n readonly logging?: LoggingOption;\n /** Substring(s) the agent emits to stop the iteration loop early. Matched via `includes` against agent output. (default: `\"<promise>COMPLETE</promise>\"`) */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. If the agent produces no output for this long, it fails. Default: 600 (10 minutes) */\n readonly idleTimeoutSeconds?: number;\n /**\n * Grace window in seconds after a completion signal is observed in the\n * agent's output. The agent process is expected to exit shortly after\n * emitting the signal; if it does not (typically because a spawned child —\n * a `gh`/git subprocess or long-lived MCP server — keeps stdout open),\n * Sandcastle force-completes the iteration with a warning. Resets on every\n * subsequent output line so trailing data (token-usage events, terminal\n * `result` events, structured-output tags) is still captured. Independent\n * of `idleTimeoutSeconds`. Default: 60.\n */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run, shown as a prefix in log output */\n readonly name?: string;\n /** Paths relative to the host repo root to copy into the worktree before sandbox start. */\n readonly copyToWorktree?: string[];\n /** Branch strategy — controls how the agent's changes relate to branches.\n * Defaults to { type: \"head\" } for bind-mount providers and { type: \"merge-to-head\" } for isolated providers. */\n readonly branchStrategy?: BranchStrategy;\n /** Resume a prior Claude Code session by ID. The session JSONL must exist on the host. Incompatible with maxIterations > 1. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it. The parent session JSONL is left intact and the agent writes a new\n * session under a fresh id. Exposed as the public `.fork()` method on\n * `RunResult` rather than as a stand-alone caller option — see ADR 0018.\n *\n * @internal\n */\n readonly forkSession?: boolean;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, `run()` rejects\n * immediately without doing any setup work.\n * - Aborting mid-iteration kills the in-flight agent subprocess.\n * - Phase boundaries (between iterations) also check the signal.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n * - The worktree is preserved on disk after abort, even when it has no\n * uncommitted changes, and its path is printed to stderr.\n */\n readonly signal?: AbortSignal;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /**\n * Structured output definition. When provided, the agent's stdout is\n * scanned for the configured XML tag after the iteration completes, and the\n * result is parsed/validated and returned on `RunResult.output`.\n *\n * Use `Output.object({ tag, schema })` for JSON+schema or\n * `Output.string({ tag })` for raw string extraction.\n *\n * Constraints:\n * - `maxIterations` must be `1` (the default).\n * - The resolved prompt must contain the configured opening tag literal.\n *\n * See ADR 0010 for design rationale.\n */\n readonly output?: OutputDefinition;\n}\n\nexport type { IterationResult, IterationUsage } from \"./Orchestrator.js\";\nexport type { ContextWindow } from \"./ContextWindow.js\";\n\nexport type ResumeRunResultOptions = Omit<\n RunOptions,\n | \"agent\"\n | \"sandbox\"\n | \"prompt\"\n | \"promptFile\"\n | \"resumeSession\"\n | \"forkSession\"\n | \"maxIterations\"\n>;\n\nexport interface RunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if no signal fired before the iteration limit. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run, each identified by its SHA. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on inside the sandbox. */\n readonly branch: string;\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n /** Host path to the preserved worktree, set when the run succeeded but the worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n /** Continue the last captured agent session for exactly one iteration.\n * Present only when the provider supports resume (`sessionStorage` populated).\n * `output` and `promptArgs` are not inherited: pass `output` again to get\n * structured output from the follow-up (its prompt must contain the tag). */\n readonly resume?: (\n prompt: string,\n options?: ResumeRunResultOptions,\n ) => Promise<RunResult>;\n /**\n * Fork the last captured agent session for exactly one iteration: the\n * parent session JSONL is left intact and the child run gets its own\n * session id, enabling fan-out patterns where multiple children diverge\n * from a single parent. Present only when the provider supports resume\n * (`sessionStorage` populated).\n *\n * Sessions only: fork isolates the agent session, not the branch or\n * sandbox. Safe concurrent fan-out (`Promise.all([r.fork(a), r.fork(b)])`)\n * requires the caller to give each fork a distinct `branch` — `head` and\n * `merge-to-head` are not safe for concurrent forks. See ADR 0018.\n *\n * Like `resume`, `output` and `promptArgs` are not inherited.\n */\n readonly fork?: (\n prompt: string,\n options?: ResumeRunResultOptions,\n ) => Promise<RunResult>;\n}\n\n/** Fails when the branch strategy can't be used with the other options. */\nconst validateBranchOptions = (\n options: RunOptions,\n branchType: BranchStrategy[\"type\"],\n): void => {\n // Validate: head strategy is not supported with isolated providers\n if (branchType === \"head\" && options.sandbox.tag === \"isolated\") {\n throw new Error(\n \"head branch strategy is not supported with isolated providers\",\n );\n }\n\n // Validate: copyToWorktree is incompatible with head strategy\n if (\n branchType === \"head\" &&\n options.copyToWorktree &&\n options.copyToWorktree.length > 0\n ) {\n throw new Error(\n \"copyToWorktree is not supported with head branch strategy. \" +\n \"In head mode the host working directory is bind-mounted directly.\",\n );\n }\n};\n\n/** Fails on an impossible resume/fork combination; whether this run resumes. */\nconst validateSessionOptions = (\n options: RunOptions,\n maxIterations: number,\n): boolean => {\n const isResuming =\n options.resumeSession !== undefined && options.resumeSession !== \"\";\n\n // Validate: resumeSession + maxIterations > 1 is not allowed\n if (isResuming && maxIterations > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n // Validate: forkSession only makes sense alongside resumeSession.\n // It is wired internally by RunResult.fork() and never set on its own.\n if (options.forkSession === true && !isResuming) {\n throw new Error(\n \"forkSession requires resumeSession. \" +\n \"Use RunResult.fork(prompt) to fork the last captured session.\",\n );\n }\n if (options.forkSession === true) {\n assertForkSupported(options.agent);\n }\n return isResuming;\n};\n\n/** Fails on unusable structured-output options; the output retry budget. */\nconst validateOutputOptions = (\n options: RunOptions,\n maxIterations: number,\n): number => {\n // Validate: output requires maxIterations === 1\n if (options.output && maxIterations !== 1) {\n throw new Error(\n \"output requires maxIterations to be 1. \" +\n \"Structured output is only supported for single-iteration runs.\",\n );\n }\n\n // Validate: output.maxRetries requires a provider that supports session\n // resumption. Fail at the earliest possible point — the issue is fully\n // determined by the inputs to run() and does not depend on the agent's\n // output. See issue #825.\n const outputMaxRetries = options.output?.maxRetries ?? 0;\n if (outputMaxRetries < 0 || !Number.isInteger(outputMaxRetries)) {\n throw new Error(\n \"output.maxRetries must be a non-negative integer. \" +\n `Received: ${outputMaxRetries}`,\n );\n }\n if (outputMaxRetries > 0 && !options.agent.sessionStorage) {\n throw new Error(\n `output.maxRetries requires an agent provider that supports session resumption. ` +\n `The \"${options.agent.name}\" provider does not. ` +\n `Use an agent provider that supports resume, or set maxRetries to 0.`,\n );\n }\n return outputMaxRetries;\n};\n\n/**\n * The prompt the agent gets. Inline prompts pass through to the agent\n * literally — no substitution, no built-in arg injection. Guard against\n * silently ignoring promptArgs.\n */\nconst buildAgentPrompt = (input: {\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n readonly userArgs: PromptArgs;\n readonly sourceBranch: string;\n readonly targetBranch: string;\n}): Effect.Effect<string, PromptError, Display> =>\n Effect.gen(function* () {\n if (input.isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(input.userArgs);\n return input.rawPrompt;\n }\n yield* validateNoBuiltInArgOverride(input.userArgs);\n const effectiveArgs = {\n SOURCE_BRANCH: input.sourceBranch,\n TARGET_BRANCH: input.targetBranch,\n ...input.userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n return yield* substitutePromptArgs(\n input.rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n });\n\n/** Shows how the run ended and how full each iteration's context window got. */\nconst reportRunEnd = (\n result: OrchestrateResult,\n): Effect.Effect<void, never, Display> =>\n Effect.gen(function* () {\n const d = yield* Display;\n const completion = buildCompletionMessage(\n result.completionSignal,\n result.iterations.length,\n );\n yield* d.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(result.iterations)) {\n yield* d.text(line);\n }\n });\n\n/**\n * A follow-up run on the last iteration's session: `resume` continues it,\n * `fork` continues a copy.\n */\nconst followUpRun =\n (options: RunOptions, result: OrchestrateResult, kind: \"resume\" | \"fork\") =>\n async (\n followUpPrompt: string,\n followUpOptions?: ResumeRunResultOptions,\n ): Promise<RunResult> => {\n const lastIteration = result.iterations.at(-1);\n if (\n lastIteration?.sessionId === undefined ||\n lastIteration.sessionId === \"\"\n ) {\n throw new Error(`Cannot ${kind}: no sessionId was captured`);\n }\n return run({\n ...options,\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n // The follow-up prompt is new: structured output is opt-in per call.\n output: undefined,\n ...followUpOptions,\n prompt: followUpPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: lastIteration.sessionId,\n ...(kind === \"fork\" ? { forkSession: true } : {}),\n });\n };\n\n/** The host repo dir; when resuming, also checks the session file exists there. */\nconst resolveRunHostRepoDir = async (\n options: RunOptions,\n isResuming: boolean,\n): Promise<string> => {\n const hostRepoDir = await Effect.runPromise(\n resolveCwd(options.cwd).pipe(Effect.provide(NodeContext.layer)),\n );\n // Validate: resumeSession file must exist on the host\n if (isResuming && options.resumeSession !== undefined) {\n await assertResumeSessionExists({\n provider: options.agent,\n sandboxTag: options.sandbox.tag,\n hostRepoDir,\n resumeSession: options.resumeSession,\n });\n }\n return hostRepoDir;\n};\n\n/** Explicit branch strategy, else merge-to-head for isolated providers, else head. */\nconst resolveBranchStrategy = (options: RunOptions): BranchStrategy =>\n options.branchStrategy ??\n (options.sandbox.tag === \"isolated\"\n ? { type: \"merge-to-head\" }\n : { type: \"head\" });\n\n/** The prompt text and whether it was inline, with the output tag checked. */\nconst resolveRunPrompt = async (\n options: RunOptions,\n): Promise<{\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n}> => {\n const resolved = await Effect.runPromise(\n resolvePrompt({\n prompt: options.prompt,\n promptFile: options.promptFile,\n }).pipe(Effect.provide(NodeContext.layer)),\n );\n // Validate: output tag must appear in the resolved prompt\n if (options.output && !resolved.text.includes(`<${options.output.tag}>`)) {\n throw new Error(\n `output tag <${options.output.tag}> not found in the resolved prompt. ` +\n \"The caller must instruct the agent to emit the configured tag.\",\n );\n }\n return {\n rawPrompt: resolved.text,\n isInlinePrompt: resolved.source === \"inline\",\n };\n};\n\n/** The branches a run works with, derived from the host's current branch. */\ninterface RunBranches {\n /** The host's current branch: the TARGET_BRANCH built-in prompt argument. */\n readonly currentHostBranch: string;\n /** The branch the agent works on. */\n readonly resolvedBranch: string;\n /** Set when using a temp branch: prefixes the log filename. */\n readonly targetBranch: string | undefined;\n /** The branch passed to orchestrate (see `resolveRunBranches`). */\n readonly orchestrateBranch: string | undefined;\n}\n\nconst resolveRunBranches = async (\n options: RunOptions,\n branchStrategy: BranchStrategy,\n hostRepoDir: string,\n): Promise<RunBranches> => {\n // Explicit branch when in branch mode\n const branch =\n branchStrategy.type === \"branch\" ? branchStrategy.branch : undefined;\n const currentHostBranch = await Effect.runPromise(\n getCurrentBranch(hostRepoDir),\n );\n return {\n currentHostBranch,\n // When in merge-to-head mode, generate a temporary branch name.\n // In head mode, use the host's current branch directly (no worktree).\n resolvedBranch:\n branchStrategy.type === \"head\"\n ? currentHostBranch\n : (branch ?? generateTempBranchName(options.name)),\n // When using a temp branch, prefix the log filename with the target branch\n // (the host's current branch) so developers can tell which branch was targeted.\n targetBranch:\n branchStrategy.type === \"merge-to-head\" ? currentHostBranch : undefined,\n // In head mode, pass the host branch so SandboxLifecycle skips the merge step.\n // In merge-to-head mode, branch is undefined (triggers merge). In branch mode, it's the explicit branch.\n orchestrateBranch:\n branchStrategy.type === \"head\" ? currentHostBranch : branch,\n };\n};\n\n/** Resolve env vars and merge with the agent and sandbox providers' env. */\nconst resolveRunEnv = async (options: RunOptions, hostRepoDir: string) =>\n mergeProviderEnv({\n resolvedEnv: await Effect.runPromise(\n resolveEnv(hostRepoDir).pipe(Effect.provide(NodeContext.layer)),\n ),\n agentProviderEnv: options.agent.env,\n sandboxProviderEnv: options.sandbox.env,\n });\n\n/** Shared inputs for building a run's layers and effect. */\ninterface RunSetup {\n readonly options: RunOptions;\n readonly branchStrategy: BranchStrategy;\n readonly hostRepoDir: string;\n readonly maxIterations: number;\n readonly branches: RunBranches;\n readonly logging: LoggingOption;\n /** Resolved env vars merged with the agent and sandbox providers' env. */\n readonly env: Record<string, string>;\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n}\n\n/** `options.logging`, else a file under .sandcastle/logs named for the branch. */\nconst resolveRunLogging = (\n options: RunOptions,\n hostRepoDir: string,\n { resolvedBranch, targetBranch }: RunBranches,\n): LoggingOption =>\n options.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(resolvedBranch, targetBranch, options.name),\n ),\n };\n\nconst buildDisplayLayer = ({\n options,\n hostRepoDir,\n branches,\n logging,\n}: RunSetup) => {\n if (logging.type !== \"file\") {\n return ClackDisplay.layer;\n }\n printFileDisplayStartup({\n logPath: logging.path,\n agentName: options.name,\n branch: branches.resolvedBranch,\n hostRepoDir,\n });\n return Layer.provide(FileDisplay.layer(logging.path), NodeFileSystem.layer);\n};\n\n/** The display, sandbox factory and agent stream layers for a run. */\nconst buildRunLayer = (setup: RunSetup) => {\n const { options, hostRepoDir, branchStrategy, branches, env } = setup;\n const displayLayer = buildDisplayLayer(setup);\n const factoryLayer = Layer.provide(\n WorktreeDockerSandboxFactory.layer,\n Layer.mergeAll(\n Layer.succeed(SandboxConfig, {\n env,\n hostRepoDir,\n copyToWorktree: options.copyToWorktree,\n name: options.name,\n // Create the worktree on the temp branch already shown to the user,\n // rather than letting WorktreeManager generate a second name.\n tempBranch:\n branchStrategy.type === \"merge-to-head\"\n ? branches.resolvedBranch\n : undefined,\n sandboxProvider: options.sandbox,\n branchStrategy,\n hooks: options.hooks,\n signal: options.signal,\n timeouts: options.timeouts,\n }),\n NodeFileSystem.layer,\n displayLayer,\n ),\n );\n return Layer.mergeAll(\n factoryLayer,\n displayLayer,\n agentStreamEmitterLayer(buildAgentStreamHandler(setup.logging)),\n );\n};\n\n/** Shows the run summary, builds the prompt, and orchestrates the iterations. */\nconst runIterations = ({\n options,\n hostRepoDir,\n maxIterations,\n branches,\n rawPrompt,\n isInlinePrompt,\n}: RunSetup) =>\n Effect.gen(function* () {\n const d = yield* Display;\n yield* d.intro(options.name ?? \"sandcastle\");\n const rows = buildRunSummaryRows({\n name: options.name,\n agentName: options.agent.name,\n sandboxName: options.sandbox.name,\n maxIterations,\n branch: branches.resolvedBranch,\n });\n yield* d.summary(\"Sandcastle Run\", rows);\n\n const resolvedPrompt = yield* buildAgentPrompt({\n rawPrompt,\n isInlinePrompt,\n userArgs: options.promptArgs ?? {},\n sourceBranch: branches.resolvedBranch,\n targetBranch: branches.currentHostBranch,\n });\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir,\n iterations: maxIterations,\n hooks: options.hooks,\n prompt: resolvedPrompt,\n branch: branches.orchestrateBranch,\n provider: options.agent,\n completionSignal: options.completionSignal,\n idleTimeoutSeconds: options.idleTimeoutSeconds,\n completionTimeoutSeconds: options.completionTimeoutSeconds,\n name: options.name,\n resumeSession: options.resumeSession,\n forkSession: options.forkSession,\n signal: options.signal,\n skipPromptExpansion: isInlinePrompt,\n timeouts: options.timeouts,\n });\n\n yield* reportRunEnd(orchestrateResult);\n return orchestrateResult;\n });\n\n/** Runs the iterations; with file logging, errors are written to the log first. */\nconst executeRun = async (setup: RunSetup): Promise<OrchestrateResult> => {\n const baseEffect = runIterations(setup);\n // In stdout mode (ClackDisplay), errors are already shown by withFriendlyErrors\n // in main.ts, so we skip to avoid duplicate terminal output.\n const withErrorLog =\n setup.logging.type === \"file\"\n ? baseEffect.pipe(\n Effect.tapError((error) =>\n Effect.gen(function* () {\n const d = yield* Display;\n yield* d.status(formatErrorMessage(error), \"error\");\n }),\n ),\n )\n : baseEffect;\n const runLayer = buildRunLayer(setup);\n try {\n return await Effect.runPromise(withErrorLog.pipe(Effect.provide(runLayer)));\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n setup.options.signal?.throwIfAborted();\n throw error;\n }\n};\n\n/**\n * Extracts structured output from a finished run. On a StructuredOutputError\n * with retries left and a session to resume, retries with a token-efficient\n * feedback prompt; each retry decrements maxRetries, so it terminates (#825).\n */\nconst withStructuredOutput = async (\n options: RunOptions & { output: NonNullable<RunOptions[\"output\"]> },\n baseResult: RunResult,\n outputMaxRetries: number,\n): Promise<RunResult & { output?: unknown }> => {\n // Structured output runs are single-iteration, so the last iteration is the\n // one that produced this stdout. Carry its session id onto the error so a\n // caller can resume the same session to re-emit corrected output.\n const lastIteration = baseResult.iterations.at(-1);\n try {\n const output = await extractStructuredOutput(\n baseResult.stdout,\n options.output,\n {\n commits: baseResult.commits,\n branch: baseResult.branch,\n preservedWorktreePath: baseResult.preservedWorktreePath,\n sessionId: lastIteration?.sessionId,\n sessionFilePath: lastIteration?.sessionFilePath,\n },\n );\n return { ...baseResult, output };\n } catch (error) {\n if (\n error instanceof StructuredOutputError &&\n outputMaxRetries > 0 &&\n error.sessionId !== undefined\n ) {\n const retriesRemainingAfter = outputMaxRetries - 1;\n const retryOutput = {\n ...options.output,\n maxRetries: retriesRemainingAfter,\n };\n return run({\n ...options,\n prompt: buildStructuredOutputRetryFeedback(\n error,\n retriesRemainingAfter,\n ),\n promptFile: undefined,\n promptArgs: undefined,\n resumeSession: error.sessionId,\n forkSession: false,\n output: retryOutput,\n } as RunOptions);\n }\n throw error;\n }\n};\n\n/** The run's result, with its follow-ups and any structured output. */\nconst finishRun = async ({\n options,\n result,\n logging,\n outputMaxRetries,\n}: {\n readonly options: RunOptions;\n readonly result: OrchestrateResult;\n readonly logging: LoggingOption;\n readonly outputMaxRetries: number;\n}): Promise<RunResult & { output?: unknown }> => {\n const baseResult = {\n ...result,\n logFilePath: logging.type === \"file\" ? logging.path : undefined,\n resume: followUpRun(options, result, \"resume\"),\n fork: followUpRun(options, result, \"fork\"),\n };\n // Extract structured output after the iteration completes (separate pass from completion signal)\n const { output } = options;\n if (!output) {\n return baseResult;\n }\n return withStructuredOutput(\n { ...options, output },\n baseResult,\n outputMaxRetries,\n );\n};\n\n/** Overload: with `Output.object`, returns `RunResult` with typed `output: T`. */\nexport function run<T, A extends AgentProvider>(\n options: RunOptions<A> & { output: OutputObjectDefinition<T> },\n): Promise<RunResult & { output: T }>;\n/** Overload: with `Output.string`, returns `RunResult` with `output: string`. */\nexport function run<A extends AgentProvider>(\n options: RunOptions<A> & { output: OutputStringDefinition },\n): Promise<RunResult & { output: string }>;\n/** Overload: without `output`, returns the standard `RunResult`. */\nexport function run<A extends AgentProvider>(\n options: RunOptions<A>,\n): Promise<RunResult>;\nexport async function run(\n options: RunOptions,\n): Promise<RunResult & { output?: unknown }> {\n // If signal is already aborted, reject immediately without any setup\n options.signal?.throwIfAborted();\n\n const { maxIterations = DEFAULT_MAX_ITERATIONS } = options;\n const branchStrategy = resolveBranchStrategy(options);\n\n // Validate: timeouts must be positive (0 would fire before the agent's first output)\n validateTimeoutOptions(options);\n validateBranchOptions(options, branchStrategy.type);\n const isResuming = validateSessionOptions(options, maxIterations);\n const outputMaxRetries = validateOutputOptions(options, maxIterations);\n\n const hostRepoDir = await resolveRunHostRepoDir(options, isResuming);\n\n const { rawPrompt, isInlinePrompt } = await resolveRunPrompt(options);\n const env = await resolveRunEnv(options, hostRepoDir);\n const branches = await resolveRunBranches(\n options,\n branchStrategy,\n hostRepoDir,\n );\n const logging = resolveRunLogging(options, hostRepoDir, branches);\n const result = await executeRun({\n options,\n branchStrategy,\n hostRepoDir,\n maxIterations,\n branches,\n logging,\n env,\n rawPrompt,\n isInlinePrompt,\n });\n\n return finishRun({ options, result, logging, outputMaxRetries });\n}\n","import { Deferred, Effect, Runtime } from \"effect\";\n\n/**\n * Race an Effect against an optional `AbortSignal`.\n *\n * - If no signal is provided, the effect runs unmodified.\n * - If the signal is already aborted at call time, dies immediately with\n * `signal.reason`.\n * - Otherwise, races the effect against a Deferred that fires when the\n * signal aborts.\n *\n * Uses `Effect.die` so the abort reason propagates as a defect — callers\n * should use `signal.throwIfAborted()` in their catch handler to surface\n * the original reason without Sandcastle-specific wrapping.\n *\n * The abort listener is always cleaned up, even when the effect wins the race.\n */\nexport const raceAbortSignal = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n signal?: AbortSignal,\n): Effect.Effect<A, E, R> => {\n if (!signal) {\n return effect;\n }\n\n return Effect.gen(function* () {\n if (signal.aborted) {\n return yield* Effect.die(signal.reason);\n }\n\n const abortDeferred = yield* Deferred.make<never>();\n // The listener fires outside any fiber; fork onto the surrounding runtime.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n const onAbort = () => {\n runFork(Deferred.die(abortDeferred, signal.reason));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n return yield* Effect.raceFirst(effect, Deferred.await(abortDeferred)).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n signal.removeEventListener(\"abort\", onAbort);\n }),\n ),\n );\n });\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport * as clack from \"@clack/prompts\";\nimport { Effect, Layer } from \"effect\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport {\n makeSandboxFromHandle,\n resolveGitMounts,\n SANDBOX_REPO_DIR,\n} from \"./SandboxFactory.js\";\nimport type { MountEntry } from \"./SandboxFactory.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type {\n SandboxProvider,\n BranchStrategy,\n BindMountSandboxHandle,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n} from \"./SandboxProvider.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { startSandbox } from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { generateTempBranchName, getCurrentBranch } from \"./WorktreeManager.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n findMissingPromptArgKeys,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { noSandbox } from \"./sandboxes/no-sandbox.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport type { Timeouts } from \"./run.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\nexport interface InteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker(), noSandbox()). */\n readonly sandbox?: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Optional name for the interactive session. */\n readonly name?: string;\n /** Branch strategy — controls how the agent's changes relate to branches.\n * Defaults to { type: \"head\" } for bind-mount providers and { type: \"merge-to-head\" } for isolated providers. */\n readonly branchStrategy?: BranchStrategy;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree before sandbox start. */\n readonly copyToWorktree?: string[];\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /**\n * Host repo directory to use instead of `process.cwd()`.\n *\n * Relative paths resolve against `process.cwd()`; absolute paths pass\n * through as-is. A {@link CwdError} is thrown if the path does not exist\n * or is not a directory.\n */\n readonly cwd?: string;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, `interactive()` rejects\n * immediately without doing any setup work.\n * - Aborting during an active session kills the agent subprocess.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n * - The worktree is preserved on disk after abort (error-path behavior).\n */\n readonly signal?: AbortSignal;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n}\n\nexport interface InteractiveResult {\n /** List of commits made during the interactive session. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on. */\n readonly branch: string;\n /** Host path to the preserved worktree, if worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n /** Exit code of the interactive process. */\n readonly exitCode: number;\n}\n\n/**\n * Launch an interactive agent session inside a sandbox.\n *\n * The user sees the agent's TUI directly. When the session ends,\n * Sandcastle collects commits and handles branch merging, just like run().\n *\n * Full prompt preprocessing pipeline: PromptResolver -> PromptArgumentSubstitution\n * -> PromptPreprocessor (shell expressions inside sandbox).\n *\n * All three branch strategies are supported: head, merge-to-head, branch.\n */\nexport const interactive = async (\n options: InteractiveOptions,\n): Promise<InteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n options.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = options;\n\n validateTimeoutOptions(options);\n\n const resolvedSandbox = options.sandbox ?? noSandbox();\n assertInteractiveSupported(resolvedSandbox);\n\n // Derive branch strategy\n const branchStrategy: BranchStrategy =\n options.branchStrategy ??\n (resolvedSandbox.tag === \"isolated\"\n ? { type: \"merge-to-head\" }\n : { type: \"head\" }); // \"bind-mount\" and \"none\" both default to head\n\n // Validate: head strategy is not supported with isolated providers\n if (branchStrategy.type === \"head\" && resolvedSandbox.tag === \"isolated\") {\n throw new Error(\n \"head branch strategy is not supported with isolated providers\",\n );\n }\n\n // Validate: copyToWorktree is incompatible with head strategy\n if (\n branchStrategy.type === \"head\" &&\n options.copyToWorktree &&\n options.copyToWorktree.length > 0\n ) {\n throw new Error(\n \"copyToWorktree is not supported with head branch strategy. \" +\n \"In head mode the host working directory is bind-mounted directly.\",\n );\n }\n\n // Validate buildInteractiveArgs is available\n const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n const branch: string | undefined =\n branchStrategy.type === \"branch\" ? branchStrategy.branch : undefined;\n\n const isHeadMode = branchStrategy.type === \"head\";\n const sandboxProvider = resolvedSandbox;\n\n const inner = Effect.gen(function* () {\n const hostRepoDir = yield* resolveCwd(options.cwd);\n const d = yield* Display;\n\n // 1. Resolve prompt (from string or file), or skip if neither provided\n const hasPromptSource = prompt !== undefined || promptFile !== undefined;\n const resolved = hasPromptSource\n ? yield* resolvePrompt({ prompt, promptFile })\n : undefined;\n const rawPrompt = resolved?.text ?? \"\";\n const isInlinePrompt = resolved?.source === \"inline\";\n\n // 2. Resolve env vars\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: provider.env,\n sandboxProviderEnv: sandboxProvider.env,\n });\n const effectiveEnv = { ...env, ...options.env };\n\n // 3. Capture host's current branch\n const currentHostBranch = yield* getCurrentBranch(hostRepoDir);\n\n const resolvedBranch =\n branchStrategy.type === \"head\"\n ? currentHostBranch\n : (branch ?? generateTempBranchName(options.name));\n\n // 4. Validate prompt args and collect missing ones interactively (skip when no prompt).\n // Inline prompts pass through literally — skip scanning, substitution, and built-in args.\n let substitutedPrompt = rawPrompt;\n if (hasPromptSource && !isInlinePrompt) {\n const userArgs = options.promptArgs ?? {};\n yield* validateNoBuiltInArgOverride(userArgs);\n\n // Scan for missing keys and prompt the user for each one\n const missingKeys = findMissingPromptArgKeys(rawPrompt, userArgs);\n const collectedArgs: Record<string, string> = {};\n for (const key of missingKeys) {\n const value = yield* Effect.promise(async () =>\n clack.text({\n message: `Enter value for {{${key}}}`,\n validate: (v) => {\n if (v === undefined || v === \"\") {\n return `A value is required for {{${key}}}`;\n }\n },\n }),\n );\n if (clack.isCancel(value)) {\n clack.cancel(\"Prompt arg collection cancelled.\");\n return yield* Effect.fail(\n new Error(\"User cancelled prompt arg collection\"),\n );\n }\n collectedArgs[key] = value;\n }\n\n const mergedUserArgs = { ...userArgs, ...collectedArgs };\n const effectiveArgs = {\n SOURCE_BRANCH: resolvedBranch,\n TARGET_BRANCH: currentHostBranch,\n ...mergedUserArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n substitutedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n } else if (isInlinePrompt) {\n const userArgs = options.promptArgs ?? {};\n yield* validateNoArgsWithInlinePrompt(userArgs);\n }\n\n // In head mode, pass the host branch so SandboxLifecycle skips the merge step.\n const lifecycleBranch = isHeadMode ? currentHostBranch : branch;\n\n // Display intro and summary\n yield* d.intro(options.name ?? \"sandcastle interactive\");\n yield* d.summary(\"Interactive Session\", {\n Agent: options.name ?? provider.name,\n Sandbox: sandboxProvider.name,\n Branch: resolvedBranch,\n });\n\n // 5. Create worktree (unless head mode)\n let worktreeInfo: WorktreeManager.WorktreeInfo | undefined;\n\n if (!isHeadMode) {\n worktreeInfo = yield* d.taskLog(\"Creating worktree\", () =>\n WorktreeManager.pruneStale(hostRepoDir).pipe(\n Effect.catchAll(() => Effect.void),\n Effect.andThen(\n branch !== undefined && branch !== \"\"\n ? WorktreeManager.create(hostRepoDir, { branch })\n : WorktreeManager.create(hostRepoDir, {\n name: options.name,\n tempBranch: resolvedBranch,\n }),\n ),\n ),\n );\n }\n // Where the agent works on the host: the worktree, or the repo itself in\n // head mode (the only mode without a worktree).\n const hostWorkPath = worktreeInfo?.path ?? hostRepoDir;\n const copyPaths = options.copyToWorktree;\n const onWorktreeReady = hooks?.host?.onWorktreeReady ?? [];\n\n // 6. Prepare the worktree and start the sandbox. If any step fails after the\n // worktree exists (copying, hooks, or sandbox start), remove the worktree so\n // it is not orphaned on disk.\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n const handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle = yield* Effect.gen(function* () {\n if (!isHeadMode) {\n // Copy files to worktree (bind-mount and no-sandbox, non-head)\n if (\n (sandboxProvider.tag === \"bind-mount\" ||\n sandboxProvider.tag === \"none\") &&\n copyPaths &&\n copyPaths.length > 0\n ) {\n yield* d.taskLog(\"Copying files to worktree\", () =>\n copyToWorktree(\n copyPaths,\n hostRepoDir,\n hostWorkPath,\n options.timeouts?.copyToWorktreeMs,\n ),\n );\n }\n\n // Run host.onWorktreeReady hooks\n if (onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, hostWorkPath);\n }\n } else if (onWorktreeReady.length > 0) {\n // Head strategy: cwd is the host repo root\n yield* runHostHooks(onWorktreeReady, hostRepoDir);\n }\n\n // Start sandbox\n if (sandboxProvider.tag === \"none\") {\n // No-sandbox: run directly on the host, no container\n return yield* Effect.promise(async () =>\n sandboxProvider.create({\n worktreePath: hostWorkPath,\n env: effectiveEnv,\n }),\n );\n } else if (sandboxProvider.tag === \"isolated\") {\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: sandboxProvider,\n hostRepoDir: hostWorkPath,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n }),\n );\n return startResult.handle;\n }\n const gitPath = join(hostRepoDir, \".git\");\n const rawGitMounts = yield* resolveGitMounts(gitPath);\n const gitMounts = yield* patchGitMountsForWindows(\n rawGitMounts,\n hostWorkPath,\n SANDBOX_REPO_DIR,\n );\n mountsToClean.push(...gitMounts);\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: hostWorkPath,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n );\n return startResult.handle;\n }).pipe(\n Effect.tapError(() =>\n worktreeInfo\n ? WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n )\n : Effect.void,\n ),\n Effect.onError(() => removeMountTempDirs(mountsToClean)),\n );\n\n // Run lifecycle with guaranteed cleanup of handle and worktree\n return yield* Effect.gen(function* () {\n // Check interactiveExec is available (no-sandbox always has it; bind-mount/isolated it's optional)\n if (!handle.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn = handle.interactiveExec.bind(handle);\n\n // Build sandbox service and run withSandboxLifecycle\n const sandbox = makeSandboxFromHandle(handle);\n const { worktreePath } = handle;\n\n const applyToHost =\n sandboxProvider.tag === \"isolated\" && worktreeInfo\n ? () => syncOut(hostWorkPath, handle as IsolatedSandboxHandle)\n : () => Effect.void; // bind-mount and no-sandbox don't need sync\n\n const lifecycleEffect = withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: worktreePath,\n hooks,\n branch: lifecycleBranch,\n hostWorktreePath: isHeadMode ? hostRepoDir : worktreeInfo?.path,\n applyToHost,\n timeouts: options.timeouts,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n // Preprocess prompt (expand !`command` shell expressions inside sandbox).\n // Skip when no prompt source was provided, or when inline (literal passthrough).\n const fullPrompt =\n !hasPromptSource || isInlinePrompt\n ? substitutedPrompt\n : yield* preprocessPrompt(\n substitutedPrompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n // Build interactive args and run the session\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: sandboxProvider.tag !== \"none\",\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(async () =>\n interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: worktreePath,\n }),\n ),\n options.signal,\n );\n\n return result.exitCode;\n }),\n );\n\n const lifecycleResult = yield* lifecycleEffect;\n\n const exitCode = lifecycleResult.result;\n\n // Check for uncommitted changes (worktree mode only)\n let preservedWorktreePath: string | undefined;\n if (worktreeInfo) {\n const hasUncommitted = yield* WorktreeManager.hasUncommittedChanges(\n worktreeInfo.path,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (hasUncommitted) {\n preservedWorktreePath = worktreeInfo.path;\n }\n }\n\n // Clean up worktree if not preserved\n if (worktreeInfo && preservedWorktreePath === undefined) {\n yield* WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n );\n }\n\n // Final summary\n yield* d.summary(\"Session Complete\", {\n Commits: String(lifecycleResult.commits.length),\n Branch: lifecycleResult.branch,\n \"Exit code\": String(exitCode),\n ...(preservedWorktreePath === undefined\n ? {}\n : { \"Preserved worktree\": preservedWorktreePath }),\n });\n\n return {\n commits: lifecycleResult.commits,\n branch: lifecycleResult.branch,\n preservedWorktreePath,\n exitCode,\n };\n }).pipe(\n // On error, always clean up worktree (on success, handled above with preserve check)\n Effect.tapError(() =>\n worktreeInfo\n ? WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n )\n : Effect.void,\n ),\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () => handle.close().catch(() => {})).pipe(\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n });\n\n let result: InteractiveResult;\n try {\n result = await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n options.signal?.throwIfAborted();\n throw error;\n }\n\n return result;\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { Effect, Layer, Ref } from \"effect\";\nimport { shellEscape } from \"./AgentProvider.js\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport {\n ClackDisplay,\n Display,\n FileDisplay,\n SilentDisplay,\n} from \"./Display.js\";\nimport type { DisplayEntry } from \"./Display.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult } from \"./Orchestrator.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport type { LoggingOption, Timeouts } from \"./run.js\";\nimport {\n buildAgentStreamHandler,\n buildCompletionMessage,\n buildContextWindowLines,\n buildLogFilename,\n printFileDisplayStartup,\n} from \"./run.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SyncError, SyncOutPathError } from \"./errors.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport {\n reuseSandboxFactoryLayer,\n SANDBOX_REPO_DIR,\n resolveGitMounts,\n} from \"./SandboxFactory.js\";\nimport type { MountEntry, SandboxService } from \"./SandboxFactory.js\";\nimport type {\n SandboxProvider,\n BindMountSandboxHandle,\n BindMountSandboxProvider,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n MergeToHeadBranchStrategy,\n NamedBranchStrategy,\n ExecResult,\n} from \"./SandboxProvider.js\";\nimport { startSandbox } from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport {\n assertForkSupported,\n assertResumeSessionExists,\n} from \"./resumePrecheck.js\";\nimport { registerShutdown } from \"./shutdownRegistry.js\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\nexport interface CreateSandboxOptions {\n /** Explicit branch for the worktree (required). */\n readonly branch: string;\n /**\n * Ref to fork from when `branch` does not yet exist. Ignored when the branch\n * already exists. Defaults to `HEAD`.\n */\n readonly baseBranch?: string;\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** @internal Test-only overrides to bypass the sandbox provider. */\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n /**\n * Fake bind-mount handle exposed to the orchestrator's session-capture path.\n * Only honored when `sandbox.tag === \"bind-mount\"`. Used to exercise the\n * `bindMountHandle` flow in tests without booting a real container.\n */\n readonly bindMountHandle?: BindMountSandboxHandle;\n };\n}\n\n/**\n * Options accepted by `SandboxRunResult.resume()` / `.fork()`. Mirrors\n * `ResumeRunResultOptions` in `run.ts` — drops the fields owned by the\n * captured run (prompt, iteration count, resumeSession/forkSession bookkeeping).\n *\n * Defined as the base interface that `SandboxRunOptions` extends — the\n * interface-extends shape is cheaper for the TS checker than\n * `Omit<SandboxRunOptions, ...>` (which forces a mapped-type computation\n * on every reference).\n */\nexport interface ResumeSandboxRunResultOptions {\n /** Key-value map for {{KEY}} placeholder substitution in prompts. */\n readonly promptArgs?: PromptArgs;\n /** Substring(s) the agent emits to stop the iteration loop early. */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. Default: 600. */\n readonly idleTimeoutSeconds?: number;\n /** Grace window in seconds after a completion signal is observed but the agent process has not exited. See ADR 0019. Default: 60. */\n readonly completionTimeoutSeconds?: number;\n /** Display name for this run. */\n readonly name?: string;\n /** Logging mode. */\n readonly logging?: LoggingOption;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - Pre-aborted signal rejects immediately without setup.\n * - Mid-iteration abort kills the in-flight agent subprocess.\n * - The rejected promise surfaces `signal.reason` verbatim.\n * - The `Sandbox` handle remains usable after abort — call `.run()` again\n * with a fresh signal, or `.close()` to tear down.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface SandboxRunOptions extends ResumeSandboxRunResultOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")). */\n readonly agent: AgentProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Maximum iterations to run (default: 1). */\n readonly maxIterations?: number;\n /** Resume a prior agent session by id. The session JSONL must exist on the host (captured by a prior `sandbox.run()`). Incompatible with `maxIterations > 1`. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it. The parent session JSONL is left intact and the agent writes a new\n * session under a fresh id. Exposed as the public `.fork()` method on\n * `SandboxRunResult` rather than as a stand-alone caller option — see\n * ADR 0018.\n *\n * @internal\n */\n readonly forkSession?: boolean;\n}\n\nexport interface SandboxRunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run. */\n readonly commits: { sha: string }[];\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n /**\n * Continue the last captured agent session for exactly one iteration inside\n * the same long-lived sandbox. Present only when the provider supports\n * resume (`sessionStorage` populated) and a session id was captured.\n */\n readonly resume?: (\n prompt: string,\n options?: ResumeSandboxRunResultOptions,\n ) => Promise<SandboxRunResult>;\n /**\n * Fork the last captured agent session for exactly one iteration inside the\n * same long-lived sandbox: the parent session JSONL is left intact and the\n * child run gets its own session id. Present only when the provider\n * supports resume (`sessionStorage` populated) and a session id was\n * captured. See ADR 0018 for fork semantics.\n */\n readonly fork?: (\n prompt: string,\n options?: ResumeSandboxRunResultOptions,\n ) => Promise<SandboxRunResult>;\n}\n\nexport interface SandboxInteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")). */\n readonly agent: AgentProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Key-value map for {{KEY}} placeholder substitution in prompts. */\n readonly promptArgs?: PromptArgs;\n /** Display name for this interactive session. */\n readonly name?: string;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - Pre-aborted signal rejects immediately without setup.\n * - The rejected promise surfaces `signal.reason` verbatim.\n * - The `Sandbox` handle remains usable after abort.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface SandboxInteractiveResult {\n /** List of commits made during the interactive session. */\n readonly commits: { sha: string }[];\n /** Exit code of the interactive process. */\n readonly exitCode: number;\n}\n\nexport interface CloseResult {\n /** Host path to the preserved worktree, set when the worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n}\n\nexport interface Sandbox {\n /** The branch the worktree is on. */\n readonly branch: string;\n /** Host path to the worktree. */\n readonly worktreePath: string;\n /**\n * The provider's id for this sandbox, for a supervisor outside this process\n * (a run registry, a kill step for stuck runs) to address it with the\n * provider's own tools:\n *\n * - `docker()`: the container name: `docker inspect <sandboxId>`,\n * `docker rm -f <sandboxId>`.\n * - `podman()`: the container name: `podman inspect <sandboxId>`,\n * `podman rm -f <sandboxId>`.\n * - `vercel()`: the Vercel sandbox's id (its `name` from `@vercel/sandbox`\n * 2 on, its `sandboxId` in 1.x): pass it to the SDK's `Sandbox.get()`,\n * then call `stop()`.\n * - `daytona()`: the Daytona sandbox id: `daytona.get(<sandboxId>)`, then\n * `delete()`, from `@daytona/sdk`.\n * - `modal()`: the Modal sandbox id: `modal.sandboxes.fromId(<sandboxId>)`,\n * then `terminate()`, from `modal`.\n * - `sprites()`: the Sprite's name: `client.getSprite(<sandboxId>)`, then\n * `delete()`, from `@fly/sprites`.\n * - A custom provider: whatever its handle's `sandboxId` is.\n *\n * `undefined` for `noSandbox()` and the native `bwrap()` and `seatbelt()`\n * sandboxes: their sandbox is a child process of this one, with nothing\n * outside it to address.\n */\n readonly sandboxId?: string;\n /** Invoke an agent inside the existing sandbox. */\n run(options: SandboxRunOptions): Promise<SandboxRunResult>;\n /** Launch an interactive agent session inside the existing sandbox. */\n interactive(\n options: SandboxInteractiveOptions,\n ): Promise<SandboxInteractiveResult>;\n /**\n * Execute a command inside the existing sandbox.\n *\n * `cwd` defaults to the sandbox repo path (same default `interactive()`\n * uses), so callers get the same working directory across providers. Pass\n * `cwd` to override.\n *\n * Returns the full `ExecResult` — non-zero `exitCode` is surfaced, not\n * thrown. Callers that want strict semantics should check `result.exitCode`\n * themselves (matching the contract of `BindMountSandboxHandle.exec`).\n */\n exec(command: string, options?: SandboxExecOptions): Promise<ExecResult>;\n /** Tear down the sandbox and worktree. */\n close(): Promise<CloseResult>;\n /** Auto teardown via `await using`. */\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/** Options accepted by `Sandbox.exec()`. Mirrors the provider handle's `exec` options. */\nexport interface SandboxExecOptions {\n /** Per-line stdout callback for streaming output. */\n readonly onLine?: (line: string) => void;\n /** Working directory for the command. Defaults to the sandbox repo path. */\n readonly cwd?: string;\n /** Run the whole command as root, when the provider supports it. */\n readonly sudo?: boolean;\n /** Stdin payload — piped to the child process and then closed. Avoids the Linux 128 KB per-arg limit. */\n readonly stdin?: string;\n}\n\n/** @internal Context for building Sandbox handle methods. */\ninterface SandboxHandleContext {\n readonly branch: string;\n readonly worktreePath: string;\n readonly hostRepoDir: string;\n readonly sandboxRepoDir: string;\n readonly sandbox: SandboxService;\n readonly providerHandle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle\n | undefined;\n /**\n * Pre-narrowed bind-mount handle, set when the provider is a bind-mount\n * provider. Required by the orchestrator's session capture path\n * (`AgentSessionStorage.captureToHost/resumeIntoSandbox`), which is typed\n * on `BindMountSandboxHandle` and calls `copyFileOut`/`copyFileIn` —\n * methods that no-sandbox and isolated handles do not implement.\n */\n readonly bindMountHandle: BindMountSandboxHandle | undefined;\n /** Provider tag, used by resumeSession to dispatch the host-side session lookup. */\n readonly providerTag: SandboxProvider[\"tag\"];\n /** The sandbox provider, checked before an interactive session starts. */\n readonly sandboxProvider: SandboxProvider;\n /** The sandbox provider's env, checked against each run's agent env for overlapping keys. */\n readonly sandboxProviderEnv: Record<string, string>;\n readonly applyToHost: () => Effect.Effect<void, SyncError | SyncOutPathError>;\n readonly timeouts?: Timeouts;\n /** Worktree branch strategy. Set only when the handle is backed by a\n * `createWorktree(...)` handle; absent for top-level `createSandbox()`,\n * which is always explicit-branch. When `type === \"merge-to-head\"`, each\n * run()/interactive() routes through the lifecycle's merge step and the\n * worktree's source branch is preserved across calls. */\n readonly branchStrategy?: MergeToHeadBranchStrategy | NamedBranchStrategy;\n}\n\n/**\n * @internal Applies an agent provider's `env` to its print command.\n *\n * `run()` merges the agent's env into the container env at start. A\n * long-lived sandbox (`createSandbox()`, `worktree.createSandbox()`) is\n * started before any agent is chosen, and each `sandbox.run()` may use a\n * different agent, so the env is exported in the agent's own shell instead.\n * It reaches only that run's agent process, with the same precedence as\n * `run()` (agent env overrides `.sandcastle/.env`) and the same rejection of\n * keys that overlap the sandbox provider's env.\n */\nconst withAgentEnv = (\n agent: AgentProvider,\n sandboxProviderEnv: Record<string, string>,\n): AgentProvider => {\n const entries = Object.entries(agent.env);\n if (entries.length === 0) {\n return agent;\n }\n mergeProviderEnv({\n resolvedEnv: {},\n agentProviderEnv: agent.env,\n sandboxProviderEnv,\n });\n const invalid = entries\n .map(([key]) => key)\n .filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));\n if (invalid.length > 0) {\n throw new Error(\n `Invalid agent provider env key(s): ${invalid.join(\", \")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`,\n );\n }\n const exports = entries\n .map(([key, value]) => `export ${key}=${shellEscape(value)}; `)\n .join(\"\");\n return {\n ...agent,\n buildPrintCommand: (options) => {\n const printCommand = agent.buildPrintCommand(options);\n return { ...printCommand, command: exports + printCommand.command };\n },\n };\n};\n\n/**\n * @internal Builds a Sandbox handle with run() and interactive() methods.\n * The close callback controls teardown behavior — top-level createSandbox()\n * cleans up both container and worktree, while worktree-backed sandboxes\n * only tear down the container.\n */\nconst buildSandboxHandle = (\n ctx: SandboxHandleContext,\n close: () => Promise<CloseResult>,\n): Sandbox => {\n const {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n providerHandle,\n bindMountHandle,\n applyToHost,\n timeouts,\n branchStrategy,\n } = ctx;\n // Routing for the lifecycle: in merge-to-head mode pass `branch: undefined`\n // (so the lifecycle records host's current branch and merges back) and keep\n // the worktree's source branch alive for subsequent calls. In all other\n // cases (top-level createSandbox, named-branch worktree) forward `branch`\n // as-is and let the lifecycle delete the temp branch normally.\n const mergeToHead = branchStrategy?.type === \"merge-to-head\";\n\n const sandboxHandle: Sandbox = {\n branch,\n worktreePath,\n sandboxId:\n providerHandle !== undefined && \"sandboxId\" in providerHandle\n ? providerHandle.sandboxId\n : undefined,\n\n run: async (runOptions: SandboxRunOptions): Promise<SandboxRunResult> => {\n // If signal is already aborted, reject immediately without any setup\n runOptions.signal?.throwIfAborted();\n\n const { prompt, promptFile, maxIterations = 1 } = runOptions;\n // The container was started before this agent was chosen, so the\n // agent's env is applied to its own process instead (see withAgentEnv).\n const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);\n\n validateTimeoutOptions(runOptions);\n\n const isResuming =\n runOptions.resumeSession !== undefined &&\n runOptions.resumeSession !== \"\";\n\n // Validate: resumeSession + maxIterations > 1 is not allowed.\n if (isResuming && maxIterations > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n // Validate: forkSession only makes sense alongside resumeSession.\n if (runOptions.forkSession === true && !isResuming) {\n throw new Error(\n \"forkSession requires resumeSession. \" +\n \"Use sandboxRunResult.fork(prompt) to fork the most recent captured session.\",\n );\n }\n if (runOptions.forkSession === true) {\n assertForkSupported(provider);\n }\n\n // Validate: resumeSession file must exist on the host before launching.\n if (isResuming) {\n await assertResumeSessionExists({\n provider,\n sandboxTag: ctx.providerTag,\n hostRepoDir,\n resumeSession: runOptions.resumeSession,\n });\n }\n\n const resolved = await Effect.runPromise(\n resolvePrompt({ prompt, promptFile }).pipe(\n Effect.provide(NodeContext.layer),\n ),\n );\n const rawPrompt = resolved.text;\n const isInlinePrompt = resolved.source === \"inline\";\n\n const userArgs = runOptions.promptArgs ?? {};\n const currentHostBranch = await Effect.runPromise(\n WorktreeManager.getCurrentBranch(hostRepoDir),\n );\n\n const displayRef = Ref.unsafeMake<readonly DisplayEntry[]>([]);\n const silentDisplayLayer = SilentDisplay.layer(displayRef);\n\n const resolvedPrompt = await Effect.runPromise(\n Effect.gen(function* () {\n if (isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(userArgs);\n return rawPrompt;\n }\n yield* validateNoBuiltInArgOverride(userArgs);\n const effectiveArgs = {\n SOURCE_BRANCH: branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n return yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n }).pipe(Effect.provide(silentDisplayLayer)),\n );\n\n const resolvedLogging: LoggingOption = runOptions.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(branch, undefined, runOptions.name),\n ),\n };\n\n const runDisplayLayer =\n resolvedLogging.type === \"file\"\n ? (() => {\n printFileDisplayStartup({\n logPath: resolvedLogging.path,\n agentName: runOptions.name,\n branch,\n });\n return Layer.provide(\n FileDisplay.layer(resolvedLogging.path),\n NodeFileSystem.layer,\n );\n })()\n : silentDisplayLayer;\n\n const reuseFactoryLayer = reuseSandboxFactoryLayer(\n {\n hostWorktreePath: worktreePath,\n sandboxRepoPath: sandboxRepoDir,\n applyToHost,\n bindMountHandle,\n },\n sandbox,\n );\n\n const streamEmitterLayer = agentStreamEmitterLayer(\n buildAgentStreamHandler(resolvedLogging),\n );\n\n const runLayer = Layer.mergeAll(\n reuseFactoryLayer,\n runDisplayLayer,\n streamEmitterLayer,\n );\n\n let result;\n try {\n result = await Effect.runPromise(\n Effect.gen(function* () {\n const display = yield* Display;\n yield* display.intro(runOptions.name ?? \"sandcastle\");\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir,\n iterations: maxIterations,\n prompt: resolvedPrompt,\n branch: mergeToHead ? undefined : branch,\n provider,\n completionSignal: runOptions.completionSignal,\n idleTimeoutSeconds: runOptions.idleTimeoutSeconds,\n completionTimeoutSeconds: runOptions.completionTimeoutSeconds,\n name: runOptions.name,\n resumeSession: runOptions.resumeSession,\n forkSession: runOptions.forkSession,\n signal: runOptions.signal,\n skipPromptExpansion: isInlinePrompt,\n timeouts,\n keepSourceBranch: mergeToHead,\n });\n\n const completion = buildCompletionMessage(\n orchestrateResult.completionSignal,\n orchestrateResult.iterations.length,\n );\n yield* display.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(\n orchestrateResult.iterations,\n )) {\n yield* display.text(line);\n }\n\n return orchestrateResult;\n }).pipe(Effect.provide(runLayer)),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim\n runOptions.signal?.throwIfAborted();\n throw error;\n }\n\n const baseResult: SandboxRunResult = {\n iterations: result.iterations,\n completionSignal: result.completionSignal,\n stdout: result.stdout,\n commits: result.commits,\n logFilePath:\n resolvedLogging.type === \"file\" ? resolvedLogging.path : undefined,\n };\n\n // Expose .resume()/.fork() only when the provider supports session\n // capture and a session id was actually captured on the last iteration.\n // The functions re-enter the same long-lived sandbox by calling\n // sandboxHandle.run() — container and worktree stay warm.\n const lastIteration = result.iterations.at(-1);\n if (\n provider.sessionStorage &&\n lastIteration?.sessionId !== undefined &&\n lastIteration.sessionId !== \"\"\n ) {\n const capturedSessionId = lastIteration.sessionId;\n return {\n ...baseResult,\n resume: (\n nextPrompt: string,\n resumeOptions?: ResumeSandboxRunResultOptions,\n ): Promise<SandboxRunResult> =>\n sandboxHandle.run({\n ...runOptions,\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n ...resumeOptions,\n prompt: nextPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: capturedSessionId,\n }),\n fork: (\n nextPrompt: string,\n forkOptions?: ResumeSandboxRunResultOptions,\n ): Promise<SandboxRunResult> =>\n sandboxHandle.run({\n ...runOptions,\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n ...forkOptions,\n prompt: nextPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: capturedSessionId,\n forkSession: true,\n }),\n };\n }\n\n return baseResult;\n },\n\n interactive: async (\n interactiveOptions: SandboxInteractiveOptions,\n ): Promise<SandboxInteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n interactiveOptions.signal?.throwIfAborted();\n assertInteractiveSupported(ctx.sandboxProvider);\n\n const { agent: provider, prompt, promptFile } = interactiveOptions;\n\n const buildInteractiveArgs =\n provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n if (!providerHandle?.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn =\n providerHandle.interactiveExec.bind(providerHandle);\n\n let lifecycleResult;\n try {\n lifecycleResult = await Effect.runPromise(\n Effect.gen(function* () {\n const resolved = yield* resolvePrompt({ prompt, promptFile });\n const rawPrompt = resolved.text;\n const isInlinePrompt = resolved.source === \"inline\";\n\n const userArgs = interactiveOptions.promptArgs ?? {};\n const currentHostBranch =\n yield* WorktreeManager.getCurrentBranch(hostRepoDir);\n\n let resolvedPrompt: string;\n if (isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(userArgs);\n resolvedPrompt = rawPrompt;\n } else {\n yield* validateNoBuiltInArgOverride(userArgs);\n const effectiveArgs = {\n SOURCE_BRANCH: branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n };\n const builtInArgKeysSet = new Set<string>(\n BUILT_IN_PROMPT_ARG_KEYS,\n );\n resolvedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n }\n\n return yield* withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir,\n branch: mergeToHead ? undefined : branch,\n hostWorktreePath: worktreePath,\n applyToHost,\n timeouts,\n keepSourceBranch: mergeToHead,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n const fullPrompt = isInlinePrompt\n ? resolvedPrompt\n : yield* preprocessPrompt(\n resolvedPrompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: true,\n });\n const execPromise = interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: sandboxRepoDir,\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(() => execPromise),\n interactiveOptions.signal,\n );\n\n return result.exitCode;\n }),\n );\n }).pipe(\n Effect.provide(\n Layer.mergeAll(ClackDisplay.layer, NodeContext.layer),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim\n interactiveOptions.signal?.throwIfAborted();\n throw error;\n }\n\n return {\n commits: lifecycleResult.commits,\n exitCode: lifecycleResult.result,\n };\n },\n\n exec: async (\n command: string,\n options?: SandboxExecOptions,\n ): Promise<ExecResult> => {\n const mergedOptions = { cwd: sandboxRepoDir, ...options };\n if (providerHandle) {\n return providerHandle.exec(command, mergedOptions);\n }\n // Test-mode fallback: no providerHandle, only the Effect SandboxService.\n return Effect.runPromise(sandbox.exec(command, mergedOptions));\n },\n\n close: async (): Promise<CloseResult> => close(),\n\n [Symbol.asyncDispose]: async (): Promise<void> => {\n await sandboxHandle.close();\n },\n };\n\n return sandboxHandle;\n};\n\n/** @internal Options for createSandboxFromWorktree — used by worktree.createSandbox(). */\nexport interface CreateSandboxFromWorktreeOptions {\n readonly branch: string;\n readonly worktreePath: string;\n readonly hostRepoDir: string;\n readonly sandbox: SandboxProvider;\n readonly hooks?: SandboxHooks;\n readonly copyToWorktree?: string[];\n readonly timeouts?: Timeouts;\n /** Forwarded to the Sandbox handle. Set by `createWorktree` so the handle\n * can route run()/interactive() correctly: for `merge-to-head`, each call\n * merges back to the host's current branch and the worktree's source\n * branch is preserved; for `branch`, the lifecycle is driven as\n * explicit-branch mode. Absent for top-level `createSandbox()`. */\n readonly branchStrategy?: MergeToHeadBranchStrategy | NamedBranchStrategy;\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n /**\n * Fake bind-mount handle exposed to the orchestrator's session-capture path.\n * Only honored when `sandbox.tag === \"bind-mount\"`.\n */\n readonly bindMountHandle?: BindMountSandboxHandle;\n };\n}\n\ntype ProviderHandle =\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n\ninterface StartProviderSandboxOptions {\n readonly provider: SandboxProvider;\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly env: Record<string, string>;\n readonly copyToWorktree: string[] | undefined;\n /** Temp dirs behind the git mounts get pushed here, for the caller to remove. */\n readonly mountsToClean: MountEntry[];\n}\n\n/**\n * Starts a bind-mount provider's sandbox on `worktreePath`, after resolving\n * the host repo's git mounts and patching them for Windows.\n */\nconst startBindMountWithGitMounts = (\n provider: BindMountSandboxProvider,\n {\n hostRepoDir,\n worktreePath,\n env,\n mountsToClean,\n }: StartProviderSandboxOptions,\n) =>\n resolveGitMounts(join(hostRepoDir, \".git\")).pipe(\n Effect.provide(NodeFileSystem.layer),\n Effect.catchAll(() => Effect.succeed([])),\n // Patch git mounts for Windows worktree compatibility (ADR-0006)\n Effect.flatMap((gitMounts) =>\n patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR),\n ),\n Effect.tap((gitMounts) => {\n mountsToClean.push(...gitMounts);\n }),\n Effect.flatMap((gitMounts) =>\n startSandbox({\n provider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n ),\n );\n\n/** Starts `provider`'s sandbox on `worktreePath`, whatever its tag. */\nconst startProviderSandbox = (options: StartProviderSandboxOptions) => {\n const { provider, hostRepoDir, worktreePath, env } = options;\n if (provider.tag === \"isolated\") {\n return startSandbox({\n provider,\n hostRepoDir: worktreePath,\n env,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n });\n }\n if (provider.tag === \"none\") {\n return startSandbox({\n provider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n });\n }\n return startBindMountWithGitMounts(provider, options);\n};\n\n/**\n * Copies `copyToWorktree` paths from the host repo into the worktree.\n * Isolated providers skip this: startSandbox copies their paths in.\n */\nconst copyIntoWorktree = (\n options: Pick<\n CreateSandboxOptions,\n \"copyToWorktree\" | \"sandbox\" | \"timeouts\"\n >,\n hostRepoDir: string,\n worktreePath: string,\n) =>\n options.copyToWorktree &&\n options.copyToWorktree.length > 0 &&\n options.sandbox.tag !== \"isolated\"\n ? copyToWorktree(\n options.copyToWorktree,\n hostRepoDir,\n worktreePath,\n options.timeouts?.copyToWorktreeMs,\n )\n : Effect.void;\n\n/** The `buildSandboxHandle` fields that come from the provider and its handle. */\nconst providerHandleFields = (\n provider: SandboxProvider,\n providerHandle: ProviderHandle | undefined,\n worktreePath: string,\n) => ({\n providerHandle,\n // Pre-narrow the bind-mount handle for the orchestrator's session-capture\n // path. Gating on the provider tag avoids handing a NoSandbox/Isolated\n // handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage and\n // turning a missing-feature into a runtime SessionCaptureError.\n bindMountHandle:\n provider.tag === \"bind-mount\"\n ? (providerHandle as BindMountSandboxHandle | undefined)\n : undefined,\n providerTag: provider.tag,\n sandboxProvider: provider,\n sandboxProviderEnv: provider.env,\n // Syncs an isolated sandbox's changes back to the host worktree.\n applyToHost:\n provider.tag === \"isolated\" && providerHandle\n ? () => syncOut(worktreePath, providerHandle as IsolatedSandboxHandle)\n : () => Effect.void,\n});\n\n/**\n * Starts the sandbox on `worktreePath`: the provider's, or the local sandbox\n * layer in test mode.\n */\nconst startSandboxOnWorktree = ({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n}: {\n readonly options: Pick<\n CreateSandboxOptions,\n \"sandbox\" | \"_test\" | \"copyToWorktree\"\n >;\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly mountsToClean: MountEntry[];\n}) =>\n Effect.gen(function* () {\n if (options._test?.buildSandbox) {\n return {\n sandbox: options._test.buildSandbox(worktreePath),\n sandboxRepoDir: worktreePath,\n providerHandle: options._test.bindMountHandle,\n };\n }\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: {},\n sandboxProviderEnv: options.sandbox.env,\n });\n const startResult = yield* startProviderSandbox({\n provider: options.sandbox,\n hostRepoDir,\n worktreePath,\n env,\n copyToWorktree: options.copyToWorktree,\n mountsToClean,\n });\n return {\n providerHandle: startResult.handle,\n sandbox: startResult.sandbox,\n sandboxRepoDir: startResult.worktreePath,\n };\n });\n\n/**\n * Runs the onSandboxReady hooks, sandbox-side and host-side in parallel,\n * after marking the sandbox repo a git safe.directory. A no-op without hooks.\n */\nconst runOnSandboxReadyHooks = ({\n sandbox,\n sandboxRepoDir,\n worktreePath,\n hooks,\n}: {\n readonly sandbox: SandboxService;\n readonly sandboxRepoDir: string;\n readonly worktreePath: string;\n readonly hooks: SandboxHooks | undefined;\n}) => {\n const sandboxOnReady = hooks?.sandbox?.onSandboxReady ?? [];\n const hostOnReady = hooks?.host?.onSandboxReady ?? [];\n if (sandboxOnReady.length === 0 && hostOnReady.length === 0) {\n return Effect.void;\n }\n return Effect.gen(function* () {\n yield* sandbox.exec(\n `git config --global --add safe.directory \"${sandboxRepoDir}\"`,\n );\n const sandboxEffects = sandboxOnReady.map((hook) =>\n sandbox.exec(hook.command, {\n cwd: sandboxRepoDir,\n sudo: hook.sudo,\n }),\n );\n const allEffects = [\n ...sandboxEffects,\n ...(hostOnReady.length > 0\n ? [runHostHooks(hostOnReady, worktreePath)]\n : []),\n ];\n yield* Effect.all(allEffects, { concurrency: \"unbounded\" });\n });\n};\n\n/** A close() that tears down the container only, once, and its mount temp dirs. */\nconst closeContainerOnly = (\n providerHandle: ProviderHandle | undefined,\n mountsToClean: readonly MountEntry[],\n): (() => Promise<CloseResult>) => {\n let closed = false;\n return async () => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n if (providerHandle) {\n await providerHandle.close();\n }\n await Effect.runPromise(removeMountTempDirs(mountsToClean));\n return { preservedWorktreePath: undefined };\n };\n};\n\n/**\n * @internal Creates a sandbox backed by an existing worktree.\n * Split ownership: close() tears down the container only, leaving the worktree intact.\n * Used by Worktree.createSandbox().\n */\nexport const createSandboxFromWorktree = async (\n options: CreateSandboxFromWorktreeOptions,\n): Promise<Sandbox> => {\n const { branch, worktreePath, hostRepoDir } = options;\n validateTimeoutOptions(options);\n\n // 1. Copy files if requested (bind-mount only)\n await Effect.runPromise(copyIntoWorktree(options, hostRepoDir, worktreePath));\n\n // 2. Start sandbox via provider or local sandbox layer (test mode)\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n const { providerHandle, sandbox, sandboxRepoDir } = await Effect.runPromise(\n startSandboxOnWorktree({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n }).pipe(\n Effect.onError(() => removeMountTempDirs(mountsToClean)),\n Effect.provide(NodeContext.layer),\n ),\n );\n\n // 3. Run onSandboxReady hooks (sandbox-side and host-side in parallel)\n await Effect.runPromise(\n runOnSandboxReadyHooks({\n sandbox,\n sandboxRepoDir,\n worktreePath,\n hooks: options.hooks,\n }),\n );\n\n // 4. Build and return sandbox handle — container-only close (worktree owns worktree)\n return buildSandboxHandle(\n {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n ...providerHandleFields(options.sandbox, providerHandle, worktreePath),\n timeouts: options.timeouts,\n branchStrategy: options.branchStrategy,\n },\n closeContainerOnly(providerHandle, mountsToClean),\n );\n};\n\n/**\n * Eagerly creates a git worktree on the provided explicit branch and starts\n * a sandbox with the worktree bind-mounted. Returns a Sandbox handle that\n * can be reused across multiple `run()` calls.\n */\nexport const createSandbox = async (\n options: CreateSandboxOptions,\n): Promise<Sandbox> => {\n const { branch } = options;\n validateTimeoutOptions(options);\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n\n // Resolve cwd, create the worktree, and set up the sandbox in a single Effect.\n // Once the worktree exists, any later failure (e.g. a missing image surfacing\n // when the provider creates the container) tears down the container — if it\n // started — and removes the worktree so it is not orphaned on disk.\n const { hostRepoDir, worktreePath, providerHandle, sandbox, sandboxRepoDir } =\n await Effect.runPromise(\n Effect.gen(function* () {\n const hostRepoDir = yield* resolveCwd(options.cwd);\n\n yield* WorktreeManager.pruneStale(hostRepoDir).pipe(\n Effect.catchAll(() => Effect.void),\n );\n const { path: worktreePath } = yield* WorktreeManager.create(\n hostRepoDir,\n { branch, baseBranch: options.baseBranch },\n );\n\n const prepared = yield* Effect.gen(function* () {\n // Copy files (bind-mount/no-sandbox only; isolated copies in startSandbox).\n yield* copyIntoWorktree(options, hostRepoDir, worktreePath);\n\n // Run host.onWorktreeReady hooks (after copy, before sandbox creation).\n const onWorktreeReady = options.hooks?.host?.onWorktreeReady;\n if (onWorktreeReady !== undefined && onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, worktreePath);\n }\n\n // Start the sandbox via the test layer or the shared startSandbox helper.\n const { providerHandle, sandbox, sandboxRepoDir } =\n yield* startSandboxOnWorktree({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n });\n\n // Run onSandboxReady hooks (sandbox-side and host-side in parallel). If\n // they fail, tear down the container that just started before the outer\n // handler removes the worktree.\n yield* runOnSandboxReadyHooks({\n sandbox,\n sandboxRepoDir,\n worktreePath,\n hooks: options.hooks,\n }).pipe(\n Effect.onError(() =>\n (providerHandle\n ? Effect.promise(() => providerHandle.close().catch(() => {}))\n : Effect.void\n ).pipe(Effect.andThen(removeMountTempDirs(mountsToClean))),\n ),\n );\n\n return { providerHandle, sandbox, sandboxRepoDir };\n }).pipe(\n Effect.onError(() =>\n WorktreeManager.remove(worktreePath).pipe(\n Effect.catchAll(() => Effect.void),\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n\n return { hostRepoDir, worktreePath, ...prepared };\n }).pipe(Effect.provide(NodeContext.layer)),\n );\n\n let closed = false;\n\n const forceCleanup = () => {\n console.error(`\\nWorktree preserved at ${worktreePath}`);\n console.error(` To review: cd ${worktreePath}`);\n console.error(` To clean up: git worktree remove --force ${worktreePath}`);\n };\n\n // Route cleanup through the shared registry so concurrent sandboxes share one\n // SIGINT/SIGTERM/exit listener instead of tripping MaxListenersExceededWarning.\n const unregisterShutdown = registerShutdown(forceCleanup);\n\n // Build close function\n const doClose = async (): Promise<CloseResult> => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n\n return Effect.runPromise(\n Effect.gen(function* () {\n if (providerHandle) {\n yield* Effect.promise(() => providerHandle.close());\n }\n yield* removeMountTempDirs(mountsToClean);\n\n // Preserve the worktree when it has uncommitted changes; otherwise remove it.\n const isDirty = yield* WorktreeManager.hasUncommittedChanges(\n worktreePath,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (isDirty) {\n return { preservedWorktreePath: worktreePath };\n }\n\n yield* WorktreeManager.remove(worktreePath).pipe(\n Effect.catchAll(() => Effect.void),\n );\n return { preservedWorktreePath: undefined };\n }),\n );\n };\n\n // Return the Sandbox handle\n return buildSandboxHandle(\n {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n // applyToHost is built once, reused across runs.\n ...providerHandleFields(options.sandbox, providerHandle, worktreePath),\n timeouts: options.timeouts,\n },\n async () => {\n unregisterShutdown();\n return doClose();\n },\n );\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport { Effect, Layer } from \"effect\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display, FileDisplay } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport {\n reuseSandboxFactoryLayer,\n makeSandboxFromHandle,\n resolveGitMounts,\n SANDBOX_REPO_DIR,\n} from \"./SandboxFactory.js\";\nimport type { MountEntry, SandboxService } from \"./SandboxFactory.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type {\n SandboxProvider,\n MergeToHeadBranchStrategy,\n NamedBranchStrategy,\n BindMountSandboxHandle,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n} from \"./SandboxProvider.js\";\nimport type { CloseResult, Sandbox } from \"./createSandbox.js\";\nimport { createSandboxFromWorktree } from \"./createSandbox.js\";\nimport type { InteractiveResult } from \"./interactive.js\";\nimport {\n buildAgentStreamHandler,\n buildCompletionMessage,\n buildContextWindowLines,\n buildLogFilename,\n printFileDisplayStartup,\n} from \"./run.js\";\nimport type { LoggingOption, Timeouts } from \"./run.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult } from \"./Orchestrator.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { startSandbox } from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport { assertResumeSessionExists } from \"./resumePrecheck.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { noSandbox } from \"./sandboxes/no-sandbox.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\n/** Branch strategies valid for createWorktree — head is excluded. */\nexport type WorktreeBranchStrategy =\n | MergeToHeadBranchStrategy\n | NamedBranchStrategy;\n\nexport interface CreateWorktreeOptions {\n /** Branch strategy — only 'branch' and 'merge-to-head' are allowed. */\n readonly branchStrategy: WorktreeBranchStrategy;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Lifecycle hooks grouped by execution location (host or sandbox).\n * Only `host.onWorktreeReady` is executed here — other hooks are passed through\n * to `run()`, `interactive()`, or `createSandbox()`. */\n readonly hooks?: SandboxHooks;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n}\n\nexport interface WorktreeInteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker(), noSandbox()). Defaults to noSandbox(). */\n readonly sandbox?: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Optional name for the interactive session. */\n readonly name?: string;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, rejects immediately.\n * - Aborting during an active session kills the agent subprocess.\n * - The worktree is preserved on disk after abort.\n * - The `Worktree` handle remains usable for subsequent operations.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface WorktreeRunOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker()). Required — AFK agents should always be sandboxed. */\n readonly sandbox: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Maximum iterations to run (default: 1). */\n readonly maxIterations?: number;\n /** Substring(s) the agent emits to stop the iteration loop early. */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. Default: 600. */\n readonly idleTimeoutSeconds?: number;\n /** Grace window in seconds after a completion signal is observed but the agent process has not exited. See ADR 0019. Default: 60. */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run. */\n readonly name?: string;\n /** Logging mode. */\n readonly logging?: LoggingOption;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /** Resume a prior Claude Code session by ID. The session JSONL must exist on the host. Incompatible with maxIterations > 1. */\n readonly resumeSession?: string;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, rejects immediately\n * without doing any setup work.\n * - Aborting mid-iteration kills the in-flight agent subprocess.\n * - The worktree is preserved on disk after abort.\n * - The `Worktree` handle remains usable for subsequent operations.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface WorktreeRunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on. */\n readonly branch: string;\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n}\n\nexport interface WorktreeCreateSandboxOptions {\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** @internal Test-only overrides to bypass the sandbox provider. */\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n };\n}\n\nexport interface Worktree {\n /** The branch the worktree is on. */\n readonly branch: string;\n /** Host path to the worktree (worktree). */\n readonly worktreePath: string;\n /** Run an AFK agent in this worktree with a required sandbox. */\n run(options: WorktreeRunOptions): Promise<WorktreeRunResult>;\n /** Run an interactive agent session in this worktree. */\n interactive(options: WorktreeInteractiveOptions): Promise<InteractiveResult>;\n /** Create a long-lived sandbox backed by this worktree's worktree. */\n createSandbox(options: WorktreeCreateSandboxOptions): Promise<Sandbox>;\n /** Clean up the worktree. Preserves worktree if dirty. */\n close(): Promise<CloseResult>;\n /** Auto cleanup via `await using`. */\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/**\n * Creates a git worktree as an independent, first-class worktree.\n * Returns a Worktree handle with close() and [Symbol.asyncDispose]().\n *\n * Only accepts 'branch' and 'merge-to-head' strategies — 'head' is a\n * compile-time type error since head means no worktree.\n */\nexport const createWorktree = async (\n options: CreateWorktreeOptions,\n): Promise<Worktree> => {\n validateTimeoutOptions(options);\n\n const branch =\n options.branchStrategy.type === \"branch\"\n ? options.branchStrategy.branch\n : undefined;\n\n const baseBranch =\n options.branchStrategy.type === \"branch\"\n ? options.branchStrategy.baseBranch\n : undefined;\n\n // Captured for the worktree's run/interactive/createSandbox methods so they\n // can route the branch correctly into `SandboxLifecycle`: in `merge-to-head`\n // mode they pass `branch: undefined` (to trigger the merge step) plus\n // `keepSourceBranch: true` (so the worktree's source branch survives).\n const isMergeToHead = options.branchStrategy.type === \"merge-to-head\";\n\n const { hostRepoDir, worktreeInfo } = await Effect.gen(function* () {\n const repoDir = yield* resolveCwd(options.cwd);\n yield* WorktreeManager.pruneStale(repoDir).pipe(\n Effect.catchAll(() => Effect.void),\n );\n const info = yield* WorktreeManager.create(repoDir, {\n branch,\n baseBranch,\n });\n if (options.copyToWorktree && options.copyToWorktree.length > 0) {\n yield* copyToWorktree(\n options.copyToWorktree,\n repoDir,\n info.path,\n options.timeouts?.copyToWorktreeMs,\n );\n }\n // Run host.onWorktreeReady hooks after copyToWorktree, before sandbox creation\n const onWorktreeReady = options.hooks?.host?.onWorktreeReady;\n if (onWorktreeReady !== undefined && onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, info.path);\n }\n return { hostRepoDir: repoDir, worktreeInfo: info };\n }).pipe(Effect.provide(NodeContext.layer), Effect.runPromise);\n\n let closed = false;\n\n const close = async (): Promise<CloseResult> => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n\n return Effect.gen(function* () {\n const isDirty = yield* WorktreeManager.hasUncommittedChanges(\n worktreeInfo.path,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n\n if (isDirty) {\n return { preservedWorktreePath: worktreeInfo.path };\n }\n\n yield* WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n );\n\n // merge-to-head: the temp branch only outlives each wt.run() so the\n // handle can be reused. Once the handle is closed, delete it, unless it\n // holds commits that never reached another branch (e.g. a failed merge).\n if (isMergeToHead) {\n yield* WorktreeManager.deleteTempBranchIfUnused(\n hostRepoDir,\n worktreeInfo.branch,\n ).pipe(Effect.catchAll(() => Effect.void));\n }\n\n return { preservedWorktreePath: undefined };\n }).pipe(Effect.runPromise);\n };\n\n const worktreeInteractive = async (\n opts: WorktreeInteractiveOptions,\n ): Promise<InteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n opts.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = opts;\n const resolvedSandbox = opts.sandbox ?? noSandbox();\n assertInteractiveSupported(resolvedSandbox);\n\n // Validate buildInteractiveArgs is available\n const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n const inner = Effect.gen(function* () {\n const d = yield* Display;\n\n // 1. Resolve prompt (from string or file), or skip if neither provided\n const hasPromptSource = prompt !== undefined || promptFile !== undefined;\n const resolved = hasPromptSource\n ? yield* resolvePrompt({ prompt, promptFile })\n : undefined;\n const rawPrompt = resolved?.text ?? \"\";\n const isInlinePrompt = resolved?.source === \"inline\";\n\n // 2. Resolve env vars\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: provider.env,\n sandboxProviderEnv: resolvedSandbox.env,\n });\n const effectiveEnv = { ...env, ...opts.env };\n\n // 3. Prompt args substitution (skip when no prompt, or when inline passthrough)\n let substitutedPrompt = rawPrompt;\n if (hasPromptSource && !isInlinePrompt) {\n const userArgs = opts.promptArgs ?? {};\n yield* validateNoBuiltInArgOverride(userArgs);\n\n // TARGET_BRANCH is the host's active branch at run() time, matching\n // top-level run(): the branch merge-to-head merges back into.\n const currentHostBranch =\n yield* WorktreeManager.getCurrentBranch(hostRepoDir);\n const effectiveArgs = {\n SOURCE_BRANCH: worktreeInfo.branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n substitutedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n } else if (isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(opts.promptArgs ?? {});\n }\n\n // Display intro\n yield* d.intro(opts.name ?? \"sandcastle interactive\");\n yield* d.summary(\"Interactive Session\", {\n Agent: opts.name ?? provider.name,\n Sandbox: resolvedSandbox.name,\n Branch: worktreeInfo.branch,\n });\n\n // 4. Start sandbox\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n let handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n\n if (resolvedSandbox.tag === \"none\") {\n handle = yield* Effect.promise(async () =>\n resolvedSandbox.create({\n worktreePath: worktreeInfo.path,\n env: effectiveEnv,\n }),\n );\n } else if (resolvedSandbox.tag === \"isolated\") {\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: resolvedSandbox,\n hostRepoDir: worktreeInfo.path,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n }),\n );\n handle = startResult.handle;\n } else {\n const gitPath = join(hostRepoDir, \".git\");\n const rawGitMounts = yield* resolveGitMounts(gitPath);\n const gitMounts = yield* patchGitMountsForWindows(\n rawGitMounts,\n worktreeInfo.path,\n SANDBOX_REPO_DIR,\n );\n mountsToClean.push(...gitMounts);\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: resolvedSandbox,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: worktreeInfo.path,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n );\n handle = startResult.handle;\n }\n\n // Run lifecycle — worktree owns worktree, so no worktree cleanup here\n return yield* Effect.gen(function* () {\n if (!handle.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn = handle.interactiveExec.bind(handle);\n const sandbox = makeSandboxFromHandle(handle);\n const { worktreePath } = handle;\n\n const applyToHost =\n resolvedSandbox.tag === \"isolated\"\n ? () => syncOut(worktreeInfo.path, handle as IsolatedSandboxHandle)\n : () => Effect.void;\n\n const lifecycleEffect = withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: worktreePath,\n hooks,\n // merge-to-head: pass `undefined` so the lifecycle records the\n // host's current branch and merges the worktree's commits back into\n // it. branch strategy: pin to the worktree's branch.\n branch: isMergeToHead ? undefined : worktreeInfo.branch,\n hostWorktreePath: worktreeInfo.path,\n applyToHost,\n timeouts: options.timeouts,\n keepSourceBranch: isMergeToHead,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n const fullPrompt =\n !hasPromptSource || isInlinePrompt\n ? substitutedPrompt\n : yield* preprocessPrompt(\n substitutedPrompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: resolvedSandbox.tag !== \"none\",\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(async () =>\n interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: worktreePath,\n }),\n ),\n opts.signal,\n );\n\n return result.exitCode;\n }),\n );\n\n const lifecycleResult = yield* lifecycleEffect;\n\n const exitCode = lifecycleResult.result;\n\n // Summary\n yield* d.summary(\"Session Complete\", {\n Commits: String(lifecycleResult.commits.length),\n Branch: lifecycleResult.branch,\n \"Exit code\": String(exitCode),\n });\n\n return {\n commits: lifecycleResult.commits,\n branch: lifecycleResult.branch,\n preservedWorktreePath: undefined,\n exitCode,\n } satisfies InteractiveResult;\n }).pipe(\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () => handle.close().catch(() => {})).pipe(\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n });\n\n try {\n return await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n opts.signal?.throwIfAborted();\n throw error;\n }\n };\n\n const worktreeRun = async (\n opts: WorktreeRunOptions,\n ): Promise<WorktreeRunResult> => {\n // If signal is already aborted, reject immediately without any setup\n opts.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = opts;\n const sandboxProvider = opts.sandbox;\n const maxIterations = opts.maxIterations ?? 1;\n\n validateTimeoutOptions(opts);\n\n const isResuming =\n opts.resumeSession !== undefined && opts.resumeSession !== \"\";\n\n if (isResuming && maxIterations > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n if (isResuming) {\n await assertResumeSessionExists({\n provider,\n sandboxTag: sandboxProvider.tag,\n hostRepoDir,\n resumeSession: opts.resumeSession,\n });\n }\n\n const inner = Effect.gen(function* () {\n // 1. Resolve prompt\n const resolved = yield* resolvePrompt({ prompt, promptFile });\n const rawPrompt = resolved.text;\n const isInlinePrompt = resolved.source === \"inline\";\n\n // 2. Resolve env vars\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: provider.env,\n sandboxProviderEnv: sandboxProvider.env,\n });\n const effectiveEnv = { ...env, ...opts.env };\n\n // 3. Prompt args substitution (skipped for inline prompts — passthrough)\n const userArgs = opts.promptArgs ?? {};\n let resolvedPrompt: string;\n if (isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(userArgs);\n resolvedPrompt = rawPrompt;\n } else {\n yield* validateNoBuiltInArgOverride(userArgs);\n // TARGET_BRANCH is the host's active branch, matching top-level\n // interactive(): the branch merge-to-head merges back into.\n const currentHostBranch =\n yield* WorktreeManager.getCurrentBranch(hostRepoDir);\n const effectiveArgs = {\n SOURCE_BRANCH: worktreeInfo.branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n resolvedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n }\n\n // 4. Start sandbox\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n let handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n let sandboxRepoDir: string;\n\n if (sandboxProvider.tag === \"isolated\") {\n const startResult = yield* startSandbox({\n provider: sandboxProvider,\n hostRepoDir: worktreeInfo.path,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n });\n handle = startResult.handle;\n sandboxRepoDir = startResult.worktreePath;\n } else if (sandboxProvider.tag === \"none\") {\n const startResult = yield* startSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: worktreeInfo.path,\n });\n handle = startResult.handle;\n sandboxRepoDir = startResult.worktreePath;\n } else {\n const gitPath = join(hostRepoDir, \".git\");\n const rawGitMounts = yield* resolveGitMounts(gitPath);\n const gitMounts = yield* patchGitMountsForWindows(\n rawGitMounts,\n worktreeInfo.path,\n SANDBOX_REPO_DIR,\n );\n mountsToClean.push(...gitMounts);\n const startResult = yield* startSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: worktreeInfo.path,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n });\n handle = startResult.handle;\n sandboxRepoDir = startResult.worktreePath;\n }\n\n const sandbox = makeSandboxFromHandle(handle);\n const applyToHost =\n sandboxProvider.tag === \"isolated\"\n ? () => syncOut(worktreeInfo.path, handle as IsolatedSandboxHandle)\n : () => Effect.void;\n\n // 5. Resolve logging\n const resolvedLogging: LoggingOption = opts.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(worktreeInfo.branch, undefined, opts.name),\n ),\n };\n\n const runDisplayLayer =\n resolvedLogging.type === \"file\"\n ? (() => {\n printFileDisplayStartup({\n logPath: resolvedLogging.path,\n agentName: opts.name,\n branch: worktreeInfo.branch,\n });\n return Layer.provide(\n FileDisplay.layer(resolvedLogging.path),\n NodeFileSystem.layer,\n );\n })()\n : ClackDisplay.layer;\n\n // Pre-narrow the bind-mount handle for the orchestrator's session-capture\n // path. Gated on the provider tag so we never hand a NoSandbox/Isolated\n // handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage.\n const bindMountHandle =\n sandboxProvider.tag === \"bind-mount\"\n ? (handle as BindMountSandboxHandle)\n : undefined;\n\n // 6. Build a SandboxFactory that reuses the started sandbox\n const reuseFactoryLayer = reuseSandboxFactoryLayer(\n {\n hostWorktreePath: worktreeInfo.path,\n sandboxRepoPath: sandboxRepoDir,\n applyToHost,\n bindMountHandle,\n },\n sandbox,\n );\n\n const streamEmitterLayer = agentStreamEmitterLayer(\n buildAgentStreamHandler(resolvedLogging),\n );\n\n const runLayer = Layer.mergeAll(\n reuseFactoryLayer,\n runDisplayLayer,\n streamEmitterLayer,\n );\n\n // 7. Run orchestration\n const result = yield* Effect.gen(function* () {\n const display = yield* Display;\n yield* display.intro(opts.name ?? \"sandcastle\");\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir,\n iterations: maxIterations,\n hooks,\n prompt: resolvedPrompt,\n // merge-to-head: pass `undefined` so the lifecycle records the host's\n // current branch and routes through the merge step. branch strategy:\n // pin to the worktree's branch so commits stay there.\n branch: isMergeToHead ? undefined : worktreeInfo.branch,\n provider,\n completionSignal: opts.completionSignal,\n idleTimeoutSeconds: opts.idleTimeoutSeconds,\n completionTimeoutSeconds: opts.completionTimeoutSeconds,\n name: opts.name,\n resumeSession: opts.resumeSession,\n signal: opts.signal,\n skipPromptExpansion: isInlinePrompt,\n timeouts: options.timeouts,\n keepSourceBranch: isMergeToHead,\n });\n\n const completion = buildCompletionMessage(\n orchestrateResult.completionSignal,\n orchestrateResult.iterations.length,\n );\n yield* display.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(\n orchestrateResult.iterations,\n )) {\n yield* display.text(line);\n }\n\n return orchestrateResult;\n }).pipe(\n Effect.provide(runLayer),\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () => handle.close().catch(() => {})).pipe(\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n\n return {\n iterations: result.iterations,\n completionSignal: result.completionSignal,\n stdout: result.stdout,\n commits: result.commits,\n branch: result.branch,\n logFilePath:\n resolvedLogging.type === \"file\" ? resolvedLogging.path : undefined,\n } satisfies WorktreeRunResult;\n });\n\n try {\n return await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n opts.signal?.throwIfAborted();\n throw error;\n }\n };\n\n const worktreeCreateSandbox = async (\n opts: WorktreeCreateSandboxOptions,\n ): Promise<Sandbox> =>\n createSandboxFromWorktree({\n branch: worktreeInfo.branch,\n worktreePath: worktreeInfo.path,\n hostRepoDir,\n sandbox: opts.sandbox,\n hooks: opts.hooks,\n // Isolated sandboxes sync in via git bundle, so the worktree's own\n // copyToWorktree files (often gitignored) must be copied in as well.\n copyToWorktree:\n opts.sandbox.tag === \"isolated\"\n ? [...(options.copyToWorktree ?? []), ...(opts.copyToWorktree ?? [])]\n : opts.copyToWorktree,\n timeouts: opts.timeouts,\n branchStrategy: options.branchStrategy,\n _test: opts._test,\n });\n return {\n branch: worktreeInfo.branch,\n worktreePath: worktreeInfo.path,\n run: worktreeRun,\n interactive: worktreeInteractive,\n createSandbox: worktreeCreateSandbox,\n close,\n async [Symbol.asyncDispose]() {\n await close();\n },\n };\n};\n","import { CwdError as CwdErrorImpl } from \"./resolveCwd.js\";\n\n/**\n * The provided `cwd` path does not exist or is not a directory.\n *\n * Public-facing type for `CwdError`. The runtime class is the same\n * `Data.TaggedError` from `resolveCwd.ts`, but we re-declare its public\n * shape here as a plain `Error` subclass so that Effect's type machinery\n * does not leak into Sandcastle's published `.d.ts` files.\n */\nexport interface CwdError extends Error {\n readonly _tag: \"CwdError\";\n readonly message: string;\n readonly cwd: string;\n}\n\ninterface CwdErrorConstructor {\n new (args: { readonly message: string; readonly cwd: string }): CwdError;\n readonly prototype: CwdError;\n}\n\n/** The provided `cwd` path does not exist or is not a directory. */\nexport const CwdError: CwdErrorConstructor = CwdErrorImpl;\n","import { SyncOutPathError as SyncOutPathErrorImpl } from \"./errors.js\";\n\n/**\n * Sync-out refused to write a file on the host because its path, as reported\n * by an isolated sandbox, would land outside the host worktree (or in its\n * `.git`): an absolute path, a `..` segment, or a symlink leading out.\n *\n * Public-facing type for `SyncOutPathError`. The runtime class is the same\n * `Data.TaggedError` from `errors.ts`, re-declared here as a plain `Error`\n * subclass so that Effect's types stay out of Sandcastle's published `.d.ts`\n * files.\n */\nexport interface SyncOutPathError extends Error {\n readonly _tag: \"SyncOutPathError\";\n readonly message: string;\n /** The offending path, as the sandbox reported it. */\n readonly path: string;\n}\n\ninterface SyncOutPathErrorConstructor {\n new (args: {\n readonly message: string;\n readonly path: string;\n }): SyncOutPathError;\n readonly prototype: SyncOutPathError;\n}\n\n/** Sync-out refused a host path that would land outside the worktree. */\nexport const SyncOutPathError: SyncOutPathErrorConstructor =\n SyncOutPathErrorImpl;\n"]}
1
+ {"version":3,"sources":["../src/resumePrecheck.ts","../src/AgentStreamEmitter.ts","../src/PromptPreprocessor.ts","../src/TextDeltaBuffer.ts","../src/ContextWindow.ts","../src/Orchestrator.ts","../src/PromptResolver.ts","../src/EnvResolver.ts","../src/mergeProviderEnv.ts","../src/PromptArgumentSubstitution.ts","../src/Output.ts","../src/extractStructuredOutput.ts","../src/validateTimeouts.ts","../src/run.ts","../src/raceAbortSignal.ts","../src/interactive.ts","../src/resolveSandboxPrompt.ts","../src/createSandbox.ts","../src/createWorktree.ts","../src/CwdError.ts","../src/SyncOutPathError.ts"],"names":["cursor","text","join","startResult","result","exports","resolveRunLogging","resolveRunPrompt","buildRunLayer","hostLink","CwdError","SyncOutPathError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,mBAAA,GAAsB,CAAC,QAAA,KAAkC;AACpE,EAAA,IAAI,QAAA,CAAS,cAAA,EAAgB,OAAA,KAAY,KAAA,EAAO;AAC9C,IAAA,MAAM,IAAI,qBAAA,CAAsB;AAAA,MAC9B,OAAA,EAAS,CAAA,EAAG,QAAA,CAAS,IAAI,CAAA,uGAAA,CAAA;AAAA,MACzB,eAAe,QAAA,CAAS;AAAA,KACzB,CAAA;AAAA,EACH;AACF,CAAA;AAoBO,IAAM,yBAAA,GAA4B,OAAO,MAAA,KAK3B;AACnB,EAAA,MAAM,EAAE,QAAA,EAAU,UAAA,EAAY,WAAA,EAAa,eAAc,GAAI,MAAA;AAE7D,EAAA,IAAI,CAAC,SAAS,cAAA,EAAgB;AAC5B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,YAAA,CAAa,IAAA;AAAA,IAC3B,GAAA,EAAK,WAAA;AAAA,IACL,WAAA,EAAa,mBAAA;AAAA,IACb,aAAA,EAAe,qBAAA;AAAA,IACf,KAAA;AAAA,IACA,OAAO,MAAA,CAAO,YAAY,CAAA,GAAI;AAC5B,MAAA,MAAM,KAAA,EAAM;AAAA,IACd;AAAA,GACF;AACF;;;AC54BO,IAAMQ,SAAAA,GAAgC;;;ACMtC,IAAMC,iBAAAA,GACX","file":"index.js","sourcesContent":["import type { AgentProvider } from \"./AgentProvider.js\";\nimport { ForkNotSupportedError } from \"./errors.js\";\nimport type { SandboxProvider } from \"./SandboxProvider.js\";\n\n/**\n * Fail-fast validation, for a run asked to fork its session, that the agent\n * provider can fork. One that resumes but has no native fork declares\n * `sessionStorage.canFork: false` and gets a `ForkNotSupportedError` naming\n * it. A provider with no `sessionStorage` is left to\n * `assertResumeSessionExists`, which rejects any resume.\n */\nexport const assertForkSupported = (provider: AgentProvider): void => {\n if (provider.sessionStorage?.canFork === false) {\n throw new ForkNotSupportedError({\n message: `${provider.name} cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.`,\n agentProvider: provider.name,\n });\n }\n};\n\n/**\n * Fail-fast validation that a resumable agent session exists on the host before\n * launching the agent. Throws a descriptive error when the session is missing.\n *\n * The lookup strategy depends on the sandbox:\n *\n * - **No-sandbox**: the agent runs directly on the host and writes its session\n * in place under a cwd-derived directory; Sandcastle never moves it. The\n * agent's own path encoding (realpath canonicalisation plus\n * non-alphanumeric → hyphen) is fragile and platform-specific to reconstruct,\n * so we locate the file by its globally-unique session id instead.\n * - **Sandboxed (bind-mount)**: Sandcastle's capture transfers the session into\n * the host store keyed on the host repo dir, so for a resumable run the file\n * lives at that exact encoded location — check it directly rather than\n * scanning. (Isolated sandboxes fall here too, but neither capture nor resume\n * transfer is wired for them today, so this is the host-repo-dir check by\n * default.)\n */\nexport const assertResumeSessionExists = async (params: {\n readonly provider: AgentProvider;\n readonly sandboxTag: SandboxProvider[\"tag\"];\n readonly hostRepoDir: string;\n readonly resumeSession: string;\n}): Promise<void> => {\n const { provider, sandboxTag, hostRepoDir, resumeSession } = params;\n\n if (!provider.sessionStorage) {\n throw new Error(`${provider.name} does not support resumeSession`);\n }\n\n if (sandboxTag === \"none\") {\n const found = await provider.sessionStorage.findByIdOnHost(resumeSession);\n if (found.path === undefined) {\n throw new Error(\n `resumeSession \"${resumeSession}\" not found under ${found.searchedRoot}`,\n );\n }\n return;\n }\n\n const exists = await provider.sessionStorage.existsOnHost(\n hostRepoDir,\n resumeSession,\n );\n if (!exists) {\n const sessionPath = provider.sessionStorage.hostSessionFilePath(\n hostRepoDir,\n resumeSession,\n );\n throw new Error(\n sessionPath === undefined\n ? `resumeSession \"${resumeSession}\" not found`\n : `resumeSession \"${resumeSession}\" not found: expected session file at ${sessionPath}`,\n );\n }\n};\n","import { Context, Effect, Layer } from \"effect\";\n\n/**\n * A single event in the agent's output stream, surfaced to callers of `run()`\n * so they can forward it to their own observability system.\n *\n * Emitted only in log-to-file mode when an `onAgentStreamEvent` callback is\n * provided via `logging`. See `run()`.\n *\n * The `\"raw\"` variant carries every stdout line the agent emits, verbatim and\n * before parsing — including lines that the provider's stream parser would\n * otherwise drop (e.g. tool-use blocks for unrecognised tools). Intended for\n * debugging when the typed `\"text\"` / `\"toolCall\"` events don't surface\n * enough detail.\n */\nexport type AgentStreamEvent =\n | {\n readonly type: \"text\";\n readonly message: string;\n readonly iteration: number;\n readonly timestamp: Date;\n }\n | {\n readonly type: \"toolCall\";\n readonly name: string;\n readonly formattedArgs: string;\n readonly iteration: number;\n readonly timestamp: Date;\n }\n | {\n readonly type: \"raw\";\n readonly line: string;\n readonly iteration: number;\n readonly timestamp: Date;\n };\n\nexport interface AgentStreamEmitterService {\n readonly emit: (event: AgentStreamEvent) => Effect.Effect<void>;\n}\n\nexport class AgentStreamEmitter extends Context.Tag(\n \"@ai-hero/sandcastle/AgentStreamEmitter\",\n)<AgentStreamEmitter, AgentStreamEmitterService>() {}\n\n/**\n * Build a layer for the AgentStreamEmitter service.\n *\n * Called with no argument, returns a no-op layer that discards events.\n * Called with a callback, returns a layer that forwards each event to it.\n * The callback is invoked synchronously inside an `Effect.sync`; any error\n * thrown by the callback is caught and discarded so observability failures\n * cannot kill the run.\n */\nexport const agentStreamEmitterLayer = (\n onEvent?: (event: AgentStreamEvent) => void,\n): Layer.Layer<AgentStreamEmitter> =>\n Layer.succeed(AgentStreamEmitter, {\n emit: onEvent\n ? (event) =>\n Effect.sync(() => {\n try {\n onEvent(event);\n } catch {\n // Swallow callback errors — a broken forwarder must not kill the run.\n }\n })\n : () => Effect.void,\n });\n","import { Clock, Duration, Effect, Option } from \"effect\";\nimport { Display } from \"./Display.js\";\nimport { PromptError, PromptExpansionTimeoutError } from \"./errors.js\";\nimport type { ExecError } from \"./errors.js\";\nimport type { SandboxService } from \"./SandboxFactory.js\";\n\nconst PROMPT_EXPANSION_TIMEOUT_MS = 30_000;\n\n/**\n * @internal\n * Marker inserted between `!` and the opening backtick for shell blocks that\n * appear in the raw template. The preprocessor only executes marked blocks, so\n * `!`...`` patterns arriving via argument substitution are treated as data.\n * Used only by `substitutePromptArgs`; not part of the public API.\n */\nexport const SHELL_BLOCK_MARKER = \"\\u0001\";\n\nconst MARKED_SHELL_BLOCK_PATTERN = new RegExp(\n `!${SHELL_BLOCK_MARKER}\\`([^\\`]+)\\``,\n \"gu\",\n);\n\ninterface ShellBlock {\n readonly text: string;\n readonly command: string;\n readonly index: number;\n}\n\n/** Runs one block's command in the sandbox and returns its trimmed stdout. */\nconst expandBlock = (\n block: ShellBlock,\n sandbox: SandboxService,\n cwd: string,\n): Effect.Effect<\n ShellBlock & { readonly output: string },\n ExecError | PromptError | PromptExpansionTimeoutError\n> =>\n Effect.gen(function* () {\n const { command } = block;\n const start = yield* Clock.currentTimeMillis;\n const maybeResult = yield* sandbox\n .exec(command, { cwd })\n .pipe(Effect.timeoutOption(Duration.millis(PROMPT_EXPANSION_TIMEOUT_MS)));\n if (Option.isNone(maybeResult)) {\n const elapsedMs = (yield* Clock.currentTimeMillis) - start;\n return yield* new PromptExpansionTimeoutError({\n message: `Shell expression \\`${command}\\` timed out after ${elapsedMs}ms`,\n timeoutMs: PROMPT_EXPANSION_TIMEOUT_MS,\n expression: command,\n elapsedMs,\n });\n }\n const execResult = maybeResult.value;\n if (execResult.exitCode !== 0) {\n return yield* new PromptError({\n message: `Command \\`${command}\\` exited with code ${execResult.exitCode}: ${execResult.stderr}`,\n exitCode: execResult.exitCode,\n });\n }\n return { ...block, output: execResult.stdout.trimEnd() };\n });\n\n/**\n * Splices each output in place of its block. Blocks are in prompt order and\n * don't overlap, so one forward pass over `prompt` works.\n */\nconst spliceOutputs = (\n prompt: string,\n expanded: readonly (ShellBlock & { readonly output: string })[],\n): string => {\n let result = \"\";\n let cursor = 0;\n for (const { index, text, output } of expanded) {\n result += prompt.slice(cursor, index) + output;\n cursor = index + text.length;\n }\n result += prompt.slice(cursor);\n return result.replaceAll(SHELL_BLOCK_MARKER, \"\");\n};\n\nexport const preprocessPrompt = (\n prompt: string,\n sandbox: SandboxService,\n cwd: string,\n): Effect.Effect<\n string,\n ExecError | PromptError | PromptExpansionTimeoutError,\n Display\n> => {\n // The capture group is required, so the `?? \"\"` fallback never applies.\n const blocks = [...prompt.matchAll(MARKED_SHELL_BLOCK_PATTERN)].map(\n (match): ShellBlock => ({\n text: match[0],\n command: match[1] ?? \"\",\n index: match.index,\n }),\n );\n\n if (blocks.length === 0) {\n return Effect.succeed(prompt.replaceAll(SHELL_BLOCK_MARKER, \"\"));\n }\n\n return Effect.gen(function* () {\n const display = yield* Display;\n return yield* display.taskLog(\"Expanding shell expressions\", (message) =>\n Effect.gen(function* () {\n // Execute all commands in parallel\n const expanded = yield* Effect.all(\n blocks.map((block) => expandBlock(block, sandbox, cwd)),\n { concurrency: \"unbounded\" },\n );\n\n // Log per-command token counts\n for (const { command, output } of expanded) {\n const tokens = Math.ceil(output.length / 4);\n message(`${command} → ~${tokens} tokens`);\n }\n\n return spliceOutputs(prompt, expanded);\n }),\n );\n });\n};\n","const LENGTH_THRESHOLD = 80;\nconst DEBOUNCE_MS = 50;\n\n/**\n * Sentence-boundary pattern: period, exclamation, or question mark followed by a space.\n */\nconst SENTENCE_BOUNDARY_RE = /[.!?] $/u;\n\n/**\n * Buffers streaming text deltas and flushes them as readable multi-word chunks.\n *\n * Flush triggers:\n * - Newline character in the accumulated buffer\n * - Sentence boundary (`. `, `! `, `? ` at end of buffer)\n * - Buffer exceeds ~80 characters\n * - Debounce timer (~50ms of no new writes)\n */\nexport class TextDeltaBuffer {\n private buffer = \"\";\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly onFlush: (text: string) => void;\n\n constructor(onFlush: (text: string) => void) {\n this.onFlush = onFlush;\n }\n\n write(text: string): void {\n if (text.length === 0) {\n return;\n }\n this.buffer += text;\n this.clearTimer();\n\n if (this.shouldFlush()) {\n this.doFlush();\n return;\n }\n\n this.timer = setTimeout(() => {\n this.doFlush();\n }, DEBOUNCE_MS);\n }\n\n /** Force-flush any buffered text. */\n flush(): void {\n this.clearTimer();\n this.doFlush();\n }\n\n /** Flush remaining buffer and clean up. */\n dispose(): void {\n this.flush();\n }\n\n private shouldFlush(): boolean {\n if (this.buffer.includes(\"\\n\")) {\n return true;\n }\n if (SENTENCE_BOUNDARY_RE.test(this.buffer)) {\n return true;\n }\n if (this.buffer.length >= LENGTH_THRESHOLD) {\n return true;\n }\n return false;\n }\n\n private doFlush(): void {\n if (this.buffer.length === 0) {\n return;\n }\n const text = this.buffer;\n this.buffer = \"\";\n this.onFlush(text);\n }\n\n private clearTimer(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n","/**\n * How full an iteration's context window was: the input side of its LAST\n * model call, cache reads and cache writes included (see ADR 0023).\n *\n * Each model call's input already holds the whole conversation so far, so the\n * last call is the context size. Never sum calls, and never use a total the\n * agent reports for a turn or a session: those grow with every tool\n * round-trip and can exceed the window.\n */\nexport interface ContextWindow {\n /** Input tokens of the last model call, cached and uncached together. */\n readonly tokens: number;\n /** The model's context window size, only when the agent itself reports it. */\n readonly limit?: number;\n}\n\n/**\n * Format a context window as `47k`, or `32k / 258k` when the limit is known.\n * Tokens round up (never understate use); the limit rounds down (never\n * overstate room).\n */\nexport const formatContextWindow = (contextWindow: ContextWindow): string => {\n const used = `${Math.ceil(contextWindow.tokens / 1000)}k`;\n return contextWindow.limit === undefined\n ? used\n : `${used} / ${Math.floor(contextWindow.limit / 1000)}k`;\n};\n\n/**\n * Build `Context window: NNNk` lines, one per iteration that has a context\n * window. Iterations without one (e.g. cursor, which reports no per-call\n * figure) are skipped.\n */\nexport const buildContextWindowLines = (\n iterations: readonly { readonly contextWindow?: ContextWindow }[],\n): string[] =>\n iterations.flatMap((it) =>\n it.contextWindow\n ? [`Context window: ${formatContextWindow(it.contextWindow)}`]\n : [],\n );\n","import { Deferred, Duration, Effect, Fiber, Runtime } from \"effect\";\nimport { AgentStreamEmitter } from \"./AgentStreamEmitter.js\";\nimport { Display } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport {\n AgentError,\n AgentIdleTimeoutError,\n SessionCaptureError,\n} from \"./errors.js\";\nimport type { SandboxError } from \"./errors.js\";\nimport type { SandboxService } from \"./SandboxFactory.js\";\nimport { SandboxFactory } from \"./SandboxFactory.js\";\nimport { withSandboxLifecycle } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type { AgentProvider, IterationUsage } from \"./AgentProvider.js\";\nimport type { Timeouts } from \"./run.js\";\nimport { TextDeltaBuffer } from \"./TextDeltaBuffer.js\";\nimport { buildContextWindowLines } from \"./ContextWindow.js\";\nimport type { ContextWindow } from \"./ContextWindow.js\";\n\nexport type { ParsedStreamEvent, IterationUsage } from \"./AgentProvider.js\";\n\nconst IDLE_WARNING_INTERVAL_MS = 60_000;\n\nconst invokeAgent = (\n sandbox: SandboxService,\n sandboxRepoDir: string,\n prompt: string,\n provider: AgentProvider,\n idleTimeoutMs: number,\n completionTimeoutMs: number,\n completionSignals: readonly string[],\n onText: (text: string) => void,\n onToolCall: (name: string, formattedArgs: string) => void,\n onRawLine: (line: string) => void,\n onIdleWarning: (minutes: number) => void,\n onCompletionTimeout: (timeoutMs: number) => void,\n onContextWindow: (contextWindow: ContextWindow) => void,\n idleWarningIntervalMs: number = IDLE_WARNING_INTERVAL_MS,\n resumeSession?: string,\n forkSession?: boolean,\n signal?: AbortSignal,\n): Effect.Effect<\n { result: string; sessionId?: string; usage?: IterationUsage },\n SandboxError\n> =>\n Effect.gen(function* () {\n let resultText = \"\";\n // Last error the agent reported in its own stream (see ParsedStreamEvent).\n let streamError: string | undefined;\n let sessionId: string | undefined;\n let usage: IterationUsage | undefined;\n // Accumulated assistant text, in order. Scanned (with resultText) for the\n // completion signal so a hanging process can be force-completed once the\n // signal is in the buffer (see ADR 0019). Kept apart from resultText:\n // some agents (Claude Code) continue one reply across several assistant\n // messages, then repeat only the last one as their final result (#970).\n let accumulatedOutput = \"\";\n // The iteration's output: the whole streamed text when the final result\n // only repeats its end, else the final result, else `fallback`.\n const getResult = (fallback: string): string => {\n if (resultText !== \"\" && accumulatedOutput.endsWith(resultText)) {\n return accumulatedOutput;\n }\n // A distinct final result may hold text that was never streamed.\n return resultText === \"\" ? fallback : resultText;\n };\n\n // Deferred that fails when the idle timer fires (no signal seen).\n const timeoutSignal = yield* Deferred.make<never, AgentIdleTimeoutError>();\n // Deferred that resolves successfully when the completion-grace timer\n // fires (signal seen but process hasn't exited). Resolving lets the race\n // hand control back to the orchestrator with the buffered output, which\n // still contains the signal so the existing completionSignal check works.\n const completionTimeoutDeferred = yield* Deferred.make<{\n result: string;\n sessionId?: string;\n usage?: IterationUsage;\n }>();\n // Timer and abort callbacks fire outside any fiber; they fork onto the\n // surrounding runtime rather than a fresh default one.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n let timeoutFiber: Fiber.RuntimeFiber<unknown, unknown> | null = null;\n let completionDetected = false;\n\n // Periodic idle warning state\n let warningFiber: Fiber.RuntimeFiber<unknown, unknown> | null = null;\n let idleMinuteCounter = 0;\n // Set once the race below settles (success, failure, abort, idle or\n // completion timeout). The losing exec may still be streaming — e.g. a\n // `docker exec` outliving the run — and every line would otherwise fork\n // fresh timer fibers nobody interrupts, keeping the host process alive.\n let settled = false;\n\n const interruptFiber = (\n fiber: Fiber.RuntimeFiber<unknown, unknown> | null,\n ) => {\n if (fiber !== null) {\n runFork(Fiber.interrupt(fiber));\n }\n };\n\n const startWarningInterval = () => {\n interruptFiber(warningFiber);\n idleMinuteCounter = 0;\n warningFiber = runFork(\n Effect.gen(function* () {\n while (true) {\n yield* Effect.sleep(Duration.millis(idleWarningIntervalMs));\n idleMinuteCounter++;\n onIdleWarning(idleMinuteCounter);\n }\n }),\n );\n };\n\n const resetTimer = () => {\n interruptFiber(timeoutFiber);\n if (completionDetected) {\n // Post-signal grace window — successful resolution on expiry.\n timeoutFiber = runFork(\n Effect.gen(function* () {\n yield* Effect.sleep(Duration.millis(completionTimeoutMs));\n onCompletionTimeout(completionTimeoutMs);\n yield* Deferred.succeed(completionTimeoutDeferred, {\n result: getResult(accumulatedOutput),\n sessionId,\n usage,\n });\n }),\n );\n } else {\n // Pre-signal idle window — failure on expiry.\n timeoutFiber = runFork(\n Effect.gen(function* () {\n yield* Effect.sleep(Duration.millis(idleTimeoutMs));\n yield* Deferred.fail(\n timeoutSignal,\n new AgentIdleTimeoutError({\n message: `Agent idle for ${idleTimeoutMs / 1000} seconds — no output received. Increase the idleTimeoutSeconds option to allow longer silences.`,\n timeoutMs: idleTimeoutMs,\n }),\n );\n }),\n );\n // Reset warning interval on activity, idle-phase only.\n startWarningInterval();\n }\n };\n\n // Deferred that will be resolved (as a defect) when the AbortSignal fires.\n // Uses Effect.die so the abort reason propagates as-is to run().\n const abortDeferred = yield* Deferred.make<never>();\n let abortCleanup: (() => void) | null = null;\n if (signal) {\n if (signal.aborted) {\n return yield* Effect.die(signal.reason);\n }\n const onAbort = () => {\n runFork(Deferred.die(abortDeferred, signal.reason));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n abortCleanup = () => {\n signal.removeEventListener(\"abort\", onAbort);\n };\n }\n\n resetTimer();\n\n const execEffect = Effect.gen(function* () {\n const printCmd = provider.buildPrintCommand({\n prompt,\n dangerouslySkipPermissions: true,\n resumeSession,\n forkSession,\n });\n const execResult = yield* sandbox.exec(printCmd.command, {\n onLine: (line) => {\n if (settled) {\n return;\n }\n // Surface the raw line FIRST so verbose mode/forwarders see every\n // stdout line the agent produced, including ones parseStreamLine\n // drops. Errors thrown by the callback are caught by the emitter\n // layer; isolate the parser path here so a broken forwarder cannot\n // skip parsing.\n try {\n onRawLine(line);\n } catch {\n // Swallow — must not skip parsing/timer logic below.\n }\n for (const parsed of provider.parseStreamLine(line)) {\n if (parsed.type === \"text\") {\n onText(parsed.text);\n accumulatedOutput += parsed.text;\n } else if (parsed.type === \"context_window\") {\n onContextWindow(parsed.contextWindow);\n } else if (parsed.type === \"result\") {\n resultText = parsed.result;\n } else if (parsed.type === \"tool_call\") {\n onToolCall(parsed.name, parsed.args);\n } else if (parsed.type === \"session_id\") {\n sessionId = parsed.sessionId;\n } else if (parsed.type === \"usage\") {\n usage = parsed.usage;\n } else if (parsed.type === \"error\") {\n streamError = parsed.message;\n }\n }\n // Check for the completion signal AFTER parsing this line so the\n // buffers contain everything seen so far. Flip to the\n // completion-grace timer the first time the signal appears.\n if (\n !completionDetected &&\n completionSignals.some(\n (sig) =>\n accumulatedOutput.includes(sig) || resultText.includes(sig),\n )\n ) {\n completionDetected = true;\n interruptFiber(warningFiber);\n warningFiber = null;\n }\n resetTimer();\n },\n cwd: sandboxRepoDir,\n stdin: printCmd.stdin,\n });\n\n if (execResult.exitCode !== 0) {\n // Prefer stderr; fall back to the stream's own error, then resultText\n // (from parsed stream events), then to the tail of raw stdout (last\n // 20 non-empty lines).\n let errorDetail = execResult.stderr;\n if (!errorDetail.trim()) {\n errorDetail = streamError ?? \"\";\n }\n if (!errorDetail.trim()) {\n errorDetail = resultText;\n }\n if (!errorDetail.trim()) {\n const lines = execResult.stdout.split(\"\\n\").filter((l) => l.trim());\n errorDetail = lines.slice(-20).join(\"\\n\");\n }\n return yield* new AgentError({\n message: `${provider.name} exited with code ${execResult.exitCode}:\\n${errorDetail}`,\n });\n }\n\n // Some agents (pi, opencode) exit 0 after reporting a failure in their\n // stream. Treat the reported error as authoritative.\n if (streamError !== undefined) {\n return yield* new AgentError({\n message: `${provider.name} reported an error:\\n${streamError}`,\n });\n }\n\n return { result: getResult(execResult.stdout), sessionId, usage };\n }).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n interruptFiber(timeoutFiber);\n timeoutFiber = null;\n interruptFiber(warningFiber);\n warningFiber = null;\n }),\n ),\n );\n\n let raced: Effect.Effect<\n { result: string; sessionId?: string; usage?: IterationUsage },\n AgentIdleTimeoutError | SandboxError\n > = Effect.raceFirst(execEffect, Deferred.await(timeoutSignal));\n raced = Effect.raceFirst(raced, Deferred.await(completionTimeoutDeferred));\n if (signal) {\n raced = Effect.raceFirst(raced, Deferred.await(abortDeferred));\n }\n\n return yield* raced.pipe(\n Effect.ensuring(\n Effect.sync(() => {\n settled = true;\n abortCleanup?.();\n interruptFiber(timeoutFiber);\n timeoutFiber = null;\n interruptFiber(warningFiber);\n warningFiber = null;\n }),\n ),\n );\n });\n\nconst DEFAULT_COMPLETION_SIGNAL = \"<promise>COMPLETE</promise>\";\nconst DEFAULT_IDLE_TIMEOUT_SECONDS = 10 * 60; // 600 seconds\nconst DEFAULT_COMPLETION_TIMEOUT_SECONDS = 60;\n\nexport interface OrchestrateOptions {\n readonly hostRepoDir: string;\n readonly iterations: number;\n readonly hooks?: SandboxHooks;\n readonly prompt: string;\n readonly branch?: string;\n readonly provider: AgentProvider;\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. If the agent produces no output for this long, it fails with AgentIdleTimeoutError. Default: 600 (10 minutes) */\n readonly idleTimeoutSeconds?: number;\n /**\n * Grace window in seconds after a completion signal is observed in the\n * agent's output. The agent process is expected to exit shortly after\n * emitting the signal; if it does not (because a spawned child is keeping\n * stdout open — see ADR 0019), this timer fires and the iteration resolves\n * successfully with the buffered output. Resets on every subsequent output\n * line, so trailing data (token-usage events, terminal `result` events,\n * structured-output tags) is still captured. Default: 60 seconds.\n */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run, prepended to status messages as [name] */\n readonly name?: string;\n /** @internal Test-only override for the idle warning interval in milliseconds. Default: 60000 (1 minute). */\n readonly _idleWarningIntervalMs?: number;\n /** Resume a prior Claude Code session by ID. Applied to iteration 1 only. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it — the parent JSONL stays intact and the agent writes a new session\n * under a fresh id. Applied to iteration 1 only. See ADR 0018.\n */\n readonly forkSession?: boolean;\n /** An AbortSignal that cancels the orchestration when aborted. */\n readonly signal?: AbortSignal;\n /** When true, skip prompt expansion (shell expression evaluation). Set for dynamic inline prompts. */\n readonly skipPromptExpansion?: boolean;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** Forwarded to `withSandboxLifecycle` — see `SandboxLifecycleOptions.keepSourceBranch`. */\n readonly keepSourceBranch?: boolean;\n}\n\n/** Per-iteration result carrying an optional session ID. */\nexport interface IterationResult {\n /** Claude Code session ID extracted from the init line, or undefined for non-Claude agents. */\n readonly sessionId?: string;\n /** Absolute host path to the captured session JSONL, or undefined when capture is disabled or provider is non-Claude. */\n readonly sessionFilePath?: string;\n /** Token usage snapshot from the last assistant message in the session, or undefined when capture is disabled or provider does not support usage parsing. */\n readonly usage?: IterationUsage;\n /** Input tokens of the iteration's last model call (cache included), plus the model's limit when the agent reports it. Undefined when the agent reports no per-call figure. */\n readonly contextWindow?: ContextWindow;\n}\n\nexport interface OrchestrateResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n readonly stdout: string;\n readonly commits: { sha: string }[];\n readonly branch: string;\n /** Host path to the preserved worktree from the last iteration, set when the worktree was left behind due to uncommitted changes on a successful run. */\n readonly preservedWorktreePath?: string;\n}\n\nexport const orchestrate = (\n options: OrchestrateOptions,\n): Effect.Effect<\n OrchestrateResult,\n SandboxError,\n SandboxFactory | Display | AgentStreamEmitter\n> => {\n const idleTimeoutMs =\n (options.idleTimeoutSeconds ?? DEFAULT_IDLE_TIMEOUT_SECONDS) * 1000;\n const completionTimeoutMs =\n (options.completionTimeoutSeconds ?? DEFAULT_COMPLETION_TIMEOUT_SECONDS) *\n 1000;\n return Effect.gen(function* () {\n const factory = yield* SandboxFactory;\n const display = yield* Display;\n const streamEmitter = yield* AgentStreamEmitter;\n // The agent's stream callbacks fire outside any fiber; they fork their\n // display and emitter effects onto the surrounding runtime.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n const { hostRepoDir, iterations, hooks, prompt, branch, provider } =\n options;\n const { sessionStorage } = provider;\n let completionSignals: string[];\n if (options.completionSignal === undefined) {\n completionSignals = [DEFAULT_COMPLETION_SIGNAL];\n } else if (Array.isArray(options.completionSignal)) {\n completionSignals = options.completionSignal;\n } else {\n completionSignals = [options.completionSignal];\n }\n\n const label = (msg: string): string =>\n options.name !== undefined && options.name !== \"\"\n ? `[${options.name}] ${msg}`\n : msg;\n\n const allCommits: { sha: string }[] = [];\n const allIterations: IterationResult[] = [];\n let allStdout = \"\";\n let resolvedBranch = \"\";\n let iterationPreservedPath: string | undefined;\n\n // Helper: check abort signal and bail via defect so run() can\n // re-throw the signal's reason verbatim (no Sandcastle wrapping).\n const checkAbort = (): Effect.Effect<void> =>\n options.signal?.aborted === true\n ? Effect.die(options.signal.reason)\n : Effect.void;\n\n for (let i = 1; i <= iterations; i++) {\n yield* checkAbort();\n yield* display.status(label(`Iteration ${i}/${iterations}`), \"info\");\n\n const sandboxResult = yield* factory\n .withSandbox(\n (\n { hostWorktreePath, sandboxRepoPath, applyToHost, bindMountHandle },\n sandbox,\n ) =>\n withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: sandboxRepoPath,\n hooks,\n branch,\n hostWorktreePath,\n applyToHost,\n signal: options.signal,\n timeouts: options.timeouts,\n keepSourceBranch: options.keepSourceBranch,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n // Resume session: transfer JSONL from host to sandbox before iteration 1\n const iterationResumeSession =\n i === 1 ? options.resumeSession : undefined;\n const iterationForkSession =\n i === 1 ? options.forkSession : undefined;\n if (\n iterationResumeSession !== undefined &&\n iterationResumeSession !== \"\" &&\n bindMountHandle &&\n sessionStorage\n ) {\n yield* display.status(label(\"Resuming session\"), \"info\");\n yield* Effect.tryPromise({\n try: () =>\n sessionStorage.resumeIntoSandbox({\n hostCwd: hostRepoDir,\n sandboxCwd: ctx.sandboxRepoDir,\n sessionId: iterationResumeSession,\n handle: bindMountHandle,\n }),\n catch: (e) =>\n new SessionCaptureError({\n message: `Session resume failed: ${e instanceof Error ? e.message : String(e)}`,\n sessionId: iterationResumeSession,\n }),\n });\n }\n\n // Preprocess prompt (run !`command` expressions inside sandbox).\n // Inline prompts pass through literally — skip expansion.\n const fullPrompt =\n options.skipPromptExpansion === true\n ? prompt\n : yield* preprocessPrompt(\n prompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n yield* display.status(label(\"Agent started\"), \"success\");\n\n // Every display write and stream event the agent's output\n // forks is tracked, so the iteration can wait for them to\n // land before it returns: a run() that has settled (even by\n // abort) must not still be appending to its log file.\n const pendingOutput = new Set<Fiber.RuntimeFiber<void>>();\n const forkOutput = (effect: Effect.Effect<void>) => {\n const fiber = runFork(effect);\n pendingOutput.add(fiber);\n fiber.addObserver(() => {\n pendingOutput.delete(fiber);\n });\n };\n // Invoke the agent — buffer text deltas so Pi's single-token\n // chunks are displayed as readable multi-word lines.\n const textBuffer = new TextDeltaBuffer((chunk) => {\n forkOutput(display.textChunk(chunk));\n forkOutput(\n streamEmitter.emit({\n type: \"text\",\n message: chunk,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n });\n const onText = (text: string) => {\n textBuffer.write(text);\n };\n const onToolCall = (name: string, formattedArgs: string) => {\n textBuffer.flush();\n forkOutput(display.toolCall(name, formattedArgs));\n forkOutput(\n streamEmitter.emit({\n type: \"toolCall\",\n name,\n formattedArgs,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n };\n const onRawLine = (line: string) => {\n forkOutput(\n streamEmitter.emit({\n type: \"raw\",\n line,\n iteration: i,\n timestamp: new Date(),\n }),\n );\n };\n const onIdleWarning = (minutes: number) => {\n const msg =\n minutes === 1\n ? \"Agent idle for 1 minute\"\n : `Agent idle for ${minutes} minutes`;\n forkOutput(display.status(label(msg), \"warn\"));\n };\n const onCompletionTimeout = (timeoutMs: number) => {\n forkOutput(\n display.status(\n label(\n `Completion signal seen but agent process is hanging — force-completing after ${timeoutMs / 1000}s grace window.`,\n ),\n \"warn\",\n ),\n );\n };\n // Last call wins: each event is one model call, and the last\n // call's input is the context size (see ContextWindow).\n let contextWindow: ContextWindow | undefined;\n const onContextWindow = (cw: ContextWindow) => {\n contextWindow = cw;\n };\n const {\n result: agentOutput,\n sessionId,\n usage: streamUsage,\n } = yield* invokeAgent(\n ctx.sandbox,\n ctx.sandboxRepoDir,\n fullPrompt,\n provider,\n idleTimeoutMs,\n completionTimeoutMs,\n completionSignals,\n onText,\n onToolCall,\n onRawLine,\n onIdleWarning,\n onCompletionTimeout,\n onContextWindow,\n options._idleWarningIntervalMs,\n iterationResumeSession,\n iterationForkSession,\n options.signal,\n ).pipe(\n // On every exit, abort included: flush the buffered text\n // deltas, then wait for the output forked so far.\n Effect.ensuring(\n Effect.suspend(() => {\n textBuffer.dispose();\n return Fiber.awaitAll([...pendingOutput]);\n }),\n ),\n );\n\n yield* display.status(label(\"Agent stopped\"), \"info\");\n\n // Capture session while sandbox is still alive. Usage from the\n // stream (e.g. Codex's turn.completed) is the baseline; a\n // session-parsed value below overrides it when available.\n let sessionFilePath: string | undefined;\n let usage: IterationUsage | undefined = streamUsage;\n if (\n provider.captureSessions &&\n sessionStorage &&\n sessionId !== undefined &&\n sessionId !== \"\" &&\n bindMountHandle\n ) {\n yield* display.status(label(\"Capturing session\"), \"info\");\n yield* Effect.tryPromise({\n try: () =>\n sessionStorage.captureToHost({\n hostCwd: hostRepoDir,\n sandboxCwd: ctx.sandboxRepoDir,\n sessionId,\n handle: bindMountHandle,\n }),\n catch: (e) =>\n new SessionCaptureError({\n message: `Session capture failed: ${e instanceof Error ? e.message : String(e)}`,\n sessionId,\n }),\n });\n sessionFilePath = sessionStorage.hostSessionFilePath(\n hostRepoDir,\n sessionId,\n );\n\n // Parse token usage and the context window from the\n // captured session JSONL\n if (\n provider.parseSessionUsage ||\n provider.parseSessionContextWindow\n ) {\n const content = yield* Effect.promise(() =>\n sessionStorage\n .readHostSession(hostRepoDir, sessionId)\n .catch(() => undefined as string | undefined),\n );\n if (content !== undefined && content !== \"\") {\n const parsedUsage =\n provider.parseSessionUsage?.(content);\n if (parsedUsage) {\n usage = parsedUsage;\n }\n const parsedContextWindow =\n provider.parseSessionContextWindow?.(content);\n if (parsedContextWindow) {\n contextWindow = parsedContextWindow;\n }\n }\n }\n }\n\n // Check completion signal\n const matchedSignal = completionSignals.find((sig) =>\n agentOutput.includes(sig),\n );\n return {\n completionSignal: matchedSignal,\n stdout: agentOutput,\n sessionId,\n sessionFilePath,\n usage,\n contextWindow,\n } as const;\n }),\n ),\n )\n .pipe(\n // A failed iteration ends the run before run() prints the context\n // window lines, so print the completed iterations' lines here.\n Effect.tapError(() =>\n Effect.forEach(buildContextWindowLines(allIterations), (line) =>\n display.text(line),\n ),\n ),\n );\n\n const lifecycleResult = sandboxResult.value;\n iterationPreservedPath = sandboxResult.preservedWorktreePath;\n\n allCommits.push(...lifecycleResult.commits);\n allStdout += lifecycleResult.result.stdout;\n resolvedBranch = lifecycleResult.branch;\n\n allIterations.push({\n sessionId: lifecycleResult.result.sessionId,\n sessionFilePath: lifecycleResult.result.sessionFilePath,\n usage: lifecycleResult.result.usage,\n contextWindow: lifecycleResult.result.contextWindow,\n });\n\n if (lifecycleResult.result.completionSignal !== undefined) {\n yield* display.status(\n label(`Agent signaled completion after ${i} iteration(s).`),\n \"success\",\n );\n return {\n iterations: allIterations,\n completionSignal: lifecycleResult.result.completionSignal,\n stdout: allStdout,\n commits: allCommits,\n branch: resolvedBranch,\n preservedWorktreePath: iterationPreservedPath,\n };\n }\n }\n\n yield* display.status(\n label(`Reached max iterations (${iterations}).`),\n \"info\",\n );\n return {\n iterations: allIterations,\n completionSignal: undefined,\n stdout: allStdout,\n commits: allCommits,\n branch: resolvedBranch,\n preservedWorktreePath: iterationPreservedPath,\n };\n });\n};\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { PromptError } from \"./errors.js\";\n\nexport interface ResolvePromptOptions {\n readonly prompt?: string;\n readonly promptFile?: string;\n}\n\n/**\n * The resolved prompt text plus the source it came from.\n *\n * - `inline`: came from `prompt: \"...\"` — delivered to the agent verbatim.\n * No prompt argument substitution, no prompt expansion, no built-in args.\n * - `template`: came from `promptFile` — eligible for `{{KEY}}` substitution\n * and `` !`command` `` expansion.\n */\nexport interface ResolvedPrompt {\n readonly text: string;\n readonly source: \"inline\" | \"template\";\n}\n\nexport const resolvePrompt = (\n options: ResolvePromptOptions,\n): Effect.Effect<ResolvedPrompt, PromptError, FileSystem.FileSystem> => {\n const { prompt, promptFile } = options;\n\n if (prompt !== undefined && promptFile !== undefined) {\n return Effect.fail(\n new PromptError({\n message: \"Cannot provide both prompt and promptFile\",\n }),\n );\n }\n\n if (prompt !== undefined) {\n return Effect.succeed({ text: prompt, source: \"inline\" });\n }\n\n if (promptFile === undefined) {\n return Effect.fail(\n new PromptError({\n message:\n \"Must provide either prompt or promptFile. Pass prompt: '...' or promptFile: './.sandcastle/prompt.md' to run().\",\n }),\n );\n }\n\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const text = yield* fs.readFileString(promptFile).pipe(\n Effect.mapError(\n (e) =>\n new PromptError({\n message: `Failed to read prompt from ${promptFile}: ${String(e)}`,\n }),\n ),\n );\n return { text, source: \"template\" as const };\n });\n};\n","import { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport { join } from \"node:path\";\n\nconst ESCAPES: Record<string, string> = {\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n \"\\\\\": \"\\\\\",\n};\n\n/** Strips matching quotes; double-quoted values also expand \\n, \\r, \\t, \\\\. */\nconst unquote = (value: string): string => {\n const isDoubleQuoted =\n value.length >= 2 && value.startsWith('\"') && value.at(-1) === '\"';\n const isSingleQuoted =\n value.length >= 2 && value.startsWith(\"'\") && value.at(-1) === \"'\";\n if (isSingleQuoted) {\n return value.slice(1, -1);\n }\n if (!isDoubleQuoted) {\n return value;\n }\n return value\n .slice(1, -1)\n .replaceAll(/\\\\(?<escape>[nrt\\\\])/gu, (_, ch: string) => ESCAPES[ch] ?? ch);\n};\n\n/** One `KEY=value` line as a pair, or undefined for blanks and comments. */\nconst parseEnvLine = (line: string): [string, string] | undefined => {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) {\n return undefined;\n }\n const eqIndex = trimmed.indexOf(\"=\");\n if (eqIndex === -1) {\n return undefined;\n }\n const key = trimmed.slice(0, eqIndex).trim();\n return [key, unquote(trimmed.slice(eqIndex + 1).trim())];\n};\n\nconst parseEnvFile = (\n filePath: string,\n): Effect.Effect<Record<string, string>, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const content = yield* fs\n .readFileString(filePath)\n .pipe(Effect.catchAll(() => Effect.succeed(null)));\n if (content === null) {\n return {};\n }\n const entries = content\n .split(\"\\n\")\n .map((line) => parseEnvLine(line))\n .filter((entry) => entry !== undefined);\n return Object.fromEntries(entries);\n });\n\n/**\n * Resolve all env vars from .env files with process.env fallback.\n *\n * Precedence: .sandcastle/.env > process.env\n * Only keys declared in .sandcastle/.env are resolved from process.env.\n * Repo root .env is not part of the resolution chain.\n */\nexport const resolveEnv = (\n repoDir: string,\n): Effect.Effect<Record<string, string>, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const sandcastleEnv = yield* parseEnvFile(\n join(repoDir, \".sandcastle\", \".env\"),\n );\n\n const result: Record<string, string> = {};\n for (const [key, fileValue] of Object.entries(sandcastleEnv)) {\n const value = fileValue || (process.env[key] ?? \"\");\n if (value) {\n result[key] = value;\n }\n }\n\n return result;\n });\n","/**\n * Merge env vars from the env resolver, agent provider, and sandbox provider.\n *\n * Provider env (agent + sandbox) overrides env resolver output for shared keys.\n * Agent and sandbox provider env must NOT have overlapping keys — if they do,\n * this function throws.\n */\nexport const mergeProviderEnv = (options: {\n readonly resolvedEnv: Record<string, string>;\n readonly agentProviderEnv: Record<string, string>;\n readonly sandboxProviderEnv: Record<string, string>;\n}): Record<string, string> => {\n const { resolvedEnv, agentProviderEnv, sandboxProviderEnv } = options;\n\n // Check for overlapping keys between agent and sandbox provider env\n const agentKeys = Object.keys(agentProviderEnv);\n const sandboxKeys = new Set(Object.keys(sandboxProviderEnv));\n const overlapping = agentKeys.filter((k) => sandboxKeys.has(k));\n\n if (overlapping.length > 0) {\n throw new Error(\n `Overlapping env keys between agent provider and sandbox provider: ${overlapping.join(\", \")}`,\n );\n }\n\n return {\n ...resolvedEnv,\n ...sandboxProviderEnv,\n ...agentProviderEnv,\n };\n};\n","import { Effect } from \"effect\";\nimport { Display } from \"./Display.js\";\nimport { PromptError } from \"./errors.js\";\nimport { SHELL_BLOCK_MARKER } from \"./PromptPreprocessor.js\";\n\nconst SHELL_BLOCK_PATTERN = /!`(?<command>[^`]+)`/gu;\n\n/**\n * A map of named values used for prompt argument substitution.\n * Each key corresponds to a `{{KEY}}` placeholder in the prompt; the value\n * replaces it before the prompt is passed to the agent.\n */\nexport type PromptArgs = Record<string, string | number | boolean>;\n\n/**\n * Prompt argument keys that Sandcastle injects automatically.\n * These cannot be overridden via `promptArgs`.\n */\nexport const BUILT_IN_PROMPT_ARG_KEYS = [\n \"SOURCE_BRANCH\",\n \"TARGET_BRANCH\",\n] as const;\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(?<key>[A-Za-z_][A-Za-z0-9_]*)\\s*\\}\\}/gu;\n\n/**\n * The key of every `{{KEY}}` placeholder in `text`, in order, repeats\n * included. The `key` group is required, so the `?? \"\"` never applies.\n */\nconst placeholderKeys = (text: string): string[] =>\n [...text.matchAll(PLACEHOLDER_PATTERN)].map((m) => m.groups?.[\"key\"] ?? \"\");\n\n/**\n * Validates that the user has not provided any built-in prompt argument keys.\n * Fails with a PromptError if any built-in key is found in `args`.\n */\n/**\n * Fails if the user passed any `promptArgs` alongside an inline prompt.\n * Inline prompts are delivered to the agent verbatim, so `promptArgs` would\n * silently do nothing. An empty object is treated as absent.\n */\nexport const validateNoArgsWithInlinePrompt = (\n args: PromptArgs,\n): Effect.Effect<void, PromptError> => {\n if (Object.keys(args).length === 0) {\n return Effect.void;\n }\n return Effect.fail(\n new PromptError({\n message:\n 'promptArgs is only supported with promptFile. Inline prompts (prompt: \"...\") are passed to the agent as-is — interpolate values directly in JavaScript, or switch to promptFile to use {{KEY}} substitution.',\n }),\n );\n};\n\nexport const validateNoBuiltInArgOverride = (\n args: PromptArgs,\n): Effect.Effect<void, PromptError> => {\n for (const key of BUILT_IN_PROMPT_ARG_KEYS) {\n if (key in args) {\n return Effect.fail(\n new PromptError({\n message: `\"${key}\" is a built-in prompt argument and cannot be overridden via promptArgs`,\n }),\n );\n }\n }\n return Effect.void;\n};\n\n/**\n * Scans a prompt for `{{KEY}}` placeholders and returns the keys that are\n * missing from `providedArgs`, excluding built-in keys.\n */\nexport const findMissingPromptArgKeys = (\n prompt: string,\n providedArgs: PromptArgs,\n): string[] => {\n const builtInSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n const seen = new Set<string>();\n const missing: string[] = [];\n\n for (const key of placeholderKeys(prompt)) {\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n if (builtInSet.has(key)) {\n continue;\n }\n if (\n key in providedArgs &&\n providedArgs[key] !== null &&\n providedArgs[key] !== undefined\n ) {\n continue;\n }\n missing.push(key);\n }\n\n return missing;\n};\n\nconst HTML_COMMENT_PATTERN = /<!--[\\s\\S]*?(?:-->|$)/gu;\n\nconst markShellBlocks = (prompt: string): string => {\n const commentRanges = [...prompt.matchAll(HTML_COMMENT_PATTERN)].map(\n (m) => [m.index, m.index + m[0].length] as const,\n );\n return prompt.replaceAll(SHELL_BLOCK_PATTERN, (block, command, offset) =>\n commentRanges.some(([start, end]) => offset >= start && offset < end)\n ? block\n : `!${SHELL_BLOCK_MARKER}\\`${command}\\``,\n );\n};\n\n/** Strips shell-block markers from string arg values so they can't be forged. */\nconst sanitizeArgs = (args: PromptArgs): PromptArgs =>\n Object.fromEntries(\n Object.entries(args).map(([key, value]) => [\n key,\n typeof value === \"string\"\n ? value.replaceAll(SHELL_BLOCK_MARKER, \"\")\n : value,\n ]),\n );\n\n/**\n * Check for missing keys (placeholder in prompt but no matching arg, or\n * a present-but-nullish value supplied by an untyped caller — e.g. an\n * orchestrator building args from JSON.parse).\n */\nconst checkReferencedArgs = (\n referencedKeys: ReadonlySet<string>,\n args: PromptArgs,\n): Effect.Effect<void, PromptError> =>\n Effect.gen(function* () {\n for (const key of referencedKeys) {\n if (!(key in args)) {\n return yield* new PromptError({\n message: `Prompt argument \"{{${key}}}\" has no matching value in promptArgs`,\n });\n }\n const value = args[key];\n if (value === null || value === undefined) {\n return yield* new PromptError({\n message: `Prompt argument \"{{${key}}}\" has value ${value === null ? \"null\" : \"undefined\"} in promptArgs`,\n });\n }\n }\n });\n\n/**\n * Warn about unused keys (arg provided but no matching placeholder).\n * Skip keys listed in silentKeys (e.g. built-in args).\n */\nconst warnUnusedArgs = (\n args: PromptArgs,\n referencedKeys: ReadonlySet<string>,\n silentKeys: ReadonlySet<string> | undefined,\n): Effect.Effect<void, never, Display> =>\n Effect.gen(function* () {\n const display = yield* Display;\n for (const key of Object.keys(args)) {\n if (!referencedKeys.has(key) && silentKeys?.has(key) !== true) {\n yield* display.status(\n `Prompt argument \"${key}\" was provided but not referenced in the prompt`,\n \"warn\",\n );\n }\n }\n });\n\nexport const substitutePromptArgs = (\n prompt: string,\n args: PromptArgs,\n silentKeys?: ReadonlySet<string>,\n): Effect.Effect<string, PromptError, Display> => {\n // Mark shell blocks written in the raw template so the preprocessor can\n // distinguish them from `!`...`` patterns that arrive via arg substitution.\n // Shell blocks inside HTML comments stay unmarked, so commented-out examples\n // never run. Comment ranges come from the raw template, so an arg value\n // can't open or close one. Strip any markers already present in raw input\n // so they can't be forged.\n const markedPrompt = markShellBlocks(\n prompt.replaceAll(SHELL_BLOCK_MARKER, \"\"),\n );\n const sanitizedArgs = sanitizeArgs(args);\n const keys = placeholderKeys(markedPrompt);\n\n if (keys.length === 0 && Object.keys(sanitizedArgs).length === 0) {\n return Effect.succeed(markedPrompt);\n }\n\n return Effect.gen(function* () {\n // Collect all keys referenced in the prompt\n const referencedKeys = new Set(keys);\n yield* checkReferencedArgs(referencedKeys, sanitizedArgs);\n yield* warnUnusedArgs(sanitizedArgs, referencedKeys, silentKeys);\n\n // Replace all placeholders with their values\n // Every key was checked above to have a non-null value.\n return markedPrompt.replaceAll(PLACEHOLDER_PATTERN, (_match, key: string) =>\n String(sanitizedArgs[key]),\n );\n });\n};\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// ---------------------------------------------------------------------------\n// Output definition types (branded values for run() overload discrimination)\n// ---------------------------------------------------------------------------\n\n/** Branded output definition for `Output.object({ tag, schema })`. */\nexport interface OutputObjectDefinition<T> {\n readonly _tag: \"object\";\n readonly tag: string;\n readonly schema: StandardSchemaV1<unknown, T>;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction or validation fails. Each retry resumes the failed run's agent\n * session and feeds back a token-efficient description of the error so the\n * agent can re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Claude Code, Codex, Pi). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Branded output definition for `Output.string({ tag })`. */\nexport interface OutputStringDefinition {\n readonly _tag: \"string\";\n readonly tag: string;\n /**\n * Maximum number of additional attempts after the first if structured output\n * extraction fails. Each retry resumes the failed run's agent session and\n * feeds back a token-efficient description of the error so the agent can\n * re-emit a corrected tag. Default: `0` (no retries).\n *\n * Retries require the agent provider to support session resumption (i.e.\n * `provider.sessionStorage` is populated — Claude Code, Codex, Pi). `run()`\n * fails at entry with a clear error when retries are requested but the\n * provider cannot resume.\n */\n readonly maxRetries?: number;\n}\n\n/** Union of all output definition shapes accepted by `run()`. */\nexport type OutputDefinition =\n | OutputObjectDefinition<unknown>\n | OutputStringDefinition;\n\n// ---------------------------------------------------------------------------\n// Output namespace — public API\n// ---------------------------------------------------------------------------\n\n/**\n * Helpers for declaring structured output on `run()`.\n *\n * ```ts\n * import { Output, run } from \"@ai-hero/sandcastle\";\n * import { z } from \"zod\";\n *\n * const result = await run({\n * output: Output.object({ tag: \"result\", schema: z.object({ answer: z.number() }) }),\n * // ...\n * });\n * console.log(result.output.answer); // typed as number\n * ```\n */\nexport const Output = {\n /**\n * Declare an object-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are JSON-parsed (with fence-aware\n * unwrapping) and validated against the provided Standard Schema validator.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction or\n * validation fails. Default: `0` (no retries).\n */\n object: <Schema extends StandardSchemaV1>(opts: {\n tag: string;\n schema: Schema;\n maxRetries?: number;\n }): OutputObjectDefinition<StandardSchemaV1.InferOutput<Schema>> => ({\n _tag: \"object\",\n tag: opts.tag,\n schema: opts.schema,\n maxRetries: opts.maxRetries,\n }),\n\n /**\n * Declare a string-typed structured output extracted from an XML tag in\n * the agent's stdout. The tag contents are whitespace-trimmed and returned\n * as a plain string — no JSON parsing, no schema validation.\n *\n * Set `maxRetries` to have `run()` automatically resume the failed session\n * and ask the agent to re-emit corrected output when extraction fails.\n * Default: `0` (no retries).\n */\n string: (opts: {\n tag: string;\n maxRetries?: number;\n }): OutputStringDefinition => ({\n _tag: \"string\",\n tag: opts.tag,\n maxRetries: opts.maxRetries,\n }),\n} as const;\n\n// ---------------------------------------------------------------------------\n// StructuredOutputError\n// ---------------------------------------------------------------------------\n\nexport interface StructuredOutputErrorOptions {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n readonly cause?: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Thrown by `run()` when structured output extraction or validation fails.\n *\n * Possible failure modes:\n * - The configured XML tag was not found in stdout (`rawMatched` is `undefined`).\n * - The tag contents failed `JSON.parse` (`cause` carries the parse error).\n * - The parsed JSON failed schema validation (`cause` carries the Standard Schema issues).\n *\n * The error carries `commits`, `branch`, and optionally `preservedWorktreePath`\n * so callers can decide recovery without losing the run's side effects.\n *\n * It also carries `sessionId` (and `sessionFilePath` when the session was\n * captured to the host) of the iteration that produced the bad output, so a\n * caller can resume that same session and ask the agent to re-emit corrected\n * output:\n *\n * ```ts\n * try {\n * return await run({ ...opts, output });\n * } catch (e) {\n * if (e instanceof StructuredOutputError && e.sessionId) {\n * return await run({\n * ...opts,\n * output,\n * resumeSession: e.sessionId,\n * prompt: feedback(e),\n * });\n * }\n * throw e;\n * }\n * ```\n */\nexport class StructuredOutputError extends Error {\n readonly tag: string;\n readonly rawMatched: string | undefined;\n override readonly cause: unknown;\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n /** Session ID of the iteration that produced the bad output, when available. */\n readonly sessionId?: string;\n /** Host path to the captured session JSONL, when the session was captured. */\n readonly sessionFilePath?: string;\n\n constructor(message: string, options: StructuredOutputErrorOptions) {\n super(message);\n this.name = \"StructuredOutputError\";\n this.tag = options.tag;\n this.rawMatched = options.rawMatched;\n this.cause = options.cause;\n this.commits = options.commits;\n this.branch = options.branch;\n this.preservedWorktreePath = options.preservedWorktreePath;\n this.sessionId = options.sessionId;\n this.sessionFilePath = options.sessionFilePath;\n }\n}\n","import { StructuredOutputError } from \"./Output.js\";\nimport type {\n OutputDefinition,\n OutputObjectDefinition,\n OutputStringDefinition,\n} from \"./Output.js\";\n\ninterface ExtractionContext {\n readonly commits: { sha: string }[];\n readonly branch: string;\n readonly preservedWorktreePath?: string;\n readonly sessionId?: string;\n readonly sessionFilePath?: string;\n}\n\n/**\n * Extract and validate structured output from the agent's stdout.\n *\n * - Finds the **last** occurrence of `<tag>...</tag>` in stdout.\n * - For `Output.object`: unwraps optional Markdown fences, JSON-parses,\n * and validates against the Standard Schema.\n * - For `Output.string`: trims whitespace only.\n *\n * Throws `StructuredOutputError` on missing tag, invalid JSON, or schema failure.\n */\nexport const extractStructuredOutput = async (\n stdout: string,\n definition: OutputDefinition,\n context: ExtractionContext,\n): Promise<unknown> => {\n if (definition._tag === \"object\") {\n return extractObject(stdout, definition, context);\n }\n return extractString(stdout, definition, context);\n};\n\n// ---------------------------------------------------------------------------\n// Object extraction\n// ---------------------------------------------------------------------------\n\nconst extractObject = async <T>(\n stdout: string,\n definition: OutputObjectDefinition<T>,\n context: ExtractionContext,\n): Promise<T> => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n // Fence-aware unwrap + JSON parse\n const unwrapped = unwrapFences(raw.trim());\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(unwrapped);\n } catch (error) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> contains invalid JSON`,\n { tag: definition.tag, rawMatched: raw, cause: error, ...context },\n );\n }\n\n // Standard Schema validation\n const result = await definition.schema[\"~standard\"].validate(parsed);\n\n if (result.issues) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> failed schema validation`,\n {\n tag: definition.tag,\n rawMatched: raw,\n cause: result.issues,\n ...context,\n },\n );\n }\n\n return result.value;\n};\n\n// ---------------------------------------------------------------------------\n// String extraction\n// ---------------------------------------------------------------------------\n\nconst extractString = (\n stdout: string,\n definition: OutputStringDefinition,\n context: ExtractionContext,\n): string => {\n const raw = findLastTagContent(stdout, definition.tag);\n\n if (raw === undefined) {\n throw new StructuredOutputError(\n `Structured output tag <${definition.tag}> not found in agent output`,\n { tag: definition.tag, rawMatched: undefined, ...context },\n );\n }\n\n return raw.trim();\n};\n\n// ---------------------------------------------------------------------------\n// Tag extraction — last match wins\n// ---------------------------------------------------------------------------\n\n/**\n * Find the content between the **last** `<tag>` and `</tag>` pair in text.\n * Returns `undefined` if the tag is not found.\n */\nconst findLastTagContent = (text: string, tag: string): string | undefined => {\n const openTag = `<${tag}>`;\n const closeTag = `</${tag}>`;\n\n let lastContent: string | undefined;\n let searchFrom = 0;\n\n while (true) {\n const openIdx = text.indexOf(openTag, searchFrom);\n if (openIdx === -1) {\n break;\n }\n\n const contentStart = openIdx + openTag.length;\n const closeIdx = text.indexOf(closeTag, contentStart);\n if (closeIdx === -1) {\n break;\n }\n\n lastContent = text.slice(contentStart, closeIdx);\n searchFrom = closeIdx + closeTag.length;\n }\n\n return lastContent;\n};\n\n// ---------------------------------------------------------------------------\n// Fence-aware unwrap (object mode only)\n// ---------------------------------------------------------------------------\n\n/**\n * Strip an optional Markdown code fence from text.\n *\n * Recognises:\n * - ` ```json\\n...\\n``` `\n * - ` ```\\n...\\n``` `\n *\n * If no fence is detected, returns the input unchanged (already trimmed by caller).\n */\nconst unwrapFences = (text: string): string => {\n // Match ```json ... ``` or ``` ... ``` (with optional language hint)\n const fenced = /^```(?:json)?\\s*\\n(?<body>[\\s\\S]*?)\\n\\s*```\\s*$/u.exec(text)\n ?.groups?.body;\n if (fenced !== undefined) {\n return fenced.trim();\n }\n return text;\n};\n","import { inspect } from \"node:util\";\nimport type { Timeouts } from \"./run.js\";\n\n/** The timeout-shaped options shared by `run()`, `interactive()`, `createSandbox()`, `createWorktree()` and their handles. */\nexport interface TimeoutOptions {\n readonly idleTimeoutSeconds?: number;\n readonly completionTimeoutSeconds?: number;\n readonly timeouts?: Timeouts;\n}\n\nconst TIMEOUTS_KEYS = [\n \"copyToWorktreeMs\",\n \"gitSetupMs\",\n \"commitCollectionMs\",\n \"mergeToHostMs\",\n] as const satisfies readonly (keyof Timeouts)[];\n\nconst assertPositive = (\n name: string,\n unit: \"seconds\" | \"milliseconds\",\n value: unknown,\n): void => {\n if (value === undefined) {\n return;\n }\n // `!(value > 0)` also rejects NaN. Infinity stays allowed (no timeout).\n if (typeof value !== \"number\" || !(value > 0)) {\n throw new Error(\n `${name} must be a positive number of ${unit}. Received: ${inspect(value)}`,\n );\n }\n};\n\n/**\n * Throw a clear error when a timeout option is zero, negative or NaN.\n *\n * Called at entry, before any worktree or sandbox exists: a non-positive\n * timeout would otherwise fire before the agent's first output (or fail a\n * lifecycle step instantly) with a misleading error.\n */\nexport const validateTimeoutOptions = (options: TimeoutOptions): void => {\n assertPositive(\"idleTimeoutSeconds\", \"seconds\", options.idleTimeoutSeconds);\n assertPositive(\n \"completionTimeoutSeconds\",\n \"seconds\",\n options.completionTimeoutSeconds,\n );\n for (const key of TIMEOUTS_KEYS) {\n assertPositive(`timeouts.${key}`, \"milliseconds\", options.timeouts?.[key]);\n }\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport {\n appendFileSync,\n closeSync,\n fstatSync,\n mkdirSync,\n openSync,\n readSync,\n} from \"node:fs\";\nimport path, { join } from \"node:path\";\nimport { styleText } from \"node:util\";\nimport { Effect, Layer } from \"effect\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport {\n assertForkSupported,\n assertResumeSessionExists,\n} from \"./resumePrecheck.js\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display, FileDisplay } from \"./Display.js\";\nimport type { Severity } from \"./Display.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult, OrchestrateResult } from \"./Orchestrator.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport {\n WorktreeDockerSandboxFactory,\n SandboxConfig,\n} from \"./SandboxFactory.js\";\nimport type { SandboxProvider, BranchStrategy } from \"./SandboxProvider.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { formatErrorMessage } from \"./ErrorHandler.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport type { AgentStreamEvent } from \"./AgentStreamEmitter.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { generateTempBranchName, getCurrentBranch } from \"./WorktreeManager.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport type {\n OutputDefinition,\n OutputObjectDefinition,\n OutputStringDefinition,\n} from \"./Output.js\";\nimport { StructuredOutputError } from \"./Output.js\";\nimport type { PromptError } from \"./errors.js\";\nimport { extractStructuredOutput } from \"./extractStructuredOutput.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\nimport { buildContextWindowLines } from \"./ContextWindow.js\";\n\n/**\n * Build the token-efficient feedback prompt sent to the agent when retrying\n * structured output. The agent has already done the work in the resumed\n * session — the only ask is to re-emit a corrected tag.\n *\n * @internal\n */\nconst describeParserCause = (cause: unknown): string => {\n if (cause === undefined) {\n return \"(no parser detail)\";\n }\n if (typeof cause === \"string\") {\n return cause;\n }\n return JSON.stringify(cause, null, 2);\n};\n\nexport const buildStructuredOutputRetryFeedback = (\n error: StructuredOutputError,\n retriesRemaining: number,\n): string => {\n const raw = error.rawMatched ?? \"(no matching tag was emitted)\";\n const cause = describeParserCause(error.cause);\n\n return `Your previous response did not produce valid structured output.\n\nRetries remaining after this attempt: ${retriesRemaining}.\n\nProblem:\n${error.message}\n\nParser detail:\n${cause}\n\nPrevious matched output:\n${raw}\n\nEmit only a corrected <${error.tag}> block. Do not change files or run commands.`;\n};\n\n/** Default maximum number of iterations for a run. */\nexport const DEFAULT_MAX_ITERATIONS = 1;\n\n/** Replace characters that are invalid or problematic in file paths with dashes. */\nexport const sanitizeBranchForFilename = (branch: string): string =>\n branch.replaceAll(/[/\\\\:*?\"<>|]/gu, \"-\");\n\nexport interface FileDisplayStartupOptions {\n readonly logPath: string;\n readonly agentName?: string;\n readonly branch?: string;\n /** Resolved host repo directory. When it differs from `process.cwd()`, the\n * log-file hint is printed as an absolute path so it can be pasted into any\n * terminal. When it equals `process.cwd()` (or is omitted), a relative path\n * is printed instead. */\n readonly hostRepoDir?: string;\n}\n\n/**\n * Print the startup message to the terminal when using file-based logging.\n * Uses styleText for lightweight bold/dim styling — does not use Clack.\n */\nexport const printFileDisplayStartup = (\n options: FileDisplayStartupOptions,\n): void => {\n const name = options.agentName ?? \"Agent\";\n const label = styleText(\"bold\", `[${name}]`);\n const branchPart =\n options.branch !== undefined && options.branch !== \"\"\n ? ` on branch ${options.branch}`\n : \"\";\n const hostRepoDir = options.hostRepoDir ?? process.cwd();\n const displayLogPath =\n hostRepoDir === process.cwd()\n ? path.relative(process.cwd(), options.logPath)\n : options.logPath;\n console.log(`${label} Started${branchPart}`);\n console.log(styleText(\"dim\", ` tail -f ${displayLogPath}`));\n};\n\n/**\n * Build the log filename for a run.\n * When a targetBranch is provided (temp branch mode), prefixes the filename\n * with the sanitized target branch name so developers can identify which\n * branch the run was targeting: `<targetBranch>-<resolvedBranch>.log`\n * When no targetBranch, uses just the resolved branch: `<resolvedBranch>.log`\n * When a name is provided, appends it to avoid collisions in multi-agent workflows.\n */\nexport const buildLogFilename = (\n resolvedBranch: string,\n targetBranch?: string,\n name?: string,\n): string => {\n const sanitized = sanitizeBranchForFilename(resolvedBranch);\n // One dash per UTF-16 unit, as before the `u` flag on the regex below.\n const nameSuffix =\n name !== undefined && name !== \"\"\n ? `-${name.toLowerCase().replaceAll(/[^a-z0-9_.-]/gu, (char) => \"-\".repeat(char.length))}`\n : \"\";\n if (targetBranch !== undefined && targetBranch !== \"\") {\n return `${sanitizeBranchForFilename(targetBranch)}-${sanitized}${nameSuffix}.log`;\n }\n return `${sanitized}${nameSuffix}.log`;\n};\n\nexport interface RunSummaryRowsOptions {\n readonly name?: string;\n readonly agentName: string;\n readonly sandboxName: string;\n readonly maxIterations: number;\n readonly branch: string;\n}\n\n/**\n * Build the summary rows for a run, used in both terminal mode and\n * log-to-file mode. When a custom name is provided it appears as the\n * Agent value instead of the internal provider name.\n */\nexport const buildRunSummaryRows = (\n options: RunSummaryRowsOptions,\n): Record<string, string> => ({\n Agent: options.name ?? options.agentName,\n Sandbox: options.sandboxName,\n \"Max iterations\": String(options.maxIterations),\n Branch: options.branch,\n});\n\n/**\n * Build the completion status message for a run, used in both terminal mode\n * and log-to-file mode to record the final outcome.\n */\nexport const buildCompletionMessage = (\n completionSignal: string | undefined,\n iterationsRun: number,\n): { readonly message: string; readonly severity: Severity } => {\n if (completionSignal !== undefined) {\n return {\n message: `Run complete: agent finished after ${iterationsRun} iteration(s).`,\n severity: \"success\",\n };\n }\n return {\n message: `Run complete: reached ${iterationsRun} iteration(s) without completion signal.`,\n severity: \"warn\",\n };\n};\n\nexport { buildContextWindowLines } from \"./ContextWindow.js\";\n\n/**\n * Controls where Sandcastle writes iteration progress and agent output.\n * Use `\"file\"` (log-to-file mode) to write to a log file on disk, or\n * `\"stdout\"` (terminal mode) to render an interactive UI in the terminal.\n */\nexport type LoggingOption =\n /** Write progress and agent output to a log file at the given path (log-to-file mode). */\n | {\n readonly type: \"file\";\n readonly path: string;\n /**\n * Optional callback invoked for each agent stream event (text chunk,\n * tool call, or raw stdout line) in addition to being written to the\n * log file. Intended for forwarding the agent's output stream to\n * external observability systems. Errors thrown by the callback are\n * swallowed.\n */\n readonly onAgentStreamEvent?: (event: AgentStreamEvent) => void;\n /**\n * When `true`, every raw stdout line the agent emits is appended\n * verbatim to the same log file at `path`, in real time. Includes\n * lines the provider's stream parser would otherwise drop (e.g.\n * tool-use blocks for unrecognised tools). Intended for debugging\n * stuck or unexpected agent behavior — note that the raw JSON is\n * interleaved with the human-readable log output. Default: `false`.\n */\n readonly verbose?: boolean;\n }\n /** Render progress and agent output as an interactive UI in the terminal (terminal mode). */\n | {\n readonly type: \"stdout\";\n /**\n * When `true`, every raw stdout line the agent emits is written\n * verbatim to `process.stdout`, in real time. Includes lines the\n * provider's stream parser would otherwise drop. Intended for\n * debugging stuck or unexpected agent behavior. Note: the raw output\n * is interleaved with the interactive terminal UI. Default: `false`.\n */\n readonly verbose?: boolean;\n };\n\n/**\n * Build the agent-stream event handler for a resolved logging option.\n *\n * Composes the user-provided `onAgentStreamEvent` callback (file mode only)\n * with the verbose raw-line sink: the log file at `path` for file mode, or\n * `process.stdout` for stdout mode. Returns `undefined` when neither\n * verbose mode nor a user callback is set.\n *\n * Raw lines are written synchronously to honor the `onLine` real-time\n * contract — the debugger needs each line as soon as the agent emits it.\n *\n * @internal\n */\nexport const buildAgentStreamHandler = (\n logging: LoggingOption,\n): ((event: AgentStreamEvent) => void) | undefined => {\n const userHandler =\n logging.type === \"file\" ? logging.onAgentStreamEvent : undefined;\n const verboseSink =\n logging.verbose === true ? buildVerboseRawLineSink(logging) : undefined;\n if (!userHandler && !verboseSink) {\n return undefined;\n }\n return (event) => {\n if (userHandler) {\n try {\n userHandler(event);\n } catch {\n // Swallow — a broken forwarder must not stop the verbose sink.\n }\n }\n if (verboseSink && event.type === \"raw\") {\n verboseSink(event.line);\n }\n };\n};\n\n/**\n * Whether the file's last byte is something other than a newline. The log file\n * has two writers: FileDisplay streams agent prose as chunks with no trailing\n * newline, and the verbose sink appends raw lines. Reading the file's actual\n * tail lets the sink start each raw line on a fresh line without sharing state\n * with FileDisplay. A missing or empty file counts as \"not mid-line\".\n */\nconst fileEndsMidLine = (filePath: string): boolean => {\n let fd: number | undefined;\n try {\n fd = openSync(filePath, \"r\");\n const { size } = fstatSync(fd);\n if (size === 0) {\n return false;\n }\n const lastByte = Buffer.alloc(1);\n readSync(fd, lastByte, 0, 1, size - 1);\n return lastByte[0] !== 0x0a;\n } catch {\n return false;\n } finally {\n if (fd !== undefined) {\n closeSync(fd);\n }\n }\n};\n\nconst buildVerboseRawLineSink = (\n logging: LoggingOption,\n): ((line: string) => void) => {\n if (logging.type === \"file\") {\n const logPath = logging.path;\n // Ensure the directory exists; the FileDisplay layer creates it for the\n // primary log file but it hasn't necessarily run by the time the first\n // raw line is flushed.\n try {\n mkdirSync(path.dirname(logPath), { recursive: true });\n } catch {\n // Swallow — appendFileSync below will surface any real I/O error.\n }\n return (line) => {\n try {\n const prefix = fileEndsMidLine(logPath) ? \"\\n\" : \"\";\n appendFileSync(logPath, `${prefix + line}\\n`);\n } catch {\n // Swallow — verbose-mode I/O errors must not kill the run.\n }\n };\n }\n return (line) => {\n process.stdout.write(`${line}\\n`);\n };\n};\n\n/** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\nexport interface Timeouts {\n /** Timeout (ms) for the host-side copy of `copyToWorktree` paths into the worktree. Default: 60_000. */\n readonly copyToWorktreeMs?: number;\n /** Timeout (ms) for each in-sandbox git setup command (safe.directory, user.name/email, branch discovery). Default: 10_000. */\n readonly gitSetupMs?: number;\n /** Timeout (ms) for collecting the commits produced during the run. Default: 30_000. */\n readonly commitCollectionMs?: number;\n /** Timeout (ms) for merging the temp branch back to the host branch (merge-to-head strategy). Default: 30_000. */\n readonly mergeToHostMs?: number;\n}\n\nexport interface RunOptions<A extends AgentProvider = AgentProvider> {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: A;\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, `.sandcastle/logs/`,\n * `.sandcastle/patches/`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Inline prompt string (mutually exclusive with promptFile) */\n readonly prompt?: string;\n /**\n * Path to a prompt file (mutually exclusive with prompt).\n *\n * **Note:** `promptFile` is always resolved against `process.cwd()`, not\n * against the `cwd` option. If you set a custom `cwd`, pass an absolute\n * `promptFile` to avoid ambiguity.\n */\n readonly promptFile?: string;\n /** Maximum iterations to run (default: 1) */\n readonly maxIterations?: number;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Logging mode (default: { type: 'file' } with auto-generated path under .sandcastle/logs/) */\n readonly logging?: LoggingOption;\n /** Substring(s) the agent emits to stop the iteration loop early. Matched via `includes` against agent output. (default: `\"<promise>COMPLETE</promise>\"`) */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. If the agent produces no output for this long, it fails. Default: 600 (10 minutes) */\n readonly idleTimeoutSeconds?: number;\n /**\n * Grace window in seconds after a completion signal is observed in the\n * agent's output. The agent process is expected to exit shortly after\n * emitting the signal; if it does not (typically because a spawned child —\n * a `gh`/git subprocess or long-lived MCP server — keeps stdout open),\n * Sandcastle force-completes the iteration with a warning. Resets on every\n * subsequent output line so trailing data (token-usage events, terminal\n * `result` events, structured-output tags) is still captured. Independent\n * of `idleTimeoutSeconds`. Default: 60.\n */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run, shown as a prefix in log output */\n readonly name?: string;\n /** Paths relative to the host repo root to copy into the worktree before sandbox start. */\n readonly copyToWorktree?: string[];\n /** Branch strategy — controls how the agent's changes relate to branches.\n * Defaults to { type: \"head\" } for bind-mount providers and { type: \"merge-to-head\" } for isolated providers. */\n readonly branchStrategy?: BranchStrategy;\n /** Resume a prior Claude Code session by ID. The session JSONL must exist on the host. Incompatible with maxIterations > 1. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it. The parent session JSONL is left intact and the agent writes a new\n * session under a fresh id. Exposed as the public `.fork()` method on\n * `RunResult` rather than as a stand-alone caller option — see ADR 0018.\n *\n * @internal\n */\n readonly forkSession?: boolean;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, `run()` rejects\n * immediately without doing any setup work.\n * - Aborting mid-iteration kills the in-flight agent subprocess.\n * - Phase boundaries (between iterations) also check the signal.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n * - The worktree is preserved on disk after abort, even when it has no\n * uncommitted changes, and its path is printed to stderr.\n */\n readonly signal?: AbortSignal;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /**\n * Structured output definition. When provided, the agent's stdout is\n * scanned for the configured XML tag after the iteration completes, and the\n * result is parsed/validated and returned on `RunResult.output`.\n *\n * Use `Output.object({ tag, schema })` for JSON+schema or\n * `Output.string({ tag })` for raw string extraction.\n *\n * Constraints:\n * - `maxIterations` must be `1` (the default).\n * - The resolved prompt must contain the configured opening tag literal.\n *\n * See ADR 0010 for design rationale.\n */\n readonly output?: OutputDefinition;\n}\n\nexport type { IterationResult, IterationUsage } from \"./Orchestrator.js\";\nexport type { ContextWindow } from \"./ContextWindow.js\";\n\nexport type ResumeRunResultOptions = Omit<\n RunOptions,\n | \"agent\"\n | \"sandbox\"\n | \"prompt\"\n | \"promptFile\"\n | \"resumeSession\"\n | \"forkSession\"\n | \"maxIterations\"\n>;\n\nexport interface RunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if no signal fired before the iteration limit. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run, each identified by its SHA. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on inside the sandbox. */\n readonly branch: string;\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n /** Host path to the preserved worktree, set when the run succeeded but the worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n /** Continue the last captured agent session for exactly one iteration.\n * Present only when the provider supports resume (`sessionStorage` populated).\n * `output` and `promptArgs` are not inherited: pass `output` again to get\n * structured output from the follow-up (its prompt must contain the tag). */\n readonly resume?: (\n prompt: string,\n options?: ResumeRunResultOptions,\n ) => Promise<RunResult>;\n /**\n * Fork the last captured agent session for exactly one iteration: the\n * parent session JSONL is left intact and the child run gets its own\n * session id, enabling fan-out patterns where multiple children diverge\n * from a single parent. Present only when the provider supports resume\n * (`sessionStorage` populated).\n *\n * Sessions only: fork isolates the agent session, not the branch or\n * sandbox. Safe concurrent fan-out (`Promise.all([r.fork(a), r.fork(b)])`)\n * requires the caller to give each fork a distinct `branch` — `head` and\n * `merge-to-head` are not safe for concurrent forks. See ADR 0018.\n *\n * Like `resume`, `output` and `promptArgs` are not inherited.\n */\n readonly fork?: (\n prompt: string,\n options?: ResumeRunResultOptions,\n ) => Promise<RunResult>;\n}\n\n/** Fails when the branch strategy can't be used with the other options. */\nconst validateBranchOptions = (\n options: RunOptions,\n branchType: BranchStrategy[\"type\"],\n): void => {\n // Validate: head strategy is not supported with isolated providers\n if (branchType === \"head\" && options.sandbox.tag === \"isolated\") {\n throw new Error(\n \"head branch strategy is not supported with isolated providers\",\n );\n }\n\n // Validate: copyToWorktree is incompatible with head strategy\n if (\n branchType === \"head\" &&\n options.copyToWorktree &&\n options.copyToWorktree.length > 0\n ) {\n throw new Error(\n \"copyToWorktree is not supported with head branch strategy. \" +\n \"In head mode the host working directory is bind-mounted directly.\",\n );\n }\n};\n\n/** Fails on an impossible resume/fork combination; whether this run resumes. */\nconst validateSessionOptions = (\n options: RunOptions,\n maxIterations: number,\n): boolean => {\n const isResuming =\n options.resumeSession !== undefined && options.resumeSession !== \"\";\n\n // Validate: resumeSession + maxIterations > 1 is not allowed\n if (isResuming && maxIterations > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n // Validate: forkSession only makes sense alongside resumeSession.\n // It is wired internally by RunResult.fork() and never set on its own.\n if (options.forkSession === true && !isResuming) {\n throw new Error(\n \"forkSession requires resumeSession. \" +\n \"Use RunResult.fork(prompt) to fork the last captured session.\",\n );\n }\n if (options.forkSession === true) {\n assertForkSupported(options.agent);\n }\n return isResuming;\n};\n\n/** Fails on unusable structured-output options; the output retry budget. */\nconst validateOutputOptions = (\n options: RunOptions,\n maxIterations: number,\n): number => {\n // Validate: output requires maxIterations === 1\n if (options.output && maxIterations !== 1) {\n throw new Error(\n \"output requires maxIterations to be 1. \" +\n \"Structured output is only supported for single-iteration runs.\",\n );\n }\n\n // Validate: output.maxRetries requires a provider that supports session\n // resumption. Fail at the earliest possible point — the issue is fully\n // determined by the inputs to run() and does not depend on the agent's\n // output. See issue #825.\n const outputMaxRetries = options.output?.maxRetries ?? 0;\n if (outputMaxRetries < 0 || !Number.isInteger(outputMaxRetries)) {\n throw new Error(\n \"output.maxRetries must be a non-negative integer. \" +\n `Received: ${outputMaxRetries}`,\n );\n }\n if (outputMaxRetries > 0 && !options.agent.sessionStorage) {\n throw new Error(\n `output.maxRetries requires an agent provider that supports session resumption. ` +\n `The \"${options.agent.name}\" provider does not. ` +\n `Use an agent provider that supports resume, or set maxRetries to 0.`,\n );\n }\n return outputMaxRetries;\n};\n\n/**\n * The prompt the agent gets. Inline prompts pass through to the agent\n * literally — no substitution, no built-in arg injection. Guard against\n * silently ignoring promptArgs.\n */\nconst buildAgentPrompt = (input: {\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n readonly userArgs: PromptArgs;\n readonly sourceBranch: string;\n readonly targetBranch: string;\n}): Effect.Effect<string, PromptError, Display> =>\n Effect.gen(function* () {\n if (input.isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(input.userArgs);\n return input.rawPrompt;\n }\n yield* validateNoBuiltInArgOverride(input.userArgs);\n const effectiveArgs = {\n SOURCE_BRANCH: input.sourceBranch,\n TARGET_BRANCH: input.targetBranch,\n ...input.userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n return yield* substitutePromptArgs(\n input.rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n });\n\n/** Shows how the run ended and how full each iteration's context window got. */\nconst reportRunEnd = (\n result: OrchestrateResult,\n): Effect.Effect<void, never, Display> =>\n Effect.gen(function* () {\n const d = yield* Display;\n const completion = buildCompletionMessage(\n result.completionSignal,\n result.iterations.length,\n );\n yield* d.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(result.iterations)) {\n yield* d.text(line);\n }\n });\n\n/**\n * A follow-up run on the last iteration's session: `resume` continues it,\n * `fork` continues a copy.\n */\nconst followUpRun =\n (options: RunOptions, result: OrchestrateResult, kind: \"resume\" | \"fork\") =>\n async (\n followUpPrompt: string,\n followUpOptions?: ResumeRunResultOptions,\n ): Promise<RunResult> => {\n const lastIteration = result.iterations.at(-1);\n if (\n lastIteration?.sessionId === undefined ||\n lastIteration.sessionId === \"\"\n ) {\n throw new Error(`Cannot ${kind}: no sessionId was captured`);\n }\n return run({\n ...options,\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n // The follow-up prompt is new: structured output is opt-in per call.\n output: undefined,\n ...followUpOptions,\n prompt: followUpPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: lastIteration.sessionId,\n ...(kind === \"fork\" ? { forkSession: true } : {}),\n });\n };\n\n/** The host repo dir; when resuming, also checks the session file exists there. */\nconst resolveRunHostRepoDir = async (\n options: RunOptions,\n isResuming: boolean,\n): Promise<string> => {\n const hostRepoDir = await Effect.runPromise(\n resolveCwd(options.cwd).pipe(Effect.provide(NodeContext.layer)),\n );\n // Validate: resumeSession file must exist on the host\n if (isResuming && options.resumeSession !== undefined) {\n await assertResumeSessionExists({\n provider: options.agent,\n sandboxTag: options.sandbox.tag,\n hostRepoDir,\n resumeSession: options.resumeSession,\n });\n }\n return hostRepoDir;\n};\n\n/** Explicit branch strategy, else merge-to-head for isolated providers, else head. */\nconst resolveBranchStrategy = (options: RunOptions): BranchStrategy =>\n options.branchStrategy ??\n (options.sandbox.tag === \"isolated\"\n ? { type: \"merge-to-head\" }\n : { type: \"head\" });\n\n/** The prompt text and whether it was inline, with the output tag checked. */\nconst resolveRunPrompt = async (\n options: RunOptions,\n): Promise<{\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n}> => {\n const resolved = await Effect.runPromise(\n resolvePrompt({\n prompt: options.prompt,\n promptFile: options.promptFile,\n }).pipe(Effect.provide(NodeContext.layer)),\n );\n // Validate: output tag must appear in the resolved prompt\n if (options.output && !resolved.text.includes(`<${options.output.tag}>`)) {\n throw new Error(\n `output tag <${options.output.tag}> not found in the resolved prompt. ` +\n \"The caller must instruct the agent to emit the configured tag.\",\n );\n }\n return {\n rawPrompt: resolved.text,\n isInlinePrompt: resolved.source === \"inline\",\n };\n};\n\n/** The branches a run works with, derived from the host's current branch. */\ninterface RunBranches {\n /** The host's current branch: the TARGET_BRANCH built-in prompt argument. */\n readonly currentHostBranch: string;\n /** The branch the agent works on. */\n readonly resolvedBranch: string;\n /** Set when using a temp branch: prefixes the log filename. */\n readonly targetBranch: string | undefined;\n /** The branch passed to orchestrate (see `resolveRunBranches`). */\n readonly orchestrateBranch: string | undefined;\n}\n\nconst resolveRunBranches = async (\n options: RunOptions,\n branchStrategy: BranchStrategy,\n hostRepoDir: string,\n): Promise<RunBranches> => {\n // Explicit branch when in branch mode\n const branch =\n branchStrategy.type === \"branch\" ? branchStrategy.branch : undefined;\n const currentHostBranch = await Effect.runPromise(\n getCurrentBranch(hostRepoDir),\n );\n return {\n currentHostBranch,\n // When in merge-to-head mode, generate a temporary branch name.\n // In head mode, use the host's current branch directly (no worktree).\n resolvedBranch:\n branchStrategy.type === \"head\"\n ? currentHostBranch\n : (branch ?? generateTempBranchName(options.name)),\n // When using a temp branch, prefix the log filename with the target branch\n // (the host's current branch) so developers can tell which branch was targeted.\n targetBranch:\n branchStrategy.type === \"merge-to-head\" ? currentHostBranch : undefined,\n // In head mode, pass the host branch so SandboxLifecycle skips the merge step.\n // In merge-to-head mode, branch is undefined (triggers merge). In branch mode, it's the explicit branch.\n orchestrateBranch:\n branchStrategy.type === \"head\" ? currentHostBranch : branch,\n };\n};\n\n/** Resolve env vars and merge with the agent and sandbox providers' env. */\nconst resolveRunEnv = async (options: RunOptions, hostRepoDir: string) =>\n mergeProviderEnv({\n resolvedEnv: await Effect.runPromise(\n resolveEnv(hostRepoDir).pipe(Effect.provide(NodeContext.layer)),\n ),\n agentProviderEnv: options.agent.env,\n sandboxProviderEnv: options.sandbox.env,\n });\n\n/** Shared inputs for building a run's layers and effect. */\ninterface RunSetup {\n readonly options: RunOptions;\n readonly branchStrategy: BranchStrategy;\n readonly hostRepoDir: string;\n readonly maxIterations: number;\n readonly branches: RunBranches;\n readonly logging: LoggingOption;\n /** Resolved env vars merged with the agent and sandbox providers' env. */\n readonly env: Record<string, string>;\n readonly rawPrompt: string;\n readonly isInlinePrompt: boolean;\n}\n\n/** `options.logging`, else a file under .sandcastle/logs named for the branch. */\nconst resolveRunLogging = (\n options: RunOptions,\n hostRepoDir: string,\n { resolvedBranch, targetBranch }: RunBranches,\n): LoggingOption =>\n options.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(resolvedBranch, targetBranch, options.name),\n ),\n };\n\nconst buildDisplayLayer = ({\n options,\n hostRepoDir,\n branches,\n logging,\n}: RunSetup) => {\n if (logging.type !== \"file\") {\n return ClackDisplay.layer;\n }\n printFileDisplayStartup({\n logPath: logging.path,\n agentName: options.name,\n branch: branches.resolvedBranch,\n hostRepoDir,\n });\n return Layer.provide(FileDisplay.layer(logging.path), NodeFileSystem.layer);\n};\n\n/** The display, sandbox factory and agent stream layers for a run. */\nconst buildRunLayer = (setup: RunSetup) => {\n const { options, hostRepoDir, branchStrategy, branches, env } = setup;\n const displayLayer = buildDisplayLayer(setup);\n const factoryLayer = Layer.provide(\n WorktreeDockerSandboxFactory.layer,\n Layer.mergeAll(\n Layer.succeed(SandboxConfig, {\n env,\n hostRepoDir,\n copyToWorktree: options.copyToWorktree,\n name: options.name,\n // Create the worktree on the temp branch already shown to the user,\n // rather than letting WorktreeManager generate a second name.\n tempBranch:\n branchStrategy.type === \"merge-to-head\"\n ? branches.resolvedBranch\n : undefined,\n sandboxProvider: options.sandbox,\n branchStrategy,\n hooks: options.hooks,\n signal: options.signal,\n timeouts: options.timeouts,\n }),\n NodeFileSystem.layer,\n displayLayer,\n ),\n );\n return Layer.mergeAll(\n factoryLayer,\n displayLayer,\n agentStreamEmitterLayer(buildAgentStreamHandler(setup.logging)),\n );\n};\n\n/** Shows the run summary, builds the prompt, and orchestrates the iterations. */\nconst runIterations = ({\n options,\n hostRepoDir,\n maxIterations,\n branches,\n rawPrompt,\n isInlinePrompt,\n}: RunSetup) =>\n Effect.gen(function* () {\n const d = yield* Display;\n yield* d.intro(options.name ?? \"sandcastle\");\n const rows = buildRunSummaryRows({\n name: options.name,\n agentName: options.agent.name,\n sandboxName: options.sandbox.name,\n maxIterations,\n branch: branches.resolvedBranch,\n });\n yield* d.summary(\"Sandcastle Run\", rows);\n\n const resolvedPrompt = yield* buildAgentPrompt({\n rawPrompt,\n isInlinePrompt,\n userArgs: options.promptArgs ?? {},\n sourceBranch: branches.resolvedBranch,\n targetBranch: branches.currentHostBranch,\n });\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir,\n iterations: maxIterations,\n hooks: options.hooks,\n prompt: resolvedPrompt,\n branch: branches.orchestrateBranch,\n provider: options.agent,\n completionSignal: options.completionSignal,\n idleTimeoutSeconds: options.idleTimeoutSeconds,\n completionTimeoutSeconds: options.completionTimeoutSeconds,\n name: options.name,\n resumeSession: options.resumeSession,\n forkSession: options.forkSession,\n signal: options.signal,\n skipPromptExpansion: isInlinePrompt,\n timeouts: options.timeouts,\n });\n\n yield* reportRunEnd(orchestrateResult);\n return orchestrateResult;\n });\n\n/** Runs the iterations; with file logging, errors are written to the log first. */\nconst executeRun = async (setup: RunSetup): Promise<OrchestrateResult> => {\n const baseEffect = runIterations(setup);\n // In stdout mode (ClackDisplay), errors are already shown by withFriendlyErrors\n // in main.ts, so we skip to avoid duplicate terminal output.\n const withErrorLog =\n setup.logging.type === \"file\"\n ? baseEffect.pipe(\n Effect.tapError((error) =>\n Effect.gen(function* () {\n const d = yield* Display;\n yield* d.status(formatErrorMessage(error), \"error\");\n }),\n ),\n )\n : baseEffect;\n const runLayer = buildRunLayer(setup);\n try {\n return await Effect.runPromise(withErrorLog.pipe(Effect.provide(runLayer)));\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n setup.options.signal?.throwIfAborted();\n throw error;\n }\n};\n\n/**\n * Extracts structured output from a finished run. On a StructuredOutputError\n * with retries left and a session to resume, retries with a token-efficient\n * feedback prompt; each retry decrements maxRetries, so it terminates (#825).\n */\nconst withStructuredOutput = async (\n options: RunOptions & { output: NonNullable<RunOptions[\"output\"]> },\n baseResult: RunResult,\n outputMaxRetries: number,\n): Promise<RunResult & { output?: unknown }> => {\n // Structured output runs are single-iteration, so the last iteration is the\n // one that produced this stdout. Carry its session id onto the error so a\n // caller can resume the same session to re-emit corrected output.\n const lastIteration = baseResult.iterations.at(-1);\n try {\n const output = await extractStructuredOutput(\n baseResult.stdout,\n options.output,\n {\n commits: baseResult.commits,\n branch: baseResult.branch,\n preservedWorktreePath: baseResult.preservedWorktreePath,\n sessionId: lastIteration?.sessionId,\n sessionFilePath: lastIteration?.sessionFilePath,\n },\n );\n return { ...baseResult, output };\n } catch (error) {\n if (\n error instanceof StructuredOutputError &&\n outputMaxRetries > 0 &&\n error.sessionId !== undefined\n ) {\n const retriesRemainingAfter = outputMaxRetries - 1;\n const retryOutput = {\n ...options.output,\n maxRetries: retriesRemainingAfter,\n };\n return run({\n ...options,\n prompt: buildStructuredOutputRetryFeedback(\n error,\n retriesRemainingAfter,\n ),\n promptFile: undefined,\n promptArgs: undefined,\n resumeSession: error.sessionId,\n forkSession: false,\n output: retryOutput,\n } as RunOptions);\n }\n throw error;\n }\n};\n\n/** The run's result, with its follow-ups and any structured output. */\nconst finishRun = async ({\n options,\n result,\n logging,\n outputMaxRetries,\n}: {\n readonly options: RunOptions;\n readonly result: OrchestrateResult;\n readonly logging: LoggingOption;\n readonly outputMaxRetries: number;\n}): Promise<RunResult & { output?: unknown }> => {\n const baseResult = {\n ...result,\n logFilePath: logging.type === \"file\" ? logging.path : undefined,\n resume: followUpRun(options, result, \"resume\"),\n fork: followUpRun(options, result, \"fork\"),\n };\n // Extract structured output after the iteration completes (separate pass from completion signal)\n const { output } = options;\n if (!output) {\n return baseResult;\n }\n return withStructuredOutput(\n { ...options, output },\n baseResult,\n outputMaxRetries,\n );\n};\n\n/** Overload: with `Output.object`, returns `RunResult` with typed `output: T`. */\nexport function run<T, A extends AgentProvider>(\n options: RunOptions<A> & { output: OutputObjectDefinition<T> },\n): Promise<RunResult & { output: T }>;\n/** Overload: with `Output.string`, returns `RunResult` with `output: string`. */\nexport function run<A extends AgentProvider>(\n options: RunOptions<A> & { output: OutputStringDefinition },\n): Promise<RunResult & { output: string }>;\n/** Overload: without `output`, returns the standard `RunResult`. */\nexport function run<A extends AgentProvider>(\n options: RunOptions<A>,\n): Promise<RunResult>;\nexport async function run(\n options: RunOptions,\n): Promise<RunResult & { output?: unknown }> {\n // If signal is already aborted, reject immediately without any setup\n options.signal?.throwIfAborted();\n\n const { maxIterations = DEFAULT_MAX_ITERATIONS } = options;\n const branchStrategy = resolveBranchStrategy(options);\n\n // Validate: timeouts must be positive (0 would fire before the agent's first output)\n validateTimeoutOptions(options);\n validateBranchOptions(options, branchStrategy.type);\n const isResuming = validateSessionOptions(options, maxIterations);\n const outputMaxRetries = validateOutputOptions(options, maxIterations);\n\n const hostRepoDir = await resolveRunHostRepoDir(options, isResuming);\n\n const { rawPrompt, isInlinePrompt } = await resolveRunPrompt(options);\n const env = await resolveRunEnv(options, hostRepoDir);\n const branches = await resolveRunBranches(\n options,\n branchStrategy,\n hostRepoDir,\n );\n const logging = resolveRunLogging(options, hostRepoDir, branches);\n const result = await executeRun({\n options,\n branchStrategy,\n hostRepoDir,\n maxIterations,\n branches,\n logging,\n env,\n rawPrompt,\n isInlinePrompt,\n });\n\n return finishRun({ options, result, logging, outputMaxRetries });\n}\n","import { Deferred, Effect, Runtime } from \"effect\";\n\n/**\n * Race an Effect against an optional `AbortSignal`.\n *\n * - If no signal is provided, the effect runs unmodified.\n * - If the signal is already aborted at call time, dies immediately with\n * `signal.reason`.\n * - Otherwise, races the effect against a Deferred that fires when the\n * signal aborts.\n *\n * Uses `Effect.die` so the abort reason propagates as a defect — callers\n * should use `signal.throwIfAborted()` in their catch handler to surface\n * the original reason without Sandcastle-specific wrapping.\n *\n * The abort listener is always cleaned up, even when the effect wins the race.\n */\nexport const raceAbortSignal = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n signal?: AbortSignal,\n): Effect.Effect<A, E, R> => {\n if (!signal) {\n return effect;\n }\n\n return Effect.gen(function* () {\n if (signal.aborted) {\n return yield* Effect.die(signal.reason);\n }\n\n const abortDeferred = yield* Deferred.make<never>();\n // The listener fires outside any fiber; fork onto the surrounding runtime.\n const runFork = Runtime.runFork(yield* Effect.runtime());\n const onAbort = () => {\n runFork(Deferred.die(abortDeferred, signal.reason));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n return yield* Effect.raceFirst(effect, Deferred.await(abortDeferred)).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n signal.removeEventListener(\"abort\", onAbort);\n }),\n ),\n );\n });\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport * as clack from \"@clack/prompts\";\nimport { Effect, Layer } from \"effect\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport {\n makeSandboxFromHandle,\n resolveGitMounts,\n SANDBOX_REPO_DIR,\n} from \"./SandboxFactory.js\";\nimport type { MountEntry } from \"./SandboxFactory.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type {\n SandboxProvider,\n BranchStrategy,\n BindMountSandboxHandle,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n} from \"./SandboxProvider.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { startSandbox } from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { generateTempBranchName, getCurrentBranch } from \"./WorktreeManager.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n findMissingPromptArgKeys,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { noSandbox } from \"./sandboxes/no-sandbox.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport type { Timeouts } from \"./run.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\nexport interface InteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker(), noSandbox()). */\n readonly sandbox?: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Optional name for the interactive session. */\n readonly name?: string;\n /** Branch strategy — controls how the agent's changes relate to branches.\n * Defaults to { type: \"head\" } for bind-mount providers and { type: \"merge-to-head\" } for isolated providers. */\n readonly branchStrategy?: BranchStrategy;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree before sandbox start. */\n readonly copyToWorktree?: string[];\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /**\n * Host repo directory to use instead of `process.cwd()`.\n *\n * Relative paths resolve against `process.cwd()`; absolute paths pass\n * through as-is. A {@link CwdError} is thrown if the path does not exist\n * or is not a directory.\n */\n readonly cwd?: string;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, `interactive()` rejects\n * immediately without doing any setup work.\n * - Aborting during an active session kills the agent subprocess.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n * - The worktree is preserved on disk after abort (error-path behavior).\n */\n readonly signal?: AbortSignal;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n}\n\nexport interface InteractiveResult {\n /** List of commits made during the interactive session. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on. */\n readonly branch: string;\n /** Host path to the preserved worktree, if worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n /** Exit code of the interactive process. */\n readonly exitCode: number;\n}\n\n/**\n * Launch an interactive agent session inside a sandbox.\n *\n * The user sees the agent's TUI directly. When the session ends,\n * Sandcastle collects commits and handles branch merging, just like run().\n *\n * Full prompt preprocessing pipeline: PromptResolver -> PromptArgumentSubstitution\n * -> PromptPreprocessor (shell expressions inside sandbox).\n *\n * All three branch strategies are supported: head, merge-to-head, branch.\n */\nexport const interactive = async (\n options: InteractiveOptions,\n): Promise<InteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n options.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = options;\n\n validateTimeoutOptions(options);\n\n const resolvedSandbox = options.sandbox ?? noSandbox();\n assertInteractiveSupported(resolvedSandbox);\n\n // Derive branch strategy\n const branchStrategy: BranchStrategy =\n options.branchStrategy ??\n (resolvedSandbox.tag === \"isolated\"\n ? { type: \"merge-to-head\" }\n : { type: \"head\" }); // \"bind-mount\" and \"none\" both default to head\n\n // Validate: head strategy is not supported with isolated providers\n if (branchStrategy.type === \"head\" && resolvedSandbox.tag === \"isolated\") {\n throw new Error(\n \"head branch strategy is not supported with isolated providers\",\n );\n }\n\n // Validate: copyToWorktree is incompatible with head strategy\n if (\n branchStrategy.type === \"head\" &&\n options.copyToWorktree &&\n options.copyToWorktree.length > 0\n ) {\n throw new Error(\n \"copyToWorktree is not supported with head branch strategy. \" +\n \"In head mode the host working directory is bind-mounted directly.\",\n );\n }\n\n // Validate buildInteractiveArgs is available\n const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n const branch: string | undefined =\n branchStrategy.type === \"branch\" ? branchStrategy.branch : undefined;\n\n const isHeadMode = branchStrategy.type === \"head\";\n const sandboxProvider = resolvedSandbox;\n\n const inner = Effect.gen(function* () {\n const hostRepoDir = yield* resolveCwd(options.cwd);\n const d = yield* Display;\n\n // 1. Resolve prompt (from string or file), or skip if neither provided\n const hasPromptSource = prompt !== undefined || promptFile !== undefined;\n const resolved = hasPromptSource\n ? yield* resolvePrompt({ prompt, promptFile })\n : undefined;\n const rawPrompt = resolved?.text ?? \"\";\n const isInlinePrompt = resolved?.source === \"inline\";\n\n // 2. Resolve env vars\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: provider.env,\n sandboxProviderEnv: sandboxProvider.env,\n });\n const effectiveEnv = { ...env, ...options.env };\n\n // 3. Capture host's current branch\n const currentHostBranch = yield* getCurrentBranch(hostRepoDir);\n\n const resolvedBranch =\n branchStrategy.type === \"head\"\n ? currentHostBranch\n : (branch ?? generateTempBranchName(options.name));\n\n // 4. Validate prompt args and collect missing ones interactively (skip when no prompt).\n // Inline prompts pass through literally — skip scanning, substitution, and built-in args.\n let substitutedPrompt = rawPrompt;\n if (hasPromptSource && !isInlinePrompt) {\n const userArgs = options.promptArgs ?? {};\n yield* validateNoBuiltInArgOverride(userArgs);\n\n // Scan for missing keys and prompt the user for each one\n const missingKeys = findMissingPromptArgKeys(rawPrompt, userArgs);\n const collectedArgs: Record<string, string> = {};\n for (const key of missingKeys) {\n const value = yield* Effect.promise(async () =>\n clack.text({\n message: `Enter value for {{${key}}}`,\n validate: (v) => {\n if (v === undefined || v === \"\") {\n return `A value is required for {{${key}}}`;\n }\n },\n }),\n );\n if (clack.isCancel(value)) {\n clack.cancel(\"Prompt arg collection cancelled.\");\n return yield* Effect.fail(\n new Error(\"User cancelled prompt arg collection\"),\n );\n }\n collectedArgs[key] = value;\n }\n\n const mergedUserArgs = { ...userArgs, ...collectedArgs };\n const effectiveArgs = {\n SOURCE_BRANCH: resolvedBranch,\n TARGET_BRANCH: currentHostBranch,\n ...mergedUserArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n substitutedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n } else if (isInlinePrompt) {\n const userArgs = options.promptArgs ?? {};\n yield* validateNoArgsWithInlinePrompt(userArgs);\n }\n\n // In head mode, pass the host branch so SandboxLifecycle skips the merge step.\n const lifecycleBranch = isHeadMode ? currentHostBranch : branch;\n\n // Display intro and summary\n yield* d.intro(options.name ?? \"sandcastle interactive\");\n yield* d.summary(\"Interactive Session\", {\n Agent: options.name ?? provider.name,\n Sandbox: sandboxProvider.name,\n Branch: resolvedBranch,\n });\n\n // 5. Create worktree (unless head mode)\n let worktreeInfo: WorktreeManager.WorktreeInfo | undefined;\n\n if (!isHeadMode) {\n worktreeInfo = yield* d.taskLog(\"Creating worktree\", () =>\n WorktreeManager.pruneStale(hostRepoDir).pipe(\n Effect.catchAll(() => Effect.void),\n Effect.andThen(\n branch !== undefined && branch !== \"\"\n ? WorktreeManager.create(hostRepoDir, { branch })\n : WorktreeManager.create(hostRepoDir, {\n name: options.name,\n tempBranch: resolvedBranch,\n }),\n ),\n ),\n );\n }\n // Where the agent works on the host: the worktree, or the repo itself in\n // head mode (the only mode without a worktree).\n const hostWorkPath = worktreeInfo?.path ?? hostRepoDir;\n const copyPaths = options.copyToWorktree;\n const onWorktreeReady = hooks?.host?.onWorktreeReady ?? [];\n\n // 6. Prepare the worktree and start the sandbox. If any step fails after the\n // worktree exists (copying, hooks, or sandbox start), remove the worktree so\n // it is not orphaned on disk.\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n const handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle = yield* Effect.gen(function* () {\n if (!isHeadMode) {\n // Copy files to worktree (bind-mount and no-sandbox, non-head)\n if (\n (sandboxProvider.tag === \"bind-mount\" ||\n sandboxProvider.tag === \"none\") &&\n copyPaths &&\n copyPaths.length > 0\n ) {\n yield* d.taskLog(\"Copying files to worktree\", () =>\n copyToWorktree(\n copyPaths,\n hostRepoDir,\n hostWorkPath,\n options.timeouts?.copyToWorktreeMs,\n ),\n );\n }\n\n // Run host.onWorktreeReady hooks\n if (onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, hostWorkPath);\n }\n } else if (onWorktreeReady.length > 0) {\n // Head strategy: cwd is the host repo root\n yield* runHostHooks(onWorktreeReady, hostRepoDir);\n }\n\n // Start sandbox\n if (sandboxProvider.tag === \"none\") {\n // No-sandbox: run directly on the host, no container\n return yield* Effect.promise(async () =>\n sandboxProvider.create({\n worktreePath: hostWorkPath,\n env: effectiveEnv,\n }),\n );\n } else if (sandboxProvider.tag === \"isolated\") {\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: sandboxProvider,\n hostRepoDir: hostWorkPath,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n }),\n );\n return startResult.handle;\n }\n const gitPath = join(hostRepoDir, \".git\");\n const rawGitMounts = yield* resolveGitMounts(gitPath);\n const gitMounts = yield* patchGitMountsForWindows(\n rawGitMounts,\n hostWorkPath,\n SANDBOX_REPO_DIR,\n );\n mountsToClean.push(...gitMounts);\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: hostWorkPath,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n );\n return startResult.handle;\n }).pipe(\n Effect.tapError(() =>\n worktreeInfo\n ? WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n )\n : Effect.void,\n ),\n Effect.onError(() => removeMountTempDirs(mountsToClean)),\n );\n\n // Run lifecycle with guaranteed cleanup of handle and worktree\n return yield* Effect.gen(function* () {\n // Check interactiveExec is available (no-sandbox always has it; bind-mount/isolated it's optional)\n if (!handle.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn = handle.interactiveExec.bind(handle);\n\n // Build sandbox service and run withSandboxLifecycle\n const sandbox = makeSandboxFromHandle(handle);\n const { worktreePath } = handle;\n\n const applyToHost =\n sandboxProvider.tag === \"isolated\" && worktreeInfo\n ? () => syncOut(hostWorkPath, handle as IsolatedSandboxHandle)\n : () => Effect.void; // bind-mount and no-sandbox don't need sync\n\n const lifecycleEffect = withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: worktreePath,\n hooks,\n branch: lifecycleBranch,\n hostWorktreePath: isHeadMode ? hostRepoDir : worktreeInfo?.path,\n applyToHost,\n timeouts: options.timeouts,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n // Preprocess prompt (expand !`command` shell expressions inside sandbox).\n // Skip when no prompt source was provided, or when inline (literal passthrough).\n const fullPrompt =\n !hasPromptSource || isInlinePrompt\n ? substitutedPrompt\n : yield* preprocessPrompt(\n substitutedPrompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n );\n\n // Build interactive args and run the session\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: sandboxProvider.tag !== \"none\",\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(async () =>\n interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: worktreePath,\n }),\n ),\n options.signal,\n );\n\n return result.exitCode;\n }),\n );\n\n const lifecycleResult = yield* lifecycleEffect;\n\n const exitCode = lifecycleResult.result;\n\n // Check for uncommitted changes (worktree mode only)\n let preservedWorktreePath: string | undefined;\n if (worktreeInfo) {\n const hasUncommitted = yield* WorktreeManager.hasUncommittedChanges(\n worktreeInfo.path,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (hasUncommitted) {\n preservedWorktreePath = worktreeInfo.path;\n }\n }\n\n // Clean up worktree if not preserved\n if (worktreeInfo && preservedWorktreePath === undefined) {\n yield* WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n );\n }\n\n // Final summary\n yield* d.summary(\"Session Complete\", {\n Commits: String(lifecycleResult.commits.length),\n Branch: lifecycleResult.branch,\n \"Exit code\": String(exitCode),\n ...(preservedWorktreePath === undefined\n ? {}\n : { \"Preserved worktree\": preservedWorktreePath }),\n });\n\n return {\n commits: lifecycleResult.commits,\n branch: lifecycleResult.branch,\n preservedWorktreePath,\n exitCode,\n };\n }).pipe(\n // On error, always clean up worktree (on success, handled above with preserve check)\n Effect.tapError(() =>\n worktreeInfo\n ? WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n )\n : Effect.void,\n ),\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () => handle.close().catch(() => {})).pipe(\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n });\n\n let result: InteractiveResult;\n try {\n result = await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n options.signal?.throwIfAborted();\n throw error;\n }\n\n return result;\n};\n","import type { FileSystem } from \"@effect/platform\";\nimport { Effect } from \"effect\";\nimport type { Display } from \"./Display.js\";\nimport type { PromptError, WorktreeError } from \"./errors.js\";\nimport {\n BUILT_IN_PROMPT_ARG_KEYS,\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport { getCurrentBranch } from \"./WorktreeManager.js\";\n\n/** @internal Inputs for resolving a `sandbox.run()` / `sandbox.interactive()` prompt. */\nexport interface ResolveSandboxPromptOptions {\n readonly prompt: string | undefined;\n readonly promptFile: string | undefined;\n readonly promptArgs: PromptArgs | undefined;\n /** The sandbox's branch, exposed to templates as `SOURCE_BRANCH`. */\n readonly branch: string;\n /** Host repo whose current branch is exposed to templates as `TARGET_BRANCH`. */\n readonly hostRepoDir: string;\n}\n\n/** @internal A prompt ready for the agent, plus whether it was given inline. */\nexport interface ResolvedSandboxPrompt {\n readonly text: string;\n /** Inline prompts skip argument substitution and prompt expansion. */\n readonly isInline: boolean;\n}\n\n/**\n * @internal Resolves a long-lived sandbox's prompt: reads the prompt or\n * prompt file, then substitutes `{{KEY}}` arguments (with the built-in\n * `SOURCE_BRANCH` / `TARGET_BRANCH`) for templates. Inline prompts must not\n * carry arguments and are returned verbatim.\n */\nexport const resolveSandboxPrompt = (\n options: ResolveSandboxPromptOptions,\n): Effect.Effect<\n ResolvedSandboxPrompt,\n PromptError | WorktreeError,\n FileSystem.FileSystem | Display\n> =>\n Effect.gen(function* () {\n const resolved = yield* resolvePrompt({\n prompt: options.prompt,\n promptFile: options.promptFile,\n });\n const isInline = resolved.source === \"inline\";\n const userArgs = options.promptArgs ?? {};\n const currentHostBranch = yield* getCurrentBranch(options.hostRepoDir);\n\n if (isInline) {\n yield* validateNoArgsWithInlinePrompt(userArgs);\n return { text: resolved.text, isInline };\n }\n yield* validateNoBuiltInArgOverride(userArgs);\n const text = yield* substitutePromptArgs(\n resolved.text,\n {\n SOURCE_BRANCH: options.branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n },\n new Set<string>(BUILT_IN_PROMPT_ARG_KEYS),\n );\n return { text, isInline };\n });\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { Effect, Layer, Ref } from \"effect\";\nimport { shellEscape } from \"./AgentProvider.js\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport {\n ClackDisplay,\n Display,\n FileDisplay,\n SilentDisplay,\n} from \"./Display.js\";\nimport type { DisplayEntry } from \"./Display.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult } from \"./Orchestrator.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { resolveSandboxPrompt } from \"./resolveSandboxPrompt.js\";\nimport type { ResolvedSandboxPrompt } from \"./resolveSandboxPrompt.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport type { LoggingOption, Timeouts } from \"./run.js\";\nimport {\n buildAgentStreamHandler,\n buildCompletionMessage,\n buildContextWindowLines,\n buildLogFilename,\n printFileDisplayStartup,\n} from \"./run.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SyncError, SyncOutPathError } from \"./errors.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport {\n reuseSandboxFactoryLayer,\n SANDBOX_REPO_DIR,\n resolveGitMounts,\n} from \"./SandboxFactory.js\";\nimport type { MountEntry, SandboxService } from \"./SandboxFactory.js\";\nimport type {\n SandboxProvider,\n BindMountSandboxHandle,\n BindMountSandboxProvider,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n MergeToHeadBranchStrategy,\n NamedBranchStrategy,\n ExecResult,\n} from \"./SandboxProvider.js\";\nimport { execOk } from \"./sandboxSetup.js\";\nimport { startSandbox } from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport {\n assertForkSupported,\n assertResumeSessionExists,\n} from \"./resumePrecheck.js\";\nimport { registerShutdown } from \"./shutdownRegistry.js\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\nexport interface CreateSandboxOptions {\n /** Explicit branch for the worktree (required). */\n readonly branch: string;\n /**\n * Ref to fork from when `branch` does not yet exist. Ignored when the branch\n * already exists. Defaults to `HEAD`.\n */\n readonly baseBranch?: string;\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** @internal Test-only overrides to bypass the sandbox provider. */\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n /**\n * Fake bind-mount handle exposed to the orchestrator's session-capture path.\n * Only honored when `sandbox.tag === \"bind-mount\"`. Used to exercise the\n * `bindMountHandle` flow in tests without booting a real container.\n */\n readonly bindMountHandle?: BindMountSandboxHandle;\n };\n}\n\n/**\n * Options accepted by `SandboxRunResult.resume()` / `.fork()`. Mirrors\n * `ResumeRunResultOptions` in `run.ts` — drops the fields owned by the\n * captured run (prompt, iteration count, resumeSession/forkSession bookkeeping).\n *\n * Defined as the base interface that `SandboxRunOptions` extends — the\n * interface-extends shape is cheaper for the TS checker than\n * `Omit<SandboxRunOptions, ...>` (which forces a mapped-type computation\n * on every reference).\n */\nexport interface ResumeSandboxRunResultOptions {\n /** Key-value map for {{KEY}} placeholder substitution in prompts. */\n readonly promptArgs?: PromptArgs;\n /** Substring(s) the agent emits to stop the iteration loop early. */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. Default: 600. */\n readonly idleTimeoutSeconds?: number;\n /** Grace window in seconds after a completion signal is observed but the agent process has not exited. See ADR 0019. Default: 60. */\n readonly completionTimeoutSeconds?: number;\n /** Display name for this run. */\n readonly name?: string;\n /** Logging mode. */\n readonly logging?: LoggingOption;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - Pre-aborted signal rejects immediately without setup.\n * - Mid-iteration abort kills the in-flight agent subprocess.\n * - The rejected promise surfaces `signal.reason` verbatim.\n * - The `Sandbox` handle remains usable after abort — call `.run()` again\n * with a fresh signal, or `.close()` to tear down.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface SandboxRunOptions extends ResumeSandboxRunResultOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")). */\n readonly agent: AgentProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Maximum iterations to run (default: 1). */\n readonly maxIterations?: number;\n /** Resume a prior agent session by id. The session JSONL must exist on the host (captured by a prior `sandbox.run()`). Incompatible with `maxIterations > 1`. */\n readonly resumeSession?: string;\n /**\n * When true alongside `resumeSession`, fork the session instead of mutating\n * it. The parent session JSONL is left intact and the agent writes a new\n * session under a fresh id. Exposed as the public `.fork()` method on\n * `SandboxRunResult` rather than as a stand-alone caller option — see\n * ADR 0018.\n *\n * @internal\n */\n readonly forkSession?: boolean;\n}\n\nexport interface SandboxRunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run. */\n readonly commits: { sha: string }[];\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n /**\n * Continue the last captured agent session for exactly one iteration inside\n * the same long-lived sandbox. Present only when the provider supports\n * resume (`sessionStorage` populated) and a session id was captured.\n */\n readonly resume?: (\n prompt: string,\n options?: ResumeSandboxRunResultOptions,\n ) => Promise<SandboxRunResult>;\n /**\n * Fork the last captured agent session for exactly one iteration inside the\n * same long-lived sandbox: the parent session JSONL is left intact and the\n * child run gets its own session id. Present only when the provider\n * supports resume (`sessionStorage` populated) and a session id was\n * captured. See ADR 0018 for fork semantics.\n */\n readonly fork?: (\n prompt: string,\n options?: ResumeSandboxRunResultOptions,\n ) => Promise<SandboxRunResult>;\n}\n\nexport interface SandboxInteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")). */\n readonly agent: AgentProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Key-value map for {{KEY}} placeholder substitution in prompts. */\n readonly promptArgs?: PromptArgs;\n /** Display name for this interactive session. */\n readonly name?: string;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - Pre-aborted signal rejects immediately without setup.\n * - The rejected promise surfaces `signal.reason` verbatim.\n * - The `Sandbox` handle remains usable after abort.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface SandboxInteractiveResult {\n /** List of commits made during the interactive session. */\n readonly commits: { sha: string }[];\n /** Exit code of the interactive process. */\n readonly exitCode: number;\n}\n\nexport interface CloseResult {\n /** Host path to the preserved worktree, set when the worktree had uncommitted changes. */\n readonly preservedWorktreePath?: string;\n}\n\nexport interface Sandbox {\n /** The branch the worktree is on. */\n readonly branch: string;\n /** Host path to the worktree. */\n readonly worktreePath: string;\n /**\n * The provider's id for this sandbox, for a supervisor outside this process\n * (a run registry, a kill step for stuck runs) to address it with the\n * provider's own tools:\n *\n * - `docker()`: the container name: `docker inspect <sandboxId>`,\n * `docker rm -f <sandboxId>`.\n * - `podman()`: the container name: `podman inspect <sandboxId>`,\n * `podman rm -f <sandboxId>`.\n * - `vercel()`: the Vercel sandbox's id (its `name` from `@vercel/sandbox`\n * 2 on, its `sandboxId` in 1.x): pass it to the SDK's `Sandbox.get()`,\n * then call `stop()`.\n * - `daytona()`: the Daytona sandbox id: `daytona.get(<sandboxId>)`, then\n * `delete()`, from `@daytona/sdk`.\n * - `modal()`: the Modal sandbox id: `modal.sandboxes.fromId(<sandboxId>)`,\n * then `terminate()`, from `modal`.\n * - `sprites()`: the Sprite's name: `client.getSprite(<sandboxId>)`, then\n * `delete()`, from `@fly/sprites`.\n * - A custom provider: whatever its handle's `sandboxId` is.\n *\n * `undefined` for `noSandbox()` and the native `bwrap()` and `seatbelt()`\n * sandboxes: their sandbox is a child process of this one, with nothing\n * outside it to address.\n */\n readonly sandboxId?: string;\n /** Invoke an agent inside the existing sandbox. */\n run(options: SandboxRunOptions): Promise<SandboxRunResult>;\n /** Launch an interactive agent session inside the existing sandbox. */\n interactive(\n options: SandboxInteractiveOptions,\n ): Promise<SandboxInteractiveResult>;\n /**\n * Execute a command inside the existing sandbox.\n *\n * `cwd` defaults to the sandbox repo path (same default `interactive()`\n * uses), so callers get the same working directory across providers. Pass\n * `cwd` to override.\n *\n * Returns the full `ExecResult` — non-zero `exitCode` is surfaced, not\n * thrown. Callers that want strict semantics should check `result.exitCode`\n * themselves (matching the contract of `BindMountSandboxHandle.exec`).\n */\n exec(command: string, options?: SandboxExecOptions): Promise<ExecResult>;\n /** Tear down the sandbox and worktree. */\n close(): Promise<CloseResult>;\n /** Auto teardown via `await using`. */\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/** Options accepted by `Sandbox.exec()`. Mirrors the provider handle's `exec` options. */\nexport interface SandboxExecOptions {\n /** Per-line stdout callback for streaming output. */\n readonly onLine?: (line: string) => void;\n /** Working directory for the command. Defaults to the sandbox repo path. */\n readonly cwd?: string;\n /** Run the whole command as root, when the provider supports it. */\n readonly sudo?: boolean;\n /** Stdin payload — piped to the child process and then closed. Avoids the Linux 128 KB per-arg limit. */\n readonly stdin?: string;\n}\n\n/** @internal Context for building Sandbox handle methods. */\ninterface SandboxHandleContext {\n readonly branch: string;\n readonly worktreePath: string;\n readonly hostRepoDir: string;\n readonly sandboxRepoDir: string;\n readonly sandbox: SandboxService;\n readonly providerHandle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle\n | undefined;\n /**\n * Pre-narrowed bind-mount handle, set when the provider is a bind-mount\n * provider. Required by the orchestrator's session capture path\n * (`AgentSessionStorage.captureToHost/resumeIntoSandbox`), which is typed\n * on `BindMountSandboxHandle` and calls `copyFileOut`/`copyFileIn` —\n * methods that no-sandbox and isolated handles do not implement.\n */\n readonly bindMountHandle: BindMountSandboxHandle | undefined;\n /** Provider tag, used by resumeSession to dispatch the host-side session lookup. */\n readonly providerTag: SandboxProvider[\"tag\"];\n /** The sandbox provider, checked before an interactive session starts. */\n readonly sandboxProvider: SandboxProvider;\n /** The sandbox provider's env, checked against each run's agent env for overlapping keys. */\n readonly sandboxProviderEnv: Record<string, string>;\n readonly applyToHost: () => Effect.Effect<void, SyncError | SyncOutPathError>;\n readonly timeouts?: Timeouts;\n /** Worktree branch strategy. Set only when the handle is backed by a\n * `createWorktree(...)` handle; absent for top-level `createSandbox()`,\n * which is always explicit-branch. When `type === \"merge-to-head\"`, each\n * run()/interactive() routes through the lifecycle's merge step and the\n * worktree's source branch is preserved across calls. */\n readonly branchStrategy?: MergeToHeadBranchStrategy | NamedBranchStrategy;\n}\n\n/**\n * @internal Applies an agent provider's `env` to its print command.\n *\n * `run()` merges the agent's env into the container env at start. A\n * long-lived sandbox (`createSandbox()`, `worktree.createSandbox()`) is\n * started before any agent is chosen, and each `sandbox.run()` may use a\n * different agent, so the env is exported in the agent's own shell instead.\n * It reaches only that run's agent process, with the same precedence as\n * `run()` (agent env overrides `.sandcastle/.env`) and the same rejection of\n * keys that overlap the sandbox provider's env.\n */\nconst withAgentEnv = (\n agent: AgentProvider,\n sandboxProviderEnv: Record<string, string>,\n): AgentProvider => {\n const entries = Object.entries(agent.env);\n if (entries.length === 0) {\n return agent;\n }\n mergeProviderEnv({\n resolvedEnv: {},\n agentProviderEnv: agent.env,\n sandboxProviderEnv,\n });\n const invalid = entries\n .map(([key]) => key)\n .filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));\n if (invalid.length > 0) {\n throw new Error(\n `Invalid agent provider env key(s): ${invalid.join(\", \")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`,\n );\n }\n const exports = entries\n .map(([key, value]) => `export ${key}=${shellEscape(value)}; `)\n .join(\"\");\n return {\n ...agent,\n buildPrintCommand: (options) => {\n const printCommand = agent.buildPrintCommand(options);\n return { ...printCommand, command: exports + printCommand.command };\n },\n };\n};\n\n/**\n * @internal Rejects run options that can't work before any setup happens:\n * bad timeouts, `resumeSession` with more than one iteration, `forkSession`\n * without `resumeSession` or on an agent that can't fork, and a\n * `resumeSession` whose file is missing on the host.\n */\nconst assertRunOptionsValid = async (\n runOptions: SandboxRunOptions,\n provider: AgentProvider,\n ctx: SandboxHandleContext,\n): Promise<void> => {\n validateTimeoutOptions(runOptions);\n\n const isResuming =\n runOptions.resumeSession !== undefined && runOptions.resumeSession !== \"\";\n\n // Validate: resumeSession + maxIterations > 1 is not allowed.\n if (isResuming && (runOptions.maxIterations ?? 1) > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n // Validate: forkSession only makes sense alongside resumeSession.\n if (runOptions.forkSession === true && !isResuming) {\n throw new Error(\n \"forkSession requires resumeSession. \" +\n \"Use sandboxRunResult.fork(prompt) to fork the most recent captured session.\",\n );\n }\n if (runOptions.forkSession === true) {\n assertForkSupported(provider);\n }\n\n // Validate: resumeSession file must exist on the host before launching.\n if (isResuming) {\n await assertResumeSessionExists({\n provider,\n sandboxTag: ctx.providerTag,\n hostRepoDir: ctx.hostRepoDir,\n resumeSession: runOptions.resumeSession,\n });\n }\n};\n\n/** @internal A run's logging option; defaults to a file under `.sandcastle/logs/`. */\nconst resolveRunLogging = (\n runOptions: SandboxRunOptions,\n hostRepoDir: string,\n branch: string,\n): LoggingOption =>\n runOptions.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(branch, undefined, runOptions.name),\n ),\n };\n\n/**\n * @internal The display for a run: file logging prints the startup banner\n * and writes to the log file; stdout logging renders to the terminal, as\n * run() does.\n */\nconst buildRunDisplayLayer = (\n logging: LoggingOption,\n banner: { readonly agentName: string | undefined; readonly branch: string },\n): Layer.Layer<Display> => {\n if (logging.type !== \"file\") {\n return ClackDisplay.layer;\n }\n printFileDisplayStartup({ logPath: logging.path, ...banner });\n return Layer.provide(FileDisplay.layer(logging.path), NodeFileSystem.layer);\n};\n\n/**\n * @internal Adds `.resume()` / `.fork()` to a run result, only when the\n * agent supports session capture and the last iteration captured a session\n * id. Both re-enter the same long-lived sandbox through `rerun`, which\n * repeats the original run's options with the given overrides, so the\n * container and worktree stay warm.\n */\nconst withResumeAndFork = (\n baseResult: SandboxRunResult,\n provider: AgentProvider,\n rerun: (overrides: Partial<SandboxRunOptions>) => Promise<SandboxRunResult>,\n): SandboxRunResult => {\n const lastIteration = baseResult.iterations.at(-1);\n if (\n !provider.sessionStorage ||\n lastIteration?.sessionId === undefined ||\n lastIteration.sessionId === \"\"\n ) {\n return baseResult;\n }\n const capturedSessionId = lastIteration.sessionId;\n return {\n ...baseResult,\n resume: async (\n nextPrompt: string,\n resumeOptions?: ResumeSandboxRunResultOptions,\n ): Promise<SandboxRunResult> =>\n rerun({\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n ...resumeOptions,\n prompt: nextPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: capturedSessionId,\n }),\n fork: async (\n nextPrompt: string,\n forkOptions?: ResumeSandboxRunResultOptions,\n ): Promise<SandboxRunResult> =>\n rerun({\n // The follow-up prompt is inline: drop the template's arguments.\n promptArgs: undefined,\n ...forkOptions,\n prompt: nextPrompt,\n promptFile: undefined,\n maxIterations: 1,\n resumeSession: capturedSessionId,\n forkSession: true,\n }),\n };\n};\n\n/** @internal Resolves a run's prompt, with prompt-file reads kept off the terminal. */\nconst resolveRunPrompt = (\n ctx: SandboxHandleContext,\n runOptions: SandboxRunOptions,\n): Promise<ResolvedSandboxPrompt> => {\n const displayRef = Ref.unsafeMake<readonly DisplayEntry[]>([]);\n const silentDisplayLayer = SilentDisplay.layer(displayRef);\n return Effect.runPromise(\n resolveSandboxPrompt({\n prompt: runOptions.prompt,\n promptFile: runOptions.promptFile,\n promptArgs: runOptions.promptArgs,\n branch: ctx.branch,\n hostRepoDir: ctx.hostRepoDir,\n }).pipe(\n Effect.provide(Layer.mergeAll(NodeContext.layer, silentDisplayLayer)),\n ),\n );\n};\n\n/**\n * @internal The layers a run needs: its display, a SandboxFactory that reuses\n * this handle's sandbox, and the agent stream emitter.\n */\nconst buildRunLayer = (\n ctx: SandboxHandleContext,\n runOptions: SandboxRunOptions,\n resolvedLogging: LoggingOption,\n) => {\n const runDisplayLayer = buildRunDisplayLayer(resolvedLogging, {\n agentName: runOptions.name,\n branch: ctx.branch,\n });\n\n const reuseFactoryLayer = reuseSandboxFactoryLayer(\n {\n hostWorktreePath: ctx.worktreePath,\n sandboxRepoPath: ctx.sandboxRepoDir,\n applyToHost: ctx.applyToHost,\n bindMountHandle: ctx.bindMountHandle,\n },\n ctx.sandbox,\n );\n\n const streamEmitterLayer = agentStreamEmitterLayer(\n buildAgentStreamHandler(resolvedLogging),\n );\n\n return Layer.mergeAll(reuseFactoryLayer, runDisplayLayer, streamEmitterLayer);\n};\n\n/**\n * @internal Orchestrates a run on this handle's sandbox and reports it: the\n * intro, the completion status and the context-window lines.\n */\nconst orchestrateOnSandbox = (\n ctx: SandboxHandleContext,\n runOptions: SandboxRunOptions,\n {\n provider,\n resolvedPrompt,\n }: {\n readonly provider: AgentProvider;\n readonly resolvedPrompt: ResolvedSandboxPrompt;\n },\n) =>\n Effect.gen(function* () {\n // In merge-to-head mode the lifecycle gets `branch: undefined` and keeps\n // the worktree's source branch alive (see buildSandboxHandle).\n const mergeToHead = ctx.branchStrategy?.type === \"merge-to-head\";\n const display = yield* Display;\n yield* display.intro(runOptions.name ?? \"sandcastle\");\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir: ctx.hostRepoDir,\n iterations: runOptions.maxIterations ?? 1,\n prompt: resolvedPrompt.text,\n branch: mergeToHead ? undefined : ctx.branch,\n provider,\n completionSignal: runOptions.completionSignal,\n idleTimeoutSeconds: runOptions.idleTimeoutSeconds,\n completionTimeoutSeconds: runOptions.completionTimeoutSeconds,\n name: runOptions.name,\n resumeSession: runOptions.resumeSession,\n forkSession: runOptions.forkSession,\n signal: runOptions.signal,\n skipPromptExpansion: resolvedPrompt.isInline,\n timeouts: ctx.timeouts,\n keepSourceBranch: mergeToHead,\n });\n\n const completion = buildCompletionMessage(\n orchestrateResult.completionSignal,\n orchestrateResult.iterations.length,\n );\n yield* display.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(orchestrateResult.iterations)) {\n yield* display.text(line);\n }\n\n return orchestrateResult;\n });\n\n/**\n * @internal A Sandbox handle's run(). `rerun` re-enters the same handle, for\n * the result's `.resume()` / `.fork()`.\n */\nconst runOnSandbox = async (\n ctx: SandboxHandleContext,\n runOptions: SandboxRunOptions,\n rerun: (options: SandboxRunOptions) => Promise<SandboxRunResult>,\n): Promise<SandboxRunResult> => {\n // If signal is already aborted, reject immediately without any setup\n runOptions.signal?.throwIfAborted();\n\n // The container was started before this agent was chosen, so the\n // agent's env is applied to its own process instead (see withAgentEnv).\n const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);\n\n await assertRunOptionsValid(runOptions, provider, ctx);\n\n const resolvedPrompt = await resolveRunPrompt(ctx, runOptions);\n const resolvedLogging = resolveRunLogging(\n runOptions,\n ctx.hostRepoDir,\n ctx.branch,\n );\n const runLayer = buildRunLayer(ctx, runOptions, resolvedLogging);\n\n let result;\n try {\n result = await Effect.runPromise(\n orchestrateOnSandbox(ctx, runOptions, { provider, resolvedPrompt }).pipe(\n Effect.provide(runLayer),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim\n runOptions.signal?.throwIfAborted();\n throw error;\n }\n\n return withResumeAndFork(\n {\n iterations: result.iterations,\n completionSignal: result.completionSignal,\n stdout: result.stdout,\n commits: result.commits,\n logFilePath:\n resolvedLogging.type === \"file\" ? resolvedLogging.path : undefined,\n },\n provider,\n async (overrides) => rerun({ ...runOptions, ...overrides }),\n );\n};\n\n/**\n * @internal Builds a Sandbox handle with run() and interactive() methods.\n * The close callback controls teardown behavior — top-level createSandbox()\n * cleans up both container and worktree, while worktree-backed sandboxes\n * only tear down the container.\n */\nconst buildSandboxHandle = (\n ctx: SandboxHandleContext,\n close: () => Promise<CloseResult>,\n): Sandbox => {\n const {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n providerHandle,\n applyToHost,\n timeouts,\n branchStrategy,\n } = ctx;\n // Routing for the lifecycle: in merge-to-head mode pass `branch: undefined`\n // (so the lifecycle records host's current branch and merges back) and keep\n // the worktree's source branch alive for subsequent calls. In all other\n // cases (top-level createSandbox, named-branch worktree) forward `branch`\n // as-is and let the lifecycle delete the temp branch normally.\n const mergeToHead = branchStrategy?.type === \"merge-to-head\";\n\n const sandboxHandle: Sandbox = {\n branch,\n worktreePath,\n sandboxId:\n providerHandle !== undefined && \"sandboxId\" in providerHandle\n ? providerHandle.sandboxId\n : undefined,\n\n run: async (runOptions: SandboxRunOptions): Promise<SandboxRunResult> =>\n runOnSandbox(ctx, runOptions, async (options) =>\n sandboxHandle.run(options),\n ),\n\n interactive: async (\n interactiveOptions: SandboxInteractiveOptions,\n ): Promise<SandboxInteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n interactiveOptions.signal?.throwIfAborted();\n assertInteractiveSupported(ctx.sandboxProvider);\n\n const { agent: provider, prompt, promptFile } = interactiveOptions;\n\n const buildInteractiveArgs =\n provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n if (!providerHandle?.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn =\n providerHandle.interactiveExec.bind(providerHandle);\n\n let lifecycleResult;\n try {\n lifecycleResult = await Effect.runPromise(\n Effect.gen(function* () {\n const resolvedPrompt = yield* resolveSandboxPrompt({\n prompt,\n promptFile,\n promptArgs: interactiveOptions.promptArgs,\n branch,\n hostRepoDir,\n });\n\n return yield* withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir,\n branch: mergeToHead ? undefined : branch,\n hostWorktreePath: worktreePath,\n applyToHost,\n timeouts,\n keepSourceBranch: mergeToHead,\n },\n sandbox,\n (sandboxCtx) =>\n Effect.gen(function* () {\n const fullPrompt = resolvedPrompt.isInline\n ? resolvedPrompt.text\n : yield* preprocessPrompt(\n resolvedPrompt.text,\n sandboxCtx.sandbox,\n sandboxCtx.sandboxRepoDir,\n );\n\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: true,\n });\n const execPromise = interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: sandboxRepoDir,\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(() => execPromise),\n interactiveOptions.signal,\n );\n\n return result.exitCode;\n }),\n );\n }).pipe(\n Effect.provide(\n Layer.mergeAll(ClackDisplay.layer, NodeContext.layer),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim\n interactiveOptions.signal?.throwIfAborted();\n throw error;\n }\n\n return {\n commits: lifecycleResult.commits,\n exitCode: lifecycleResult.result,\n };\n },\n\n exec: async (\n command: string,\n options?: SandboxExecOptions,\n ): Promise<ExecResult> => {\n const mergedOptions = { cwd: sandboxRepoDir, ...options };\n if (providerHandle) {\n return providerHandle.exec(command, mergedOptions);\n }\n // Test-mode fallback: no providerHandle, only the Effect SandboxService.\n return Effect.runPromise(sandbox.exec(command, mergedOptions));\n },\n\n close: async (): Promise<CloseResult> => close(),\n\n [Symbol.asyncDispose]: async (): Promise<void> => {\n await sandboxHandle.close();\n },\n };\n\n return sandboxHandle;\n};\n\n/** @internal Options for createSandboxFromWorktree — used by worktree.createSandbox(). */\nexport interface CreateSandboxFromWorktreeOptions {\n readonly branch: string;\n readonly worktreePath: string;\n readonly hostRepoDir: string;\n readonly sandbox: SandboxProvider;\n readonly hooks?: SandboxHooks;\n readonly copyToWorktree?: string[];\n readonly timeouts?: Timeouts;\n /** Forwarded to the Sandbox handle. Set by `createWorktree` so the handle\n * can route run()/interactive() correctly: for `merge-to-head`, each call\n * merges back to the host's current branch and the worktree's source\n * branch is preserved; for `branch`, the lifecycle is driven as\n * explicit-branch mode. Absent for top-level `createSandbox()`. */\n readonly branchStrategy?: MergeToHeadBranchStrategy | NamedBranchStrategy;\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n /**\n * Fake bind-mount handle exposed to the orchestrator's session-capture path.\n * Only honored when `sandbox.tag === \"bind-mount\"`.\n */\n readonly bindMountHandle?: BindMountSandboxHandle;\n };\n}\n\ntype ProviderHandle =\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n\ninterface StartProviderSandboxOptions {\n readonly provider: SandboxProvider;\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly env: Record<string, string>;\n readonly copyToWorktree: string[] | undefined;\n /** Temp dirs behind the git mounts get pushed here, for the caller to remove. */\n readonly mountsToClean: MountEntry[];\n}\n\n/**\n * Starts a bind-mount provider's sandbox on `worktreePath`, after resolving\n * the host repo's git mounts and patching them for Windows.\n */\nconst startBindMountWithGitMounts = (\n provider: BindMountSandboxProvider,\n {\n hostRepoDir,\n worktreePath,\n env,\n mountsToClean,\n }: StartProviderSandboxOptions,\n) =>\n resolveGitMounts(join(hostRepoDir, \".git\")).pipe(\n Effect.provide(NodeFileSystem.layer),\n Effect.catchAll(() => Effect.succeed([])),\n // Patch git mounts for Windows worktree compatibility (ADR-0006)\n Effect.flatMap((gitMounts) =>\n patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR),\n ),\n Effect.tap((gitMounts) => {\n mountsToClean.push(...gitMounts);\n }),\n Effect.flatMap((gitMounts) =>\n startSandbox({\n provider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n ),\n );\n\n/** Starts `provider`'s sandbox on `worktreePath`, whatever its tag. */\nconst startProviderSandbox = (options: StartProviderSandboxOptions) => {\n const { provider, hostRepoDir, worktreePath, env } = options;\n if (provider.tag === \"isolated\") {\n return startSandbox({\n provider,\n hostRepoDir: worktreePath,\n env,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n });\n }\n if (provider.tag === \"none\") {\n return startSandbox({\n provider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n });\n }\n return startBindMountWithGitMounts(provider, options);\n};\n\n/**\n * Copies `copyToWorktree` paths from the host repo into the worktree.\n * Isolated providers skip this: startSandbox copies their paths in.\n */\nconst copyIntoWorktree = (\n options: Pick<\n CreateSandboxOptions,\n \"copyToWorktree\" | \"sandbox\" | \"timeouts\"\n >,\n hostRepoDir: string,\n worktreePath: string,\n) =>\n options.copyToWorktree &&\n options.copyToWorktree.length > 0 &&\n options.sandbox.tag !== \"isolated\"\n ? copyToWorktree(\n options.copyToWorktree,\n hostRepoDir,\n worktreePath,\n options.timeouts?.copyToWorktreeMs,\n )\n : Effect.void;\n\n/** The `buildSandboxHandle` fields that come from the provider and its handle. */\nconst providerHandleFields = (\n provider: SandboxProvider,\n providerHandle: ProviderHandle | undefined,\n worktreePath: string,\n) => ({\n providerHandle,\n // Pre-narrow the bind-mount handle for the orchestrator's session-capture\n // path. Gating on the provider tag avoids handing a NoSandbox/Isolated\n // handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage and\n // turning a missing-feature into a runtime SessionCaptureError.\n bindMountHandle:\n provider.tag === \"bind-mount\"\n ? (providerHandle as BindMountSandboxHandle | undefined)\n : undefined,\n providerTag: provider.tag,\n sandboxProvider: provider,\n sandboxProviderEnv: provider.env,\n // Syncs an isolated sandbox's changes back to the host worktree.\n applyToHost:\n provider.tag === \"isolated\" && providerHandle\n ? () => syncOut(worktreePath, providerHandle as IsolatedSandboxHandle)\n : () => Effect.void,\n});\n\n/**\n * Starts the sandbox on `worktreePath`: the provider's, or the local sandbox\n * layer in test mode.\n */\nconst startSandboxOnWorktree = ({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n}: {\n readonly options: Pick<\n CreateSandboxOptions,\n \"sandbox\" | \"_test\" | \"copyToWorktree\"\n >;\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly mountsToClean: MountEntry[];\n}) =>\n Effect.gen(function* () {\n if (options._test?.buildSandbox) {\n return {\n sandbox: options._test.buildSandbox(worktreePath),\n sandboxRepoDir: worktreePath,\n providerHandle: options._test.bindMountHandle,\n };\n }\n const resolvedEnv = yield* resolveEnv(hostRepoDir);\n const env = mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: {},\n sandboxProviderEnv: options.sandbox.env,\n });\n const startResult = yield* startProviderSandbox({\n provider: options.sandbox,\n hostRepoDir,\n worktreePath,\n env,\n copyToWorktree: options.copyToWorktree,\n mountsToClean,\n });\n return {\n providerHandle: startResult.handle,\n sandbox: startResult.sandbox,\n sandboxRepoDir: startResult.worktreePath,\n };\n });\n\n/**\n * Runs the onSandboxReady hooks, sandbox-side and host-side in parallel,\n * after marking the sandbox repo a git safe.directory. A no-op without hooks.\n */\nconst runOnSandboxReadyHooks = ({\n sandbox,\n sandboxRepoDir,\n worktreePath,\n hooks,\n}: {\n readonly sandbox: SandboxService;\n readonly sandboxRepoDir: string;\n readonly worktreePath: string;\n readonly hooks: SandboxHooks | undefined;\n}) => {\n const sandboxOnReady = hooks?.sandbox?.onSandboxReady ?? [];\n const hostOnReady = hooks?.host?.onSandboxReady ?? [];\n if (sandboxOnReady.length === 0 && hostOnReady.length === 0) {\n return Effect.void;\n }\n return Effect.gen(function* () {\n yield* sandbox.exec(\n `git config --global --add safe.directory \"${sandboxRepoDir}\"`,\n );\n const sandboxEffects = sandboxOnReady.map((hook) =>\n execOk(sandbox, hook.command, {\n cwd: sandboxRepoDir,\n sudo: hook.sudo,\n }),\n );\n const allEffects = [\n ...sandboxEffects,\n ...(hostOnReady.length > 0\n ? [runHostHooks(hostOnReady, worktreePath)]\n : []),\n ];\n yield* Effect.all(allEffects, { concurrency: \"unbounded\" });\n });\n};\n\n/**\n * Tears down a sandbox whose setup failed after it started: closes the\n * container, ignoring close errors, and removes its mount temp dirs.\n */\nconst tearDownStartedSandbox = (\n providerHandle: ProviderHandle | undefined,\n mountsToClean: readonly MountEntry[],\n): Effect.Effect<void> =>\n (providerHandle\n ? Effect.promise(() => providerHandle.close().catch(() => undefined))\n : Effect.void\n ).pipe(Effect.andThen(removeMountTempDirs(mountsToClean)));\n\n/** A close() that tears down the container only, once, and its mount temp dirs. */\nconst closeContainerOnly = (\n providerHandle: ProviderHandle | undefined,\n mountsToClean: readonly MountEntry[],\n): (() => Promise<CloseResult>) => {\n let closed = false;\n return async () => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n if (providerHandle) {\n await providerHandle.close();\n }\n await Effect.runPromise(removeMountTempDirs(mountsToClean));\n return { preservedWorktreePath: undefined };\n };\n};\n\n/**\n * Starts the sandbox on an existing worktree (provider or local sandbox layer\n * in test mode), then runs the onSandboxReady hooks, sandbox-side and\n * host-side in parallel. If the start fails, removes the mount temp dirs; if\n * the hooks fail, tears down the container that just started. The worktree\n * stays either way.\n */\nconst startSandboxWithReadyHooks = (\n options: CreateSandboxFromWorktreeOptions,\n mountsToClean: MountEntry[],\n) =>\n Effect.gen(function* () {\n const { hostRepoDir, worktreePath } = options;\n const started = yield* startSandboxOnWorktree({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n }).pipe(\n Effect.onError(() => removeMountTempDirs(mountsToClean)),\n Effect.provide(NodeContext.layer),\n );\n yield* runOnSandboxReadyHooks({\n sandbox: started.sandbox,\n sandboxRepoDir: started.sandboxRepoDir,\n worktreePath,\n hooks: options.hooks,\n }).pipe(\n Effect.onError(() =>\n tearDownStartedSandbox(started.providerHandle, mountsToClean),\n ),\n );\n return started;\n });\n\n/**\n * @internal Creates a sandbox backed by an existing worktree.\n * Split ownership: close() tears down the container only, leaving the worktree intact.\n * Used by Worktree.createSandbox().\n */\nexport const createSandboxFromWorktree = async (\n options: CreateSandboxFromWorktreeOptions,\n): Promise<Sandbox> => {\n const { branch, worktreePath, hostRepoDir } = options;\n validateTimeoutOptions(options);\n\n // 1. Copy files if requested (bind-mount only)\n await Effect.runPromise(copyIntoWorktree(options, hostRepoDir, worktreePath));\n\n // 2. Start the sandbox and run its onSandboxReady hooks.\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n const { providerHandle, sandbox, sandboxRepoDir } = await Effect.runPromise(\n startSandboxWithReadyHooks(options, mountsToClean),\n );\n\n // 3. Build and return sandbox handle — container-only close (worktree owns worktree)\n return buildSandboxHandle(\n {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n ...providerHandleFields(options.sandbox, providerHandle, worktreePath),\n timeouts: options.timeouts,\n branchStrategy: options.branchStrategy,\n },\n closeContainerOnly(providerHandle, mountsToClean),\n );\n};\n\n/**\n * @internal Copies files into the new worktree, runs host `onWorktreeReady`\n * hooks, starts the sandbox, then runs `onSandboxReady` hooks. If those\n * hooks fail, the sandbox that just started is torn down.\n */\nconst prepareSandboxOnWorktree = (\n options: CreateSandboxOptions,\n target: {\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly mountsToClean: MountEntry[];\n },\n) =>\n Effect.gen(function* () {\n const { hostRepoDir, worktreePath, mountsToClean } = target;\n // Copy files (bind-mount/no-sandbox only; isolated copies in startSandbox).\n yield* copyIntoWorktree(options, hostRepoDir, worktreePath);\n\n // Run host.onWorktreeReady hooks (after copy, before sandbox creation).\n const onWorktreeReady = options.hooks?.host?.onWorktreeReady;\n if (onWorktreeReady !== undefined && onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, worktreePath);\n }\n\n // Start the sandbox via the test layer or the shared startSandbox helper.\n const { providerHandle, sandbox, sandboxRepoDir } =\n yield* startSandboxOnWorktree({\n options,\n hostRepoDir,\n worktreePath,\n mountsToClean,\n });\n\n // Run onSandboxReady hooks (sandbox-side and host-side in parallel). If\n // they fail, tear down the container that just started before the outer\n // handler removes the worktree.\n yield* runOnSandboxReadyHooks({\n sandbox,\n sandboxRepoDir,\n worktreePath,\n hooks: options.hooks,\n }).pipe(\n Effect.onError(() =>\n tearDownStartedSandbox(providerHandle, mountsToClean),\n ),\n );\n\n return { providerHandle, sandbox, sandboxRepoDir };\n });\n\n/**\n * @internal Resolves the host repo, creates the worktree on `options.branch`\n * and prepares the sandbox on it. Once the worktree exists, any later\n * failure (e.g. a missing image surfacing when the provider creates the\n * container) tears down the container — if it started — and removes the\n * worktree so it is not orphaned on disk.\n */\nconst setUpWorktreeSandbox = (\n options: CreateSandboxOptions,\n mountsToClean: MountEntry[],\n) =>\n Effect.gen(function* () {\n const hostRepoDir = yield* resolveCwd(options.cwd);\n\n yield* WorktreeManager.pruneStale(hostRepoDir).pipe(\n Effect.catchAll(() => Effect.void),\n );\n const { path: worktreePath } = yield* WorktreeManager.create(hostRepoDir, {\n branch: options.branch,\n baseBranch: options.baseBranch,\n });\n\n const prepared = yield* prepareSandboxOnWorktree(options, {\n hostRepoDir,\n worktreePath,\n mountsToClean,\n }).pipe(\n Effect.onError(() =>\n WorktreeManager.remove(worktreePath).pipe(\n Effect.catchAll(() => Effect.void),\n Effect.andThen(removeMountTempDirs(mountsToClean)),\n ),\n ),\n );\n\n return { hostRepoDir, worktreePath, ...prepared };\n });\n\n/** @internal Tells the user where a worktree left behind by a shutdown is. */\nconst printWorktreePreserved = (worktreePath: string): void => {\n console.error(`\\nWorktree preserved at ${worktreePath}`);\n console.error(` To review: cd ${worktreePath}`);\n console.error(` To clean up: git worktree remove --force ${worktreePath}`);\n};\n\n/**\n * @internal Closes a top-level `createSandbox()`: the container, the git\n * mounts' temp dirs, then the worktree unless it has uncommitted changes.\n */\nconst closeSandboxAndWorktree = (target: {\n readonly providerHandle: ProviderHandle | undefined;\n readonly mountsToClean: readonly MountEntry[];\n readonly worktreePath: string;\n}): Effect.Effect<CloseResult> =>\n Effect.gen(function* () {\n const { providerHandle, mountsToClean, worktreePath } = target;\n if (providerHandle) {\n yield* Effect.promise(() => providerHandle.close());\n }\n yield* removeMountTempDirs(mountsToClean);\n\n // Preserve the worktree when it has uncommitted changes; otherwise remove it.\n const isDirty = yield* WorktreeManager.hasUncommittedChanges(\n worktreePath,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n if (isDirty) {\n return { preservedWorktreePath: worktreePath };\n }\n\n yield* WorktreeManager.remove(worktreePath).pipe(\n Effect.catchAll(() => Effect.void),\n );\n return { preservedWorktreePath: undefined };\n });\n\n/**\n * Eagerly creates a git worktree on the provided explicit branch and starts\n * a sandbox with the worktree bind-mounted. Returns a Sandbox handle that\n * can be reused across multiple `run()` calls.\n */\nexport const createSandbox = async (\n options: CreateSandboxOptions,\n): Promise<Sandbox> => {\n const { branch } = options;\n validateTimeoutOptions(options);\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n\n // Resolve cwd, create the worktree, and set up the sandbox in a single Effect.\n const { hostRepoDir, worktreePath, providerHandle, sandbox, sandboxRepoDir } =\n await Effect.runPromise(\n setUpWorktreeSandbox(options, mountsToClean).pipe(\n Effect.provide(NodeContext.layer),\n ),\n );\n\n // Route cleanup through the shared registry so concurrent sandboxes share one\n // SIGINT/SIGTERM/exit listener instead of tripping MaxListenersExceededWarning.\n const unregisterShutdown = registerShutdown(() => {\n printWorktreePreserved(worktreePath);\n });\n\n let closed = false;\n const doClose = async (): Promise<CloseResult> => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n return Effect.runPromise(\n closeSandboxAndWorktree({ providerHandle, mountsToClean, worktreePath }),\n );\n };\n\n return buildSandboxHandle(\n {\n branch,\n worktreePath,\n hostRepoDir,\n sandboxRepoDir,\n sandbox,\n // applyToHost is built once, reused across runs.\n ...providerHandleFields(options.sandbox, providerHandle, worktreePath),\n timeouts: options.timeouts,\n },\n async () => {\n unregisterShutdown();\n return doClose();\n },\n );\n};\n","import { NodeContext, NodeFileSystem } from \"@effect/platform-node\";\nimport { join } from \"node:path\";\nimport { assertInteractiveSupported } from \"./nativeSandboxProvider.js\";\nimport { Effect, Layer } from \"effect\";\nimport type { AgentProvider } from \"./AgentProvider.js\";\nimport { ClackDisplay, Display, FileDisplay } from \"./Display.js\";\nimport { preprocessPrompt } from \"./PromptPreprocessor.js\";\nimport { resolvePrompt } from \"./PromptResolver.js\";\nimport type { ResolvedPrompt } from \"./PromptResolver.js\";\nimport {\n reuseSandboxFactoryLayer,\n makeSandboxFromHandle,\n resolveGitMounts,\n SANDBOX_REPO_DIR,\n} from \"./SandboxFactory.js\";\nimport type {\n MountEntry,\n SandboxInfo,\n SandboxService,\n} from \"./SandboxFactory.js\";\nimport { patchGitMountsForWindows, removeMountTempDirs } from \"./mountUtils.js\";\nimport { withSandboxLifecycle, runHostHooks } from \"./SandboxLifecycle.js\";\nimport type { SandboxHooks } from \"./SandboxLifecycle.js\";\nimport type {\n SandboxProvider,\n MergeToHeadBranchStrategy,\n NamedBranchStrategy,\n BindMountSandboxHandle,\n IsolatedSandboxHandle,\n NoSandboxHandle,\n} from \"./SandboxProvider.js\";\nimport type { CloseResult, Sandbox } from \"./createSandbox.js\";\nimport { createSandboxFromWorktree } from \"./createSandbox.js\";\nimport type { InteractiveResult } from \"./interactive.js\";\nimport {\n buildAgentStreamHandler,\n buildCompletionMessage,\n buildContextWindowLines,\n buildLogFilename,\n printFileDisplayStartup,\n} from \"./run.js\";\nimport type { LoggingOption, Timeouts } from \"./run.js\";\nimport { orchestrate } from \"./Orchestrator.js\";\nimport type { IterationResult } from \"./Orchestrator.js\";\nimport { agentStreamEmitterLayer } from \"./AgentStreamEmitter.js\";\nimport { resolveEnv } from \"./EnvResolver.js\";\nimport { mergeProviderEnv } from \"./mergeProviderEnv.js\";\nimport {\n startBindMountSandbox,\n startIsolatedSandbox,\n startSandbox,\n} from \"./startSandbox.js\";\nimport { syncOut } from \"./syncOut.js\";\nimport * as WorktreeManager from \"./WorktreeManager.js\";\nimport { copyToWorktree } from \"./CopyToWorktree.js\";\nimport { resolveCwd } from \"./resolveCwd.js\";\nimport { assertResumeSessionExists } from \"./resumePrecheck.js\";\nimport {\n substitutePromptArgs,\n validateNoArgsWithInlinePrompt,\n validateNoBuiltInArgOverride,\n BUILT_IN_PROMPT_ARG_KEYS,\n} from \"./PromptArgumentSubstitution.js\";\nimport type { PromptArgs } from \"./PromptArgumentSubstitution.js\";\nimport { noSandbox } from \"./sandboxes/no-sandbox.js\";\nimport { raceAbortSignal } from \"./raceAbortSignal.js\";\nimport { validateTimeoutOptions } from \"./validateTimeouts.js\";\n\n/** Branch strategies valid for createWorktree — head is excluded. */\nexport type WorktreeBranchStrategy =\n | MergeToHeadBranchStrategy\n | NamedBranchStrategy;\n\nexport interface CreateWorktreeOptions {\n /** Branch strategy — only 'branch' and 'merge-to-head' are allowed. */\n readonly branchStrategy: WorktreeBranchStrategy;\n /**\n * Host repo directory. Replaces `process.cwd()` as the anchor for\n * `.sandcastle/worktrees/`, `.sandcastle/.env`, and git operations.\n *\n * - Relative paths are resolved against `process.cwd()`.\n * - Absolute paths are used as-is.\n * - Defaults to `process.cwd()` when omitted.\n */\n readonly cwd?: string;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Lifecycle hooks grouped by execution location (host or sandbox).\n * Only `host.onWorktreeReady` is executed here — other hooks are passed through\n * to `run()`, `interactive()`, or `createSandbox()`. */\n readonly hooks?: SandboxHooks;\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n}\n\nexport interface WorktreeInteractiveOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker(), noSandbox()). Defaults to noSandbox(). */\n readonly sandbox?: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Optional name for the interactive session. */\n readonly name?: string;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /**\n * An `AbortSignal` that cancels the interactive session when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, rejects immediately.\n * - Aborting during an active session kills the agent subprocess.\n * - The worktree is preserved on disk after abort.\n * - The `Worktree` handle remains usable for subsequent operations.\n * - The rejected promise surfaces `signal.reason` via\n * `signal.throwIfAborted()` — no Sandcastle-specific wrapping.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface WorktreeRunOptions {\n /** Agent provider to use (e.g. claudeCode(\"claude-opus-4-8\")) */\n readonly agent: AgentProvider;\n /** Sandbox provider (e.g. docker()). Required — AFK agents should always be sandboxed. */\n readonly sandbox: SandboxProvider;\n /** Inline prompt string (mutually exclusive with promptFile). */\n readonly prompt?: string;\n /** Path to a prompt file (mutually exclusive with prompt). */\n readonly promptFile?: string;\n /** Key-value map for {{KEY}} placeholder substitution in prompts */\n readonly promptArgs?: PromptArgs;\n /** Maximum iterations to run (default: 1). */\n readonly maxIterations?: number;\n /** Substring(s) the agent emits to stop the iteration loop early. */\n readonly completionSignal?: string | string[];\n /** Idle timeout in seconds. Default: 600. */\n readonly idleTimeoutSeconds?: number;\n /** Grace window in seconds after a completion signal is observed but the agent process has not exited. See ADR 0019. Default: 60. */\n readonly completionTimeoutSeconds?: number;\n /** Optional name for the run. */\n readonly name?: string;\n /** Logging mode. */\n readonly logging?: LoggingOption;\n /** Hooks to run during sandbox lifecycle */\n readonly hooks?: SandboxHooks;\n /** Environment variables to inject into the sandbox. */\n readonly env?: Record<string, string>;\n /** Resume a prior Claude Code session by ID. The session JSONL must exist on the host. Incompatible with maxIterations > 1. */\n readonly resumeSession?: string;\n /**\n * An `AbortSignal` that cancels the run when aborted.\n *\n * - If `signal.aborted` is already `true` at entry, rejects immediately\n * without doing any setup work.\n * - Aborting mid-iteration kills the in-flight agent subprocess.\n * - The worktree is preserved on disk after abort.\n * - The `Worktree` handle remains usable for subsequent operations.\n */\n readonly signal?: AbortSignal;\n}\n\nexport interface WorktreeRunResult {\n /** Per-iteration results (use `iterations.length` for the count). */\n readonly iterations: IterationResult[];\n /** The matched completion signal string, or undefined if none fired. */\n readonly completionSignal?: string;\n /** Combined stdout output from all agent iterations. */\n readonly stdout: string;\n /** List of commits made by the agent during the run. */\n readonly commits: { sha: string }[];\n /** The branch name the agent worked on. */\n readonly branch: string;\n /** Path to the log file, if logging was drained to a file. */\n readonly logFilePath?: string;\n}\n\nexport interface WorktreeCreateSandboxOptions {\n /** Sandbox provider (e.g. docker({ imageName: \"sandcastle:myrepo\" })). */\n readonly sandbox: SandboxProvider;\n /** Lifecycle hooks grouped by execution location (host or sandbox). */\n readonly hooks?: SandboxHooks;\n /** Paths relative to the host repo root to copy into the worktree at creation time. */\n readonly copyToWorktree?: string[];\n /** Override default timeouts for built-in lifecycle steps. Unset keys keep their defaults. */\n readonly timeouts?: Timeouts;\n /** @internal Test-only overrides to bypass the sandbox provider. */\n readonly _test?: {\n readonly buildSandbox?: (sandboxDir: string) => SandboxService;\n };\n}\n\nexport interface Worktree {\n /** The branch the worktree is on. */\n readonly branch: string;\n /** Host path to the worktree (worktree). */\n readonly worktreePath: string;\n /** Run an AFK agent in this worktree with a required sandbox. */\n run(options: WorktreeRunOptions): Promise<WorktreeRunResult>;\n /** Run an interactive agent session in this worktree. */\n interactive(options: WorktreeInteractiveOptions): Promise<InteractiveResult>;\n /** Create a long-lived sandbox backed by this worktree's worktree. */\n createSandbox(options: WorktreeCreateSandboxOptions): Promise<Sandbox>;\n /** Clean up the worktree. Preserves worktree if dirty. */\n close(): Promise<CloseResult>;\n /** Auto cleanup via `await using`. */\n [Symbol.asyncDispose](): Promise<void>;\n}\n\n/**\n * @internal Substitutes `{{KEY}}` prompt arguments into a\n * `worktree.interactive()` template prompt, with the built-in\n * `SOURCE_BRANCH` / `TARGET_BRANCH`. An inline prompt must not carry\n * arguments and passes through; no prompt at all gives \"\".\n */\nconst substituteInteractivePromptArgs = (\n resolved: ResolvedPrompt | undefined,\n args: {\n readonly promptArgs: PromptArgs | undefined;\n readonly hostRepoDir: string;\n readonly sourceBranch: string;\n },\n) =>\n Effect.gen(function* () {\n const rawPrompt = resolved?.text ?? \"\";\n if (resolved?.source === \"inline\") {\n yield* validateNoArgsWithInlinePrompt(args.promptArgs ?? {});\n return rawPrompt;\n }\n if (resolved === undefined) {\n return rawPrompt;\n }\n const userArgs = args.promptArgs ?? {};\n yield* validateNoBuiltInArgOverride(userArgs);\n // TARGET_BRANCH is the host's active branch at run() time, matching\n // top-level run(): the branch merge-to-head merges back into.\n const currentHostBranch = yield* WorktreeManager.getCurrentBranch(\n args.hostRepoDir,\n );\n return yield* substitutePromptArgs(\n rawPrompt,\n {\n SOURCE_BRANCH: args.sourceBranch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n },\n new Set<string>(BUILT_IN_PROMPT_ARG_KEYS),\n );\n });\n\n/**\n * @internal The env for a worktree's sandbox: `.sandcastle/.env` merged with\n * the agent's and sandbox provider's env, then the caller's `overrides`.\n */\nconst resolveWorktreeEnv = (\n hostRepoDir: string,\n sources: {\n readonly agentProviderEnv: Record<string, string>;\n readonly sandboxProviderEnv: Record<string, string>;\n readonly overrides: Record<string, string> | undefined;\n },\n) =>\n resolveEnv(hostRepoDir).pipe(\n Effect.map((resolvedEnv) => ({\n ...mergeProviderEnv({\n resolvedEnv,\n agentProviderEnv: sources.agentProviderEnv,\n sandboxProviderEnv: sources.sandboxProviderEnv,\n }),\n ...sources.overrides,\n })),\n );\n\n/** @internal The host repo's git mounts, patched for a Windows worktree (ADR-0006). */\nconst resolveWorktreeGitMounts = (hostRepoDir: string, worktreePath: string) =>\n resolveGitMounts(join(hostRepoDir, \".git\")).pipe(\n Effect.flatMap((rawGitMounts) =>\n patchGitMountsForWindows(rawGitMounts, worktreePath, SANDBOX_REPO_DIR),\n ),\n );\n\n/**\n * @internal Starts the sandbox for `worktree.run()`. Returns its handle, the\n * repo dir inside it, the git mounts (bind-mount only) whose temp dirs must be\n * removed once the sandbox closes, and how the run reaches the host: an\n * isolated sandbox syncs its commits back to the host worktree, a bind-mount\n * one hands its handle to session capture.\n */\nconst startWorktreeRunSandbox = (\n sandboxProvider: SandboxProvider,\n target: {\n readonly hostRepoDir: string;\n readonly worktreePath: string;\n readonly env: Record<string, string>;\n readonly copyPaths: string[] | undefined;\n },\n) =>\n Effect.gen(function* () {\n const { hostRepoDir, worktreePath, env } = target;\n const noMounts: MountEntry[] = [];\n if (sandboxProvider.tag === \"isolated\") {\n const startResult = yield* startIsolatedSandbox({\n provider: sandboxProvider,\n hostRepoDir: worktreePath,\n env,\n copyPaths: target.copyPaths,\n copySourceDir: hostRepoDir,\n });\n const hostLink: HostLink = {\n applyToHost: () => syncOut(worktreePath, startResult.handle),\n };\n return { ...toStarted(startResult), gitMounts: noMounts, hostLink };\n }\n if (sandboxProvider.tag === \"none\") {\n const startResult = yield* startSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n });\n const hostLink: HostLink = {};\n return { ...toStarted(startResult), gitMounts: noMounts, hostLink };\n }\n const gitMounts = yield* resolveWorktreeGitMounts(\n hostRepoDir,\n worktreePath,\n );\n const startResult = yield* startBindMountSandbox({\n provider: sandboxProvider,\n hostRepoDir,\n env,\n worktreeOrRepoPath: worktreePath,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n });\n const hostLink: HostLink = { bindMountHandle: startResult.handle };\n return { ...toStarted(startResult), gitMounts, hostLink };\n });\n\n/**\n * @internal How a started sandbox reaches the host worktree: `applyToHost`\n * for an isolated sandbox, `bindMountHandle` (for session capture) for a\n * bind-mount one, neither for no sandbox.\n */\ntype HostLink = Pick<SandboxInfo, \"applyToHost\" | \"bindMountHandle\">;\n\n/** @internal `applyToHost` for a sandbox that shares the host worktree. */\nconst skipHostSync = () => Effect.void;\n\n/** @internal A started sandbox's handle and the repo dir inside it. */\nconst toStarted = (startResult: {\n readonly handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n readonly worktreePath: string;\n}): {\n readonly handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n readonly sandboxRepoDir: string;\n} => ({ handle: startResult.handle, sandboxRepoDir: startResult.worktreePath });\n\n/**\n * @internal A SandboxFactory layer that reuses a sandbox `worktree.run()`\n * already started, reaching the host through its `hostLink`.\n */\nconst reuseStartedSandboxLayer = (\n handle: BindMountSandboxHandle | IsolatedSandboxHandle | NoSandboxHandle,\n hostLink: HostLink,\n paths: {\n readonly hostWorktreePath: string;\n readonly sandboxRepoPath: string;\n },\n) =>\n reuseSandboxFactoryLayer(\n {\n ...paths,\n applyToHost: hostLink.applyToHost ?? skipHostSync,\n bindMountHandle: hostLink.bindMountHandle,\n },\n makeSandboxFromHandle(handle),\n );\n\n/**\n * @internal A `worktree.run()`'s logging (default: a file under\n * `.sandcastle/logs/`) and its display: file logging prints the startup\n * banner and writes to the log file, anything else uses the terminal.\n */\nconst resolveWorktreeRunDisplay = (\n opts: WorktreeRunOptions,\n hostRepoDir: string,\n branch: string,\n): {\n readonly resolvedLogging: LoggingOption;\n readonly runDisplayLayer: Layer.Layer<Display>;\n} => {\n const resolvedLogging: LoggingOption = opts.logging ?? {\n type: \"file\",\n path: join(\n hostRepoDir,\n \".sandcastle\",\n \"logs\",\n buildLogFilename(branch, undefined, opts.name),\n ),\n };\n if (resolvedLogging.type !== \"file\") {\n return { resolvedLogging, runDisplayLayer: ClackDisplay.layer };\n }\n printFileDisplayStartup({\n logPath: resolvedLogging.path,\n agentName: opts.name,\n branch,\n });\n return {\n resolvedLogging,\n runDisplayLayer: Layer.provide(\n FileDisplay.layer(resolvedLogging.path),\n NodeFileSystem.layer,\n ),\n };\n};\n\n/**\n * Creates a git worktree as an independent, first-class worktree.\n * Returns a Worktree handle with close() and [Symbol.asyncDispose]().\n *\n * Only accepts 'branch' and 'merge-to-head' strategies — 'head' is a\n * compile-time type error since head means no worktree.\n */\nexport const createWorktree = async (\n options: CreateWorktreeOptions,\n): Promise<Worktree> => {\n validateTimeoutOptions(options);\n\n const branch =\n options.branchStrategy.type === \"branch\"\n ? options.branchStrategy.branch\n : undefined;\n\n const baseBranch =\n options.branchStrategy.type === \"branch\"\n ? options.branchStrategy.baseBranch\n : undefined;\n\n // Captured for the worktree's run/interactive/createSandbox methods so they\n // can route the branch correctly into `SandboxLifecycle`: in `merge-to-head`\n // mode they pass `branch: undefined` (to trigger the merge step) plus\n // `keepSourceBranch: true` (so the worktree's source branch survives).\n const isMergeToHead = options.branchStrategy.type === \"merge-to-head\";\n\n const { hostRepoDir, worktreeInfo } = await Effect.gen(function* () {\n const repoDir = yield* resolveCwd(options.cwd);\n yield* WorktreeManager.pruneStale(repoDir).pipe(\n Effect.catchAll(() => Effect.void),\n );\n const info = yield* WorktreeManager.create(repoDir, {\n branch,\n baseBranch,\n });\n if (options.copyToWorktree && options.copyToWorktree.length > 0) {\n yield* copyToWorktree(\n options.copyToWorktree,\n repoDir,\n info.path,\n options.timeouts?.copyToWorktreeMs,\n );\n }\n // Run host.onWorktreeReady hooks after copyToWorktree, before sandbox creation\n const onWorktreeReady = options.hooks?.host?.onWorktreeReady;\n if (onWorktreeReady !== undefined && onWorktreeReady.length > 0) {\n yield* runHostHooks(onWorktreeReady, info.path);\n }\n return { hostRepoDir: repoDir, worktreeInfo: info };\n }).pipe(Effect.provide(NodeContext.layer), Effect.runPromise);\n\n let closed = false;\n\n const close = async (): Promise<CloseResult> => {\n if (closed) {\n return { preservedWorktreePath: undefined };\n }\n closed = true;\n\n return Effect.gen(function* () {\n const isDirty = yield* WorktreeManager.hasUncommittedChanges(\n worktreeInfo.path,\n ).pipe(Effect.catchAll(() => Effect.succeed(false)));\n\n if (isDirty) {\n return { preservedWorktreePath: worktreeInfo.path };\n }\n\n yield* WorktreeManager.remove(worktreeInfo.path).pipe(\n Effect.catchAll(() => Effect.void),\n );\n\n // merge-to-head: the temp branch only outlives each wt.run() so the\n // handle can be reused. Once the handle is closed, delete it, unless it\n // holds commits that never reached another branch (e.g. a failed merge).\n if (isMergeToHead) {\n yield* WorktreeManager.deleteTempBranchIfUnused(\n hostRepoDir,\n worktreeInfo.branch,\n ).pipe(Effect.catchAll(() => Effect.void));\n }\n\n return { preservedWorktreePath: undefined };\n }).pipe(Effect.runPromise);\n };\n\n const worktreeInteractive = async (\n opts: WorktreeInteractiveOptions,\n ): Promise<InteractiveResult> => {\n // If signal is already aborted, reject immediately without any setup\n opts.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = opts;\n const resolvedSandbox = opts.sandbox ?? noSandbox();\n assertInteractiveSupported(resolvedSandbox);\n\n // Validate buildInteractiveArgs is available\n const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);\n if (!buildInteractiveArgs) {\n throw new Error(\n `Agent provider \"${provider.name}\" does not support buildInteractiveArgs, required for interactive sessions.`,\n );\n }\n\n const inner = Effect.gen(function* () {\n const d = yield* Display;\n\n // 1. Resolve prompt (from string or file), or skip if neither provided\n const resolved =\n prompt !== undefined || promptFile !== undefined\n ? yield* resolvePrompt({ prompt, promptFile })\n : undefined;\n\n // 2. Resolve env vars\n const effectiveEnv = yield* resolveWorktreeEnv(hostRepoDir, {\n agentProviderEnv: provider.env,\n sandboxProviderEnv: resolvedSandbox.env,\n overrides: opts.env,\n });\n\n // 3. Prompt args substitution (skip when no prompt, or when inline passthrough)\n const substitutedPrompt = yield* substituteInteractivePromptArgs(\n resolved,\n {\n promptArgs: opts.promptArgs,\n hostRepoDir,\n sourceBranch: worktreeInfo.branch,\n },\n );\n\n // Display intro\n yield* d.intro(opts.name ?? \"sandcastle interactive\");\n yield* d.summary(\"Interactive Session\", {\n Agent: opts.name ?? provider.name,\n Sandbox: resolvedSandbox.name,\n Branch: worktreeInfo.branch,\n });\n\n // 4. Start sandbox\n // Temp dirs behind the git mounts, removed once the sandbox is closed.\n const mountsToClean: MountEntry[] = [];\n let handle:\n | BindMountSandboxHandle\n | IsolatedSandboxHandle\n | NoSandboxHandle;\n // Only an isolated sandbox syncs its commits back to the host worktree.\n let applyToHost: NonNullable<SandboxInfo[\"applyToHost\"]> = skipHostSync;\n\n if (resolvedSandbox.tag === \"none\") {\n handle = yield* Effect.promise(async () =>\n resolvedSandbox.create({\n worktreePath: worktreeInfo.path,\n env: effectiveEnv,\n }),\n );\n } else if (resolvedSandbox.tag === \"isolated\") {\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startIsolatedSandbox({\n provider: resolvedSandbox,\n hostRepoDir: worktreeInfo.path,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n copySourceDir: hostRepoDir,\n }),\n );\n ({ handle } = startResult);\n applyToHost = () => syncOut(worktreeInfo.path, startResult.handle);\n } else {\n const gitMounts = yield* resolveWorktreeGitMounts(\n hostRepoDir,\n worktreeInfo.path,\n );\n mountsToClean.push(...gitMounts);\n const startResult = yield* d.taskLog(\"Starting sandbox\", () =>\n startSandbox({\n provider: resolvedSandbox,\n hostRepoDir,\n env: effectiveEnv,\n worktreeOrRepoPath: worktreeInfo.path,\n gitMounts,\n repoDir: SANDBOX_REPO_DIR,\n }),\n );\n ({ handle } = startResult);\n }\n\n // Run lifecycle — worktree owns worktree, so no worktree cleanup here\n return yield* Effect.gen(function* () {\n if (!handle.interactiveExec) {\n throw new Error(\n `Sandbox provider does not support interactiveExec. ` +\n `The provider must implement the optional interactiveExec method to use interactive().`,\n );\n }\n const interactiveExecFn = handle.interactiveExec.bind(handle);\n const sandbox = makeSandboxFromHandle(handle);\n const { worktreePath } = handle;\n\n const lifecycleEffect = withSandboxLifecycle(\n {\n hostRepoDir,\n sandboxRepoDir: worktreePath,\n hooks,\n // merge-to-head: pass `undefined` so the lifecycle records the\n // host's current branch and merges the worktree's commits back into\n // it. branch strategy: pin to the worktree's branch.\n branch: isMergeToHead ? undefined : worktreeInfo.branch,\n hostWorktreePath: worktreeInfo.path,\n applyToHost,\n timeouts: options.timeouts,\n keepSourceBranch: isMergeToHead,\n },\n sandbox,\n (ctx) =>\n Effect.gen(function* () {\n const fullPrompt =\n resolved?.source === \"template\"\n ? yield* preprocessPrompt(\n substitutedPrompt,\n ctx.sandbox,\n ctx.sandboxRepoDir,\n )\n : substitutedPrompt;\n\n const interactiveArgs = buildInteractiveArgs({\n prompt: fullPrompt,\n dangerouslySkipPermissions: resolvedSandbox.tag !== \"none\",\n });\n\n const result = yield* raceAbortSignal(\n Effect.promise(async () =>\n interactiveExecFn(interactiveArgs, {\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n cwd: worktreePath,\n }),\n ),\n opts.signal,\n );\n\n return result.exitCode;\n }),\n );\n\n const lifecycleResult = yield* lifecycleEffect;\n\n const exitCode = lifecycleResult.result;\n\n // Summary\n yield* d.summary(\"Session Complete\", {\n Commits: String(lifecycleResult.commits.length),\n Branch: lifecycleResult.branch,\n \"Exit code\": String(exitCode),\n });\n\n return {\n commits: lifecycleResult.commits,\n branch: lifecycleResult.branch,\n preservedWorktreePath: undefined,\n exitCode,\n } satisfies InteractiveResult;\n }).pipe(\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () =>\n handle.close().catch(() => undefined),\n ).pipe(Effect.andThen(removeMountTempDirs(mountsToClean))),\n ),\n );\n });\n\n try {\n return await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n opts.signal?.throwIfAborted();\n throw error;\n }\n };\n\n const worktreeRun = async (\n opts: WorktreeRunOptions,\n ): Promise<WorktreeRunResult> => {\n // If signal is already aborted, reject immediately without any setup\n opts.signal?.throwIfAborted();\n\n const { prompt, promptFile, hooks, agent: provider } = opts;\n const sandboxProvider = opts.sandbox;\n const maxIterations = opts.maxIterations ?? 1;\n\n validateTimeoutOptions(opts);\n\n const isResuming =\n opts.resumeSession !== undefined && opts.resumeSession !== \"\";\n\n if (isResuming && maxIterations > 1) {\n throw new Error(\n \"resumeSession cannot be combined with maxIterations > 1. \" +\n \"Resume applies to iteration 1 only; multi-iteration resume semantics are not supported.\",\n );\n }\n\n if (isResuming) {\n await assertResumeSessionExists({\n provider,\n sandboxTag: sandboxProvider.tag,\n hostRepoDir,\n resumeSession: opts.resumeSession,\n });\n }\n\n const inner = Effect.gen(function* () {\n // 1. Resolve prompt\n const resolved = yield* resolvePrompt({ prompt, promptFile });\n const rawPrompt = resolved.text;\n const isInlinePrompt = resolved.source === \"inline\";\n\n // 2. Resolve env vars\n const effectiveEnv = yield* resolveWorktreeEnv(hostRepoDir, {\n agentProviderEnv: provider.env,\n sandboxProviderEnv: sandboxProvider.env,\n overrides: opts.env,\n });\n\n // 3. Prompt args substitution (skipped for inline prompts — passthrough)\n const userArgs = opts.promptArgs ?? {};\n let resolvedPrompt: string;\n if (isInlinePrompt) {\n yield* validateNoArgsWithInlinePrompt(userArgs);\n resolvedPrompt = rawPrompt;\n } else {\n yield* validateNoBuiltInArgOverride(userArgs);\n // TARGET_BRANCH is the host's active branch, matching top-level\n // interactive(): the branch merge-to-head merges back into.\n const currentHostBranch =\n yield* WorktreeManager.getCurrentBranch(hostRepoDir);\n const effectiveArgs = {\n SOURCE_BRANCH: worktreeInfo.branch,\n TARGET_BRANCH: currentHostBranch,\n ...userArgs,\n };\n const builtInArgKeysSet = new Set<string>(BUILT_IN_PROMPT_ARG_KEYS);\n resolvedPrompt = yield* substitutePromptArgs(\n rawPrompt,\n effectiveArgs,\n builtInArgKeysSet,\n );\n }\n\n // 4. Start sandbox. `mountsToClean` are the temp dirs behind the git\n // mounts, removed once the sandbox is closed.\n const {\n handle,\n sandboxRepoDir,\n gitMounts: mountsToClean,\n hostLink,\n } = yield* startWorktreeRunSandbox(sandboxProvider, {\n hostRepoDir,\n worktreePath: worktreeInfo.path,\n env: effectiveEnv,\n copyPaths: options.copyToWorktree,\n });\n\n // 5. Resolve logging\n const { resolvedLogging, runDisplayLayer } = resolveWorktreeRunDisplay(\n opts,\n hostRepoDir,\n worktreeInfo.branch,\n );\n\n // 6. Build a SandboxFactory that reuses the started sandbox\n const runLayer = Layer.mergeAll(\n reuseStartedSandboxLayer(handle, hostLink, {\n hostWorktreePath: worktreeInfo.path,\n sandboxRepoPath: sandboxRepoDir,\n }),\n runDisplayLayer,\n agentStreamEmitterLayer(buildAgentStreamHandler(resolvedLogging)),\n );\n\n // 7. Run orchestration\n const result = yield* Effect.gen(function* () {\n const display = yield* Display;\n yield* display.intro(opts.name ?? \"sandcastle\");\n\n const orchestrateResult = yield* orchestrate({\n hostRepoDir,\n iterations: maxIterations,\n hooks,\n prompt: resolvedPrompt,\n // merge-to-head: pass `undefined` so the lifecycle records the host's\n // current branch and routes through the merge step. branch strategy:\n // pin to the worktree's branch so commits stay there.\n branch: isMergeToHead ? undefined : worktreeInfo.branch,\n provider,\n completionSignal: opts.completionSignal,\n idleTimeoutSeconds: opts.idleTimeoutSeconds,\n completionTimeoutSeconds: opts.completionTimeoutSeconds,\n name: opts.name,\n resumeSession: opts.resumeSession,\n signal: opts.signal,\n skipPromptExpansion: isInlinePrompt,\n timeouts: options.timeouts,\n keepSourceBranch: isMergeToHead,\n });\n\n const completion = buildCompletionMessage(\n orchestrateResult.completionSignal,\n orchestrateResult.iterations.length,\n );\n yield* display.status(completion.message, completion.severity);\n\n for (const line of buildContextWindowLines(\n orchestrateResult.iterations,\n )) {\n yield* display.text(line);\n }\n\n return orchestrateResult;\n }).pipe(\n Effect.provide(runLayer),\n // Always close sandbox handle\n Effect.ensuring(\n Effect.promise(async () =>\n handle.close().catch(() => undefined),\n ).pipe(Effect.andThen(removeMountTempDirs(mountsToClean))),\n ),\n );\n\n return {\n iterations: result.iterations,\n completionSignal: result.completionSignal,\n stdout: result.stdout,\n commits: result.commits,\n branch: result.branch,\n logFilePath:\n resolvedLogging.type === \"file\" ? resolvedLogging.path : undefined,\n } satisfies WorktreeRunResult;\n });\n\n try {\n return await Effect.runPromise(\n inner.pipe(\n Effect.provide(\n Layer.mergeAll(\n ClackDisplay.layer,\n NodeContext.layer,\n NodeFileSystem.layer,\n ),\n ),\n ),\n );\n } catch (error: unknown) {\n // If the signal was aborted, surface its reason verbatim (no wrapping)\n opts.signal?.throwIfAborted();\n throw error;\n }\n };\n\n const worktreeCreateSandbox = async (\n opts: WorktreeCreateSandboxOptions,\n ): Promise<Sandbox> =>\n createSandboxFromWorktree({\n branch: worktreeInfo.branch,\n worktreePath: worktreeInfo.path,\n hostRepoDir,\n sandbox: opts.sandbox,\n hooks: opts.hooks,\n // Isolated sandboxes sync in via git bundle, so the worktree's own\n // copyToWorktree files (often gitignored) must be copied in as well.\n copyToWorktree:\n opts.sandbox.tag === \"isolated\"\n ? [...(options.copyToWorktree ?? []), ...(opts.copyToWorktree ?? [])]\n : opts.copyToWorktree,\n timeouts: opts.timeouts,\n branchStrategy: options.branchStrategy,\n _test: opts._test,\n });\n return {\n branch: worktreeInfo.branch,\n worktreePath: worktreeInfo.path,\n run: worktreeRun,\n interactive: worktreeInteractive,\n createSandbox: worktreeCreateSandbox,\n close,\n async [Symbol.asyncDispose]() {\n await close();\n },\n };\n};\n","import { CwdError as CwdErrorImpl } from \"./resolveCwd.js\";\n\n/**\n * The provided `cwd` path does not exist or is not a directory.\n *\n * Public-facing type for `CwdError`. The runtime class is the same\n * `Data.TaggedError` from `resolveCwd.ts`, but we re-declare its public\n * shape here as a plain `Error` subclass so that Effect's type machinery\n * does not leak into Sandcastle's published `.d.ts` files.\n */\nexport interface CwdError extends Error {\n readonly _tag: \"CwdError\";\n readonly message: string;\n readonly cwd: string;\n}\n\ninterface CwdErrorConstructor {\n new (args: { readonly message: string; readonly cwd: string }): CwdError;\n readonly prototype: CwdError;\n}\n\n/** The provided `cwd` path does not exist or is not a directory. */\nexport const CwdError: CwdErrorConstructor = CwdErrorImpl;\n","import { SyncOutPathError as SyncOutPathErrorImpl } from \"./errors.js\";\n\n/**\n * Sync-out refused to write a file on the host because its path, as reported\n * by an isolated sandbox, would land outside the host worktree (or in its\n * `.git`): an absolute path, a `..` segment, or a symlink leading out.\n *\n * Public-facing type for `SyncOutPathError`. The runtime class is the same\n * `Data.TaggedError` from `errors.ts`, re-declared here as a plain `Error`\n * subclass so that Effect's types stay out of Sandcastle's published `.d.ts`\n * files.\n */\nexport interface SyncOutPathError extends Error {\n readonly _tag: \"SyncOutPathError\";\n readonly message: string;\n /** The offending path, as the sandbox reported it. */\n readonly path: string;\n}\n\ninterface SyncOutPathErrorConstructor {\n new (args: {\n readonly message: string;\n readonly path: string;\n }): SyncOutPathError;\n readonly prototype: SyncOutPathError;\n}\n\n/** Sync-out refused a host path that would land outside the worktree. */\nexport const SyncOutPathError: SyncOutPathErrorConstructor =\n SyncOutPathErrorImpl;\n"]}