@ai-hero/sandcastle 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +15 -1368
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
  4. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  5. package/dist/chunk-6NQPCXSG.js.map +1 -0
  6. package/dist/chunk-7N7AMUYA.js +353 -0
  7. package/dist/chunk-7N7AMUYA.js.map +1 -0
  8. package/dist/chunk-ATA2V2TC.js +112 -0
  9. package/dist/chunk-ATA2V2TC.js.map +1 -0
  10. package/dist/chunk-BIF2X6QB.js +94 -0
  11. package/dist/chunk-BIF2X6QB.js.map +1 -0
  12. package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
  13. package/dist/chunk-BVZWLFFT.js.map +1 -0
  14. package/dist/chunk-EXYXBRCX.js +60 -0
  15. package/dist/chunk-EXYXBRCX.js.map +1 -0
  16. package/dist/chunk-G2R53CVZ.js +3172 -0
  17. package/dist/chunk-G2R53CVZ.js.map +1 -0
  18. package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
  19. package/dist/chunk-GCLEXPXG.js.map +1 -0
  20. package/dist/chunk-H2PEFS4W.js +1244 -0
  21. package/dist/chunk-H2PEFS4W.js.map +1 -0
  22. package/dist/chunk-HSXPRZKG.js +150 -0
  23. package/dist/chunk-HSXPRZKG.js.map +1 -0
  24. package/dist/chunk-IBK2XNSS.js +50 -0
  25. package/dist/chunk-IBK2XNSS.js.map +1 -0
  26. package/dist/chunk-RDW7FNN6.js +792 -0
  27. package/dist/chunk-RDW7FNN6.js.map +1 -0
  28. package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
  29. package/dist/chunk-S6UHPTRG.js.map +1 -0
  30. package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
  31. package/dist/chunk-STB2U7BB.js.map +1 -0
  32. package/dist/chunk-VRXR2T3S.js +24 -0
  33. package/dist/chunk-VRXR2T3S.js.map +1 -0
  34. package/dist/index.d.ts +241 -26
  35. package/dist/index.js +1082 -1679
  36. package/dist/index.js.map +1 -1
  37. package/dist/main.js +1248 -854
  38. package/dist/main.js.map +1 -1
  39. package/dist/sandboxes/bwrap.d.ts +58 -0
  40. package/dist/sandboxes/bwrap.js +296 -0
  41. package/dist/sandboxes/bwrap.js.map +1 -0
  42. package/dist/sandboxes/daytona.d.ts +1 -1
  43. package/dist/sandboxes/daytona.js +203 -98
  44. package/dist/sandboxes/daytona.js.map +1 -1
  45. package/dist/sandboxes/docker.d.ts +18 -4
  46. package/dist/sandboxes/docker.js +7 -4
  47. package/dist/sandboxes/e2b.d.ts +41 -0
  48. package/dist/sandboxes/e2b.js +202 -0
  49. package/dist/sandboxes/e2b.js.map +1 -0
  50. package/dist/sandboxes/modal.d.ts +78 -0
  51. package/dist/sandboxes/modal.js +171 -0
  52. package/dist/sandboxes/modal.js.map +1 -0
  53. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  54. package/dist/sandboxes/no-sandbox.js +2 -2
  55. package/dist/sandboxes/podman.d.ts +18 -4
  56. package/dist/sandboxes/podman.js +72 -56
  57. package/dist/sandboxes/podman.js.map +1 -1
  58. package/dist/sandboxes/seatbelt.d.ts +65 -0
  59. package/dist/sandboxes/seatbelt.js +425 -0
  60. package/dist/sandboxes/seatbelt.js.map +1 -0
  61. package/dist/sandboxes/sprites.d.ts +54 -0
  62. package/dist/sandboxes/sprites.js +198 -0
  63. package/dist/sandboxes/sprites.js.map +1 -0
  64. package/dist/sandboxes/vercel.d.ts +12 -5
  65. package/dist/sandboxes/vercel.js +195 -126
  66. package/dist/sandboxes/vercel.js.map +1 -1
  67. package/dist/templates/parallel-planner/main.mts +13 -22
  68. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  69. package/package.json +63 -11
  70. package/dist/chunk-62WN33RK.js +0 -104
  71. package/dist/chunk-62WN33RK.js.map +0 -1
  72. package/dist/chunk-BIWNFKGV.js.map +0 -1
  73. package/dist/chunk-CP3TYXZA.js.map +0 -1
  74. package/dist/chunk-DJRHWPEH.js.map +0 -1
  75. package/dist/chunk-NGBM7T3E.js.map +0 -1
  76. package/dist/chunk-VOG34SRF.js.map +0 -1
  77. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
package/dist/index.js CHANGED
@@ -1,19 +1,34 @@
1
1
  import { createRequire } from 'node:module';
2
- import { NodeContext_exports, NodeFileSystem_exports, formatErrorMessage } from './chunk-DJRHWPEH.js';
3
- import { Context_exports, CwdError, Effect_exports, resolveCwd, getCurrentBranch, generateTempBranchName, Layer_exports, FileDisplay, ClackDisplay, WorktreeDockerSandboxFactory, SandboxConfig, Display, pruneStale, create, copyToWorktree, runHostHooks, startSandbox, resolveGitMounts, patchGitMountsForWindows, SANDBOX_REPO_DIR, remove, makeSandboxFromHandle, syncOut, withSandboxLifecycle, hasUncommittedChanges, registerShutdown, SandboxFactory, PromptError, FileSystem_exports, SessionCaptureError, Clock_exports, Duration_exports, Option_exports, PromptExpansionTimeoutError, Deferred_exports, AgentError, Ref_exports, SilentDisplay, AgentIdleTimeoutError, Fiber_exports } from './chunk-VOG34SRF.js';
4
- export { createBindMountSandboxProvider, createIsolatedSandboxProvider } from './chunk-BIWNFKGV.js';
5
- import { noSandbox } from './chunk-62WN33RK.js';
6
- import './chunk-NGBM7T3E.js';
7
- import { mkdirSync, appendFileSync } from 'fs';
8
- import path, { join, posix, dirname, relative } from 'path';
9
- import { styleText } from 'util';
2
+ import { noSandbox } from './chunk-7N7AMUYA.js';
3
+ import { assertInteractiveSupported } from './chunk-VRXR2T3S.js';
4
+ export { NativeInteractiveNotSupportedError } from './chunk-VRXR2T3S.js';
5
+ import { formatErrorMessage } from './chunk-BIF2X6QB.js';
6
+ import { NodeContext_exports, NodeFileSystem_exports } from './chunk-S6UHPTRG.js';
7
+ export { NativeSandboxUnavailableError } from './chunk-S6UHPTRG.js';
8
+ import { Display, getCurrentBranch, generateTempBranchName, pruneStale, create, copyToWorktree, runHostHooks, startSandbox, resolveGitMounts, patchGitMountsForWindows, SANDBOX_REPO_DIR, remove, removeMountTempDirs, makeSandboxFromHandle, syncOut, withSandboxLifecycle, hasUncommittedChanges, ClackDisplay, deleteTempBranchIfUnused, FileDisplay, reuseSandboxFactoryLayer, SandboxFactory, WorktreeDockerSandboxFactory, SandboxConfig, SilentDisplay } from './chunk-G2R53CVZ.js';
9
+ import { registerShutdown } from './chunk-EXYXBRCX.js';
10
+ import { shellEscape } from './chunk-H2PEFS4W.js';
11
+ export { claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, opencode, pi, transferClaudeSession, transferCodexSession } from './chunk-H2PEFS4W.js';
12
+ import { CwdError, SyncOutPathError, resolveCwd, PromptError, FileSystem_exports, SessionCaptureError, ForkNotSupportedError, PromptExpansionTimeoutError, AgentError, AgentIdleTimeoutError } from './chunk-RDW7FNN6.js';
13
+ import { Context_exports, Effect_exports, Layer_exports, Deferred_exports, Runtime_exports, Clock_exports, Duration_exports, Option_exports, Ref_exports, Fiber_exports } from './chunk-STB2U7BB.js';
14
+ export { createBindMountSandboxProvider, createIsolatedSandboxProvider } from './chunk-BVZWLFFT.js';
15
+ import './chunk-6NQPCXSG.js';
16
+ import { mkdirSync, appendFileSync, openSync, fstatSync, readSync, closeSync } from 'fs';
17
+ import path, { join } from 'path';
18
+ import { styleText, inspect } from 'util';
10
19
  import * as clack from '@clack/prompts';
11
- import { readdir, access, readFile, mkdir, writeFile, rm } from 'fs/promises';
12
- import { tmpdir } from 'os';
13
20
 
14
21
  createRequire(import.meta.url);
15
22
 
16
23
  // src/resumePrecheck.ts
