@ai-hero/sandcastle 0.13.0 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-CwRLxIXZ.d.ts} +5 -41
- package/dist/{chunk-XCYK7I45.js → chunk-4BB7DNPW.js} +3 -3
- package/dist/chunk-4BB7DNPW.js.map +1 -0
- package/dist/chunk-4GZMUHVO.js +60 -0
- package/dist/chunk-4GZMUHVO.js.map +1 -0
- package/dist/{chunk-A4C2FG74.js → chunk-7JUTKCHL.js} +43 -42
- package/dist/chunk-7JUTKCHL.js.map +1 -0
- package/dist/chunk-7PHPLDVS.js +284 -0
- package/dist/chunk-7PHPLDVS.js.map +1 -0
- package/dist/{chunk-NMQ5Z6YG.js → chunk-BXLS4HRY.js} +15 -4
- package/dist/chunk-BXLS4HRY.js.map +1 -0
- package/dist/chunk-EM4QNWKF.js +3161 -0
- package/dist/chunk-EM4QNWKF.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/{chunk-LWNC4UTZ.js → chunk-JEQ4IVQM.js} +1520 -5375
- package/dist/chunk-JEQ4IVQM.js.map +1 -0
- package/dist/{chunk-XCWKLDH4.js → chunk-L3BU47F6.js} +3 -3
- package/dist/{chunk-XCWKLDH4.js.map → chunk-L3BU47F6.js.map} +1 -1
- package/dist/{chunk-7N7AMUYA.js → chunk-PTJEKJPQ.js} +7 -5
- package/dist/chunk-PTJEKJPQ.js.map +1 -0
- package/dist/chunk-SAQXFLO2.js +1268 -0
- package/dist/chunk-SAQXFLO2.js.map +1 -0
- package/dist/{chunk-767EAJVT.js → chunk-TBVRAXYF.js} +3 -3
- package/dist/{chunk-767EAJVT.js.map → chunk-TBVRAXYF.js.map} +1 -1
- package/dist/{chunk-J5J5YJ5S.js → chunk-VUOXFCWO.js} +3 -3
- package/dist/{chunk-J5J5YJ5S.js.map → chunk-VUOXFCWO.js.map} +1 -1
- package/dist/{chunk-U42XXICG.js → chunk-WYOGXC72.js} +47 -82
- package/dist/chunk-WYOGXC72.js.map +1 -0
- package/dist/chunk-YDQW5IOY.js +799 -0
- package/dist/chunk-YDQW5IOY.js.map +1 -0
- package/dist/index.d.ts +51 -4
- package/dist/index.js +892 -2018
- package/dist/index.js.map +1 -1
- package/dist/main.js +322 -251
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -14
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +183 -136
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +23 -1
- package/dist/sandboxes/docker.js +7 -3
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/no-sandbox.js +1 -1
- package/dist/sandboxes/podman.d.ts +27 -4
- package/dist/sandboxes/podman.js +19 -43
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +2 -2
- package/dist/sandboxes/seatbelt.js +10 -7
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +219 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +10 -1
- package/dist/sandboxes/vercel.js +74 -46
- package/dist/sandboxes/vercel.js.map +1 -1
- package/dist/templates/parallel-planner/main.mts +43 -21
- package/dist/templates/parallel-planner-with-review/main.mts +55 -27
- package/dist/templates/sequential-reviewer/main.mts +1 -1
- package/package.json +36 -4
- package/dist/chunk-4EIVTSOZ.js +0 -93
- package/dist/chunk-4EIVTSOZ.js.map +0 -1
- package/dist/chunk-7N7AMUYA.js.map +0 -1
- package/dist/chunk-A4C2FG74.js.map +0 -1
- package/dist/chunk-LWNC4UTZ.js.map +0 -1
- package/dist/chunk-NMQ5Z6YG.js.map +0 -1
- package/dist/chunk-U42XXICG.js.map +0 -1
- package/dist/chunk-XCYK7I45.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
import { NodeContext_exports, NodeFileSystem_exports } from './chunk-
|
|
7
|
-
export { NativeSandboxUnavailableError } from './chunk-
|
|
8
|
-
import {
|
|
9
|
-
|
|
2
|
+
import { noSandbox } from './chunk-PTJEKJPQ.js';
|
|
3
|
+
import { assertInteractiveSupported } from './chunk-L3BU47F6.js';
|
|
4
|
+
export { NativeInteractiveNotSupportedError } from './chunk-L3BU47F6.js';
|
|
5
|
+
import { Display, getCurrentBranch, generateTempBranchName, pruneStale, create, copyToWorktree, runHostHooks, startSandbox, resolveGitMounts, remove, syncOut, withSandboxLifecycle, hasUncommittedChanges, ClackDisplay, deleteTempBranchIfUnused, startIsolatedSandbox, formatErrorMessage, startBindMountSandbox, FileDisplay, reuseSandboxFactoryLayer, SandboxFactory, WorktreeDockerSandboxFactory, SandboxConfig, execOk, SilentDisplay } from './chunk-EM4QNWKF.js';
|
|
6
|
+
import { NodeContext_exports, NodeFileSystem_exports } from './chunk-7JUTKCHL.js';
|
|
7
|
+
export { NativeSandboxUnavailableError } from './chunk-7JUTKCHL.js';
|
|
8
|
+
import { patchGitMountsForWindows, SANDBOX_REPO_DIR, removeMountTempDirs, makeSandboxFromHandle } from './chunk-7PHPLDVS.js';
|
|
9
|
+
import { registerShutdown } from './chunk-EXYXBRCX.js';
|
|
10
|
+
import { shellEscape } from './chunk-SAQXFLO2.js';
|
|
11
|
+
export { claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, opencode, pi, transferClaudeSession, transferCodexSession } from './chunk-SAQXFLO2.js';
|
|
12
|
+
import { CwdError, SyncOutPathError, resolveCwd, PromptError, FileSystem_exports, SessionCaptureError, ForkNotSupportedError, PromptExpansionTimeoutError, AgentError, AgentIdleTimeoutError } from './chunk-YDQW5IOY.js';
|
|
13
|
+
import { Context_exports, Effect_exports, Layer_exports, Deferred_exports, Runtime_exports, Fiber_exports, Clock_exports, Duration_exports, Option_exports, Ref_exports } from './chunk-JEQ4IVQM.js';
|
|
14
|
+
export { createBindMountSandboxProvider, createIsolatedSandboxProvider } from './chunk-4BB7DNPW.js';
|
|
10
15
|
import './chunk-6NQPCXSG.js';
|
|
11
16
|
import { mkdirSync, appendFileSync, openSync, fstatSync, readSync, closeSync } from 'fs';
|
|
12
|
-
import path, { join
|
|
13
|
-
import {
|
|
17
|
+
import path, { join } from 'path';
|
|
18
|
+
import { inspect, styleText } from 'util';
|
|
14
19
|
import * as clack from '@clack/prompts';
|
|
15
|
-
import { readdir, mkdir, writeFile, readFile, access, rm } from 'fs/promises';
|
|
16
|
-
import { tmpdir } from 'os';
|
|
17
|
-
import { createHash } from 'crypto';
|
|
18
20
|
|
|
19
21
|
createRequire(import.meta.url);
|
|
20
22
|
|
|
@@ -218,6 +220,12 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
|
|
|
218
220
|
let sessionId;
|
|
219
221
|
let usage;
|
|
220
222
|
let accumulatedOutput = "";
|
|
223
|
+
const getResult = (fallback) => {
|
|
224
|
+
if (resultText !== "" && accumulatedOutput.endsWith(resultText)) {
|
|
225
|
+
return accumulatedOutput;
|
|
226
|
+
}
|
|
227
|
+
return resultText === "" ? fallback : resultText;
|
|
228
|
+
};
|
|
221
229
|
const timeoutSignal = yield* Deferred_exports.make();
|
|
222
230
|
const completionTimeoutDeferred = yield* Deferred_exports.make();
|
|
223
231
|
const runFork = Runtime_exports.runFork(yield* Effect_exports.runtime());
|
|
@@ -252,7 +260,7 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
|
|
|
252
260
|
yield* Effect_exports.sleep(Duration_exports.millis(completionTimeoutMs));
|
|
253
261
|
onCompletionTimeout(completionTimeoutMs);
|
|
254
262
|
yield* Deferred_exports.succeed(completionTimeoutDeferred, {
|
|
255
|
-
result:
|
|
263
|
+
result: getResult(accumulatedOutput),
|
|
256
264
|
sessionId,
|
|
257
265
|
usage
|
|
258
266
|
});
|
|
@@ -313,7 +321,6 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
|
|
|
313
321
|
onContextWindow(parsed.contextWindow);
|
|
314
322
|
} else if (parsed.type === "result") {
|
|
315
323
|
resultText = parsed.result;
|
|
316
|
-
accumulatedOutput += parsed.result;
|
|
317
324
|
} else if (parsed.type === "tool_call") {
|
|
318
325
|
onToolCall(parsed.name, parsed.args);
|
|
319
326
|
} else if (parsed.type === "session_id") {
|
|
@@ -324,7 +331,9 @@ var invokeAgent = (sandbox, sandboxRepoDir, prompt, provider, idleTimeoutMs, com
|
|
|
324
331
|
streamError = parsed.message;
|
|
325
332
|
}
|
|
326
333
|
}
|
|
327
|
-
if (!completionDetected && completionSignals.some(
|
|
334
|
+
if (!completionDetected && completionSignals.some(
|
|
335
|
+
(sig) => accumulatedOutput.includes(sig) || resultText.includes(sig)
|
|
336
|
+
)) {
|
|
328
337
|
completionDetected = true;
|
|
329
338
|
interruptFiber(warningFiber);
|
|
330
339
|
warningFiber = null;
|
|
@@ -357,7 +366,7 @@ ${errorDetail}`
|
|
|
357
366
|
${streamError}`
|
|
358
367
|
});
|
|
359
368
|
}
|
|
360
|
-
return { result:
|
|
369
|
+
return { result: getResult(execResult.stdout), sessionId, usage };
|
|
361
370
|
}).pipe(
|
|
362
371
|
Effect_exports.ensuring(
|
|
363
372
|
Effect_exports.sync(() => {
|
|
@@ -455,9 +464,17 @@ var orchestrate = (options) => {
|
|
|
455
464
|
ctx.sandboxRepoDir
|
|
456
465
|
);
|
|
457
466
|
yield* display.status(label("Agent started"), "success");
|
|
467
|
+
const pendingOutput = /* @__PURE__ */ new Set();
|
|
468
|
+
const forkOutput = (effect) => {
|
|
469
|
+
const fiber = runFork(effect);
|
|
470
|
+
pendingOutput.add(fiber);
|
|
471
|
+
fiber.addObserver(() => {
|
|
472
|
+
pendingOutput.delete(fiber);
|
|
473
|
+
});
|
|
474
|
+
};
|
|
458
475
|
const textBuffer = new TextDeltaBuffer((chunk) => {
|
|
459
|
-
|
|
460
|
-
|
|
476
|
+
forkOutput(display.textChunk(chunk));
|
|
477
|
+
forkOutput(
|
|
461
478
|
streamEmitter.emit({
|
|
462
479
|
type: "text",
|
|
463
480
|
message: chunk,
|
|
@@ -471,8 +488,8 @@ var orchestrate = (options) => {
|
|
|
471
488
|
};
|
|
472
489
|
const onToolCall = (name, formattedArgs) => {
|
|
473
490
|
textBuffer.flush();
|
|
474
|
-
|
|
475
|
-
|
|
491
|
+
forkOutput(display.toolCall(name, formattedArgs));
|
|
492
|
+
forkOutput(
|
|
476
493
|
streamEmitter.emit({
|
|
477
494
|
type: "toolCall",
|
|
478
495
|
name,
|
|
@@ -483,7 +500,7 @@ var orchestrate = (options) => {
|
|
|
483
500
|
);
|
|
484
501
|
};
|
|
485
502
|
const onRawLine = (line) => {
|
|
486
|
-
|
|
503
|
+
forkOutput(
|
|
487
504
|
streamEmitter.emit({
|
|
488
505
|
type: "raw",
|
|
489
506
|
line,
|
|
@@ -494,10 +511,10 @@ var orchestrate = (options) => {
|
|
|
494
511
|
};
|
|
495
512
|
const onIdleWarning = (minutes) => {
|
|
496
513
|
const msg = minutes === 1 ? "Agent idle for 1 minute" : `Agent idle for ${minutes} minutes`;
|
|
497
|
-
|
|
514
|
+
forkOutput(display.status(label(msg), "warn"));
|
|
498
515
|
};
|
|
499
516
|
const onCompletionTimeout = (timeoutMs) => {
|
|
500
|
-
|
|
517
|
+
forkOutput(
|
|
501
518
|
display.status(
|
|
502
519
|
label(
|
|
503
520
|
`Completion signal seen but agent process is hanging \u2014 force-completing after ${timeoutMs / 1e3}s grace window.`
|
|
@@ -532,8 +549,16 @@ var orchestrate = (options) => {
|
|
|
532
549
|
iterationResumeSession,
|
|
533
550
|
iterationForkSession,
|
|
534
551
|
options.signal
|
|
552
|
+
).pipe(
|
|
553
|
+
// On every exit, abort included: flush the buffered text
|
|
554
|
+
// deltas, then wait for the output forked so far.
|
|
555
|
+
Effect_exports.ensuring(
|
|
556
|
+
Effect_exports.suspend(() => {
|
|
557
|
+
textBuffer.dispose();
|
|
558
|
+
return Fiber_exports.awaitAll([...pendingOutput]);
|
|
559
|
+
})
|
|
560
|
+
)
|
|
535
561
|
);
|
|
536
|
-
textBuffer.dispose();
|
|
537
562
|
yield* display.status(label("Agent stopped"), "info");
|
|
538
563
|
let sessionFilePath;
|
|
539
564
|
let usage = streamUsage;
|
|
@@ -1228,83 +1253,92 @@ var followUpRun = (options, result, kind) => async (followUpPrompt, followUpOpti
|
|
|
1228
1253
|
...kind === "fork" ? { forkSession: true } : {}
|
|
1229
1254
|
});
|
|
1230
1255
|
};
|
|
1231
|
-
async
|
|
1232
|
-
options.signal?.throwIfAborted();
|
|
1233
|
-
const {
|
|
1234
|
-
prompt,
|
|
1235
|
-
promptFile,
|
|
1236
|
-
maxIterations = DEFAULT_MAX_ITERATIONS,
|
|
1237
|
-
hooks,
|
|
1238
|
-
agent: provider
|
|
1239
|
-
} = options;
|
|
1240
|
-
const branchStrategy = options.branchStrategy ?? (options.sandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
|
|
1241
|
-
const effectiveBranchType = branchStrategy.type;
|
|
1242
|
-
validateTimeoutOptions(options);
|
|
1243
|
-
validateBranchOptions(options, effectiveBranchType);
|
|
1244
|
-
const isResuming = validateSessionOptions(options, maxIterations);
|
|
1245
|
-
const outputMaxRetries = validateOutputOptions(options, maxIterations);
|
|
1246
|
-
const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
|
|
1256
|
+
var resolveRunHostRepoDir = async (options, isResuming) => {
|
|
1247
1257
|
const hostRepoDir = await Effect_exports.runPromise(
|
|
1248
1258
|
resolveCwd(options.cwd).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1249
1259
|
);
|
|
1250
1260
|
if (isResuming && options.resumeSession !== void 0) {
|
|
1251
1261
|
await assertResumeSessionExists({
|
|
1252
|
-
provider,
|
|
1262
|
+
provider: options.agent,
|
|
1253
1263
|
sandboxTag: options.sandbox.tag,
|
|
1254
1264
|
hostRepoDir,
|
|
1255
1265
|
resumeSession: options.resumeSession
|
|
1256
1266
|
});
|
|
1257
1267
|
}
|
|
1268
|
+
return hostRepoDir;
|
|
1269
|
+
};
|
|
1270
|
+
var resolveBranchStrategy = (options) => options.branchStrategy ?? (options.sandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
|
|
1271
|
+
var resolveRunPrompt = async (options) => {
|
|
1258
1272
|
const resolved = await Effect_exports.runPromise(
|
|
1259
|
-
resolvePrompt({
|
|
1260
|
-
|
|
1261
|
-
|
|
1273
|
+
resolvePrompt({
|
|
1274
|
+
prompt: options.prompt,
|
|
1275
|
+
promptFile: options.promptFile
|
|
1276
|
+
}).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1262
1277
|
);
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
if (!rawPrompt.includes(openTag)) {
|
|
1268
|
-
throw new Error(
|
|
1269
|
-
`output tag <${options.output.tag}> not found in the resolved prompt. The caller must instruct the agent to emit the configured tag.`
|
|
1270
|
-
);
|
|
1271
|
-
}
|
|
1278
|
+
if (options.output && !resolved.text.includes(`<${options.output.tag}>`)) {
|
|
1279
|
+
throw new Error(
|
|
1280
|
+
`output tag <${options.output.tag}> not found in the resolved prompt. The caller must instruct the agent to emit the configured tag.`
|
|
1281
|
+
);
|
|
1272
1282
|
}
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
sandboxProviderEnv: options.sandbox.env
|
|
1281
|
-
});
|
|
1283
|
+
return {
|
|
1284
|
+
rawPrompt: resolved.text,
|
|
1285
|
+
isInlinePrompt: resolved.source === "inline"
|
|
1286
|
+
};
|
|
1287
|
+
};
|
|
1288
|
+
var resolveRunBranches = async (options, branchStrategy, hostRepoDir) => {
|
|
1289
|
+
const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
|
|
1282
1290
|
const currentHostBranch = await Effect_exports.runPromise(
|
|
1283
1291
|
getCurrentBranch(hostRepoDir)
|
|
1284
1292
|
);
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
)
|
|
1293
|
+
return {
|
|
1294
|
+
currentHostBranch,
|
|
1295
|
+
// When in merge-to-head mode, generate a temporary branch name.
|
|
1296
|
+
// In head mode, use the host's current branch directly (no worktree).
|
|
1297
|
+
resolvedBranch: branchStrategy.type === "head" ? currentHostBranch : branch ?? generateTempBranchName(options.name),
|
|
1298
|
+
// When using a temp branch, prefix the log filename with the target branch
|
|
1299
|
+
// (the host's current branch) so developers can tell which branch was targeted.
|
|
1300
|
+
targetBranch: branchStrategy.type === "merge-to-head" ? currentHostBranch : void 0,
|
|
1301
|
+
// In head mode, pass the host branch so SandboxLifecycle skips the merge step.
|
|
1302
|
+
// In merge-to-head mode, branch is undefined (triggers merge). In branch mode, it's the explicit branch.
|
|
1303
|
+
orchestrateBranch: branchStrategy.type === "head" ? currentHostBranch : branch
|
|
1295
1304
|
};
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1305
|
+
};
|
|
1306
|
+
var resolveRunEnv = async (options, hostRepoDir) => mergeProviderEnv({
|
|
1307
|
+
resolvedEnv: await Effect_exports.runPromise(
|
|
1308
|
+
resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1309
|
+
),
|
|
1310
|
+
agentProviderEnv: options.agent.env,
|
|
1311
|
+
sandboxProviderEnv: options.sandbox.env
|
|
1312
|
+
});
|
|
1313
|
+
var resolveRunLogging = (options, hostRepoDir, { resolvedBranch, targetBranch }) => options.logging ?? {
|
|
1314
|
+
type: "file",
|
|
1315
|
+
path: join(
|
|
1316
|
+
hostRepoDir,
|
|
1317
|
+
".sandcastle",
|
|
1318
|
+
"logs",
|
|
1319
|
+
buildLogFilename(resolvedBranch, targetBranch, options.name)
|
|
1320
|
+
)
|
|
1321
|
+
};
|
|
1322
|
+
var buildDisplayLayer = ({
|
|
1323
|
+
options,
|
|
1324
|
+
hostRepoDir,
|
|
1325
|
+
branches,
|
|
1326
|
+
logging
|
|
1327
|
+
}) => {
|
|
1328
|
+
if (logging.type !== "file") {
|
|
1329
|
+
return ClackDisplay.layer;
|
|
1330
|
+
}
|
|
1331
|
+
printFileDisplayStartup({
|
|
1332
|
+
logPath: logging.path,
|
|
1333
|
+
agentName: options.name,
|
|
1334
|
+
branch: branches.resolvedBranch,
|
|
1335
|
+
hostRepoDir
|
|
1336
|
+
});
|
|
1337
|
+
return Layer_exports.provide(FileDisplay.layer(logging.path), NodeFileSystem_exports.layer);
|
|
1338
|
+
};
|
|
1339
|
+
var buildRunLayer = (setup) => {
|
|
1340
|
+
const { options, hostRepoDir, branchStrategy, branches, env } = setup;
|
|
1341
|
+
const displayLayer = buildDisplayLayer(setup);
|
|
1308
1342
|
const factoryLayer = Layer_exports.provide(
|
|
1309
1343
|
WorktreeDockerSandboxFactory.layer,
|
|
1310
1344
|
Layer_exports.mergeAll(
|
|
@@ -1315,10 +1349,10 @@ async function run(options) {
|
|
|
1315
1349
|
name: options.name,
|
|
1316
1350
|
// Create the worktree on the temp branch already shown to the user,
|
|
1317
1351
|
// rather than letting WorktreeManager generate a second name.
|
|
1318
|
-
tempBranch:
|
|
1352
|
+
tempBranch: branchStrategy.type === "merge-to-head" ? branches.resolvedBranch : void 0,
|
|
1319
1353
|
sandboxProvider: options.sandbox,
|
|
1320
1354
|
branchStrategy,
|
|
1321
|
-
hooks,
|
|
1355
|
+
hooks: options.hooks,
|
|
1322
1356
|
signal: options.signal,
|
|
1323
1357
|
timeouts: options.timeouts
|
|
1324
1358
|
}),
|
|
@@ -1326,54 +1360,60 @@ async function run(options) {
|
|
|
1326
1360
|
displayLayer
|
|
1327
1361
|
)
|
|
1328
1362
|
);
|
|
1329
|
-
|
|
1330
|
-
buildAgentStreamHandler(resolvedLogging)
|
|
1331
|
-
);
|
|
1332
|
-
const runLayer = Layer_exports.mergeAll(
|
|
1363
|
+
return Layer_exports.mergeAll(
|
|
1333
1364
|
factoryLayer,
|
|
1334
1365
|
displayLayer,
|
|
1335
|
-
|
|
1366
|
+
agentStreamEmitterLayer(buildAgentStreamHandler(setup.logging))
|
|
1336
1367
|
);
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1368
|
+
};
|
|
1369
|
+
var runIterations = ({
|
|
1370
|
+
options,
|
|
1371
|
+
hostRepoDir,
|
|
1372
|
+
maxIterations,
|
|
1373
|
+
branches,
|
|
1374
|
+
rawPrompt,
|
|
1375
|
+
isInlinePrompt
|
|
1376
|
+
}) => Effect_exports.gen(function* () {
|
|
1377
|
+
const d = yield* Display;
|
|
1378
|
+
yield* d.intro(options.name ?? "sandcastle");
|
|
1379
|
+
const rows = buildRunSummaryRows({
|
|
1380
|
+
name: options.name,
|
|
1381
|
+
agentName: options.agent.name,
|
|
1382
|
+
sandboxName: options.sandbox.name,
|
|
1383
|
+
maxIterations,
|
|
1384
|
+
branch: branches.resolvedBranch
|
|
1385
|
+
});
|
|
1386
|
+
yield* d.summary("Sandcastle Run", rows);
|
|
1387
|
+
const resolvedPrompt = yield* buildAgentPrompt({
|
|
1388
|
+
rawPrompt,
|
|
1389
|
+
isInlinePrompt,
|
|
1390
|
+
userArgs: options.promptArgs ?? {},
|
|
1391
|
+
sourceBranch: branches.resolvedBranch,
|
|
1392
|
+
targetBranch: branches.currentHostBranch
|
|
1393
|
+
});
|
|
1394
|
+
const orchestrateResult = yield* orchestrate({
|
|
1395
|
+
hostRepoDir,
|
|
1396
|
+
iterations: maxIterations,
|
|
1397
|
+
hooks: options.hooks,
|
|
1398
|
+
prompt: resolvedPrompt,
|
|
1399
|
+
branch: branches.orchestrateBranch,
|
|
1400
|
+
provider: options.agent,
|
|
1401
|
+
completionSignal: options.completionSignal,
|
|
1402
|
+
idleTimeoutSeconds: options.idleTimeoutSeconds,
|
|
1403
|
+
completionTimeoutSeconds: options.completionTimeoutSeconds,
|
|
1404
|
+
name: options.name,
|
|
1405
|
+
resumeSession: options.resumeSession,
|
|
1406
|
+
forkSession: options.forkSession,
|
|
1407
|
+
signal: options.signal,
|
|
1408
|
+
skipPromptExpansion: isInlinePrompt,
|
|
1409
|
+
timeouts: options.timeouts
|
|
1375
1410
|
});
|
|
1376
|
-
|
|
1411
|
+
yield* reportRunEnd(orchestrateResult);
|
|
1412
|
+
return orchestrateResult;
|
|
1413
|
+
});
|
|
1414
|
+
var executeRun = async (setup) => {
|
|
1415
|
+
const baseEffect = runIterations(setup);
|
|
1416
|
+
const withErrorLog = setup.logging.type === "file" ? baseEffect.pipe(
|
|
1377
1417
|
Effect_exports.tapError(
|
|
1378
1418
|
(error) => Effect_exports.gen(function* () {
|
|
1379
1419
|
const d = yield* Display;
|
|
@@ -1381,60 +1421,103 @@ async function run(options) {
|
|
|
1381
1421
|
})
|
|
1382
1422
|
)
|
|
1383
1423
|
) : baseEffect;
|
|
1384
|
-
|
|
1424
|
+
const runLayer = buildRunLayer(setup);
|
|
1385
1425
|
try {
|
|
1386
|
-
|
|
1387
|
-
|
|
1426
|
+
return await Effect_exports.runPromise(withErrorLog.pipe(Effect_exports.provide(runLayer)));
|
|
1427
|
+
} catch (error) {
|
|
1428
|
+
setup.options.signal?.throwIfAborted();
|
|
1429
|
+
throw error;
|
|
1430
|
+
}
|
|
1431
|
+
};
|
|
1432
|
+
var withStructuredOutput = async (options, baseResult, outputMaxRetries) => {
|
|
1433
|
+
const lastIteration = baseResult.iterations.at(-1);
|
|
1434
|
+
try {
|
|
1435
|
+
const output = await extractStructuredOutput(
|
|
1436
|
+
baseResult.stdout,
|
|
1437
|
+
options.output,
|
|
1438
|
+
{
|
|
1439
|
+
commits: baseResult.commits,
|
|
1440
|
+
branch: baseResult.branch,
|
|
1441
|
+
preservedWorktreePath: baseResult.preservedWorktreePath,
|
|
1442
|
+
sessionId: lastIteration?.sessionId,
|
|
1443
|
+
sessionFilePath: lastIteration?.sessionFilePath
|
|
1444
|
+
}
|
|
1388
1445
|
);
|
|
1446
|
+
return { ...baseResult, output };
|
|
1389
1447
|
} catch (error) {
|
|
1390
|
-
|
|
1448
|
+
if (error instanceof StructuredOutputError && outputMaxRetries > 0 && error.sessionId !== void 0) {
|
|
1449
|
+
const retriesRemainingAfter = outputMaxRetries - 1;
|
|
1450
|
+
const retryOutput = {
|
|
1451
|
+
...options.output,
|
|
1452
|
+
maxRetries: retriesRemainingAfter
|
|
1453
|
+
};
|
|
1454
|
+
return run({
|
|
1455
|
+
...options,
|
|
1456
|
+
prompt: buildStructuredOutputRetryFeedback(
|
|
1457
|
+
error,
|
|
1458
|
+
retriesRemainingAfter
|
|
1459
|
+
),
|
|
1460
|
+
promptFile: void 0,
|
|
1461
|
+
promptArgs: void 0,
|
|
1462
|
+
resumeSession: error.sessionId,
|
|
1463
|
+
forkSession: false,
|
|
1464
|
+
output: retryOutput
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1391
1467
|
throw error;
|
|
1392
1468
|
}
|
|
1469
|
+
};
|
|
1470
|
+
var finishRun = async ({
|
|
1471
|
+
options,
|
|
1472
|
+
result,
|
|
1473
|
+
logging,
|
|
1474
|
+
outputMaxRetries
|
|
1475
|
+
}) => {
|
|
1393
1476
|
const baseResult = {
|
|
1394
1477
|
...result,
|
|
1395
|
-
logFilePath:
|
|
1478
|
+
logFilePath: logging.type === "file" ? logging.path : void 0,
|
|
1396
1479
|
resume: followUpRun(options, result, "resume"),
|
|
1397
1480
|
fork: followUpRun(options, result, "fork")
|
|
1398
1481
|
};
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
}
|
|
1437
|
-
return
|
|
1482
|
+
const { output } = options;
|
|
1483
|
+
if (!output) {
|
|
1484
|
+
return baseResult;
|
|
1485
|
+
}
|
|
1486
|
+
return withStructuredOutput(
|
|
1487
|
+
{ ...options, output },
|
|
1488
|
+
baseResult,
|
|
1489
|
+
outputMaxRetries
|
|
1490
|
+
);
|
|
1491
|
+
};
|
|
1492
|
+
async function run(options) {
|
|
1493
|
+
options.signal?.throwIfAborted();
|
|
1494
|
+
const { maxIterations = DEFAULT_MAX_ITERATIONS } = options;
|
|
1495
|
+
const branchStrategy = resolveBranchStrategy(options);
|
|
1496
|
+
validateTimeoutOptions(options);
|
|
1497
|
+
validateBranchOptions(options, branchStrategy.type);
|
|
1498
|
+
const isResuming = validateSessionOptions(options, maxIterations);
|
|
1499
|
+
const outputMaxRetries = validateOutputOptions(options, maxIterations);
|
|
1500
|
+
const hostRepoDir = await resolveRunHostRepoDir(options, isResuming);
|
|
1501
|
+
const { rawPrompt, isInlinePrompt } = await resolveRunPrompt(options);
|
|
1502
|
+
const env = await resolveRunEnv(options, hostRepoDir);
|
|
1503
|
+
const branches = await resolveRunBranches(
|
|
1504
|
+
options,
|
|
1505
|
+
branchStrategy,
|
|
1506
|
+
hostRepoDir
|
|
1507
|
+
);
|
|
1508
|
+
const logging = resolveRunLogging(options, hostRepoDir, branches);
|
|
1509
|
+
const result = await executeRun({
|
|
1510
|
+
options,
|
|
1511
|
+
branchStrategy,
|
|
1512
|
+
hostRepoDir,
|
|
1513
|
+
maxIterations,
|
|
1514
|
+
branches,
|
|
1515
|
+
logging,
|
|
1516
|
+
env,
|
|
1517
|
+
rawPrompt,
|
|
1518
|
+
isInlinePrompt
|
|
1519
|
+
});
|
|
1520
|
+
return finishRun({ options, result, logging, outputMaxRetries });
|
|
1438
1521
|
}
|
|
1439
1522
|
|
|
1440
1523
|
// src/raceAbortSignal.ts
|
|
@@ -1747,1266 +1830,230 @@ var interactive = async (options) => {
|
|
|
1747
1830
|
}
|
|
1748
1831
|
return result;
|
|
1749
1832
|
};
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
const normalized = isRoot ? cwd : cwd.replace(/[\\/]+$/u, "");
|
|
1774
|
-
const encoded = normalized.replaceAll(/[^A-Za-z0-9]/gu, "-");
|
|
1775
|
-
if (encoded.length <= MAX_PROJECT_DIR_LENGTH) {
|
|
1776
|
-
return encoded;
|
|
1777
|
-
}
|
|
1778
|
-
return `${encoded.slice(0, MAX_PROJECT_DIR_LENGTH)}-${claudePathHash(normalized)}`;
|
|
1779
|
-
};
|
|
1780
|
-
var DEFAULT_SANDBOX_DIRS = { home: "/home/agent", tmp: "/tmp" };
|
|
1781
|
-
var sandboxDirsOf = (handle) => ({
|
|
1782
|
-
home: handle.sandboxHomedir ?? DEFAULT_SANDBOX_DIRS.home,
|
|
1783
|
-
tmp: handle.sandboxTmpdir ?? DEFAULT_SANDBOX_DIRS.tmp
|
|
1784
|
-
});
|
|
1785
|
-
var claudeHostSessionPath = (cwd, id, projectsDir) => {
|
|
1786
|
-
const base = projectsDir ?? join(homeDir(), ".claude", "projects");
|
|
1787
|
-
return join(base, encodeProjectPath(cwd), `${id}.jsonl`);
|
|
1788
|
-
};
|
|
1789
|
-
var claudeSandboxSessionPath = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), `${id}.jsonl`);
|
|
1790
|
-
var claudeSubagentsDirInSandbox = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), id, "subagents");
|
|
1791
|
-
var claudeSubagentsDirOnHost = (cwd, id, projectsDir) => {
|
|
1792
|
-
const base = projectsDir ?? join(homeDir(), ".claude", "projects");
|
|
1793
|
-
return join(base, encodeProjectPath(cwd), id, "subagents");
|
|
1794
|
-
};
|
|
1795
|
-
var listClaudeSubagentSessionsInSandbox = async (cwd, id, handle, sandboxProjectsDir) => {
|
|
1796
|
-
const dir = claudeSubagentsDirInSandbox(cwd, id, sandboxProjectsDir);
|
|
1797
|
-
const result = await handle.exec(
|
|
1798
|
-
`find ${JSON.stringify(dir)} -type f -name ${JSON.stringify("agent-*.jsonl")} 2>/dev/null`
|
|
1833
|
+
|
|
1834
|
+
// src/resolveSandboxPrompt.ts
|
|
1835
|
+
var resolveSandboxPrompt = (options) => Effect_exports.gen(function* () {
|
|
1836
|
+
const resolved = yield* resolvePrompt({
|
|
1837
|
+
prompt: options.prompt,
|
|
1838
|
+
promptFile: options.promptFile
|
|
1839
|
+
});
|
|
1840
|
+
const isInline = resolved.source === "inline";
|
|
1841
|
+
const userArgs = options.promptArgs ?? {};
|
|
1842
|
+
const currentHostBranch = yield* getCurrentBranch(options.hostRepoDir);
|
|
1843
|
+
if (isInline) {
|
|
1844
|
+
yield* validateNoArgsWithInlinePrompt(userArgs);
|
|
1845
|
+
return { text: resolved.text, isInline };
|
|
1846
|
+
}
|
|
1847
|
+
yield* validateNoBuiltInArgOverride(userArgs);
|
|
1848
|
+
const text2 = yield* substitutePromptArgs(
|
|
1849
|
+
resolved.text,
|
|
1850
|
+
{
|
|
1851
|
+
SOURCE_BRANCH: options.branch,
|
|
1852
|
+
TARGET_BRANCH: currentHostBranch,
|
|
1853
|
+
...userArgs
|
|
1854
|
+
},
|
|
1855
|
+
new Set(BUILT_IN_PROMPT_ARG_KEYS)
|
|
1799
1856
|
);
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
};
|
|
1809
|
-
var findClaudeSessionOnHost = async (id, projectsDir) => {
|
|
1810
|
-
const root = projectsDir ?? join(homeDir(), ".claude", "projects");
|
|
1811
|
-
let entries;
|
|
1812
|
-
try {
|
|
1813
|
-
entries = await readdir(root, { withFileTypes: true });
|
|
1814
|
-
} catch {
|
|
1815
|
-
return { path: void 0, searchedRoot: root };
|
|
1816
|
-
}
|
|
1817
|
-
const candidates = entries.filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name, `${id}.jsonl`));
|
|
1818
|
-
return { path: await firstExistingPath(candidates), searchedRoot: root };
|
|
1819
|
-
};
|
|
1820
|
-
var rewriteEntryCwd = (entry, fromCwd, toCwd) => {
|
|
1821
|
-
if (typeof entry.cwd === "string" && entry.cwd === fromCwd) {
|
|
1822
|
-
entry.cwd = toCwd;
|
|
1823
|
-
}
|
|
1824
|
-
if (entry.type === "session_meta" && isRecord(entry.payload) && typeof entry.payload.cwd === "string" && entry.payload.cwd === fromCwd) {
|
|
1825
|
-
entry.payload.cwd = toCwd;
|
|
1857
|
+
return { text: text2, isInline };
|
|
1858
|
+
});
|
|
1859
|
+
|
|
1860
|
+
// src/createSandbox.ts
|
|
1861
|
+
var withAgentEnv = (agent, sandboxProviderEnv) => {
|
|
1862
|
+
const entries = Object.entries(agent.env);
|
|
1863
|
+
if (entries.length === 0) {
|
|
1864
|
+
return agent;
|
|
1826
1865
|
}
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1866
|
+
mergeProviderEnv({
|
|
1867
|
+
resolvedEnv: {},
|
|
1868
|
+
agentProviderEnv: agent.env,
|
|
1869
|
+
sandboxProviderEnv
|
|
1870
|
+
});
|
|
1871
|
+
const invalid = entries.map(([key]) => key).filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));
|
|
1872
|
+
if (invalid.length > 0) {
|
|
1873
|
+
throw new Error(
|
|
1874
|
+
`Invalid agent provider env key(s): ${invalid.join(", ")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`
|
|
1875
|
+
);
|
|
1831
1876
|
}
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
if (!isRecord(entry)) {
|
|
1839
|
-
return line;
|
|
1840
|
-
}
|
|
1841
|
-
rewriteEntryCwd(entry, fromCwd, toCwd);
|
|
1842
|
-
return JSON.stringify(entry);
|
|
1843
|
-
} catch {
|
|
1844
|
-
return line;
|
|
1877
|
+
const exports$1 = entries.map(([key, value]) => `export ${key}=${shellEscape(value)}; `).join("");
|
|
1878
|
+
return {
|
|
1879
|
+
...agent,
|
|
1880
|
+
buildPrintCommand: (options) => {
|
|
1881
|
+
const printCommand = agent.buildPrintCommand(options);
|
|
1882
|
+
return { ...printCommand, command: exports$1 + printCommand.command };
|
|
1845
1883
|
}
|
|
1846
|
-
}
|
|
1884
|
+
};
|
|
1847
1885
|
};
|
|
1848
|
-
var
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
} catch {
|
|
1856
|
-
return { path: void 0, searchedRoot: root };
|
|
1886
|
+
var assertRunOptionsValid = async (runOptions, provider, ctx) => {
|
|
1887
|
+
validateTimeoutOptions(runOptions);
|
|
1888
|
+
const isResuming = runOptions.resumeSession !== void 0 && runOptions.resumeSession !== "";
|
|
1889
|
+
if (isResuming && (runOptions.maxIterations ?? 1) > 1) {
|
|
1890
|
+
throw new Error(
|
|
1891
|
+
"resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
|
|
1892
|
+
);
|
|
1857
1893
|
}
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
}
|
|
1863
|
-
if (entry.isDirectory()) {
|
|
1864
|
-
const { path: path2 } = await findCodexSessionOnHost(id, child);
|
|
1865
|
-
if (path2 !== void 0) {
|
|
1866
|
-
return { path: path2, searchedRoot: root };
|
|
1867
|
-
}
|
|
1868
|
-
}
|
|
1894
|
+
if (runOptions.forkSession === true && !isResuming) {
|
|
1895
|
+
throw new Error(
|
|
1896
|
+
"forkSession requires resumeSession. Use sandboxRunResult.fork(prompt) to fork the most recent captured session."
|
|
1897
|
+
);
|
|
1869
1898
|
}
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
var requireHostSessionPath = (found, id) => {
|
|
1873
|
-
if (found.path === void 0) {
|
|
1874
|
-
throw new Error(`session ${id} not found in ${found.searchedRoot}`);
|
|
1899
|
+
if (runOptions.forkSession === true) {
|
|
1900
|
+
assertForkSupported(provider);
|
|
1875
1901
|
}
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
if (result.exitCode !== 0 || path2 === "") {
|
|
1884
|
-
throw new Error(`session ${nameGlob} not found in ${sessionsDir}`);
|
|
1902
|
+
if (isResuming) {
|
|
1903
|
+
await assertResumeSessionExists({
|
|
1904
|
+
provider,
|
|
1905
|
+
sandboxTag: ctx.providerTag,
|
|
1906
|
+
hostRepoDir: ctx.hostRepoDir,
|
|
1907
|
+
resumeSession: runOptions.resumeSession
|
|
1908
|
+
});
|
|
1885
1909
|
}
|
|
1886
|
-
return { path: path2, relativePath: posix.relative(sessionsDir, path2) };
|
|
1887
|
-
};
|
|
1888
|
-
var transferCodexSession = (jsonl, fromCwd, toCwd) => rewriteSessionCwd(jsonl, fromCwd, toCwd);
|
|
1889
|
-
var encodePiSessionDir = (cwd) => {
|
|
1890
|
-
const stripped = cwd.replace(/^[/\\]/u, "");
|
|
1891
|
-
const replaced = stripped.replaceAll(/[/\\:]/gu, "-");
|
|
1892
|
-
return `--${replaced}--`;
|
|
1893
1910
|
};
|
|
1894
|
-
var
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
try {
|
|
1903
|
-
entries = await readdir(root, { withFileTypes: true });
|
|
1904
|
-
} catch {
|
|
1905
|
-
return { path: void 0, searchedRoot: root };
|
|
1906
|
-
}
|
|
1907
|
-
for (const entry of entries) {
|
|
1908
|
-
if (!entry.isDirectory()) {
|
|
1909
|
-
continue;
|
|
1910
|
-
}
|
|
1911
|
-
const dirAbs = join(root, entry.name);
|
|
1912
|
-
let files;
|
|
1913
|
-
try {
|
|
1914
|
-
files = await readdir(dirAbs);
|
|
1915
|
-
} catch {
|
|
1916
|
-
continue;
|
|
1917
|
-
}
|
|
1918
|
-
const match = files.find((name) => isPiSessionFilename(name, id));
|
|
1919
|
-
if (match !== void 0) {
|
|
1920
|
-
return { path: join(dirAbs, match), searchedRoot: root };
|
|
1921
|
-
}
|
|
1922
|
-
}
|
|
1923
|
-
return { path: void 0, searchedRoot: root };
|
|
1911
|
+
var resolveRunLogging2 = (runOptions, hostRepoDir, branch) => runOptions.logging ?? {
|
|
1912
|
+
type: "file",
|
|
1913
|
+
path: join(
|
|
1914
|
+
hostRepoDir,
|
|
1915
|
+
".sandcastle",
|
|
1916
|
+
"logs",
|
|
1917
|
+
buildLogFilename(branch, void 0, runOptions.name)
|
|
1918
|
+
)
|
|
1924
1919
|
};
|
|
1925
|
-
var
|
|
1926
|
-
if (
|
|
1927
|
-
return
|
|
1920
|
+
var buildRunDisplayLayer = (logging, banner) => {
|
|
1921
|
+
if (logging.type !== "file") {
|
|
1922
|
+
return ClackDisplay.layer;
|
|
1928
1923
|
}
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
return line;
|
|
1932
|
-
}
|
|
1933
|
-
try {
|
|
1934
|
-
const entry = JSON.parse(line);
|
|
1935
|
-
if (isRecord(entry) && entry.type === "session" && typeof entry.cwd === "string" && entry.cwd === fromCwd) {
|
|
1936
|
-
entry.cwd = toCwd;
|
|
1937
|
-
return JSON.stringify(entry);
|
|
1938
|
-
}
|
|
1939
|
-
return line;
|
|
1940
|
-
} catch {
|
|
1941
|
-
return line;
|
|
1942
|
-
}
|
|
1943
|
-
}).join("\n");
|
|
1924
|
+
printFileDisplayStartup({ logPath: logging.path, ...banner });
|
|
1925
|
+
return Layer_exports.provide(FileDisplay.layer(logging.path), NodeFileSystem_exports.layer);
|
|
1944
1926
|
};
|
|
1945
|
-
var
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
let entry;
|
|
1950
|
-
try {
|
|
1951
|
-
entry = JSON.parse(line);
|
|
1952
|
-
} catch {
|
|
1953
|
-
return line;
|
|
1954
|
-
}
|
|
1955
|
-
const data = isRecord(entry) ? entry["data"] : void 0;
|
|
1956
|
-
const context = isRecord(data) ? data["context"] : void 0;
|
|
1957
|
-
if (!isRecord(context)) {
|
|
1958
|
-
return line;
|
|
1959
|
-
}
|
|
1960
|
-
const keys = ["cwd", "gitRoot"].filter((key) => context[key] === fromCwd);
|
|
1961
|
-
for (const key of keys) {
|
|
1962
|
-
context[key] = toCwd;
|
|
1927
|
+
var withResumeAndFork = (baseResult, provider, rerun) => {
|
|
1928
|
+
const lastIteration = baseResult.iterations.at(-1);
|
|
1929
|
+
if (!provider.sessionStorage || lastIteration?.sessionId === void 0 || lastIteration.sessionId === "") {
|
|
1930
|
+
return baseResult;
|
|
1963
1931
|
}
|
|
1964
|
-
|
|
1932
|
+
const capturedSessionId = lastIteration.sessionId;
|
|
1933
|
+
return {
|
|
1934
|
+
...baseResult,
|
|
1935
|
+
resume: async (nextPrompt, resumeOptions) => rerun({
|
|
1936
|
+
// The follow-up prompt is inline: drop the template's arguments.
|
|
1937
|
+
promptArgs: void 0,
|
|
1938
|
+
...resumeOptions,
|
|
1939
|
+
prompt: nextPrompt,
|
|
1940
|
+
promptFile: void 0,
|
|
1941
|
+
maxIterations: 1,
|
|
1942
|
+
resumeSession: capturedSessionId
|
|
1943
|
+
}),
|
|
1944
|
+
fork: async (nextPrompt, forkOptions) => rerun({
|
|
1945
|
+
// The follow-up prompt is inline: drop the template's arguments.
|
|
1946
|
+
promptArgs: void 0,
|
|
1947
|
+
...forkOptions,
|
|
1948
|
+
prompt: nextPrompt,
|
|
1949
|
+
promptFile: void 0,
|
|
1950
|
+
maxIterations: 1,
|
|
1951
|
+
resumeSession: capturedSessionId,
|
|
1952
|
+
forkSession: true
|
|
1953
|
+
})
|
|
1954
|
+
};
|
|
1965
1955
|
};
|
|
1966
|
-
var
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
sandboxCwd,
|
|
1980
|
-
sessionId,
|
|
1981
|
-
sandboxDirsOf(handle)
|
|
1956
|
+
var resolveRunPrompt2 = (ctx, runOptions) => {
|
|
1957
|
+
const displayRef = Ref_exports.unsafeMake([]);
|
|
1958
|
+
const silentDisplayLayer = SilentDisplay.layer(displayRef);
|
|
1959
|
+
return Effect_exports.runPromise(
|
|
1960
|
+
resolveSandboxPrompt({
|
|
1961
|
+
prompt: runOptions.prompt,
|
|
1962
|
+
promptFile: runOptions.promptFile,
|
|
1963
|
+
promptArgs: runOptions.promptArgs,
|
|
1964
|
+
branch: ctx.branch,
|
|
1965
|
+
hostRepoDir: ctx.hostRepoDir
|
|
1966
|
+
}).pipe(
|
|
1967
|
+
Effect_exports.provide(Layer_exports.mergeAll(NodeContext_exports.layer, silentDisplayLayer))
|
|
1968
|
+
)
|
|
1982
1969
|
);
|
|
1983
|
-
if (layout.sandboxExport !== void 0) {
|
|
1984
|
-
const command = layout.sandboxExport(sessionId, source);
|
|
1985
|
-
const result = await handle.exec(command, { cwd: sandboxCwd });
|
|
1986
|
-
if (result.exitCode !== 0) {
|
|
1987
|
-
throw sandboxCommandError(command, result);
|
|
1988
|
-
}
|
|
1989
|
-
}
|
|
1990
|
-
const target = layout.hostPath(hostCwd, sessionId);
|
|
1991
|
-
await mkdir(dirname(target), { recursive: true });
|
|
1992
|
-
await handle.copyFileOut(source, target);
|
|
1993
|
-
if (layout.rewrite !== void 0) {
|
|
1994
|
-
const content = await readFile(target, "utf8");
|
|
1995
|
-
await writeFile(target, layout.rewrite(content, sandboxCwd, hostCwd));
|
|
1996
|
-
}
|
|
1997
1970
|
};
|
|
1998
|
-
var
|
|
1999
|
-
const
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
1971
|
+
var buildRunLayer2 = (ctx, runOptions, resolvedLogging) => {
|
|
1972
|
+
const runDisplayLayer = buildRunDisplayLayer(resolvedLogging, {
|
|
1973
|
+
agentName: runOptions.name,
|
|
1974
|
+
branch: ctx.branch
|
|
1975
|
+
});
|
|
1976
|
+
const reuseFactoryLayer = reuseSandboxFactoryLayer(
|
|
1977
|
+
{
|
|
1978
|
+
hostWorktreePath: ctx.worktreePath,
|
|
1979
|
+
sandboxRepoPath: ctx.sandboxRepoDir,
|
|
1980
|
+
applyToHost: ctx.applyToHost,
|
|
1981
|
+
bindMountHandle: ctx.bindMountHandle
|
|
1982
|
+
},
|
|
1983
|
+
ctx.sandbox
|
|
2005
1984
|
);
|
|
2006
|
-
const
|
|
2007
|
-
|
|
2008
|
-
await handle.exec(`mkdir -p ${dir}`);
|
|
2009
|
-
await handle.copyFileIn(source, target);
|
|
2010
|
-
if (layout.sandboxImport !== void 0) {
|
|
2011
|
-
const command = layout.sandboxImport(sessionId, target);
|
|
2012
|
-
const result2 = await handle.exec(command, { cwd: sandboxCwd });
|
|
2013
|
-
if (result2.exitCode !== 0) {
|
|
2014
|
-
throw sandboxCommandError(command, result2);
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
return;
|
|
2018
|
-
}
|
|
2019
|
-
const content = await readFile(source, "utf8");
|
|
2020
|
-
const result = await handle.exec(
|
|
2021
|
-
`mkdir -p ${dir} && cat > ${JSON.stringify(target)}`,
|
|
2022
|
-
{ stdin: layout.rewrite(content, hostCwd, sandboxCwd) }
|
|
1985
|
+
const streamEmitterLayer = agentStreamEmitterLayer(
|
|
1986
|
+
buildAgentStreamHandler(resolvedLogging)
|
|
2023
1987
|
);
|
|
2024
|
-
|
|
2025
|
-
throw new Error(`writing ${target} failed: ${result.stderr}`);
|
|
2026
|
-
}
|
|
1988
|
+
return Layer_exports.mergeAll(reuseFactoryLayer, runDisplayLayer, streamEmitterLayer);
|
|
2027
1989
|
};
|
|
2028
|
-
var
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
1990
|
+
var orchestrateOnSandbox = (ctx, runOptions, {
|
|
1991
|
+
provider,
|
|
1992
|
+
resolvedPrompt
|
|
1993
|
+
}) => Effect_exports.gen(function* () {
|
|
1994
|
+
const mergeToHead = ctx.branchStrategy?.type === "merge-to-head";
|
|
1995
|
+
const display = yield* Display;
|
|
1996
|
+
yield* display.intro(runOptions.name ?? "sandcastle");
|
|
1997
|
+
const orchestrateResult = yield* orchestrate({
|
|
1998
|
+
hostRepoDir: ctx.hostRepoDir,
|
|
1999
|
+
iterations: runOptions.maxIterations ?? 1,
|
|
2000
|
+
prompt: resolvedPrompt.text,
|
|
2001
|
+
branch: mergeToHead ? void 0 : ctx.branch,
|
|
2002
|
+
provider,
|
|
2003
|
+
completionSignal: runOptions.completionSignal,
|
|
2004
|
+
idleTimeoutSeconds: runOptions.idleTimeoutSeconds,
|
|
2005
|
+
completionTimeoutSeconds: runOptions.completionTimeoutSeconds,
|
|
2006
|
+
name: runOptions.name,
|
|
2007
|
+
resumeSession: runOptions.resumeSession,
|
|
2008
|
+
forkSession: runOptions.forkSession,
|
|
2009
|
+
signal: runOptions.signal,
|
|
2010
|
+
skipPromptExpansion: resolvedPrompt.isInline,
|
|
2011
|
+
timeouts: ctx.timeouts,
|
|
2012
|
+
keepSourceBranch: mergeToHead
|
|
2013
|
+
});
|
|
2014
|
+
const completion = buildCompletionMessage(
|
|
2015
|
+
orchestrateResult.completionSignal,
|
|
2016
|
+
orchestrateResult.iterations.length
|
|
2017
|
+
);
|
|
2018
|
+
yield* display.status(completion.message, completion.severity);
|
|
2019
|
+
for (const line of buildContextWindowLines(orchestrateResult.iterations)) {
|
|
2020
|
+
yield* display.text(line);
|
|
2021
|
+
}
|
|
2022
|
+
return orchestrateResult;
|
|
2048
2023
|
});
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2024
|
+
var runOnSandbox = async (ctx, runOptions, rerun) => {
|
|
2025
|
+
runOptions.signal?.throwIfAborted();
|
|
2026
|
+
const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);
|
|
2027
|
+
await assertRunOptionsValid(runOptions, provider, ctx);
|
|
2028
|
+
const resolvedPrompt = await resolveRunPrompt2(ctx, runOptions);
|
|
2029
|
+
const resolvedLogging = resolveRunLogging2(
|
|
2030
|
+
runOptions,
|
|
2031
|
+
ctx.hostRepoDir,
|
|
2032
|
+
ctx.branch
|
|
2033
|
+
);
|
|
2034
|
+
const runLayer = buildRunLayer2(ctx, runOptions, resolvedLogging);
|
|
2035
|
+
let result;
|
|
2060
2036
|
try {
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
u?.input_tokens,
|
|
2066
|
-
u?.cache_creation_input_tokens,
|
|
2067
|
-
u?.cache_read_input_tokens
|
|
2037
|
+
result = await Effect_exports.runPromise(
|
|
2038
|
+
orchestrateOnSandbox(ctx, runOptions, { provider, resolvedPrompt }).pipe(
|
|
2039
|
+
Effect_exports.provide(runLayer)
|
|
2040
|
+
)
|
|
2068
2041
|
);
|
|
2069
|
-
} catch {
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
};
|
|
2073
|
-
var TOOL_ARG_FIELDS = {
|
|
2074
|
-
Bash: "command",
|
|
2075
|
-
WebSearch: "query",
|
|
2076
|
-
WebFetch: "url",
|
|
2077
|
-
Agent: "description"
|
|
2078
|
-
};
|
|
2079
|
-
var messageField = (value) => typeof value === "object" && value !== null && "message" in value && typeof value.message === "string" ? value.message : void 0;
|
|
2080
|
-
var extractErrorMessage = (obj) => {
|
|
2081
|
-
if (typeof obj !== "object" || obj === null) {
|
|
2082
|
-
return void 0;
|
|
2083
|
-
}
|
|
2084
|
-
const err = "error" in obj ? obj.error : void 0;
|
|
2085
|
-
if (typeof err === "string") {
|
|
2086
|
-
return err;
|
|
2087
|
-
}
|
|
2088
|
-
if (typeof err === "object" && err !== null) {
|
|
2089
|
-
const nested = messageField(err) ?? ("data" in err ? messageField(err.data) : void 0);
|
|
2090
|
-
if (nested !== void 0) {
|
|
2091
|
-
return nested;
|
|
2092
|
-
}
|
|
2042
|
+
} catch (error) {
|
|
2043
|
+
runOptions.signal?.throwIfAborted();
|
|
2044
|
+
throw error;
|
|
2093
2045
|
}
|
|
2094
|
-
return
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
if (typeof argValue !== "string") {
|
|
2106
|
-
return void 0;
|
|
2107
|
-
}
|
|
2108
|
-
return { type: "tool_call", name: block.name, args: argValue };
|
|
2109
|
-
};
|
|
2110
|
-
var mergeAdjacentText = (events) => {
|
|
2111
|
-
const merged = [];
|
|
2112
|
-
for (const event of events) {
|
|
2113
|
-
const last = merged.at(-1);
|
|
2114
|
-
if (event.type === "text" && last?.type === "text") {
|
|
2115
|
-
merged[merged.length - 1] = {
|
|
2116
|
-
type: "text",
|
|
2117
|
-
text: last.text + event.text
|
|
2118
|
-
};
|
|
2119
|
-
} else {
|
|
2120
|
-
merged.push(event);
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
return merged;
|
|
2124
|
-
};
|
|
2125
|
-
var parseClaudeAssistantContent = (content) => mergeAdjacentText(
|
|
2126
|
-
content.flatMap((block) => {
|
|
2127
|
-
if (block.type === "text" && typeof block.text === "string") {
|
|
2128
|
-
return [{ type: "text", text: block.text }];
|
|
2129
|
-
}
|
|
2130
|
-
const toolCall = toolCallFromClaudeBlock(block);
|
|
2131
|
-
return toolCall === void 0 ? [] : [toolCall];
|
|
2132
|
-
})
|
|
2133
|
-
);
|
|
2134
|
-
var parseStreamJsonLine = (line) => {
|
|
2135
|
-
if (!line.startsWith("{")) return [];
|
|
2136
|
-
try {
|
|
2137
|
-
const obj = JSON.parse(line);
|
|
2138
|
-
if (obj.type === "assistant" && Array.isArray(obj.message?.content)) {
|
|
2139
|
-
return parseClaudeAssistantContent(
|
|
2140
|
-
obj.message.content
|
|
2141
|
-
);
|
|
2142
|
-
}
|
|
2143
|
-
if (obj.type === "result" && typeof obj.result === "string") {
|
|
2144
|
-
if (obj.is_error === true) {
|
|
2145
|
-
return [{ type: "error", message: obj.result }];
|
|
2146
|
-
}
|
|
2147
|
-
return [{ type: "result", result: obj.result }];
|
|
2148
|
-
}
|
|
2149
|
-
if (obj.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string") {
|
|
2150
|
-
return [{ type: "session_id", sessionId: obj.session_id }];
|
|
2151
|
-
}
|
|
2152
|
-
} catch {
|
|
2153
|
-
}
|
|
2154
|
-
return [];
|
|
2155
|
-
};
|
|
2156
|
-
var CURSOR_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
|
|
2157
|
-
var assertCursorPrintPromptFitsArgv = (prompt) => {
|
|
2158
|
-
const n = Buffer.byteLength(prompt, "utf8");
|
|
2159
|
-
if (n > CURSOR_PRINT_PROMPT_MAX_BYTES) {
|
|
2160
|
-
throw new Error(
|
|
2161
|
-
`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.`
|
|
2162
|
-
);
|
|
2163
|
-
}
|
|
2164
|
-
};
|
|
2165
|
-
var cursorToolCallArg = (toolCall, field) => {
|
|
2166
|
-
if (typeof toolCall !== "object" || toolCall === null) {
|
|
2167
|
-
return void 0;
|
|
2168
|
-
}
|
|
2169
|
-
const args = Reflect.get(toolCall, "args");
|
|
2170
|
-
if (typeof args !== "object" || args === null) {
|
|
2171
|
-
return void 0;
|
|
2172
|
-
}
|
|
2173
|
-
const value = Reflect.get(args, field);
|
|
2174
|
-
return typeof value === "string" ? value : void 0;
|
|
2175
|
-
};
|
|
2176
|
-
var CURSOR_TYPED_TOOL_CALLS = [
|
|
2177
|
-
{ kind: "readToolCall", name: "Read", field: "path" },
|
|
2178
|
-
{ kind: "writeToolCall", name: "Write", field: "path" },
|
|
2179
|
-
{ kind: "editToolCall", name: "Edit", field: "path" },
|
|
2180
|
-
{ kind: "shellToolCall", name: "Bash", field: "command" }
|
|
2181
|
-
];
|
|
2182
|
-
var parseCursorFunctionToolCall = (fn) => {
|
|
2183
|
-
if (typeof fn !== "object" || fn === null) {
|
|
2184
|
-
return [];
|
|
2185
|
-
}
|
|
2186
|
-
const name = Reflect.get(fn, "name");
|
|
2187
|
-
if (typeof name !== "string") {
|
|
2188
|
-
return [];
|
|
2189
|
-
}
|
|
2190
|
-
const rawArguments = Reflect.get(fn, "arguments");
|
|
2191
|
-
const rawArgs = typeof rawArguments === "string" ? rawArguments : "";
|
|
2192
|
-
if (rawArgs === "") {
|
|
2193
|
-
return [{ type: "tool_call", name, args: "" }];
|
|
2194
|
-
}
|
|
2195
|
-
try {
|
|
2196
|
-
const parsedArgs = JSON.parse(rawArgs);
|
|
2197
|
-
const command = typeof parsedArgs === "object" && parsedArgs !== null ? Reflect.get(parsedArgs, "command") : void 0;
|
|
2198
|
-
if (typeof command === "string") {
|
|
2199
|
-
return [{ type: "tool_call", name: "Bash", args: command }];
|
|
2200
|
-
}
|
|
2201
|
-
} catch {
|
|
2202
|
-
}
|
|
2203
|
-
return [{ type: "tool_call", name, args: rawArgs }];
|
|
2204
|
-
};
|
|
2205
|
-
var parseCursorToolCallStarted = (obj) => {
|
|
2206
|
-
if (obj.type !== "tool_call" || obj.subtype !== "started") {
|
|
2207
|
-
return [];
|
|
2208
|
-
}
|
|
2209
|
-
const toolCall = obj.tool_call;
|
|
2210
|
-
if (typeof toolCall !== "object" || toolCall === null) {
|
|
2211
|
-
return [];
|
|
2212
|
-
}
|
|
2213
|
-
for (const { kind, name, field } of CURSOR_TYPED_TOOL_CALLS) {
|
|
2214
|
-
const args = cursorToolCallArg(Reflect.get(toolCall, kind), field);
|
|
2215
|
-
if (args !== void 0) {
|
|
2216
|
-
return [{ type: "tool_call", name, args }];
|
|
2217
|
-
}
|
|
2218
|
-
}
|
|
2219
|
-
return parseCursorFunctionToolCall(Reflect.get(toolCall, "function"));
|
|
2220
|
-
};
|
|
2221
|
-
var parseCursorStreamLine = (line) => {
|
|
2222
|
-
if (!line.startsWith("{")) return [];
|
|
2223
|
-
let obj;
|
|
2224
|
-
try {
|
|
2225
|
-
obj = JSON.parse(line);
|
|
2226
|
-
} catch {
|
|
2227
|
-
return [];
|
|
2228
|
-
}
|
|
2229
|
-
if (obj.type === "tool_call") {
|
|
2230
|
-
return parseCursorToolCallStarted(obj);
|
|
2231
|
-
}
|
|
2232
|
-
return parseStreamJsonLine(line);
|
|
2233
|
-
};
|
|
2234
|
-
var readSandboxFile = async (handle, sandboxPath, tag) => {
|
|
2235
|
-
const tmpPath = join(
|
|
2236
|
-
tmpdir(),
|
|
2237
|
-
`sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
|
|
2238
|
-
);
|
|
2239
|
-
await handle.copyFileOut(sandboxPath, tmpPath);
|
|
2240
|
-
try {
|
|
2241
|
-
return await readFile(tmpPath, "utf8");
|
|
2242
|
-
} finally {
|
|
2243
|
-
await rm(tmpPath, { force: true }).catch(() => {
|
|
2244
|
-
});
|
|
2245
|
-
}
|
|
2246
|
-
};
|
|
2247
|
-
var writeSandboxFile = async (handle, { sandboxPath, content, tag }) => {
|
|
2248
|
-
const tmpPath = join(
|
|
2249
|
-
tmpdir(),
|
|
2250
|
-
`sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
|
|
2251
|
-
);
|
|
2252
|
-
await writeFile(tmpPath, content);
|
|
2253
|
-
try {
|
|
2254
|
-
await handle.exec(`mkdir -p ${JSON.stringify(posix.dirname(sandboxPath))}`);
|
|
2255
|
-
await handle.copyFileIn(tmpPath, sandboxPath);
|
|
2256
|
-
} finally {
|
|
2257
|
-
await rm(tmpPath, { force: true }).catch(() => {
|
|
2258
|
-
});
|
|
2259
|
-
}
|
|
2260
|
-
};
|
|
2261
|
-
var copyClaudeSessionFile = async ({
|
|
2262
|
-
handle,
|
|
2263
|
-
sourcePath,
|
|
2264
|
-
fromCwd,
|
|
2265
|
-
toCwd,
|
|
2266
|
-
destPath,
|
|
2267
|
-
tag
|
|
2268
|
-
}) => {
|
|
2269
|
-
const jsonl = await readSandboxFile(handle, sourcePath, tag);
|
|
2270
|
-
const rewritten = transferClaudeSession(jsonl, fromCwd, toCwd);
|
|
2271
|
-
await mkdir(dirname(destPath), { recursive: true });
|
|
2272
|
-
await writeFile(destPath, rewritten);
|
|
2273
|
-
};
|
|
2274
|
-
var captureClaudeSubagents = async ({
|
|
2275
|
-
handle,
|
|
2276
|
-
hostCwd,
|
|
2277
|
-
sandboxCwd,
|
|
2278
|
-
sessionId,
|
|
2279
|
-
sandboxProjectsDir,
|
|
2280
|
-
hostProjectsDir
|
|
2281
|
-
}) => {
|
|
2282
|
-
const subagentSandboxPaths = await listClaudeSubagentSessionsInSandbox(
|
|
2283
|
-
sandboxCwd,
|
|
2284
|
-
sessionId,
|
|
2285
|
-
handle,
|
|
2286
|
-
sandboxProjectsDir
|
|
2287
|
-
);
|
|
2288
|
-
const hostSubagentsDir = claudeSubagentsDirOnHost(
|
|
2289
|
-
hostCwd,
|
|
2290
|
-
sessionId,
|
|
2291
|
-
hostProjectsDir
|
|
2292
|
-
);
|
|
2293
|
-
for (const sandboxSubagentPath of subagentSandboxPaths) {
|
|
2294
|
-
try {
|
|
2295
|
-
await copyClaudeSessionFile({
|
|
2296
|
-
handle,
|
|
2297
|
-
sourcePath: sandboxSubagentPath,
|
|
2298
|
-
fromCwd: sandboxCwd,
|
|
2299
|
-
toCwd: hostCwd,
|
|
2300
|
-
destPath: join(hostSubagentsDir, posix.basename(sandboxSubagentPath)),
|
|
2301
|
-
tag: "claude-sub"
|
|
2302
|
-
});
|
|
2303
|
-
} catch (error) {
|
|
2304
|
-
console.error(
|
|
2305
|
-
`sandcastle: failed to capture Claude subagent transcript ${sandboxSubagentPath}: ${error instanceof Error ? error.message : String(error)}`
|
|
2306
|
-
);
|
|
2307
|
-
}
|
|
2308
|
-
}
|
|
2309
|
-
};
|
|
2310
|
-
var resumeClaudeIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
|
|
2311
|
-
const hostPath = claudeHostSessionPath(
|
|
2312
|
-
hostCwd,
|
|
2313
|
-
sessionId,
|
|
2314
|
-
dirs.hostProjectsDir
|
|
2315
|
-
);
|
|
2316
|
-
const jsonl = await readFile(hostPath, "utf8");
|
|
2317
|
-
await writeSandboxFile(handle, {
|
|
2318
|
-
sandboxPath: claudeSandboxSessionPath(
|
|
2319
|
-
sandboxCwd,
|
|
2320
|
-
sessionId,
|
|
2321
|
-
dirs.sandboxProjectsDir
|
|
2322
|
-
),
|
|
2323
|
-
content: transferClaudeSession(jsonl, hostCwd, sandboxCwd),
|
|
2324
|
-
tag: "claude-res"
|
|
2325
|
-
});
|
|
2326
|
-
};
|
|
2327
|
-
var captureClaudeSession = (capture) => (
|
|
2328
|
-
// Main session: failure is fatal — the user expects their session.
|
|
2329
|
-
copyClaudeSessionFile({
|
|
2330
|
-
handle: capture.handle,
|
|
2331
|
-
sourcePath: claudeSandboxSessionPath(
|
|
2332
|
-
capture.sandboxCwd,
|
|
2333
|
-
capture.sessionId,
|
|
2334
|
-
capture.sandboxProjectsDir
|
|
2335
|
-
),
|
|
2336
|
-
fromCwd: capture.sandboxCwd,
|
|
2337
|
-
toCwd: capture.hostCwd,
|
|
2338
|
-
destPath: claudeHostSessionPath(
|
|
2339
|
-
capture.hostCwd,
|
|
2340
|
-
capture.sessionId,
|
|
2341
|
-
capture.hostProjectsDir
|
|
2342
|
-
),
|
|
2343
|
-
tag: "claude-cap"
|
|
2344
|
-
}).then(() => captureClaudeSubagents(capture))
|
|
2345
|
-
);
|
|
2346
|
-
var makeClaudeSessionStorage = (options) => {
|
|
2347
|
-
const hostProjectsDir = options?.sessionStorage?.hostProjectsDir;
|
|
2348
|
-
const sandboxProjectsDirOf = (handle) => options?.sessionStorage?.sandboxProjectsDir ?? posix.join(sandboxDirsOf(handle).home, ".claude", "projects");
|
|
2349
|
-
return {
|
|
2350
|
-
hostSessionFilePath: (cwd, id) => claudeHostSessionPath(cwd, id, hostProjectsDir),
|
|
2351
|
-
existsOnHost: (cwd, id) => pathExists(claudeHostSessionPath(cwd, id, hostProjectsDir)),
|
|
2352
|
-
readHostSession: async (cwd, id) => {
|
|
2353
|
-
const path2 = claudeHostSessionPath(cwd, id, hostProjectsDir);
|
|
2354
|
-
if (!await pathExists(path2)) return void 0;
|
|
2355
|
-
return readFile(path2, "utf8");
|
|
2356
|
-
},
|
|
2357
|
-
captureToHost: ({ hostCwd, sandboxCwd, sessionId, handle }) => captureClaudeSession({
|
|
2358
|
-
handle,
|
|
2359
|
-
hostCwd,
|
|
2360
|
-
sandboxCwd,
|
|
2361
|
-
sessionId,
|
|
2362
|
-
sandboxProjectsDir: sandboxProjectsDirOf(handle),
|
|
2363
|
-
hostProjectsDir
|
|
2364
|
-
}),
|
|
2365
|
-
resumeIntoSandbox: (transfer) => resumeClaudeIntoSandbox(transfer, {
|
|
2366
|
-
hostProjectsDir,
|
|
2367
|
-
sandboxProjectsDir: sandboxProjectsDirOf(transfer.handle)
|
|
2368
|
-
}),
|
|
2369
|
-
findByIdOnHost: (id) => findClaudeSessionOnHost(id, hostProjectsDir)
|
|
2370
|
-
};
|
|
2371
|
-
};
|
|
2372
|
-
var resumeCodexIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
|
|
2373
|
-
const found = await findCodexSessionOnHost(sessionId, dirs.hostSessionsDir);
|
|
2374
|
-
const path2 = requireHostSessionPath(found, sessionId);
|
|
2375
|
-
const jsonl = await readFile(path2, "utf8");
|
|
2376
|
-
await writeSandboxFile(handle, {
|
|
2377
|
-
sandboxPath: posix.join(
|
|
2378
|
-
dirs.sandboxSessionsDir,
|
|
2379
|
-
...relative(found.searchedRoot, path2).split(/[\\/]/u)
|
|
2380
|
-
),
|
|
2381
|
-
content: transferCodexSession(jsonl, hostCwd, sandboxCwd),
|
|
2382
|
-
tag: "codex-res"
|
|
2383
|
-
});
|
|
2384
|
-
};
|
|
2385
|
-
var makeCodexSessionStorage = (options) => {
|
|
2386
|
-
const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
|
|
2387
|
-
const sandboxSessionsDirOf = (handle) => options?.sessionStorage?.sandboxSessionsDir ?? posix.join(sandboxDirsOf(handle).home, ".codex", "sessions");
|
|
2388
|
-
const capturedPaths = /* @__PURE__ */ new Map();
|
|
2389
|
-
return {
|
|
2390
|
-
hostSessionFilePath: (_cwd, id) => capturedPaths.get(id),
|
|
2391
|
-
existsOnHost: async (_cwd, id) => {
|
|
2392
|
-
const found = await findCodexSessionOnHost(id, hostSessionsDir);
|
|
2393
|
-
return found.path !== void 0;
|
|
2394
|
-
},
|
|
2395
|
-
readHostSession: async (_cwd, id) => {
|
|
2396
|
-
const found = await findCodexSessionOnHost(id, hostSessionsDir);
|
|
2397
|
-
if (!found.path) return void 0;
|
|
2398
|
-
return readFile(found.path, "utf8");
|
|
2399
|
-
},
|
|
2400
|
-
captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
|
|
2401
|
-
const located = await locateSandboxSessionFile(
|
|
2402
|
-
handle,
|
|
2403
|
-
sandboxSessionsDirOf(handle),
|
|
2404
|
-
`rollout-*-${sessionId}.jsonl`
|
|
2405
|
-
);
|
|
2406
|
-
const jsonl = await readSandboxFile(handle, located.path, "codex-cap");
|
|
2407
|
-
const rewritten = transferCodexSession(jsonl, sandboxCwd, hostCwd);
|
|
2408
|
-
const root = hostSessionsDir ?? join(homeDir(), ".codex", "sessions");
|
|
2409
|
-
const target = join(root, located.relativePath);
|
|
2410
|
-
await mkdir(dirname(target), { recursive: true });
|
|
2411
|
-
await writeFile(target, rewritten);
|
|
2412
|
-
capturedPaths.set(sessionId, target);
|
|
2413
|
-
},
|
|
2414
|
-
resumeIntoSandbox: (transfer) => resumeCodexIntoSandbox(transfer, {
|
|
2415
|
-
hostSessionsDir,
|
|
2416
|
-
sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle)
|
|
2417
|
-
}),
|
|
2418
|
-
findByIdOnHost: (id) => findCodexSessionOnHost(id, hostSessionsDir)
|
|
2419
|
-
};
|
|
2420
|
-
};
|
|
2421
|
-
var piHostCaptureTarget = (hostCwd, sandboxPath, hostSessionsDir) => join(piSessionDirPath(hostCwd, hostSessionsDir), posix.basename(sandboxPath));
|
|
2422
|
-
var resumePiIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
|
|
2423
|
-
const found = await findPiSessionOnHost(sessionId, dirs.hostSessionsDir);
|
|
2424
|
-
const path2 = requireHostSessionPath(found, sessionId);
|
|
2425
|
-
const jsonl = await readFile(path2, "utf8");
|
|
2426
|
-
const filename = posix.basename(path2.replaceAll("\\", "/"));
|
|
2427
|
-
await writeSandboxFile(handle, {
|
|
2428
|
-
sandboxPath: posix.join(
|
|
2429
|
-
dirs.sandboxSessionsDir,
|
|
2430
|
-
encodePiSessionDir(sandboxCwd),
|
|
2431
|
-
filename
|
|
2432
|
-
),
|
|
2433
|
-
content: transferPiSession(jsonl, hostCwd, sandboxCwd),
|
|
2434
|
-
tag: "pi-res"
|
|
2435
|
-
});
|
|
2436
|
-
};
|
|
2437
|
-
var makePiSessionStorage = (options) => {
|
|
2438
|
-
const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
|
|
2439
|
-
const sandboxSessionsDirOf = (handle) => options?.sessionStorage?.sandboxSessionsDir ?? posix.join(sandboxDirsOf(handle).home, ".pi", "agent", "sessions");
|
|
2440
|
-
const capturedPaths = /* @__PURE__ */ new Map();
|
|
2441
|
-
return {
|
|
2442
|
-
hostSessionFilePath: (cwd, id) => capturedPaths.get(id) ?? piSessionDirPath(cwd, hostSessionsDir),
|
|
2443
|
-
existsOnHost: async (_cwd, id) => {
|
|
2444
|
-
const found = await findPiSessionOnHost(id, hostSessionsDir);
|
|
2445
|
-
return found.path !== void 0;
|
|
2446
|
-
},
|
|
2447
|
-
readHostSession: async (_cwd, id) => {
|
|
2448
|
-
const { path: path2 } = await findPiSessionOnHost(id, hostSessionsDir);
|
|
2449
|
-
return path2 === void 0 ? void 0 : readFile(path2, "utf8");
|
|
2450
|
-
},
|
|
2451
|
-
captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
|
|
2452
|
-
const located = await locateSandboxSessionFile(
|
|
2453
|
-
handle,
|
|
2454
|
-
sandboxSessionsDirOf(handle),
|
|
2455
|
-
`*_${sessionId}.jsonl`
|
|
2456
|
-
);
|
|
2457
|
-
const jsonl = await readSandboxFile(handle, located.path, "pi-cap");
|
|
2458
|
-
const rewritten = transferPiSession(jsonl, sandboxCwd, hostCwd);
|
|
2459
|
-
const target = piHostCaptureTarget(
|
|
2460
|
-
hostCwd,
|
|
2461
|
-
located.path,
|
|
2462
|
-
hostSessionsDir
|
|
2463
|
-
);
|
|
2464
|
-
await mkdir(dirname(target), { recursive: true });
|
|
2465
|
-
await writeFile(target, rewritten);
|
|
2466
|
-
capturedPaths.set(sessionId, target);
|
|
2467
|
-
},
|
|
2468
|
-
resumeIntoSandbox: (transfer) => resumePiIntoSandbox(transfer, {
|
|
2469
|
-
hostSessionsDir,
|
|
2470
|
-
sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle)
|
|
2471
|
-
}),
|
|
2472
|
-
findByIdOnHost: (id) => findPiSessionOnHost(id, hostSessionsDir)
|
|
2473
|
-
};
|
|
2474
|
-
};
|
|
2475
|
-
var lastAssistantMessage = (messages) => {
|
|
2476
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2477
|
-
const msg = messages[i];
|
|
2478
|
-
if (msg?.role === "assistant") {
|
|
2479
|
-
return msg;
|
|
2480
|
-
}
|
|
2481
|
-
}
|
|
2482
|
-
return null;
|
|
2483
|
-
};
|
|
2484
|
-
var parsePiAgentEnd = (messages) => {
|
|
2485
|
-
const msg = lastAssistantMessage(messages);
|
|
2486
|
-
if (msg === null) {
|
|
2487
|
-
return [];
|
|
2488
|
-
}
|
|
2489
|
-
if (msg.stopReason === "error") {
|
|
2490
|
-
return [
|
|
2491
|
-
{
|
|
2492
|
-
type: "error",
|
|
2493
|
-
message: typeof msg.errorMessage === "string" && msg.errorMessage ? msg.errorMessage : 'pi stopped with stopReason "error"'
|
|
2494
|
-
}
|
|
2495
|
-
];
|
|
2496
|
-
}
|
|
2497
|
-
const texts = msg.content.flatMap(
|
|
2498
|
-
(block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []
|
|
2499
|
-
);
|
|
2500
|
-
return texts.length > 0 ? [{ type: "result", result: texts.join("") }] : [];
|
|
2501
|
-
};
|
|
2502
|
-
var parsePiStreamLine = (line) => {
|
|
2503
|
-
if (!line.startsWith("{")) return [];
|
|
2504
|
-
try {
|
|
2505
|
-
const obj = JSON.parse(line);
|
|
2506
|
-
if (obj.type === "session" && typeof obj.id === "string") {
|
|
2507
|
-
return [{ type: "session_id", sessionId: obj.id }];
|
|
2508
|
-
}
|
|
2509
|
-
if (obj.type === "message_end" && obj.message?.role === "assistant") {
|
|
2510
|
-
const u = obj.message.usage;
|
|
2511
|
-
return contextWindowEvent(u?.input, u?.cacheRead, u?.cacheWrite);
|
|
2512
|
-
}
|
|
2513
|
-
if (obj.type === "message_update" && obj.assistantMessageEvent) {
|
|
2514
|
-
const evt = obj.assistantMessageEvent;
|
|
2515
|
-
if (evt.type === "text_delta" && typeof evt.delta === "string") {
|
|
2516
|
-
return [{ type: "text", text: evt.delta }];
|
|
2517
|
-
}
|
|
2518
|
-
return [];
|
|
2519
|
-
}
|
|
2520
|
-
if (obj.type === "tool_execution_start") {
|
|
2521
|
-
const rawName = obj.toolName;
|
|
2522
|
-
if (typeof rawName !== "string") return [];
|
|
2523
|
-
const toolName = Object.keys(TOOL_ARG_FIELDS).find(
|
|
2524
|
-
(name) => name.toLowerCase() === rawName.toLowerCase()
|
|
2525
|
-
);
|
|
2526
|
-
if (toolName === void 0) return [];
|
|
2527
|
-
const argField = TOOL_ARG_FIELDS[toolName];
|
|
2528
|
-
if (argField === void 0) return [];
|
|
2529
|
-
const args = obj.args;
|
|
2530
|
-
if (!args) return [];
|
|
2531
|
-
const argValue = args[argField];
|
|
2532
|
-
if (typeof argValue !== "string") return [];
|
|
2533
|
-
return [{ type: "tool_call", name: toolName, args: argValue }];
|
|
2534
|
-
}
|
|
2535
|
-
if (obj.type === "agent_error" || obj.type === "error") {
|
|
2536
|
-
const msg = extractErrorMessage(obj);
|
|
2537
|
-
return msg ? [{ type: "error", message: msg }] : [];
|
|
2538
|
-
}
|
|
2539
|
-
if (obj.type === "agent_end" && Array.isArray(obj.messages)) {
|
|
2540
|
-
return parsePiAgentEnd(obj.messages);
|
|
2541
|
-
}
|
|
2542
|
-
} catch {
|
|
2543
|
-
}
|
|
2544
|
-
return [];
|
|
2545
|
-
};
|
|
2546
|
-
var pi = (model, options) => ({
|
|
2547
|
-
name: "pi",
|
|
2548
|
-
env: options?.env ?? {},
|
|
2549
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2550
|
-
sessionStorage: makePiSessionStorage(options),
|
|
2551
|
-
buildPrintCommand({
|
|
2552
|
-
prompt,
|
|
2553
|
-
resumeSession,
|
|
2554
|
-
forkSession
|
|
2555
|
-
}) {
|
|
2556
|
-
const thinkingFlag = options?.thinking ? ` --thinking ${options.thinking}` : "";
|
|
2557
|
-
const sessionFlag = resumeSession ? ` --${forkSession ? "fork" : "session"} ${shellEscape(resumeSession)}` : "";
|
|
2558
|
-
return {
|
|
2559
|
-
command: `pi -p --mode json --model ${shellEscape(model)}${thinkingFlag}${sessionFlag}`,
|
|
2560
|
-
stdin: prompt
|
|
2561
|
-
};
|
|
2562
|
-
},
|
|
2563
|
-
buildInteractiveArgs({ prompt }) {
|
|
2564
|
-
const args = ["pi", "--model", model];
|
|
2565
|
-
if (prompt) args.push(prompt);
|
|
2566
|
-
return args;
|
|
2567
|
-
},
|
|
2568
|
-
parseStreamLine(line) {
|
|
2569
|
-
return parsePiStreamLine(line);
|
|
2570
|
-
}
|
|
2571
|
-
});
|
|
2572
|
-
var parseCodexUsage = (usage) => {
|
|
2573
|
-
if (typeof usage !== "object" || usage === null) return void 0;
|
|
2574
|
-
const u = usage;
|
|
2575
|
-
if (typeof u.input_tokens !== "number" || typeof u.cached_input_tokens !== "number" || typeof u.output_tokens !== "number") {
|
|
2576
|
-
return void 0;
|
|
2577
|
-
}
|
|
2578
|
-
return {
|
|
2579
|
-
inputTokens: u.input_tokens - u.cached_input_tokens,
|
|
2580
|
-
cacheCreationInputTokens: 0,
|
|
2581
|
-
cacheReadInputTokens: u.cached_input_tokens,
|
|
2582
|
-
outputTokens: u.output_tokens
|
|
2583
|
-
};
|
|
2584
|
-
};
|
|
2585
|
-
var parseCodexSessionContextWindow = (content) => {
|
|
2586
|
-
const lines = content.split("\n");
|
|
2587
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2588
|
-
const line = lines[i];
|
|
2589
|
-
if (!line.startsWith("{")) continue;
|
|
2590
|
-
try {
|
|
2591
|
-
const obj = JSON.parse(line);
|
|
2592
|
-
if (obj.type !== "event_msg" || obj.payload?.type !== "token_count") {
|
|
2593
|
-
continue;
|
|
2594
|
-
}
|
|
2595
|
-
const { info } = obj.payload;
|
|
2596
|
-
const tokens = info?.last_token_usage?.input_tokens;
|
|
2597
|
-
if (typeof tokens !== "number" || tokens <= 0) continue;
|
|
2598
|
-
const limit = info.model_context_window;
|
|
2599
|
-
return typeof limit === "number" && limit > 0 ? { tokens, limit } : { tokens };
|
|
2600
|
-
} catch {
|
|
2601
|
-
}
|
|
2602
|
-
}
|
|
2603
|
-
return void 0;
|
|
2604
|
-
};
|
|
2605
|
-
var parseCodexStreamLine = (line) => {
|
|
2606
|
-
if (!line.startsWith("{")) return [];
|
|
2607
|
-
try {
|
|
2608
|
-
const obj = JSON.parse(line);
|
|
2609
|
-
if (obj.type === "thread.started" && typeof obj.thread_id === "string") {
|
|
2610
|
-
return [{ type: "session_id", sessionId: obj.thread_id }];
|
|
2611
|
-
}
|
|
2612
|
-
if (obj.type === "item.completed" && obj.item?.type === "agent_message" && typeof obj.item.text === "string") {
|
|
2613
|
-
const { text: text2 } = obj.item;
|
|
2614
|
-
return [
|
|
2615
|
-
{ type: "text", text: text2 },
|
|
2616
|
-
{ type: "result", result: text2 }
|
|
2617
|
-
];
|
|
2618
|
-
}
|
|
2619
|
-
if (obj.type === "item.started" && obj.item?.type === "command_execution" && typeof obj.item.command === "string") {
|
|
2620
|
-
return [{ type: "tool_call", name: "Bash", args: obj.item.command }];
|
|
2621
|
-
}
|
|
2622
|
-
if (obj.type === "error") {
|
|
2623
|
-
const msg = extractErrorMessage(obj);
|
|
2624
|
-
return msg ? [{ type: "result", result: msg }] : [];
|
|
2625
|
-
}
|
|
2626
|
-
if (obj.type === "turn.failed") {
|
|
2627
|
-
const msg = extractErrorMessage(obj);
|
|
2628
|
-
return [{ type: "error", message: msg ?? "codex turn failed" }];
|
|
2629
|
-
}
|
|
2630
|
-
if (obj.type === "turn.completed") {
|
|
2631
|
-
const usage = parseCodexUsage(obj.usage);
|
|
2632
|
-
return usage ? [{ type: "usage", usage }] : [];
|
|
2633
|
-
}
|
|
2634
|
-
} catch {
|
|
2635
|
-
}
|
|
2636
|
-
return [];
|
|
2637
|
-
};
|
|
2638
|
-
var buildCodexPrintCommand = (model, options, { prompt, resumeSession, forkSession }) => {
|
|
2639
|
-
const effortFlag = options?.effort ? ` -c ${shellEscape(`model_reasoning_effort="${options.effort}"`)}` : "";
|
|
2640
|
-
const approvalsFlags = options?.approvalsReviewer === "auto_review" ? ` -a on-request -s danger-full-access -c ${shellEscape(`approvals_reviewer="auto_review"`)}` : " --dangerously-bypass-approvals-and-sandbox";
|
|
2641
|
-
let base;
|
|
2642
|
-
if (resumeSession && forkSession) {
|
|
2643
|
-
base = `codex exec fork ${shellEscape(resumeSession)}`;
|
|
2644
|
-
} else if (resumeSession) {
|
|
2645
|
-
base = `codex exec resume ${shellEscape(resumeSession)}`;
|
|
2646
|
-
} else {
|
|
2647
|
-
base = "codex exec";
|
|
2648
|
-
}
|
|
2649
|
-
const stdinArg = resumeSession ? " -" : "";
|
|
2650
|
-
return {
|
|
2651
|
-
command: `${base} --json${approvalsFlags} -m ${shellEscape(model)}${effortFlag}${stdinArg}`,
|
|
2652
|
-
stdin: prompt
|
|
2653
|
-
};
|
|
2654
|
-
};
|
|
2655
|
-
var codex = (model, options) => ({
|
|
2656
|
-
name: "codex",
|
|
2657
|
-
env: options?.env ?? {},
|
|
2658
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2659
|
-
sessionStorage: makeCodexSessionStorage(options),
|
|
2660
|
-
buildPrintCommand(commandOptions) {
|
|
2661
|
-
return buildCodexPrintCommand(model, options, commandOptions);
|
|
2662
|
-
},
|
|
2663
|
-
buildInteractiveArgs({ prompt }) {
|
|
2664
|
-
const args = ["codex", "--model", model];
|
|
2665
|
-
if (prompt) args.push(prompt);
|
|
2666
|
-
return args;
|
|
2667
|
-
},
|
|
2668
|
-
parseStreamLine(line) {
|
|
2669
|
-
return parseCodexStreamLine(line);
|
|
2670
|
-
},
|
|
2671
|
-
parseSessionContextWindow(content) {
|
|
2672
|
-
return parseCodexSessionContextWindow(content);
|
|
2673
|
-
}
|
|
2674
|
-
});
|
|
2675
|
-
var makeCursorSessionStorage = (options) => {
|
|
2676
|
-
const hostDir = options?.sessionStorage?.hostChatsDir ?? cursorHostChatsDir();
|
|
2677
|
-
const sandboxDirOverride = options?.sessionStorage?.sandboxChatsDir;
|
|
2678
|
-
return {
|
|
2679
|
-
...makeSessionFileStorage({
|
|
2680
|
-
hostRoot: hostDir,
|
|
2681
|
-
hostPath: (cwd, id) => join(hostDir, cursorChatDirName(cwd), id, "store.db"),
|
|
2682
|
-
hostPathsById: (id, chatDirs) => chatDirs.map((chatDir) => join(hostDir, chatDir, id, "store.db")),
|
|
2683
|
-
sandboxPath: (cwd, id, dirs) => posix.join(
|
|
2684
|
-
sandboxDirOverride ?? posix.join(dirs.home, ".cursor", "chats"),
|
|
2685
|
-
cursorChatDirName(cwd),
|
|
2686
|
-
id,
|
|
2687
|
-
"store.db"
|
|
2688
|
-
)
|
|
2689
|
-
}),
|
|
2690
|
-
canFork: false
|
|
2691
|
-
};
|
|
2692
|
-
};
|
|
2693
|
-
var cursor = (model, options) => ({
|
|
2694
|
-
name: "cursor",
|
|
2695
|
-
env: options?.env ?? {},
|
|
2696
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2697
|
-
sessionStorage: makeCursorSessionStorage(options),
|
|
2698
|
-
buildPrintCommand({
|
|
2699
|
-
prompt,
|
|
2700
|
-
dangerouslySkipPermissions,
|
|
2701
|
-
resumeSession,
|
|
2702
|
-
forkSession
|
|
2703
|
-
}) {
|
|
2704
|
-
if (resumeSession !== void 0 && forkSession === true) {
|
|
2705
|
-
throw new ForkNotSupportedError({
|
|
2706
|
-
message: "cursor cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.",
|
|
2707
|
-
agentProvider: "cursor"
|
|
2708
|
-
});
|
|
2709
|
-
}
|
|
2710
|
-
assertCursorPrintPromptFitsArgv(prompt);
|
|
2711
|
-
const forceFlag = dangerouslySkipPermissions ? " --force" : "";
|
|
2712
|
-
const resumeFlag = resumeSession === void 0 ? "" : ` --resume=${shellEscape(resumeSession)}`;
|
|
2713
|
-
return {
|
|
2714
|
-
command: `agent --print --output-format stream-json --model ${shellEscape(model)} ${forceFlag}${resumeFlag} ${shellEscape(prompt)}`
|
|
2715
|
-
};
|
|
2716
|
-
},
|
|
2717
|
-
buildInteractiveArgs({
|
|
2718
|
-
prompt,
|
|
2719
|
-
dangerouslySkipPermissions
|
|
2720
|
-
}) {
|
|
2721
|
-
const args = ["agent", "--model", model];
|
|
2722
|
-
if (dangerouslySkipPermissions) args.push("--force");
|
|
2723
|
-
if (prompt) args.push(prompt);
|
|
2724
|
-
return args;
|
|
2725
|
-
},
|
|
2726
|
-
parseStreamLine(line) {
|
|
2727
|
-
return parseCursorStreamLine(line);
|
|
2728
|
-
}
|
|
2729
|
-
});
|
|
2730
|
-
var OPENCODE_TOOL_ARG_FIELDS = {
|
|
2731
|
-
bash: "command",
|
|
2732
|
-
webfetch: "url",
|
|
2733
|
-
task: "description"
|
|
2734
|
-
};
|
|
2735
|
-
var parseOpenCodeStreamLine = (line) => {
|
|
2736
|
-
if (!line.startsWith("{")) return [];
|
|
2737
|
-
try {
|
|
2738
|
-
const obj = JSON.parse(line);
|
|
2739
|
-
const { part } = obj;
|
|
2740
|
-
if (obj.type === "step_start" && typeof obj.sessionID === "string") {
|
|
2741
|
-
return [{ type: "session_id", sessionId: obj.sessionID }];
|
|
2742
|
-
}
|
|
2743
|
-
if (obj.type === "step_finish" && part?.tokens) {
|
|
2744
|
-
const t = part.tokens;
|
|
2745
|
-
return contextWindowEvent(t.input, t.cache?.read, t.cache?.write);
|
|
2746
|
-
}
|
|
2747
|
-
if (obj.type === "text" && part?.type === "text" && typeof part.text === "string") {
|
|
2748
|
-
return [
|
|
2749
|
-
{ type: "text", text: part.text },
|
|
2750
|
-
{ type: "result", result: part.text }
|
|
2751
|
-
];
|
|
2752
|
-
}
|
|
2753
|
-
if (obj.type === "tool_use" && part?.type === "tool") {
|
|
2754
|
-
if (typeof part.tool !== "string") return [];
|
|
2755
|
-
const state = part.state;
|
|
2756
|
-
if (state?.status !== "completed") return [];
|
|
2757
|
-
const { input } = state;
|
|
2758
|
-
if (!input) return [];
|
|
2759
|
-
const argField = OPENCODE_TOOL_ARG_FIELDS[part.tool];
|
|
2760
|
-
const argValue = argField === void 0 ? void 0 : input[argField];
|
|
2761
|
-
const args = typeof argValue === "string" ? argValue : JSON.stringify(input);
|
|
2762
|
-
return [{ type: "tool_call", name: part.tool, args }];
|
|
2763
|
-
}
|
|
2764
|
-
if (obj.type === "error") {
|
|
2765
|
-
const msg = extractErrorMessage(obj);
|
|
2766
|
-
return msg ? [{ type: "error", message: msg }] : [];
|
|
2767
|
-
}
|
|
2768
|
-
} catch {
|
|
2769
|
-
}
|
|
2770
|
-
return [];
|
|
2771
|
-
};
|
|
2772
|
-
var makeOpenCodeSessionStorage = (options) => {
|
|
2773
|
-
const hostDir = options?.sessionStorage?.hostSessionsDir ?? opencodeHostSessionsDir();
|
|
2774
|
-
const exportDirOverride = options?.sessionStorage?.sandboxExportDir;
|
|
2775
|
-
const hostPath = (id) => join(hostDir, `${id}.json`);
|
|
2776
|
-
return makeSessionFileStorage({
|
|
2777
|
-
hostRoot: hostDir,
|
|
2778
|
-
hostPath: (_cwd, id) => hostPath(id),
|
|
2779
|
-
// A no-sandbox run resumes from OpenCode's own database, which can't be
|
|
2780
|
-
// queried by id from here; OpenCode reports an unknown id itself.
|
|
2781
|
-
hostPathsById: (id) => [hostPath(id), opencodeHostDatabase()],
|
|
2782
|
-
sandboxPath: (_cwd, id, dirs) => posix.join(exportDirOverride ?? dirs.tmp, `${id}.json`),
|
|
2783
|
-
sandboxExport: (id, path2) => `opencode export ${shellEscape(id)} > ${shellEscape(path2)}`,
|
|
2784
|
-
sandboxImport: (_id, path2) => `opencode import ${shellEscape(path2)}`
|
|
2785
|
-
});
|
|
2786
|
-
};
|
|
2787
|
-
var opencode = (model, options) => ({
|
|
2788
|
-
name: "opencode",
|
|
2789
|
-
env: options?.env ?? {},
|
|
2790
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2791
|
-
sessionStorage: makeOpenCodeSessionStorage(options),
|
|
2792
|
-
buildPrintCommand({
|
|
2793
|
-
prompt,
|
|
2794
|
-
dangerouslySkipPermissions,
|
|
2795
|
-
resumeSession,
|
|
2796
|
-
forkSession
|
|
2797
|
-
}) {
|
|
2798
|
-
const variantFlag = options?.variant ? ` --variant ${shellEscape(options.variant)}` : "";
|
|
2799
|
-
const agentFlag = options?.agent ? ` --agent ${shellEscape(options.agent)}` : "";
|
|
2800
|
-
const permissionsFlag = dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
|
|
2801
|
-
const sessionFlags = resumeSession === void 0 ? "" : ` --session ${shellEscape(resumeSession)}${forkSession === true ? " --fork" : ""}`;
|
|
2802
|
-
return {
|
|
2803
|
-
command: `opencode run --format json --model ${shellEscape(model)}${variantFlag}${agentFlag}${permissionsFlag}${sessionFlags} ${shellEscape(prompt)}`
|
|
2804
|
-
};
|
|
2805
|
-
},
|
|
2806
|
-
buildInteractiveArgs({ prompt }) {
|
|
2807
|
-
const args = ["opencode", "--model", model];
|
|
2808
|
-
if (options?.agent) args.push("--agent", options.agent);
|
|
2809
|
-
if (prompt) args.push("--prompt", prompt);
|
|
2810
|
-
return args;
|
|
2811
|
-
},
|
|
2812
|
-
parseStreamLine(line) {
|
|
2813
|
-
return parseOpenCodeStreamLine(line);
|
|
2814
|
-
}
|
|
2815
|
-
});
|
|
2816
|
-
var COPILOT_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
|
|
2817
|
-
var assertCopilotPrintPromptFitsArgv = (prompt) => {
|
|
2818
|
-
const n = Buffer.byteLength(prompt, "utf8");
|
|
2819
|
-
if (n > COPILOT_PRINT_PROMPT_MAX_BYTES) {
|
|
2820
|
-
throw new Error(
|
|
2821
|
-
`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.`
|
|
2822
|
-
);
|
|
2823
|
-
}
|
|
2824
|
-
};
|
|
2825
|
-
var parseCopilotStreamLine = (line) => {
|
|
2826
|
-
if (!line.startsWith("{")) return [];
|
|
2827
|
-
try {
|
|
2828
|
-
const obj = JSON.parse(line);
|
|
2829
|
-
if (obj.type === "assistant.message_delta" && typeof obj.data?.deltaContent === "string") {
|
|
2830
|
-
return [{ type: "text", text: obj.data.deltaContent }];
|
|
2831
|
-
}
|
|
2832
|
-
if (obj.type === "tool.execution_start") {
|
|
2833
|
-
const rawName = obj.data?.toolName;
|
|
2834
|
-
if (typeof rawName !== "string") return [];
|
|
2835
|
-
const toolName = rawName === "bash" ? "Bash" : rawName;
|
|
2836
|
-
const argField = TOOL_ARG_FIELDS[toolName];
|
|
2837
|
-
if (argField === void 0) return [];
|
|
2838
|
-
const args = obj.data?.arguments;
|
|
2839
|
-
if (!args) return [];
|
|
2840
|
-
const argValue = args[argField];
|
|
2841
|
-
if (typeof argValue !== "string") return [];
|
|
2842
|
-
return [{ type: "tool_call", name: toolName, args: argValue }];
|
|
2843
|
-
}
|
|
2844
|
-
if (obj.type === "assistant.message" && typeof obj.data?.content === "string" && obj.data.content.length > 0) {
|
|
2845
|
-
return [{ type: "result", result: obj.data.content }];
|
|
2846
|
-
}
|
|
2847
|
-
if (obj.type === "session.usage_checkpoint") {
|
|
2848
|
-
return contextWindowEvent(
|
|
2849
|
-
obj.data?.accountingSnapshot?.lastCallInputTokens
|
|
2850
|
-
);
|
|
2851
|
-
}
|
|
2852
|
-
if (obj.type === "result" && typeof obj.sessionId === "string") {
|
|
2853
|
-
return [{ type: "session_id", sessionId: obj.sessionId }];
|
|
2854
|
-
}
|
|
2855
|
-
if (obj.type === "error" || obj.type === "agent_error") {
|
|
2856
|
-
const msg = extractErrorMessage(obj);
|
|
2857
|
-
return msg ? [{ type: "error", message: msg }] : [];
|
|
2858
|
-
}
|
|
2859
|
-
} catch {
|
|
2860
|
-
}
|
|
2861
|
-
return [];
|
|
2862
|
-
};
|
|
2863
|
-
var makeCopilotSessionStorage = (options) => {
|
|
2864
|
-
const hostDir = options?.sessionStorage?.hostSessionsDir ?? copilotHostSessionsDir();
|
|
2865
|
-
const sandboxDirOverride = options?.sessionStorage?.sandboxSessionsDir;
|
|
2866
|
-
const hostPath = (id) => join(hostDir, id, "events.jsonl");
|
|
2867
|
-
return {
|
|
2868
|
-
...makeSessionFileStorage({
|
|
2869
|
-
hostRoot: hostDir,
|
|
2870
|
-
hostPath: (_cwd, id) => hostPath(id),
|
|
2871
|
-
hostPathsById: (id) => [hostPath(id)],
|
|
2872
|
-
sandboxPath: (_cwd, id, dirs) => copilotSessionPath(
|
|
2873
|
-
sandboxDirOverride ?? posix.join(dirs.home, ".copilot", "session-state"),
|
|
2874
|
-
id
|
|
2875
|
-
),
|
|
2876
|
-
rewrite: transferCopilotSession
|
|
2877
|
-
}),
|
|
2878
|
-
canFork: false
|
|
2879
|
-
};
|
|
2880
|
-
};
|
|
2881
|
-
var copilot = (model, options) => ({
|
|
2882
|
-
name: "copilot",
|
|
2883
|
-
env: options?.env ?? {},
|
|
2884
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2885
|
-
sessionStorage: makeCopilotSessionStorage(options),
|
|
2886
|
-
buildPrintCommand({
|
|
2887
|
-
prompt,
|
|
2888
|
-
dangerouslySkipPermissions,
|
|
2889
|
-
resumeSession,
|
|
2890
|
-
forkSession
|
|
2891
|
-
}) {
|
|
2892
|
-
if (resumeSession !== void 0 && forkSession === true) {
|
|
2893
|
-
throw new ForkNotSupportedError({
|
|
2894
|
-
message: "copilot cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.",
|
|
2895
|
-
agentProvider: "copilot"
|
|
2896
|
-
});
|
|
2897
|
-
}
|
|
2898
|
-
assertCopilotPrintPromptFitsArgv(prompt);
|
|
2899
|
-
const allowAll = dangerouslySkipPermissions ? " --allow-all-tools" : "";
|
|
2900
|
-
const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
|
|
2901
|
-
const resumeFlag = resumeSession === void 0 ? "" : ` --resume=${shellEscape(resumeSession)}`;
|
|
2902
|
-
return {
|
|
2903
|
-
command: `copilot -p ${shellEscape(prompt)} --output-format json --model ${shellEscape(model)}${allowAll}${effortFlag}${resumeFlag}`
|
|
2904
|
-
};
|
|
2905
|
-
},
|
|
2906
|
-
buildInteractiveArgs({ prompt }) {
|
|
2907
|
-
const args = ["copilot", "--model", model];
|
|
2908
|
-
if (prompt) args.push("-i", prompt);
|
|
2909
|
-
return args;
|
|
2910
|
-
},
|
|
2911
|
-
parseStreamLine(line) {
|
|
2912
|
-
return parseCopilotStreamLine(line);
|
|
2913
|
-
}
|
|
2914
|
-
});
|
|
2915
|
-
var buildClaudePrintCommand = (model, options, {
|
|
2916
|
-
prompt,
|
|
2917
|
-
dangerouslySkipPermissions,
|
|
2918
|
-
resumeSession,
|
|
2919
|
-
forkSession
|
|
2920
|
-
}) => {
|
|
2921
|
-
const skipPermissionsFlag = dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
|
|
2922
|
-
const permissionFlag = options?.permissionMode ? ` --permission-mode ${options.permissionMode}` : skipPermissionsFlag;
|
|
2923
|
-
const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
|
|
2924
|
-
const resumeFlag = resumeSession ? ` --resume ${shellEscape(resumeSession)}` : "";
|
|
2925
|
-
const forkFlag = resumeSession && forkSession ? " --fork-session" : "";
|
|
2926
|
-
return {
|
|
2927
|
-
command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag} -p -`,
|
|
2928
|
-
stdin: prompt
|
|
2929
|
-
};
|
|
2930
|
-
};
|
|
2931
|
-
var parseClaudeSessionUsage = (content) => {
|
|
2932
|
-
const lines = content.split("\n");
|
|
2933
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2934
|
-
const line = lines[i];
|
|
2935
|
-
if (!line.startsWith("{")) continue;
|
|
2936
|
-
try {
|
|
2937
|
-
const obj = JSON.parse(line);
|
|
2938
|
-
if (obj.type === "assistant" && obj.message?.usage) {
|
|
2939
|
-
const u = obj.message.usage;
|
|
2940
|
-
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") {
|
|
2941
|
-
return {
|
|
2942
|
-
inputTokens: u.input_tokens,
|
|
2943
|
-
cacheCreationInputTokens: u.cache_creation_input_tokens,
|
|
2944
|
-
cacheReadInputTokens: u.cache_read_input_tokens,
|
|
2945
|
-
outputTokens: u.output_tokens
|
|
2946
|
-
};
|
|
2947
|
-
}
|
|
2948
|
-
}
|
|
2949
|
-
} catch {
|
|
2950
|
-
}
|
|
2951
|
-
}
|
|
2952
|
-
return void 0;
|
|
2953
|
-
};
|
|
2954
|
-
var claudeCode = (model, options) => ({
|
|
2955
|
-
name: "claude-code",
|
|
2956
|
-
env: options?.env ?? {},
|
|
2957
|
-
captureSessions: options?.captureSessions ?? true,
|
|
2958
|
-
sessionStorage: makeClaudeSessionStorage(options),
|
|
2959
|
-
buildPrintCommand(commandOptions) {
|
|
2960
|
-
return buildClaudePrintCommand(model, options, commandOptions);
|
|
2961
|
-
},
|
|
2962
|
-
buildInteractiveArgs({
|
|
2963
|
-
prompt,
|
|
2964
|
-
dangerouslySkipPermissions
|
|
2965
|
-
}) {
|
|
2966
|
-
const args = ["claude"];
|
|
2967
|
-
if (options?.permissionMode) {
|
|
2968
|
-
args.push("--permission-mode", options.permissionMode);
|
|
2969
|
-
} else if (dangerouslySkipPermissions) {
|
|
2970
|
-
args.push("--dangerously-skip-permissions");
|
|
2971
|
-
}
|
|
2972
|
-
args.push("--model", model);
|
|
2973
|
-
if (options?.effort) args.push("--effort", options.effort);
|
|
2974
|
-
if (prompt) args.push(prompt);
|
|
2975
|
-
return args;
|
|
2976
|
-
},
|
|
2977
|
-
parseStreamLine(line) {
|
|
2978
|
-
return [...parseStreamJsonLine(line), ...parseClaudeContextWindow(line)];
|
|
2979
|
-
},
|
|
2980
|
-
parseSessionUsage(content) {
|
|
2981
|
-
return parseClaudeSessionUsage(content);
|
|
2982
|
-
}
|
|
2983
|
-
});
|
|
2984
|
-
|
|
2985
|
-
// src/createSandbox.ts
|
|
2986
|
-
var withAgentEnv = (agent, sandboxProviderEnv) => {
|
|
2987
|
-
const entries = Object.entries(agent.env);
|
|
2988
|
-
if (entries.length === 0) {
|
|
2989
|
-
return agent;
|
|
2990
|
-
}
|
|
2991
|
-
mergeProviderEnv({
|
|
2992
|
-
resolvedEnv: {},
|
|
2993
|
-
agentProviderEnv: agent.env,
|
|
2994
|
-
sandboxProviderEnv
|
|
2995
|
-
});
|
|
2996
|
-
const invalid = entries.map(([key]) => key).filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));
|
|
2997
|
-
if (invalid.length > 0) {
|
|
2998
|
-
throw new Error(
|
|
2999
|
-
`Invalid agent provider env key(s): ${invalid.join(", ")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`
|
|
3000
|
-
);
|
|
3001
|
-
}
|
|
3002
|
-
const exports$1 = entries.map(([key, value]) => `export ${key}=${shellEscape(value)}; `).join("");
|
|
3003
|
-
return {
|
|
3004
|
-
...agent,
|
|
3005
|
-
buildPrintCommand: (options) => {
|
|
3006
|
-
const printCommand = agent.buildPrintCommand(options);
|
|
3007
|
-
return { ...printCommand, command: exports$1 + printCommand.command };
|
|
3008
|
-
}
|
|
3009
|
-
};
|
|
2046
|
+
return withResumeAndFork(
|
|
2047
|
+
{
|
|
2048
|
+
iterations: result.iterations,
|
|
2049
|
+
completionSignal: result.completionSignal,
|
|
2050
|
+
stdout: result.stdout,
|
|
2051
|
+
commits: result.commits,
|
|
2052
|
+
logFilePath: resolvedLogging.type === "file" ? resolvedLogging.path : void 0
|
|
2053
|
+
},
|
|
2054
|
+
provider,
|
|
2055
|
+
async (overrides) => rerun({ ...runOptions, ...overrides })
|
|
2056
|
+
);
|
|
3010
2057
|
};
|
|
3011
2058
|
var buildSandboxHandle = (ctx, close) => {
|
|
3012
2059
|
const {
|
|
@@ -3016,7 +2063,6 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3016
2063
|
sandboxRepoDir,
|
|
3017
2064
|
sandbox,
|
|
3018
2065
|
providerHandle,
|
|
3019
|
-
bindMountHandle,
|
|
3020
2066
|
applyToHost,
|
|
3021
2067
|
timeouts,
|
|
3022
2068
|
branchStrategy
|
|
@@ -3026,180 +2072,11 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3026
2072
|
branch,
|
|
3027
2073
|
worktreePath,
|
|
3028
2074
|
sandboxId: providerHandle !== void 0 && "sandboxId" in providerHandle ? providerHandle.sandboxId : void 0,
|
|
3029
|
-
run: async (runOptions) =>
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
const isResuming = runOptions.resumeSession !== void 0 && runOptions.resumeSession !== "";
|
|
3035
|
-
if (isResuming && maxIterations > 1) {
|
|
3036
|
-
throw new Error(
|
|
3037
|
-
"resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
|
|
3038
|
-
);
|
|
3039
|
-
}
|
|
3040
|
-
if (runOptions.forkSession === true && !isResuming) {
|
|
3041
|
-
throw new Error(
|
|
3042
|
-
"forkSession requires resumeSession. Use sandboxRunResult.fork(prompt) to fork the most recent captured session."
|
|
3043
|
-
);
|
|
3044
|
-
}
|
|
3045
|
-
if (runOptions.forkSession === true) {
|
|
3046
|
-
assertForkSupported(provider);
|
|
3047
|
-
}
|
|
3048
|
-
if (isResuming) {
|
|
3049
|
-
await assertResumeSessionExists({
|
|
3050
|
-
provider,
|
|
3051
|
-
sandboxTag: ctx.providerTag,
|
|
3052
|
-
hostRepoDir,
|
|
3053
|
-
resumeSession: runOptions.resumeSession
|
|
3054
|
-
});
|
|
3055
|
-
}
|
|
3056
|
-
const resolved = await Effect_exports.runPromise(
|
|
3057
|
-
resolvePrompt({ prompt, promptFile }).pipe(
|
|
3058
|
-
Effect_exports.provide(NodeContext_exports.layer)
|
|
3059
|
-
)
|
|
3060
|
-
);
|
|
3061
|
-
const rawPrompt = resolved.text;
|
|
3062
|
-
const isInlinePrompt = resolved.source === "inline";
|
|
3063
|
-
const userArgs = runOptions.promptArgs ?? {};
|
|
3064
|
-
const currentHostBranch = await Effect_exports.runPromise(
|
|
3065
|
-
getCurrentBranch(hostRepoDir)
|
|
3066
|
-
);
|
|
3067
|
-
const displayRef = Ref_exports.unsafeMake([]);
|
|
3068
|
-
const silentDisplayLayer = SilentDisplay.layer(displayRef);
|
|
3069
|
-
const resolvedPrompt = await Effect_exports.runPromise(
|
|
3070
|
-
Effect_exports.gen(function* () {
|
|
3071
|
-
if (isInlinePrompt) {
|
|
3072
|
-
yield* validateNoArgsWithInlinePrompt(userArgs);
|
|
3073
|
-
return rawPrompt;
|
|
3074
|
-
}
|
|
3075
|
-
yield* validateNoBuiltInArgOverride(userArgs);
|
|
3076
|
-
const effectiveArgs = {
|
|
3077
|
-
SOURCE_BRANCH: branch,
|
|
3078
|
-
TARGET_BRANCH: currentHostBranch,
|
|
3079
|
-
...userArgs
|
|
3080
|
-
};
|
|
3081
|
-
const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
|
|
3082
|
-
return yield* substitutePromptArgs(
|
|
3083
|
-
rawPrompt,
|
|
3084
|
-
effectiveArgs,
|
|
3085
|
-
builtInArgKeysSet
|
|
3086
|
-
);
|
|
3087
|
-
}).pipe(Effect_exports.provide(silentDisplayLayer))
|
|
3088
|
-
);
|
|
3089
|
-
const resolvedLogging = runOptions.logging ?? {
|
|
3090
|
-
type: "file",
|
|
3091
|
-
path: join(
|
|
3092
|
-
hostRepoDir,
|
|
3093
|
-
".sandcastle",
|
|
3094
|
-
"logs",
|
|
3095
|
-
buildLogFilename(branch, void 0, runOptions.name)
|
|
3096
|
-
)
|
|
3097
|
-
};
|
|
3098
|
-
const runDisplayLayer = resolvedLogging.type === "file" ? (() => {
|
|
3099
|
-
printFileDisplayStartup({
|
|
3100
|
-
logPath: resolvedLogging.path,
|
|
3101
|
-
agentName: runOptions.name,
|
|
3102
|
-
branch
|
|
3103
|
-
});
|
|
3104
|
-
return Layer_exports.provide(
|
|
3105
|
-
FileDisplay.layer(resolvedLogging.path),
|
|
3106
|
-
NodeFileSystem_exports.layer
|
|
3107
|
-
);
|
|
3108
|
-
})() : silentDisplayLayer;
|
|
3109
|
-
const reuseFactoryLayer = reuseSandboxFactoryLayer(
|
|
3110
|
-
{
|
|
3111
|
-
hostWorktreePath: worktreePath,
|
|
3112
|
-
sandboxRepoPath: sandboxRepoDir,
|
|
3113
|
-
applyToHost,
|
|
3114
|
-
bindMountHandle
|
|
3115
|
-
},
|
|
3116
|
-
sandbox
|
|
3117
|
-
);
|
|
3118
|
-
const streamEmitterLayer = agentStreamEmitterLayer(
|
|
3119
|
-
buildAgentStreamHandler(resolvedLogging)
|
|
3120
|
-
);
|
|
3121
|
-
const runLayer = Layer_exports.mergeAll(
|
|
3122
|
-
reuseFactoryLayer,
|
|
3123
|
-
runDisplayLayer,
|
|
3124
|
-
streamEmitterLayer
|
|
3125
|
-
);
|
|
3126
|
-
let result;
|
|
3127
|
-
try {
|
|
3128
|
-
result = await Effect_exports.runPromise(
|
|
3129
|
-
Effect_exports.gen(function* () {
|
|
3130
|
-
const display = yield* Display;
|
|
3131
|
-
yield* display.intro(runOptions.name ?? "sandcastle");
|
|
3132
|
-
const orchestrateResult = yield* orchestrate({
|
|
3133
|
-
hostRepoDir,
|
|
3134
|
-
iterations: maxIterations,
|
|
3135
|
-
prompt: resolvedPrompt,
|
|
3136
|
-
branch: mergeToHead ? void 0 : branch,
|
|
3137
|
-
provider,
|
|
3138
|
-
completionSignal: runOptions.completionSignal,
|
|
3139
|
-
idleTimeoutSeconds: runOptions.idleTimeoutSeconds,
|
|
3140
|
-
completionTimeoutSeconds: runOptions.completionTimeoutSeconds,
|
|
3141
|
-
name: runOptions.name,
|
|
3142
|
-
resumeSession: runOptions.resumeSession,
|
|
3143
|
-
forkSession: runOptions.forkSession,
|
|
3144
|
-
signal: runOptions.signal,
|
|
3145
|
-
skipPromptExpansion: isInlinePrompt,
|
|
3146
|
-
timeouts,
|
|
3147
|
-
keepSourceBranch: mergeToHead
|
|
3148
|
-
});
|
|
3149
|
-
const completion = buildCompletionMessage(
|
|
3150
|
-
orchestrateResult.completionSignal,
|
|
3151
|
-
orchestrateResult.iterations.length
|
|
3152
|
-
);
|
|
3153
|
-
yield* display.status(completion.message, completion.severity);
|
|
3154
|
-
for (const line of buildContextWindowLines(
|
|
3155
|
-
orchestrateResult.iterations
|
|
3156
|
-
)) {
|
|
3157
|
-
yield* display.text(line);
|
|
3158
|
-
}
|
|
3159
|
-
return orchestrateResult;
|
|
3160
|
-
}).pipe(Effect_exports.provide(runLayer))
|
|
3161
|
-
);
|
|
3162
|
-
} catch (error) {
|
|
3163
|
-
runOptions.signal?.throwIfAborted();
|
|
3164
|
-
throw error;
|
|
3165
|
-
}
|
|
3166
|
-
const baseResult = {
|
|
3167
|
-
iterations: result.iterations,
|
|
3168
|
-
completionSignal: result.completionSignal,
|
|
3169
|
-
stdout: result.stdout,
|
|
3170
|
-
commits: result.commits,
|
|
3171
|
-
logFilePath: resolvedLogging.type === "file" ? resolvedLogging.path : void 0
|
|
3172
|
-
};
|
|
3173
|
-
const lastIteration = result.iterations.at(-1);
|
|
3174
|
-
if (provider.sessionStorage && lastIteration?.sessionId !== void 0 && lastIteration.sessionId !== "") {
|
|
3175
|
-
const capturedSessionId = lastIteration.sessionId;
|
|
3176
|
-
return {
|
|
3177
|
-
...baseResult,
|
|
3178
|
-
resume: (nextPrompt, resumeOptions) => sandboxHandle.run({
|
|
3179
|
-
...runOptions,
|
|
3180
|
-
// The follow-up prompt is inline: drop the template's arguments.
|
|
3181
|
-
promptArgs: void 0,
|
|
3182
|
-
...resumeOptions,
|
|
3183
|
-
prompt: nextPrompt,
|
|
3184
|
-
promptFile: void 0,
|
|
3185
|
-
maxIterations: 1,
|
|
3186
|
-
resumeSession: capturedSessionId
|
|
3187
|
-
}),
|
|
3188
|
-
fork: (nextPrompt, forkOptions) => sandboxHandle.run({
|
|
3189
|
-
...runOptions,
|
|
3190
|
-
// The follow-up prompt is inline: drop the template's arguments.
|
|
3191
|
-
promptArgs: void 0,
|
|
3192
|
-
...forkOptions,
|
|
3193
|
-
prompt: nextPrompt,
|
|
3194
|
-
promptFile: void 0,
|
|
3195
|
-
maxIterations: 1,
|
|
3196
|
-
resumeSession: capturedSessionId,
|
|
3197
|
-
forkSession: true
|
|
3198
|
-
})
|
|
3199
|
-
};
|
|
3200
|
-
}
|
|
3201
|
-
return baseResult;
|
|
3202
|
-
},
|
|
2075
|
+
run: async (runOptions) => runOnSandbox(
|
|
2076
|
+
ctx,
|
|
2077
|
+
runOptions,
|
|
2078
|
+
async (options) => sandboxHandle.run(options)
|
|
2079
|
+
),
|
|
3203
2080
|
interactive: async (interactiveOptions) => {
|
|
3204
2081
|
interactiveOptions.signal?.throwIfAborted();
|
|
3205
2082
|
assertInteractiveSupported(ctx.sandboxProvider);
|
|
@@ -3220,31 +2097,13 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3220
2097
|
try {
|
|
3221
2098
|
lifecycleResult = await Effect_exports.runPromise(
|
|
3222
2099
|
Effect_exports.gen(function* () {
|
|
3223
|
-
const
|
|
3224
|
-
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
yield* validateNoArgsWithInlinePrompt(userArgs);
|
|
3231
|
-
resolvedPrompt = rawPrompt;
|
|
3232
|
-
} else {
|
|
3233
|
-
yield* validateNoBuiltInArgOverride(userArgs);
|
|
3234
|
-
const effectiveArgs = {
|
|
3235
|
-
SOURCE_BRANCH: branch,
|
|
3236
|
-
TARGET_BRANCH: currentHostBranch,
|
|
3237
|
-
...userArgs
|
|
3238
|
-
};
|
|
3239
|
-
const builtInArgKeysSet = new Set(
|
|
3240
|
-
BUILT_IN_PROMPT_ARG_KEYS
|
|
3241
|
-
);
|
|
3242
|
-
resolvedPrompt = yield* substitutePromptArgs(
|
|
3243
|
-
rawPrompt,
|
|
3244
|
-
effectiveArgs,
|
|
3245
|
-
builtInArgKeysSet
|
|
3246
|
-
);
|
|
3247
|
-
}
|
|
2100
|
+
const resolvedPrompt = yield* resolveSandboxPrompt({
|
|
2101
|
+
prompt,
|
|
2102
|
+
promptFile,
|
|
2103
|
+
promptArgs: interactiveOptions.promptArgs,
|
|
2104
|
+
branch,
|
|
2105
|
+
hostRepoDir
|
|
2106
|
+
});
|
|
3248
2107
|
return yield* withSandboxLifecycle(
|
|
3249
2108
|
{
|
|
3250
2109
|
hostRepoDir,
|
|
@@ -3256,11 +2115,11 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3256
2115
|
keepSourceBranch: mergeToHead
|
|
3257
2116
|
},
|
|
3258
2117
|
sandbox,
|
|
3259
|
-
(
|
|
3260
|
-
const fullPrompt =
|
|
3261
|
-
resolvedPrompt,
|
|
3262
|
-
|
|
3263
|
-
|
|
2118
|
+
(sandboxCtx) => Effect_exports.gen(function* () {
|
|
2119
|
+
const fullPrompt = resolvedPrompt.isInline ? resolvedPrompt.text : yield* preprocessPrompt(
|
|
2120
|
+
resolvedPrompt.text,
|
|
2121
|
+
sandboxCtx.sandbox,
|
|
2122
|
+
sandboxCtx.sandboxRepoDir
|
|
3264
2123
|
);
|
|
3265
2124
|
const interactiveArgs = buildInteractiveArgs({
|
|
3266
2125
|
prompt: fullPrompt,
|
|
@@ -3308,111 +2167,179 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3308
2167
|
};
|
|
3309
2168
|
return sandboxHandle;
|
|
3310
2169
|
};
|
|
3311
|
-
var
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
2170
|
+
var startBindMountWithGitMounts = (provider, {
|
|
2171
|
+
hostRepoDir,
|
|
2172
|
+
worktreePath,
|
|
2173
|
+
env,
|
|
2174
|
+
mountsToClean
|
|
2175
|
+
}) => resolveGitMounts(join(hostRepoDir, ".git")).pipe(
|
|
2176
|
+
Effect_exports.provide(NodeFileSystem_exports.layer),
|
|
2177
|
+
Effect_exports.catchAll(() => Effect_exports.succeed([])),
|
|
2178
|
+
// Patch git mounts for Windows worktree compatibility (ADR-0006)
|
|
2179
|
+
Effect_exports.flatMap(
|
|
2180
|
+
(gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
|
|
2181
|
+
),
|
|
2182
|
+
Effect_exports.tap((gitMounts) => {
|
|
2183
|
+
mountsToClean.push(...gitMounts);
|
|
2184
|
+
}),
|
|
2185
|
+
Effect_exports.flatMap(
|
|
2186
|
+
(gitMounts) => startSandbox({
|
|
2187
|
+
provider,
|
|
2188
|
+
hostRepoDir,
|
|
2189
|
+
env,
|
|
2190
|
+
worktreeOrRepoPath: worktreePath,
|
|
2191
|
+
gitMounts,
|
|
2192
|
+
repoDir: SANDBOX_REPO_DIR
|
|
2193
|
+
})
|
|
2194
|
+
)
|
|
2195
|
+
);
|
|
2196
|
+
var startProviderSandbox = (options) => {
|
|
2197
|
+
const { provider, hostRepoDir, worktreePath, env } = options;
|
|
2198
|
+
if (provider.tag === "isolated") {
|
|
2199
|
+
return startSandbox({
|
|
2200
|
+
provider,
|
|
2201
|
+
hostRepoDir: worktreePath,
|
|
2202
|
+
env,
|
|
2203
|
+
copyPaths: options.copyToWorktree,
|
|
2204
|
+
copySourceDir: hostRepoDir
|
|
2205
|
+
});
|
|
3324
2206
|
}
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
sandbox = options._test.buildSandbox(worktreePath);
|
|
3332
|
-
sandboxRepoDir = worktreePath;
|
|
3333
|
-
providerHandle = options._test.bindMountHandle;
|
|
3334
|
-
} else {
|
|
3335
|
-
const resolvedEnv = await Effect_exports.runPromise(
|
|
3336
|
-
resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
3337
|
-
);
|
|
3338
|
-
const env = mergeProviderEnv({
|
|
3339
|
-
resolvedEnv,
|
|
3340
|
-
agentProviderEnv: {},
|
|
3341
|
-
sandboxProviderEnv: options.sandbox.env
|
|
2207
|
+
if (provider.tag === "none") {
|
|
2208
|
+
return startSandbox({
|
|
2209
|
+
provider,
|
|
2210
|
+
hostRepoDir,
|
|
2211
|
+
env,
|
|
2212
|
+
worktreeOrRepoPath: worktreePath
|
|
3342
2213
|
});
|
|
3343
|
-
const provider = options.sandbox;
|
|
3344
|
-
let startEffect;
|
|
3345
|
-
if (provider.tag === "isolated") {
|
|
3346
|
-
startEffect = startSandbox({
|
|
3347
|
-
provider,
|
|
3348
|
-
hostRepoDir: worktreePath,
|
|
3349
|
-
env,
|
|
3350
|
-
copyPaths: options.copyToWorktree,
|
|
3351
|
-
copySourceDir: hostRepoDir
|
|
3352
|
-
});
|
|
3353
|
-
} else if (provider.tag === "none") {
|
|
3354
|
-
startEffect = startSandbox({
|
|
3355
|
-
provider,
|
|
3356
|
-
hostRepoDir,
|
|
3357
|
-
env,
|
|
3358
|
-
worktreeOrRepoPath: worktreePath
|
|
3359
|
-
});
|
|
3360
|
-
} else {
|
|
3361
|
-
startEffect = resolveGitMounts(join(hostRepoDir, ".git")).pipe(
|
|
3362
|
-
Effect_exports.provide(NodeFileSystem_exports.layer),
|
|
3363
|
-
Effect_exports.catchAll(() => Effect_exports.succeed([])),
|
|
3364
|
-
// Patch git mounts for Windows worktree compatibility (ADR-0006)
|
|
3365
|
-
Effect_exports.flatMap(
|
|
3366
|
-
(gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
|
|
3367
|
-
),
|
|
3368
|
-
Effect_exports.tap((gitMounts) => {
|
|
3369
|
-
mountsToClean.push(...gitMounts);
|
|
3370
|
-
}),
|
|
3371
|
-
Effect_exports.flatMap(
|
|
3372
|
-
(gitMounts) => startSandbox({
|
|
3373
|
-
provider,
|
|
3374
|
-
hostRepoDir,
|
|
3375
|
-
env,
|
|
3376
|
-
worktreeOrRepoPath: worktreePath,
|
|
3377
|
-
gitMounts,
|
|
3378
|
-
repoDir: SANDBOX_REPO_DIR
|
|
3379
|
-
})
|
|
3380
|
-
),
|
|
3381
|
-
Effect_exports.onError(() => removeMountTempDirs(mountsToClean))
|
|
3382
|
-
);
|
|
3383
|
-
}
|
|
3384
|
-
const startResult = await Effect_exports.runPromise(startEffect);
|
|
3385
|
-
providerHandle = startResult.handle;
|
|
3386
|
-
sandbox = startResult.sandbox;
|
|
3387
|
-
sandboxRepoDir = startResult.worktreePath;
|
|
3388
2214
|
}
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
2215
|
+
return startBindMountWithGitMounts(provider, options);
|
|
2216
|
+
};
|
|
2217
|
+
var copyIntoWorktree = (options, hostRepoDir, worktreePath) => options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated" ? copyToWorktree(
|
|
2218
|
+
options.copyToWorktree,
|
|
2219
|
+
hostRepoDir,
|
|
2220
|
+
worktreePath,
|
|
2221
|
+
options.timeouts?.copyToWorktreeMs
|
|
2222
|
+
) : Effect_exports.void;
|
|
2223
|
+
var providerHandleFields = (provider, providerHandle, worktreePath) => ({
|
|
2224
|
+
providerHandle,
|
|
2225
|
+
// Pre-narrow the bind-mount handle for the orchestrator's session-capture
|
|
2226
|
+
// path. Gating on the provider tag avoids handing a NoSandbox/Isolated
|
|
2227
|
+
// handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage and
|
|
2228
|
+
// turning a missing-feature into a runtime SessionCaptureError.
|
|
2229
|
+
bindMountHandle: provider.tag === "bind-mount" ? providerHandle : void 0,
|
|
2230
|
+
providerTag: provider.tag,
|
|
2231
|
+
sandboxProvider: provider,
|
|
2232
|
+
sandboxProviderEnv: provider.env,
|
|
2233
|
+
// Syncs an isolated sandbox's changes back to the host worktree.
|
|
2234
|
+
applyToHost: provider.tag === "isolated" && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void
|
|
2235
|
+
});
|
|
2236
|
+
var startSandboxOnWorktree = ({
|
|
2237
|
+
options,
|
|
2238
|
+
hostRepoDir,
|
|
2239
|
+
worktreePath,
|
|
2240
|
+
mountsToClean
|
|
2241
|
+
}) => Effect_exports.gen(function* () {
|
|
2242
|
+
if (options._test?.buildSandbox) {
|
|
2243
|
+
return {
|
|
2244
|
+
sandbox: options._test.buildSandbox(worktreePath),
|
|
2245
|
+
sandboxRepoDir: worktreePath,
|
|
2246
|
+
providerHandle: options._test.bindMountHandle
|
|
2247
|
+
};
|
|
2248
|
+
}
|
|
2249
|
+
const resolvedEnv = yield* resolveEnv(hostRepoDir);
|
|
2250
|
+
const env = mergeProviderEnv({
|
|
2251
|
+
resolvedEnv,
|
|
2252
|
+
agentProviderEnv: {},
|
|
2253
|
+
sandboxProviderEnv: options.sandbox.env
|
|
2254
|
+
});
|
|
2255
|
+
const startResult = yield* startProviderSandbox({
|
|
2256
|
+
provider: options.sandbox,
|
|
2257
|
+
hostRepoDir,
|
|
2258
|
+
worktreePath,
|
|
2259
|
+
env,
|
|
2260
|
+
copyToWorktree: options.copyToWorktree,
|
|
2261
|
+
mountsToClean
|
|
2262
|
+
});
|
|
2263
|
+
return {
|
|
2264
|
+
providerHandle: startResult.handle,
|
|
2265
|
+
sandbox: startResult.sandbox,
|
|
2266
|
+
sandboxRepoDir: startResult.worktreePath
|
|
2267
|
+
};
|
|
2268
|
+
});
|
|
2269
|
+
var runOnSandboxReadyHooks = ({
|
|
2270
|
+
sandbox,
|
|
2271
|
+
sandboxRepoDir,
|
|
2272
|
+
worktreePath,
|
|
2273
|
+
hooks
|
|
2274
|
+
}) => {
|
|
2275
|
+
const sandboxOnReady = hooks?.sandbox?.onSandboxReady ?? [];
|
|
2276
|
+
const hostOnReady = hooks?.host?.onSandboxReady ?? [];
|
|
2277
|
+
if (sandboxOnReady.length === 0 && hostOnReady.length === 0) {
|
|
2278
|
+
return Effect_exports.void;
|
|
2279
|
+
}
|
|
2280
|
+
return Effect_exports.gen(function* () {
|
|
2281
|
+
yield* sandbox.exec(
|
|
2282
|
+
`git config --global --add safe.directory "${sandboxRepoDir}"`
|
|
2283
|
+
);
|
|
2284
|
+
const sandboxEffects = sandboxOnReady.map(
|
|
2285
|
+
(hook) => execOk(sandbox, hook.command, {
|
|
2286
|
+
cwd: sandboxRepoDir,
|
|
2287
|
+
sudo: hook.sudo
|
|
3410
2288
|
})
|
|
3411
2289
|
);
|
|
3412
|
-
|
|
3413
|
-
|
|
2290
|
+
const allEffects = [
|
|
2291
|
+
...sandboxEffects,
|
|
2292
|
+
...hostOnReady.length > 0 ? [runHostHooks(hostOnReady, worktreePath)] : []
|
|
2293
|
+
];
|
|
2294
|
+
yield* Effect_exports.all(allEffects, { concurrency: "unbounded" });
|
|
2295
|
+
});
|
|
2296
|
+
};
|
|
2297
|
+
var tearDownStartedSandbox = (providerHandle, mountsToClean) => (providerHandle ? Effect_exports.promise(() => providerHandle.close().catch(() => void 0)) : Effect_exports.void).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)));
|
|
2298
|
+
var closeContainerOnly = (providerHandle, mountsToClean) => {
|
|
3414
2299
|
let closed = false;
|
|
3415
|
-
|
|
2300
|
+
return async () => {
|
|
2301
|
+
if (closed) {
|
|
2302
|
+
return { preservedWorktreePath: void 0 };
|
|
2303
|
+
}
|
|
2304
|
+
closed = true;
|
|
2305
|
+
if (providerHandle) {
|
|
2306
|
+
await providerHandle.close();
|
|
2307
|
+
}
|
|
2308
|
+
await Effect_exports.runPromise(removeMountTempDirs(mountsToClean));
|
|
2309
|
+
return { preservedWorktreePath: void 0 };
|
|
2310
|
+
};
|
|
2311
|
+
};
|
|
2312
|
+
var startSandboxWithReadyHooks = (options, mountsToClean) => Effect_exports.gen(function* () {
|
|
2313
|
+
const { hostRepoDir, worktreePath } = options;
|
|
2314
|
+
const started = yield* startSandboxOnWorktree({
|
|
2315
|
+
options,
|
|
2316
|
+
hostRepoDir,
|
|
2317
|
+
worktreePath,
|
|
2318
|
+
mountsToClean
|
|
2319
|
+
}).pipe(
|
|
2320
|
+
Effect_exports.onError(() => removeMountTempDirs(mountsToClean)),
|
|
2321
|
+
Effect_exports.provide(NodeContext_exports.layer)
|
|
2322
|
+
);
|
|
2323
|
+
yield* runOnSandboxReadyHooks({
|
|
2324
|
+
sandbox: started.sandbox,
|
|
2325
|
+
sandboxRepoDir: started.sandboxRepoDir,
|
|
2326
|
+
worktreePath,
|
|
2327
|
+
hooks: options.hooks
|
|
2328
|
+
}).pipe(
|
|
2329
|
+
Effect_exports.onError(
|
|
2330
|
+
() => tearDownStartedSandbox(started.providerHandle, mountsToClean)
|
|
2331
|
+
)
|
|
2332
|
+
);
|
|
2333
|
+
return started;
|
|
2334
|
+
});
|
|
2335
|
+
var createSandboxFromWorktree = async (options) => {
|
|
2336
|
+
const { branch, worktreePath, hostRepoDir } = options;
|
|
2337
|
+
validateTimeoutOptions(options);
|
|
2338
|
+
await Effect_exports.runPromise(copyIntoWorktree(options, hostRepoDir, worktreePath));
|
|
2339
|
+
const mountsToClean = [];
|
|
2340
|
+
const { providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
|
|
2341
|
+
startSandboxWithReadyHooks(options, mountsToClean)
|
|
2342
|
+
);
|
|
3416
2343
|
return buildSandboxHandle(
|
|
3417
2344
|
{
|
|
3418
2345
|
branch,
|
|
@@ -3420,191 +2347,106 @@ var createSandboxFromWorktree = async (options) => {
|
|
|
3420
2347
|
hostRepoDir,
|
|
3421
2348
|
sandboxRepoDir,
|
|
3422
2349
|
sandbox,
|
|
3423
|
-
providerHandle,
|
|
3424
|
-
bindMountHandle,
|
|
3425
|
-
providerTag: options.sandbox.tag,
|
|
3426
|
-
sandboxProvider: options.sandbox,
|
|
3427
|
-
sandboxProviderEnv: options.sandbox.env,
|
|
3428
|
-
applyToHost,
|
|
2350
|
+
...providerHandleFields(options.sandbox, providerHandle, worktreePath),
|
|
3429
2351
|
timeouts: options.timeouts,
|
|
3430
2352
|
branchStrategy: options.branchStrategy
|
|
3431
2353
|
},
|
|
3432
|
-
|
|
3433
|
-
if (closed) {
|
|
3434
|
-
return { preservedWorktreePath: void 0 };
|
|
3435
|
-
}
|
|
3436
|
-
closed = true;
|
|
3437
|
-
if (providerHandle) {
|
|
3438
|
-
await providerHandle.close();
|
|
3439
|
-
}
|
|
3440
|
-
await Effect_exports.runPromise(removeMountTempDirs(mountsToClean));
|
|
3441
|
-
return { preservedWorktreePath: void 0 };
|
|
3442
|
-
}
|
|
2354
|
+
closeContainerOnly(providerHandle, mountsToClean)
|
|
3443
2355
|
);
|
|
3444
2356
|
};
|
|
2357
|
+
var prepareSandboxOnWorktree = (options, target) => Effect_exports.gen(function* () {
|
|
2358
|
+
const { hostRepoDir, worktreePath, mountsToClean } = target;
|
|
2359
|
+
yield* copyIntoWorktree(options, hostRepoDir, worktreePath);
|
|
2360
|
+
const onWorktreeReady = options.hooks?.host?.onWorktreeReady;
|
|
2361
|
+
if (onWorktreeReady !== void 0 && onWorktreeReady.length > 0) {
|
|
2362
|
+
yield* runHostHooks(onWorktreeReady, worktreePath);
|
|
2363
|
+
}
|
|
2364
|
+
const { providerHandle, sandbox, sandboxRepoDir } = yield* startSandboxOnWorktree({
|
|
2365
|
+
options,
|
|
2366
|
+
hostRepoDir,
|
|
2367
|
+
worktreePath,
|
|
2368
|
+
mountsToClean
|
|
2369
|
+
});
|
|
2370
|
+
yield* runOnSandboxReadyHooks({
|
|
2371
|
+
sandbox,
|
|
2372
|
+
sandboxRepoDir,
|
|
2373
|
+
worktreePath,
|
|
2374
|
+
hooks: options.hooks
|
|
2375
|
+
}).pipe(
|
|
2376
|
+
Effect_exports.onError(
|
|
2377
|
+
() => tearDownStartedSandbox(providerHandle, mountsToClean)
|
|
2378
|
+
)
|
|
2379
|
+
);
|
|
2380
|
+
return { providerHandle, sandbox, sandboxRepoDir };
|
|
2381
|
+
});
|
|
2382
|
+
var setUpWorktreeSandbox = (options, mountsToClean) => Effect_exports.gen(function* () {
|
|
2383
|
+
const hostRepoDir = yield* resolveCwd(options.cwd);
|
|
2384
|
+
yield* pruneStale(hostRepoDir).pipe(
|
|
2385
|
+
Effect_exports.catchAll(() => Effect_exports.void)
|
|
2386
|
+
);
|
|
2387
|
+
const { path: worktreePath } = yield* create(hostRepoDir, {
|
|
2388
|
+
branch: options.branch,
|
|
2389
|
+
baseBranch: options.baseBranch
|
|
2390
|
+
});
|
|
2391
|
+
const prepared = yield* prepareSandboxOnWorktree(options, {
|
|
2392
|
+
hostRepoDir,
|
|
2393
|
+
worktreePath,
|
|
2394
|
+
mountsToClean
|
|
2395
|
+
}).pipe(
|
|
2396
|
+
Effect_exports.onError(
|
|
2397
|
+
() => remove(worktreePath).pipe(
|
|
2398
|
+
Effect_exports.catchAll(() => Effect_exports.void),
|
|
2399
|
+
Effect_exports.andThen(removeMountTempDirs(mountsToClean))
|
|
2400
|
+
)
|
|
2401
|
+
)
|
|
2402
|
+
);
|
|
2403
|
+
return { hostRepoDir, worktreePath, ...prepared };
|
|
2404
|
+
});
|
|
2405
|
+
var printWorktreePreserved = (worktreePath) => {
|
|
2406
|
+
console.error(`
|
|
2407
|
+
Worktree preserved at ${worktreePath}`);
|
|
2408
|
+
console.error(` To review: cd ${worktreePath}`);
|
|
2409
|
+
console.error(` To clean up: git worktree remove --force ${worktreePath}`);
|
|
2410
|
+
};
|
|
2411
|
+
var closeSandboxAndWorktree = (target) => Effect_exports.gen(function* () {
|
|
2412
|
+
const { providerHandle, mountsToClean, worktreePath } = target;
|
|
2413
|
+
if (providerHandle) {
|
|
2414
|
+
yield* Effect_exports.promise(() => providerHandle.close());
|
|
2415
|
+
}
|
|
2416
|
+
yield* removeMountTempDirs(mountsToClean);
|
|
2417
|
+
const isDirty = yield* hasUncommittedChanges(
|
|
2418
|
+
worktreePath
|
|
2419
|
+
).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(false)));
|
|
2420
|
+
if (isDirty) {
|
|
2421
|
+
return { preservedWorktreePath: worktreePath };
|
|
2422
|
+
}
|
|
2423
|
+
yield* remove(worktreePath).pipe(
|
|
2424
|
+
Effect_exports.catchAll(() => Effect_exports.void)
|
|
2425
|
+
);
|
|
2426
|
+
return { preservedWorktreePath: void 0 };
|
|
2427
|
+
});
|
|
3445
2428
|
var createSandbox = async (options) => {
|
|
3446
2429
|
const { branch } = options;
|
|
3447
|
-
const isTestMode = !!options._test?.buildSandbox;
|
|
3448
|
-
const isIsolated = options.sandbox.tag === "isolated";
|
|
3449
2430
|
validateTimeoutOptions(options);
|
|
3450
2431
|
const mountsToClean = [];
|
|
3451
2432
|
const { hostRepoDir, worktreePath, providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
Effect_exports.catchAll(() => Effect_exports.void)
|
|
3456
|
-
);
|
|
3457
|
-
const { path: worktreePath2 } = yield* create(
|
|
3458
|
-
hostRepoDir2,
|
|
3459
|
-
{ branch, baseBranch: options.baseBranch }
|
|
3460
|
-
);
|
|
3461
|
-
const prepared = yield* Effect_exports.gen(function* () {
|
|
3462
|
-
if (options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated") {
|
|
3463
|
-
yield* copyToWorktree(
|
|
3464
|
-
options.copyToWorktree,
|
|
3465
|
-
hostRepoDir2,
|
|
3466
|
-
worktreePath2,
|
|
3467
|
-
options.timeouts?.copyToWorktreeMs
|
|
3468
|
-
);
|
|
3469
|
-
}
|
|
3470
|
-
const onWorktreeReady = options.hooks?.host?.onWorktreeReady;
|
|
3471
|
-
if (onWorktreeReady !== void 0 && onWorktreeReady.length > 0) {
|
|
3472
|
-
yield* runHostHooks(onWorktreeReady, worktreePath2);
|
|
3473
|
-
}
|
|
3474
|
-
let providerHandle2;
|
|
3475
|
-
let sandbox2;
|
|
3476
|
-
let sandboxRepoDir2;
|
|
3477
|
-
if (isTestMode) {
|
|
3478
|
-
sandbox2 = options._test.buildSandbox(worktreePath2);
|
|
3479
|
-
sandboxRepoDir2 = worktreePath2;
|
|
3480
|
-
providerHandle2 = options._test.bindMountHandle;
|
|
3481
|
-
} else {
|
|
3482
|
-
const resolvedEnv = yield* resolveEnv(hostRepoDir2);
|
|
3483
|
-
const env = mergeProviderEnv({
|
|
3484
|
-
resolvedEnv,
|
|
3485
|
-
agentProviderEnv: {},
|
|
3486
|
-
sandboxProviderEnv: options.sandbox.env
|
|
3487
|
-
});
|
|
3488
|
-
const provider = options.sandbox;
|
|
3489
|
-
const startResult = yield* (() => {
|
|
3490
|
-
if (provider.tag === "isolated") {
|
|
3491
|
-
return startSandbox({
|
|
3492
|
-
provider,
|
|
3493
|
-
hostRepoDir: worktreePath2,
|
|
3494
|
-
env,
|
|
3495
|
-
copyPaths: options.copyToWorktree,
|
|
3496
|
-
copySourceDir: hostRepoDir2
|
|
3497
|
-
});
|
|
3498
|
-
}
|
|
3499
|
-
if (provider.tag === "none") {
|
|
3500
|
-
return startSandbox({
|
|
3501
|
-
provider,
|
|
3502
|
-
hostRepoDir: hostRepoDir2,
|
|
3503
|
-
env,
|
|
3504
|
-
worktreeOrRepoPath: worktreePath2
|
|
3505
|
-
});
|
|
3506
|
-
}
|
|
3507
|
-
return resolveGitMounts(join(hostRepoDir2, ".git")).pipe(
|
|
3508
|
-
Effect_exports.provide(NodeFileSystem_exports.layer),
|
|
3509
|
-
Effect_exports.catchAll(() => Effect_exports.succeed([])),
|
|
3510
|
-
// Patch git mounts for Windows worktree compatibility (ADR-0006)
|
|
3511
|
-
Effect_exports.flatMap(
|
|
3512
|
-
(gitMounts) => patchGitMountsForWindows(
|
|
3513
|
-
gitMounts,
|
|
3514
|
-
worktreePath2,
|
|
3515
|
-
SANDBOX_REPO_DIR
|
|
3516
|
-
)
|
|
3517
|
-
),
|
|
3518
|
-
Effect_exports.tap((gitMounts) => {
|
|
3519
|
-
mountsToClean.push(...gitMounts);
|
|
3520
|
-
}),
|
|
3521
|
-
Effect_exports.flatMap(
|
|
3522
|
-
(gitMounts) => startSandbox({
|
|
3523
|
-
provider,
|
|
3524
|
-
hostRepoDir: hostRepoDir2,
|
|
3525
|
-
env,
|
|
3526
|
-
worktreeOrRepoPath: worktreePath2,
|
|
3527
|
-
gitMounts,
|
|
3528
|
-
repoDir: SANDBOX_REPO_DIR
|
|
3529
|
-
})
|
|
3530
|
-
)
|
|
3531
|
-
);
|
|
3532
|
-
})();
|
|
3533
|
-
providerHandle2 = startResult.handle;
|
|
3534
|
-
sandbox2 = startResult.sandbox;
|
|
3535
|
-
sandboxRepoDir2 = startResult.worktreePath;
|
|
3536
|
-
}
|
|
3537
|
-
const sandboxOnReady = options.hooks?.sandbox?.onSandboxReady;
|
|
3538
|
-
const hostOnReady = options.hooks?.host?.onSandboxReady;
|
|
3539
|
-
if ((sandboxOnReady?.length ?? 0) > 0 || (hostOnReady?.length ?? 0) > 0) {
|
|
3540
|
-
yield* Effect_exports.gen(function* () {
|
|
3541
|
-
yield* sandbox2.exec(
|
|
3542
|
-
`git config --global --add safe.directory "${sandboxRepoDir2}"`
|
|
3543
|
-
);
|
|
3544
|
-
const sandboxEffects = (sandboxOnReady ?? []).map(
|
|
3545
|
-
(hook) => sandbox2.exec(hook.command, {
|
|
3546
|
-
cwd: sandboxRepoDir2,
|
|
3547
|
-
sudo: hook.sudo
|
|
3548
|
-
})
|
|
3549
|
-
);
|
|
3550
|
-
const allEffects = [
|
|
3551
|
-
...sandboxEffects,
|
|
3552
|
-
...hostOnReady !== void 0 && hostOnReady.length > 0 ? [runHostHooks(hostOnReady, worktreePath2)] : []
|
|
3553
|
-
];
|
|
3554
|
-
yield* Effect_exports.all(allEffects, { concurrency: "unbounded" });
|
|
3555
|
-
}).pipe(
|
|
3556
|
-
Effect_exports.onError(
|
|
3557
|
-
() => (providerHandle2 ? Effect_exports.promise(() => providerHandle2.close().catch(() => {
|
|
3558
|
-
})) : Effect_exports.void).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)))
|
|
3559
|
-
)
|
|
3560
|
-
);
|
|
3561
|
-
}
|
|
3562
|
-
return { providerHandle: providerHandle2, sandbox: sandbox2, sandboxRepoDir: sandboxRepoDir2 };
|
|
3563
|
-
}).pipe(
|
|
3564
|
-
Effect_exports.onError(
|
|
3565
|
-
() => remove(worktreePath2).pipe(
|
|
3566
|
-
Effect_exports.catchAll(() => Effect_exports.void),
|
|
3567
|
-
Effect_exports.andThen(removeMountTempDirs(mountsToClean))
|
|
3568
|
-
)
|
|
3569
|
-
)
|
|
3570
|
-
);
|
|
3571
|
-
return { hostRepoDir: hostRepoDir2, worktreePath: worktreePath2, ...prepared };
|
|
3572
|
-
}).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
2433
|
+
setUpWorktreeSandbox(options, mountsToClean).pipe(
|
|
2434
|
+
Effect_exports.provide(NodeContext_exports.layer)
|
|
2435
|
+
)
|
|
3573
2436
|
);
|
|
3574
|
-
const
|
|
2437
|
+
const unregisterShutdown = registerShutdown(() => {
|
|
2438
|
+
printWorktreePreserved(worktreePath);
|
|
2439
|
+
});
|
|
3575
2440
|
let closed = false;
|
|
3576
|
-
const forceCleanup = () => {
|
|
3577
|
-
console.error(`
|
|
3578
|
-
Worktree preserved at ${worktreePath}`);
|
|
3579
|
-
console.error(` To review: cd ${worktreePath}`);
|
|
3580
|
-
console.error(` To clean up: git worktree remove --force ${worktreePath}`);
|
|
3581
|
-
};
|
|
3582
|
-
const unregisterShutdown = registerShutdown(forceCleanup);
|
|
3583
2441
|
const doClose = async () => {
|
|
3584
2442
|
if (closed) {
|
|
3585
2443
|
return { preservedWorktreePath: void 0 };
|
|
3586
2444
|
}
|
|
3587
2445
|
closed = true;
|
|
3588
2446
|
return Effect_exports.runPromise(
|
|
3589
|
-
|
|
3590
|
-
if (providerHandle) {
|
|
3591
|
-
yield* Effect_exports.promise(() => providerHandle.close());
|
|
3592
|
-
}
|
|
3593
|
-
yield* removeMountTempDirs(mountsToClean);
|
|
3594
|
-
const isDirty = yield* hasUncommittedChanges(
|
|
3595
|
-
worktreePath
|
|
3596
|
-
).pipe(Effect_exports.catchAll(() => Effect_exports.succeed(false)));
|
|
3597
|
-
if (isDirty) {
|
|
3598
|
-
return { preservedWorktreePath: worktreePath };
|
|
3599
|
-
}
|
|
3600
|
-
yield* remove(worktreePath).pipe(
|
|
3601
|
-
Effect_exports.catchAll(() => Effect_exports.void)
|
|
3602
|
-
);
|
|
3603
|
-
return { preservedWorktreePath: void 0 };
|
|
3604
|
-
})
|
|
2447
|
+
closeSandboxAndWorktree({ providerHandle, mountsToClean, worktreePath })
|
|
3605
2448
|
);
|
|
3606
2449
|
};
|
|
3607
|
-
const bindMountHandle = options.sandbox.tag === "bind-mount" ? providerHandle : void 0;
|
|
3608
2450
|
return buildSandboxHandle(
|
|
3609
2451
|
{
|
|
3610
2452
|
branch,
|
|
@@ -3612,12 +2454,8 @@ Worktree preserved at ${worktreePath}`);
|
|
|
3612
2454
|
hostRepoDir,
|
|
3613
2455
|
sandboxRepoDir,
|
|
3614
2456
|
sandbox,
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
providerTag: options.sandbox.tag,
|
|
3618
|
-
sandboxProvider: options.sandbox,
|
|
3619
|
-
sandboxProviderEnv: options.sandbox.env,
|
|
3620
|
-
applyToHost,
|
|
2457
|
+
// applyToHost is built once, reused across runs.
|
|
2458
|
+
...providerHandleFields(options.sandbox, providerHandle, worktreePath),
|
|
3621
2459
|
timeouts: options.timeouts
|
|
3622
2460
|
},
|
|
3623
2461
|
async () => {
|
|
@@ -3626,6 +2464,122 @@ Worktree preserved at ${worktreePath}`);
|
|
|
3626
2464
|
}
|
|
3627
2465
|
);
|
|
3628
2466
|
};
|
|
2467
|
+
var substituteInteractivePromptArgs = (resolved, args) => Effect_exports.gen(function* () {
|
|
2468
|
+
const rawPrompt = resolved?.text ?? "";
|
|
2469
|
+
if (resolved?.source === "inline") {
|
|
2470
|
+
yield* validateNoArgsWithInlinePrompt(args.promptArgs ?? {});
|
|
2471
|
+
return rawPrompt;
|
|
2472
|
+
}
|
|
2473
|
+
if (resolved === void 0) {
|
|
2474
|
+
return rawPrompt;
|
|
2475
|
+
}
|
|
2476
|
+
const userArgs = args.promptArgs ?? {};
|
|
2477
|
+
yield* validateNoBuiltInArgOverride(userArgs);
|
|
2478
|
+
const currentHostBranch = yield* getCurrentBranch(
|
|
2479
|
+
args.hostRepoDir
|
|
2480
|
+
);
|
|
2481
|
+
return yield* substitutePromptArgs(
|
|
2482
|
+
rawPrompt,
|
|
2483
|
+
{
|
|
2484
|
+
SOURCE_BRANCH: args.sourceBranch,
|
|
2485
|
+
TARGET_BRANCH: currentHostBranch,
|
|
2486
|
+
...userArgs
|
|
2487
|
+
},
|
|
2488
|
+
new Set(BUILT_IN_PROMPT_ARG_KEYS)
|
|
2489
|
+
);
|
|
2490
|
+
});
|
|
2491
|
+
var resolveWorktreeEnv = (hostRepoDir, sources) => resolveEnv(hostRepoDir).pipe(
|
|
2492
|
+
Effect_exports.map((resolvedEnv) => ({
|
|
2493
|
+
...mergeProviderEnv({
|
|
2494
|
+
resolvedEnv,
|
|
2495
|
+
agentProviderEnv: sources.agentProviderEnv,
|
|
2496
|
+
sandboxProviderEnv: sources.sandboxProviderEnv
|
|
2497
|
+
}),
|
|
2498
|
+
...sources.overrides
|
|
2499
|
+
}))
|
|
2500
|
+
);
|
|
2501
|
+
var resolveWorktreeGitMounts = (hostRepoDir, worktreePath) => resolveGitMounts(join(hostRepoDir, ".git")).pipe(
|
|
2502
|
+
Effect_exports.flatMap(
|
|
2503
|
+
(rawGitMounts) => patchGitMountsForWindows(rawGitMounts, worktreePath, SANDBOX_REPO_DIR)
|
|
2504
|
+
)
|
|
2505
|
+
);
|
|
2506
|
+
var startWorktreeRunSandbox = (sandboxProvider, target) => Effect_exports.gen(function* () {
|
|
2507
|
+
const { hostRepoDir, worktreePath, env } = target;
|
|
2508
|
+
const noMounts = [];
|
|
2509
|
+
if (sandboxProvider.tag === "isolated") {
|
|
2510
|
+
const startResult2 = yield* startIsolatedSandbox({
|
|
2511
|
+
provider: sandboxProvider,
|
|
2512
|
+
hostRepoDir: worktreePath,
|
|
2513
|
+
env,
|
|
2514
|
+
copyPaths: target.copyPaths,
|
|
2515
|
+
copySourceDir: hostRepoDir
|
|
2516
|
+
});
|
|
2517
|
+
const hostLink2 = {
|
|
2518
|
+
applyToHost: () => syncOut(worktreePath, startResult2.handle)
|
|
2519
|
+
};
|
|
2520
|
+
return { ...toStarted(startResult2), gitMounts: noMounts, hostLink: hostLink2 };
|
|
2521
|
+
}
|
|
2522
|
+
if (sandboxProvider.tag === "none") {
|
|
2523
|
+
const startResult2 = yield* startSandbox({
|
|
2524
|
+
provider: sandboxProvider,
|
|
2525
|
+
hostRepoDir,
|
|
2526
|
+
env,
|
|
2527
|
+
worktreeOrRepoPath: worktreePath
|
|
2528
|
+
});
|
|
2529
|
+
const hostLink2 = {};
|
|
2530
|
+
return { ...toStarted(startResult2), gitMounts: noMounts, hostLink: hostLink2 };
|
|
2531
|
+
}
|
|
2532
|
+
const gitMounts = yield* resolveWorktreeGitMounts(
|
|
2533
|
+
hostRepoDir,
|
|
2534
|
+
worktreePath
|
|
2535
|
+
);
|
|
2536
|
+
const startResult = yield* startBindMountSandbox({
|
|
2537
|
+
provider: sandboxProvider,
|
|
2538
|
+
hostRepoDir,
|
|
2539
|
+
env,
|
|
2540
|
+
worktreeOrRepoPath: worktreePath,
|
|
2541
|
+
gitMounts,
|
|
2542
|
+
repoDir: SANDBOX_REPO_DIR
|
|
2543
|
+
});
|
|
2544
|
+
const hostLink = { bindMountHandle: startResult.handle };
|
|
2545
|
+
return { ...toStarted(startResult), gitMounts, hostLink };
|
|
2546
|
+
});
|
|
2547
|
+
var skipHostSync = () => Effect_exports.void;
|
|
2548
|
+
var toStarted = (startResult) => ({ handle: startResult.handle, sandboxRepoDir: startResult.worktreePath });
|
|
2549
|
+
var reuseStartedSandboxLayer = (handle, hostLink, paths) => reuseSandboxFactoryLayer(
|
|
2550
|
+
{
|
|
2551
|
+
...paths,
|
|
2552
|
+
applyToHost: hostLink.applyToHost ?? skipHostSync,
|
|
2553
|
+
bindMountHandle: hostLink.bindMountHandle
|
|
2554
|
+
},
|
|
2555
|
+
makeSandboxFromHandle(handle)
|
|
2556
|
+
);
|
|
2557
|
+
var resolveWorktreeRunDisplay = (opts, hostRepoDir, branch) => {
|
|
2558
|
+
const resolvedLogging = opts.logging ?? {
|
|
2559
|
+
type: "file",
|
|
2560
|
+
path: join(
|
|
2561
|
+
hostRepoDir,
|
|
2562
|
+
".sandcastle",
|
|
2563
|
+
"logs",
|
|
2564
|
+
buildLogFilename(branch, void 0, opts.name)
|
|
2565
|
+
)
|
|
2566
|
+
};
|
|
2567
|
+
if (resolvedLogging.type !== "file") {
|
|
2568
|
+
return { resolvedLogging, runDisplayLayer: ClackDisplay.layer };
|
|
2569
|
+
}
|
|
2570
|
+
printFileDisplayStartup({
|
|
2571
|
+
logPath: resolvedLogging.path,
|
|
2572
|
+
agentName: opts.name,
|
|
2573
|
+
branch
|
|
2574
|
+
});
|
|
2575
|
+
return {
|
|
2576
|
+
resolvedLogging,
|
|
2577
|
+
runDisplayLayer: Layer_exports.provide(
|
|
2578
|
+
FileDisplay.layer(resolvedLogging.path),
|
|
2579
|
+
NodeFileSystem_exports.layer
|
|
2580
|
+
)
|
|
2581
|
+
};
|
|
2582
|
+
};
|
|
3629
2583
|
var createWorktree = async (options) => {
|
|
3630
2584
|
validateTimeoutOptions(options);
|
|
3631
2585
|
const branch = options.branchStrategy.type === "branch" ? options.branchStrategy.branch : void 0;
|
|
@@ -3692,36 +2646,20 @@ var createWorktree = async (options) => {
|
|
|
3692
2646
|
}
|
|
3693
2647
|
const inner = Effect_exports.gen(function* () {
|
|
3694
2648
|
const d = yield* Display;
|
|
3695
|
-
const
|
|
3696
|
-
const
|
|
3697
|
-
const rawPrompt = resolved?.text ?? "";
|
|
3698
|
-
const isInlinePrompt = resolved?.source === "inline";
|
|
3699
|
-
const resolvedEnv = yield* resolveEnv(hostRepoDir);
|
|
3700
|
-
const env = mergeProviderEnv({
|
|
3701
|
-
resolvedEnv,
|
|
2649
|
+
const resolved = prompt !== void 0 || promptFile !== void 0 ? yield* resolvePrompt({ prompt, promptFile }) : void 0;
|
|
2650
|
+
const effectiveEnv = yield* resolveWorktreeEnv(hostRepoDir, {
|
|
3702
2651
|
agentProviderEnv: provider.env,
|
|
3703
|
-
sandboxProviderEnv: resolvedSandbox.env
|
|
2652
|
+
sandboxProviderEnv: resolvedSandbox.env,
|
|
2653
|
+
overrides: opts.env
|
|
3704
2654
|
});
|
|
3705
|
-
const
|
|
3706
|
-
|
|
3707
|
-
|
|
3708
|
-
|
|
3709
|
-
|
|
3710
|
-
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
TARGET_BRANCH: currentHostBranch,
|
|
3714
|
-
...userArgs
|
|
3715
|
-
};
|
|
3716
|
-
const builtInArgKeysSet = new Set(BUILT_IN_PROMPT_ARG_KEYS);
|
|
3717
|
-
substitutedPrompt = yield* substitutePromptArgs(
|
|
3718
|
-
rawPrompt,
|
|
3719
|
-
effectiveArgs,
|
|
3720
|
-
builtInArgKeysSet
|
|
3721
|
-
);
|
|
3722
|
-
} else if (isInlinePrompt) {
|
|
3723
|
-
yield* validateNoArgsWithInlinePrompt(opts.promptArgs ?? {});
|
|
3724
|
-
}
|
|
2655
|
+
const substitutedPrompt = yield* substituteInteractivePromptArgs(
|
|
2656
|
+
resolved,
|
|
2657
|
+
{
|
|
2658
|
+
promptArgs: opts.promptArgs,
|
|
2659
|
+
hostRepoDir,
|
|
2660
|
+
sourceBranch: worktreeInfo.branch
|
|
2661
|
+
}
|
|
2662
|
+
);
|
|
3725
2663
|
yield* d.intro(opts.name ?? "sandcastle interactive");
|
|
3726
2664
|
yield* d.summary("Interactive Session", {
|
|
3727
2665
|
Agent: opts.name ?? provider.name,
|
|
@@ -3730,6 +2668,7 @@ var createWorktree = async (options) => {
|
|
|
3730
2668
|
});
|
|
3731
2669
|
const mountsToClean = [];
|
|
3732
2670
|
let handle;
|
|
2671
|
+
let applyToHost = skipHostSync;
|
|
3733
2672
|
if (resolvedSandbox.tag === "none") {
|
|
3734
2673
|
handle = yield* Effect_exports.promise(
|
|
3735
2674
|
async () => resolvedSandbox.create({
|
|
@@ -3740,7 +2679,7 @@ var createWorktree = async (options) => {
|
|
|
3740
2679
|
} else if (resolvedSandbox.tag === "isolated") {
|
|
3741
2680
|
const startResult = yield* d.taskLog(
|
|
3742
2681
|
"Starting sandbox",
|
|
3743
|
-
() =>
|
|
2682
|
+
() => startIsolatedSandbox({
|
|
3744
2683
|
provider: resolvedSandbox,
|
|
3745
2684
|
hostRepoDir: worktreeInfo.path,
|
|
3746
2685
|
env: effectiveEnv,
|
|
@@ -3748,14 +2687,12 @@ var createWorktree = async (options) => {
|
|
|
3748
2687
|
copySourceDir: hostRepoDir
|
|
3749
2688
|
})
|
|
3750
2689
|
);
|
|
3751
|
-
handle = startResult
|
|
2690
|
+
({ handle } = startResult);
|
|
2691
|
+
applyToHost = () => syncOut(worktreeInfo.path, startResult.handle);
|
|
3752
2692
|
} else {
|
|
3753
|
-
const
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
rawGitMounts,
|
|
3757
|
-
worktreeInfo.path,
|
|
3758
|
-
SANDBOX_REPO_DIR
|
|
2693
|
+
const gitMounts = yield* resolveWorktreeGitMounts(
|
|
2694
|
+
hostRepoDir,
|
|
2695
|
+
worktreeInfo.path
|
|
3759
2696
|
);
|
|
3760
2697
|
mountsToClean.push(...gitMounts);
|
|
3761
2698
|
const startResult = yield* d.taskLog(
|
|
@@ -3769,7 +2706,7 @@ var createWorktree = async (options) => {
|
|
|
3769
2706
|
repoDir: SANDBOX_REPO_DIR
|
|
3770
2707
|
})
|
|
3771
2708
|
);
|
|
3772
|
-
handle = startResult
|
|
2709
|
+
({ handle } = startResult);
|
|
3773
2710
|
}
|
|
3774
2711
|
return yield* Effect_exports.gen(function* () {
|
|
3775
2712
|
if (!handle.interactiveExec) {
|
|
@@ -3780,7 +2717,6 @@ var createWorktree = async (options) => {
|
|
|
3780
2717
|
const interactiveExecFn = handle.interactiveExec.bind(handle);
|
|
3781
2718
|
const sandbox = makeSandboxFromHandle(handle);
|
|
3782
2719
|
const { worktreePath } = handle;
|
|
3783
|
-
const applyToHost = resolvedSandbox.tag === "isolated" ? () => syncOut(worktreeInfo.path, handle) : () => Effect_exports.void;
|
|
3784
2720
|
const lifecycleEffect = withSandboxLifecycle(
|
|
3785
2721
|
{
|
|
3786
2722
|
hostRepoDir,
|
|
@@ -3797,11 +2733,11 @@ var createWorktree = async (options) => {
|
|
|
3797
2733
|
},
|
|
3798
2734
|
sandbox,
|
|
3799
2735
|
(ctx) => Effect_exports.gen(function* () {
|
|
3800
|
-
const fullPrompt =
|
|
2736
|
+
const fullPrompt = resolved?.source === "template" ? yield* preprocessPrompt(
|
|
3801
2737
|
substitutedPrompt,
|
|
3802
2738
|
ctx.sandbox,
|
|
3803
2739
|
ctx.sandboxRepoDir
|
|
3804
|
-
);
|
|
2740
|
+
) : substitutedPrompt;
|
|
3805
2741
|
const interactiveArgs = buildInteractiveArgs({
|
|
3806
2742
|
prompt: fullPrompt,
|
|
3807
2743
|
dangerouslySkipPermissions: resolvedSandbox.tag !== "none"
|
|
@@ -3836,10 +2772,9 @@ var createWorktree = async (options) => {
|
|
|
3836
2772
|
}).pipe(
|
|
3837
2773
|
// Always close sandbox handle
|
|
3838
2774
|
Effect_exports.ensuring(
|
|
3839
|
-
Effect_exports.promise(
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
)
|
|
2775
|
+
Effect_exports.promise(
|
|
2776
|
+
async () => handle.close().catch(() => void 0)
|
|
2777
|
+
).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)))
|
|
3843
2778
|
)
|
|
3844
2779
|
);
|
|
3845
2780
|
});
|
|
@@ -3884,13 +2819,11 @@ var createWorktree = async (options) => {
|
|
|
3884
2819
|
const resolved = yield* resolvePrompt({ prompt, promptFile });
|
|
3885
2820
|
const rawPrompt = resolved.text;
|
|
3886
2821
|
const isInlinePrompt = resolved.source === "inline";
|
|
3887
|
-
const
|
|
3888
|
-
const env = mergeProviderEnv({
|
|
3889
|
-
resolvedEnv,
|
|
2822
|
+
const effectiveEnv = yield* resolveWorktreeEnv(hostRepoDir, {
|
|
3890
2823
|
agentProviderEnv: provider.env,
|
|
3891
|
-
sandboxProviderEnv: sandboxProvider.env
|
|
2824
|
+
sandboxProviderEnv: sandboxProvider.env,
|
|
2825
|
+
overrides: opts.env
|
|
3892
2826
|
});
|
|
3893
|
-
const effectiveEnv = { ...env, ...opts.env };
|
|
3894
2827
|
const userArgs = opts.promptArgs ?? {};
|
|
3895
2828
|
let resolvedPrompt;
|
|
3896
2829
|
if (isInlinePrompt) {
|
|
@@ -3911,87 +2844,29 @@ var createWorktree = async (options) => {
|
|
|
3911
2844
|
builtInArgKeysSet
|
|
3912
2845
|
);
|
|
3913
2846
|
}
|
|
3914
|
-
const
|
|
3915
|
-
|
|
3916
|
-
|
|
3917
|
-
|
|
3918
|
-
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
3925
|
-
|
|
3926
|
-
|
|
3927
|
-
|
|
3928
|
-
|
|
3929
|
-
provider: sandboxProvider,
|
|
3930
|
-
hostRepoDir,
|
|
3931
|
-
env: effectiveEnv,
|
|
3932
|
-
worktreeOrRepoPath: worktreeInfo.path
|
|
3933
|
-
});
|
|
3934
|
-
handle = startResult.handle;
|
|
3935
|
-
sandboxRepoDir = startResult.worktreePath;
|
|
3936
|
-
} else {
|
|
3937
|
-
const gitPath = join(hostRepoDir, ".git");
|
|
3938
|
-
const rawGitMounts = yield* resolveGitMounts(gitPath);
|
|
3939
|
-
const gitMounts = yield* patchGitMountsForWindows(
|
|
3940
|
-
rawGitMounts,
|
|
3941
|
-
worktreeInfo.path,
|
|
3942
|
-
SANDBOX_REPO_DIR
|
|
3943
|
-
);
|
|
3944
|
-
mountsToClean.push(...gitMounts);
|
|
3945
|
-
const startResult = yield* startSandbox({
|
|
3946
|
-
provider: sandboxProvider,
|
|
3947
|
-
hostRepoDir,
|
|
3948
|
-
env: effectiveEnv,
|
|
3949
|
-
worktreeOrRepoPath: worktreeInfo.path,
|
|
3950
|
-
gitMounts,
|
|
3951
|
-
repoDir: SANDBOX_REPO_DIR
|
|
3952
|
-
});
|
|
3953
|
-
handle = startResult.handle;
|
|
3954
|
-
sandboxRepoDir = startResult.worktreePath;
|
|
3955
|
-
}
|
|
3956
|
-
const sandbox = makeSandboxFromHandle(handle);
|
|
3957
|
-
const applyToHost = sandboxProvider.tag === "isolated" ? () => syncOut(worktreeInfo.path, handle) : () => Effect_exports.void;
|
|
3958
|
-
const resolvedLogging = opts.logging ?? {
|
|
3959
|
-
type: "file",
|
|
3960
|
-
path: join(
|
|
3961
|
-
hostRepoDir,
|
|
3962
|
-
".sandcastle",
|
|
3963
|
-
"logs",
|
|
3964
|
-
buildLogFilename(worktreeInfo.branch, void 0, opts.name)
|
|
3965
|
-
)
|
|
3966
|
-
};
|
|
3967
|
-
const runDisplayLayer = resolvedLogging.type === "file" ? (() => {
|
|
3968
|
-
printFileDisplayStartup({
|
|
3969
|
-
logPath: resolvedLogging.path,
|
|
3970
|
-
agentName: opts.name,
|
|
3971
|
-
branch: worktreeInfo.branch
|
|
3972
|
-
});
|
|
3973
|
-
return Layer_exports.provide(
|
|
3974
|
-
FileDisplay.layer(resolvedLogging.path),
|
|
3975
|
-
NodeFileSystem_exports.layer
|
|
3976
|
-
);
|
|
3977
|
-
})() : ClackDisplay.layer;
|
|
3978
|
-
const bindMountHandle = sandboxProvider.tag === "bind-mount" ? handle : void 0;
|
|
3979
|
-
const reuseFactoryLayer = reuseSandboxFactoryLayer(
|
|
3980
|
-
{
|
|
3981
|
-
hostWorktreePath: worktreeInfo.path,
|
|
3982
|
-
sandboxRepoPath: sandboxRepoDir,
|
|
3983
|
-
applyToHost,
|
|
3984
|
-
bindMountHandle
|
|
3985
|
-
},
|
|
3986
|
-
sandbox
|
|
3987
|
-
);
|
|
3988
|
-
const streamEmitterLayer = agentStreamEmitterLayer(
|
|
3989
|
-
buildAgentStreamHandler(resolvedLogging)
|
|
2847
|
+
const {
|
|
2848
|
+
handle,
|
|
2849
|
+
sandboxRepoDir,
|
|
2850
|
+
gitMounts: mountsToClean,
|
|
2851
|
+
hostLink
|
|
2852
|
+
} = yield* startWorktreeRunSandbox(sandboxProvider, {
|
|
2853
|
+
hostRepoDir,
|
|
2854
|
+
worktreePath: worktreeInfo.path,
|
|
2855
|
+
env: effectiveEnv,
|
|
2856
|
+
copyPaths: options.copyToWorktree
|
|
2857
|
+
});
|
|
2858
|
+
const { resolvedLogging, runDisplayLayer } = resolveWorktreeRunDisplay(
|
|
2859
|
+
opts,
|
|
2860
|
+
hostRepoDir,
|
|
2861
|
+
worktreeInfo.branch
|
|
3990
2862
|
);
|
|
3991
2863
|
const runLayer = Layer_exports.mergeAll(
|
|
3992
|
-
|
|
2864
|
+
reuseStartedSandboxLayer(handle, hostLink, {
|
|
2865
|
+
hostWorktreePath: worktreeInfo.path,
|
|
2866
|
+
sandboxRepoPath: sandboxRepoDir
|
|
2867
|
+
}),
|
|
3993
2868
|
runDisplayLayer,
|
|
3994
|
-
|
|
2869
|
+
agentStreamEmitterLayer(buildAgentStreamHandler(resolvedLogging))
|
|
3995
2870
|
);
|
|
3996
2871
|
const result = yield* Effect_exports.gen(function* () {
|
|
3997
2872
|
const display = yield* Display;
|
|
@@ -4031,10 +2906,9 @@ var createWorktree = async (options) => {
|
|
|
4031
2906
|
Effect_exports.provide(runLayer),
|
|
4032
2907
|
// Always close sandbox handle
|
|
4033
2908
|
Effect_exports.ensuring(
|
|
4034
|
-
Effect_exports.promise(
|
|
4035
|
-
|
|
4036
|
-
|
|
4037
|
-
)
|
|
2909
|
+
Effect_exports.promise(
|
|
2910
|
+
async () => handle.close().catch(() => void 0)
|
|
2911
|
+
).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)))
|
|
4038
2912
|
)
|
|
4039
2913
|
);
|
|
4040
2914
|
return {
|
|
@@ -4095,6 +2969,6 @@ var CwdError2 = CwdError;
|
|
|
4095
2969
|
// src/SyncOutPathError.ts
|
|
4096
2970
|
var SyncOutPathError2 = SyncOutPathError;
|
|
4097
2971
|
|
|
4098
|
-
export { CwdError2 as CwdError, Output, StructuredOutputError, SyncOutPathError2 as SyncOutPathError,
|
|
2972
|
+
export { CwdError2 as CwdError, Output, StructuredOutputError, SyncOutPathError2 as SyncOutPathError, createSandbox, createWorktree, interactive, run };
|
|
4099
2973
|
//# sourceMappingURL=index.js.map
|
|
4100
2974
|
//# sourceMappingURL=index.js.map
|