@ai-hero/sandcastle 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +15 -1368
  2. package/dist/LinuxCapability-B_PQfsY_.d.ts +32 -0
  3. package/dist/{SandboxProvider-EkSMuBp8.d.ts → SandboxProvider-Chsi-Zs6.d.ts} +31 -3
  4. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  5. package/dist/chunk-6NQPCXSG.js.map +1 -0
  6. package/dist/chunk-7N7AMUYA.js +353 -0
  7. package/dist/chunk-7N7AMUYA.js.map +1 -0
  8. package/dist/chunk-ATA2V2TC.js +112 -0
  9. package/dist/chunk-ATA2V2TC.js.map +1 -0
  10. package/dist/chunk-BIF2X6QB.js +94 -0
  11. package/dist/chunk-BIF2X6QB.js.map +1 -0
  12. package/dist/{chunk-BIWNFKGV.js → chunk-BVZWLFFT.js} +2 -2
  13. package/dist/chunk-BVZWLFFT.js.map +1 -0
  14. package/dist/chunk-EXYXBRCX.js +60 -0
  15. package/dist/chunk-EXYXBRCX.js.map +1 -0
  16. package/dist/chunk-G2R53CVZ.js +3172 -0
  17. package/dist/chunk-G2R53CVZ.js.map +1 -0
  18. package/dist/{chunk-CP3TYXZA.js → chunk-GCLEXPXG.js} +95 -85
  19. package/dist/chunk-GCLEXPXG.js.map +1 -0
  20. package/dist/chunk-H2PEFS4W.js +1244 -0
  21. package/dist/chunk-H2PEFS4W.js.map +1 -0
  22. package/dist/chunk-HSXPRZKG.js +150 -0
  23. package/dist/chunk-HSXPRZKG.js.map +1 -0
  24. package/dist/chunk-IBK2XNSS.js +50 -0
  25. package/dist/chunk-IBK2XNSS.js.map +1 -0
  26. package/dist/chunk-RDW7FNN6.js +792 -0
  27. package/dist/chunk-RDW7FNN6.js.map +1 -0
  28. package/dist/{chunk-DJRHWPEH.js → chunk-S6UHPTRG.js} +284 -352
  29. package/dist/chunk-S6UHPTRG.js.map +1 -0
  30. package/dist/{chunk-VOG34SRF.js → chunk-STB2U7BB.js} +11823 -6977
  31. package/dist/chunk-STB2U7BB.js.map +1 -0
  32. package/dist/chunk-VRXR2T3S.js +24 -0
  33. package/dist/chunk-VRXR2T3S.js.map +1 -0
  34. package/dist/index.d.ts +241 -26
  35. package/dist/index.js +1082 -1679
  36. package/dist/index.js.map +1 -1
  37. package/dist/main.js +1248 -854
  38. package/dist/main.js.map +1 -1
  39. package/dist/sandboxes/bwrap.d.ts +58 -0
  40. package/dist/sandboxes/bwrap.js +296 -0
  41. package/dist/sandboxes/bwrap.js.map +1 -0
  42. package/dist/sandboxes/daytona.d.ts +1 -1
  43. package/dist/sandboxes/daytona.js +203 -98
  44. package/dist/sandboxes/daytona.js.map +1 -1
  45. package/dist/sandboxes/docker.d.ts +18 -4
  46. package/dist/sandboxes/docker.js +7 -4
  47. package/dist/sandboxes/e2b.d.ts +41 -0
  48. package/dist/sandboxes/e2b.js +202 -0
  49. package/dist/sandboxes/e2b.js.map +1 -0
  50. package/dist/sandboxes/modal.d.ts +78 -0
  51. package/dist/sandboxes/modal.js +171 -0
  52. package/dist/sandboxes/modal.js.map +1 -0
  53. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  54. package/dist/sandboxes/no-sandbox.js +2 -2
  55. package/dist/sandboxes/podman.d.ts +18 -4
  56. package/dist/sandboxes/podman.js +72 -56
  57. package/dist/sandboxes/podman.js.map +1 -1
  58. package/dist/sandboxes/seatbelt.d.ts +65 -0
  59. package/dist/sandboxes/seatbelt.js +425 -0
  60. package/dist/sandboxes/seatbelt.js.map +1 -0
  61. package/dist/sandboxes/sprites.d.ts +54 -0
  62. package/dist/sandboxes/sprites.js +198 -0
  63. package/dist/sandboxes/sprites.js.map +1 -0
  64. package/dist/sandboxes/vercel.d.ts +12 -5
  65. package/dist/sandboxes/vercel.js +195 -126
  66. package/dist/sandboxes/vercel.js.map +1 -1
  67. package/dist/templates/parallel-planner/main.mts +13 -22
  68. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  69. package/package.json +63 -11
  70. package/dist/chunk-62WN33RK.js +0 -104
  71. package/dist/chunk-62WN33RK.js.map +0 -1
  72. package/dist/chunk-BIWNFKGV.js.map +0 -1
  73. package/dist/chunk-CP3TYXZA.js.map +0 -1
  74. package/dist/chunk-DJRHWPEH.js.map +0 -1
  75. package/dist/chunk-NGBM7T3E.js.map +0 -1
  76. package/dist/chunk-VOG34SRF.js.map +0 -1
  77. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,1244 @@
