@ai-hero/sandcastle 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{SandboxProvider-YCL97qco.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +3 -2
- package/dist/{chunk-767EAJVT.js → chunk-ATA2V2TC.js} +3 -3
- package/dist/{chunk-767EAJVT.js.map → chunk-ATA2V2TC.js.map} +1 -1
- package/dist/{chunk-4EIVTSOZ.js → chunk-BIF2X6QB.js} +4 -3
- package/dist/chunk-BIF2X6QB.js.map +1 -0
- package/dist/{chunk-XCYK7I45.js → chunk-BVZWLFFT.js} +2 -2
- package/dist/chunk-BVZWLFFT.js.map +1 -0
- package/dist/chunk-EXYXBRCX.js +60 -0
- package/dist/chunk-EXYXBRCX.js.map +1 -0
- package/dist/chunk-G2R53CVZ.js +3172 -0
- package/dist/chunk-G2R53CVZ.js.map +1 -0
- package/dist/{chunk-U42XXICG.js → chunk-GCLEXPXG.js} +7 -4
- package/dist/chunk-GCLEXPXG.js.map +1 -0
- package/dist/chunk-H2PEFS4W.js +1244 -0
- package/dist/chunk-H2PEFS4W.js.map +1 -0
- package/dist/{chunk-NMQ5Z6YG.js → chunk-HSXPRZKG.js} +5 -3
- package/dist/chunk-HSXPRZKG.js.map +1 -0
- package/dist/{chunk-J5J5YJ5S.js → chunk-IBK2XNSS.js} +3 -3
- package/dist/{chunk-J5J5YJ5S.js.map → chunk-IBK2XNSS.js.map} +1 -1
- package/dist/chunk-RDW7FNN6.js +792 -0
- package/dist/chunk-RDW7FNN6.js.map +1 -0
- package/dist/{chunk-A4C2FG74.js → chunk-S6UHPTRG.js} +43 -42
- package/dist/chunk-S6UHPTRG.js.map +1 -0
- package/dist/{chunk-LWNC4UTZ.js → chunk-STB2U7BB.js} +5414 -9389
- package/dist/chunk-STB2U7BB.js.map +1 -0
- package/dist/{chunk-XCWKLDH4.js → chunk-VRXR2T3S.js} +3 -3
- package/dist/{chunk-XCWKLDH4.js.map → chunk-VRXR2T3S.js.map} +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +458 -1675
- package/dist/index.js.map +1 -1
- package/dist/main.js +262 -247
- package/dist/main.js.map +1 -1
- package/dist/sandboxes/bwrap.d.ts +1 -1
- package/dist/sandboxes/bwrap.js +9 -6
- package/dist/sandboxes/bwrap.js.map +1 -1
- package/dist/sandboxes/daytona.d.ts +1 -1
- package/dist/sandboxes/daytona.js +179 -135
- package/dist/sandboxes/daytona.js.map +1 -1
- package/dist/sandboxes/docker.d.ts +1 -1
- package/dist/sandboxes/docker.js +6 -3
- package/dist/sandboxes/e2b.d.ts +41 -0
- package/dist/sandboxes/e2b.js +202 -0
- package/dist/sandboxes/e2b.js.map +1 -0
- package/dist/sandboxes/modal.d.ts +78 -0
- package/dist/sandboxes/modal.js +171 -0
- package/dist/sandboxes/modal.js.map +1 -0
- package/dist/sandboxes/no-sandbox.d.ts +1 -1
- package/dist/sandboxes/podman.d.ts +1 -1
- package/dist/sandboxes/podman.js +6 -3
- package/dist/sandboxes/podman.js.map +1 -1
- package/dist/sandboxes/seatbelt.d.ts +1 -1
- package/dist/sandboxes/seatbelt.js +9 -6
- package/dist/sandboxes/seatbelt.js.map +1 -1
- package/dist/sandboxes/sprites.d.ts +54 -0
- package/dist/sandboxes/sprites.js +198 -0
- package/dist/sandboxes/sprites.js.map +1 -0
- package/dist/sandboxes/vercel.d.ts +1 -1
- package/dist/sandboxes/vercel.js +1 -1
- package/package.json +30 -2
- package/dist/chunk-4EIVTSOZ.js.map +0 -1
- package/dist/chunk-A4C2FG74.js.map +0 -1
- package/dist/chunk-LWNC4UTZ.js.map +0 -1
- package/dist/chunk-NMQ5Z6YG.js.map +0 -1
- package/dist/chunk-U42XXICG.js.map +0 -1
- package/dist/chunk-XCYK7I45.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
|
-
import { formatErrorMessage } from './chunk-4EIVTSOZ.js';
|
|
3
2
|
import { noSandbox } from './chunk-7N7AMUYA.js';
|
|
4
|
-
import { assertInteractiveSupported } from './chunk-
|
|
5
|
-
export { NativeInteractiveNotSupportedError } from './chunk-
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
import { assertInteractiveSupported } from './chunk-VRXR2T3S.js';
|
|
4
|
+
export { NativeInteractiveNotSupportedError } from './chunk-VRXR2T3S.js';
|
|
5
|
+
import { formatErrorMessage } from './chunk-BIF2X6QB.js';
|
|
6
|
+
import { NodeContext_exports, NodeFileSystem_exports } from './chunk-S6UHPTRG.js';
|
|
7
|
+
export { NativeSandboxUnavailableError } from './chunk-S6UHPTRG.js';
|
|
8
|
+
import { Display, getCurrentBranch, generateTempBranchName, pruneStale, create, copyToWorktree, runHostHooks, startSandbox, resolveGitMounts, patchGitMountsForWindows, SANDBOX_REPO_DIR, remove, removeMountTempDirs, makeSandboxFromHandle, syncOut, withSandboxLifecycle, hasUncommittedChanges, ClackDisplay, deleteTempBranchIfUnused, FileDisplay, reuseSandboxFactoryLayer, SandboxFactory, WorktreeDockerSandboxFactory, SandboxConfig, SilentDisplay } from './chunk-G2R53CVZ.js';
|
|
9
|
+
import { registerShutdown } from './chunk-EXYXBRCX.js';
|
|
10
|
+
import { shellEscape } from './chunk-H2PEFS4W.js';
|
|
11
|
+
export { claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, opencode, pi, transferClaudeSession, transferCodexSession } from './chunk-H2PEFS4W.js';
|
|
12
|
+
import { CwdError, SyncOutPathError, resolveCwd, PromptError, FileSystem_exports, SessionCaptureError, ForkNotSupportedError, PromptExpansionTimeoutError, AgentError, AgentIdleTimeoutError } from './chunk-RDW7FNN6.js';
|
|
13
|
+
import { Context_exports, Effect_exports, Layer_exports, Deferred_exports, Runtime_exports, Clock_exports, Duration_exports, Option_exports, Ref_exports, Fiber_exports } from './chunk-STB2U7BB.js';
|
|
14
|
+
export { createBindMountSandboxProvider, createIsolatedSandboxProvider } from './chunk-BVZWLFFT.js';
|
|
10
15
|
import './chunk-6NQPCXSG.js';
|
|
11
16
|
import { mkdirSync, appendFileSync, openSync, fstatSync, readSync, closeSync } from 'fs';
|
|
12
|
-
import path, { join
|
|
17
|
+
import path, { join } from 'path';
|
|
13
18
|
import { styleText, inspect } 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
|
|
|
@@ -1228,83 +1230,92 @@ var followUpRun = (options, result, kind) => async (followUpPrompt, followUpOpti
|
|
|
1228
1230
|
...kind === "fork" ? { forkSession: true } : {}
|
|
1229
1231
|
});
|
|
1230
1232
|
};
|
|
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;
|
|
1233
|
+
var resolveRunHostRepoDir = async (options, isResuming) => {
|
|
1247
1234
|
const hostRepoDir = await Effect_exports.runPromise(
|
|
1248
1235
|
resolveCwd(options.cwd).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1249
1236
|
);
|
|
1250
1237
|
if (isResuming && options.resumeSession !== void 0) {
|
|
1251
1238
|
await assertResumeSessionExists({
|
|
1252
|
-
provider,
|
|
1239
|
+
provider: options.agent,
|
|
1253
1240
|
sandboxTag: options.sandbox.tag,
|
|
1254
1241
|
hostRepoDir,
|
|
1255
1242
|
resumeSession: options.resumeSession
|
|
1256
1243
|
});
|
|
1257
1244
|
}
|
|
1245
|
+
return hostRepoDir;
|
|
1246
|
+
};
|
|
1247
|
+
var resolveBranchStrategy = (options) => options.branchStrategy ?? (options.sandbox.tag === "isolated" ? { type: "merge-to-head" } : { type: "head" });
|
|
1248
|
+
var resolveRunPrompt = async (options) => {
|
|
1258
1249
|
const resolved = await Effect_exports.runPromise(
|
|
1259
|
-
resolvePrompt({
|
|
1260
|
-
|
|
1261
|
-
|
|
1250
|
+
resolvePrompt({
|
|
1251
|
+
prompt: options.prompt,
|
|
1252
|
+
promptFile: options.promptFile
|
|
1253
|
+
}).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1262
1254
|
);
|
|
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
|
-
}
|
|
1255
|
+
if (options.output && !resolved.text.includes(`<${options.output.tag}>`)) {
|
|
1256
|
+
throw new Error(
|
|
1257
|
+
`output tag <${options.output.tag}> not found in the resolved prompt. The caller must instruct the agent to emit the configured tag.`
|
|
1258
|
+
);
|
|
1272
1259
|
}
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
sandboxProviderEnv: options.sandbox.env
|
|
1281
|
-
});
|
|
1260
|
+
return {
|
|
1261
|
+
rawPrompt: resolved.text,
|
|
1262
|
+
isInlinePrompt: resolved.source === "inline"
|
|
1263
|
+
};
|
|
1264
|
+
};
|
|
1265
|
+
var resolveRunBranches = async (options, branchStrategy, hostRepoDir) => {
|
|
1266
|
+
const branch = branchStrategy.type === "branch" ? branchStrategy.branch : void 0;
|
|
1282
1267
|
const currentHostBranch = await Effect_exports.runPromise(
|
|
1283
1268
|
getCurrentBranch(hostRepoDir)
|
|
1284
1269
|
);
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
)
|
|
1270
|
+
return {
|
|
1271
|
+
currentHostBranch,
|
|
1272
|
+
// When in merge-to-head mode, generate a temporary branch name.
|
|
1273
|
+
// In head mode, use the host's current branch directly (no worktree).
|
|
1274
|
+
resolvedBranch: branchStrategy.type === "head" ? currentHostBranch : branch ?? generateTempBranchName(options.name),
|
|
1275
|
+
// When using a temp branch, prefix the log filename with the target branch
|
|
1276
|
+
// (the host's current branch) so developers can tell which branch was targeted.
|
|
1277
|
+
targetBranch: branchStrategy.type === "merge-to-head" ? currentHostBranch : void 0,
|
|
1278
|
+
// In head mode, pass the host branch so SandboxLifecycle skips the merge step.
|
|
1279
|
+
// In merge-to-head mode, branch is undefined (triggers merge). In branch mode, it's the explicit branch.
|
|
1280
|
+
orchestrateBranch: branchStrategy.type === "head" ? currentHostBranch : branch
|
|
1295
1281
|
};
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1282
|
+
};
|
|
1283
|
+
var resolveRunEnv = async (options, hostRepoDir) => mergeProviderEnv({
|
|
1284
|
+
resolvedEnv: await Effect_exports.runPromise(
|
|
1285
|
+
resolveEnv(hostRepoDir).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
1286
|
+
),
|
|
1287
|
+
agentProviderEnv: options.agent.env,
|
|
1288
|
+
sandboxProviderEnv: options.sandbox.env
|
|
1289
|
+
});
|
|
1290
|
+
var resolveRunLogging = (options, hostRepoDir, { resolvedBranch, targetBranch }) => options.logging ?? {
|
|
1291
|
+
type: "file",
|
|
1292
|
+
path: join(
|
|
1293
|
+
hostRepoDir,
|
|
1294
|
+
".sandcastle",
|
|
1295
|
+
"logs",
|
|
1296
|
+
buildLogFilename(resolvedBranch, targetBranch, options.name)
|
|
1297
|
+
)
|
|
1298
|
+
};
|
|
1299
|
+
var buildDisplayLayer = ({
|
|
1300
|
+
options,
|
|
1301
|
+
hostRepoDir,
|
|
1302
|
+
branches,
|
|
1303
|
+
logging
|
|
1304
|
+
}) => {
|
|
1305
|
+
if (logging.type !== "file") {
|
|
1306
|
+
return ClackDisplay.layer;
|
|
1307
|
+
}
|
|
1308
|
+
printFileDisplayStartup({
|
|
1309
|
+
logPath: logging.path,
|
|
1310
|
+
agentName: options.name,
|
|
1311
|
+
branch: branches.resolvedBranch,
|
|
1312
|
+
hostRepoDir
|
|
1313
|
+
});
|
|
1314
|
+
return Layer_exports.provide(FileDisplay.layer(logging.path), NodeFileSystem_exports.layer);
|
|
1315
|
+
};
|
|
1316
|
+
var buildRunLayer = (setup) => {
|
|
1317
|
+
const { options, hostRepoDir, branchStrategy, branches, env } = setup;
|
|
1318
|
+
const displayLayer = buildDisplayLayer(setup);
|
|
1308
1319
|
const factoryLayer = Layer_exports.provide(
|
|
1309
1320
|
WorktreeDockerSandboxFactory.layer,
|
|
1310
1321
|
Layer_exports.mergeAll(
|
|
@@ -1315,10 +1326,10 @@ async function run(options) {
|
|
|
1315
1326
|
name: options.name,
|
|
1316
1327
|
// Create the worktree on the temp branch already shown to the user,
|
|
1317
1328
|
// rather than letting WorktreeManager generate a second name.
|
|
1318
|
-
tempBranch:
|
|
1329
|
+
tempBranch: branchStrategy.type === "merge-to-head" ? branches.resolvedBranch : void 0,
|
|
1319
1330
|
sandboxProvider: options.sandbox,
|
|
1320
1331
|
branchStrategy,
|
|
1321
|
-
hooks,
|
|
1332
|
+
hooks: options.hooks,
|
|
1322
1333
|
signal: options.signal,
|
|
1323
1334
|
timeouts: options.timeouts
|
|
1324
1335
|
}),
|
|
@@ -1326,54 +1337,60 @@ async function run(options) {
|
|
|
1326
1337
|
displayLayer
|
|
1327
1338
|
)
|
|
1328
1339
|
);
|
|
1329
|
-
|
|
1330
|
-
buildAgentStreamHandler(resolvedLogging)
|
|
1331
|
-
);
|
|
1332
|
-
const runLayer = Layer_exports.mergeAll(
|
|
1340
|
+
return Layer_exports.mergeAll(
|
|
1333
1341
|
factoryLayer,
|
|
1334
1342
|
displayLayer,
|
|
1335
|
-
|
|
1343
|
+
agentStreamEmitterLayer(buildAgentStreamHandler(setup.logging))
|
|
1336
1344
|
);
|
|
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
|
-
|
|
1345
|
+
};
|
|
1346
|
+
var runIterations = ({
|
|
1347
|
+
options,
|
|
1348
|
+
hostRepoDir,
|
|
1349
|
+
maxIterations,
|
|
1350
|
+
branches,
|
|
1351
|
+
rawPrompt,
|
|
1352
|
+
isInlinePrompt
|
|
1353
|
+
}) => Effect_exports.gen(function* () {
|
|
1354
|
+
const d = yield* Display;
|
|
1355
|
+
yield* d.intro(options.name ?? "sandcastle");
|
|
1356
|
+
const rows = buildRunSummaryRows({
|
|
1357
|
+
name: options.name,
|
|
1358
|
+
agentName: options.agent.name,
|
|
1359
|
+
sandboxName: options.sandbox.name,
|
|
1360
|
+
maxIterations,
|
|
1361
|
+
branch: branches.resolvedBranch
|
|
1362
|
+
});
|
|
1363
|
+
yield* d.summary("Sandcastle Run", rows);
|
|
1364
|
+
const resolvedPrompt = yield* buildAgentPrompt({
|
|
1365
|
+
rawPrompt,
|
|
1366
|
+
isInlinePrompt,
|
|
1367
|
+
userArgs: options.promptArgs ?? {},
|
|
1368
|
+
sourceBranch: branches.resolvedBranch,
|
|
1369
|
+
targetBranch: branches.currentHostBranch
|
|
1370
|
+
});
|
|
1371
|
+
const orchestrateResult = yield* orchestrate({
|
|
1372
|
+
hostRepoDir,
|
|
1373
|
+
iterations: maxIterations,
|
|
1374
|
+
hooks: options.hooks,
|
|
1375
|
+
prompt: resolvedPrompt,
|
|
1376
|
+
branch: branches.orchestrateBranch,
|
|
1377
|
+
provider: options.agent,
|
|
1378
|
+
completionSignal: options.completionSignal,
|
|
1379
|
+
idleTimeoutSeconds: options.idleTimeoutSeconds,
|
|
1380
|
+
completionTimeoutSeconds: options.completionTimeoutSeconds,
|
|
1381
|
+
name: options.name,
|
|
1382
|
+
resumeSession: options.resumeSession,
|
|
1383
|
+
forkSession: options.forkSession,
|
|
1384
|
+
signal: options.signal,
|
|
1385
|
+
skipPromptExpansion: isInlinePrompt,
|
|
1386
|
+
timeouts: options.timeouts
|
|
1375
1387
|
});
|
|
1376
|
-
|
|
1388
|
+
yield* reportRunEnd(orchestrateResult);
|
|
1389
|
+
return orchestrateResult;
|
|
1390
|
+
});
|
|
1391
|
+
var executeRun = async (setup) => {
|
|
1392
|
+
const baseEffect = runIterations(setup);
|
|
1393
|
+
const withErrorLog = setup.logging.type === "file" ? baseEffect.pipe(
|
|
1377
1394
|
Effect_exports.tapError(
|
|
1378
1395
|
(error) => Effect_exports.gen(function* () {
|
|
1379
1396
|
const d = yield* Display;
|
|
@@ -1381,60 +1398,103 @@ async function run(options) {
|
|
|
1381
1398
|
})
|
|
1382
1399
|
)
|
|
1383
1400
|
) : baseEffect;
|
|
1384
|
-
|
|
1401
|
+
const runLayer = buildRunLayer(setup);
|
|
1385
1402
|
try {
|
|
1386
|
-
|
|
1387
|
-
|
|
1403
|
+
return await Effect_exports.runPromise(withErrorLog.pipe(Effect_exports.provide(runLayer)));
|
|
1404
|
+
} catch (error) {
|
|
1405
|
+
setup.options.signal?.throwIfAborted();
|
|
1406
|
+
throw error;
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
var withStructuredOutput = async (options, baseResult, outputMaxRetries) => {
|
|
1410
|
+
const lastIteration = baseResult.iterations.at(-1);
|
|
1411
|
+
try {
|
|
1412
|
+
const output = await extractStructuredOutput(
|
|
1413
|
+
baseResult.stdout,
|
|
1414
|
+
options.output,
|
|
1415
|
+
{
|
|
1416
|
+
commits: baseResult.commits,
|
|
1417
|
+
branch: baseResult.branch,
|
|
1418
|
+
preservedWorktreePath: baseResult.preservedWorktreePath,
|
|
1419
|
+
sessionId: lastIteration?.sessionId,
|
|
1420
|
+
sessionFilePath: lastIteration?.sessionFilePath
|
|
1421
|
+
}
|
|
1388
1422
|
);
|
|
1423
|
+
return { ...baseResult, output };
|
|
1389
1424
|
} catch (error) {
|
|
1390
|
-
|
|
1425
|
+
if (error instanceof StructuredOutputError && outputMaxRetries > 0 && error.sessionId !== void 0) {
|
|
1426
|
+
const retriesRemainingAfter = outputMaxRetries - 1;
|
|
1427
|
+
const retryOutput = {
|
|
1428
|
+
...options.output,
|
|
1429
|
+
maxRetries: retriesRemainingAfter
|
|
1430
|
+
};
|
|
1431
|
+
return run({
|
|
1432
|
+
...options,
|
|
1433
|
+
prompt: buildStructuredOutputRetryFeedback(
|
|
1434
|
+
error,
|
|
1435
|
+
retriesRemainingAfter
|
|
1436
|
+
),
|
|
1437
|
+
promptFile: void 0,
|
|
1438
|
+
promptArgs: void 0,
|
|
1439
|
+
resumeSession: error.sessionId,
|
|
1440
|
+
forkSession: false,
|
|
1441
|
+
output: retryOutput
|
|
1442
|
+
});
|
|
1443
|
+
}
|
|
1391
1444
|
throw error;
|
|
1392
1445
|
}
|
|
1446
|
+
};
|
|
1447
|
+
var finishRun = async ({
|
|
1448
|
+
options,
|
|
1449
|
+
result,
|
|
1450
|
+
logging,
|
|
1451
|
+
outputMaxRetries
|
|
1452
|
+
}) => {
|
|
1393
1453
|
const baseResult = {
|
|
1394
1454
|
...result,
|
|
1395
|
-
logFilePath:
|
|
1455
|
+
logFilePath: logging.type === "file" ? logging.path : void 0,
|
|
1396
1456
|
resume: followUpRun(options, result, "resume"),
|
|
1397
1457
|
fork: followUpRun(options, result, "fork")
|
|
1398
1458
|
};
|
|
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
|
|
1459
|
+
const { output } = options;
|
|
1460
|
+
if (!output) {
|
|
1461
|
+
return baseResult;
|
|
1462
|
+
}
|
|
1463
|
+
return withStructuredOutput(
|
|
1464
|
+
{ ...options, output },
|
|
1465
|
+
baseResult,
|
|
1466
|
+
outputMaxRetries
|
|
1467
|
+
);
|
|
1468
|
+
};
|
|
1469
|
+
async function run(options) {
|
|
1470
|
+
options.signal?.throwIfAborted();
|
|
1471
|
+
const { maxIterations = DEFAULT_MAX_ITERATIONS } = options;
|
|
1472
|
+
const branchStrategy = resolveBranchStrategy(options);
|
|
1473
|
+
validateTimeoutOptions(options);
|
|
1474
|
+
validateBranchOptions(options, branchStrategy.type);
|
|
1475
|
+
const isResuming = validateSessionOptions(options, maxIterations);
|
|
1476
|
+
const outputMaxRetries = validateOutputOptions(options, maxIterations);
|
|
1477
|
+
const hostRepoDir = await resolveRunHostRepoDir(options, isResuming);
|
|
1478
|
+
const { rawPrompt, isInlinePrompt } = await resolveRunPrompt(options);
|
|
1479
|
+
const env = await resolveRunEnv(options, hostRepoDir);
|
|
1480
|
+
const branches = await resolveRunBranches(
|
|
1481
|
+
options,
|
|
1482
|
+
branchStrategy,
|
|
1483
|
+
hostRepoDir
|
|
1484
|
+
);
|
|
1485
|
+
const logging = resolveRunLogging(options, hostRepoDir, branches);
|
|
1486
|
+
const result = await executeRun({
|
|
1487
|
+
options,
|
|
1488
|
+
branchStrategy,
|
|
1489
|
+
hostRepoDir,
|
|
1490
|
+
maxIterations,
|
|
1491
|
+
branches,
|
|
1492
|
+
logging,
|
|
1493
|
+
env,
|
|
1494
|
+
rawPrompt,
|
|
1495
|
+
isInlinePrompt
|
|
1496
|
+
});
|
|
1497
|
+
return finishRun({ options, result, logging, outputMaxRetries });
|
|
1438
1498
|
}
|
|
1439
1499
|
|
|
1440
1500
|
// src/raceAbortSignal.ts
|
|
@@ -1747,1303 +1807,67 @@ var interactive = async (options) => {
|
|
|
1747
1807
|
}
|
|
1748
1808
|
return result;
|
|
1749
1809
|
};
|
|
1750
|
-
var
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
return void 0;
|
|
1755
|
-
}
|
|
1756
|
-
return await pathExists(head) ? head : firstExistingPath(rest);
|
|
1757
|
-
};
|
|
1758
|
-
var pathExists = async (path2) => {
|
|
1759
|
-
try {
|
|
1760
|
-
await access(path2);
|
|
1761
|
-
return true;
|
|
1762
|
-
} catch {
|
|
1763
|
-
return false;
|
|
1764
|
-
}
|
|
1765
|
-
};
|
|
1766
|
-
var MAX_PROJECT_DIR_LENGTH = 200;
|
|
1767
|
-
var claudePathHash = (value) => {
|
|
1768
|
-
const hash = value.split("").reduce((acc, unit) => Math.imul(31, acc) + (unit.codePointAt(0) ?? 0), 0);
|
|
1769
|
-
return Math.abs(Math.imul(hash, 1)).toString(36);
|
|
1770
|
-
};
|
|
1771
|
-
var encodeProjectPath = (cwd) => {
|
|
1772
|
-
const isRoot = cwd === "/" || /^[A-Za-z]:[\\/]?$/u.test(cwd);
|
|
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`
|
|
1799
|
-
);
|
|
1800
|
-
if (result.exitCode !== 0) {
|
|
1801
|
-
return [];
|
|
1802
|
-
}
|
|
1803
|
-
const stdout = result.stdout.trim();
|
|
1804
|
-
if (stdout === "") {
|
|
1805
|
-
return [];
|
|
1806
|
-
}
|
|
1807
|
-
return stdout.split("\n").filter((line) => line !== "");
|
|
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;
|
|
1810
|
+
var withAgentEnv = (agent, sandboxProviderEnv) => {
|
|
1811
|
+
const entries = Object.entries(agent.env);
|
|
1812
|
+
if (entries.length === 0) {
|
|
1813
|
+
return agent;
|
|
1826
1814
|
}
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1815
|
+
mergeProviderEnv({
|
|
1816
|
+
resolvedEnv: {},
|
|
1817
|
+
agentProviderEnv: agent.env,
|
|
1818
|
+
sandboxProviderEnv
|
|
1819
|
+
});
|
|
1820
|
+
const invalid = entries.map(([key]) => key).filter((key) => !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key));
|
|
1821
|
+
if (invalid.length > 0) {
|
|
1822
|
+
throw new Error(
|
|
1823
|
+
`Invalid agent provider env key(s): ${invalid.join(", ")}. Keys must match [A-Za-z_][A-Za-z0-9_]*.`
|
|
1824
|
+
);
|
|
1831
1825
|
}
|
|
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;
|
|
1826
|
+
const exports$1 = entries.map(([key, value]) => `export ${key}=${shellEscape(value)}; `).join("");
|
|
1827
|
+
return {
|
|
1828
|
+
...agent,
|
|
1829
|
+
buildPrintCommand: (options) => {
|
|
1830
|
+
const printCommand = agent.buildPrintCommand(options);
|
|
1831
|
+
return { ...printCommand, command: exports$1 + printCommand.command };
|
|
1845
1832
|
}
|
|
1846
|
-
}
|
|
1833
|
+
};
|
|
1847
1834
|
};
|
|
1848
|
-
var
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1835
|
+
var buildSandboxHandle = (ctx, close) => {
|
|
1836
|
+
const {
|
|
1837
|
+
branch,
|
|
1838
|
+
worktreePath,
|
|
1839
|
+
hostRepoDir,
|
|
1840
|
+
sandboxRepoDir,
|
|
1841
|
+
sandbox,
|
|
1842
|
+
providerHandle,
|
|
1843
|
+
bindMountHandle,
|
|
1844
|
+
applyToHost,
|
|
1845
|
+
timeouts,
|
|
1846
|
+
branchStrategy
|
|
1847
|
+
} = ctx;
|
|
1848
|
+
const mergeToHead = branchStrategy?.type === "merge-to-head";
|
|
1849
|
+
const sandboxHandle = {
|
|
1850
|
+
branch,
|
|
1851
|
+
worktreePath,
|
|
1852
|
+
sandboxId: providerHandle !== void 0 && "sandboxId" in providerHandle ? providerHandle.sandboxId : void 0,
|
|
1853
|
+
run: async (runOptions) => {
|
|
1854
|
+
runOptions.signal?.throwIfAborted();
|
|
1855
|
+
const { prompt, promptFile, maxIterations = 1 } = runOptions;
|
|
1856
|
+
const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);
|
|
1857
|
+
validateTimeoutOptions(runOptions);
|
|
1858
|
+
const isResuming = runOptions.resumeSession !== void 0 && runOptions.resumeSession !== "";
|
|
1859
|
+
if (isResuming && maxIterations > 1) {
|
|
1860
|
+
throw new Error(
|
|
1861
|
+
"resumeSession cannot be combined with maxIterations > 1. Resume applies to iteration 1 only; multi-iteration resume semantics are not supported."
|
|
1862
|
+
);
|
|
1867
1863
|
}
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
var requireHostSessionPath = (found, id) => {
|
|
1873
|
-
if (found.path === void 0) {
|
|
1874
|
-
throw new Error(`session ${id} not found in ${found.searchedRoot}`);
|
|
1875
|
-
}
|
|
1876
|
-
return found.path;
|
|
1877
|
-
};
|
|
1878
|
-
var locateSandboxSessionFile = async (handle, sessionsDir, nameGlob) => {
|
|
1879
|
-
const result = await handle.exec(
|
|
1880
|
-
`find ${JSON.stringify(sessionsDir)} -type f -name ${JSON.stringify(nameGlob)} -print -quit`
|
|
1881
|
-
);
|
|
1882
|
-
const [path2 = ""] = result.stdout.trim().split("\n");
|
|
1883
|
-
if (result.exitCode !== 0 || path2 === "") {
|
|
1884
|
-
throw new Error(`session ${nameGlob} not found in ${sessionsDir}`);
|
|
1885
|
-
}
|
|
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
|
-
};
|
|
1894
|
-
var piSessionDirPath = (cwd, sessionsDir) => {
|
|
1895
|
-
const base = sessionsDir ?? join(homeDir(), ".pi", "agent", "sessions");
|
|
1896
|
-
return join(base, encodePiSessionDir(cwd));
|
|
1897
|
-
};
|
|
1898
|
-
var isPiSessionFilename = (filename, id) => filename.endsWith(`_${id}.jsonl`);
|
|
1899
|
-
var findPiSessionOnHost = async (id, sessionsDir) => {
|
|
1900
|
-
const root = sessionsDir ?? join(homeDir(), ".pi", "agent", "sessions");
|
|
1901
|
-
let entries;
|
|
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 };
|
|
1924
|
-
};
|
|
1925
|
-
var transferPiSession = (jsonl, fromCwd, toCwd) => {
|
|
1926
|
-
if (jsonl === "") {
|
|
1927
|
-
return "";
|
|
1928
|
-
}
|
|
1929
|
-
return jsonl.split("\n").map((line) => {
|
|
1930
|
-
if (line === "") {
|
|
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);
|
|
1864
|
+
if (runOptions.forkSession === true && !isResuming) {
|
|
1865
|
+
throw new Error(
|
|
1866
|
+
"forkSession requires resumeSession. Use sandboxRunResult.fork(prompt) to fork the most recent captured session."
|
|
1867
|
+
);
|
|
1938
1868
|
}
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
return line;
|
|
1942
|
-
}
|
|
1943
|
-
}).join("\n");
|
|
1944
|
-
};
|
|
1945
|
-
var isRecord = (value) => typeof value === "object" && value !== null;
|
|
1946
|
-
var copilotSessionPath = (sessionsDir, id) => posix.join(sessionsDir, id, "events.jsonl");
|
|
1947
|
-
var copilotHostSessionsDir = () => join(homeDir(), ".copilot", "session-state");
|
|
1948
|
-
var rewriteCopilotEvent = (line, fromCwd, toCwd) => {
|
|
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;
|
|
1963
|
-
}
|
|
1964
|
-
return keys.length > 0 ? JSON.stringify(entry) : line;
|
|
1965
|
-
};
|
|
1966
|
-
var transferCopilotSession = (jsonl, fromCwd, toCwd) => jsonl.split("\n").map(
|
|
1967
|
-
(line) => line === "" ? line : rewriteCopilotEvent(line, fromCwd, toCwd)
|
|
1968
|
-
).join("\n");
|
|
1969
|
-
var cursorChatDirName = (cwd) => createHash("md5").update(cwd).digest("hex");
|
|
1970
|
-
var cursorHostChatsDir = () => join(homeDir(), ".cursor", "chats");
|
|
1971
|
-
var opencodeHostSessionsDir = () => join(homeDir(), ".local", "share", "opencode", "sandcastle-sessions");
|
|
1972
|
-
var opencodeHostDatabase = () => join(homeDir(), ".local", "share", "opencode", "opencode.db");
|
|
1973
|
-
var sandboxCommandError = (command, result) => new Error(
|
|
1974
|
-
`\`${command}\` exited with code ${result.exitCode}: ${result.stderr.trim()}`
|
|
1975
|
-
);
|
|
1976
|
-
var captureSessionFile = (layout) => async (transfer) => {
|
|
1977
|
-
const { hostCwd, sandboxCwd, sessionId, handle } = transfer;
|
|
1978
|
-
const source = layout.sandboxPath(
|
|
1979
|
-
sandboxCwd,
|
|
1980
|
-
sessionId,
|
|
1981
|
-
sandboxDirsOf(handle)
|
|
1982
|
-
);
|
|
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
|
-
};
|
|
1998
|
-
var resumeSessionFile = (layout) => async (transfer) => {
|
|
1999
|
-
const { hostCwd, sandboxCwd, sessionId, handle } = transfer;
|
|
2000
|
-
const source = layout.hostPath(hostCwd, sessionId);
|
|
2001
|
-
const target = layout.sandboxPath(
|
|
2002
|
-
sandboxCwd,
|
|
2003
|
-
sessionId,
|
|
2004
|
-
sandboxDirsOf(handle)
|
|
2005
|
-
);
|
|
2006
|
-
const dir = JSON.stringify(posix.dirname(target));
|
|
2007
|
-
if (layout.rewrite === void 0) {
|
|
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) }
|
|
2023
|
-
);
|
|
2024
|
-
if (result.exitCode !== 0) {
|
|
2025
|
-
throw new Error(`writing ${target} failed: ${result.stderr}`);
|
|
2026
|
-
}
|
|
2027
|
-
};
|
|
2028
|
-
var makeSessionFileStorage = (layout) => ({
|
|
2029
|
-
hostSessionFilePath: (cwd, id) => layout.hostPath(cwd, id),
|
|
2030
|
-
existsOnHost: async (cwd, id) => pathExists(layout.hostPath(cwd, id)),
|
|
2031
|
-
readHostSession: async (cwd, id) => {
|
|
2032
|
-
const path2 = layout.hostPath(cwd, id);
|
|
2033
|
-
return await pathExists(path2) ? readFile(path2, "utf8") : void 0;
|
|
2034
|
-
},
|
|
2035
|
-
findByIdOnHost: async (id) => {
|
|
2036
|
-
let subdirs = [];
|
|
2037
|
-
try {
|
|
2038
|
-
subdirs = await readdir(layout.hostRoot);
|
|
2039
|
-
} catch {
|
|
2040
|
-
}
|
|
2041
|
-
return {
|
|
2042
|
-
path: await firstExistingPath(layout.hostPathsById(id, subdirs)),
|
|
2043
|
-
searchedRoot: layout.hostRoot
|
|
2044
|
-
};
|
|
2045
|
-
},
|
|
2046
|
-
captureToHost: captureSessionFile(layout),
|
|
2047
|
-
resumeIntoSandbox: resumeSessionFile(layout)
|
|
2048
|
-
});
|
|
2049
|
-
|
|
2050
|
-
// src/AgentProvider.ts
|
|
2051
|
-
var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
|
|
2052
|
-
var contextWindowEvent = (input, ...cacheBuckets) => {
|
|
2053
|
-
if (typeof input !== "number") return [];
|
|
2054
|
-
let tokens = input;
|
|
2055
|
-
for (const n of cacheBuckets) if (typeof n === "number") tokens += n;
|
|
2056
|
-
return tokens > 0 ? [{ type: "context_window", contextWindow: { tokens } }] : [];
|
|
2057
|
-
};
|
|
2058
|
-
var parseClaudeContextWindow = (line) => {
|
|
2059
|
-
if (!line.startsWith("{")) return [];
|
|
2060
|
-
try {
|
|
2061
|
-
const obj = JSON.parse(line);
|
|
2062
|
-
if (obj.type !== "assistant" || obj.parent_tool_use_id) return [];
|
|
2063
|
-
const u = obj.message?.usage;
|
|
2064
|
-
return contextWindowEvent(
|
|
2065
|
-
u?.input_tokens,
|
|
2066
|
-
u?.cache_creation_input_tokens,
|
|
2067
|
-
u?.cache_read_input_tokens
|
|
2068
|
-
);
|
|
2069
|
-
} catch {
|
|
2070
|
-
return [];
|
|
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
|
-
}
|
|
2093
|
-
}
|
|
2094
|
-
return messageField(obj);
|
|
2095
|
-
};
|
|
2096
|
-
var toolCallFromClaudeBlock = (block) => {
|
|
2097
|
-
if (block.type !== "tool_use" || typeof block.name !== "string" || block.input === void 0) {
|
|
2098
|
-
return void 0;
|
|
2099
|
-
}
|
|
2100
|
-
const argField = TOOL_ARG_FIELDS[block.name];
|
|
2101
|
-
if (argField === void 0) {
|
|
2102
|
-
return void 0;
|
|
2103
|
-
}
|
|
2104
|
-
const argValue = block.input[argField];
|
|
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
|
-
};
|
|
3010
|
-
};
|
|
3011
|
-
var buildSandboxHandle = (ctx, close) => {
|
|
3012
|
-
const {
|
|
3013
|
-
branch,
|
|
3014
|
-
worktreePath,
|
|
3015
|
-
hostRepoDir,
|
|
3016
|
-
sandboxRepoDir,
|
|
3017
|
-
sandbox,
|
|
3018
|
-
providerHandle,
|
|
3019
|
-
bindMountHandle,
|
|
3020
|
-
applyToHost,
|
|
3021
|
-
timeouts,
|
|
3022
|
-
branchStrategy
|
|
3023
|
-
} = ctx;
|
|
3024
|
-
const mergeToHead = branchStrategy?.type === "merge-to-head";
|
|
3025
|
-
const sandboxHandle = {
|
|
3026
|
-
branch,
|
|
3027
|
-
worktreePath,
|
|
3028
|
-
sandboxId: providerHandle !== void 0 && "sandboxId" in providerHandle ? providerHandle.sandboxId : void 0,
|
|
3029
|
-
run: async (runOptions) => {
|
|
3030
|
-
runOptions.signal?.throwIfAborted();
|
|
3031
|
-
const { prompt, promptFile, maxIterations = 1 } = runOptions;
|
|
3032
|
-
const provider = withAgentEnv(runOptions.agent, ctx.sandboxProviderEnv);
|
|
3033
|
-
validateTimeoutOptions(runOptions);
|
|
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);
|
|
1869
|
+
if (runOptions.forkSession === true) {
|
|
1870
|
+
assertForkSupported(provider);
|
|
3047
1871
|
}
|
|
3048
1872
|
if (isResuming) {
|
|
3049
1873
|
await assertResumeSessionExists({
|
|
@@ -3308,111 +2132,171 @@ var buildSandboxHandle = (ctx, close) => {
|
|
|
3308
2132
|
};
|
|
3309
2133
|
return sandboxHandle;
|
|
3310
2134
|
};
|
|
3311
|
-
var
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
2135
|
+
var startBindMountWithGitMounts = (provider, {
|
|
2136
|
+
hostRepoDir,
|
|
2137
|
+
worktreePath,
|
|
2138
|
+
env,
|
|
2139
|
+
mountsToClean
|
|
2140
|
+
}) => resolveGitMounts(join(hostRepoDir, ".git")).pipe(
|
|
2141
|
+
Effect_exports.provide(NodeFileSystem_exports.layer),
|
|
2142
|
+
Effect_exports.catchAll(() => Effect_exports.succeed([])),
|
|
2143
|
+
// Patch git mounts for Windows worktree compatibility (ADR-0006)
|
|
2144
|
+
Effect_exports.flatMap(
|
|
2145
|
+
(gitMounts) => patchGitMountsForWindows(gitMounts, worktreePath, SANDBOX_REPO_DIR)
|
|
2146
|
+
),
|
|
2147
|
+
Effect_exports.tap((gitMounts) => {
|
|
2148
|
+
mountsToClean.push(...gitMounts);
|
|
2149
|
+
}),
|
|
2150
|
+
Effect_exports.flatMap(
|
|
2151
|
+
(gitMounts) => startSandbox({
|
|
2152
|
+
provider,
|
|
2153
|
+
hostRepoDir,
|
|
2154
|
+
env,
|
|
2155
|
+
worktreeOrRepoPath: worktreePath,
|
|
2156
|
+
gitMounts,
|
|
2157
|
+
repoDir: SANDBOX_REPO_DIR
|
|
2158
|
+
})
|
|
2159
|
+
)
|
|
2160
|
+
);
|
|
2161
|
+
var startProviderSandbox = (options) => {
|
|
2162
|
+
const { provider, hostRepoDir, worktreePath, env } = options;
|
|
2163
|
+
if (provider.tag === "isolated") {
|
|
2164
|
+
return startSandbox({
|
|
2165
|
+
provider,
|
|
2166
|
+
hostRepoDir: worktreePath,
|
|
2167
|
+
env,
|
|
2168
|
+
copyPaths: options.copyToWorktree,
|
|
2169
|
+
copySourceDir: hostRepoDir
|
|
2170
|
+
});
|
|
3324
2171
|
}
|
|
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
|
|
2172
|
+
if (provider.tag === "none") {
|
|
2173
|
+
return startSandbox({
|
|
2174
|
+
provider,
|
|
2175
|
+
hostRepoDir,
|
|
2176
|
+
env,
|
|
2177
|
+
worktreeOrRepoPath: worktreePath
|
|
3342
2178
|
});
|
|
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
2179
|
}
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
|
|
3403
|
-
|
|
3404
|
-
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
2180
|
+
return startBindMountWithGitMounts(provider, options);
|
|
2181
|
+
};
|
|
2182
|
+
var copyIntoWorktree = (options, hostRepoDir, worktreePath) => options.copyToWorktree && options.copyToWorktree.length > 0 && options.sandbox.tag !== "isolated" ? copyToWorktree(
|
|
2183
|
+
options.copyToWorktree,
|
|
2184
|
+
hostRepoDir,
|
|
2185
|
+
worktreePath,
|
|
2186
|
+
options.timeouts?.copyToWorktreeMs
|
|
2187
|
+
) : Effect_exports.void;
|
|
2188
|
+
var providerHandleFields = (provider, providerHandle, worktreePath) => ({
|
|
2189
|
+
providerHandle,
|
|
2190
|
+
// Pre-narrow the bind-mount handle for the orchestrator's session-capture
|
|
2191
|
+
// path. Gating on the provider tag avoids handing a NoSandbox/Isolated
|
|
2192
|
+
// handle (which lack copyFileIn/copyFileOut) to AgentSessionStorage and
|
|
2193
|
+
// turning a missing-feature into a runtime SessionCaptureError.
|
|
2194
|
+
bindMountHandle: provider.tag === "bind-mount" ? providerHandle : void 0,
|
|
2195
|
+
providerTag: provider.tag,
|
|
2196
|
+
sandboxProvider: provider,
|
|
2197
|
+
sandboxProviderEnv: provider.env,
|
|
2198
|
+
// Syncs an isolated sandbox's changes back to the host worktree.
|
|
2199
|
+
applyToHost: provider.tag === "isolated" && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void
|
|
2200
|
+
});
|
|
2201
|
+
var startSandboxOnWorktree = ({
|
|
2202
|
+
options,
|
|
2203
|
+
hostRepoDir,
|
|
2204
|
+
worktreePath,
|
|
2205
|
+
mountsToClean
|
|
2206
|
+
}) => Effect_exports.gen(function* () {
|
|
2207
|
+
if (options._test?.buildSandbox) {
|
|
2208
|
+
return {
|
|
2209
|
+
sandbox: options._test.buildSandbox(worktreePath),
|
|
2210
|
+
sandboxRepoDir: worktreePath,
|
|
2211
|
+
providerHandle: options._test.bindMountHandle
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
const resolvedEnv = yield* resolveEnv(hostRepoDir);
|
|
2215
|
+
const env = mergeProviderEnv({
|
|
2216
|
+
resolvedEnv,
|
|
2217
|
+
agentProviderEnv: {},
|
|
2218
|
+
sandboxProviderEnv: options.sandbox.env
|
|
2219
|
+
});
|
|
2220
|
+
const startResult = yield* startProviderSandbox({
|
|
2221
|
+
provider: options.sandbox,
|
|
2222
|
+
hostRepoDir,
|
|
2223
|
+
worktreePath,
|
|
2224
|
+
env,
|
|
2225
|
+
copyToWorktree: options.copyToWorktree,
|
|
2226
|
+
mountsToClean
|
|
2227
|
+
});
|
|
2228
|
+
return {
|
|
2229
|
+
providerHandle: startResult.handle,
|
|
2230
|
+
sandbox: startResult.sandbox,
|
|
2231
|
+
sandboxRepoDir: startResult.worktreePath
|
|
2232
|
+
};
|
|
2233
|
+
});
|
|
2234
|
+
var runOnSandboxReadyHooks = ({
|
|
2235
|
+
sandbox,
|
|
2236
|
+
sandboxRepoDir,
|
|
2237
|
+
worktreePath,
|
|
2238
|
+
hooks
|
|
2239
|
+
}) => {
|
|
2240
|
+
const sandboxOnReady = hooks?.sandbox?.onSandboxReady ?? [];
|
|
2241
|
+
const hostOnReady = hooks?.host?.onSandboxReady ?? [];
|
|
2242
|
+
if (sandboxOnReady.length === 0 && hostOnReady.length === 0) {
|
|
2243
|
+
return Effect_exports.void;
|
|
2244
|
+
}
|
|
2245
|
+
return Effect_exports.gen(function* () {
|
|
2246
|
+
yield* sandbox.exec(
|
|
2247
|
+
`git config --global --add safe.directory "${sandboxRepoDir}"`
|
|
2248
|
+
);
|
|
2249
|
+
const sandboxEffects = sandboxOnReady.map(
|
|
2250
|
+
(hook) => sandbox.exec(hook.command, {
|
|
2251
|
+
cwd: sandboxRepoDir,
|
|
2252
|
+
sudo: hook.sudo
|
|
3410
2253
|
})
|
|
3411
2254
|
);
|
|
3412
|
-
|
|
3413
|
-
|
|
2255
|
+
const allEffects = [
|
|
2256
|
+
...sandboxEffects,
|
|
2257
|
+
...hostOnReady.length > 0 ? [runHostHooks(hostOnReady, worktreePath)] : []
|
|
2258
|
+
];
|
|
2259
|
+
yield* Effect_exports.all(allEffects, { concurrency: "unbounded" });
|
|
2260
|
+
});
|
|
2261
|
+
};
|
|
2262
|
+
var closeContainerOnly = (providerHandle, mountsToClean) => {
|
|
3414
2263
|
let closed = false;
|
|
3415
|
-
|
|
2264
|
+
return async () => {
|
|
2265
|
+
if (closed) {
|
|
2266
|
+
return { preservedWorktreePath: void 0 };
|
|
2267
|
+
}
|
|
2268
|
+
closed = true;
|
|
2269
|
+
if (providerHandle) {
|
|
2270
|
+
await providerHandle.close();
|
|
2271
|
+
}
|
|
2272
|
+
await Effect_exports.runPromise(removeMountTempDirs(mountsToClean));
|
|
2273
|
+
return { preservedWorktreePath: void 0 };
|
|
2274
|
+
};
|
|
2275
|
+
};
|
|
2276
|
+
var createSandboxFromWorktree = async (options) => {
|
|
2277
|
+
const { branch, worktreePath, hostRepoDir } = options;
|
|
2278
|
+
validateTimeoutOptions(options);
|
|
2279
|
+
await Effect_exports.runPromise(copyIntoWorktree(options, hostRepoDir, worktreePath));
|
|
2280
|
+
const mountsToClean = [];
|
|
2281
|
+
const { providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
|
|
2282
|
+
startSandboxOnWorktree({
|
|
2283
|
+
options,
|
|
2284
|
+
hostRepoDir,
|
|
2285
|
+
worktreePath,
|
|
2286
|
+
mountsToClean
|
|
2287
|
+
}).pipe(
|
|
2288
|
+
Effect_exports.onError(() => removeMountTempDirs(mountsToClean)),
|
|
2289
|
+
Effect_exports.provide(NodeContext_exports.layer)
|
|
2290
|
+
)
|
|
2291
|
+
);
|
|
2292
|
+
await Effect_exports.runPromise(
|
|
2293
|
+
runOnSandboxReadyHooks({
|
|
2294
|
+
sandbox,
|
|
2295
|
+
sandboxRepoDir,
|
|
2296
|
+
worktreePath,
|
|
2297
|
+
hooks: options.hooks
|
|
2298
|
+
})
|
|
2299
|
+
);
|
|
3416
2300
|
return buildSandboxHandle(
|
|
3417
2301
|
{
|
|
3418
2302
|
branch,
|
|
@@ -3420,32 +2304,15 @@ var createSandboxFromWorktree = async (options) => {
|
|
|
3420
2304
|
hostRepoDir,
|
|
3421
2305
|
sandboxRepoDir,
|
|
3422
2306
|
sandbox,
|
|
3423
|
-
providerHandle,
|
|
3424
|
-
bindMountHandle,
|
|
3425
|
-
providerTag: options.sandbox.tag,
|
|
3426
|
-
sandboxProvider: options.sandbox,
|
|
3427
|
-
sandboxProviderEnv: options.sandbox.env,
|
|
3428
|
-
applyToHost,
|
|
2307
|
+
...providerHandleFields(options.sandbox, providerHandle, worktreePath),
|
|
3429
2308
|
timeouts: options.timeouts,
|
|
3430
2309
|
branchStrategy: options.branchStrategy
|
|
3431
2310
|
},
|
|
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
|
-
}
|
|
2311
|
+
closeContainerOnly(providerHandle, mountsToClean)
|
|
3443
2312
|
);
|
|
3444
2313
|
};
|
|
3445
2314
|
var createSandbox = async (options) => {
|
|
3446
2315
|
const { branch } = options;
|
|
3447
|
-
const isTestMode = !!options._test?.buildSandbox;
|
|
3448
|
-
const isIsolated = options.sandbox.tag === "isolated";
|
|
3449
2316
|
validateTimeoutOptions(options);
|
|
3450
2317
|
const mountsToClean = [];
|
|
3451
2318
|
const { hostRepoDir, worktreePath, providerHandle, sandbox, sandboxRepoDir } = await Effect_exports.runPromise(
|
|
@@ -3459,106 +2326,28 @@ var createSandbox = async (options) => {
|
|
|
3459
2326
|
{ branch, baseBranch: options.baseBranch }
|
|
3460
2327
|
);
|
|
3461
2328
|
const prepared = yield* Effect_exports.gen(function* () {
|
|
3462
|
-
|
|
3463
|
-
yield* copyToWorktree(
|
|
3464
|
-
options.copyToWorktree,
|
|
3465
|
-
hostRepoDir2,
|
|
3466
|
-
worktreePath2,
|
|
3467
|
-
options.timeouts?.copyToWorktreeMs
|
|
3468
|
-
);
|
|
3469
|
-
}
|
|
2329
|
+
yield* copyIntoWorktree(options, hostRepoDir2, worktreePath2);
|
|
3470
2330
|
const onWorktreeReady = options.hooks?.host?.onWorktreeReady;
|
|
3471
2331
|
if (onWorktreeReady !== void 0 && onWorktreeReady.length > 0) {
|
|
3472
2332
|
yield* runHostHooks(onWorktreeReady, worktreePath2);
|
|
3473
2333
|
}
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
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
|
-
}
|
|
2334
|
+
const { providerHandle: providerHandle2, sandbox: sandbox2, sandboxRepoDir: sandboxRepoDir2 } = yield* startSandboxOnWorktree({
|
|
2335
|
+
options,
|
|
2336
|
+
hostRepoDir: hostRepoDir2,
|
|
2337
|
+
worktreePath: worktreePath2,
|
|
2338
|
+
mountsToClean
|
|
2339
|
+
});
|
|
2340
|
+
yield* runOnSandboxReadyHooks({
|
|
2341
|
+
sandbox: sandbox2,
|
|
2342
|
+
sandboxRepoDir: sandboxRepoDir2,
|
|
2343
|
+
worktreePath: worktreePath2,
|
|
2344
|
+
hooks: options.hooks
|
|
2345
|
+
}).pipe(
|
|
2346
|
+
Effect_exports.onError(
|
|
2347
|
+
() => (providerHandle2 ? Effect_exports.promise(() => providerHandle2.close().catch(() => {
|
|
2348
|
+
})) : Effect_exports.void).pipe(Effect_exports.andThen(removeMountTempDirs(mountsToClean)))
|
|
2349
|
+
)
|
|
2350
|
+
);
|
|
3562
2351
|
return { providerHandle: providerHandle2, sandbox: sandbox2, sandboxRepoDir: sandboxRepoDir2 };
|
|
3563
2352
|
}).pipe(
|
|
3564
2353
|
Effect_exports.onError(
|
|
@@ -3571,7 +2360,6 @@ var createSandbox = async (options) => {
|
|
|
3571
2360
|
return { hostRepoDir: hostRepoDir2, worktreePath: worktreePath2, ...prepared };
|
|
3572
2361
|
}).pipe(Effect_exports.provide(NodeContext_exports.layer))
|
|
3573
2362
|
);
|
|
3574
|
-
const applyToHost = isIsolated && providerHandle ? () => syncOut(worktreePath, providerHandle) : () => Effect_exports.void;
|
|
3575
2363
|
let closed = false;
|
|
3576
2364
|
const forceCleanup = () => {
|
|
3577
2365
|
console.error(`
|
|
@@ -3604,7 +2392,6 @@ Worktree preserved at ${worktreePath}`);
|
|
|
3604
2392
|
})
|
|
3605
2393
|
);
|
|
3606
2394
|
};
|
|
3607
|
-
const bindMountHandle = options.sandbox.tag === "bind-mount" ? providerHandle : void 0;
|
|
3608
2395
|
return buildSandboxHandle(
|
|
3609
2396
|
{
|
|
3610
2397
|
branch,
|
|
@@ -3612,12 +2399,8 @@ Worktree preserved at ${worktreePath}`);
|
|
|
3612
2399
|
hostRepoDir,
|
|
3613
2400
|
sandboxRepoDir,
|
|
3614
2401
|
sandbox,
|
|
3615
|
-
|
|
3616
|
-
|
|
3617
|
-
providerTag: options.sandbox.tag,
|
|
3618
|
-
sandboxProvider: options.sandbox,
|
|
3619
|
-
sandboxProviderEnv: options.sandbox.env,
|
|
3620
|
-
applyToHost,
|
|
2402
|
+
// applyToHost is built once, reused across runs.
|
|
2403
|
+
...providerHandleFields(options.sandbox, providerHandle, worktreePath),
|
|
3621
2404
|
timeouts: options.timeouts
|
|
3622
2405
|
},
|
|
3623
2406
|
async () => {
|
|
@@ -4095,6 +2878,6 @@ var CwdError2 = CwdError;
|
|
|
4095
2878
|
// src/SyncOutPathError.ts
|
|
4096
2879
|
var SyncOutPathError2 = SyncOutPathError;
|
|
4097
2880
|
|
|
4098
|
-
export { CwdError2 as CwdError, Output, StructuredOutputError, SyncOutPathError2 as SyncOutPathError,
|
|
2881
|
+
export { CwdError2 as CwdError, Output, StructuredOutputError, SyncOutPathError2 as SyncOutPathError, createSandbox, createWorktree, interactive, run };
|
|
4099
2882
|
//# sourceMappingURL=index.js.map
|
|
4100
2883
|
//# sourceMappingURL=index.js.map
|