24
+ var assertForkSupported = (provider) => {
25
+ if (provider.sessionStorage?.canFork === false) {
26
+ throw new ForkNotSupportedError({
27
+ message: `${provider.name} cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.`,
28
+ agentProvider: provider.name
29
+ });
30
+ }
31
+ };
17
32
  var assertResumeSessionExists = async (params) => {
18
33
  const { provider, sandboxTag, hostRepoDir, resumeSession } = params;
19
34
  if (!provider.sessionStorage) {
@@ -21,7 +36,7 @@ var assertResumeSessionExists = async (params) => {
21
36
  }
22
37
  if (sandboxTag === "none") {
23
38
  const found = await provider.sessionStorage.findByIdOnHost(resumeSession);
24
- if (!found.path) {
39
+ if (found.path === void 0) {
25
40
  throw new Error(
26
41
  `resumeSession "${resumeSession}" not found under ${found.searchedRoot}`
27
42
  );
@@ -38,13 +53,15 @@ var assertResumeSessionExists = async (params) => {
38
53
  resumeSession
39
54
  );
40
55
  throw new Error(
41
- sessionPath ? `resumeSession "${resumeSession}" not found: expected session file at ${sessionPath}` : `resumeSession "${resumeSession}" not found`
56
+ sessionPath === void 0 ? `resumeSession "${resumeSession}" not found` : `resumeSession "${resumeSession}" not found: expected session file at ${sessionPath}`
42
57
  );
43
58
  }
44
59
  };
45
60
 
46
61
  // src/AgentStreamEmitter.ts
47
- var AgentStreamEmitter = class extends Context_exports.Tag("AgentStreamEmitter")() {
62
+ var AgentStreamEmitter = class extends Context_exports.Tag(
63
+ "@ai-hero/sandcastle/AgentStreamEmitter"
64
+ )() {
48
65
  };
49
66
  var agentStreamEmitterLayer = (onEvent) => Layer_exports.succeed(AgentStreamEmitter, {
50
67
  emit: onEvent ? (event) => Effect_exports.sync(() => {
@@ -60,11 +77,49 @@ var PROMPT_EXPANSION_TIMEOUT_MS = 3e4;
60
77
  var SHELL_BLOCK_MARKER = "";
61
78
  var MARKED_SHELL_BLOCK_PATTERN = new RegExp(
62
79
  `!${SHELL_BLOCK_MARKER}\`([^\`]+)\``,
63
- "g"
80
+ "gu"
64
81
  );
82
+ var expandBlock = (block, sandbox, cwd) => Effect_exports.gen(function* () {
83
+ const { command } = block;
84
+ const start = yield* Clock_exports.currentTimeMillis;
85
+ const maybeResult = yield* sandbox.exec(command, { cwd }).pipe(Effect_exports.timeoutOption(Duration_exports.millis(PROMPT_EXPANSION_TIMEOUT_MS)));
86
+ if (Option_exports.isNone(maybeResult)) {
87
+ const elapsedMs = (yield* Clock_exports.currentTimeMillis) - start;
88
+ return yield* new PromptExpansionTimeoutError({
89
+ message: `Shell expression \`${command}\` timed out after ${elapsedMs}ms`,
90
+ timeoutMs: PROMPT_EXPANSION_TIMEOUT_MS,
91
+ expression: command,
92
+ elapsedMs
93
+ });
94
+ }
95
+ const execResult = maybeResult.value;
96
+ if (execResult.exitCode !== 0) {
97
+ return yield* new PromptError({
98
+ message: `Command \`${command}\` exited with code ${execResult.exitCode}: ${execResult.stderr}`,
99
+ exitCode: execResult.exitCode
100
+ });
101
+ }
102
+ return { ...block, output: execResult.stdout.trimEnd() };
103
+ });
104
+ var spliceOutputs = (prompt, expanded) => {
105
+ let result = "";
106
+ let cursor2 = 0;
107
+ for (const { index, text: text2, output } of expanded) {
108
+ result += prompt.slice(cursor2, index) + output;
109
+ cursor2 = index + text2.length;
110
+ }
111
+ result += prompt.slice(cursor2);
112
+ return result.replaceAll(SHELL_BLOCK_MARKER, "");
113
+ };
65
114
  var preprocessPrompt = (prompt, sandbox, cwd) => {
66
- const matches = [...prompt.matchAll(MARKED_SHELL_BLOCK_PATTERN)];
67
- if (matches.length === 0) {
115
+ const blocks = [...prompt.matchAll(MARKED_SHELL_BLOCK_PATTERN)].map(
116
+ (match) => ({
117
+ text: match[0],
118
+ command: match[1] ?? "",
119
+ index: match.index
120
+ })
121
+ );
122
+ if (blocks.length === 0) {
68
123
  return Effect_exports.succeed(prompt.replaceAll(SHELL_BLOCK_MARKER, ""));
69
124
  }
70
125
  return Effect_exports.gen(function* () {
@@ -72,53 +127,15 @@ var preprocessPrompt = (prompt, sandbox, cwd) => {
72
127
  return yield* display.taskLog(
73
128
  "Expanding shell expressions",
74
129
  (message) => Effect_exports.gen(function* () {
75
- const results = yield* Effect_exports.all(
76
- matches.map((match) => {
77
- const command = match[1];
78
- return Effect_exports.gen(function* () {
79
- const start = yield* Clock_exports.currentTimeMillis;
80
- const maybeResult = yield* sandbox.exec(command, { cwd }).pipe(
81
- Effect_exports.timeoutOption(
82
- Duration_exports.millis(PROMPT_EXPANSION_TIMEOUT_MS)
83
- )
84
- );
85
- if (Option_exports.isNone(maybeResult)) {
86
- const elapsedMs = (yield* Clock_exports.currentTimeMillis) - start;
87
- return yield* Effect_exports.fail(
88
- new PromptExpansionTimeoutError({
89
- message: `Shell expression \`${command}\` timed out after ${elapsedMs}ms`,
90
- timeoutMs: PROMPT_EXPANSION_TIMEOUT_MS,
91
- expression: command,
92
- elapsedMs
93
- })
94
- );
95
- }
96
- const execResult = maybeResult.value;
97
- if (execResult.exitCode !== 0) {
98
- return yield* Effect_exports.fail(
99
- new PromptError({
100
- message: `Command \`${command}\` exited with code ${execResult.exitCode}: ${execResult.stderr}`,
101
- exitCode: execResult.exitCode
102
- })
103
- );
104
- }
105
- return execResult.stdout.trimEnd();
106
- });
107
- }),
130
+ const expanded = yield* Effect_exports.all(
131
+ blocks.map((block) => expandBlock(block, sandbox, cwd)),
108
132
  { concurrency: "unbounded" }
109
133
  );
110
- for (let i = 0; i < matches.length; i++) {
111
- const command = matches[i][1];
112
- const tokens = Math.ceil(results[i].length / 4);
134
+ for (const { command, output } of expanded) {
135
+ const tokens = Math.ceil(output.length / 4);
113
136
  message(`${command} \u2192 ~${tokens} tokens`);
114
137
  }
115
- let result = prompt;
116
- for (let i = matches.length - 1; i >= 0; i--) {
117
- const match = matches[i];
118
- const index = match.index;
119
- result = result.slice(0, index) + results[i] + result.slice(index + match[0].length);
120
- }
121
- return result.replaceAll(SHELL_BLOCK_MARKER, "");
138
+ return spliceOutputs(prompt, expanded);
122
139
  })
123
140
  );
124
141
  });
@@ -127,7 +144,7 @@ var preprocessPrompt = (prompt, sandbox, cwd) => {
127
144
  // src/TextDeltaBuffer.ts
128
145
  var LENGTH_THRESHOLD = 80;
129
146
  var DEBOUNCE_MS = 50;
130
- var SENTENCE_BOUNDARY_RE = /[.!?] $/;
147
+ var SENTENCE_BOUNDARY_RE = /[.!?] $/u;
131
148
  var TextDeltaBuffer = class {
132
149
  buffer = "";
133
150
  timer = null;
@@ -136,7 +153,9 @@ var TextDeltaBuffer = class {
136
153
  this.onFlush = onFlush;
137
154
  }
138
155
  write(text2) {
139
- if (text2.length === 0) return;
156
+ if (text2.length === 0) {
157
+ return;
158
+ }
140
159
  this.buffer += text2;
141
160
  this.clearTimer();
142
161
  if (this.shouldFlush()) {
@@ -157,13 +176,21 @@ var TextDeltaBuffer = class {
157
176
  this.flush();
158
177
  }
159
178
  shouldFlush() {
160
- if (this.buffer.includes("\n")) return true;
161
- if (SENTENCE_BOUNDARY_RE.test(this.buffer)) return true;
162
- if (this.buffer.length >= LENGTH_THRESHOLD) return true;
179
+ if (this.buffer.includes("\n")) {
180
+ return true;
181
+ }
182
+ if (SENTENCE_BOUNDARY_RE.test(this.buffer)) {
183
+ return true;
184
+ }
185
+ if (this.buffer.length >= LENGTH_THRESHOLD) {
186
+ return true;
187
+ }
163
188
  return false;
164
189
  }
165
190
  doFlush() {
166
- if (this.buffer.length === 0) return;
191
+ if (this.buffer.length === 0) {
192
+ return;
193
+ }
167
194
  const text2 = this.buffer;
168
195
  this.buffer = "";
169
196
  this.onFlush(text2);
@@ -176,26 +203,40 @@ var TextDeltaBuffer = class {
176
203
  }
177
204
  };
178
205
 
206
+ // src/ContextWindow.ts
207
+ var formatContextWindow = (contextWindow) => {
208
+ const used = `${Math.ceil(contextWindow.tokens / 1e3)}k`;
209
+ return contextWindow.limit === void 0 ? used : `${used} / ${Math.floor(contextWindow.limit / 1e3)}k`;
210
+ };
211
+ var buildContextWindowLines = (iterations) => iterations.flatMap(
212
+ (it) => it.contextWindow ? [`Context window: ${formatContextWindow(it.contextWindow)}`] : []
213
+ );
214
+
179
215
  // src/Orchestrator.ts
180
216
  var IDLE_WARNING_INTERVAL_MS = 6e4;
181
- var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, completionTimeoutMs, completionSignals, onText, onToolCall, onRawLine, onIdleWarning, onCompletionTimeout, idleWarningIntervalMs = IDLE_WARNING_INTERVAL_MS, resumeSession, forkSession, signal) => Effect_exports.gen(function* () {
217
+ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, completionTimeoutMs, completionSignals, onText, onToolCall, onRawLine, onIdleWarning, onCompletionTimeout, onContextWindow, idleWarningIntervalMs = IDLE_WARNING_INTERVAL_MS, resumeSession, forkSession, signal) => Effect_exports.gen(function* () {
182
218
  let resultText = "";
219
+ let streamError;
183
220
  let sessionId;
184
221
  let usage;
185
222
  let accumulatedOutput = "";
186
223
  const timeoutSignal = yield* Deferred_exports.make();
187
224
  const completionTimeoutDeferred = yield* Deferred_exports.make();
225
+ const runFork = Runtime_exports.runFork(yield* Effect_exports.runtime());
188
226
  let timeoutFiber = null;
189
227
  let completionDetected = false;
190
228
  let warningFiber = null;
191
229
  let idleMinuteCounter = 0;
230
+ let settled = false;
192
231
  const interruptFiber = (fiber) => {
193
- if (fiber !== null) Effect_exports.runFork(Fiber_exports.interrupt(fiber));
232
+ if (fiber !== null) {
233
+ runFork(Fiber_exports.interrupt(fiber));
234
+ }
194
235
  };
195
236
  const startWarningInterval = () => {
196
237
  interruptFiber(warningFiber);
197
238
  idleMinuteCounter = 0;
198
- warningFiber = Effect_exports.runFork(
239
+ warningFiber = runFork(
199
240
  Effect_exports.gen(function* () {
200
241
  while (true) {
201
242
  yield* Effect_exports.sleep(Duration_exports.millis(idleWarningIntervalMs));
@@ -208,7 +249,7 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
208
249
  const resetTimer = () => {
209
250
  interruptFiber(timeoutFiber);
210
251
  if (completionDetected) {
211
- timeoutFiber = Effect_exports.runFork(
252
+ timeoutFiber = runFork(
212
253
  Effect_exports.gen(function* () {
213
254
  yield* Effect_exports.sleep(Duration_exports.millis(completionTimeoutMs));
214
255
  onCompletionTimeout(completionTimeoutMs);
@@ -220,13 +261,13 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
220
261
  })
221
262
  );
222
263
  } else {
223
- timeoutFiber = Effect_exports.runFork(
264
+ timeoutFiber = runFork(
224
265
  Effect_exports.gen(function* () {
225
266
  yield* Effect_exports.sleep(Duration_exports.millis(idleTimeoutMs));
226
267
  yield* Deferred_exports.fail(
227
268
  timeoutSignal,
228
269
  new AgentIdleTimeoutError({
229
- message: `Agent idle for ${idleTimeoutMs / 1e3} seconds \u2014 no output received. Consider increasing the idle timeout with --idle-timeout.`,
270
+ message: `Agent idle for ${idleTimeoutMs / 1e3} seconds \u2014 no output received. Increase the idleTimeoutSeconds option to allow longer silences.`,
230
271
  timeoutMs: idleTimeoutMs
231
272
  })
232
273
  );
@@ -242,10 +283,12 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
242
283
  return yield* Effect_exports.die(signal.reason);
243
284
  }
244
285
  const onAbort = () => {
245
- Effect_exports.runFork(Deferred_exports.die(abortDeferred, signal.reason));
286
+ runFork(Deferred_exports.die(abortDeferred, signal.reason));
246
287
  };
247
288
  signal.addEventListener("abort", onAbort, { once: true });
248
- abortCleanup = () => signal.removeEventListener("abort", onAbort);
289
+ abortCleanup = () => {
290
+ signal.removeEventListener("abort", onAbort);
291
+ };
249
292
  }
250
293
  resetTimer();
251
294
  const execEffect = Effect_exports.gen(function* () {
@@ -257,6 +300,9 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
257
300
  });
258
301
  const execResult = yield* sandbox.exec(printCmd.command, {
259
302
  onLine: (line) => {
303
+ if (settled) {
304
+ return;
305
+ }
260
306
  try {
261
307
  onRawLine(line);
262
308
  } catch {
@@ -265,6 +311,8 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
265
311
  if (parsed.type === "text") {
266
312
  onText(parsed.text);
267
313
  accumulatedOutput += parsed.text;
314
+ } else if (parsed.type === "context_window") {
315
+ onContextWindow(parsed.contextWindow);
268
316
  } else if (parsed.type === "result") {
269
317
  resultText = parsed.result;
270
318
  accumulatedOutput += parsed.result;
@@ -274,6 +322,8 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
274
322
  sessionId = parsed.sessionId;
275
323
  } else if (parsed.type === "usage") {
276
324
  usage = parsed.usage;
325
+ } else if (parsed.type === "error") {
326
+ streamError = parsed.message;
277
327
  }
278
328
  }
279
329
  if (!completionDetected && completionSignals.some((sig) => accumulatedOutput.includes(sig))) {
@@ -288,6 +338,9 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
288
338
  });
289
339
  if (execResult.exitCode !== 0) {
290
340
  let errorDetail = execResult.stderr;
341
+ if (!errorDetail.trim()) {
342
+ errorDetail = streamError ?? "";
343
+ }
291
344
  if (!errorDetail.trim()) {
292
345
  errorDetail = resultText;
293
346
  }
@@ -295,12 +348,16 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
295
348
  const lines = execResult.stdout.split("\n").filter((l) => l.trim());
296
349
  errorDetail = lines.slice(-20).join("\n");
297
350
  }
298
- return yield* Effect_exports.fail(
299
- new AgentError({
300
- message: `${provider.name} exited with code ${execResult.exitCode}:
351
+ return yield* new AgentError({
352
+ message: `${provider.name} exited with code ${execResult.exitCode}:
301
353
  ${errorDetail}`
302
- })
303
- );
354
+ });
355
+ }
356
+ if (streamError !== void 0) {
357
+ return yield* new AgentError({
358
+ message: `${provider.name} reported an error:
359
+ ${streamError}`
360
+ });
304
361
  }
305
362
  return { result: resultText || execResult.stdout, sessionId, usage };
306
363
  }).pipe(
@@ -316,14 +373,12 @@ ${errorDetail}`
316
373
  let raced = Effect_exports.raceFirst(execEffect, Deferred_exports.await(timeoutSignal));
317
374
  raced = Effect_exports.raceFirst(raced, Deferred_exports.await(completionTimeoutDeferred));
318
375
  if (signal) {
319
- raced = Effect_exports.raceFirst(
320
- raced,
321
- Deferred_exports.await(abortDeferred)
322
- );
376
+ raced = Effect_exports.raceFirst(raced, Deferred_exports.await(abortDeferred));
323
377
  }
324
378
  return yield* raced.pipe(
325
379
  Effect_exports.ensuring(
326
380
  Effect_exports.sync(() => {
381
+ settled = true;
327
382
  abortCleanup?.();
328
383
  interruptFiber(timeoutFiber);
329
384
  timeoutFiber = null;
@@ -343,7 +398,9 @@ var orchestrate = (options) => {
343
398
  const factory = yield* SandboxFactory;
344
399
  const display = yield* Display;
345
400
  const streamEmitter = yield* AgentStreamEmitter;
401
+ const runFork = Runtime_exports.runFork(yield* Effect_exports.runtime());
346
402
  const { hostRepoDir, iterations, hooks, prompt, branch, provider } = options;
403
+ const { sessionStorage } = provider;
347
404
  let completionSignals;
348
405
  if (options.completionSignal === void 0) {
349
406
  completionSignals = [DEFAULT_COMPLETION_SIGNAL];
@@ -352,13 +409,13 @@ var orchestrate = (options) => {
352
409
  } else {
353
410
  completionSignals = [options.completionSignal];
354
411
  }
355
- const label = (msg) => options.name ? `[${options.name}] ${msg}` : msg;
412
+ const label = (msg) => options.name !== void 0 && options.name !== "" ? `[${options.name}] ${msg}` : msg;
356
413
  const allCommits = [];
357
414
  const allIterations = [];
358
415
  let allStdout = "";
359
416
  let resolvedBranch = "";
360
417
  let iterationPreservedPath;
361
- const checkAbort = () => options.signal?.aborted ? Effect_exports.die(options.signal.reason) : Effect_exports.void;
418
+ const checkAbort = () => options.signal?.aborted === true ? Effect_exports.die(options.signal.reason) : Effect_exports.void;
362
419
  for (let i = 1; i <= iterations; i++) {
363
420
  yield* checkAbort();
364
421
  yield* display.status(label(`Iteration ${i}/${iterations}`), "info");
@@ -379,10 +436,10 @@ var orchestrate = (options) => {
379
436
  (ctx) => Effect_exports.gen(function* () {
380
437
  const iterationResumeSession = i === 1 ? options.resumeSession : void 0;
381
438
  const iterationForkSession = i === 1 ? options.forkSession : void 0;
382
- if (iterationResumeSession && bindMountHandle && provider.sessionStorage) {
439
+ if (iterationResumeSession !== void 0 && iterationResumeSession !== "" && bindMountHandle && sessionStorage) {
383
440
  yield* display.status(label("Resuming session"), "info");
384
441
  yield* Effect_exports.tryPromise({
385
- try: () => provider.sessionStorage.resumeIntoSandbox({
442
+ try: () => sessionStorage.resumeIntoSandbox({
386
443
  hostCwd: hostRepoDir,
387
444
  sandboxCwd: ctx.sandboxRepoDir,
388
445
  sessionId: iterationResumeSession,
@@ -394,15 +451,15 @@ var orchestrate = (options) => {
394
451
  })
395
452
  });
396
453
  }
397
- const fullPrompt = options.skipPromptExpansion ? prompt : yield* preprocessPrompt(
454
+ const fullPrompt = options.skipPromptExpansion === true ? prompt : yield* preprocessPrompt(
398
455
  prompt,
399
456
  ctx.sandbox,
400
457
  ctx.sandboxRepoDir
401
458
  );
402
459
  yield* display.status(label("Agent started"), "success");
403
460
  const textBuffer = new TextDeltaBuffer((chunk) => {
404
- Effect_exports.runPromise(display.textChunk(chunk));
405
- Effect_exports.runPromise(
461
+ runFork(display.textChunk(chunk));
462
+ runFork(
406
463
  streamEmitter.emit({
407
464
  type: "text",
408
465
  message: chunk,
@@ -416,8 +473,8 @@ var orchestrate = (options) => {
416
473
  };
417
474
  const onToolCall = (name, formattedArgs) => {
418
475
  textBuffer.flush();
419
- Effect_exports.runPromise(display.toolCall(name, formattedArgs));
420
- Effect_exports.runPromise(
476
+ runFork(display.toolCall(name, formattedArgs));
477
+ runFork(
421
478
  streamEmitter.emit({
422
479
  type: "toolCall",
423
480
  name,
@@ -428,7 +485,7 @@ var orchestrate = (options) => {
428
485
  );
429
486
  };
430
487
  const onRawLine = (line) => {
431
- Effect_exports.runPromise(
488
+ runFork(
432
489
  streamEmitter.emit({
433
490
  type: "raw",
434
491
  line,
@@ -439,10 +496,10 @@ var orchestrate = (options) => {
439
496
  };
440
497
  const onIdleWarning = (minutes) => {
441
498
  const msg = minutes === 1 ? "Agent idle for 1 minute" : `Agent idle for ${minutes} minutes`;
442
- Effect_exports.runPromise(display.status(label(msg), "warn"));
499
+ runFork(display.status(label(msg), "warn"));
443
500
  };
444
501
  const onCompletionTimeout = (timeoutMs) => {
445
- Effect_exports.runPromise(
502
+ runFork(
446
503
  display.status(
447
504
  label(
448
505
  `Completion signal seen but agent process is hanging \u2014 force-completing after ${timeoutMs / 1e3}s grace window.`
@@ -451,6 +508,10 @@ var orchestrate = (options) => {
451
508
  )
452
509
  );
453
510
  };
511
+ let contextWindow;
512
+ const onContextWindow = (cw) => {
513
+ contextWindow = cw;
514
+ };
454
515
  const {
455
516
  result: agentOutput,
456
517
  sessionId,
@@ -468,6 +529,7 @@ var orchestrate = (options) => {
468
529
  onRawLine,
469
530
  onIdleWarning,
470
531
  onCompletionTimeout,
532
+ onContextWindow,
471
533
  options._idleWarningIntervalMs,
472
534
  iterationResumeSession,
473
535
  iterationForkSession,
@@ -477,10 +539,10 @@ var orchestrate = (options) => {
477
539
  yield* display.status(label("Agent stopped"), "info");
478
540
  let sessionFilePath;
479
541
  let usage = streamUsage;
480
- if (provider.captureSessions && provider.sessionStorage && sessionId && bindMountHandle) {
542
+ if (provider.captureSessions && sessionStorage && sessionId !== void 0 && sessionId !== "" && bindMountHandle) {
481
543
  yield* display.status(label("Capturing session"), "info");
482
544
  yield* Effect_exports.tryPromise({
483
- try: () => provider.sessionStorage.captureToHost({
545
+ try: () => sessionStorage.captureToHost({
484
546
  hostCwd: hostRepoDir,
485
547
  sandboxCwd: ctx.sandboxRepoDir,
486
548
  sessionId,
@@ -491,17 +553,23 @@ var orchestrate = (options) => {
491
553
  sessionId
492
554
  })
493
555
  });
494
- sessionFilePath = provider.sessionStorage.hostSessionFilePath(
556
+ sessionFilePath = sessionStorage.hostSessionFilePath(
495
557
  hostRepoDir,
496
558
  sessionId
497
559
  );
498
- if (provider.parseSessionUsage) {
560
+ if (provider.parseSessionUsage || provider.parseSessionContextWindow) {
499
561
  const content = yield* Effect_exports.promise(
500
- () => provider.sessionStorage.readHostSession(hostRepoDir, sessionId).catch(() => void 0)
562
+ () => sessionStorage.readHostSession(hostRepoDir, sessionId).catch(() => void 0)
501
563
  );
502
- if (content) {
503
- const parsedUsage = provider.parseSessionUsage(content);
504
- if (parsedUsage) usage = parsedUsage;
564
+ if (content !== void 0 && content !== "") {
565
+ const parsedUsage = provider.parseSessionUsage?.(content);
566
+ if (parsedUsage) {
567
+ usage = parsedUsage;
568
+ }
569
+ const parsedContextWindow = provider.parseSessionContextWindow?.(content);
570
+ if (parsedContextWindow) {
571
+ contextWindow = parsedContextWindow;
572
+ }
505
573
  }
506
574
  }
507
575
  }
@@ -513,10 +581,20 @@ var orchestrate = (options) => {
513
581
  stdout: agentOutput,
514
582
  sessionId,
515
583
  sessionFilePath,
516
- usage
584
+ usage,
585
+ contextWindow
517
586
  };
518
587
  })
519
588
  )
589
+ ).pipe(
590
+ // A failed iteration ends the run before run() prints the context
591
+ // window lines, so print the completed iterations' lines here.
592
+ Effect_exports.tapError(
593
+ () => Effect_exports.forEach(
594
+ buildContextWindowLines(allIterations),
595
+ (line) => display.text(line)
596
+ )
597
+ )
520
598
  );
521
599
  const lifecycleResult = sandboxResult.value;
522
600
  iterationPreservedPath = sandboxResult.preservedWorktreePath;
@@ -526,7 +604,8 @@ var orchestrate = (options) => {
526
604
  allIterations.push({
527
605
  sessionId: lifecycleResult.result.sessionId,
528
606
  sessionFilePath: lifecycleResult.result.sessionFilePath,
529
- usage: lifecycleResult.result.usage
607
+ usage: lifecycleResult.result.usage,
608
+ contextWindow: lifecycleResult.result.contextWindow
530
609
  });
531
610
  if (lifecycleResult.result.completionSignal !== void 0) {
532
611
  yield* display.status(
@@ -564,7 +643,7 @@ var resolvePrompt = (options) => {
564
643
  if (prompt !== void 0 && promptFile !== void 0) {
565
644
  return Effect_exports.fail(
566
645
  new PromptError({
567
- message: "Cannot provide both --prompt and --prompt-file"
646
+ message: "Cannot provide both prompt and promptFile"
568
647
  })
569
648
  );
570
649
  }
@@ -581,56 +660,60 @@ var resolvePrompt = (options) => {
581
660
  return Effect_exports.gen(function* () {
582
661
  const fs = yield* FileSystem_exports.FileSystem;
583
662
  const text2 = yield* fs.readFileString(promptFile).pipe(
584
- Effect_exports.catchAll(
585
- (e) => Effect_exports.fail(
586
- new PromptError({
587
- message: `Failed to read prompt from ${promptFile}: ${e}`
588
- })
589
- )
663
+ Effect_exports.mapError(
664
+ (e) => new PromptError({
665
+ message: `Failed to read prompt from ${promptFile}: ${String(e)}`
666
+ })
590
667
  )
591
668
  );
592
669
  return { text: text2, source: "template" };
593
670
  });
594
671
  };
672
+ var ESCAPES = {
673
+ n: "\n",
674
+ r: "\r",
675
+ t: " ",
676
+ "\\": "\\"
677
+ };
678
+ var unquote = (value) => {
679
+ const isDoubleQuoted = value.length >= 2 && value.startsWith('"') && value.at(-1) === '"';
680
+ const isSingleQuoted = value.length >= 2 && value.startsWith("'") && value.at(-1) === "'";
681
+ if (isSingleQuoted) {
682
+ return value.slice(1, -1);
683
+ }
684
+ if (!isDoubleQuoted) {
685
+ return value;
686
+ }
687
+ return value.slice(1, -1).replaceAll(/\\(?<escape>[nrt\\])/gu, (_, ch) => ESCAPES[ch] ?? ch);
688
+ };
689
+ var parseEnvLine = (line) => {
690
+ const trimmed = line.trim();
691
+ if (!trimmed || trimmed.startsWith("#")) {
692
+ return void 0;
693
+ }
694
+ const eqIndex = trimmed.indexOf("=");
695
+ if (eqIndex === -1) {
696
+ return void 0;
697
+ }
698
+ const key = trimmed.slice(0, eqIndex).trim();
699
+ return [key, unquote(trimmed.slice(eqIndex + 1).trim())];
700
+ };
595
701
  var parseEnvFile = (filePath) => Effect_exports.gen(function* () {
596
702
  const fs = yield* FileSystem_exports.FileSystem;
597
703
  const content = yield* fs.readFileString(filePath).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(null)));
598
- if (content === null) return {};
599
- const vars = {};
600
- for (const line of content.split("\n")) {
601
- const trimmed = line.trim();
602
- if (!trimmed || trimmed.startsWith("#")) continue;
603
- const eqIndex = trimmed.indexOf("=");
604
- if (eqIndex === -1) continue;
605
- const key = trimmed.slice(0, eqIndex).trim();
606
- let value = trimmed.slice(eqIndex + 1).trim();
607
- const isDoubleQuoted = value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"';
608
- const isSingleQuoted = value.length >= 2 && value[0] === "'" && value[value.length - 1] === "'";
609
- if (isDoubleQuoted || isSingleQuoted) {
610
- value = value.slice(1, -1);
611
- }
612
- if (isDoubleQuoted) {
613
- value = value.replace(/\\([nrt\\])/g, (_, ch) => {
614
- const escapes = {
615
- n: "\n",
616
- r: "\r",
617
- t: " ",
618
- "\\": "\\"
619
- };
620
- return escapes[ch] ?? ch;
621
- });
622
- }
623
- vars[key] = value;
704
+ if (content === null) {
705
+ return {};
624
706
  }
625
- return vars;
707
+ const entries = content.split("\n").map((line) => parseEnvLine(line)).filter((entry) => entry !== void 0);
708
+ return Object.fromEntries(entries);
626
709
  });
627
710
  var resolveEnv = (repoDir) => Effect_exports.gen(function* () {
628
711
  const sandcastleEnv = yield* parseEnvFile(
629
712
  join(repoDir, ".sandcastle", ".env")
630
713
  );
631
714
  const result = {};
632
- for (const key of Object.keys(sandcastleEnv)) {
633
- const value = sandcastleEnv[key] || process.env[key];
715
+ for (const [key, fileValue] of Object.entries(sandcastleEnv)) {
716
+ const value = fileValue || (process.env[key] ?? "");
634
717
  if (value) {
635
718
  result[key] = value;
636
719
  }
@@ -657,14 +740,17 @@ var mergeProviderEnv = (options) => {
657
740
  };
658
741
 
659
742
  // src/PromptArgumentSubstitution.ts
660
- var SHELL_BLOCK_PATTERN = /!`([^`]+)`/g;
743
+ var SHELL_BLOCK_PATTERN = /!`(?<command>[^`]+)`/gu;
661
744
  var BUILT_IN_PROMPT_ARG_KEYS = [
662
745
  "SOURCE_BRANCH",
663
746
  "TARGET_BRANCH"
664
747
  ];
665
- var PLACEHOLDER_PATTERN = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
748
+ var PLACEHOLDER_PATTERN = /\{\{\s*(?<key>[A-Za-z_][A-Za-z0-9_]*)\s*\}\}/gu;
749
+ var placeholderKeys = (text2) => [...text2.matchAll(PLACEHOLDER_PATTERN)].map((m) => m.groups?.["key"] ?? "");
666
750
  var validateNoArgsWithInlinePrompt = (args) => {
667
- if (Object.keys(args).length === 0) return Effect_exports.void;
751
+ if (Object.keys(args).length === 0) {
752
+ return Effect_exports.void;
753
+ }
668
754
  return Effect_exports.fail(
669
755
  new PromptError({
670
756
  message: 'promptArgs is only supported with promptFile. Inline prompts (prompt: "...") are passed to the agent as-is \u2014 interpolate values directly in JavaScript, or switch to promptFile to use {{KEY}} substitution.'
@@ -684,65 +770,83 @@ var validateNoBuiltInArgOverride = (args) => {
684
770
  return Effect_exports.void;
685
771
  };
686
772
  var findMissingPromptArgKeys = (prompt, providedArgs) => {
687
- const matches = [...prompt.matchAll(PLACEHOLDER_PATTERN)];
688
773
  const builtInSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
689
774
  const seen = /* @__PURE__ */ new Set();
690
775
  const missing = [];
691
- for (const m of matches) {
692
- const key = m[1];
693
- if (seen.has(key)) continue;
776
+ for (const key of placeholderKeys(prompt)) {
777
+ if (seen.has(key)) {
778
+ continue;
779
+ }
694
780
  seen.add(key);
695
- if (builtInSet.has(key)) continue;
696
- if (key in providedArgs && providedArgs[key] != null) continue;
781
+ if (builtInSet.has(key)) {
782
+ continue;
783
+ }
784
+ if (key in providedArgs && providedArgs[key] !== null && providedArgs[key] !== void 0) {
785
+ continue;
786
+ }
697
787
  missing.push(key);
698
788
  }
699
789
  return missing;
700
790
  };
791
+ var HTML_COMMENT_PATTERN = /<!--[\s\S]*?(?:-->|$)/gu;
792
+ var markShellBlocks = (prompt) => {
793
+ const commentRanges = [...prompt.matchAll(HTML_COMMENT_PATTERN)].map(
794
+ (m) => [m.index, m.index + m[0].length]
795
+ );
796
+ return prompt.replaceAll(
797
+ SHELL_BLOCK_PATTERN,
798
+ (block, command, offset) => commentRanges.some(([start, end]) => offset >= start && offset < end) ? block : `!${SHELL_BLOCK_MARKER}\`${command}\``
799
+ );
800
+ };
801
+ var sanitizeArgs = (args) => Object.fromEntries(
802
+ Object.entries(args).map(([key, value]) => [
803
+ key,
804
+ typeof value === "string" ? value.replaceAll(SHELL_BLOCK_MARKER, "") : value
805
+ ])
806
+ );
807
+ var checkReferencedArgs = (referencedKeys, args) => Effect_exports.gen(function* () {
808
+ for (const key of referencedKeys) {
809
+ if (!(key in args)) {
810
+ return yield* new PromptError({
811
+ message: `Prompt argument "{{${key}}}" has no matching value in promptArgs`
812
+ });
813
+ }
814
+ const value = args[key];
815
+ if (value === null || value === void 0) {
816
+ return yield* new PromptError({
817
+ message: `Prompt argument "{{${key}}}" has value ${value === null ? "null" : "undefined"} in promptArgs`
818
+ });
819
+ }
820
+ }
821
+ });
822
+ var warnUnusedArgs = (args, referencedKeys, silentKeys) => Effect_exports.gen(function* () {
823
+ const display = yield* Display;
824
+ for (const key of Object.keys(args)) {
825
+ if (!referencedKeys.has(key) && silentKeys?.has(key) !== true) {
826
+ yield* display.status(
827
+ `Prompt argument "${key}" was provided but not referenced in the prompt`,
828
+ "warn"
829
+ );
830
+ }
831
+ }
832
+ });
701
833
  var substitutePromptArgs = (prompt, args, silentKeys) => {
702
- const markedPrompt = prompt.replaceAll(SHELL_BLOCK_MARKER, "").replace(SHELL_BLOCK_PATTERN, `!${SHELL_BLOCK_MARKER}\`$1\``);
703
- const sanitizedArgs = Object.fromEntries(
704
- Object.entries(args).map(([key, value]) => [
705
- key,
706
- typeof value === "string" ? value.replaceAll(SHELL_BLOCK_MARKER, "") : value
707
- ])
834
+ const markedPrompt = markShellBlocks(
835
+ prompt.replaceAll(SHELL_BLOCK_MARKER, "")
708
836
  );
709
- const matches = [...markedPrompt.matchAll(PLACEHOLDER_PATTERN)];
710
- if (matches.length === 0 && Object.keys(sanitizedArgs).length === 0) {
837
+ const sanitizedArgs = sanitizeArgs(args);
838
+ const keys = placeholderKeys(markedPrompt);
839
+ if (keys.length === 0 && Object.keys(sanitizedArgs).length === 0) {
711
840
  return Effect_exports.succeed(markedPrompt);
712
841
  }
713
842
  return Effect_exports.gen(function* () {
714
- const display = yield* Display;
715
- const referencedKeys = new Set(matches.map((m) => m[1]));
716
- for (const key of referencedKeys) {
717
- if (!(key in sanitizedArgs)) {
718
- return yield* Effect_exports.fail(
719
- new PromptError({
720
- message: `Prompt argument "{{${key}}}" has no matching value in promptArgs`
721
- })
722
- );
723
- }
724
- const value = sanitizedArgs[key];
725
- if (value == null) {
726
- return yield* Effect_exports.fail(
727
- new PromptError({
728
- message: `Prompt argument "{{${key}}}" has value ${value === null ? "null" : "undefined"} in promptArgs`
729
- })
730
- );
731
- }
732
- }
733
- for (const key of Object.keys(sanitizedArgs)) {
734
- if (!referencedKeys.has(key) && !silentKeys?.has(key)) {
735
- yield* display.status(
736
- `Prompt argument "${key}" was provided but not referenced in the prompt`,
737
- "warn"
738
- );
739
- }
740
- }
741
- const result = markedPrompt.replace(
843
+ const referencedKeys = new Set(keys);
844
+ yield* checkReferencedArgs(referencedKeys, sanitizedArgs);
845
+ yield* warnUnusedArgs(sanitizedArgs, referencedKeys, silentKeys);
846
+ return markedPrompt.replaceAll(
742
847
  PLACEHOLDER_PATTERN,
743
- (_match, key) => sanitizedArgs[key].toString()
848
+ (_match, key) => String(sanitizedArgs[key])
744
849
  );
745
- return result;
746
850
  });
747
851
  };
748
852
 
@@ -806,11 +910,7 @@ var StructuredOutputError = class extends Error {
806
910
  // src/extractStructuredOutput.ts
807
911
  var extractStructuredOutput = async (stdout, definition, context) => {
808
912
  if (definition._tag === "object") {
809
- return extractObject(
810
- stdout,
811
- definition,
812
- context
813
- );
913
+ return extractObject(stdout, definition, context);
814
914
  }
815
915
  return extractString(stdout, definition, context);
816
916
  };
@@ -826,10 +926,10 @@ var extractObject = async (stdout, definition, context) => {
826
926
  let parsed;
827
927
  try {
828
928
  parsed = JSON.parse(unwrapped);
829
- } catch (cause) {
929
+ } catch (error) {
830
930
  throw new StructuredOutputError(
831
931
  `Structured output tag <${definition.tag}> contains invalid JSON`,
832
- { tag: definition.tag, rawMatched: raw, cause, ...context }
932
+ { tag: definition.tag, rawMatched: raw, cause: error, ...context }
833
933
  );
834
934
  }
835
935
  const result = await definition.schema["~standard"].validate(parsed);
@@ -863,27 +963,67 @@ var findLastTagContent = (text2, tag) => {
863
963
  let searchFrom = 0;
864
964
  while (true) {
865
965
  const openIdx = text2.indexOf(openTag, searchFrom);
866
- if (openIdx === -1) break;
966
+ if (openIdx === -1) {
967
+ break;
968
+ }
867
969
  const contentStart = openIdx + openTag.length;
868
970
  const closeIdx = text2.indexOf(closeTag, contentStart);
869
- if (closeIdx === -1) break;
971
+ if (closeIdx === -1) {
972
+ break;
973
+ }
870
974
  lastContent = text2.slice(contentStart, closeIdx);
871
975
  searchFrom = closeIdx + closeTag.length;
872
976
  }
873
977
  return lastContent;
874
978
  };
875
979
  var unwrapFences = (text2) => {
876
- const fenceMatch = text2.match(/^```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/);
877
- if (fenceMatch) {
878
- return fenceMatch[1].trim();
980
+ const fenced = /^```(?:json)?\s*\n(?<body>[\s\S]*?)\n\s*```\s*$/u.exec(text2)?.groups?.body;
981
+ if (fenced !== void 0) {
982
+ return fenced.trim();
879
983
  }
880
984
  return text2;
881
985
  };
986
+ var TIMEOUTS_KEYS = [
987
+ "copyToWorktreeMs",
988
+ "gitSetupMs",
989
+ "commitCollectionMs",
990
+ "mergeToHostMs"
991
+ ];
992
+ var assertPositive = (name, unit, value) => {
993
+ if (value === void 0) {
994
+ return;
995
+ }
996
+ if (typeof value !== "number" || !(value > 0)) {
997
+ throw new Error(
998
+ `${name} must be a positive number of ${unit}. Received: ${inspect(value)}`
999
+ );
1000
+ }
1001
+ };
1002
+ var validateTimeoutOptions = (options) => {
1003
+ assertPositive("idleTimeoutSeconds", "seconds", options.idleTimeoutSeconds);
1004
+ assertPositive(
1005
+ "completionTimeoutSeconds",
1006
+ "seconds",
1007
+ options.completionTimeoutSeconds
1008
+ );
1009
+ for (const key of TIMEOUTS_KEYS) {
1010
+ assertPositive(`timeouts.${key}`, "milliseconds", options.timeouts?.[key]);
1011
+ }
1012
+ };
882
1013
 
883
1014
  // src/run.ts
1015
+ var describeParserCause = (cause) => {
1016
+ if (cause === void 0) {
1017
+ return "(no parser detail)";
1018
+ }
1019
+ if (typeof cause === "string") {
1020
+ return cause;
1021
+ }
1022
+ return JSON.stringify(cause, null, 2);
1023
+ };
884
1024
  var buildStructuredOutputRetryFeedback = (error, retriesRemaining) => {
885
- const raw = error.rawMatched === void 0 ? "(no matching tag was emitted)" : error.rawMatched;
886
- const cause = error.cause === void 0 ? "(no parser detail)" : typeof error.cause === "string" ? error.cause : JSON.stringify(error.cause, null, 2);
1025
+ const raw = error.rawMatched ?? "(no matching tag was emitted)";
1026
+ const cause = describeParserCause(error.cause);
887
1027
  return `Your previous response did not produce valid structured output.
888
1028
 
889
1029
  Retries remaining after this attempt: ${retriesRemaining}.
@@ -900,11 +1040,11 @@ ${raw}
900
1040
  Emit only a corrected <${error.tag}> block. Do not change files or run commands.`;
901
1041
  };
902
1042
  var DEFAULT_MAX_ITERATIONS = 1;
903
- var sanitizeBranchForFilename = (branch) => branch.replace(/[/\\:*?"<>|]/g, "-");
1043
+ var sanitizeBranchForFilename = (branch) => branch.replaceAll(/[/\\:*?"<>|]/gu, "-");
904
1044
  var printFileDisplayStartup = (options) => {
905
1045
  const name = options.agentName ?? "Agent";
906
1046
  const label = styleText("bold", `[${name}]`);
907
- const branchPart = options.branch ? ` on branch ${options.branch}` : "";
1047
+ const branchPart = options.branch !== void 0 && options.branch !== "" ? ` on branch ${options.branch}` : "";
908
1048
  const hostRepoDir = options.hostRepoDir ?? process.cwd();
909
1049
  const displayLogPath = hostRepoDir === process.cwd() ? path.relative(process.cwd(), options.logPath) : options.logPath;
910
1050
  console.log(`${label} Started${branchPart}`);
@@ -912,8 +1052,8 @@ var printFileDisplayStartup = (options) => {
912
1052
  };
913
1053
  var buildLogFilename = (resolvedBranch, targetBranch, name) => {
914
1054
  const sanitized = sanitizeBranchForFilename(resolvedBranch);
915
- const nameSuffix = name ? `-${name.toLowerCase().replace(/[^a-z0-9_.-]/g, "-")}` : "";
916
- if (targetBranch) {
1055
+ const nameSuffix = name !== void 0 && name !== "" ? `-${name.toLowerCase().replaceAll(/[^a-z0-9_.-]/gu, (char) => "-".repeat(char.length))}` : "";
1056
+ if (targetBranch !== void 0 && targetBranch !== "") {
917
1057
  return `${sanitizeBranchForFilename(targetBranch)}-${sanitized}${nameSuffix}.log`;
918
1058
  }
919
1059
  return `${sanitized}${nameSuffix}.log`;
@@ -936,15 +1076,12 @@ var buildCompletionMessage = (completionSignal, iterationsRun) => {
936
1076
  severity: "warn"
937
1077
  };
938
1078
  };
939
- var formatContextWindowSize = (usage) => {
940
- const total = usage.inputTokens + usage.cacheCreationInputTokens + usage.cacheReadInputTokens;
941
- return `${Math.ceil(total / 1e3)}k`;
942
- };
943
- var buildContextWindowLines = (iterations) => iterations.filter((it) => it.usage !== void 0).map((it) => `Context window: ${formatContextWindowSize(it.usage)}`);
944
1079
  var buildAgentStreamHandler = (logging) => {
945
1080
  const userHandler = logging.type === "file" ? logging.onAgentStreamEvent : void 0;
946
- const verboseSink = logging.verbose ? buildVerboseRawLineSink(logging) : void 0;
947
- if (!userHandler && !verboseSink) return void 0;
1081
+ const verboseSink = logging.verbose === true ? buildVerboseRawLineSink(logging) : void 0;
1082
+ if (!userHandler && !verboseSink) {
1083
+ return void 0;
1084
+ }
948
1085
  return (event) => {
949
1086
  if (userHandler) {
950
1087
  try {
@@ -957,6 +1094,25 @@ var buildAgentStreamHandler = (logging) => {
957
1094
  }
958
1095
  };
959
1096
  };
1097
+ var fileEndsMidLine = (filePath) => {
1098
+ let fd;
1099
+ try {
1100
+ fd = openSync(filePath, "r");
1101
+ const { size } = fstatSync(fd);
1102
+ if (size === 0) {
1103
+ return false;
1104
+ }
1105
+ const lastByte = Buffer.alloc(1);
1106
+ readSync(fd, lastByte, 0, 1, size - 1);
1107
+ return lastByte[0] !== 10;
1108
+ } catch {
1109
+ return false;
1110
+ } finally {
1111
+ if (fd !== void 0) {
1112
+ closeSync(fd);
1113
+ }
1114
+ }
1115
+ };
960
1116
  var buildVerboseRawLineSink = (logging) => {
961
1117
  if (logging.type === "file") {
962
1118
  const logPath = logging.path;
@@ -966,46 +1122,48 @@ var buildVerboseRawLineSink = (logging) => {
966
1122
  }
967
1123
  return (line) => {
968
1124
  try {
969
- appendFileSync(logPath, line + "\n");
1125
+ const prefix = fileEndsMidLine(logPath) ? "\n" : "";
1126
+ appendFileSync(logPath, `${prefix + line}
1127
+ `);
970
1128
  } catch {
971
1129
  }
972
1130
  };
973
1131
  }
974
1132
  return (line) => {
975
- process.stdout.write(line + "\n");
1133
+ process.stdout.write(`${line}
1134
+ `);
976
1135
  };
977
1136
  };
978
- async function run(options) {
979
- options.signal?.throwIfAborted();
980
- const {
981
- prompt,
982
- promptFile,
983
- maxIterations = DEFAULT_MAX_ITERATIONS,
984
- hooks,
985
- agent: provider
986
- } = options;
987
- const branchStrategy = options.branchStrategy ?? (options.sandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
988
- const effectiveBranchType = branchStrategy.type;
989
- if (effectiveBranchType === "head" && options.sandbox.tag === "isolated") {
1137
+ var validateBranchOptions = (options, branchType) => {
1138
+ if (branchType === "head" && options.sandbox.tag === "isolated") {
990
1139
  throw new Error(
991
1140
  "head branch strategy is not supported with isolated providers"
992
1141
  );
993
1142
  }
994
- if (effectiveBranchType === "head" && options.copyToWorktree && options.copyToWorktree.length > 0) {
1143
+ if (branchType === "head" && options.copyToWorktree && options.copyToWorktree.length > 0) {
995
1144
  throw new Error(
996
1145
  "copyToWorktree is not supported with head branch strategy. In head mode the host working directory is bind-mounted directly."
997
1146
  );
998
1147
  }
999
- if (options.resumeSession && maxIterations > 1) {
1148
+ };
1149
+ var validateSessionOptions = (options, maxIterations) => {
1150
+ const isResuming = options.resumeSession !== void 0 && options.resumeSession !== "";
1151
+ if (isResuming && maxIterations > 1) {
1000
1152
  throw new Error(
1001
1153
  "resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
1002
1154
  );
1003
1155
  }
1004
- if (options.forkSession && !options.resumeSession) {
1156
+ if (options.forkSession === true && !isResuming) {
1005
1157
  throw new Error(
1006
1158
  "forkSession requires resumeSession. Use RunResult.fork(prompt) to fork the last captured session."
1007
1159
  );
1008
1160
  }
1161
+ if (options.forkSession === true) {
1162
+ assertForkSupported(options.agent);
1163
+ }
1164
+ return isResuming;
1165
+ };
1166
+ var validateOutputOptions = (options, maxIterations) => {
1009
1167
  if (options.output && maxIterations !== 1) {
1010
1168
  throw new Error(
1011
1169
  "output requires maxIterations to be 1. Structured output is only supported for single-iteration runs."
@@ -1017,73 +1175,147 @@ async function run(options) {
1017
1175
  `output.maxRetries must be a non-negative integer. Received: ${outputMaxRetries}`
1018
1176
  );
1019
1177
  }
1020
- if (outputMaxRetries > 0 && !provider.sessionStorage) {
1178
+ if (outputMaxRetries > 0 && !options.agent.sessionStorage) {
1021
1179
  throw new Error(
1022
- `output.maxRetries requires an agent provider that supports session resumption. The "${provider.name}" provider does not. Use claudeCode, codex, or pi, or set maxRetries to 0.`
1180
+ `output.maxRetries requires an agent provider that supports session resumption. The "${options.agent.name}" provider does not. Use an agent provider that supports resume, or set maxRetries to 0.`
1023
1181
  );
1024
1182
  }
1025
- const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
1183
+ return outputMaxRetries;
1184
+ };
1185
+ var buildAgentPrompt = (input) => Effect_exports.gen(function* () {
1186
+ if (input.isInlinePrompt) {
1187
+ yield* validateNoArgsWithInlinePrompt(input.userArgs);
1188
+ return input.rawPrompt;
1189
+ }
1190
+ yield* validateNoBuiltInArgOverride(input.userArgs);
1191
+ const effectiveArgs = {
1192
+ SOURCE_BRANCH: input.sourceBranch,
1193
+ TARGET_BRANCH: input.targetBranch,
1194
+ ...input.userArgs
1195
+ };
1196
+ const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
1197
+ return yield* substitutePromptArgs(
1198
+ input.rawPrompt,
1199
+ effectiveArgs,
1200
+ builtInArgKeysSet
1201
+ );
1202
+ });
1203
+ var reportRunEnd = (result) => Effect_exports.gen(function* () {
1204
+ const d = yield* Display;
1205
+ const completion = buildCompletionMessage(
1206
+ result.completionSignal,
1207
+ result.iterations.length
1208
+ );
1209
+ yield* d.status(completion.message, completion.severity);
1210
+ for (const line of buildContextWindowLines(result.iterations)) {
1211
+ yield* d.text(line);
1212
+ }
1213
+ });
1214
+ var followUpRun = (options, result, kind) => async (followUpPrompt, followUpOptions) => {
1215
+ const lastIteration = result.iterations.at(-1);
1216
+ if (lastIteration?.sessionId === void 0 || lastIteration.sessionId === "") {
1217
+ throw new Error(`Cannot ${kind}: no sessionId was captured`);
1218
+ }
1219
+ return run({
1220
+ ...options,
1221
+ // The follow-up prompt is inline: drop the template's arguments.
1222
+ promptArgs: void 0,
1223
+ // The follow-up prompt is new: structured output is opt-in per call.
1224
+ output: void 0,
1225
+ ...followUpOptions,
1226
+ prompt: followUpPrompt,
1227
+ promptFile: void 0,
1228
+ maxIterations: 1,
1229
+ resumeSession: lastIteration.sessionId,
1230
+ ...kind === "fork" ? { forkSession: true } : {}
1231
+ });
1232
+ };
1233
+ var resolveRunHostRepoDir = async (options, isResuming) => {
1026
1234
  const hostRepoDir = await Effect_exports.runPromise(
1027
1235
  resolveCwd(options.cwd).pipe(Effect_exports.provide(NodeContext_exports.layer))
1028
1236
  );
1029
- if (options.resumeSession) {
1237
+ if (isResuming && options.resumeSession !== void 0) {
1030
1238
  await assertResumeSessionExists({
1031
- provider,
1239
+ provider: options.agent,
1032
1240
  sandboxTag: options.sandbox.tag,
1033
1241
  hostRepoDir,
1034
1242
  resumeSession: options.resumeSession
1035
1243
  });
1036
1244
  }
1245
+ return hostRepoDir;
1246
+ };
1247
+ var resolveBranchStrategy = (options) => options.branchStrategy ?? (options.sandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
1248
+ var resolveRunPrompt = async (options) => {
1037
1249
  const resolved = await Effect_exports.runPromise(
1038
- resolvePrompt({ prompt, promptFile }).pipe(
1039
- Effect_exports.provide(NodeContext_exports.layer)
1040
- )
1250
+ resolvePrompt({
1251
+ prompt: options.prompt,
1252
+ promptFile: options.promptFile
1253
+ }).pipe(Effect_exports.provide(NodeContext_exports.layer))
1041
1254
  );
1042
- const rawPrompt = resolved.text;
1043
- const isInlinePrompt = resolved.source === "inline";
1044
- if (options.output) {
1045
- const openTag = `<${options.output.tag}>`;
1046
- if (!rawPrompt.includes(openTag)) {
1047
- throw new Error(
1048
- `output tag <${options.output.tag}> not found in the resolved prompt. The caller must instruct the agent to emit the configured tag.`
1049
- );
1050
- }
1255
+ if (options.output && !resolved.text.includes(`<${options.output.tag}>`)) {
1256
+ throw new Error(
1257
+ `output tag <${options.output.tag}> not found in the resolved prompt. The caller must instruct the agent to emit the configured tag.`
1258
+ );
1051
1259
  }
1052
- const agentName = provider.name;
1053
- const resolvedEnv = await Effect_exports.runPromise(
1054
- resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
1055
- );
1056
- const env = mergeProviderEnv({
1057
- resolvedEnv,
1058
- agentProviderEnv: provider.env,
1059
- sandboxProviderEnv: options.sandbox.env
1060
- });
1260
+ return {
1261
+ rawPrompt: resolved.text,
1262
+ isInlinePrompt: resolved.source === "inline"
1263
+ };
1264
+ };
1265
+ var resolveRunBranches = async (options, branchStrategy, hostRepoDir) => {
1266
+ const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
1061
1267
  const currentHostBranch = await Effect_exports.runPromise(
1062
1268
  getCurrentBranch(hostRepoDir)
1063
1269
  );
1064
- const resolvedBranch = effectiveBranchType === "head" ? currentHostBranch : branch ?? generateTempBranchName(options.name);
1065
- const targetBranch = effectiveBranchType === "merge-to-head" ? currentHostBranch : void 0;
1066
- const resolvedLogging = options.logging ?? {
1067
- type: "file",
1068
- path: join(
1069
- hostRepoDir,
1070
- ".sandcastle",
1071
- "logs",
1072
- buildLogFilename(resolvedBranch, targetBranch, options.name)
1073
- )
1270
+ return {
1271
+ currentHostBranch,
1272
+ // When in merge-to-head mode, generate a temporary branch name.
1273
+ // In head mode, use the host's current branch directly (no worktree).
1274
+ resolvedBranch: branchStrategy.type === "head" ? currentHostBranch : branch ?? generateTempBranchName(options.name),
1275
+ // When using a temp branch, prefix the log filename with the target branch
1276
+ // (the host's current branch) so developers can tell which branch was targeted.
1277
+ targetBranch: branchStrategy.type === "merge-to-head" ? currentHostBranch : void 0,
1278
+ // In head mode, pass the host branch so SandboxLifecycle skips the merge step.
1279
+ // In merge-to-head mode, branch is undefined (triggers merge). In branch mode, it's the explicit branch.
1280
+ orchestrateBranch: branchStrategy.type === "head" ? currentHostBranch : branch
1074
1281
  };
1075
- const displayLayer = resolvedLogging.type === "file" ? (() => {
1076
- printFileDisplayStartup({
1077
- logPath: resolvedLogging.path,
1078
- agentName: options.name,
1079
- branch: resolvedBranch,
1080
- hostRepoDir
1081
- });
1082
- return Layer_exports.provide(
1083
- FileDisplay.layer(resolvedLogging.path),
1084
- NodeFileSystem_exports.layer
1085
- );
1086
- })() : ClackDisplay.layer;
1282
+ };
1283
+ var resolveRunEnv = async (options, hostRepoDir) => mergeProviderEnv({
1284
+ resolvedEnv: await Effect_exports.runPromise(
1285
+ resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
1286
+ ),
1287
+ agentProviderEnv: options.agent.env,
1288
+ sandboxProviderEnv: options.sandbox.env
1289
+ });
1290
+ var resolveRunLogging = (options, hostRepoDir, { resolvedBranch, targetBranch }) => options.logging ?? {
1291
+ type: "file",
1292
+ path: join(
1293
+ hostRepoDir,
1294
+ ".sandcastle",
1295
+ "logs",
1296
+ buildLogFilename(resolvedBranch, targetBranch, options.name)
1297
+ )
1298
+ };
1299
+ var buildDisplayLayer = ({
1300
+ options,
1301
+ hostRepoDir,
1302
+ branches,
1303
+ logging
1304
+ }) => {
1305
+ if (logging.type !== "file") {
1306
+ return ClackDisplay.layer;
1307
+ }
1308
+ printFileDisplayStartup({
1309
+ logPath: logging.path,
1310
+ agentName: options.name,
1311
+ branch: branches.resolvedBranch,
1312
+ hostRepoDir
1313
+ });
1314
+ return Layer_exports.provide(FileDisplay.layer(logging.path), NodeFileSystem_exports.layer);
1315
+ };
1316
+ var buildRunLayer = (setup) => {
1317
+ const { options, hostRepoDir, branchStrategy, branches, env } = setup;
1318
+ const displayLayer = buildDisplayLayer(setup);
1087
1319
  const factoryLayer = Layer_exports.provide(
1088
1320
  WorktreeDockerSandboxFactory.layer,
1089
1321
  Layer_exports.mergeAll(
@@ -1092,9 +1324,12 @@ async function run(options) {
1092
1324
  hostRepoDir,
1093
1325
  copyToWorktree: options.copyToWorktree,
1094
1326
  name: options.name,
1327
+ // Create the worktree on the temp branch already shown to the user,
1328
+ // rather than letting WorktreeManager generate a second name.
1329
+ tempBranch: branchStrategy.type === "merge-to-head" ? branches.resolvedBranch : void 0,
1095
1330
  sandboxProvider: options.sandbox,
1096
1331
  branchStrategy,
1097
- hooks,
1332
+ hooks: options.hooks,
1098
1333
  signal: options.signal,
1099
1334
  timeouts: options.timeouts
1100
1335
  }),
@@ -1102,187 +1337,186 @@ async function run(options) {
1102
1337
  displayLayer
1103
1338
  )
1104
1339
  );
1105
- const streamEmitterLayer = agentStreamEmitterLayer(
1106
- buildAgentStreamHandler(resolvedLogging)
1107
- );
1108
- const runLayer = Layer_exports.mergeAll(
1340
+ return Layer_exports.mergeAll(
1109
1341
  factoryLayer,
1110
1342
  displayLayer,
1111
- streamEmitterLayer
1343
+ agentStreamEmitterLayer(buildAgentStreamHandler(setup.logging))
1112
1344
  );
1113
- const baseEffect = Effect_exports.gen(function* () {
1114
- const d = yield* Display;
1115
- yield* d.intro(options.name ?? "sandcastle");
1116
- const rows = buildRunSummaryRows({
1117
- name: options.name,
1118
- agentName,
1119
- sandboxName: options.sandbox.name,
1120
- maxIterations,
1121
- branch: resolvedBranch
1122
- });
1123
- yield* d.summary("Sandcastle Run", rows);
1124
- const userArgs = options.promptArgs ?? {};
1125
- let resolvedPrompt;
1126
- if (isInlinePrompt) {
1127
- yield* validateNoArgsWithInlinePrompt(userArgs);
1128
- resolvedPrompt = rawPrompt;
1129
- } else {
1130
- yield* validateNoBuiltInArgOverride(userArgs);
1131
- const effectiveArgs = {
1132
- SOURCE_BRANCH: resolvedBranch,
1133
- TARGET_BRANCH: currentHostBranch,
1134
- ...userArgs
1135
- };
1136
- const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
1137
- resolvedPrompt = yield* substitutePromptArgs(
1138
- rawPrompt,
1139
- effectiveArgs,
1140
- builtInArgKeysSet
1141
- );
1142
- }
1143
- const orchestrateBranch = effectiveBranchType === "head" ? currentHostBranch : branch;
1144
- const orchestrateResult = yield* orchestrate({
1145
- hostRepoDir,
1146
- iterations: maxIterations,
1147
- hooks,
1148
- prompt: resolvedPrompt,
1149
- branch: orchestrateBranch,
1150
- provider,
1151
- completionSignal: options.completionSignal,
1152
- idleTimeoutSeconds: options.idleTimeoutSeconds,
1153
- completionTimeoutSeconds: options.completionTimeoutSeconds,
1154
- name: options.name,
1155
- resumeSession: options.resumeSession,
1156
- forkSession: options.forkSession,
1157
- signal: options.signal,
1158
- skipPromptExpansion: isInlinePrompt,
1159
- timeouts: options.timeouts
1160
- });
1161
- const completion = buildCompletionMessage(
1162
- orchestrateResult.completionSignal,
1163
- orchestrateResult.iterations.length
1164
- );
1165
- yield* d.status(completion.message, completion.severity);
1166
- for (const line of buildContextWindowLines(orchestrateResult.iterations)) {
1167
- yield* d.text(line);
1168
- }
1169
- return orchestrateResult;
1345
+ };
1346
+ var runIterations = ({
1347
+ options,
1348
+ hostRepoDir,
1349
+ maxIterations,
1350
+ branches,
1351
+ rawPrompt,
1352
+ isInlinePrompt
1353
+ }) => Effect_exports.gen(function* () {
1354
+ const d = yield* Display;
1355
+ yield* d.intro(options.name ?? "sandcastle");
1356
+ const rows = buildRunSummaryRows({
1357
+ name: options.name,
1358
+ agentName: options.agent.name,
1359
+ sandboxName: options.sandbox.name,
1360
+ maxIterations,
1361
+ branch: branches.resolvedBranch
1362
+ });
1363
+ yield* d.summary("Sandcastle Run", rows);
1364
+ const resolvedPrompt = yield* buildAgentPrompt({
1365
+ rawPrompt,
1366
+ isInlinePrompt,
1367
+ userArgs: options.promptArgs ?? {},
1368
+ sourceBranch: branches.resolvedBranch,
1369
+ targetBranch: branches.currentHostBranch
1370
+ });
1371
+ const orchestrateResult = yield* orchestrate({
1372
+ hostRepoDir,
1373
+ iterations: maxIterations,
1374
+ hooks: options.hooks,
1375
+ prompt: resolvedPrompt,
1376
+ branch: branches.orchestrateBranch,
1377
+ provider: options.agent,
1378
+ completionSignal: options.completionSignal,
1379
+ idleTimeoutSeconds: options.idleTimeoutSeconds,
1380
+ completionTimeoutSeconds: options.completionTimeoutSeconds,
1381
+ name: options.name,
1382
+ resumeSession: options.resumeSession,
1383
+ forkSession: options.forkSession,
1384
+ signal: options.signal,
1385
+ skipPromptExpansion: isInlinePrompt,
1386
+ timeouts: options.timeouts
1170
1387
  });
1171
- const withErrorLog = resolvedLogging.type === "file" ? baseEffect.pipe(
1388
+ yield* reportRunEnd(orchestrateResult);
1389
+ return orchestrateResult;
1390
+ });
1391
+ var executeRun = async (setup) => {
1392
+ const baseEffect = runIterations(setup);
1393
+ const withErrorLog = setup.logging.type === "file" ? baseEffect.pipe(
1172
1394
  Effect_exports.tapError(
1173
1395
  (error) => Effect_exports.gen(function* () {
1174
1396
  const d = yield* Display;
1175
- yield* d.status(
1176
- formatErrorMessage(error),
1177
- "error"
1178
- );
1397
+ yield* d.status(formatErrorMessage(error), "error");
1179
1398
  })
1180
1399
  )
1181
1400
  ) : baseEffect;
1182
- let result;
1401
+ const runLayer = buildRunLayer(setup);
1183
1402
  try {
1184
- result = await Effect_exports.runPromise(
1185
- withErrorLog.pipe(Effect_exports.provide(runLayer))
1186
- );
1403
+ return await Effect_exports.runPromise(withErrorLog.pipe(Effect_exports.provide(runLayer)));
1187
1404
  } catch (error) {
1188
- options.signal?.throwIfAborted();
1405
+ setup.options.signal?.throwIfAborted();
1189
1406
  throw error;
1190
1407
  }
1191
- const baseResult = {
1192
- ...result,
1193
- logFilePath: resolvedLogging.type === "file" ? resolvedLogging.path : void 0,
1194
- resume: async (prompt2, resumeOptions) => {
1195
- const lastIteration = result.iterations.at(-1);
1196
- if (!lastIteration?.sessionId) {
1197
- throw new Error("Cannot resume: no sessionId was captured");
1198
- }
1199
- return run({
1200
- ...options,
1201
- ...resumeOptions,
1202
- prompt: prompt2,
1203
- promptFile: void 0,
1204
- maxIterations: 1,
1205
- resumeSession: lastIteration.sessionId
1206
- });
1207
- },
1208
- fork: async (prompt2, forkOptions) => {
1209
- const lastIteration = result.iterations.at(-1);
1210
- if (!lastIteration?.sessionId) {
1211
- throw new Error("Cannot fork: no sessionId was captured");
1408
+ };
1409
+ var withStructuredOutput = async (options, baseResult, outputMaxRetries) => {
1410
+ const lastIteration = baseResult.iterations.at(-1);
1411
+ try {
1412
+ const output = await extractStructuredOutput(
1413
+ baseResult.stdout,
1414
+ options.output,
1415
+ {
1416
+ commits: baseResult.commits,
1417
+ branch: baseResult.branch,
1418
+ preservedWorktreePath: baseResult.preservedWorktreePath,
1419
+ sessionId: lastIteration?.sessionId,
1420
+ sessionFilePath: lastIteration?.sessionFilePath
1212
1421
  }
1422
+ );
1423
+ return { ...baseResult, output };
1424
+ } catch (error) {
1425
+ if (error instanceof StructuredOutputError && outputMaxRetries > 0 && error.sessionId !== void 0) {
1426
+ const retriesRemainingAfter = outputMaxRetries - 1;
1427
+ const retryOutput = {
1428
+ ...options.output,
1429
+ maxRetries: retriesRemainingAfter
1430
+ };
1213
1431
  return run({
1214
1432
  ...options,
1215
- ...forkOptions,
1216
- prompt: prompt2,
1433
+ prompt: buildStructuredOutputRetryFeedback(
1434
+ error,
1435
+ retriesRemainingAfter
1436
+ ),
1217
1437
  promptFile: void 0,
1218
- maxIterations: 1,
1219
- resumeSession: lastIteration.sessionId,
1220
- forkSession: true
1438
+ promptArgs: void 0,
1439
+ resumeSession: error.sessionId,
1440
+ forkSession: false,
1441
+ output: retryOutput
1221
1442
  });
1222
1443
  }
1223
- };
1224
- if (options.output) {
1225
- const lastIteration = baseResult.iterations.at(-1);
1226
- try {
1227
- const output = await extractStructuredOutput(
1228
- baseResult.stdout,
1229
- options.output,
1230
- {
1231
- commits: baseResult.commits,
1232
- branch: baseResult.branch,
1233
- preservedWorktreePath: baseResult.preservedWorktreePath,
1234
- sessionId: lastIteration?.sessionId,
1235
- sessionFilePath: lastIteration?.sessionFilePath
1236
- }
1237
- );
1238
- return { ...baseResult, output };
1239
- } catch (error) {
1240
- if (error instanceof StructuredOutputError && outputMaxRetries > 0 && error.sessionId !== void 0) {
1241
- const retriesRemainingAfter = outputMaxRetries - 1;
1242
- const retryOutput = {
1243
- ...options.output,
1244
- maxRetries: retriesRemainingAfter
1245
- };
1246
- return run({
1247
- ...options,
1248
- prompt: buildStructuredOutputRetryFeedback(
1249
- error,
1250
- retriesRemainingAfter
1251
- ),
1252
- promptFile: void 0,
1253
- promptArgs: void 0,
1254
- resumeSession: error.sessionId,
1255
- forkSession: false,
1256
- output: retryOutput
1257
- });
1258
- }
1259
- throw error;
1260
- }
1444
+ throw error;
1261
1445
  }
1262
- return baseResult;
1446
+ };
1447
+ var finishRun = async ({
1448
+ options,
1449
+ result,
1450
+ logging,
1451
+ outputMaxRetries
1452
+ }) => {
1453
+ const baseResult = {
1454
+ ...result,
1455
+ logFilePath: logging.type === "file" ? logging.path : void 0,
1456
+ resume: followUpRun(options, result, "resume"),
1457
+ fork: followUpRun(options, result, "fork")
1458
+ };
1459
+ const { output } = options;
1460
+ if (!output) {
1461
+ return baseResult;
1462
+ }
1463
+ return withStructuredOutput(
1464
+ { ...options, output },
1465
+ baseResult,
1466
+ outputMaxRetries
1467
+ );
1468
+ };
1469
+ async function run(options) {
1470
+ options.signal?.throwIfAborted();
1471
+ const { maxIterations = DEFAULT_MAX_ITERATIONS } = options;
1472
+ const branchStrategy = resolveBranchStrategy(options);
1473
+ validateTimeoutOptions(options);
1474
+ validateBranchOptions(options, branchStrategy.type);
1475
+ const isResuming = validateSessionOptions(options, maxIterations);
1476
+ const outputMaxRetries = validateOutputOptions(options, maxIterations);
1477
+ const hostRepoDir = await resolveRunHostRepoDir(options, isResuming);
1478
+ const { rawPrompt, isInlinePrompt } = await resolveRunPrompt(options);
1479
+ const env = await resolveRunEnv(options, hostRepoDir);
1480
+ const branches = await resolveRunBranches(
1481
+ options,
1482
+ branchStrategy,
1483
+ hostRepoDir
1484
+ );
1485
+ const logging = resolveRunLogging(options, hostRepoDir, branches);
1486
+ const result = await executeRun({
1487
+ options,
1488
+ branchStrategy,
1489
+ hostRepoDir,
1490
+ maxIterations,
1491
+ branches,
1492
+ logging,
1493
+ env,
1494
+ rawPrompt,
1495
+ isInlinePrompt
1496
+ });
1497
+ return finishRun({ options, result, logging, outputMaxRetries });
1263
1498
  }
1264
1499
 
1265
1500
  // src/raceAbortSignal.ts
1266
1501
  var raceAbortSignal = (effect, signal) => {
1267
- if (!signal) return effect;
1502
+ if (!signal) {
1503
+ return effect;
1504
+ }
1268
1505
  return Effect_exports.gen(function* () {
1269
1506
  if (signal.aborted) {
1270
1507
  return yield* Effect_exports.die(signal.reason);
1271
1508
  }
1272
1509
  const abortDeferred = yield* Deferred_exports.make();
1510
+ const runFork = Runtime_exports.runFork(yield* Effect_exports.runtime());
1273
1511
  const onAbort = () => {
1274
- Effect_exports.runPromise(Deferred_exports.die(abortDeferred, signal.reason)).catch(
1275
- () => {
1276
- }
1277
- );
1512
+ runFork(Deferred_exports.die(abortDeferred, signal.reason));
1278
1513
  };
1279
1514
  signal.addEventListener("abort", onAbort, { once: true });
1280
- return yield* Effect_exports.raceFirst(
1281
- effect,
1282
- Deferred_exports.await(abortDeferred)
1283
- ).pipe(
1515
+ return yield* Effect_exports.raceFirst(effect, Deferred_exports.await(abortDeferred)).pipe(
1284
1516
  Effect_exports.ensuring(
1285
- Effect_exports.sync(() => signal.removeEventListener("abort", onAbort))
1517
+ Effect_exports.sync(() => {
1518
+ signal.removeEventListener("abort", onAbort);
1519
+ })
1286
1520
  )
1287
1521
  );
1288
1522
  });
@@ -1292,7 +1526,9 @@ var raceAbortSignal = (effect, signal) => {
1292
1526
  var interactive = async (options) => {
1293
1527
  options.signal?.throwIfAborted();
1294
1528
  const { prompt, promptFile, hooks, agent: provider } = options;
1529
+ validateTimeoutOptions(options);
1295
1530
  const resolvedSandbox = options.sandbox ?? noSandbox();
1531
+ assertInteractiveSupported(resolvedSandbox);
1296
1532
  const branchStrategy = options.branchStrategy ?? (resolvedSandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
1297
1533
  if (branchStrategy.type === "head" && resolvedSandbox.tag === "isolated") {
1298
1534
  throw new Error(
@@ -1304,7 +1540,8 @@ var interactive = async (options) => {
1304
1540
  "copyToWorktree is not supported with head branch strategy. In head mode the host working directory is bind-mounted directly."
1305
1541
  );
1306
1542
  }
1307
- if (!provider.buildInteractiveArgs) {
1543
+ const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);
1544
+ if (!buildInteractiveArgs) {
1308
1545
  throw new Error(
1309
1546
  `Agent provider "${provider.name}" does not support buildInteractiveArgs, required for interactive sessions.`
1310
1547
  );
@@ -1325,7 +1562,7 @@ var interactive = async (options) => {
1325
1562
  agentProviderEnv: provider.env,
1326
1563
  sandboxProviderEnv: sandboxProvider.env
1327
1564
  });
1328
- const effectiveEnv = { ...env, ...options.env ?? {} };
1565
+ const effectiveEnv = { ...env, ...options.env };
1329
1566
  const currentHostBranch = yield* getCurrentBranch(hostRepoDir);
1330
1567
  const resolvedBranch = branchStrategy.type === "head" ? currentHostBranch : branch ?? generateTempBranchName(options.name);
1331
1568
  let substitutedPrompt = rawPrompt;
@@ -1336,10 +1573,12 @@ var interactive = async (options) => {
1336
1573
  const collectedArgs = {};
1337
1574
  for (const key of missingKeys) {
1338
1575
  const value = yield* Effect_exports.promise(
1339
- () => clack.text({
1576
+ async () => clack.text({
1340
1577
  message: `Enter value for {{${key}}}`,
1341
1578
  validate: (v) => {
1342
- if (!v) return `A value is required for {{${key}}}`;
1579
+ if (v === void 0 || v === "") {
1580
+ return `A value is required for {{${key}}}`;
1581
+ }
1343
1582
  }
1344
1583
  })
1345
1584
  );
@@ -1381,77 +1620,84 @@ var interactive = async (options) => {
1381
1620
  () => pruneStale(hostRepoDir).pipe(
1382
1621
  Effect_exports.catchAll(() => Effect_exports.void),
1383
1622
  Effect_exports.andThen(
1384
- branch ? create(hostRepoDir, { branch }) : create(hostRepoDir, { name: options.name })
1623
+ branch !== void 0 && branch !== "" ? create(hostRepoDir, { branch }) : create(hostRepoDir, {
1624
+ name: options.name,
1625
+ tempBranch: resolvedBranch
1626
+ })
1385
1627
  )
1386
1628
  )
1387
1629
  );
1388
1630
  }
1631
+ const hostWorkPath = worktreeInfo?.path ?? hostRepoDir;
1632
+ const copyPaths = options.copyToWorktree;
1633
+ const onWorktreeReady = hooks?.host?.onWorktreeReady ?? [];
1634
+ const mountsToClean = [];
1389
1635
  const handle = yield* Effect_exports.gen(function* () {
1390
1636
  if (!isHeadMode) {
1391
- if ((sandboxProvider.tag === "bind-mount" || sandboxProvider.tag === "none") && options.copyToWorktree && options.copyToWorktree.length > 0) {
1637
+ if ((sandboxProvider.tag === "bind-mount" || sandboxProvider.tag === "none") && copyPaths && copyPaths.length > 0) {
1392
1638
  yield* d.taskLog(
1393
1639
  "Copying files to worktree",
1394
1640
  () => copyToWorktree(
1395
- options.copyToWorktree,
1641
+ copyPaths,
1396
1642
  hostRepoDir,
1397
- worktreeInfo.path,
1643
+ hostWorkPath,
1398
1644
  options.timeouts?.copyToWorktreeMs
1399
1645
  )
1400
1646
  );
1401
1647
  }
1402
- if (hooks?.host?.onWorktreeReady?.length) {
1403
- yield* runHostHooks(hooks.host.onWorktreeReady, worktreeInfo.path);
1648
+ if (onWorktreeReady.length > 0) {
1649
+ yield* runHostHooks(onWorktreeReady, hostWorkPath);
1404
1650
  }
1405
- } else if (hooks?.host?.onWorktreeReady?.length) {
1406
- yield* runHostHooks(hooks.host.onWorktreeReady, hostRepoDir);
1651
+ } else if (onWorktreeReady.length > 0) {
1652
+ yield* runHostHooks(onWorktreeReady, hostRepoDir);
1407
1653
  }
1408
1654
  if (sandboxProvider.tag === "none") {
1409
- const worktreePath = isHeadMode ? hostRepoDir : worktreeInfo.path;
1410
1655
  return yield* Effect_exports.promise(
1411
- () => sandboxProvider.create({
1412
- worktreePath,
1656
+ async () => sandboxProvider.create({
1657
+ worktreePath: hostWorkPath,
1413
1658
  env: effectiveEnv
1414
1659
  })
1415
1660
  );
1416
1661
  } else if (sandboxProvider.tag === "isolated") {
1417
- const startResult = yield* d.taskLog(
1662
+ const startResult2 = yield* d.taskLog(
1418
1663
  "Starting sandbox",
1419
1664
  () => startSandbox({
1420
1665
  provider: sandboxProvider,
1421
- hostRepoDir: worktreeInfo.path,
1666
+ hostRepoDir: hostWorkPath,
1422
1667
  env: effectiveEnv,
1423
- copyPaths: options.copyToWorktree
1668
+ copyPaths: options.copyToWorktree,
1669
+ copySourceDir: hostRepoDir
1424
1670
  })
1425
1671
  );
1426
- return startResult.handle;
1427
- } else {
1428
- const gitPath = join(hostRepoDir, ".git");
1429
- const rawGitMounts = yield* resolveGitMounts(gitPath);
1430
- const worktreeOrRepoPath = isHeadMode ? hostRepoDir : worktreeInfo.path;
1431
- const gitMounts = yield* patchGitMountsForWindows(
1432
- rawGitMounts,
1433
- worktreeOrRepoPath,
1434
- SANDBOX_REPO_DIR
1435
- );
1436
- const startResult = yield* d.taskLog(
1437
- "Starting sandbox",
1438
- () => startSandbox({
1439
- provider: sandboxProvider,
1440
- hostRepoDir,
1441
- env: effectiveEnv,
1442
- worktreeOrRepoPath,
1443
- gitMounts,
1444
- repoDir: SANDBOX_REPO_DIR
1445
- })
1446
- );
1447
- return startResult.handle;
1672
+ return startResult2.handle;
1448
1673
  }
1674
+ const gitPath = join(hostRepoDir, ".git");
1675
+ const rawGitMounts = yield* resolveGitMounts(gitPath);
1676
+ const gitMounts = yield* patchGitMountsForWindows(
1677
+ rawGitMounts,
1678
+ hostWorkPath,
1679
+ SANDBOX_REPO_DIR
1680
+ );
1681
+ mountsToClean.push(...gitMounts);
1682
+ const startResult = yield* d.taskLog(
1683
+ "Starting sandbox",
1684
+ () => startSandbox({
1685
+ provider: sandboxProvider,
1686
+ hostRepoDir,
1687
+ env: effectiveEnv,
1688
+ worktreeOrRepoPath: hostWorkPath,
1689
+ gitMounts,
1690
+ repoDir: SANDBOX_REPO_DIR
1691
+ })
1692
+ );
1693
+ return startResult.handle;
1449
1694
  }).pipe(
1450
1695
  Effect_exports.tapError(
1451
1696
  () => worktreeInfo ? remove(worktreeInfo.path).pipe(
1452
1697
  Effect_exports.catchAll(() => Effect_exports.void)
1453
1698
  ) : Effect_exports.void
1454
- )
1699
+ ),
1700
+ Effect_exports.onError(() => removeMountTempDirs(mountsToClean))
1455
1701
  );
1456
1702
  return yield* Effect_exports.gen(function* () {
1457
1703
  if (!handle.interactiveExec) {
@@ -1461,8 +1707,8 @@ var interactive = async (options) => {
1461
1707
  }
1462
1708
  const interactiveExecFn = handle.interactiveExec.bind(handle);
1463
1709
  const sandbox = makeSandboxFromHandle(handle);
1464
- const worktreePath = handle.worktreePath;
1465
- const applyToHost = sandboxProvider.tag === "isolated" && worktreeInfo ? () => syncOut(worktreeInfo.path, handle) : () => Effect_exports.void;
1710
+ const { worktreePath } = handle;
1711
+ const applyToHost = sandboxProvider.tag === "isolated" && worktreeInfo ? () => syncOut(hostWorkPath, handle) : () => Effect_exports.void;
1466
1712
  const lifecycleEffect = withSandboxLifecycle(
1467
1713
  {
1468
1714
  hostRepoDir,
@@ -1480,13 +1726,13 @@ var interactive = async (options) => {
1480
1726
  ctx.sandbox,
1481
1727
  ctx.sandboxRepoDir
1482
1728
  );
1483
- const interactiveArgs = provider.buildInteractiveArgs({
1729
+ const interactiveArgs = buildInteractiveArgs({
1484
1730
  prompt: fullPrompt,
1485
1731
  dangerouslySkipPermissions: sandboxProvider.tag !== "none"
1486
1732
  });
1487
1733
  const result2 = yield* raceAbortSignal(
1488
1734
  Effect_exports.promise(
1489
- () => interactiveExecFn(interactiveArgs, {
1735
+ async () => interactiveExecFn(interactiveArgs, {
1490
1736
  stdin: process.stdin,
1491
1737
  stdout: process.stdout,
1492
1738
  stderr: process.stderr,
@@ -1509,7 +1755,7 @@ var interactive = async (options) => {
1509
1755
  preservedWorktreePath = worktreeInfo.path;
1510
1756
  }
1511
1757
  }
1512
- if (worktreeInfo && !preservedWorktreePath) {
1758
+ if (worktreeInfo && preservedWorktreePath === void 0) {
1513
1759
  yield* remove(worktreeInfo.path).pipe(
1514
1760
  Effect_exports.catchAll(() => Effect_exports.void)
1515
1761
  );
@@ -1518,7 +1764,7 @@ var interactive = async (options) => {
1518
1764
  Commits: String(lifecycleResult.commits.length),
1519
1765
  Branch: lifecycleResult.branch,
1520
1766
  "Exit code": String(exitCode),
1521
- ...preservedWorktreePath ? { "Preserved worktree": preservedWorktreePath } : {}
1767
+ ...preservedWorktreePath === void 0 ? {} : { "Preserved worktree": preservedWorktreePath }
1522
1768
  });
1523
1769
  return {
1524
1770
  commits: lifecycleResult.commits,
@@ -1534,17 +1780,25 @@ var interactive = async (options) => {
1534
1780
  ) : Effect_exports.void
1535
1781
  ),
1536
1782
  // Always close sandbox handle
1537
- Effect_exports.ensuring(Effect_exports.promise(() => handle.close().catch(() => {
1538
- })))
1783
+ Effect_exports.ensuring(
1784
+ Effect_exports.promise(async () => handle.close().catch(() => {
1785
+ })).pipe(
1786
+ Effect_exports.andThen(removeMountTempDirs(mountsToClean))
1787
+ )
1788
+ )
1539
1789
  );
1540
1790
  });
1541
1791
  let result;
1542
1792
  try {
1543
1793
  result = await Effect_exports.runPromise(
1544
1794
  inner.pipe(
1545
- Effect_exports.provide(ClackDisplay.layer),
1546
- Effect_exports.provide(NodeContext_exports.layer),
1547
- Effect_exports.provide(NodeFileSystem_exports.layer)
1795
+ Effect_exports.provide(
1796
+ Layer_exports.mergeAll(
1797
+ ClackDisplay.layer,
1798
+ NodeContext_exports.layer,
1799
+ NodeFileSystem_exports.layer
1800
+ )
1801
+ )
1548
1802
  )
1549
1803
  );
1550
1804
  } catch (error) {
@@ -1553,6 +1807,31 @@ var interactive = async (options) => {
1553
1807
  }
1554
1808
  return result;
1555
1809
  };
1810
+ var withAgentEnv = (agent, sandboxProviderEnv) => {
1811
+ const entries = Object.entries(agent.env);
1812
+ if (entries.length === 0) {
1813
+ return agent;
1814
+ }
1815
+ mergeProviderEnv({
1816
+ resolvedEnv: {},
1817
+ agentProviderEnv: agent.env,
1818
+ sandboxProviderEnv
1819
+ });
1820
+ const invalid = entries.map(([key]) => key).filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));
1821
+ if (invalid.length > 0) {
1822
+ throw new Error(
1823
+ `Invalid agent provider env key(s): ${invalid.join(", ")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`
1824
+ );
1825
+ }
1826
+ const exports$1 = entries.map(([key, value]) => `export ${key}=${shellEscape(value)}; `).join("");
1827
+ return {
1828
+ ...agent,
1829
+ buildPrintCommand: (options) => {
1830
+ const printCommand = agent.buildPrintCommand(options);
1831
+ return { ...printCommand, command: exports$1 + printCommand.command };
1832
+ }
1833
+ };
1834
+ };
1556
1835
  var buildSandboxHandle = (ctx, close) => {
1557
1836
  const {
1558
1837
  branch,
@@ -1570,25 +1849,27 @@ var buildSandboxHandle = (ctx, close) => {
1570
1849
  const sandboxHandle = {
1571
1850
  branch,
1572
1851
  worktreePath,
1852
+ sandboxId: providerHandle !== void 0 && "sandboxId" in providerHandle ? providerHandle.sandboxId : void 0,
1573
1853
  run: async (runOptions) => {
1574
1854
  runOptions.signal?.throwIfAborted();
1575
- const {
1576
- agent: provider,
1577
- prompt,
1578
- promptFile,
1579
- maxIterations = 1
1580
- } = runOptions;
1581
- if (runOptions.resumeSession && maxIterations > 1) {
1855
+ const { prompt, promptFile, maxIterations = 1 } = runOptions;
1856
+ const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);
1857
+ validateTimeoutOptions(runOptions);
1858
+ const isResuming = runOptions.resumeSession !== void 0 && runOptions.resumeSession !== "";
1859
+ if (isResuming && maxIterations > 1) {
1582
1860
  throw new Error(
1583
1861
  "resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
1584
1862
  );
1585
1863
  }
1586
- if (runOptions.forkSession && !runOptions.resumeSession) {
1864
+ if (runOptions.forkSession === true && !isResuming) {
1587
1865
  throw new Error(
1588
1866
  "forkSession requires resumeSession. Use sandboxRunResult.fork(prompt) to fork the most recent captured session."
1589
1867
  );
1590
1868
  }
1591
- if (runOptions.resumeSession) {
1869
+ if (runOptions.forkSession === true) {
1870
+ assertForkSupported(provider);
1871
+ }
1872
+ if (isResuming) {
1592
1873
  await assertResumeSessionExists({
1593
1874
  provider,
1594
1875
  sandboxTag: ctx.providerTag,
@@ -1649,22 +1930,15 @@ var buildSandboxHandle = (ctx, close) => {
1649
1930
  NodeFileSystem_exports.layer
1650
1931
  );
1651
1932
  })() : silentDisplayLayer;
1652
- const reuseFactoryLayer = Layer_exports.succeed(SandboxFactory, {
1653
- withSandbox: (makeEffect) => makeEffect(
1654
- {
1655
- hostWorktreePath: worktreePath,
1656
- sandboxRepoPath: sandboxRepoDir,
1657
- applyToHost,
1658
- bindMountHandle
1659
- },
1660
- sandbox
1661
- ).pipe(
1662
- Effect_exports.map((value) => ({
1663
- value,
1664
- preservedWorktreePath: void 0
1665
- }))
1666
- )
1667
- });
1933
+ const reuseFactoryLayer = reuseSandboxFactoryLayer(
1934
+ {
1935
+ hostWorktreePath: worktreePath,
1936
+ sandboxRepoPath: sandboxRepoDir,
1937
+ applyToHost,
1938
+ bindMountHandle
1939
+ },
1940
+ sandbox
1941
+ );
1668
1942
  const streamEmitterLayer = agentStreamEmitterLayer(
1669
1943
  buildAgentStreamHandler(resolvedLogging)
1670
1944
  );
@@ -1721,12 +1995,14 @@ var buildSandboxHandle = (ctx, close) => {
1721
1995
  logFilePath: resolvedLogging.type === "file" ? resolvedLogging.path : void 0
1722
1996
  };
1723
1997
  const lastIteration = result.iterations.at(-1);
1724
- if (provider.sessionStorage && lastIteration?.sessionId) {
1998
+ if (provider.sessionStorage && lastIteration?.sessionId !== void 0 && lastIteration.sessionId !== "") {
1725
1999
  const capturedSessionId = lastIteration.sessionId;
1726
2000
  return {
1727
2001
  ...baseResult,
1728
2002
  resume: (nextPrompt, resumeOptions) => sandboxHandle.run({
1729
2003
  ...runOptions,
2004
+ // The follow-up prompt is inline: drop the template's arguments.
2005
+ promptArgs: void 0,
1730
2006
  ...resumeOptions,
1731
2007
  prompt: nextPrompt,
1732
2008
  promptFile: void 0,
@@ -1735,6 +2011,8 @@ var buildSandboxHandle = (ctx, close) => {
1735
2011
  }),
1736
2012
  fork: (nextPrompt, forkOptions) => sandboxHandle.run({
1737
2013
  ...runOptions,
2014
+ // The follow-up prompt is inline: drop the template's arguments.
2015
+ promptArgs: void 0,
1738
2016
  ...forkOptions,
1739
2017
  prompt: nextPrompt,
1740
2018
  promptFile: void 0,
@@ -1748,8 +2026,10 @@ var buildSandboxHandle = (ctx, close) => {
1748
2026
  },
1749
2027
  interactive: async (interactiveOptions) => {
1750
2028
  interactiveOptions.signal?.throwIfAborted();
2029
+ assertInteractiveSupported(ctx.sandboxProvider);
1751
2030
  const { agent: provider, prompt, promptFile } = interactiveOptions;
1752
- if (!provider.buildInteractiveArgs) {
2031
+ const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);
2032
+ if (!buildInteractiveArgs) {
1753
2033
  throw new Error(
1754
2034
  `Agent provider "${provider.name}" does not support buildInteractiveArgs, required for interactive sessions.`
1755
2035
  );
@@ -1806,7 +2086,7 @@ var buildSandboxHandle = (ctx, close) => {
1806
2086
  ctx2.sandbox,
1807
2087
  ctx2.sandboxRepoDir
1808
2088
  );
1809
- const interactiveArgs = provider.buildInteractiveArgs({
2089
+ const interactiveArgs = buildInteractiveArgs({
1810
2090
  prompt: fullPrompt,
1811
2091
  dangerouslySkipPermissions: true
1812
2092
  });
@@ -1816,35 +2096,17 @@ var buildSandboxHandle = (ctx, close) => {
1816
2096
  stderr: process.stderr,
1817
2097
  cwd: sandboxRepoDir
1818
2098
  });
1819
- const signal = interactiveOptions.signal;
1820
- const result = yield* Effect_exports.promise(() => {
1821
- if (!signal) return execPromise;
1822
- if (signal.aborted) return Promise.reject(signal.reason);
1823
- return new Promise(
1824
- (resolve, reject) => {
1825
- const onAbort = () => reject(signal.reason);
1826
- signal.addEventListener("abort", onAbort, {
1827
- once: true
1828
- });
1829
- execPromise.then(
1830
- (r) => {
1831
- signal.removeEventListener("abort", onAbort);
1832
- resolve(r);
1833
- },
1834
- (e) => {
1835
- signal.removeEventListener("abort", onAbort);
1836
- reject(e);
1837
- }
1838
- );
1839
- }
1840
- );
1841
- });
2099
+ const result = yield* raceAbortSignal(
2100
+ Effect_exports.promise(() => execPromise),
2101
+ interactiveOptions.signal
2102
+ );
1842
2103
  return result.exitCode;
1843
2104
  })
1844
2105
  );
1845
2106
  }).pipe(
1846
- Effect_exports.provide(ClackDisplay.layer),
1847
- Effect_exports.provide(NodeContext_exports.layer)
2107
+ Effect_exports.provide(
2108
+ Layer_exports.mergeAll(ClackDisplay.layer, NodeContext_exports.layer)
2109
+ )
1848
2110
  )
1849
2111
  );
1850
2112
  } catch (error) {
@@ -1870,104 +2132,171 @@ var buildSandboxHandle = (ctx, close) => {
1870
2132
  };
1871
2133
  return sandboxHandle;
1872
2134
  };
1873
- var createSandboxFromWorktree = async (options) => {
1874
- const { branch, worktreePath, hostRepoDir } = options;
1875
- const isTestMode = !!options._test?.buildSandbox;
1876
- if (options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated") {
1877
- await Effect_exports.runPromise(
1878
- copyToWorktree(
1879
- options.copyToWorktree,
1880
- hostRepoDir,
1881
- worktreePath,
1882
- options.timeouts?.copyToWorktreeMs
1883
- )
1884
- );
2135
+ var startBindMountWithGitMounts = (provider, {
2136
+ hostRepoDir,
2137
+ worktreePath,
2138
+ env,
2139
+ mountsToClean
2140
+ }) => resolveGitMounts(join(hostRepoDir, ".git")).pipe(
2141
+ Effect_exports.provide(NodeFileSystem_exports.layer),
2142
+ Effect_exports.catchAll(() => Effect_exports.succeed([])),
2143
+ // Patch git mounts for Windows worktree compatibility (ADR-0006)
2144
+ Effect_exports.flatMap(
2145
+ (gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
2146
+ ),
2147
+ Effect_exports.tap((gitMounts) => {
2148
+ mountsToClean.push(...gitMounts);
2149
+ }),
2150
+ Effect_exports.flatMap(
2151
+ (gitMounts) => startSandbox({
2152
+ provider,
2153
+ hostRepoDir,
2154
+ env,
2155
+ worktreeOrRepoPath: worktreePath,
2156
+ gitMounts,
2157
+ repoDir: SANDBOX_REPO_DIR
2158
+ })
2159
+ )
2160
+ );
2161
+ var startProviderSandbox = (options) => {
2162
+ const { provider, hostRepoDir, worktreePath, env } = options;
2163
+ if (provider.tag === "isolated") {
2164
+ return startSandbox({
2165
+ provider,
2166
+ hostRepoDir: worktreePath,
2167
+ env,
2168
+ copyPaths: options.copyToWorktree,
2169
+ copySourceDir: hostRepoDir
2170
+ });
1885
2171
  }
1886
- let providerHandle;
1887
- let sandbox;
1888
- let sandboxRepoDir;
1889
- const isIsolated = options.sandbox.tag === "isolated";
1890
- if (isTestMode) {
1891
- sandbox = options._test.buildSandbox(worktreePath);
1892
- sandboxRepoDir = worktreePath;
1893
- providerHandle = options._test.bindMountHandle;
1894
- } else {
1895
- const resolvedEnv = await Effect_exports.runPromise(
1896
- resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
1897
- );
1898
- const env = mergeProviderEnv({
1899
- resolvedEnv,
1900
- agentProviderEnv: {},
1901
- sandboxProviderEnv: options.sandbox.env
2172
+ if (provider.tag === "none") {
2173
+ return startSandbox({
2174
+ provider,
2175
+ hostRepoDir,
2176
+ env,
2177
+ worktreeOrRepoPath: worktreePath
1902
2178
  });
1903
- const provider = options.sandbox;
1904
- let startEffect;
1905
- if (provider.tag === "isolated") {
1906
- startEffect = startSandbox({
1907
- provider,
1908
- hostRepoDir: worktreePath,
1909
- env,
1910
- copyPaths: options.copyToWorktree
1911
- });
1912
- } else if (provider.tag === "none") {
1913
- startEffect = startSandbox({
1914
- provider,
1915
- hostRepoDir,
1916
- env,
1917
- worktreeOrRepoPath: worktreePath
1918
- });
1919
- } else {
1920
- startEffect = resolveGitMounts(join(hostRepoDir, ".git")).pipe(
1921
- Effect_exports.provide(NodeFileSystem_exports.layer),
1922
- Effect_exports.catchAll(() => Effect_exports.succeed([])),
1923
- // Patch git mounts for Windows worktree compatibility (ADR-0006)
1924
- Effect_exports.flatMap(
1925
- (gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
1926
- ),
1927
- Effect_exports.flatMap(
1928
- (gitMounts) => startSandbox({
1929
- provider,
1930
- hostRepoDir,
1931
- env,
1932
- worktreeOrRepoPath: worktreePath,
1933
- gitMounts,
1934
- repoDir: SANDBOX_REPO_DIR
1935
- })
1936
- )
1937
- );
1938
- }
1939
- const startResult = await Effect_exports.runPromise(startEffect);
1940
- providerHandle = startResult.handle;
1941
- sandbox = startResult.sandbox;
1942
- sandboxRepoDir = startResult.worktreePath;
1943
- }
1944
- const sandboxOnReady = options.hooks?.sandbox?.onSandboxReady;
1945
- const hostOnReady = options.hooks?.host?.onSandboxReady;
1946
- if (sandboxOnReady?.length || hostOnReady?.length) {
1947
- await Effect_exports.runPromise(
1948
- Effect_exports.gen(function* () {
1949
- yield* sandbox.exec(
1950
- `git config --global --add safe.directory "${sandboxRepoDir}"`
1951
- );
1952
- const sandboxEffects = (sandboxOnReady ?? []).map(
1953
- (hook) => sandbox.exec(hook.command, {
1954
- cwd: sandboxRepoDir,
1955
- sudo: hook.sudo
1956
- })
1957
- );
1958
- const allEffects = [...sandboxEffects];
1959
- if (hostOnReady?.length) {
1960
- allEffects.push(runHostHooks(hostOnReady, worktreePath));
1961
- }
1962
- yield* Effect_exports.all(allEffects, {
1963
- concurrency: "unbounded"
1964
- });
2179
+ }
2180
+ return startBindMountWithGitMounts(provider, options);
2181
+ };
2182
+ var copyIntoWorktree = (options, hostRepoDir, worktreePath) => options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated" ? copyToWorktree(
2183
+ options.copyToWorktree,
2184
+ hostRepoDir,
2185
+ worktreePath,
2186
+ options.timeouts?.copyToWorktreeMs
2187
+ ) : Effect_exports.void;
2188
+ var providerHandleFields = (provider, providerHandle, worktreePath) => ({
2189
+ providerHandle,
2190
+ // Pre-narrow the bind-mount handle for the orchestrator's session-capture
2191
+ // path. Gating on the provider tag avoids handing a NoSandbox/Isolated
2192
+ // handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage and
2193
+ // turning a missing-feature into a runtime SessionCaptureError.
2194
+ bindMountHandle: provider.tag === "bind-mount" ? providerHandle : void 0,
2195
+ providerTag: provider.tag,
2196
+ sandboxProvider: provider,
2197
+ sandboxProviderEnv: provider.env,
2198
+ // Syncs an isolated sandbox's changes back to the host worktree.
2199
+ applyToHost: provider.tag === "isolated" && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void
2200
+ });
2201
+ var startSandboxOnWorktree = ({
2202
+ options,
2203
+ hostRepoDir,
2204
+ worktreePath,
2205
+ mountsToClean
2206
+ }) => Effect_exports.gen(function* () {
2207
+ if (options._test?.buildSandbox) {
2208
+ return {
2209
+ sandbox: options._test.buildSandbox(worktreePath),
2210
+ sandboxRepoDir: worktreePath,
2211
+ providerHandle: options._test.bindMountHandle
2212
+ };
2213
+ }
2214
+ const resolvedEnv = yield* resolveEnv(hostRepoDir);
2215
+ const env = mergeProviderEnv({
2216
+ resolvedEnv,
2217
+ agentProviderEnv: {},
2218
+ sandboxProviderEnv: options.sandbox.env
2219
+ });
2220
+ const startResult = yield* startProviderSandbox({
2221
+ provider: options.sandbox,
2222
+ hostRepoDir,
2223
+ worktreePath,
2224
+ env,
2225
+ copyToWorktree: options.copyToWorktree,
2226
+ mountsToClean
2227
+ });
2228
+ return {
2229
+ providerHandle: startResult.handle,
2230
+ sandbox: startResult.sandbox,
2231
+ sandboxRepoDir: startResult.worktreePath
2232
+ };
2233
+ });
2234
+ var runOnSandboxReadyHooks = ({
2235
+ sandbox,
2236
+ sandboxRepoDir,
2237
+ worktreePath,
2238
+ hooks
2239
+ }) => {
2240
+ const sandboxOnReady = hooks?.sandbox?.onSandboxReady ?? [];
2241
+ const hostOnReady = hooks?.host?.onSandboxReady ?? [];
2242
+ if (sandboxOnReady.length === 0 && hostOnReady.length === 0) {
2243
+ return Effect_exports.void;
2244
+ }
2245
+ return Effect_exports.gen(function* () {
2246
+ yield* sandbox.exec(
2247
+ `git config --global --add safe.directory "${sandboxRepoDir}"`
2248
+ );
2249
+ const sandboxEffects = sandboxOnReady.map(
2250
+ (hook) => sandbox.exec(hook.command, {
2251
+ cwd: sandboxRepoDir,
2252
+ sudo: hook.sudo
1965
2253
  })
1966
2254
  );
1967
- }
1968
- const applyToHost = isIsolated && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void;
2255
+ const allEffects = [
2256
+ ...sandboxEffects,
2257
+ ...hostOnReady.length > 0 ? [runHostHooks(hostOnReady, worktreePath)] : []
2258
+ ];
2259
+ yield* Effect_exports.all(allEffects, { concurrency: "unbounded" });
2260
+ });
2261
+ };
2262
+ var closeContainerOnly = (providerHandle, mountsToClean) => {
1969
2263
  let closed = false;
1970
- const bindMountHandle = options.sandbox.tag === "bind-mount" ? providerHandle : void 0;
2264
+ return async () => {
2265
+ if (closed) {
2266
+ return { preservedWorktreePath: void 0 };
2267
+ }
2268
+ closed = true;
2269
+ if (providerHandle) {
2270
+ await providerHandle.close();
2271
+ }
2272
+ await Effect_exports.runPromise(removeMountTempDirs(mountsToClean));
2273
+ return { preservedWorktreePath: void 0 };
2274
+ };
2275
+ };
2276
+ var createSandboxFromWorktree = async (options) => {
2277
+ const { branch, worktreePath, hostRepoDir } = options;
2278
+ validateTimeoutOptions(options);
2279
+ await Effect_exports.runPromise(copyIntoWorktree(options, hostRepoDir, worktreePath));
2280
+ const mountsToClean = [];
2281
+ const { providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
2282
+ startSandboxOnWorktree({
2283
+ options,
2284
+ hostRepoDir,
2285
+ worktreePath,
2286
+ mountsToClean
2287
+ }).pipe(
2288
+ Effect_exports.onError(() => removeMountTempDirs(mountsToClean)),
2289
+ Effect_exports.provide(NodeContext_exports.layer)
2290
+ )
2291
+ );
2292
+ await Effect_exports.runPromise(
2293
+ runOnSandboxReadyHooks({
2294
+ sandbox,
2295
+ sandboxRepoDir,
2296
+ worktreePath,
2297
+ hooks: options.hooks
2298
+ })
2299
+ );
1971
2300
  return buildSandboxHandle(
1972
2301
  {
1973
2302
  branch,
@@ -1975,25 +2304,17 @@ var createSandboxFromWorktree = async (options) => {
1975
2304
  hostRepoDir,
1976
2305
  sandboxRepoDir,
1977
2306
  sandbox,
1978
- providerHandle,
1979
- bindMountHandle,
1980
- providerTag: options.sandbox.tag,
1981
- applyToHost,
2307
+ ...providerHandleFields(options.sandbox, providerHandle, worktreePath),
1982
2308
  timeouts: options.timeouts,
1983
2309
  branchStrategy: options.branchStrategy
1984
2310
  },
1985
- async () => {
1986
- if (closed) return { preservedWorktreePath: void 0 };
1987
- closed = true;
1988
- if (providerHandle) await providerHandle.close();
1989
- return { preservedWorktreePath: void 0 };
1990
- }
2311
+ closeContainerOnly(providerHandle, mountsToClean)
1991
2312
  );
1992
2313
  };
1993
2314
  var createSandbox = async (options) => {
1994
2315
  const { branch } = options;
1995
- const isTestMode = !!options._test?.buildSandbox;
1996
- const isIsolated = options.sandbox.tag === "isolated";
2316
+ validateTimeoutOptions(options);
2317
+ const mountsToClean = [];
1997
2318
  const { hostRepoDir, worktreePath, providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
1998
2319
  Effect_exports.gen(function* () {
1999
2320
  const hostRepoDir2 = yield* resolveCwd(options.cwd);
@@ -2005,110 +2326,40 @@ var createSandbox = async (options) => {
2005
2326
  { branch, baseBranch: options.baseBranch }
2006
2327
  );
2007
2328
  const prepared = yield* Effect_exports.gen(function* () {
2008
- if (options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated") {
2009
- yield* copyToWorktree(
2010
- options.copyToWorktree,
2011
- hostRepoDir2,
2012
- worktreePath2,
2013
- options.timeouts?.copyToWorktreeMs
2014
- );
2015
- }
2016
- if (options.hooks?.host?.onWorktreeReady?.length) {
2017
- yield* runHostHooks(
2018
- options.hooks.host.onWorktreeReady,
2019
- worktreePath2
2020
- );
2021
- }
2022
- let providerHandle2;
2023
- let sandbox2;
2024
- let sandboxRepoDir2;
2025
- if (isTestMode) {
2026
- sandbox2 = options._test.buildSandbox(worktreePath2);
2027
- sandboxRepoDir2 = worktreePath2;
2028
- providerHandle2 = options._test.bindMountHandle;
2029
- } else {
2030
- const resolvedEnv = yield* resolveEnv(hostRepoDir2);
2031
- const env = mergeProviderEnv({
2032
- resolvedEnv,
2033
- agentProviderEnv: {},
2034
- sandboxProviderEnv: options.sandbox.env
2035
- });
2036
- const provider = options.sandbox;
2037
- const startResult = yield* provider.tag === "isolated" ? startSandbox({
2038
- provider,
2039
- hostRepoDir: worktreePath2,
2040
- env,
2041
- copyPaths: options.copyToWorktree
2042
- }) : provider.tag === "none" ? startSandbox({
2043
- provider,
2044
- hostRepoDir: hostRepoDir2,
2045
- env,
2046
- worktreeOrRepoPath: worktreePath2
2047
- }) : resolveGitMounts(join(hostRepoDir2, ".git")).pipe(
2048
- Effect_exports.provide(NodeFileSystem_exports.layer),
2049
- Effect_exports.catchAll(() => Effect_exports.succeed([])),
2050
- // Patch git mounts for Windows worktree compatibility (ADR-0006)
2051
- Effect_exports.flatMap(
2052
- (gitMounts) => patchGitMountsForWindows(
2053
- gitMounts,
2054
- worktreePath2,
2055
- SANDBOX_REPO_DIR
2056
- )
2057
- ),
2058
- Effect_exports.flatMap(
2059
- (gitMounts) => startSandbox({
2060
- provider,
2061
- hostRepoDir: hostRepoDir2,
2062
- env,
2063
- worktreeOrRepoPath: worktreePath2,
2064
- gitMounts,
2065
- repoDir: SANDBOX_REPO_DIR
2066
- })
2067
- )
2068
- );
2069
- providerHandle2 = startResult.handle;
2070
- sandbox2 = startResult.sandbox;
2071
- sandboxRepoDir2 = startResult.worktreePath;
2072
- }
2073
- const sandboxOnReady = options.hooks?.sandbox?.onSandboxReady;
2074
- const hostOnReady = options.hooks?.host?.onSandboxReady;
2075
- if (sandboxOnReady?.length || hostOnReady?.length) {
2076
- yield* Effect_exports.gen(function* () {
2077
- yield* sandbox2.exec(
2078
- `git config --global --add safe.directory "${sandboxRepoDir2}"`
2079
- );
2080
- const sandboxEffects = (sandboxOnReady ?? []).map(
2081
- (hook) => sandbox2.exec(hook.command, {
2082
- cwd: sandboxRepoDir2,
2083
- sudo: hook.sudo
2084
- })
2085
- );
2086
- const allEffects = [...sandboxEffects];
2087
- if (hostOnReady?.length) {
2088
- allEffects.push(runHostHooks(hostOnReady, worktreePath2));
2089
- }
2090
- yield* Effect_exports.all(allEffects, { concurrency: "unbounded" });
2091
- }).pipe(
2092
- Effect_exports.onError(
2093
- () => providerHandle2 ? Effect_exports.promise(
2094
- () => providerHandle2.close().catch(() => {
2095
- })
2096
- ) : Effect_exports.void
2097
- )
2098
- );
2329
+ yield* copyIntoWorktree(options, hostRepoDir2, worktreePath2);
2330
+ const onWorktreeReady = options.hooks?.host?.onWorktreeReady;
2331
+ if (onWorktreeReady !== void 0 && onWorktreeReady.length > 0) {
2332
+ yield* runHostHooks(onWorktreeReady, worktreePath2);
2099
2333
  }
2334
+ const { providerHandle: providerHandle2, sandbox: sandbox2, sandboxRepoDir: sandboxRepoDir2 } = yield* startSandboxOnWorktree({
2335
+ options,
2336
+ hostRepoDir: hostRepoDir2,
2337
+ worktreePath: worktreePath2,
2338
+ mountsToClean
2339
+ });
2340
+ yield* runOnSandboxReadyHooks({
2341
+ sandbox: sandbox2,
2342
+ sandboxRepoDir: sandboxRepoDir2,
2343
+ worktreePath: worktreePath2,
2344
+ hooks: options.hooks
2345
+ }).pipe(
2346
+ Effect_exports.onError(
2347
+ () => (providerHandle2 ? Effect_exports.promise(() => providerHandle2.close().catch(() => {
2348
+ })) : Effect_exports.void).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)))
2349
+ )
2350
+ );
2100
2351
  return { providerHandle: providerHandle2, sandbox: sandbox2, sandboxRepoDir: sandboxRepoDir2 };
2101
2352
  }).pipe(
2102
2353
  Effect_exports.onError(
2103
2354
  () => remove(worktreePath2).pipe(
2104
- Effect_exports.catchAll(() => Effect_exports.void)
2355
+ Effect_exports.catchAll(() => Effect_exports.void),
2356
+ Effect_exports.andThen(removeMountTempDirs(mountsToClean))
2105
2357
  )
2106
2358
  )
2107
2359
  );
2108
2360
  return { hostRepoDir: hostRepoDir2, worktreePath: worktreePath2, ...prepared };
2109
2361
  }).pipe(Effect_exports.provide(NodeContext_exports.layer))
2110
2362
  );
2111
- const applyToHost = isIsolated && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void;
2112
2363
  let closed = false;
2113
2364
  const forceCleanup = () => {
2114
2365
  console.error(`
@@ -2118,13 +2369,16 @@ Worktree preserved at ${worktreePath}`);
2118
2369
  };
2119
2370
  const unregisterShutdown = registerShutdown(forceCleanup);
2120
2371
  const doClose = async () => {
2121
- if (closed) return { preservedWorktreePath: void 0 };
2372
+ if (closed) {
2373
+ return { preservedWorktreePath: void 0 };
2374
+ }
2122
2375
  closed = true;
2123
2376
  return Effect_exports.runPromise(
2124
2377
  Effect_exports.gen(function* () {
2125
2378
  if (providerHandle) {
2126
2379
  yield* Effect_exports.promise(() => providerHandle.close());
2127
2380
  }
2381
+ yield* removeMountTempDirs(mountsToClean);
2128
2382
  const isDirty = yield* hasUncommittedChanges(
2129
2383
  worktreePath
2130
2384
  ).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(false)));
@@ -2138,7 +2392,6 @@ Worktree preserved at ${worktreePath}`);
2138
2392
  })
2139
2393
  );
2140
2394
  };
2141
- const bindMountHandle = options.sandbox.tag === "bind-mount" ? providerHandle : void 0;
2142
2395
  return buildSandboxHandle(
2143
2396
  {
2144
2397
  branch,
@@ -2146,10 +2399,8 @@ Worktree preserved at ${worktreePath}`);
2146
2399
  hostRepoDir,
2147
2400
  sandboxRepoDir,
2148
2401
  sandbox,
2149
- providerHandle,
2150
- bindMountHandle,
2151
- providerTag: options.sandbox.tag,
2152
- applyToHost,
2402
+ // applyToHost is built once, reused across runs.
2403
+ ...providerHandleFields(options.sandbox, providerHandle, worktreePath),
2153
2404
  timeouts: options.timeouts
2154
2405
  },
2155
2406
  async () => {
@@ -2159,34 +2410,38 @@ Worktree preserved at ${worktreePath}`);
2159
2410
  );
2160
2411
  };
2161
2412
  var createWorktree = async (options) => {
2413
+ validateTimeoutOptions(options);
2162
2414
  const branch = options.branchStrategy.type === "branch" ? options.branchStrategy.branch : void 0;
2163
2415
  const baseBranch = options.branchStrategy.type === "branch" ? options.branchStrategy.baseBranch : void 0;
2164
2416
  const isMergeToHead = options.branchStrategy.type === "merge-to-head";
2165
2417
  const { hostRepoDir, worktreeInfo } = await Effect_exports.gen(function* () {
2166
- const hostRepoDir2 = yield* resolveCwd(options.cwd);
2167
- yield* pruneStale(hostRepoDir2).pipe(
2418
+ const repoDir = yield* resolveCwd(options.cwd);
2419
+ yield* pruneStale(repoDir).pipe(
2168
2420
  Effect_exports.catchAll(() => Effect_exports.void)
2169
2421
  );
2170
- const info = yield* create(hostRepoDir2, {
2422
+ const info = yield* create(repoDir, {
2171
2423
  branch,
2172
2424
  baseBranch
2173
2425
  });
2174
2426
  if (options.copyToWorktree && options.copyToWorktree.length > 0) {
2175
2427
  yield* copyToWorktree(
2176
2428
  options.copyToWorktree,
2177
- hostRepoDir2,
2429
+ repoDir,
2178
2430
  info.path,
2179
2431
  options.timeouts?.copyToWorktreeMs
2180
2432
  );
2181
2433
  }
2182
- if (options.hooks?.host?.onWorktreeReady?.length) {
2183
- yield* runHostHooks(options.hooks.host.onWorktreeReady, info.path);
2434
+ const onWorktreeReady = options.hooks?.host?.onWorktreeReady;
2435
+ if (onWorktreeReady !== void 0 && onWorktreeReady.length > 0) {
2436
+ yield* runHostHooks(onWorktreeReady, info.path);
2184
2437
  }
2185
- return { hostRepoDir: hostRepoDir2, worktreeInfo: info };
2438
+ return { hostRepoDir: repoDir, worktreeInfo: info };
2186
2439
  }).pipe(Effect_exports.provide(NodeContext_exports.layer), Effect_exports.runPromise);
2187
2440
  let closed = false;
2188
2441
  const close = async () => {
2189
- if (closed) return { preservedWorktreePath: void 0 };
2442
+ if (closed) {
2443
+ return { preservedWorktreePath: void 0 };
2444
+ }
2190
2445
  closed = true;
2191
2446
  return Effect_exports.gen(function* () {
2192
2447
  const isDirty = yield* hasUncommittedChanges(
@@ -2198,6 +2453,12 @@ var createWorktree = async (options) => {
2198
2453
  yield* remove(worktreeInfo.path).pipe(
2199
2454
  Effect_exports.catchAll(() => Effect_exports.void)
2200
2455
  );
2456
+ if (isMergeToHead) {
2457
+ yield* deleteTempBranchIfUnused(
2458
+ hostRepoDir,
2459
+ worktreeInfo.branch
2460
+ ).pipe(Effect_exports.catchAll(() => Effect_exports.void));
2461
+ }
2201
2462
  return { preservedWorktreePath: void 0 };
2202
2463
  }).pipe(Effect_exports.runPromise);
2203
2464
  };
@@ -2205,7 +2466,9 @@ var createWorktree = async (options) => {
2205
2466
  opts.signal?.throwIfAborted();
2206
2467
  const { prompt, promptFile, hooks, agent: provider } = opts;
2207
2468
  const resolvedSandbox = opts.sandbox ?? noSandbox();
2208
- if (!provider.buildInteractiveArgs) {
2469
+ assertInteractiveSupported(resolvedSandbox);
2470
+ const buildInteractiveArgs = provider.buildInteractiveArgs?.bind(provider);
2471
+ if (!buildInteractiveArgs) {
2209
2472
  throw new Error(
2210
2473
  `Agent provider "${provider.name}" does not support buildInteractiveArgs, required for interactive sessions.`
2211
2474
  );
@@ -2222,14 +2485,15 @@ var createWorktree = async (options) => {
2222
2485
  agentProviderEnv: provider.env,
2223
2486
  sandboxProviderEnv: resolvedSandbox.env
2224
2487
  });
2225
- const effectiveEnv = { ...env, ...opts.env ?? {} };
2488
+ const effectiveEnv = { ...env, ...opts.env };
2226
2489
  let substitutedPrompt = rawPrompt;
2227
2490
  if (hasPromptSource && !isInlinePrompt) {
2228
2491
  const userArgs = opts.promptArgs ?? {};
2229
2492
  yield* validateNoBuiltInArgOverride(userArgs);
2493
+ const currentHostBranch = yield* getCurrentBranch(hostRepoDir);
2230
2494
  const effectiveArgs = {
2231
2495
  SOURCE_BRANCH: worktreeInfo.branch,
2232
- TARGET_BRANCH: worktreeInfo.branch,
2496
+ TARGET_BRANCH: currentHostBranch,
2233
2497
  ...userArgs
2234
2498
  };
2235
2499
  const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
@@ -2247,10 +2511,11 @@ var createWorktree = async (options) => {
2247
2511
  Sandbox: resolvedSandbox.name,
2248
2512
  Branch: worktreeInfo.branch
2249
2513
  });
2514
+ const mountsToClean = [];
2250
2515
  let handle;
2251
2516
  if (resolvedSandbox.tag === "none") {
2252
2517
  handle = yield* Effect_exports.promise(
2253
- () => resolvedSandbox.create({
2518
+ async () => resolvedSandbox.create({
2254
2519
  worktreePath: worktreeInfo.path,
2255
2520
  env: effectiveEnv
2256
2521
  })
@@ -2261,7 +2526,9 @@ var createWorktree = async (options) => {
2261
2526
  () => startSandbox({
2262
2527
  provider: resolvedSandbox,
2263
2528
  hostRepoDir: worktreeInfo.path,
2264
- env: effectiveEnv
2529
+ env: effectiveEnv,
2530
+ copyPaths: options.copyToWorktree,
2531
+ copySourceDir: hostRepoDir
2265
2532
  })
2266
2533
  );
2267
2534
  handle = startResult.handle;
@@ -2273,6 +2540,7 @@ var createWorktree = async (options) => {
2273
2540
  worktreeInfo.path,
2274
2541
  SANDBOX_REPO_DIR
2275
2542
  );
2543
+ mountsToClean.push(...gitMounts);
2276
2544
  const startResult = yield* d.taskLog(
2277
2545
  "Starting sandbox",
2278
2546
  () => startSandbox({
@@ -2294,7 +2562,7 @@ var createWorktree = async (options) => {
2294
2562
  }
2295
2563
  const interactiveExecFn = handle.interactiveExec.bind(handle);
2296
2564
  const sandbox = makeSandboxFromHandle(handle);
2297
- const worktreePath = handle.worktreePath;
2565
+ const { worktreePath } = handle;
2298
2566
  const applyToHost = resolvedSandbox.tag === "isolated" ? () => syncOut(worktreeInfo.path, handle) : () => Effect_exports.void;
2299
2567
  const lifecycleEffect = withSandboxLifecycle(
2300
2568
  {
@@ -2317,13 +2585,13 @@ var createWorktree = async (options) => {
2317
2585
  ctx.sandbox,
2318
2586
  ctx.sandboxRepoDir
2319
2587
  );
2320
- const interactiveArgs = provider.buildInteractiveArgs({
2588
+ const interactiveArgs = buildInteractiveArgs({
2321
2589
  prompt: fullPrompt,
2322
2590
  dangerouslySkipPermissions: resolvedSandbox.tag !== "none"
2323
2591
  });
2324
2592
  const result = yield* raceAbortSignal(
2325
2593
  Effect_exports.promise(
2326
- () => interactiveExecFn(interactiveArgs, {
2594
+ async () => interactiveExecFn(interactiveArgs, {
2327
2595
  stdin: process.stdin,
2328
2596
  stdout: process.stdout,
2329
2597
  stderr: process.stderr,
@@ -2350,16 +2618,24 @@ var createWorktree = async (options) => {
2350
2618
  };
2351
2619
  }).pipe(
2352
2620
  // Always close sandbox handle
2353
- Effect_exports.ensuring(Effect_exports.promise(() => handle.close().catch(() => {
2354
- })))
2621
+ Effect_exports.ensuring(
2622
+ Effect_exports.promise(async () => handle.close().catch(() => {
2623
+ })).pipe(
2624
+ Effect_exports.andThen(removeMountTempDirs(mountsToClean))
2625
+ )
2626
+ )
2355
2627
  );
2356
2628
  });
2357
2629
  try {
2358
2630
  return await Effect_exports.runPromise(
2359
2631
  inner.pipe(
2360
- Effect_exports.provide(ClackDisplay.layer),
2361
- Effect_exports.provide(NodeContext_exports.layer),
2362
- Effect_exports.provide(NodeFileSystem_exports.layer)
2632
+ Effect_exports.provide(
2633
+ Layer_exports.mergeAll(
2634
+ ClackDisplay.layer,
2635
+ NodeContext_exports.layer,
2636
+ NodeFileSystem_exports.layer
2637
+ )
2638
+ )
2363
2639
  )
2364
2640
  );
2365
2641
  } catch (error) {
@@ -2372,12 +2648,14 @@ var createWorktree = async (options) => {
2372
2648
  const { prompt, promptFile, hooks, agent: provider } = opts;
2373
2649
  const sandboxProvider = opts.sandbox;
2374
2650
  const maxIterations = opts.maxIterations ?? 1;
2375
- if (opts.resumeSession && maxIterations > 1) {
2651
+ validateTimeoutOptions(opts);
2652
+ const isResuming = opts.resumeSession !== void 0 && opts.resumeSession !== "";
2653
+ if (isResuming && maxIterations > 1) {
2376
2654
  throw new Error(
2377
2655
  "resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
2378
2656
  );
2379
2657
  }
2380
- if (opts.resumeSession) {
2658
+ if (isResuming) {
2381
2659
  await assertResumeSessionExists({
2382
2660
  provider,
2383
2661
  sandboxTag: sandboxProvider.tag,
@@ -2395,7 +2673,7 @@ var createWorktree = async (options) => {
2395
2673
  agentProviderEnv: provider.env,
2396
2674
  sandboxProviderEnv: sandboxProvider.env
2397
2675
  });
2398
- const effectiveEnv = { ...env, ...opts.env ?? {} };
2676
+ const effectiveEnv = { ...env, ...opts.env };
2399
2677
  const userArgs = opts.promptArgs ?? {};
2400
2678
  let resolvedPrompt;
2401
2679
  if (isInlinePrompt) {
@@ -2403,9 +2681,10 @@ var createWorktree = async (options) => {
2403
2681
  resolvedPrompt = rawPrompt;
2404
2682
  } else {
2405
2683
  yield* validateNoBuiltInArgOverride(userArgs);
2684
+ const currentHostBranch = yield* getCurrentBranch(hostRepoDir);
2406
2685
  const effectiveArgs = {
2407
2686
  SOURCE_BRANCH: worktreeInfo.branch,
2408
- TARGET_BRANCH: worktreeInfo.branch,
2687
+ TARGET_BRANCH: currentHostBranch,
2409
2688
  ...userArgs
2410
2689
  };
2411
2690
  const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
@@ -2415,13 +2694,16 @@ var createWorktree = async (options) => {
2415
2694
  builtInArgKeysSet
2416
2695
  );
2417
2696
  }
2697
+ const mountsToClean = [];
2418
2698
  let handle;
2419
2699
  let sandboxRepoDir;
2420
2700
  if (sandboxProvider.tag === "isolated") {
2421
2701
  const startResult = yield* startSandbox({
2422
2702
  provider: sandboxProvider,
2423
2703
  hostRepoDir: worktreeInfo.path,
2424
- env: effectiveEnv
2704
+ env: effectiveEnv,
2705
+ copyPaths: options.copyToWorktree,
2706
+ copySourceDir: hostRepoDir
2425
2707
  });
2426
2708
  handle = startResult.handle;
2427
2709
  sandboxRepoDir = startResult.worktreePath;
@@ -2442,6 +2724,7 @@ var createWorktree = async (options) => {
2442
2724
  worktreeInfo.path,
2443
2725
  SANDBOX_REPO_DIR
2444
2726
  );
2727
+ mountsToClean.push(...gitMounts);
2445
2728
  const startResult = yield* startSandbox({
2446
2729
  provider: sandboxProvider,
2447
2730
  hostRepoDir,
@@ -2476,22 +2759,15 @@ var createWorktree = async (options) => {
2476
2759
  );
2477
2760
  })() : ClackDisplay.layer;
2478
2761
  const bindMountHandle = sandboxProvider.tag === "bind-mount" ? handle : void 0;
2479
- const reuseFactoryLayer = Layer_exports.succeed(SandboxFactory, {
2480
- withSandbox: (makeEffect) => makeEffect(
2481
- {
2482
- hostWorktreePath: worktreeInfo.path,
2483
- sandboxRepoPath: sandboxRepoDir,
2484
- applyToHost,
2485
- bindMountHandle
2486
- },
2487
- sandbox
2488
- ).pipe(
2489
- Effect_exports.map((value) => ({
2490
- value,
2491
- preservedWorktreePath: void 0
2492
- }))
2493
- )
2494
- });
2762
+ const reuseFactoryLayer = reuseSandboxFactoryLayer(
2763
+ {
2764
+ hostWorktreePath: worktreeInfo.path,
2765
+ sandboxRepoPath: sandboxRepoDir,
2766
+ applyToHost,
2767
+ bindMountHandle
2768
+ },
2769
+ sandbox
2770
+ );
2495
2771
  const streamEmitterLayer = agentStreamEmitterLayer(
2496
2772
  buildAgentStreamHandler(resolvedLogging)
2497
2773
  );
@@ -2537,8 +2813,12 @@ var createWorktree = async (options) => {
2537
2813
  }).pipe(
2538
2814
  Effect_exports.provide(runLayer),
2539
2815
  // Always close sandbox handle
2540
- Effect_exports.ensuring(Effect_exports.promise(() => handle.close().catch(() => {
2541
- })))
2816
+ Effect_exports.ensuring(
2817
+ Effect_exports.promise(async () => handle.close().catch(() => {
2818
+ })).pipe(
2819
+ Effect_exports.andThen(removeMountTempDirs(mountsToClean))
2820
+ )
2821
+ )
2542
2822
  );
2543
2823
  return {
2544
2824
  iterations: result.iterations,
@@ -2552,9 +2832,13 @@ var createWorktree = async (options) => {
2552
2832
  try {
2553
2833
  return await Effect_exports.runPromise(
2554
2834
  inner.pipe(
2555
- Effect_exports.provide(ClackDisplay.layer),
2556
- Effect_exports.provide(NodeContext_exports.layer),
2557
- Effect_exports.provide(NodeFileSystem_exports.layer)
2835
+ Effect_exports.provide(
2836
+ Layer_exports.mergeAll(
2837
+ ClackDisplay.layer,
2838
+ NodeContext_exports.layer,
2839
+ NodeFileSystem_exports.layer
2840
+ )
2841
+ )
2558
2842
  )
2559
2843
  );
2560
2844
  } catch (error) {
@@ -2562,19 +2846,19 @@ var createWorktree = async (options) => {
2562
2846
  throw error;
2563
2847
  }
2564
2848
  };
2565
- const worktreeCreateSandbox = async (opts) => {
2566
- return createSandboxFromWorktree({
2567
- branch: worktreeInfo.branch,
2568
- worktreePath: worktreeInfo.path,
2569
- hostRepoDir,
2570
- sandbox: opts.sandbox,
2571
- hooks: opts.hooks,
2572
- copyToWorktree: opts.copyToWorktree,
2573
- timeouts: opts.timeouts,
2574
- branchStrategy: options.branchStrategy,
2575
- _test: opts._test
2576
- });
2577
- };
2849
+ const worktreeCreateSandbox = async (opts) => createSandboxFromWorktree({
2850
+ branch: worktreeInfo.branch,
2851
+ worktreePath: worktreeInfo.path,
2852
+ hostRepoDir,
2853
+ sandbox: opts.sandbox,
2854
+ hooks: opts.hooks,
2855
+ // Isolated sandboxes sync in via git bundle, so the worktree's own
2856
+ // copyToWorktree files (often gitignored) must be copied in as well.
2857
+ copyToWorktree: opts.sandbox.tag === "isolated" ? [...options.copyToWorktree ?? [], ...opts.copyToWorktree ?? []] : opts.copyToWorktree,
2858
+ timeouts: opts.timeouts,
2859
+ branchStrategy: options.branchStrategy,
2860
+ _test: opts._test
2861
+ });
2578
2862
  return {
2579
2863
  branch: worktreeInfo.branch,
2580
2864
  worktreePath: worktreeInfo.path,
@@ -2587,894 +2871,13 @@ var createWorktree = async (options) => {
2587
2871
  }
2588
2872
  };
2589
2873
  };
2590
- var pathExists = async (path2) => {
2591
- try {
2592
- await access(path2);
2593
- return true;
2594
- } catch {
2595
- return false;
2596
- }
2597
- };
2598
- var encodeProjectPath = (cwd) => {
2599
- const isRoot = cwd === "/" || /^[A-Za-z]:[\\/]?$/.test(cwd);
2600
- const normalized = isRoot ? cwd : cwd.replace(/[\\/]+$/, "");
2601
- return normalized.replace(/^([A-Za-z]):/, "$1").replace(/[\\/]/g, "-");
2602
- };
2603
- var claudeHostSessionPath = (cwd, id, projectsDir) => {
2604
- const base = projectsDir ?? join(process.env.HOME ?? "~", ".claude", "projects");
2605
- return join(base, encodeProjectPath(cwd), `${id}.jsonl`);
2606
- };
2607
- var claudeSandboxSessionPath = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), `${id}.jsonl`);
2608
- var claudeSubagentsDirInSandbox = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), id, "subagents");
2609
- var claudeSubagentsDirOnHost = (cwd, id, projectsDir) => {
2610
- const base = projectsDir ?? join(process.env.HOME ?? "~", ".claude", "projects");
2611
- return join(base, encodeProjectPath(cwd), id, "subagents");
2612
- };
2613
- var listClaudeSubagentSessionsInSandbox = async (cwd, id, handle, sandboxProjectsDir) => {
2614
- const dir = claudeSubagentsDirInSandbox(cwd, id, sandboxProjectsDir);
2615
- const result = await handle.exec(
2616
- `find ${JSON.stringify(dir)} -type f -name ${JSON.stringify("agent-*.jsonl")} 2>/dev/null`
2617
- );
2618
- if (result.exitCode !== 0) return [];
2619
- const stdout = result.stdout.trim();
2620
- if (stdout === "") return [];
2621
- return stdout.split("\n").filter((line) => line !== "");
2622
- };
2623
- var findClaudeSessionOnHost = async (id, projectsDir) => {
2624
- const root = projectsDir ?? join(process.env.HOME ?? "~", ".claude", "projects");
2625
- let entries;
2626
- try {
2627
- entries = await readdir(root, { withFileTypes: true });
2628
- } catch {
2629
- return { path: void 0, searchedRoot: root };
2630
- }
2631
- for (const entry of entries) {
2632
- if (!entry.isDirectory()) continue;
2633
- const candidate = join(root, entry.name, `${id}.jsonl`);
2634
- if (await pathExists(candidate)) {
2635
- return { path: candidate, searchedRoot: root };
2636
- }
2637
- }
2638
- return { path: void 0, searchedRoot: root };
2639
- };
2640
- var rewriteSessionCwd = (content, fromCwd, toCwd) => {
2641
- if (content === "") return "";
2642
- return content.split("\n").map((line) => {
2643
- if (line === "") return line;
2644
- try {
2645
- const entry = JSON.parse(line);
2646
- if (typeof entry.cwd === "string" && entry.cwd === fromCwd) {
2647
- entry.cwd = toCwd;
2648
- }
2649
- if (entry.type === "session_meta" && typeof entry.payload === "object" && entry.payload !== null && typeof entry.payload.cwd === "string" && entry.payload.cwd === fromCwd) {
2650
- entry.payload.cwd = toCwd;
2651
- }
2652
- return JSON.stringify(entry);
2653
- } catch {
2654
- return line;
2655
- }
2656
- }).join("\n");
2657
- };
2658
- var transferClaudeSession = (jsonl, fromCwd, toCwd) => rewriteSessionCwd(jsonl, fromCwd, toCwd);
2659
- var isCodexSessionFilename = (filename, id) => filename.startsWith("rollout-") && filename.endsWith(`-${id}.jsonl`);
2660
- var findCodexSessionPath = async (rootDir, id) => {
2661
- const visit = async (dir) => {
2662
- let entries;
2663
- try {
2664
- entries = await readdir(dir, { withFileTypes: true });
2665
- } catch {
2666
- return void 0;
2667
- }
2668
- for (const entry of entries) {
2669
- const child = join(dir, entry.name);
2670
- if (entry.isFile() && isCodexSessionFilename(entry.name, id)) {
2671
- return child;
2672
- }
2673
- if (entry.isDirectory()) {
2674
- const found = await visit(child);
2675
- if (found) return found;
2676
- }
2677
- }
2678
- return void 0;
2679
- };
2680
- return visit(rootDir);
2681
- };
2682
- var findCodexSessionOnHost = async (id, sessionsDir) => {
2683
- const root = sessionsDir ?? join(process.env.HOME ?? "~", ".codex", "sessions");
2684
- const path2 = await findCodexSessionPath(root, id);
2685
- return { path: path2, searchedRoot: root };
2686
- };
2687
- var locateCodexHostSession = async (id, sessionsDir) => {
2688
- const root = sessionsDir ?? join(process.env.HOME ?? "~", ".codex", "sessions");
2689
- const path2 = await findCodexSessionPath(root, id);
2690
- if (!path2) throw new Error(`session ${id} not found in ${root}`);
2691
- return { path: path2, relativePath: relative(root, path2) };
2692
- };
2693
- var locateCodexSandboxSession = async (id, handle, sessionsDir) => {
2694
- const result = await handle.exec(
2695
- `find ${JSON.stringify(sessionsDir)} -type f -name ${JSON.stringify(`rollout-*-${id}.jsonl`)} -print -quit`
2696
- );
2697
- const path2 = result.stdout.trim().split("\n")[0];
2698
- if (result.exitCode !== 0 || !path2) {
2699
- throw new Error(`session ${id} not found in ${sessionsDir}`);
2700
- }
2701
- return { path: path2, relativePath: posix.relative(sessionsDir, path2) };
2702
- };
2703
- var transferCodexSession = (jsonl, fromCwd, toCwd) => rewriteSessionCwd(jsonl, fromCwd, toCwd);
2704
- var encodePiSessionDir = (cwd) => {
2705
- const stripped = cwd.replace(/^[/\\]/, "");
2706
- const replaced = stripped.replace(/[/\\:]/g, "-");
2707
- return `--${replaced}--`;
2708
- };
2709
- var piSessionDirPath = (cwd, sessionsDir) => {
2710
- const base = sessionsDir ?? join(process.env.HOME ?? "~", ".pi", "agent", "sessions");
2711
- return join(base, encodePiSessionDir(cwd));
2712
- };
2713
- var isPiSessionFilename = (filename, id) => filename.endsWith(`_${id}.jsonl`);
2714
- var findPiSessionPath = async (rootDir, id) => {
2715
- let entries;
2716
- try {
2717
- entries = await readdir(rootDir, { withFileTypes: true });
2718
- } catch {
2719
- return void 0;
2720
- }
2721
- for (const entry of entries) {
2722
- if (!entry.isDirectory()) continue;
2723
- const dirAbs = join(rootDir, entry.name);
2724
- let files;
2725
- try {
2726
- files = await readdir(dirAbs);
2727
- } catch {
2728
- continue;
2729
- }
2730
- const match = files.find((name) => isPiSessionFilename(name, id));
2731
- if (match) {
2732
- return {
2733
- path: join(dirAbs, match),
2734
- relativePath: join(entry.name, match)
2735
- };
2736
- }
2737
- }
2738
- return void 0;
2739
- };
2740
- var findPiSessionOnHost = async (id, sessionsDir) => {
2741
- const root = sessionsDir ?? join(process.env.HOME ?? "~", ".pi", "agent", "sessions");
2742
- const found = await findPiSessionPath(root, id);
2743
- return { path: found?.path, searchedRoot: root };
2744
- };
2745
- var locatePiHostSession = async (id, sessionsDir) => {
2746
- const root = sessionsDir ?? join(process.env.HOME ?? "~", ".pi", "agent", "sessions");
2747
- const found = await findPiSessionPath(root, id);
2748
- if (!found) throw new Error(`session ${id} not found in ${root}`);
2749
- return found;
2750
- };
2751
- var locatePiSandboxSession = async (id, handle, sessionsDir) => {
2752
- const result = await handle.exec(
2753
- `find ${JSON.stringify(sessionsDir)} -type f -name ${JSON.stringify(`*_${id}.jsonl`)} -print -quit`
2754
- );
2755
- const path2 = result.stdout.trim().split("\n")[0];
2756
- if (result.exitCode !== 0 || !path2) {
2757
- throw new Error(`session ${id} not found in ${sessionsDir}`);
2758
- }
2759
- return { path: path2, relativePath: posix.relative(sessionsDir, path2) };
2760
- };
2761
- var transferPiSession = (jsonl, fromCwd, toCwd) => {
2762
- if (jsonl === "") return "";
2763
- return jsonl.split("\n").map((line) => {
2764
- if (line === "") return line;
2765
- try {
2766
- const entry = JSON.parse(line);
2767
- if (entry.type === "session" && typeof entry.cwd === "string" && entry.cwd === fromCwd) {
2768
- entry.cwd = toCwd;
2769
- return JSON.stringify(entry);
2770
- }
2771
- return line;
2772
- } catch {
2773
- return line;
2774
- }
2775
- }).join("\n");
2776
- };
2777
2874
 
2778
2875
  // src/CwdError.ts
2779
2876
  var CwdError2 = CwdError;
2780
- var fileExists = async (path2) => {
2781
- try {
2782
- await access(path2);
2783
- return true;
2784
- } catch {
2785
- return false;
2786
- }
2787
- };
2788
- var shellEscape = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
2789
- var TOOL_ARG_FIELDS = {
2790
- Bash: "command",
2791
- WebSearch: "query",
2792
- WebFetch: "url",
2793
- Agent: "description"
2794
- };
2795
- var extractErrorMessage = (obj) => {
2796
- const err = obj.error;
2797
- if (typeof err === "string") return err;
2798
- if (typeof err === "object" && err !== null) {
2799
- if (typeof err.message === "string") return err.message;
2800
- if (typeof err.data?.message === "string") return err.data.message;
2801
- }
2802
- if (typeof obj.message === "string") return obj.message;
2803
- return void 0;
2804
- };
2805
- var parseStreamJsonLine = (line) => {
2806
- if (!line.startsWith("{")) return [];
2807
- try {
2808
- const obj = JSON.parse(line);
2809
- if (obj.type === "assistant" && Array.isArray(obj.message?.content)) {
2810
- const events = [];
2811
- const texts = [];
2812
- for (const block of obj.message.content) {
2813
- if (block.type === "text" && typeof block.text === "string") {
2814
- texts.push(block.text);
2815
- } else if (block.type === "tool_use" && typeof block.name === "string" && block.input !== void 0) {
2816
- const argField = TOOL_ARG_FIELDS[block.name];
2817
- if (argField === void 0) continue;
2818
- const argValue = block.input[argField];
2819
- if (typeof argValue !== "string") continue;
2820
- if (texts.length > 0) {
2821
- events.push({ type: "text", text: texts.join("") });
2822
- texts.length = 0;
2823
- }
2824
- events.push({
2825
- type: "tool_call",
2826
- name: block.name,
2827
- args: argValue
2828
- });
2829
- }
2830
- }
2831
- if (texts.length > 0) {
2832
- events.push({ type: "text", text: texts.join("") });
2833
- }
2834
- return events;
2835
- }
2836
- if (obj.type === "result" && typeof obj.result === "string") {
2837
- return [{ type: "result", result: obj.result }];
2838
- }
2839
- if (obj.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string") {
2840
- return [{ type: "session_id", sessionId: obj.session_id }];
2841
- }
2842
- } catch {
2843
- }
2844
- return [];
2845
- };
2846
- var CURSOR_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
2847
- function assertCursorPrintPromptFitsArgv(prompt) {
2848
- const n = Buffer.byteLength(prompt, "utf8");
2849
- if (n > CURSOR_PRINT_PROMPT_MAX_BYTES) {
2850
- throw new Error(
2851
- `Cursor print-mode prompt is ${n} bytes (max ${CURSOR_PRINT_PROMPT_MAX_BYTES} bytes). The Cursor CLI accepts the prompt only as a command-line argument; shorten the prompt or split the work. Other Sandcastle providers use stdin for large prompts.`
2852
- );
2853
- }
2854
- }
2855
- var parseCursorToolCallStarted = (obj) => {
2856
- if (obj.type !== "tool_call" || obj.subtype !== "started") return [];
2857
- const toolCall = obj.tool_call;
2858
- if (!toolCall || typeof toolCall !== "object") return [];
2859
- const tc = toolCall;
2860
- const readToolCall = tc.readToolCall;
2861
- if (readToolCall?.args && typeof readToolCall.args.path === "string") {
2862
- return [{ type: "tool_call", name: "Read", args: readToolCall.args.path }];
2863
- }
2864
- const writeToolCall = tc.writeToolCall;
2865
- if (writeToolCall?.args && typeof writeToolCall.args.path === "string") {
2866
- return [
2867
- { type: "tool_call", name: "Write", args: writeToolCall.args.path }
2868
- ];
2869
- }
2870
- const fn = tc.function;
2871
- if (fn && typeof fn.name === "string") {
2872
- const rawArgs = typeof fn.arguments === "string" ? fn.arguments : "";
2873
- if (rawArgs) {
2874
- try {
2875
- const parsedArgs = JSON.parse(rawArgs);
2876
- if (typeof parsedArgs.command === "string") {
2877
- return [
2878
- { type: "tool_call", name: "Bash", args: parsedArgs.command }
2879
- ];
2880
- }
2881
- } catch {
2882
- }
2883
- return [{ type: "tool_call", name: fn.name, args: rawArgs }];
2884
- }
2885
- return [{ type: "tool_call", name: fn.name, args: "" }];
2886
- }
2887
- return [];
2888
- };
2889
- var parseCursorStreamLine = (line) => {
2890
- if (!line.startsWith("{")) return [];
2891
- let obj;
2892
- try {
2893
- obj = JSON.parse(line);
2894
- } catch {
2895
- return [];
2896
- }
2897
- if (obj.type === "tool_call") {
2898
- return parseCursorToolCallStarted(obj);
2899
- }
2900
- return parseStreamJsonLine(line);
2901
- };
2902
- var readSandboxFile = async (handle, sandboxPath, tag) => {
2903
- const tmpPath = join(
2904
- tmpdir(),
2905
- `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
2906
- );
2907
- await handle.copyFileOut(sandboxPath, tmpPath);
2908
- try {
2909
- return await readFile(tmpPath, "utf-8");
2910
- } finally {
2911
- await rm(tmpPath, { force: true }).catch(() => {
2912
- });
2913
- }
2914
- };
2915
- var writeSandboxFile = async (handle, sandboxPath, content, tag) => {
2916
- const tmpPath = join(
2917
- tmpdir(),
2918
- `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
2919
- );
2920
- await writeFile(tmpPath, content);
2921
- try {
2922
- await handle.exec(`mkdir -p ${JSON.stringify(posix.dirname(sandboxPath))}`);
2923
- await handle.copyFileIn(tmpPath, sandboxPath);
2924
- } finally {
2925
- await rm(tmpPath, { force: true }).catch(() => {
2926
- });
2927
- }
2928
- };
2929
- var copyClaudeSessionFile = async ({
2930
- handle,
2931
- sourcePath,
2932
- fromCwd,
2933
- toCwd,
2934
- destPath,
2935
- tag
2936
- }) => {
2937
- const jsonl = await readSandboxFile(handle, sourcePath, tag);
2938
- const rewritten = transferClaudeSession(jsonl, fromCwd, toCwd);
2939
- await mkdir(dirname(destPath), { recursive: true });
2940
- await writeFile(destPath, rewritten);
2941
- };
2942
- var makeClaudeSessionStorage = (options) => {
2943
- const hostProjectsDir = options?.sessionStorage?.hostProjectsDir;
2944
- const sandboxProjectsDir = options?.sessionStorage?.sandboxProjectsDir ?? "/home/agent/.claude/projects";
2945
- return {
2946
- hostSessionFilePath: (cwd, id) => claudeHostSessionPath(cwd, id, hostProjectsDir),
2947
- existsOnHost: (cwd, id) => fileExists(claudeHostSessionPath(cwd, id, hostProjectsDir)),
2948
- readHostSession: async (cwd, id) => {
2949
- const path2 = claudeHostSessionPath(cwd, id, hostProjectsDir);
2950
- if (!await fileExists(path2)) return void 0;
2951
- return readFile(path2, "utf-8");
2952
- },
2953
- captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
2954
- await copyClaudeSessionFile({
2955
- handle,
2956
- sourcePath: claudeSandboxSessionPath(
2957
- sandboxCwd,
2958
- sessionId,
2959
- sandboxProjectsDir
2960
- ),
2961
- fromCwd: sandboxCwd,
2962
- toCwd: hostCwd,
2963
- destPath: claudeHostSessionPath(hostCwd, sessionId, hostProjectsDir),
2964
- tag: "claude-cap"
2965
- });
2966
- const subagentSandboxPaths = await listClaudeSubagentSessionsInSandbox(
2967
- sandboxCwd,
2968
- sessionId,
2969
- handle,
2970
- sandboxProjectsDir
2971
- );
2972
- const hostSubagentsDir = claudeSubagentsDirOnHost(
2973
- hostCwd,
2974
- sessionId,
2975
- hostProjectsDir
2976
- );
2977
- for (const sandboxSubagentPath of subagentSandboxPaths) {
2978
- try {
2979
- await copyClaudeSessionFile({
2980
- handle,
2981
- sourcePath: sandboxSubagentPath,
2982
- fromCwd: sandboxCwd,
2983
- toCwd: hostCwd,
2984
- destPath: join(
2985
- hostSubagentsDir,
2986
- posix.basename(sandboxSubagentPath)
2987
- ),
2988
- tag: "claude-sub"
2989
- });
2990
- } catch (err) {
2991
- console.error(
2992
- `sandcastle: failed to capture Claude subagent transcript ${sandboxSubagentPath}: ${err instanceof Error ? err.message : String(err)}`
2993
- );
2994
- }
2995
- }
2996
- },
2997
- resumeIntoSandbox: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
2998
- const hostPath = claudeHostSessionPath(
2999
- hostCwd,
3000
- sessionId,
3001
- hostProjectsDir
3002
- );
3003
- const jsonl = await readFile(hostPath, "utf-8");
3004
- const rewritten = transferClaudeSession(jsonl, hostCwd, sandboxCwd);
3005
- const sandboxPath = claudeSandboxSessionPath(
3006
- sandboxCwd,
3007
- sessionId,
3008
- sandboxProjectsDir
3009
- );
3010
- await writeSandboxFile(handle, sandboxPath, rewritten, "claude-res");
3011
- },
3012
- findByIdOnHost: (id) => findClaudeSessionOnHost(id, hostProjectsDir)
3013
- };
3014
- };
3015
- var makeCodexSessionStorage = (options) => {
3016
- const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
3017
- const sandboxSessionsDir = options?.sessionStorage?.sandboxSessionsDir ?? posix.join("/home/agent", ".codex", "sessions");
3018
- const capturedPaths = /* @__PURE__ */ new Map();
3019
- return {
3020
- hostSessionFilePath: (_cwd, id) => capturedPaths.get(id),
3021
- existsOnHost: async (_cwd, id) => {
3022
- const found = await findCodexSessionOnHost(id, hostSessionsDir);
3023
- return found.path !== void 0;
3024
- },
3025
- readHostSession: async (_cwd, id) => {
3026
- const found = await findCodexSessionOnHost(id, hostSessionsDir);
3027
- if (!found.path) return void 0;
3028
- return readFile(found.path, "utf-8");
3029
- },
3030
- captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
3031
- const located = await locateCodexSandboxSession(
3032
- sessionId,
3033
- handle,
3034
- sandboxSessionsDir
3035
- );
3036
- const jsonl = await readSandboxFile(handle, located.path, "codex-cap");
3037
- const rewritten = transferCodexSession(jsonl, sandboxCwd, hostCwd);
3038
- const root = hostSessionsDir ?? join(process.env.HOME ?? "~", ".codex", "sessions");
3039
- const target = join(root, located.relativePath);
3040
- await mkdir(dirname(target), { recursive: true });
3041
- await writeFile(target, rewritten);
3042
- capturedPaths.set(sessionId, target);
3043
- },
3044
- resumeIntoSandbox: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
3045
- const located = await locateCodexHostSession(sessionId, hostSessionsDir);
3046
- const jsonl = await readFile(located.path, "utf-8");
3047
- const rewritten = transferCodexSession(jsonl, hostCwd, sandboxCwd);
3048
- const target = posix.join(sandboxSessionsDir, located.relativePath);
3049
- await writeSandboxFile(handle, target, rewritten, "codex-res");
3050
- },
3051
- findByIdOnHost: (id) => findCodexSessionOnHost(id, hostSessionsDir)
3052
- };
3053
- };
3054
- var makePiSessionStorage = (options) => {
3055
- const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
3056
- const sandboxSessionsDir = options?.sessionStorage?.sandboxSessionsDir ?? posix.join("/home/agent", ".pi", "agent", "sessions");
3057
- return {
3058
- hostSessionFilePath: (cwd, _id) => piSessionDirPath(cwd, hostSessionsDir),
3059
- existsOnHost: async (_cwd, id) => {
3060
- const found = await findPiSessionOnHost(id, hostSessionsDir);
3061
- return found.path !== void 0;
3062
- },
3063
- readHostSession: async (_cwd, id) => {
3064
- const found = await findPiSessionOnHost(id, hostSessionsDir);
3065
- if (!found.path) return void 0;
3066
- return readFile(found.path, "utf-8");
3067
- },
3068
- captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
3069
- const located = await locatePiSandboxSession(
3070
- sessionId,
3071
- handle,
3072
- sandboxSessionsDir
3073
- );
3074
- const jsonl = await readSandboxFile(handle, located.path, "pi-cap");
3075
- const rewritten = transferPiSession(jsonl, sandboxCwd, hostCwd);
3076
- const filename = posix.basename(located.path);
3077
- const target = join(piSessionDirPath(hostCwd, hostSessionsDir), filename);
3078
- await mkdir(dirname(target), { recursive: true });
3079
- await writeFile(target, rewritten);
3080
- },
3081
- resumeIntoSandbox: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
3082
- const located = await locatePiHostSession(sessionId, hostSessionsDir);
3083
- const jsonl = await readFile(located.path, "utf-8");
3084
- const rewritten = transferPiSession(jsonl, hostCwd, sandboxCwd);
3085
- const filename = located.relativePath.split(/[\\/]/).pop();
3086
- const target = posix.join(
3087
- sandboxSessionsDir,
3088
- encodePiSessionDir(sandboxCwd),
3089
- filename
3090
- );
3091
- await writeSandboxFile(handle, target, rewritten, "pi-res");
3092
- },
3093
- findByIdOnHost: (id) => findPiSessionOnHost(id, hostSessionsDir)
3094
- };
3095
- };
3096
- var parsePiStreamLine = (line) => {
3097
- if (!line.startsWith("{")) return [];
3098
- try {
3099
- const obj = JSON.parse(line);
3100
- if (obj.type === "session" && typeof obj.id === "string") {
3101
- return [{ type: "session_id", sessionId: obj.id }];
3102
- }
3103
- if (obj.type === "message_update" && obj.assistantMessageEvent) {
3104
- const evt = obj.assistantMessageEvent;
3105
- if (evt.type === "text_delta" && typeof evt.delta === "string") {
3106
- return [{ type: "text", text: evt.delta }];
3107
- }
3108
- return [];
3109
- }
3110
- if (obj.type === "tool_execution_start") {
3111
- const toolName = obj.toolName;
3112
- if (typeof toolName !== "string") return [];
3113
- const argField = TOOL_ARG_FIELDS[toolName];
3114
- if (argField === void 0) return [];
3115
- const args = obj.args;
3116
- if (!args) return [];
3117
- const argValue = args[argField];
3118
- if (typeof argValue !== "string") return [];
3119
- return [{ type: "tool_call", name: toolName, args: argValue }];
3120
- }
3121
- if (obj.type === "agent_error" || obj.type === "error") {
3122
- const msg = extractErrorMessage(obj);
3123
- return msg ? [{ type: "result", result: msg }] : [];
3124
- }
3125
- if (obj.type === "agent_end" && Array.isArray(obj.messages)) {
3126
- const messages = obj.messages;
3127
- for (let i = messages.length - 1; i >= 0; i--) {
3128
- const msg = messages[i];
3129
- if (msg?.role === "assistant") {
3130
- const texts = [];
3131
- for (const block of msg.content) {
3132
- if (block.type === "text" && typeof block.text === "string") {
3133
- texts.push(block.text);
3134
- }
3135
- }
3136
- if (texts.length > 0) {
3137
- return [{ type: "result", result: texts.join("") }];
3138
- }
3139
- break;
3140
- }
3141
- }
3142
- return [];
3143
- }
3144
- } catch {
3145
- }
3146
- return [];
3147
- };
3148
- var pi = (model, options) => ({
3149
- name: "pi",
3150
- env: options?.env ?? {},
3151
- captureSessions: options?.captureSessions ?? true,
3152
- sessionStorage: makePiSessionStorage(options),
3153
- buildPrintCommand({
3154
- prompt,
3155
- resumeSession
3156
- }) {
3157
- const thinkingFlag = options?.thinking ? ` --thinking ${options.thinking}` : "";
3158
- const sessionFlag = resumeSession ? ` --session ${shellEscape(resumeSession)}` : "";
3159
- return {
3160
- command: `pi -p --mode json --model ${shellEscape(model)}${thinkingFlag}${sessionFlag}`,
3161
- stdin: prompt
3162
- };
3163
- },
3164
- buildInteractiveArgs({ prompt }) {
3165
- const args = ["pi", "--model", model];
3166
- if (prompt) args.push(prompt);
3167
- return args;
3168
- },
3169
- parseStreamLine(line) {
3170
- return parsePiStreamLine(line);
3171
- }
3172
- });
3173
- var parseCodexUsage = (usage) => {
3174
- if (typeof usage !== "object" || usage === null) return void 0;
3175
- const u = usage;
3176
- if (typeof u.input_tokens !== "number" || typeof u.cached_input_tokens !== "number" || typeof u.output_tokens !== "number") {
3177
- return void 0;
3178
- }
3179
- return {
3180
- inputTokens: u.input_tokens - u.cached_input_tokens,
3181
- cacheCreationInputTokens: 0,
3182
- cacheReadInputTokens: u.cached_input_tokens,
3183
- outputTokens: u.output_tokens
3184
- };
3185
- };
3186
- var parseCodexStreamLine = (line) => {
3187
- if (!line.startsWith("{")) return [];
3188
- try {
3189
- const obj = JSON.parse(line);
3190
- if (obj.type === "thread.started" && typeof obj.thread_id === "string") {
3191
- return [{ type: "session_id", sessionId: obj.thread_id }];
3192
- }
3193
- if (obj.type === "item.completed" && obj.item?.type === "agent_message" && typeof obj.item.text === "string") {
3194
- const text2 = obj.item.text;
3195
- return [
3196
- { type: "text", text: text2 },
3197
- { type: "result", result: text2 }
3198
- ];
3199
- }
3200
- if (obj.type === "item.started" && obj.item?.type === "command_execution" && typeof obj.item.command === "string") {
3201
- return [{ type: "tool_call", name: "Bash", args: obj.item.command }];
3202
- }
3203
- if (obj.type === "error") {
3204
- const msg = extractErrorMessage(obj);
3205
- return msg ? [{ type: "result", result: msg }] : [];
3206
- }
3207
- if (obj.type === "turn.completed") {
3208
- const usage = parseCodexUsage(obj.usage);
3209
- return usage ? [{ type: "usage", usage }] : [];
3210
- }
3211
- } catch {
3212
- }
3213
- return [];
3214
- };
3215
- var codex = (model, options) => ({
3216
- name: "codex",
3217
- env: options?.env ?? {},
3218
- captureSessions: options?.captureSessions ?? true,
3219
- sessionStorage: makeCodexSessionStorage(options),
3220
- buildPrintCommand({
3221
- prompt,
3222
- resumeSession,
3223
- forkSession
3224
- }) {
3225
- const effortFlag = options?.effort ? ` -c ${shellEscape(`model_reasoning_effort="${options.effort}"`)}` : "";
3226
- const approvalsFlags = options?.approvalsReviewer === "auto_review" ? ` -a on-request -s danger-full-access -c ${shellEscape(`approvals_reviewer="auto_review"`)}` : " --dangerously-bypass-approvals-and-sandbox";
3227
- let base;
3228
- if (resumeSession && forkSession) {
3229
- base = `codex exec fork ${shellEscape(resumeSession)}`;
3230
- } else if (resumeSession) {
3231
- base = `codex exec resume ${shellEscape(resumeSession)}`;
3232
- } else {
3233
- base = "codex exec";
3234
- }
3235
- const stdinArg = resumeSession ? " -" : "";
3236
- return {
3237
- command: `${base} --json${approvalsFlags} -m ${shellEscape(model)}${effortFlag}${stdinArg}`,
3238
- stdin: prompt
3239
- };
3240
- },
3241
- buildInteractiveArgs({ prompt }) {
3242
- const args = ["codex", "--model", model];
3243
- if (prompt) args.push(prompt);
3244
- return args;
3245
- },
3246
- parseStreamLine(line) {
3247
- return parseCodexStreamLine(line);
3248
- }
3249
- });
3250
- var cursor = (model, options) => ({
3251
- name: "cursor",
3252
- env: options?.env ?? {},
3253
- captureSessions: false,
3254
- // Cursor has no filesystem-backed session storage (captureSessions: false, no
3255
- // sessionStorage), so it is non-resumable per ADR 0012/0016. resumeSession is
3256
- // ignored here — like pi and opencode — rather than wired to --resume.
3257
- buildPrintCommand({
3258
- prompt,
3259
- dangerouslySkipPermissions
3260
- }) {
3261
- assertCursorPrintPromptFitsArgv(prompt);
3262
- const forceFlag = dangerouslySkipPermissions ? " --force" : "";
3263
- return {
3264
- command: `agent --print --output-format stream-json --model ${shellEscape(model)} ${forceFlag} ${shellEscape(prompt)}`
3265
- };
3266
- },
3267
- buildInteractiveArgs({
3268
- prompt,
3269
- dangerouslySkipPermissions
3270
- }) {
3271
- const args = ["agent", "--model", model];
3272
- if (dangerouslySkipPermissions) args.push("--force");
3273
- if (prompt) args.push(prompt);
3274
- return args;
3275
- },
3276
- parseStreamLine(line) {
3277
- return parseCursorStreamLine(line);
3278
- }
3279
- });
3280
- var OPENCODE_TOOL_ARG_FIELDS = {
3281
- bash: "command",
3282
- webfetch: "url",
3283
- task: "description"
3284
- };
3285
- var parseOpenCodeStreamLine = (line) => {
3286
- if (!line.startsWith("{")) return [];
3287
- try {
3288
- const obj = JSON.parse(line);
3289
- const part = obj.part;
3290
- if (obj.type === "step_start" && typeof obj.sessionID === "string") {
3291
- return [{ type: "session_id", sessionId: obj.sessionID }];
3292
- }
3293
- if (obj.type === "text" && part?.type === "text" && typeof part.text === "string") {
3294
- return [
3295
- { type: "text", text: part.text },
3296
- { type: "result", result: part.text }
3297
- ];
3298
- }
3299
- if (obj.type === "tool_use" && part?.type === "tool") {
3300
- if (typeof part.tool !== "string") return [];
3301
- const state = part.state;
3302
- if (state?.status !== "completed") return [];
3303
- const input = state.input;
3304
- if (!input) return [];
3305
- const argField = OPENCODE_TOOL_ARG_FIELDS[part.tool];
3306
- const argValue = argField !== void 0 ? input[argField] : void 0;
3307
- const args = typeof argValue === "string" ? argValue : JSON.stringify(input);
3308
- return [{ type: "tool_call", name: part.tool, args }];
3309
- }
3310
- if (obj.type === "error") {
3311
- const msg = extractErrorMessage(obj);
3312
- return msg ? [{ type: "result", result: msg }] : [];
3313
- }
3314
- } catch {
3315
- }
3316
- return [];
3317
- };
3318
- var opencode = (model, options) => ({
3319
- name: "opencode",
3320
- env: options?.env ?? {},
3321
- captureSessions: false,
3322
- buildPrintCommand({
3323
- prompt,
3324
- dangerouslySkipPermissions
3325
- }) {
3326
- const variantFlag = options?.variant ? ` --variant ${shellEscape(options.variant)}` : "";
3327
- const agentFlag = options?.agent ? ` --agent ${shellEscape(options.agent)}` : "";
3328
- const permissionsFlag = dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
3329
- return {
3330
- command: `opencode run --format json --model ${shellEscape(model)}${variantFlag}${agentFlag}${permissionsFlag} ${shellEscape(prompt)}`
3331
- };
3332
- },
3333
- buildInteractiveArgs({ prompt }) {
3334
- const args = ["opencode", "--model", model];
3335
- if (options?.agent) args.push("--agent", options.agent);
3336
- if (prompt) args.push("--prompt", prompt);
3337
- return args;
3338
- },
3339
- parseStreamLine(line) {
3340
- return parseOpenCodeStreamLine(line);
3341
- }
3342
- });
3343
- var COPILOT_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
3344
- function assertCopilotPrintPromptFitsArgv(prompt) {
3345
- const n = Buffer.byteLength(prompt, "utf8");
3346
- if (n > COPILOT_PRINT_PROMPT_MAX_BYTES) {
3347
- throw new Error(
3348
- `Copilot print-mode prompt is ${n} bytes (max ${COPILOT_PRINT_PROMPT_MAX_BYTES} bytes). This provider passes the prompt as a command-line argument; shorten the prompt or split the work. Other Sandcastle providers use stdin for large prompts.`
3349
- );
3350
- }
3351
- }
3352
- var parseCopilotStreamLine = (line) => {
3353
- if (!line.startsWith("{")) return [];
3354
- try {
3355
- const obj = JSON.parse(line);
3356
- if (obj.type === "assistant.message_delta" && typeof obj.data?.deltaContent === "string") {
3357
- return [{ type: "text", text: obj.data.deltaContent }];
3358
- }
3359
- if (obj.type === "tool.execution_start") {
3360
- const rawName = obj.data?.toolName;
3361
- if (typeof rawName !== "string") return [];
3362
- const toolName = rawName === "bash" ? "Bash" : rawName;
3363
- const argField = TOOL_ARG_FIELDS[toolName];
3364
- if (argField === void 0) return [];
3365
- const args = obj.data?.arguments;
3366
- if (!args) return [];
3367
- const argValue = args[argField];
3368
- if (typeof argValue !== "string") return [];
3369
- return [{ type: "tool_call", name: toolName, args: argValue }];
3370
- }
3371
- if (obj.type === "assistant.message" && typeof obj.data?.content === "string" && obj.data.content.length > 0) {
3372
- return [{ type: "result", result: obj.data.content }];
3373
- }
3374
- if (obj.type === "result" && typeof obj.sessionId === "string") {
3375
- return [{ type: "session_id", sessionId: obj.sessionId }];
3376
- }
3377
- if (obj.type === "error" || obj.type === "agent_error") {
3378
- const msg = extractErrorMessage(obj);
3379
- return msg ? [{ type: "result", result: msg }] : [];
3380
- }
3381
- } catch {
3382
- }
3383
- return [];
3384
- };
3385
- var copilot = (model, options) => ({
3386
- name: "copilot",
3387
- env: options?.env ?? {},
3388
- captureSessions: false,
3389
- // Copilot CLI does expose `--resume <id>`, but its session state is indexed by
3390
- // a SQLite database alongside the JSONL files in ~/.copilot/session-state/, so
3391
- // transferring a single session file between host and sandbox is not enough to
3392
- // make resume work (see ADR 0016). Until the round-trip is verified end-to-end,
3393
- // copilot is non-resumable: captureSessions is false, there is no sessionStorage,
3394
- // and resumeSession is ignored here — like cursor, pi, and opencode.
3395
- buildPrintCommand({
3396
- prompt,
3397
- dangerouslySkipPermissions
3398
- }) {
3399
- assertCopilotPrintPromptFitsArgv(prompt);
3400
- const allowAll = dangerouslySkipPermissions ? " --allow-all-tools" : "";
3401
- const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
3402
- return {
3403
- command: `copilot -p ${shellEscape(prompt)} --output-format json --model ${shellEscape(model)}${allowAll}${effortFlag}`
3404
- };
3405
- },
3406
- buildInteractiveArgs({ prompt }) {
3407
- const args = ["copilot", "--model", model];
3408
- if (prompt) args.push("-i", prompt);
3409
- return args;
3410
- },
3411
- parseStreamLine(line) {
3412
- return parseCopilotStreamLine(line);
3413
- }
3414
- });
3415
- var claudeCode = (model, options) => ({
3416
- name: "claude-code",
3417
- env: options?.env ?? {},
3418
- captureSessions: options?.captureSessions ?? true,
3419
- sessionStorage: makeClaudeSessionStorage(options),
3420
- buildPrintCommand({
3421
- prompt,
3422
- dangerouslySkipPermissions,
3423
- resumeSession,
3424
- forkSession
3425
- }) {
3426
- const permissionFlag = options?.permissionMode ? ` --permission-mode ${options.permissionMode}` : dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
3427
- const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
3428
- const resumeFlag = resumeSession ? ` --resume ${shellEscape(resumeSession)}` : "";
3429
- const forkFlag = resumeSession && forkSession ? " --fork-session" : "";
3430
- return {
3431
- command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag} -p -`,
3432
- stdin: prompt
3433
- };
3434
- },
3435
- buildInteractiveArgs({
3436
- prompt,
3437
- dangerouslySkipPermissions
3438
- }) {
3439
- const args = ["claude"];
3440
- if (options?.permissionMode) {
3441
- args.push("--permission-mode", options.permissionMode);
3442
- } else if (dangerouslySkipPermissions) {
3443
- args.push("--dangerously-skip-permissions");
3444
- }
3445
- args.push("--model", model);
3446
- if (options?.effort) args.push("--effort", options.effort);
3447
- if (prompt) args.push(prompt);
3448
- return args;
3449
- },
3450
- parseStreamLine(line) {
3451
- return parseStreamJsonLine(line);
3452
- },
3453
- parseSessionUsage(content) {
3454
- const lines = content.split("\n");
3455
- for (let i = lines.length - 1; i >= 0; i--) {
3456
- const line = lines[i];
3457
- if (!line.startsWith("{")) continue;
3458
- try {
3459
- const obj = JSON.parse(line);
3460
- if (obj.type === "assistant" && obj.message?.usage) {
3461
- const u = obj.message.usage;
3462
- if (typeof u.input_tokens === "number" && typeof u.cache_creation_input_tokens === "number" && typeof u.cache_read_input_tokens === "number" && typeof u.output_tokens === "number") {
3463
- return {
3464
- inputTokens: u.input_tokens,
3465
- cacheCreationInputTokens: u.cache_creation_input_tokens,
3466
- cacheReadInputTokens: u.cache_read_input_tokens,
3467
- outputTokens: u.output_tokens
3468
- };
3469
- }
3470
- }
3471
- } catch {
3472
- }
3473
- }
3474
- return void 0;
3475
- }
3476
- });
3477
2877
 
3478
- export { CwdError2 as CwdError, Output, StructuredOutputError, claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, createSandbox, createWorktree, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, interactive, opencode, pi, run, transferClaudeSession, transferCodexSession };
2878
+ // src/SyncOutPathError.ts
2879
+ var SyncOutPathError2 = SyncOutPathError;
2880
+
2881
+ export { CwdError2 as CwdError, Output, StructuredOutputError, SyncOutPathError2 as SyncOutPathError, createSandbox, createWorktree, interactive, run };
3479
2882
  //# sourceMappingURL=index.js.map
3480
2883
  //# sourceMappingURL=index.js.map