1
+ import { createRequire } from 'node:module';
2
+ import { ForkNotSupportedError } from './chunk-RDW7FNN6.js';
3
+ import { createHash } from 'crypto';
4
+ import { readdir, mkdir, writeFile, readFile, access, rm } from 'fs/promises';
5
+ import { join, posix, dirname, relative } from 'path';
6
+ import { tmpdir } from 'os';
7
+
8
+ createRequire(import.meta.url);
9
+ var homeDir = () => process.env.HOME ?? "~";
10
+ var firstExistingPath = async (paths) => {
11
+ const [head, ...rest] = paths;
12
+ if (head === void 0) {
13
+ return void 0;
14
+ }
15
+ return await pathExists(head) ? head : firstExistingPath(rest);
16
+ };
17
+ var pathExists = async (path) => {
18
+ try {
19
+ await access(path);
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
25
+ var MAX_PROJECT_DIR_LENGTH = 200;
26
+ var claudePathHash = (value) => {
27
+ const hash = value.split("").reduce((acc, unit) => Math.imul(31, acc) + (unit.codePointAt(0) ?? 0), 0);
28
+ return Math.abs(Math.imul(hash, 1)).toString(36);
29
+ };
30
+ var encodeProjectPath = (cwd) => {
31
+ const isRoot = cwd === "/" || /^[A-Za-z]:[\\/]?$/u.test(cwd);
32
+ const normalized = isRoot ? cwd : cwd.replace(/[\\/]+$/u, "");
33
+ const encoded = normalized.replaceAll(/[^A-Za-z0-9]/gu, "-");
34
+ if (encoded.length <= MAX_PROJECT_DIR_LENGTH) {
35
+ return encoded;
36
+ }
37
+ return `${encoded.slice(0, MAX_PROJECT_DIR_LENGTH)}-${claudePathHash(normalized)}`;
38
+ };
39
+ var DEFAULT_SANDBOX_DIRS = { home: "/home/agent", tmp: "/tmp" };
40
+ var sandboxDirsOf = (handle) => ({
41
+ home: handle.sandboxHomedir ?? DEFAULT_SANDBOX_DIRS.home,
42
+ tmp: handle.sandboxTmpdir ?? DEFAULT_SANDBOX_DIRS.tmp
43
+ });
44
+ var claudeHostSessionPath = (cwd, id, projectsDir) => {
45
+ const base = projectsDir ?? join(homeDir(), ".claude", "projects");
46
+ return join(base, encodeProjectPath(cwd), `${id}.jsonl`);
47
+ };
48
+ var claudeSandboxSessionPath = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), `${id}.jsonl`);
49
+ var claudeSubagentsDirInSandbox = (cwd, id, projectsDir) => posix.join(projectsDir, encodeProjectPath(cwd), id, "subagents");
50
+ var claudeSubagentsDirOnHost = (cwd, id, projectsDir) => {
51
+ const base = projectsDir ?? join(homeDir(), ".claude", "projects");
52
+ return join(base, encodeProjectPath(cwd), id, "subagents");
53
+ };
54
+ var listClaudeSubagentSessionsInSandbox = async (cwd, id, handle, sandboxProjectsDir) => {
55
+ const dir = claudeSubagentsDirInSandbox(cwd, id, sandboxProjectsDir);
56
+ const result = await handle.exec(
57
+ `find ${JSON.stringify(dir)} -type f -name ${JSON.stringify("agent-*.jsonl")} 2>/dev/null`
58
+ );
59
+ if (result.exitCode !== 0) {
60
+ return [];
61
+ }
62
+ const stdout = result.stdout.trim();
63
+ if (stdout === "") {
64
+ return [];
65
+ }
66
+ return stdout.split("\n").filter((line) => line !== "");
67
+ };
68
+ var findClaudeSessionOnHost = async (id, projectsDir) => {
69
+ const root = projectsDir ?? join(homeDir(), ".claude", "projects");
70
+ let entries;
71
+ try {
72
+ entries = await readdir(root, { withFileTypes: true });
73
+ } catch {
74
+ return { path: void 0, searchedRoot: root };
75
+ }
76
+ const candidates = entries.filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name, `${id}.jsonl`));
77
+ return { path: await firstExistingPath(candidates), searchedRoot: root };
78
+ };
79
+ var rewriteEntryCwd = (entry, fromCwd, toCwd) => {
80
+ if (typeof entry.cwd === "string" && entry.cwd === fromCwd) {
81
+ entry.cwd = toCwd;
82
+ }
83
+ if (entry.type === "session_meta" && isRecord(entry.payload) && typeof entry.payload.cwd === "string" && entry.payload.cwd === fromCwd) {
84
+ entry.payload.cwd = toCwd;
85
+ }
86
+ };
87
+ var rewriteSessionCwd = (content, fromCwd, toCwd) => {
88
+ if (content === "") {
89
+ return "";
90
+ }
91
+ return content.split("\n").map((line) => {
92
+ if (line === "") {
93
+ return line;
94
+ }
95
+ try {
96
+ const entry = JSON.parse(line);
97
+ if (!isRecord(entry)) {
98
+ return line;
99
+ }
100
+ rewriteEntryCwd(entry, fromCwd, toCwd);
101
+ return JSON.stringify(entry);
102
+ } catch {
103
+ return line;
104
+ }
105
+ }).join("\n");
106
+ };
107
+ var transferClaudeSession = (jsonl, fromCwd, toCwd) => rewriteSessionCwd(jsonl, fromCwd, toCwd);
108
+ var isCodexSessionFilename = (filename, id) => filename.startsWith("rollout-") && filename.endsWith(`-${id}.jsonl`);
109
+ var findCodexSessionOnHost = async (id, sessionsDir) => {
110
+ const root = sessionsDir ?? join(homeDir(), ".codex", "sessions");
111
+ let entries;
112
+ try {
113
+ entries = await readdir(root, { withFileTypes: true });
114
+ } catch {
115
+ return { path: void 0, searchedRoot: root };
116
+ }
117
+ for (const entry of entries) {
118
+ const child = join(root, entry.name);
119
+ if (entry.isFile() && isCodexSessionFilename(entry.name, id)) {
120
+ return { path: child, searchedRoot: root };
121
+ }
122
+ if (entry.isDirectory()) {
123
+ const { path } = await findCodexSessionOnHost(id, child);
124
+ if (path !== void 0) {
125
+ return { path, searchedRoot: root };
126
+ }
127
+ }
128
+ }
129
+ return { path: void 0, searchedRoot: root };
130
+ };
131
+ var requireHostSessionPath = (found, id) => {
132
+ if (found.path === void 0) {
133
+ throw new Error(`session ${id} not found in ${found.searchedRoot}`);
134
+ }
135
+ return found.path;
136
+ };
137
+ var locateSandboxSessionFile = async (handle, sessionsDir, nameGlob) => {
138
+ const result = await handle.exec(
139
+ `find ${JSON.stringify(sessionsDir)} -type f -name ${JSON.stringify(nameGlob)} -print -quit`
140
+ );
141
+ const [path = ""] = result.stdout.trim().split("\n");
142
+ if (result.exitCode !== 0 || path === "") {
143
+ throw new Error(`session ${nameGlob} not found in ${sessionsDir}`);
144
+ }
145
+ return { path, relativePath: posix.relative(sessionsDir, path) };
146
+ };
147
+ var transferCodexSession = (jsonl, fromCwd, toCwd) => rewriteSessionCwd(jsonl, fromCwd, toCwd);
148
+ var encodePiSessionDir = (cwd) => {
149
+ const stripped = cwd.replace(/^[/\\]/u, "");
150
+ const replaced = stripped.replaceAll(/[/\\:]/gu, "-");
151
+ return `--${replaced}--`;
152
+ };
153
+ var piSessionDirPath = (cwd, sessionsDir) => {
154
+ const base = sessionsDir ?? join(homeDir(), ".pi", "agent", "sessions");
155
+ return join(base, encodePiSessionDir(cwd));
156
+ };
157
+ var isPiSessionFilename = (filename, id) => filename.endsWith(`_${id}.jsonl`);
158
+ var findPiSessionOnHost = async (id, sessionsDir) => {
159
+ const root = sessionsDir ?? join(homeDir(), ".pi", "agent", "sessions");
160
+ let entries;
161
+ try {
162
+ entries = await readdir(root, { withFileTypes: true });
163
+ } catch {
164
+ return { path: void 0, searchedRoot: root };
165
+ }
166
+ for (const entry of entries) {
167
+ if (!entry.isDirectory()) {
168
+ continue;
169
+ }
170
+ const dirAbs = join(root, entry.name);
171
+ let files;
172
+ try {
173
+ files = await readdir(dirAbs);
174
+ } catch {
175
+ continue;
176
+ }
177
+ const match = files.find((name) => isPiSessionFilename(name, id));
178
+ if (match !== void 0) {
179
+ return { path: join(dirAbs, match), searchedRoot: root };
180
+ }
181
+ }
182
+ return { path: void 0, searchedRoot: root };
183
+ };
184
+ var transferPiSession = (jsonl, fromCwd, toCwd) => {
185
+ if (jsonl === "") {
186
+ return "";
187
+ }
188
+ return jsonl.split("\n").map((line) => {
189
+ if (line === "") {
190
+ return line;
191
+ }
192
+ try {
193
+ const entry = JSON.parse(line);
194
+ if (isRecord(entry) && entry.type === "session" && typeof entry.cwd === "string" && entry.cwd === fromCwd) {
195
+ entry.cwd = toCwd;
196
+ return JSON.stringify(entry);
197
+ }
198
+ return line;
199
+ } catch {
200
+ return line;
201
+ }
202
+ }).join("\n");
203
+ };
204
+ var isRecord = (value) => typeof value === "object" && value !== null;
205
+ var copilotSessionPath = (sessionsDir, id) => posix.join(sessionsDir, id, "events.jsonl");
206
+ var copilotHostSessionsDir = () => join(homeDir(), ".copilot", "session-state");
207
+ var rewriteCopilotEvent = (line, fromCwd, toCwd) => {
208
+ let entry;
209
+ try {
210
+ entry = JSON.parse(line);
211
+ } catch {
212
+ return line;
213
+ }
214
+ const data = isRecord(entry) ? entry["data"] : void 0;
215
+ const context = isRecord(data) ? data["context"] : void 0;
216
+ if (!isRecord(context)) {
217
+ return line;
218
+ }
219
+ const keys = ["cwd", "gitRoot"].filter((key) => context[key] === fromCwd);
220
+ for (const key of keys) {
221
+ context[key] = toCwd;
222
+ }
223
+ return keys.length > 0 ? JSON.stringify(entry) : line;
224
+ };
225
+ var transferCopilotSession = (jsonl, fromCwd, toCwd) => jsonl.split("\n").map(
226
+ (line) => line === "" ? line : rewriteCopilotEvent(line, fromCwd, toCwd)
227
+ ).join("\n");
228
+ var cursorChatDirName = (cwd) => createHash("md5").update(cwd).digest("hex");
229
+ var cursorHostChatsDir = () => join(homeDir(), ".cursor", "chats");
230
+ var opencodeHostSessionsDir = () => join(homeDir(), ".local", "share", "opencode", "sandcastle-sessions");
231
+ var opencodeHostDatabase = () => join(homeDir(), ".local", "share", "opencode", "opencode.db");
232
+ var sandboxCommandError = (command, result) => new Error(
233
+ `\`${command}\` exited with code ${result.exitCode}: ${result.stderr.trim()}`
234
+ );
235
+ var captureSessionFile = (layout) => async (transfer) => {
236
+ const { hostCwd, sandboxCwd, sessionId, handle } = transfer;
237
+ const source = layout.sandboxPath(
238
+ sandboxCwd,
239
+ sessionId,
240
+ sandboxDirsOf(handle)
241
+ );
242
+ if (layout.sandboxExport !== void 0) {
243
+ const command = layout.sandboxExport(sessionId, source);
244
+ const result = await handle.exec(command, { cwd: sandboxCwd });
245
+ if (result.exitCode !== 0) {
246
+ throw sandboxCommandError(command, result);
247
+ }
248
+ }
249
+ const target = layout.hostPath(hostCwd, sessionId);
250
+ await mkdir(dirname(target), { recursive: true });
251
+ await handle.copyFileOut(source, target);
252
+ if (layout.rewrite !== void 0) {
253
+ const content = await readFile(target, "utf8");
254
+ await writeFile(target, layout.rewrite(content, sandboxCwd, hostCwd));
255
+ }
256
+ };
257
+ var resumeSessionFile = (layout) => async (transfer) => {
258
+ const { hostCwd, sandboxCwd, sessionId, handle } = transfer;
259
+ const source = layout.hostPath(hostCwd, sessionId);
260
+ const target = layout.sandboxPath(
261
+ sandboxCwd,
262
+ sessionId,
263
+ sandboxDirsOf(handle)
264
+ );
265
+ const dir = JSON.stringify(posix.dirname(target));
266
+ if (layout.rewrite === void 0) {
267
+ await handle.exec(`mkdir -p ${dir}`);
268
+ await handle.copyFileIn(source, target);
269
+ if (layout.sandboxImport !== void 0) {
270
+ const command = layout.sandboxImport(sessionId, target);
271
+ const result2 = await handle.exec(command, { cwd: sandboxCwd });
272
+ if (result2.exitCode !== 0) {
273
+ throw sandboxCommandError(command, result2);
274
+ }
275
+ }
276
+ return;
277
+ }
278
+ const content = await readFile(source, "utf8");
279
+ const result = await handle.exec(
280
+ `mkdir -p ${dir} && cat > ${JSON.stringify(target)}`,
281
+ { stdin: layout.rewrite(content, hostCwd, sandboxCwd) }
282
+ );
283
+ if (result.exitCode !== 0) {
284
+ throw new Error(`writing ${target} failed: ${result.stderr}`);
285
+ }
286
+ };
287
+ var makeSessionFileStorage = (layout) => ({
288
+ hostSessionFilePath: (cwd, id) => layout.hostPath(cwd, id),
289
+ existsOnHost: async (cwd, id) => pathExists(layout.hostPath(cwd, id)),
290
+ readHostSession: async (cwd, id) => {
291
+ const path = layout.hostPath(cwd, id);
292
+ return await pathExists(path) ? readFile(path, "utf8") : void 0;
293
+ },
294
+ findByIdOnHost: async (id) => {
295
+ let subdirs = [];
296
+ try {
297
+ subdirs = await readdir(layout.hostRoot);
298
+ } catch {
299
+ }
300
+ return {
301
+ path: await firstExistingPath(layout.hostPathsById(id, subdirs)),
302
+ searchedRoot: layout.hostRoot
303
+ };
304
+ },
305
+ captureToHost: captureSessionFile(layout),
306
+ resumeIntoSandbox: resumeSessionFile(layout)
307
+ });
308
+ var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
309
+ var contextWindowEvent = (input, ...cacheBuckets) => {
310
+ if (typeof input !== "number") return [];
311
+ let tokens = input;
312
+ for (const n of cacheBuckets) if (typeof n === "number") tokens += n;
313
+ return tokens > 0 ? [{ type: "context_window", contextWindow: { tokens } }] : [];
314
+ };
315
+ var parseClaudeContextWindow = (line) => {
316
+ if (!line.startsWith("{")) return [];
317
+ try {
318
+ const obj = JSON.parse(line);
319
+ if (obj.type !== "assistant" || obj.parent_tool_use_id) return [];
320
+ const u = obj.message?.usage;
321
+ return contextWindowEvent(
322
+ u?.input_tokens,
323
+ u?.cache_creation_input_tokens,
324
+ u?.cache_read_input_tokens
325
+ );
326
+ } catch {
327
+ return [];
328
+ }
329
+ };
330
+ var TOOL_ARG_FIELDS = {
331
+ Bash: "command",
332
+ WebSearch: "query",
333
+ WebFetch: "url",
334
+ Agent: "description"
335
+ };
336
+ var messageField = (value) => typeof value === "object" && value !== null && "message" in value && typeof value.message === "string" ? value.message : void 0;
337
+ var extractErrorMessage = (obj) => {
338
+ if (typeof obj !== "object" || obj === null) {
339
+ return void 0;
340
+ }
341
+ const err = "error" in obj ? obj.error : void 0;
342
+ if (typeof err === "string") {
343
+ return err;
344
+ }
345
+ if (typeof err === "object" && err !== null) {
346
+ const nested = messageField(err) ?? ("data" in err ? messageField(err.data) : void 0);
347
+ if (nested !== void 0) {
348
+ return nested;
349
+ }
350
+ }
351
+ return messageField(obj);
352
+ };
353
+ var toolCallFromClaudeBlock = (block) => {
354
+ if (block.type !== "tool_use" || typeof block.name !== "string" || block.input === void 0) {
355
+ return void 0;
356
+ }
357
+ const argField = TOOL_ARG_FIELDS[block.name];
358
+ if (argField === void 0) {
359
+ return void 0;
360
+ }
361
+ const argValue = block.input[argField];
362
+ if (typeof argValue !== "string") {
363
+ return void 0;
364
+ }
365
+ return { type: "tool_call", name: block.name, args: argValue };
366
+ };
367
+ var mergeAdjacentText = (events) => {
368
+ const merged = [];
369
+ for (const event of events) {
370
+ const last = merged.at(-1);
371
+ if (event.type === "text" && last?.type === "text") {
372
+ merged[merged.length - 1] = {
373
+ type: "text",
374
+ text: last.text + event.text
375
+ };
376
+ } else {
377
+ merged.push(event);
378
+ }
379
+ }
380
+ return merged;
381
+ };
382
+ var parseClaudeAssistantContent = (content) => mergeAdjacentText(
383
+ content.flatMap((block) => {
384
+ if (block.type === "text" && typeof block.text === "string") {
385
+ return [{ type: "text", text: block.text }];
386
+ }
387
+ const toolCall = toolCallFromClaudeBlock(block);
388
+ return toolCall === void 0 ? [] : [toolCall];
389
+ })
390
+ );
391
+ var parseStreamJsonLine = (line) => {
392
+ if (!line.startsWith("{")) return [];
393
+ try {
394
+ const obj = JSON.parse(line);
395
+ if (obj.type === "assistant" && Array.isArray(obj.message?.content)) {
396
+ return parseClaudeAssistantContent(
397
+ obj.message.content
398
+ );
399
+ }
400
+ if (obj.type === "result" && typeof obj.result === "string") {
401
+ if (obj.is_error === true) {
402
+ return [{ type: "error", message: obj.result }];
403
+ }
404
+ return [{ type: "result", result: obj.result }];
405
+ }
406
+ if (obj.type === "system" && obj.subtype === "init" && typeof obj.session_id === "string") {
407
+ return [{ type: "session_id", sessionId: obj.session_id }];
408
+ }
409
+ } catch {
410
+ }
411
+ return [];
412
+ };
413
+ var CURSOR_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
414
+ var assertCursorPrintPromptFitsArgv = (prompt) => {
415
+ const n = Buffer.byteLength(prompt, "utf8");
416
+ if (n > CURSOR_PRINT_PROMPT_MAX_BYTES) {
417
+ throw new Error(
418
+ `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.`
419
+ );
420
+ }
421
+ };
422
+ var cursorToolCallArg = (toolCall, field) => {
423
+ if (typeof toolCall !== "object" || toolCall === null) {
424
+ return void 0;
425
+ }
426
+ const args = Reflect.get(toolCall, "args");
427
+ if (typeof args !== "object" || args === null) {
428
+ return void 0;
429
+ }
430
+ const value = Reflect.get(args, field);
431
+ return typeof value === "string" ? value : void 0;
432
+ };
433
+ var CURSOR_TYPED_TOOL_CALLS = [
434
+ { kind: "readToolCall", name: "Read", field: "path" },
435
+ { kind: "writeToolCall", name: "Write", field: "path" },
436
+ { kind: "editToolCall", name: "Edit", field: "path" },
437
+ { kind: "shellToolCall", name: "Bash", field: "command" }
438
+ ];
439
+ var parseCursorFunctionToolCall = (fn) => {
440
+ if (typeof fn !== "object" || fn === null) {
441
+ return [];
442
+ }
443
+ const name = Reflect.get(fn, "name");
444
+ if (typeof name !== "string") {
445
+ return [];
446
+ }
447
+ const rawArguments = Reflect.get(fn, "arguments");
448
+ const rawArgs = typeof rawArguments === "string" ? rawArguments : "";
449
+ if (rawArgs === "") {
450
+ return [{ type: "tool_call", name, args: "" }];
451
+ }
452
+ try {
453
+ const parsedArgs = JSON.parse(rawArgs);
454
+ const command = typeof parsedArgs === "object" && parsedArgs !== null ? Reflect.get(parsedArgs, "command") : void 0;
455
+ if (typeof command === "string") {
456
+ return [{ type: "tool_call", name: "Bash", args: command }];
457
+ }
458
+ } catch {
459
+ }
460
+ return [{ type: "tool_call", name, args: rawArgs }];
461
+ };
462
+ var parseCursorToolCallStarted = (obj) => {
463
+ if (obj.type !== "tool_call" || obj.subtype !== "started") {
464
+ return [];
465
+ }
466
+ const toolCall = obj.tool_call;
467
+ if (typeof toolCall !== "object" || toolCall === null) {
468
+ return [];
469
+ }
470
+ for (const { kind, name, field } of CURSOR_TYPED_TOOL_CALLS) {
471
+ const args = cursorToolCallArg(Reflect.get(toolCall, kind), field);
472
+ if (args !== void 0) {
473
+ return [{ type: "tool_call", name, args }];
474
+ }
475
+ }
476
+ return parseCursorFunctionToolCall(Reflect.get(toolCall, "function"));
477
+ };
478
+ var parseCursorStreamLine = (line) => {
479
+ if (!line.startsWith("{")) return [];
480
+ let obj;
481
+ try {
482
+ obj = JSON.parse(line);
483
+ } catch {
484
+ return [];
485
+ }
486
+ if (obj.type === "tool_call") {
487
+ return parseCursorToolCallStarted(obj);
488
+ }
489
+ return parseStreamJsonLine(line);
490
+ };
491
+ var readSandboxFile = async (handle, sandboxPath, tag) => {
492
+ const tmpPath = join(
493
+ tmpdir(),
494
+ `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
495
+ );
496
+ await handle.copyFileOut(sandboxPath, tmpPath);
497
+ try {
498
+ return await readFile(tmpPath, "utf8");
499
+ } finally {
500
+ await rm(tmpPath, { force: true }).catch(() => {
501
+ });
502
+ }
503
+ };
504
+ var writeSandboxFile = async (handle, { sandboxPath, content, tag }) => {
505
+ const tmpPath = join(
506
+ tmpdir(),
507
+ `sandcastle-${tag}-${Date.now()}-${Math.random().toString(36).slice(2)}.jsonl`
508
+ );
509
+ await writeFile(tmpPath, content);
510
+ try {
511
+ await handle.exec(`mkdir -p ${JSON.stringify(posix.dirname(sandboxPath))}`);
512
+ await handle.copyFileIn(tmpPath, sandboxPath);
513
+ } finally {
514
+ await rm(tmpPath, { force: true }).catch(() => {
515
+ });
516
+ }
517
+ };
518
+ var copyClaudeSessionFile = async ({
519
+ handle,
520
+ sourcePath,
521
+ fromCwd,
522
+ toCwd,
523
+ destPath,
524
+ tag
525
+ }) => {
526
+ const jsonl = await readSandboxFile(handle, sourcePath, tag);
527
+ const rewritten = transferClaudeSession(jsonl, fromCwd, toCwd);
528
+ await mkdir(dirname(destPath), { recursive: true });
529
+ await writeFile(destPath, rewritten);
530
+ };
531
+ var captureClaudeSubagents = async ({
532
+ handle,
533
+ hostCwd,
534
+ sandboxCwd,
535
+ sessionId,
536
+ sandboxProjectsDir,
537
+ hostProjectsDir
538
+ }) => {
539
+ const subagentSandboxPaths = await listClaudeSubagentSessionsInSandbox(
540
+ sandboxCwd,
541
+ sessionId,
542
+ handle,
543
+ sandboxProjectsDir
544
+ );
545
+ const hostSubagentsDir = claudeSubagentsDirOnHost(
546
+ hostCwd,
547
+ sessionId,
548
+ hostProjectsDir
549
+ );
550
+ for (const sandboxSubagentPath of subagentSandboxPaths) {
551
+ try {
552
+ await copyClaudeSessionFile({
553
+ handle,
554
+ sourcePath: sandboxSubagentPath,
555
+ fromCwd: sandboxCwd,
556
+ toCwd: hostCwd,
557
+ destPath: join(hostSubagentsDir, posix.basename(sandboxSubagentPath)),
558
+ tag: "claude-sub"
559
+ });
560
+ } catch (error) {
561
+ console.error(
562
+ `sandcastle: failed to capture Claude subagent transcript ${sandboxSubagentPath}: ${error instanceof Error ? error.message : String(error)}`
563
+ );
564
+ }
565
+ }
566
+ };
567
+ var resumeClaudeIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
568
+ const hostPath = claudeHostSessionPath(
569
+ hostCwd,
570
+ sessionId,
571
+ dirs.hostProjectsDir
572
+ );
573
+ const jsonl = await readFile(hostPath, "utf8");
574
+ await writeSandboxFile(handle, {
575
+ sandboxPath: claudeSandboxSessionPath(
576
+ sandboxCwd,
577
+ sessionId,
578
+ dirs.sandboxProjectsDir
579
+ ),
580
+ content: transferClaudeSession(jsonl, hostCwd, sandboxCwd),
581
+ tag: "claude-res"
582
+ });
583
+ };
584
+ var captureClaudeSession = (capture) => (
585
+ // Main session: failure is fatal — the user expects their session.
586
+ copyClaudeSessionFile({
587
+ handle: capture.handle,
588
+ sourcePath: claudeSandboxSessionPath(
589
+ capture.sandboxCwd,
590
+ capture.sessionId,
591
+ capture.sandboxProjectsDir
592
+ ),
593
+ fromCwd: capture.sandboxCwd,
594
+ toCwd: capture.hostCwd,
595
+ destPath: claudeHostSessionPath(
596
+ capture.hostCwd,
597
+ capture.sessionId,
598
+ capture.hostProjectsDir
599
+ ),
600
+ tag: "claude-cap"
601
+ }).then(() => captureClaudeSubagents(capture))
602
+ );
603
+ var makeClaudeSessionStorage = (options) => {
604
+ const hostProjectsDir = options?.sessionStorage?.hostProjectsDir;
605
+ const sandboxProjectsDirOf = (handle) => options?.sessionStorage?.sandboxProjectsDir ?? posix.join(sandboxDirsOf(handle).home, ".claude", "projects");
606
+ return {
607
+ hostSessionFilePath: (cwd, id) => claudeHostSessionPath(cwd, id, hostProjectsDir),
608
+ existsOnHost: (cwd, id) => pathExists(claudeHostSessionPath(cwd, id, hostProjectsDir)),
609
+ readHostSession: async (cwd, id) => {
610
+ const path = claudeHostSessionPath(cwd, id, hostProjectsDir);
611
+ if (!await pathExists(path)) return void 0;
612
+ return readFile(path, "utf8");
613
+ },
614
+ captureToHost: ({ hostCwd, sandboxCwd, sessionId, handle }) => captureClaudeSession({
615
+ handle,
616
+ hostCwd,
617
+ sandboxCwd,
618
+ sessionId,
619
+ sandboxProjectsDir: sandboxProjectsDirOf(handle),
620
+ hostProjectsDir
621
+ }),
622
+ resumeIntoSandbox: (transfer) => resumeClaudeIntoSandbox(transfer, {
623
+ hostProjectsDir,
624
+ sandboxProjectsDir: sandboxProjectsDirOf(transfer.handle)
625
+ }),
626
+ findByIdOnHost: (id) => findClaudeSessionOnHost(id, hostProjectsDir)
627
+ };
628
+ };
629
+ var resumeCodexIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
630
+ const found = await findCodexSessionOnHost(sessionId, dirs.hostSessionsDir);
631
+ const path = requireHostSessionPath(found, sessionId);
632
+ const jsonl = await readFile(path, "utf8");
633
+ await writeSandboxFile(handle, {
634
+ sandboxPath: posix.join(
635
+ dirs.sandboxSessionsDir,
636
+ ...relative(found.searchedRoot, path).split(/[\\/]/u)
637
+ ),
638
+ content: transferCodexSession(jsonl, hostCwd, sandboxCwd),
639
+ tag: "codex-res"
640
+ });
641
+ };
642
+ var makeCodexSessionStorage = (options) => {
643
+ const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
644
+ const sandboxSessionsDirOf = (handle) => options?.sessionStorage?.sandboxSessionsDir ?? posix.join(sandboxDirsOf(handle).home, ".codex", "sessions");
645
+ const capturedPaths = /* @__PURE__ */ new Map();
646
+ return {
647
+ hostSessionFilePath: (_cwd, id) => capturedPaths.get(id),
648
+ existsOnHost: async (_cwd, id) => {
649
+ const found = await findCodexSessionOnHost(id, hostSessionsDir);
650
+ return found.path !== void 0;
651
+ },
652
+ readHostSession: async (_cwd, id) => {
653
+ const found = await findCodexSessionOnHost(id, hostSessionsDir);
654
+ if (!found.path) return void 0;
655
+ return readFile(found.path, "utf8");
656
+ },
657
+ captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
658
+ const located = await locateSandboxSessionFile(
659
+ handle,
660
+ sandboxSessionsDirOf(handle),
661
+ `rollout-*-${sessionId}.jsonl`
662
+ );
663
+ const jsonl = await readSandboxFile(handle, located.path, "codex-cap");
664
+ const rewritten = transferCodexSession(jsonl, sandboxCwd, hostCwd);
665
+ const root = hostSessionsDir ?? join(homeDir(), ".codex", "sessions");
666
+ const target = join(root, located.relativePath);
667
+ await mkdir(dirname(target), { recursive: true });
668
+ await writeFile(target, rewritten);
669
+ capturedPaths.set(sessionId, target);
670
+ },
671
+ resumeIntoSandbox: (transfer) => resumeCodexIntoSandbox(transfer, {
672
+ hostSessionsDir,
673
+ sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle)
674
+ }),
675
+ findByIdOnHost: (id) => findCodexSessionOnHost(id, hostSessionsDir)
676
+ };
677
+ };
678
+ var piHostCaptureTarget = (hostCwd, sandboxPath, hostSessionsDir) => join(piSessionDirPath(hostCwd, hostSessionsDir), posix.basename(sandboxPath));
679
+ var resumePiIntoSandbox = async ({ hostCwd, sandboxCwd, sessionId, handle }, dirs) => {
680
+ const found = await findPiSessionOnHost(sessionId, dirs.hostSessionsDir);
681
+ const path = requireHostSessionPath(found, sessionId);
682
+ const jsonl = await readFile(path, "utf8");
683
+ const filename = posix.basename(path.replaceAll("\\", "/"));
684
+ await writeSandboxFile(handle, {
685
+ sandboxPath: posix.join(
686
+ dirs.sandboxSessionsDir,
687
+ encodePiSessionDir(sandboxCwd),
688
+ filename
689
+ ),
690
+ content: transferPiSession(jsonl, hostCwd, sandboxCwd),
691
+ tag: "pi-res"
692
+ });
693
+ };
694
+ var makePiSessionStorage = (options) => {
695
+ const hostSessionsDir = options?.sessionStorage?.hostSessionsDir;
696
+ const sandboxSessionsDirOf = (handle) => options?.sessionStorage?.sandboxSessionsDir ?? posix.join(sandboxDirsOf(handle).home, ".pi", "agent", "sessions");
697
+ const capturedPaths = /* @__PURE__ */ new Map();
698
+ return {
699
+ hostSessionFilePath: (cwd, id) => capturedPaths.get(id) ?? piSessionDirPath(cwd, hostSessionsDir),
700
+ existsOnHost: async (_cwd, id) => {
701
+ const found = await findPiSessionOnHost(id, hostSessionsDir);
702
+ return found.path !== void 0;
703
+ },
704
+ readHostSession: async (_cwd, id) => {
705
+ const { path } = await findPiSessionOnHost(id, hostSessionsDir);
706
+ return path === void 0 ? void 0 : readFile(path, "utf8");
707
+ },
708
+ captureToHost: async ({ hostCwd, sandboxCwd, sessionId, handle }) => {
709
+ const located = await locateSandboxSessionFile(
710
+ handle,
711
+ sandboxSessionsDirOf(handle),
712
+ `*_${sessionId}.jsonl`
713
+ );
714
+ const jsonl = await readSandboxFile(handle, located.path, "pi-cap");
715
+ const rewritten = transferPiSession(jsonl, sandboxCwd, hostCwd);
716
+ const target = piHostCaptureTarget(
717
+ hostCwd,
718
+ located.path,
719
+ hostSessionsDir
720
+ );
721
+ await mkdir(dirname(target), { recursive: true });
722
+ await writeFile(target, rewritten);
723
+ capturedPaths.set(sessionId, target);
724
+ },
725
+ resumeIntoSandbox: (transfer) => resumePiIntoSandbox(transfer, {
726
+ hostSessionsDir,
727
+ sandboxSessionsDir: sandboxSessionsDirOf(transfer.handle)
728
+ }),
729
+ findByIdOnHost: (id) => findPiSessionOnHost(id, hostSessionsDir)
730
+ };
731
+ };
732
+ var lastAssistantMessage = (messages) => {
733
+ for (let i = messages.length - 1; i >= 0; i--) {
734
+ const msg = messages[i];
735
+ if (msg?.role === "assistant") {
736
+ return msg;
737
+ }
738
+ }
739
+ return null;
740
+ };
741
+ var parsePiAgentEnd = (messages) => {
742
+ const msg = lastAssistantMessage(messages);
743
+ if (msg === null) {
744
+ return [];
745
+ }
746
+ if (msg.stopReason === "error") {
747
+ return [
748
+ {
749
+ type: "error",
750
+ message: typeof msg.errorMessage === "string" && msg.errorMessage ? msg.errorMessage : 'pi stopped with stopReason "error"'
751
+ }
752
+ ];
753
+ }
754
+ const texts = msg.content.flatMap(
755
+ (block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []
756
+ );
757
+ return texts.length > 0 ? [{ type: "result", result: texts.join("") }] : [];
758
+ };
759
+ var parsePiStreamLine = (line) => {
760
+ if (!line.startsWith("{")) return [];
761
+ try {
762
+ const obj = JSON.parse(line);
763
+ if (obj.type === "session" && typeof obj.id === "string") {
764
+ return [{ type: "session_id", sessionId: obj.id }];
765
+ }
766
+ if (obj.type === "message_end" && obj.message?.role === "assistant") {
767
+ const u = obj.message.usage;
768
+ return contextWindowEvent(u?.input, u?.cacheRead, u?.cacheWrite);
769
+ }
770
+ if (obj.type === "message_update" && obj.assistantMessageEvent) {
771
+ const evt = obj.assistantMessageEvent;
772
+ if (evt.type === "text_delta" && typeof evt.delta === "string") {
773
+ return [{ type: "text", text: evt.delta }];
774
+ }
775
+ return [];
776
+ }
777
+ if (obj.type === "tool_execution_start") {
778
+ const rawName = obj.toolName;
779
+ if (typeof rawName !== "string") return [];
780
+ const toolName = Object.keys(TOOL_ARG_FIELDS).find(
781
+ (name) => name.toLowerCase() === rawName.toLowerCase()
782
+ );
783
+ if (toolName === void 0) return [];
784
+ const argField = TOOL_ARG_FIELDS[toolName];
785
+ if (argField === void 0) return [];
786
+ const args = obj.args;
787
+ if (!args) return [];
788
+ const argValue = args[argField];
789
+ if (typeof argValue !== "string") return [];
790
+ return [{ type: "tool_call", name: toolName, args: argValue }];
791
+ }
792
+ if (obj.type === "agent_error" || obj.type === "error") {
793
+ const msg = extractErrorMessage(obj);
794
+ return msg ? [{ type: "error", message: msg }] : [];
795
+ }
796
+ if (obj.type === "agent_end" && Array.isArray(obj.messages)) {
797
+ return parsePiAgentEnd(obj.messages);
798
+ }
799
+ } catch {
800
+ }
801
+ return [];
802
+ };
803
+ var pi = (model, options) => ({
804
+ name: "pi",
805
+ env: options?.env ?? {},
806
+ captureSessions: options?.captureSessions ?? true,
807
+ sessionStorage: makePiSessionStorage(options),
808
+ buildPrintCommand({
809
+ prompt,
810
+ resumeSession,
811
+ forkSession
812
+ }) {
813
+ const thinkingFlag = options?.thinking ? ` --thinking ${options.thinking}` : "";
814
+ const sessionFlag = resumeSession ? ` --${forkSession ? "fork" : "session"} ${shellEscape(resumeSession)}` : "";
815
+ return {
816
+ command: `pi -p --mode json --model ${shellEscape(model)}${thinkingFlag}${sessionFlag}`,
817
+ stdin: prompt
818
+ };
819
+ },
820
+ buildInteractiveArgs({ prompt }) {
821
+ const args = ["pi", "--model", model];
822
+ if (prompt) args.push(prompt);
823
+ return args;
824
+ },
825
+ parseStreamLine(line) {
826
+ return parsePiStreamLine(line);
827
+ }
828
+ });
829
+ var parseCodexUsage = (usage) => {
830
+ if (typeof usage !== "object" || usage === null) return void 0;
831
+ const u = usage;
832
+ if (typeof u.input_tokens !== "number" || typeof u.cached_input_tokens !== "number" || typeof u.output_tokens !== "number") {
833
+ return void 0;
834
+ }
835
+ return {
836
+ inputTokens: u.input_tokens - u.cached_input_tokens,
837
+ cacheCreationInputTokens: 0,
838
+ cacheReadInputTokens: u.cached_input_tokens,
839
+ outputTokens: u.output_tokens
840
+ };
841
+ };
842
+ var parseCodexSessionContextWindow = (content) => {
843
+ const lines = content.split("\n");
844
+ for (let i = lines.length - 1; i >= 0; i--) {
845
+ const line = lines[i];
846
+ if (!line.startsWith("{")) continue;
847
+ try {
848
+ const obj = JSON.parse(line);
849
+ if (obj.type !== "event_msg" || obj.payload?.type !== "token_count") {
850
+ continue;
851
+ }
852
+ const { info } = obj.payload;
853
+ const tokens = info?.last_token_usage?.input_tokens;
854
+ if (typeof tokens !== "number" || tokens <= 0) continue;
855
+ const limit = info.model_context_window;
856
+ return typeof limit === "number" && limit > 0 ? { tokens, limit } : { tokens };
857
+ } catch {
858
+ }
859
+ }
860
+ return void 0;
861
+ };
862
+ var parseCodexStreamLine = (line) => {
863
+ if (!line.startsWith("{")) return [];
864
+ try {
865
+ const obj = JSON.parse(line);
866
+ if (obj.type === "thread.started" && typeof obj.thread_id === "string") {
867
+ return [{ type: "session_id", sessionId: obj.thread_id }];
868
+ }
869
+ if (obj.type === "item.completed" && obj.item?.type === "agent_message" && typeof obj.item.text === "string") {
870
+ const { text } = obj.item;
871
+ return [
872
+ { type: "text", text },
873
+ { type: "result", result: text }
874
+ ];
875
+ }
876
+ if (obj.type === "item.started" && obj.item?.type === "command_execution" && typeof obj.item.command === "string") {
877
+ return [{ type: "tool_call", name: "Bash", args: obj.item.command }];
878
+ }
879
+ if (obj.type === "error") {
880
+ const msg = extractErrorMessage(obj);
881
+ return msg ? [{ type: "result", result: msg }] : [];
882
+ }
883
+ if (obj.type === "turn.failed") {
884
+ const msg = extractErrorMessage(obj);
885
+ return [{ type: "error", message: msg ?? "codex turn failed" }];
886
+ }
887
+ if (obj.type === "turn.completed") {
888
+ const usage = parseCodexUsage(obj.usage);
889
+ return usage ? [{ type: "usage", usage }] : [];
890
+ }
891
+ } catch {
892
+ }
893
+ return [];
894
+ };
895
+ var buildCodexPrintCommand = (model, options, { prompt, resumeSession, forkSession }) => {
896
+ const effortFlag = options?.effort ? ` -c ${shellEscape(`model_reasoning_effort="${options.effort}"`)}` : "";
897
+ const approvalsFlags = options?.approvalsReviewer === "auto_review" ? ` -a on-request -s danger-full-access -c ${shellEscape(`approvals_reviewer="auto_review"`)}` : " --dangerously-bypass-approvals-and-sandbox";
898
+ let base;
899
+ if (resumeSession && forkSession) {
900
+ base = `codex exec fork ${shellEscape(resumeSession)}`;
901
+ } else if (resumeSession) {
902
+ base = `codex exec resume ${shellEscape(resumeSession)}`;
903
+ } else {
904
+ base = "codex exec";
905
+ }
906
+ const stdinArg = resumeSession ? " -" : "";
907
+ return {
908
+ command: `${base} --json${approvalsFlags} -m ${shellEscape(model)}${effortFlag}${stdinArg}`,
909
+ stdin: prompt
910
+ };
911
+ };
912
+ var codex = (model, options) => ({
913
+ name: "codex",
914
+ env: options?.env ?? {},
915
+ captureSessions: options?.captureSessions ?? true,
916
+ sessionStorage: makeCodexSessionStorage(options),
917
+ buildPrintCommand(commandOptions) {
918
+ return buildCodexPrintCommand(model, options, commandOptions);
919
+ },
920
+ buildInteractiveArgs({ prompt }) {
921
+ const args = ["codex", "--model", model];
922
+ if (prompt) args.push(prompt);
923
+ return args;
924
+ },
925
+ parseStreamLine(line) {
926
+ return parseCodexStreamLine(line);
927
+ },
928
+ parseSessionContextWindow(content) {
929
+ return parseCodexSessionContextWindow(content);
930
+ }
931
+ });
932
+ var makeCursorSessionStorage = (options) => {
933
+ const hostDir = options?.sessionStorage?.hostChatsDir ?? cursorHostChatsDir();
934
+ const sandboxDirOverride = options?.sessionStorage?.sandboxChatsDir;
935
+ return {
936
+ ...makeSessionFileStorage({
937
+ hostRoot: hostDir,
938
+ hostPath: (cwd, id) => join(hostDir, cursorChatDirName(cwd), id, "store.db"),
939
+ hostPathsById: (id, chatDirs) => chatDirs.map((chatDir) => join(hostDir, chatDir, id, "store.db")),
940
+ sandboxPath: (cwd, id, dirs) => posix.join(
941
+ sandboxDirOverride ?? posix.join(dirs.home, ".cursor", "chats"),
942
+ cursorChatDirName(cwd),
943
+ id,
944
+ "store.db"
945
+ )
946
+ }),
947
+ canFork: false
948
+ };
949
+ };
950
+ var cursor = (model, options) => ({
951
+ name: "cursor",
952
+ env: options?.env ?? {},
953
+ captureSessions: options?.captureSessions ?? true,
954
+ sessionStorage: makeCursorSessionStorage(options),
955
+ buildPrintCommand({
956
+ prompt,
957
+ dangerouslySkipPermissions,
958
+ resumeSession,
959
+ forkSession
960
+ }) {
961
+ if (resumeSession !== void 0 && forkSession === true) {
962
+ throw new ForkNotSupportedError({
963
+ message: "cursor cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.",
964
+ agentProvider: "cursor"
965
+ });
966
+ }
967
+ assertCursorPrintPromptFitsArgv(prompt);
968
+ const forceFlag = dangerouslySkipPermissions ? " --force" : "";
969
+ const resumeFlag = resumeSession === void 0 ? "" : ` --resume=${shellEscape(resumeSession)}`;
970
+ return {
971
+ command: `agent --print --output-format stream-json --model ${shellEscape(model)} ${forceFlag}${resumeFlag} ${shellEscape(prompt)}`
972
+ };
973
+ },
974
+ buildInteractiveArgs({
975
+ prompt,
976
+ dangerouslySkipPermissions
977
+ }) {
978
+ const args = ["agent", "--model", model];
979
+ if (dangerouslySkipPermissions) args.push("--force");
980
+ if (prompt) args.push(prompt);
981
+ return args;
982
+ },
983
+ parseStreamLine(line) {
984
+ return parseCursorStreamLine(line);
985
+ }
986
+ });
987
+ var OPENCODE_TOOL_ARG_FIELDS = {
988
+ bash: "command",
989
+ webfetch: "url",
990
+ task: "description"
991
+ };
992
+ var parseOpenCodeStreamLine = (line) => {
993
+ if (!line.startsWith("{")) return [];
994
+ try {
995
+ const obj = JSON.parse(line);
996
+ const { part } = obj;
997
+ if (obj.type === "step_start" && typeof obj.sessionID === "string") {
998
+ return [{ type: "session_id", sessionId: obj.sessionID }];
999
+ }
1000
+ if (obj.type === "step_finish" && part?.tokens) {
1001
+ const t = part.tokens;
1002
+ return contextWindowEvent(t.input, t.cache?.read, t.cache?.write);
1003
+ }
1004
+ if (obj.type === "text" && part?.type === "text" && typeof part.text === "string") {
1005
+ return [
1006
+ { type: "text", text: part.text },
1007
+ { type: "result", result: part.text }
1008
+ ];
1009
+ }
1010
+ if (obj.type === "tool_use" && part?.type === "tool") {
1011
+ if (typeof part.tool !== "string") return [];
1012
+ const state = part.state;
1013
+ if (state?.status !== "completed") return [];
1014
+ const { input } = state;
1015
+ if (!input) return [];
1016
+ const argField = OPENCODE_TOOL_ARG_FIELDS[part.tool];
1017
+ const argValue = argField === void 0 ? void 0 : input[argField];
1018
+ const args = typeof argValue === "string" ? argValue : JSON.stringify(input);
1019
+ return [{ type: "tool_call", name: part.tool, args }];
1020
+ }
1021
+ if (obj.type === "error") {
1022
+ const msg = extractErrorMessage(obj);
1023
+ return msg ? [{ type: "error", message: msg }] : [];
1024
+ }
1025
+ } catch {
1026
+ }
1027
+ return [];
1028
+ };
1029
+ var makeOpenCodeSessionStorage = (options) => {
1030
+ const hostDir = options?.sessionStorage?.hostSessionsDir ?? opencodeHostSessionsDir();
1031
+ const exportDirOverride = options?.sessionStorage?.sandboxExportDir;
1032
+ const hostPath = (id) => join(hostDir, `${id}.json`);
1033
+ return makeSessionFileStorage({
1034
+ hostRoot: hostDir,
1035
+ hostPath: (_cwd, id) => hostPath(id),
1036
+ // A no-sandbox run resumes from OpenCode's own database, which can't be
1037
+ // queried by id from here; OpenCode reports an unknown id itself.
1038
+ hostPathsById: (id) => [hostPath(id), opencodeHostDatabase()],
1039
+ sandboxPath: (_cwd, id, dirs) => posix.join(exportDirOverride ?? dirs.tmp, `${id}.json`),
1040
+ sandboxExport: (id, path) => `opencode export ${shellEscape(id)} > ${shellEscape(path)}`,
1041
+ sandboxImport: (_id, path) => `opencode import ${shellEscape(path)}`
1042
+ });
1043
+ };
1044
+ var opencode = (model, options) => ({
1045
+ name: "opencode",
1046
+ env: options?.env ?? {},
1047
+ captureSessions: options?.captureSessions ?? true,
1048
+ sessionStorage: makeOpenCodeSessionStorage(options),
1049
+ buildPrintCommand({
1050
+ prompt,
1051
+ dangerouslySkipPermissions,
1052
+ resumeSession,
1053
+ forkSession
1054
+ }) {
1055
+ const variantFlag = options?.variant ? ` --variant ${shellEscape(options.variant)}` : "";
1056
+ const agentFlag = options?.agent ? ` --agent ${shellEscape(options.agent)}` : "";
1057
+ const permissionsFlag = dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
1058
+ const sessionFlags = resumeSession === void 0 ? "" : ` --session ${shellEscape(resumeSession)}${forkSession === true ? " --fork" : ""}`;
1059
+ return {
1060
+ command: `opencode run --format json --model ${shellEscape(model)}${variantFlag}${agentFlag}${permissionsFlag}${sessionFlags} ${shellEscape(prompt)}`
1061
+ };
1062
+ },
1063
+ buildInteractiveArgs({ prompt }) {
1064
+ const args = ["opencode", "--model", model];
1065
+ if (options?.agent) args.push("--agent", options.agent);
1066
+ if (prompt) args.push("--prompt", prompt);
1067
+ return args;
1068
+ },
1069
+ parseStreamLine(line) {
1070
+ return parseOpenCodeStreamLine(line);
1071
+ }
1072
+ });
1073
+ var COPILOT_PRINT_PROMPT_MAX_BYTES = 120 * 1024;
1074
+ var assertCopilotPrintPromptFitsArgv = (prompt) => {
1075
+ const n = Buffer.byteLength(prompt, "utf8");
1076
+ if (n > COPILOT_PRINT_PROMPT_MAX_BYTES) {
1077
+ throw new Error(
1078
+ `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.`
1079
+ );
1080
+ }
1081
+ };
1082
+ var parseCopilotStreamLine = (line) => {
1083
+ if (!line.startsWith("{")) return [];
1084
+ try {
1085
+ const obj = JSON.parse(line);
1086
+ if (obj.type === "assistant.message_delta" && typeof obj.data?.deltaContent === "string") {
1087
+ return [{ type: "text", text: obj.data.deltaContent }];
1088
+ }
1089
+ if (obj.type === "tool.execution_start") {
1090
+ const rawName = obj.data?.toolName;
1091
+ if (typeof rawName !== "string") return [];
1092
+ const toolName = rawName === "bash" ? "Bash" : rawName;
1093
+ const argField = TOOL_ARG_FIELDS[toolName];
1094
+ if (argField === void 0) return [];
1095
+ const args = obj.data?.arguments;
1096
+ if (!args) return [];
1097
+ const argValue = args[argField];
1098
+ if (typeof argValue !== "string") return [];
1099
+ return [{ type: "tool_call", name: toolName, args: argValue }];
1100
+ }
1101
+ if (obj.type === "assistant.message" && typeof obj.data?.content === "string" && obj.data.content.length > 0) {
1102
+ return [{ type: "result", result: obj.data.content }];
1103
+ }
1104
+ if (obj.type === "session.usage_checkpoint") {
1105
+ return contextWindowEvent(
1106
+ obj.data?.accountingSnapshot?.lastCallInputTokens
1107
+ );
1108
+ }
1109
+ if (obj.type === "result" && typeof obj.sessionId === "string") {
1110
+ return [{ type: "session_id", sessionId: obj.sessionId }];
1111
+ }
1112
+ if (obj.type === "error" || obj.type === "agent_error") {
1113
+ const msg = extractErrorMessage(obj);
1114
+ return msg ? [{ type: "error", message: msg }] : [];
1115
+ }
1116
+ } catch {
1117
+ }
1118
+ return [];
1119
+ };
1120
+ var makeCopilotSessionStorage = (options) => {
1121
+ const hostDir = options?.sessionStorage?.hostSessionsDir ?? copilotHostSessionsDir();
1122
+ const sandboxDirOverride = options?.sessionStorage?.sandboxSessionsDir;
1123
+ const hostPath = (id) => join(hostDir, id, "events.jsonl");
1124
+ return {
1125
+ ...makeSessionFileStorage({
1126
+ hostRoot: hostDir,
1127
+ hostPath: (_cwd, id) => hostPath(id),
1128
+ hostPathsById: (id) => [hostPath(id)],
1129
+ sandboxPath: (_cwd, id, dirs) => copilotSessionPath(
1130
+ sandboxDirOverride ?? posix.join(dirs.home, ".copilot", "session-state"),
1131
+ id
1132
+ ),
1133
+ rewrite: transferCopilotSession
1134
+ }),
1135
+ canFork: false
1136
+ };
1137
+ };
1138
+ var copilot = (model, options) => ({
1139
+ name: "copilot",
1140
+ env: options?.env ?? {},
1141
+ captureSessions: options?.captureSessions ?? true,
1142
+ sessionStorage: makeCopilotSessionStorage(options),
1143
+ buildPrintCommand({
1144
+ prompt,
1145
+ dangerouslySkipPermissions,
1146
+ resumeSession,
1147
+ forkSession
1148
+ }) {
1149
+ if (resumeSession !== void 0 && forkSession === true) {
1150
+ throw new ForkNotSupportedError({
1151
+ message: "copilot cannot fork a session: its CLI resumes but has no fork. Use resume() to continue the session in place.",
1152
+ agentProvider: "copilot"
1153
+ });
1154
+ }
1155
+ assertCopilotPrintPromptFitsArgv(prompt);
1156
+ const allowAll = dangerouslySkipPermissions ? " --allow-all-tools" : "";
1157
+ const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
1158
+ const resumeFlag = resumeSession === void 0 ? "" : ` --resume=${shellEscape(resumeSession)}`;
1159
+ return {
1160
+ command: `copilot -p ${shellEscape(prompt)} --output-format json --model ${shellEscape(model)}${allowAll}${effortFlag}${resumeFlag}`
1161
+ };
1162
+ },
1163
+ buildInteractiveArgs({ prompt }) {
1164
+ const args = ["copilot", "--model", model];
1165
+ if (prompt) args.push("-i", prompt);
1166
+ return args;
1167
+ },
1168
+ parseStreamLine(line) {
1169
+ return parseCopilotStreamLine(line);
1170
+ }
1171
+ });
1172
+ var buildClaudePrintCommand = (model, options, {
1173
+ prompt,
1174
+ dangerouslySkipPermissions,
1175
+ resumeSession,
1176
+ forkSession
1177
+ }) => {
1178
+ const skipPermissionsFlag = dangerouslySkipPermissions ? " --dangerously-skip-permissions" : "";
1179
+ const permissionFlag = options?.permissionMode ? ` --permission-mode ${options.permissionMode}` : skipPermissionsFlag;
1180
+ const effortFlag = options?.effort ? ` --effort ${options.effort}` : "";
1181
+ const resumeFlag = resumeSession ? ` --resume ${shellEscape(resumeSession)}` : "";
1182
+ const forkFlag = resumeSession && forkSession ? " --fork-session" : "";
1183
+ return {
1184
+ command: `claude --print --verbose${permissionFlag} --output-format stream-json --model ${shellEscape(model)}${effortFlag}${resumeFlag}${forkFlag} -p -`,
1185
+ stdin: prompt
1186
+ };
1187
+ };
1188
+ var parseClaudeSessionUsage = (content) => {
1189
+ const lines = content.split("\n");
1190
+ for (let i = lines.length - 1; i >= 0; i--) {
1191
+ const line = lines[i];
1192
+ if (!line.startsWith("{")) continue;
1193
+ try {
1194
+ const obj = JSON.parse(line);
1195
+ if (obj.type === "assistant" && obj.message?.usage) {
1196
+ const u = obj.message.usage;
1197
+ 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") {
1198
+ return {
1199
+ inputTokens: u.input_tokens,
1200
+ cacheCreationInputTokens: u.cache_creation_input_tokens,
1201
+ cacheReadInputTokens: u.cache_read_input_tokens,
1202
+ outputTokens: u.output_tokens
1203
+ };
1204
+ }
1205
+ }
1206
+ } catch {
1207
+ }
1208
+ }
1209
+ return void 0;
1210
+ };
1211
+ var claudeCode = (model, options) => ({
1212
+ name: "claude-code",
1213
+ env: options?.env ?? {},
1214
+ captureSessions: options?.captureSessions ?? true,
1215
+ sessionStorage: makeClaudeSessionStorage(options),
1216
+ buildPrintCommand(commandOptions) {
1217
+ return buildClaudePrintCommand(model, options, commandOptions);
1218
+ },
1219
+ buildInteractiveArgs({
1220
+ prompt,
1221
+ dangerouslySkipPermissions
1222
+ }) {
1223
+ const args = ["claude"];
1224
+ if (options?.permissionMode) {
1225
+ args.push("--permission-mode", options.permissionMode);
1226
+ } else if (dangerouslySkipPermissions) {
1227
+ args.push("--dangerously-skip-permissions");
1228
+ }
1229
+ args.push("--model", model);
1230
+ if (options?.effort) args.push("--effort", options.effort);
1231
+ if (prompt) args.push(prompt);
1232
+ return args;
1233
+ },
1234
+ parseStreamLine(line) {
1235
+ return [...parseStreamJsonLine(line), ...parseClaudeContextWindow(line)];
1236
+ },
1237
+ parseSessionUsage(content) {
1238
+ return parseClaudeSessionUsage(content);
1239
+ }
1240
+ });
1241
+
1242
+ export { claudeCode, claudeHostSessionPath, claudeSandboxSessionPath, codex, copilot, cursor, encodeProjectPath, findClaudeSessionOnHost, findCodexSessionOnHost, opencode, pi, shellEscape, transferClaudeSession, transferCodexSession };
1243
+ //# sourceMappingURL=chunk-H2PEFS4W.js.map
1244
+ //# sourceMappingURL=chunk-H2PEFS4W.js.map