@ai-hero/sandcastle 0.12.0 → 0.13.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 (60) 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-YCL97qco.d.ts} +30 -3
  4. package/dist/chunk-4EIVTSOZ.js +93 -0
  5. package/dist/chunk-4EIVTSOZ.js.map +1 -0
  6. package/dist/{chunk-NGBM7T3E.js → chunk-6NQPCXSG.js} +5 -2
  7. package/dist/chunk-6NQPCXSG.js.map +1 -0
  8. package/dist/chunk-767EAJVT.js +112 -0
  9. package/dist/chunk-767EAJVT.js.map +1 -0
  10. package/dist/chunk-7N7AMUYA.js +353 -0
  11. package/dist/chunk-7N7AMUYA.js.map +1 -0
  12. package/dist/{chunk-DJRHWPEH.js → chunk-A4C2FG74.js} +258 -327
  13. package/dist/chunk-A4C2FG74.js.map +1 -0
  14. package/dist/chunk-J5J5YJ5S.js +50 -0
  15. package/dist/chunk-J5J5YJ5S.js.map +1 -0
  16. package/dist/{chunk-VOG34SRF.js → chunk-LWNC4UTZ.js} +13702 -4881
  17. package/dist/chunk-LWNC4UTZ.js.map +1 -0
  18. package/dist/chunk-NMQ5Z6YG.js +148 -0
  19. package/dist/chunk-NMQ5Z6YG.js.map +1 -0
  20. package/dist/{chunk-CP3TYXZA.js → chunk-U42XXICG.js} +92 -85
  21. package/dist/chunk-U42XXICG.js.map +1 -0
  22. package/dist/chunk-XCWKLDH4.js +24 -0
  23. package/dist/chunk-XCWKLDH4.js.map +1 -0
  24. package/dist/{chunk-BIWNFKGV.js → chunk-XCYK7I45.js} +2 -2
  25. package/dist/chunk-XCYK7I45.js.map +1 -0
  26. package/dist/index.d.ts +237 -26
  27. package/dist/index.js +2789 -2169
  28. package/dist/index.js.map +1 -1
  29. package/dist/main.js +1004 -625
  30. package/dist/main.js.map +1 -1
  31. package/dist/sandboxes/bwrap.d.ts +58 -0
  32. package/dist/sandboxes/bwrap.js +293 -0
  33. package/dist/sandboxes/bwrap.js.map +1 -0
  34. package/dist/sandboxes/daytona.d.ts +1 -1
  35. package/dist/sandboxes/daytona.js +78 -17
  36. package/dist/sandboxes/daytona.js.map +1 -1
  37. package/dist/sandboxes/docker.d.ts +18 -4
  38. package/dist/sandboxes/docker.js +4 -4
  39. package/dist/sandboxes/no-sandbox.d.ts +1 -1
  40. package/dist/sandboxes/no-sandbox.js +2 -2
  41. package/dist/sandboxes/podman.d.ts +18 -4
  42. package/dist/sandboxes/podman.js +69 -56
  43. package/dist/sandboxes/podman.js.map +1 -1
  44. package/dist/sandboxes/seatbelt.d.ts +65 -0
  45. package/dist/sandboxes/seatbelt.js +422 -0
  46. package/dist/sandboxes/seatbelt.js.map +1 -0
  47. package/dist/sandboxes/vercel.d.ts +12 -5
  48. package/dist/sandboxes/vercel.js +195 -126
  49. package/dist/sandboxes/vercel.js.map +1 -1
  50. package/dist/templates/parallel-planner/main.mts +13 -22
  51. package/dist/templates/parallel-planner-with-review/main.mts +13 -15
  52. package/package.json +34 -10
  53. package/dist/chunk-62WN33RK.js +0 -104
  54. package/dist/chunk-62WN33RK.js.map +0 -1
  55. package/dist/chunk-BIWNFKGV.js.map +0 -1
  56. package/dist/chunk-CP3TYXZA.js.map +0 -1
  57. package/dist/chunk-DJRHWPEH.js.map +0 -1
  58. package/dist/chunk-NGBM7T3E.js.map +0 -1
  59. package/dist/chunk-VOG34SRF.js.map +0 -1
  60. package/dist/mountUtils-CCA-bbpK.d.ts +0 -25
@@ -0,0 +1,58 @@
1
+ import { B as BindMountSandboxProvider } from '../SandboxProvider-YCL97qco.js';
2
+ import { M as MountConfig } from '../MountConfig-CmXclHA5.js';
3
+
4
+ /**
5
+ * Bubblewrap sandbox provider — a native sandbox provider for Linux and WSL2.
6
+ *
7
+ * Usage:
8
+ * import { bwrap } from "@ai-hero/sandcastle/sandboxes/bwrap";
9
+ * await run({ agent: claudeCode("claude-opus-4-8"), sandbox: bwrap() });
10
+ *
11
+ * Each `exec` runs in a fresh Bubblewrap sandbox: the host's system dirs
12
+ * read-only, the worktree and git dirs at their host paths, a private home at
13
+ * `/home/agent` and a private `/tmp`, its own PID namespace, the host network,
14
+ * and only the env vars Sandcastle passes in. No image, no daemon.
15
+ */
16
+
17
+ /** Options for {@link bwrap}. */
18
+ interface BwrapOptions {
19
+ /** Environment variables injected by this provider. Merged at launch time. */
20
+ readonly env?: Record<string, string>;
21
+ /**
22
+ * Maximum number of characters of streamed `exec` output retained per stream
23
+ * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).
24
+ *
25
+ * Output is delivered live to `onLine` regardless; this only bounds the tail
26
+ * returned in `ExecResult`, preventing a long-running agent's output from
27
+ * overflowing V8's max string length and crashing the run.
28
+ */
29
+ readonly maxOutputTailChars?: number;
30
+ /**
31
+ * Extra host paths to make visible in the sandbox (a cache, a sibling
32
+ * checkout, `.beads/`). Each appears at its own host path, so after
33
+ * resolution `sandboxPath` must equal `hostPath`; `bwrap()` throws
34
+ * otherwise. `readonly` defaults to `false`.
35
+ */
36
+ readonly mounts?: readonly MountConfig[];
37
+ }
38
+ /**
39
+ * Create a Bubblewrap sandbox provider (Linux and WSL2).
40
+ *
41
+ * The agent runs the host's own toolchain, read-only, and can write only the
42
+ * worktree, the git dirs Sandcastle mounts, a private `/tmp` and a private
43
+ * home at `/home/agent`. Both private dirs are removed on close, and so is
44
+ * every process the sandbox started. The toolchain comes from the host
45
+ * `PATH`: each `PATH` dir (never the home dir or an ancestor of it) and the
46
+ * install root of each executable symlinked from one. Add other paths with
47
+ * `mounts`. It has no root: `exec` with
48
+ * `sudo: true` rejects. All three branch strategies are supported.
49
+ *
50
+ * Checks once per process that Bubblewrap is usable, and throws
51
+ * `NativeSandboxUnavailableError` (with a `fixCommand` when there is
52
+ * one) if it isn't: on a non-Linux OS, when `bwrap` isn't on `PATH`, or when
53
+ * the kernel blocks unprivileged user namespaces. It never falls back to
54
+ * running unsandboxed.
55
+ */
56
+ declare const bwrap: (options?: BwrapOptions) => BindMountSandboxProvider;
57
+
58
+ export { type BwrapOptions, bwrap };
@@ -0,0 +1,293 @@
1
+ import { createRequire } from 'node:module';
2
+ import { resolveIdentityMounts, copyCreatingParents, collectOutput, hostPathToolchainFromEnv } from '../chunk-NMQ5Z6YG.js';
3
+ import { markNativeSandboxProvider } from '../chunk-XCWKLDH4.js';
4
+ import { assertBwrapUsable } from '../chunk-767EAJVT.js';
5
+ import { NodeFileSystem_exports } from '../chunk-A4C2FG74.js';
6
+ import { Effect_exports, FileSystem_exports, Option_exports, BwrapError, registerShutdown } from '../chunk-LWNC4UTZ.js';
7
+ import { createBindMountSandboxProvider } from '../chunk-XCYK7I45.js';
8
+ import { MAX_TAIL_CHARS } from '../chunk-6NQPCXSG.js';
9
+ import { spawn } from 'child_process';
10
+ import { once } from 'events';
11
+ import { join, posix } from 'path';
12
+ import { rmSync } from 'fs';
13
+
14
+ createRequire(import.meta.url);
15
+
16
+ // src/bwrapProcess.ts
17
+ var INFO_FD = 3;
18
+ var WATCH_FD = 4;
19
+ var watchedCommand = (command) => [
20
+ "sh",
21
+ "-c",
22
+ `{ read -r _ || :; kill -9 -1; } <&${WATCH_FD} >/dev/null 2>&1 &
23
+ exec ${WATCH_FD}<&-
24
+ exec sh -c "$1"`,
25
+ "sh",
26
+ command
27
+ ];
28
+ var CHILD_PID = /"child-pid"\s*:\s*(?<pid>\d+)/u;
29
+ var parseChildPid = (info) => {
30
+ const pid = CHILD_PID.exec(info)?.groups?.["pid"];
31
+ return pid === void 0 ? void 0 : Number(pid);
32
+ };
33
+ var killSandboxProcess = (sandbox) => {
34
+ if (sandbox.sandboxPid !== void 0) {
35
+ try {
36
+ process.kill(sandbox.sandboxPid, "SIGKILL");
37
+ } catch {
38
+ }
39
+ }
40
+ sandbox.proc.kill("SIGKILL");
41
+ };
42
+
43
+ // src/bwrapSandbox.ts
44
+ var SANDBOX_HOME = "/home/agent";
45
+ var SANDBOX_TMP = "/tmp";
46
+ var SYSTEM_DIRS = [
47
+ "/usr",
48
+ "/etc",
49
+ "/bin",
50
+ "/sbin",
51
+ "/lib",
52
+ "/lib32",
53
+ "/lib64",
54
+ "/libx32",
55
+ "/opt"
56
+ ];
57
+ var DENIED_ROOTS = ["/mnt", "/run/WSL"];
58
+ var FALLBACK_PATH = "/usr/local/bin:/usr/bin:/bin";
59
+ var isWithin = (path, root) => path === root || path.startsWith(`${root}/`);
60
+ var systemDirArgs = Effect_exports.gen(function* () {
61
+ const fs = yield* FileSystem_exports.FileSystem;
62
+ const args = yield* Effect_exports.all(
63
+ SYSTEM_DIRS.map(
64
+ (dir) => Effect_exports.gen(function* () {
65
+ const link = yield* Effect_exports.option(fs.readLink(dir));
66
+ if (Option_exports.isSome(link)) {
67
+ return ["--symlink", link.value, dir];
68
+ }
69
+ const exists = yield* fs.exists(dir).pipe(Effect_exports.orElseSucceed(() => false));
70
+ return exists ? ["--ro-bind", dir, dir] : [];
71
+ })
72
+ )
73
+ );
74
+ return args.flat();
75
+ });
76
+ var resolvConfArgs = Effect_exports.gen(function* () {
77
+ const fs = yield* FileSystem_exports.FileSystem;
78
+ const target = yield* Effect_exports.option(fs.realPath("/etc/resolv.conf"));
79
+ return Option_exports.isNone(target) || SYSTEM_DIRS.some((d) => isWithin(target.value, d)) ? [] : ["--ro-bind", target.value, target.value];
80
+ });
81
+ var mountArgs = (mounts) => mounts.flatMap((m) => [
82
+ m.readonly === true ? "--ro-bind" : "--bind",
83
+ m.hostPath,
84
+ m.hostPath
85
+ ]);
86
+ var anchorArgs = (mounts) => {
87
+ const writable = mounts.filter((m) => m.readonly !== true);
88
+ const anchors = /* @__PURE__ */ new Set();
89
+ for (const overlay of mounts.filter((m) => m.readonly === true)) {
90
+ const roots = writable.filter(
91
+ (m) => isWithin(overlay.hostPath, m.hostPath)
92
+ );
93
+ const chain = [];
94
+ let dir = posix.dirname(overlay.hostPath);
95
+ while (roots.some((m) => dir !== m.hostPath && isWithin(dir, m.hostPath))) {
96
+ chain.unshift(dir);
97
+ dir = posix.dirname(dir);
98
+ }
99
+ for (const anchor of chain) {
100
+ anchors.add(anchor);
101
+ }
102
+ }
103
+ return [...anchors].flatMap((anchor) => ["--bind", anchor, anchor]);
104
+ };
105
+ var bwrapMounts = (mounts) => resolveIdentityMounts("bwrap", mounts, SANDBOX_HOME);
106
+ var toolchainArgs = (toolchain) => [
107
+ ...toolchain.readableDirs.flatMap((dir) => ["--ro-bind", dir, dir]),
108
+ ...toolchain.symlinks.flatMap((link) => [
109
+ "--symlink",
110
+ link.target,
111
+ link.path
112
+ ])
113
+ ];
114
+ var envArgs = (env) => Object.entries(env).flatMap(([key, value]) => ["--setenv", key, value]);
115
+ var makePrivateDirs = Effect_exports.gen(function* () {
116
+ const fs = yield* FileSystem_exports.FileSystem;
117
+ const root = yield* fs.makeTempDirectory({ prefix: "sandcastle-bwrap-" });
118
+ const dirs = { root, home: join(root, "home"), tmp: join(root, "tmp") };
119
+ yield* fs.makeDirectory(dirs.home);
120
+ yield* fs.makeDirectory(dirs.tmp);
121
+ return dirs;
122
+ }).pipe(
123
+ Effect_exports.mapError(
124
+ (e) => new BwrapError({
125
+ message: `Couldn't create the bwrap() sandbox's private dirs: ${e.message}`
126
+ })
127
+ )
128
+ );
129
+ var removePrivateDirs = (dirs) => Effect_exports.gen(function* () {
130
+ const fs = yield* FileSystem_exports.FileSystem;
131
+ yield* fs.remove(dirs.root, { recursive: true }).pipe(Effect_exports.orElse(() => Effect_exports.void));
132
+ });
133
+ var sandboxArgs = (options, dirs, userMounts) => Effect_exports.gen(function* () {
134
+ const toolchain = yield* hostPathToolchainFromEnv({
135
+ coveredRoots: SYSTEM_DIRS,
136
+ deniedRoots: DENIED_ROOTS
137
+ });
138
+ return [
139
+ ...yield* systemDirArgs,
140
+ ...yield* resolvConfArgs,
141
+ "--proc",
142
+ "/proc",
143
+ "--dev",
144
+ "/dev",
145
+ "--tmpfs",
146
+ "/home",
147
+ "--bind",
148
+ dirs.home,
149
+ SANDBOX_HOME,
150
+ "--bind",
151
+ dirs.tmp,
152
+ SANDBOX_TMP,
153
+ ...toolchainArgs(toolchain),
154
+ ...mountArgs(options.mounts),
155
+ ...mountArgs(userMounts),
156
+ ...anchorArgs(options.mounts),
157
+ // The read-only core mounts (the #1261 overlays) again, so no user
158
+ // mount can uncover them.
159
+ ...mountArgs(options.mounts.filter((m) => m.readonly === true)),
160
+ "--clearenv",
161
+ ...envArgs({
162
+ ...options.env,
163
+ PATH: toolchain.pathEntries.length > 0 ? toolchain.pathEntries.join(":") : FALLBACK_PATH,
164
+ HOME: SANDBOX_HOME,
165
+ TMPDIR: SANDBOX_TMP
166
+ }),
167
+ "--unshare-all",
168
+ "--share-net",
169
+ "--die-with-parent",
170
+ "--new-session"
171
+ ];
172
+ });
173
+ var toHostPath = (path, dirs, mounts) => {
174
+ const p = posix.normalize(path);
175
+ if (mounts.some((m) => isWithin(p, m.hostPath))) {
176
+ return p;
177
+ }
178
+ if (isWithin(p, SANDBOX_HOME)) {
179
+ return join(dirs.home, posix.relative(SANDBOX_HOME, p));
180
+ }
181
+ if (isWithin(p, SANDBOX_TMP)) {
182
+ return join(dirs.tmp, posix.relative(SANDBOX_TMP, p));
183
+ }
184
+ return p;
185
+ };
186
+ var registerNativeSandboxShutdown = (killAll, dirs) => registerShutdown(() => {
187
+ killAll();
188
+ try {
189
+ rmSync(dirs.root, { recursive: true, force: true });
190
+ } catch {
191
+ }
192
+ });
193
+
194
+ // src/sandboxes/bwrap.ts
195
+ var trackSandboxProcess = (proc) => {
196
+ const info = proc.stdio[INFO_FD];
197
+ const tracked = { proc, sandboxPid: void 0, reported: Promise.resolve() };
198
+ if (info !== null && info !== void 0) {
199
+ let text = "";
200
+ info.on("data", (chunk) => {
201
+ text += chunk.toString();
202
+ });
203
+ const record = async () => {
204
+ await once(info, "close").catch(() => void 0);
205
+ tracked.sandboxPid = parseChildPid(text);
206
+ };
207
+ tracked.reported = record();
208
+ }
209
+ return tracked;
210
+ };
211
+ var runInBwrap = async (args, opts, sandbox) => {
212
+ const { live, maxTailChars } = sandbox;
213
+ const proc = spawn("bwrap", ["--info-fd", String(INFO_FD), ...args], {
214
+ // fd 3 is INFO_FD; fd 4 is the watcher's WATCH_FD, which is never
215
+ // written and ends only when this process does.
216
+ stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"]
217
+ });
218
+ const tracked = trackSandboxProcess(proc);
219
+ live.add(tracked);
220
+ const output = collectOutput(proc, opts?.onLine, maxTailChars);
221
+ proc.stdin.on("error", () => void 0);
222
+ proc.stdin.end(opts?.stdin ?? "");
223
+ try {
224
+ await once(proc, "close");
225
+ return { ...output(), exitCode: proc.exitCode ?? 1 };
226
+ } finally {
227
+ live.delete(tracked);
228
+ }
229
+ };
230
+ var runOnHost = async (effect) => effect.pipe(Effect_exports.provide(NodeFileSystem_exports.layer), Effect_exports.runPromise);
231
+ var prepare = async (options, userMounts) => Effect_exports.gen(function* () {
232
+ const dirs = yield* makePrivateDirs;
233
+ const baseArgs = yield* sandboxArgs(options, dirs, userMounts);
234
+ return { dirs, baseArgs };
235
+ }).pipe(runOnHost);
236
+ var createHandle = async (options, config) => {
237
+ const { maxTailChars, userMounts } = config;
238
+ const { dirs, baseArgs } = await prepare(options, userMounts);
239
+ const live = /* @__PURE__ */ new Set();
240
+ const killAll = () => {
241
+ for (const sandbox of live) {
242
+ killSandboxProcess(sandbox);
243
+ }
244
+ };
245
+ const unregisterShutdown = registerNativeSandboxShutdown(killAll, dirs);
246
+ let closed = false;
247
+ const hostPathOf = (p) => toHostPath(p, dirs, options.mounts);
248
+ return {
249
+ worktreePath: options.worktreePath,
250
+ exec: async (command, opts) => {
251
+ if (opts?.sudo === true) {
252
+ throw new Error(
253
+ "bwrap() has no root: exec with sudo: true isn't supported in a native sandbox. Use docker() for setup that needs root."
254
+ );
255
+ }
256
+ if (closed) {
257
+ throw new Error("bwrap() sandbox is closed");
258
+ }
259
+ const cwd = opts?.cwd ?? options.worktreePath;
260
+ const args = [...baseArgs, "--chdir", cwd, ...watchedCommand(command)];
261
+ return runInBwrap(args, opts, { live, maxTailChars });
262
+ },
263
+ copyFileIn: async (hostPath, sandboxFile) => copyCreatingParents(hostPath, hostPathOf(sandboxFile)).pipe(runOnHost),
264
+ copyFileOut: async (sandboxFile, hostPath) => copyCreatingParents(hostPathOf(sandboxFile), hostPath).pipe(runOnHost),
265
+ close: async () => {
266
+ closed = true;
267
+ const running = [...live];
268
+ const exits = running.map(async ({ proc }) => once(proc, "close"));
269
+ await Promise.all(running.map(async ({ reported }) => reported));
270
+ killAll();
271
+ await Promise.allSettled(exits);
272
+ unregisterShutdown();
273
+ await removePrivateDirs(dirs).pipe(runOnHost);
274
+ }
275
+ };
276
+ };
277
+ var bwrap = (options) => {
278
+ const userMounts = bwrapMounts(options?.mounts ?? []);
279
+ assertBwrapUsable();
280
+ const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
281
+ return markNativeSandboxProvider(
282
+ createBindMountSandboxProvider({
283
+ name: "bwrap",
284
+ env: options?.env ?? {},
285
+ sandboxHomedir: SANDBOX_HOME,
286
+ create: async (createOptions) => createHandle(createOptions, { maxTailChars, userMounts })
287
+ })
288
+ );
289
+ };
290
+
291
+ export { bwrap };
292
+ //# sourceMappingURL=bwrap.js.map
293
+ //# sourceMappingURL=bwrap.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/bwrapProcess.ts","../../src/bwrapSandbox.ts","../../src/nativeSandboxShutdown.ts","../../src/sandboxes/bwrap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAQO,IAAM,OAAA,GAAU,CAAA;AAqBhB,IAAM,QAAA,GAAW,CAAA;AAcjB,IAAM,cAAA,GAAiB,CAAC,OAAA,KAA8B;AAAA,EAC3D,IAAA;AAAA,EACA,IAAA;AAAA,EACA,qCAAqC,QAAQ,CAAA;AAAA,KAAA,EACxC,QAAQ,CAAA;AAAA,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AAA,CAAQ,IAAI,OAAA,CAAQ,GAAA,CAAI,OAAO,EAAE,QAAA,EAAS,KAAM,QAAQ,CAAC,CAAA;AAC/D,MAAA,OAAA,EAAQ;AACR,MAAA,MAAM,OAAA,CAAQ,WAAW,KAAK,CAAA;AAC9B,MAAA,kBAAA,EAAmB;AACnB,MAAA,MAAM,iBAAA,CAAkB,IAAI,CAAA,CAAE,IAAA,CAAK,SAAS,CAAA;AAAA,IAC9C;AAAA,GACF;AACF,CAAA;AAoBO,IAAM,KAAA,GAAQ,CAAC,OAAA,KAAqD;AAGzE,EAAA,MAAM,UAAA,GAAa,WAAA,CAAY,OAAA,EAAS,MAAA,IAAU,EAAE,CAAA;AACpD,EAAA,iBAAA,EAAkB;AAClB,EAAA,MAAM,YAAA,GAAe,SAAS,kBAAA,IAAsB,cAAA;AACpD,EAAA,OAAO,yBAAA;AAAA,IACL,8BAAA,CAA+B;AAAA,MAC7B,IAAA,EAAM,OAAA;AAAA,MACN,GAAA,EAAK,OAAA,EAAS,GAAA,IAAO,EAAC;AAAA,MACtB,cAAA,EAAgB,YAAA;AAAA,MAChB,MAAA,EAAQ,OAAO,aAAA,KACb,YAAA,CAAa,eAAe,EAAE,YAAA,EAAc,YAAY;AAAA,KAC3D;AAAA,GACH;AACF","file":"bwrap.js","sourcesContent":["/**\n * The processes behind one `bwrap()` exec, and how to kill all of them. Used\n * only by `bwrap()`, through src/bwrapSandbox.ts.\n */\n\nimport type { ChildProcess } from \"node:child_process\";\n\n/** The fd bwrap reports the sandbox's PID 1 on (`--info-fd`). */\nexport const INFO_FD = 3;\n\n/**\n * One exec's bwrap. `proc` is the outer bwrap; `sandboxPid` is the host PID\n * of the sandbox's PID 1, once bwrap has reported it on {@link INFO_FD}.\n * Killing only the outer bwrap leaves the sandbox running: its PID 1 has its\n * own session and outlives its parent. Killing PID 1 ends every process in\n * the sandbox's PID namespace.\n */\nexport interface SandboxProcess {\n readonly proc: ChildProcess;\n sandboxPid: number | undefined;\n /** Settles once bwrap has reported the PID, or closed its info fd without one. */\n readonly reported: Promise<void>;\n}\n\n/**\n * The fd each sandbox's watcher reads (see {@link watchedCommand}). Its\n * other end is held only by this Node process, so it reads end-of-file\n * exactly when this process dies, however it dies.\n */\nexport const WATCH_FD = 4;\n\n/**\n * Runs `command` in the sandbox under a watcher: a background shell blocked\n * on {@link WATCH_FD}, which SIGKILLs every process in the sandbox's PID\n * namespace (`kill -1` spares only PID 1, which then exits) once this Node\n * process dies.\n *\n * `--die-with-parent` alone isn't enough: bwrap arms it in the sandbox's PID 1\n * only once setup is done, so a host process SIGKILLed during an exec's first\n * milliseconds leaves the sandbox running. The watcher starts after setup and\n * sees the end-of-file even if the host died first. The command itself runs\n * without the watcher's fd.\n */\nexport const watchedCommand = (command: string): string[] => [\n \"sh\",\n \"-c\",\n `{ read -r _ || :; kill -9 -1; } <&${WATCH_FD} >/dev/null 2>&1 &\nexec ${WATCH_FD}<&-\nexec sh -c \"$1\"`,\n \"sh\",\n command,\n];\n\nconst CHILD_PID = /\"child-pid\"\\s*:\\s*(?<pid>\\d+)/u;\n\n/** The `child-pid` in bwrap's `--info-fd` JSON, if it has one. */\nexport const parseChildPid = (info: string): number | undefined => {\n const pid = CHILD_PID.exec(info)?.groups?.[\"pid\"];\n return pid === undefined ? undefined : Number(pid);\n};\n\n/** SIGKILLs the sandbox's PID 1, if reported, and the outer bwrap. Synchronous, for shutdown. */\nexport const killSandboxProcess = (sandbox: SandboxProcess): void => {\n if (sandbox.sandboxPid !== undefined) {\n try {\n process.kill(sandbox.sandboxPid, \"SIGKILL\");\n } catch {\n // Already gone.\n }\n }\n sandbox.proc.kill(\"SIGKILL\");\n};\n","/**\n * The pieces of the `bwrap()` provider (src/sandboxes/bwrap.ts) that don't\n * run processes: the Bubblewrap arguments for a sandbox, its private dirs,\n * and the in-sandbox to host path mapping. Used only by `bwrap()`.\n */\n\nimport { join, posix } from \"node:path\";\nimport { FileSystem } from \"@effect/platform\";\nimport { Effect, Option } from \"effect\";\nimport type { BindMountCreateOptions } from \"./SandboxProvider.js\";\nimport { hostPathToolchainFromEnv } from \"./hostPathToolchain.js\";\nimport type { HostPathToolchain } from \"./hostPathToolchain.js\";\nimport { resolveIdentityMounts } from \"./identityMounts.js\";\nimport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\nimport { BwrapError } from \"./errors.js\";\n\n/** The construction check, from its own module (it runs a process, synchronously). */\nexport { assertBwrapUsable } from \"./bwrapPreflight.js\";\nexport type { IdentityMount, MountConfig } from \"./identityMounts.js\";\n/** Tracking and killing each exec's processes, from their own module. */\nexport {\n INFO_FD,\n WATCH_FD,\n killSandboxProcess,\n parseChildPid,\n watchedCommand,\n} from \"./bwrapProcess.js\";\nexport type { SandboxProcess } from \"./bwrapProcess.js\";\n/** Output collection and file copies, shared by the native sandbox providers. */\nexport { collectOutput, copyCreatingParents } from \"./nativeSandboxIo.js\";\n\n/** The private home's path inside the sandbox. */\nexport const SANDBOX_HOME = \"/home/agent\";\nconst SANDBOX_TMP = \"/tmp\";\n\n/** Host dirs every sandbox sees read-only: the system toolchain. */\nconst SYSTEM_DIRS = [\n \"/usr\",\n \"/etc\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/libx32\",\n \"/opt\",\n];\n\n/**\n * Host dirs that stay hidden even when the host PATH names them: WSL2's\n * Windows drives and interop, so a planted `.exe` can't run.\n */\nconst DENIED_ROOTS = [\"/mnt\", \"/run/WSL\"];\nconst FALLBACK_PATH = \"/usr/local/bin:/usr/bin:/bin\";\n\nconst isWithin = (path: string, root: string): boolean =>\n path === root || path.startsWith(`${root}/`);\n\n/** `--ro-bind` each system dir, or recreate it as a symlink (merged-/usr layouts). */\nconst systemDirArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const args = yield* Effect.all(\n SYSTEM_DIRS.map((dir) =>\n Effect.gen(function* () {\n const link = yield* Effect.option(fs.readLink(dir));\n if (Option.isSome(link)) {\n return [\"--symlink\", link.value, dir];\n }\n const exists = yield* fs\n .exists(dir)\n .pipe(Effect.orElseSucceed(() => false));\n return exists ? [\"--ro-bind\", dir, dir] : [];\n }),\n ),\n );\n return args.flat();\n });\n\n/**\n * `/etc/resolv.conf` may point outside the system dirs (WSL2 links it into\n * `/mnt/wsl`). Mount just that file, read-only, so DNS works.\n */\nconst resolvConfArgs: Effect.Effect<string[], never, FileSystem.FileSystem> =\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const target = yield* Effect.option(fs.realPath(\"/etc/resolv.conf\"));\n return Option.isNone(target) ||\n SYSTEM_DIRS.some((d) => isWithin(target.value, d))\n ? []\n : [\"--ro-bind\", target.value, target.value];\n });\n\n/** Every mount at its host path, in order, so read-only overlays land on their writable parents. */\nconst mountArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] =>\n mounts.flatMap((m) => [\n m.readonly === true ? \"--ro-bind\" : \"--bind\",\n m.hostPath,\n m.hostPath,\n ]);\n\n/**\n * Each dir between a read-only overlay and the writable mount that holds it,\n * bound onto itself, each chain shallowest first. A mount point can't be renamed or\n * removed, so the overlay can't be moved aside by moving a parent (the git\n * worktree admin dir that holds `commondir`, say).\n */\nconst anchorArgs = (\n mounts: readonly { readonly hostPath: string; readonly readonly?: boolean }[],\n): string[] => {\n const writable = mounts.filter((m) => m.readonly !== true);\n const anchors = new Set<string>();\n for (const overlay of mounts.filter((m) => m.readonly === true)) {\n const roots = writable.filter((m) =>\n isWithin(overlay.hostPath, m.hostPath),\n );\n const chain: string[] = [];\n let dir = posix.dirname(overlay.hostPath);\n while (roots.some((m) => dir !== m.hostPath && isWithin(dir, m.hostPath))) {\n chain.unshift(dir);\n dir = posix.dirname(dir);\n }\n for (const anchor of chain) {\n anchors.add(anchor);\n }\n }\n return [...anchors].flatMap((anchor) => [\"--bind\", anchor, anchor]);\n};\n\n/**\n * Checks `bwrap()`'s `mounts` option: each mount, after resolution, must sit\n * at its own host path. Throws at construction otherwise.\n */\nexport const bwrapMounts = (mounts: readonly MountConfig[]): IdentityMount[] =>\n resolveIdentityMounts(\"bwrap\", mounts, SANDBOX_HOME);\n\n/** The host PATH toolchain: each readable dir `--ro-bind`, each symlinked PATH dir recreated. */\nconst toolchainArgs = (toolchain: HostPathToolchain): string[] => [\n ...toolchain.readableDirs.flatMap((dir) => [\"--ro-bind\", dir, dir]),\n ...toolchain.symlinks.flatMap((link) => [\n \"--symlink\",\n link.target,\n link.path,\n ]),\n];\n\nconst envArgs = (env: Record<string, string>): string[] =>\n Object.entries(env).flatMap(([key, value]) => [\"--setenv\", key, value]);\n\n/** The host dirs behind a sandbox's private home and `/tmp`. */\nexport interface PrivateDirs {\n readonly root: string;\n readonly home: string;\n readonly tmp: string;\n}\n\n/** Creates a sandbox's private dirs under the host temp dir. */\nexport const makePrivateDirs: Effect.Effect<\n PrivateDirs,\n BwrapError,\n FileSystem.FileSystem\n> = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const root = yield* fs.makeTempDirectory({ prefix: \"sandcastle-bwrap-\" });\n const dirs = { root, home: join(root, \"home\"), tmp: join(root, \"tmp\") };\n yield* fs.makeDirectory(dirs.home);\n yield* fs.makeDirectory(dirs.tmp);\n return dirs;\n}).pipe(\n Effect.mapError(\n (e) =>\n new BwrapError({\n message: `Couldn't create the bwrap() sandbox's private dirs: ${e.message}`,\n }),\n ),\n);\n\n/** Removes a sandbox's private dirs. */\nexport const removePrivateDirs = (\n dirs: PrivateDirs,\n): Effect.Effect<void, never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n yield* fs\n .remove(dirs.root, { recursive: true })\n .pipe(Effect.orElse(() => Effect.void));\n });\n\n/** The bwrap arguments shared by every exec of one sandbox, up to `--chdir`. */\nexport const sandboxArgs = (\n options: BindMountCreateOptions,\n dirs: PrivateDirs,\n userMounts: readonly IdentityMount[],\n): Effect.Effect<string[], never, FileSystem.FileSystem> =>\n Effect.gen(function* () {\n const toolchain = yield* hostPathToolchainFromEnv({\n coveredRoots: SYSTEM_DIRS,\n deniedRoots: DENIED_ROOTS,\n });\n return [\n ...(yield* systemDirArgs),\n ...(yield* resolvConfArgs),\n \"--proc\",\n \"/proc\",\n \"--dev\",\n \"/dev\",\n \"--tmpfs\",\n \"/home\",\n \"--bind\",\n dirs.home,\n SANDBOX_HOME,\n \"--bind\",\n dirs.tmp,\n SANDBOX_TMP,\n ...toolchainArgs(toolchain),\n ...mountArgs(options.mounts),\n ...mountArgs(userMounts),\n ...anchorArgs(options.mounts),\n // The read-only core mounts (the #1261 overlays) again, so no user\n // mount can uncover them.\n ...mountArgs(options.mounts.filter((m) => m.readonly === true)),\n \"--clearenv\",\n ...envArgs({\n ...options.env,\n PATH:\n toolchain.pathEntries.length > 0\n ? toolchain.pathEntries.join(\":\")\n : FALLBACK_PATH,\n HOME: SANDBOX_HOME,\n TMPDIR: SANDBOX_TMP,\n }),\n \"--unshare-all\",\n \"--share-net\",\n \"--die-with-parent\",\n \"--new-session\",\n ];\n });\n\n/**\n * Maps an in-sandbox path to the host file behind it. Mounts sit at their\n * host paths; the private home and `/tmp` are the private dirs.\n */\nexport const toHostPath = (\n path: string,\n dirs: PrivateDirs,\n mounts: BindMountCreateOptions[\"mounts\"],\n): string => {\n const p = posix.normalize(path);\n if (mounts.some((m) => isWithin(p, m.hostPath))) {\n return p;\n }\n if (isWithin(p, SANDBOX_HOME)) {\n return join(dirs.home, posix.relative(SANDBOX_HOME, p));\n }\n if (isWithin(p, SANDBOX_TMP)) {\n return join(dirs.tmp, posix.relative(SANDBOX_TMP, p));\n }\n return p;\n};\n","/**\n * A native sandbox's shutdown teardown (src/shutdownRegistry.ts). On\n * SIGINT/SIGTERM nothing calls `close()`, and the registry exits as soon as\n * its teardowns return, so the private dirs are removed synchronously: async\n * removal would never finish.\n */\n\n/* oxlint-disable node/no-sync -- a shutdown teardown is synchronous (allowlisted in scripts/lint-ratchet-config.ts). */\n\nimport { rmSync } from \"node:fs\";\nimport { registerShutdown } from \"./shutdownRegistry.js\";\n\n/**\n * Registers the teardown that runs if the process is interrupted or exits\n * before the sandbox is closed: `killAll`, then removing the private dirs\n * under `dirs.root`, best-effort.\n *\n * @returns An idempotent function that unregisters the teardown.\n */\nexport const registerNativeSandboxShutdown = (\n killAll: () => void,\n dirs: { readonly root: string },\n): (() => void) =>\n registerShutdown(() => {\n killAll();\n try {\n rmSync(dirs.root, { recursive: true, force: true });\n } catch {\n // Best-effort: the process is exiting either way.\n }\n });\n","/**\n * Bubblewrap sandbox provider — a native sandbox provider for Linux and WSL2.\n *\n * Usage:\n * import { bwrap } from \"@ai-hero/sandcastle/sandboxes/bwrap\";\n * await run({ agent: claudeCode(\"claude-opus-4-8\"), sandbox: bwrap() });\n *\n * Each `exec` runs in a fresh Bubblewrap sandbox: the host's system dirs\n * read-only, the worktree and git dirs at their host paths, a private home at\n * `/home/agent` and a private `/tmp`, its own PID namespace, the host network,\n * and only the env vars Sandcastle passes in. No image, no daemon.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { once } from \"node:events\";\nimport type { FileSystem } from \"@effect/platform\";\nimport { NodeFileSystem } from \"@effect/platform-node\";\nimport { Effect } from \"effect\";\nimport {\n INFO_FD,\n SANDBOX_HOME,\n assertBwrapUsable,\n collectOutput,\n copyCreatingParents,\n bwrapMounts,\n killSandboxProcess,\n makePrivateDirs,\n removePrivateDirs,\n sandboxArgs,\n parseChildPid,\n toHostPath,\n watchedCommand,\n} from \"../bwrapSandbox.js\";\nimport type {\n IdentityMount,\n MountConfig,\n PrivateDirs,\n SandboxProcess,\n} from \"../bwrapSandbox.js\";\nimport { createBindMountSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n BindMountCreateOptions,\n BindMountSandboxHandle,\n BindMountSandboxProvider,\n ExecResult,\n} from \"../SandboxProvider.js\";\nimport { MAX_TAIL_CHARS } from \"../boundedTail.js\";\nimport { markNativeSandboxProvider } from \"../nativeSandboxProvider.js\";\nimport { registerNativeSandboxShutdown } from \"../nativeSandboxShutdown.js\";\n\n/** Options for {@link bwrap}. */\nexport interface BwrapOptions {\n /** Environment variables injected by this provider. Merged at launch time. */\n readonly env?: Record<string, string>;\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n /**\n * Extra host paths to make visible in the sandbox (a cache, a sibling\n * checkout, `.beads/`). Each appears at its own host path, so after\n * resolution `sandboxPath` must equal `hostPath`; `bwrap()` throws\n * otherwise. `readonly` defaults to `false`.\n */\n readonly mounts?: readonly MountConfig[];\n}\n\n/** Tracks the sandbox PID bwrap reports on the child's {@link INFO_FD} pipe. */\nconst trackSandboxProcess = (proc: ChildProcess): SandboxProcess => {\n const info = proc.stdio[INFO_FD];\n const tracked: { -readonly [K in keyof SandboxProcess]: SandboxProcess[K] } =\n { proc, sandboxPid: undefined, reported: Promise.resolve() };\n if (info !== null && info !== undefined) {\n let text = \"\";\n info.on(\"data\", (chunk: Buffer) => {\n text += chunk.toString();\n });\n const record = async (): Promise<void> => {\n await once(info, \"close\").catch(() => undefined);\n tracked.sandboxPid = parseChildPid(text);\n };\n tracked.reported = record();\n }\n return tracked;\n};\n\ntype ExecOptions = Parameters<BindMountSandboxHandle[\"exec\"]>[1];\n\n/** Runs `sh -c command` in a fresh bwrap and resolves when it exits. */\nconst runInBwrap = async (\n args: readonly string[],\n opts: ExecOptions,\n sandbox: { live: Set<SandboxProcess>; maxTailChars: number },\n): Promise<ExecResult> => {\n const { live, maxTailChars } = sandbox;\n const proc = spawn(\"bwrap\", [\"--info-fd\", String(INFO_FD), ...args], {\n // fd 3 is INFO_FD; fd 4 is the watcher's WATCH_FD, which is never\n // written and ends only when this process does.\n stdio: [\"pipe\", \"pipe\", \"pipe\", \"pipe\", \"pipe\"],\n });\n const tracked = trackSandboxProcess(proc);\n live.add(tracked);\n const output = collectOutput(proc, opts?.onLine, maxTailChars);\n proc.stdin.on(\"error\", () => undefined);\n proc.stdin.end(opts?.stdin ?? \"\");\n try {\n await once(proc, \"close\");\n return { ...output(), exitCode: proc.exitCode ?? 1 };\n } finally {\n live.delete(tracked);\n }\n};\n\n/** Runs a file-system Effect on the host's file system. */\nconst runOnHost = async <A, E>(\n effect: Effect.Effect<A, E, FileSystem.FileSystem>,\n): Promise<A> =>\n effect.pipe(Effect.provide(NodeFileSystem.layer), Effect.runPromise);\n\n/** Creates the sandbox's private dirs and the bwrap arguments every exec shares. */\nconst prepare = async (\n options: BindMountCreateOptions,\n userMounts: readonly IdentityMount[],\n): Promise<{ dirs: PrivateDirs; baseArgs: string[] }> =>\n Effect.gen(function* () {\n const dirs = yield* makePrivateDirs;\n const baseArgs = yield* sandboxArgs(options, dirs, userMounts);\n return { dirs, baseArgs };\n }).pipe(runOnHost);\n\nconst createHandle = async (\n options: BindMountCreateOptions,\n config: { maxTailChars: number; userMounts: readonly IdentityMount[] },\n): Promise<BindMountSandboxHandle> => {\n const { maxTailChars, userMounts } = config;\n const { dirs, baseArgs } = await prepare(options, userMounts);\n const live = new Set<SandboxProcess>();\n const killAll = (): void => {\n for (const sandbox of live) {\n killSandboxProcess(sandbox);\n }\n };\n const unregisterShutdown = registerNativeSandboxShutdown(killAll, dirs);\n let closed = false;\n const hostPathOf = (p: string): string => toHostPath(p, dirs, options.mounts);\n\n return {\n worktreePath: options.worktreePath,\n exec: async (command, opts) => {\n if (opts?.sudo === true) {\n throw new Error(\n \"bwrap() has no root: exec with sudo: true isn't supported in a native sandbox. \" +\n \"Use docker() for setup that needs root.\",\n );\n }\n if (closed) {\n throw new Error(\"bwrap() sandbox is closed\");\n }\n const cwd = opts?.cwd ?? options.worktreePath;\n const args = [...baseArgs, \"--chdir\", cwd, ...watchedCommand(command)];\n return runInBwrap(args, opts, { live, maxTailChars });\n },\n copyFileIn: async (hostPath, sandboxFile) =>\n copyCreatingParents(hostPath, hostPathOf(sandboxFile)).pipe(runOnHost),\n copyFileOut: async (sandboxFile, hostPath) =>\n copyCreatingParents(hostPathOf(sandboxFile), hostPath).pipe(runOnHost),\n close: async () => {\n closed = true;\n const running = [...live];\n const exits = running.map(async ({ proc }) => once(proc, \"close\"));\n // Wait for each sandbox's PID 1, so a just-started exec is killed too.\n await Promise.all(running.map(async ({ reported }) => reported));\n killAll();\n await Promise.allSettled(exits);\n unregisterShutdown();\n await removePrivateDirs(dirs).pipe(runOnHost);\n },\n };\n};\n\n/**\n * Create a Bubblewrap sandbox provider (Linux and WSL2).\n *\n * The agent runs the host's own toolchain, read-only, and can write only the\n * worktree, the git dirs Sandcastle mounts, a private `/tmp` and a private\n * home at `/home/agent`. Both private dirs are removed on close, and so is\n * every process the sandbox started. The toolchain comes from the host\n * `PATH`: each `PATH` dir (never the home dir or an ancestor of it) and the\n * install root of each executable symlinked from one. Add other paths with\n * `mounts`. It has no root: `exec` with\n * `sudo: true` rejects. All three branch strategies are supported.\n *\n * Checks once per process that Bubblewrap is usable, and throws\n * `NativeSandboxUnavailableError` (with a `fixCommand` when there is\n * one) if it isn't: on a non-Linux OS, when `bwrap` isn't on `PATH`, or when\n * the kernel blocks unprivileged user namespaces. It never falls back to\n * running unsandboxed.\n */\nexport const bwrap = (options?: BwrapOptions): BindMountSandboxProvider => {\n // Reject a sandboxPath/hostPath mismatch before the preflight, so the\n // config error surfaces on every OS.\n const userMounts = bwrapMounts(options?.mounts ?? []);\n assertBwrapUsable();\n const maxTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n return markNativeSandboxProvider(\n createBindMountSandboxProvider({\n name: \"bwrap\",\n env: options?.env ?? {},\n sandboxHomedir: SANDBOX_HOME,\n create: async (createOptions) =>\n createHandle(createOptions, { maxTailChars, userMounts }),\n }),\n );\n};\n"]}
@@ -1,4 +1,4 @@
1
- import { I as IsolatedSandboxProvider } from '../SandboxProvider-EkSMuBp8.js';
1
+ import { I as IsolatedSandboxProvider } from '../SandboxProvider-YCL97qco.js';
2
2
  import { CreateSandboxFromImageParams, CreateSandboxFromSnapshotParams } from '@daytona/sdk';
3
3
 
4
4
  /**
@@ -1,44 +1,69 @@
1
1
  import { createRequire } from 'node:module';
2
- import { createIsolatedSandboxProvider } from '../chunk-BIWNFKGV.js';
3
- import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-NGBM7T3E.js';
2
+ import { createIsolatedSandboxProvider } from '../chunk-XCYK7I45.js';
3
+ import { MAX_TAIL_CHARS, BoundedTail } from '../chunk-6NQPCXSG.js';
4
4
  import { stat, readdir } from 'fs/promises';
5
- import { relative, join } from 'path';
5
+ import { posix, relative, join } from 'path';
6
6
 
7
7
  createRequire(import.meta.url);
8
+ var shellEscape = (s) => `'${s.replaceAll("'", String.raw`'\''`)}'`;
9
+ var SESSION_WATCH_INTERVAL_MS = 15e3;
10
+ var toDaytonaConfig = (options) => {
11
+ const { apiKey, apiUrl, target } = options ?? {};
12
+ const config = {};
13
+ if (apiKey !== void 0 && apiKey !== "") {
14
+ config.apiKey = apiKey;
15
+ }
16
+ if (apiUrl !== void 0 && apiUrl !== "") {
17
+ config.apiUrl = apiUrl;
18
+ }
19
+ if (target !== void 0 && target !== "") {
20
+ config.target = target;
21
+ }
22
+ return config;
23
+ };
8
24
  var daytona = (options) => createIsolatedSandboxProvider({
9
25
  name: "daytona",
10
26
  env: options?.env,
11
- create: async () => {
27
+ create: async (createOptions) => {
12
28
  const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;
13
29
  const { Daytona } = await import('@daytona/sdk');
14
- const config = {};
15
- if (options?.apiKey) config.apiKey = options.apiKey;
16
- if (options?.apiUrl) config.apiUrl = options.apiUrl;
17
- if (options?.target) config.target = options.target;
18
- const client = new Daytona(config);
19
- const sandbox = await client.create(options?.create);
20
- const worktreePath = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir() ?? "/home/daytona";
30
+ const client = new Daytona(toDaytonaConfig(options));
31
+ const createParams = options?.create;
32
+ const envVars = { ...createOptions.env, ...createParams?.envVars };
33
+ const sandbox = createParams !== void 0 && "image" in createParams ? await client.create({ ...createParams, envVars }) : await client.create({ ...createParams, envVars });
34
+ const workDir = await sandbox.getWorkDir() ?? await sandbox.getUserHomeDir() ?? "/home/daytona";
35
+ const worktreePath = posix.join(workDir, "workspace");
36
+ await sandbox.fs.createFolder(worktreePath, "755");
21
37
  return {
22
38
  worktreePath,
39
+ sandboxId: sandbox.id,
23
40
  exec: async (command, opts) => {
24
- const effectiveCommand = opts?.sudo ? `sudo ${command}` : command;
41
+ let effectiveCommand = opts?.sudo === true ? `sudo sh -c ${shellEscape(command)}` : command;
42
+ if (opts?.stdin !== void 0) {
43
+ const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;
44
+ await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);
45
+ effectiveCommand = `{ rm -f ${stdinPath}; ${effectiveCommand}
46
+ } < ${stdinPath}`;
47
+ }
25
48
  if (opts?.onLine) {
26
- const onLine = opts.onLine;
49
+ const { onLine } = opts;
27
50
  const sessionId = `sandcastle-${crypto.randomUUID()}`;
51
+ const pidPath = `/tmp/${sessionId}.pid`;
28
52
  await sandbox.process.createSession(sessionId);
29
53
  try {
30
54
  const execResponse = await sandbox.process.executeSessionCommand(
31
55
  sessionId,
32
56
  {
33
- command: `cd ${opts?.cwd ?? worktreePath} && ${effectiveCommand}`,
57
+ command: `echo $$ > ${pidPath}; ( cd ${opts?.cwd ?? worktreePath} && ${effectiveCommand}
58
+ )`,
34
59
  async: true
35
60
  }
36
61
  );
37
- const cmdId = execResponse.cmdId;
62
+ const { cmdId } = execResponse;
38
63
  const stdoutTail = new BoundedTail(maxOutputTailChars, "\n");
39
64
  const stderrTail = new BoundedTail(maxOutputTailChars, "");
40
65
  let partial = "";
41
- await sandbox.process.getSessionCommandLogs(
66
+ const logsDone = sandbox.process.getSessionCommandLogs(
42
67
  sessionId,
43
68
  cmdId,
44
69
  (chunk) => {
@@ -54,6 +79,40 @@ var daytona = (options) => createIsolatedSandboxProvider({
54
79
  stderrTail.push(chunk);
55
80
  }
56
81
  );
82
+ logsDone.catch(() => {
83
+ });
84
+ let watchTimer;
85
+ let watching = true;
86
+ const sessionGone = new Promise((resolve, reject) => {
87
+ const check = async () => {
88
+ const alive = await sandbox.process.executeCommand(
89
+ `test ! -f ${pidPath} || kill -0 "$(cat ${pidPath})"`
90
+ ).then((r) => r.exitCode === 0).catch(() => true);
91
+ const cmd = alive ? void 0 : await sandbox.process.getSessionCommand(sessionId, cmdId).catch(() => void 0);
92
+ if (!watching) {
93
+ return;
94
+ }
95
+ if (alive) {
96
+ watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);
97
+ return;
98
+ }
99
+ if (typeof cmd?.exitCode === "number") {
100
+ return resolve();
101
+ }
102
+ reject(
103
+ new Error(
104
+ `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`
105
+ )
106
+ );
107
+ };
108
+ watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);
109
+ });
110
+ try {
111
+ await Promise.race([logsDone, sessionGone]);
112
+ } finally {
113
+ watching = false;
114
+ clearTimeout(watchTimer);
115
+ }
57
116
  if (partial) {
58
117
  stdoutTail.push(partial);
59
118
  onLine(partial);
@@ -70,6 +129,8 @@ var daytona = (options) => createIsolatedSandboxProvider({
70
129
  } finally {
71
130
  await sandbox.process.deleteSession(sessionId).catch(() => {
72
131
  });
132
+ await sandbox.process.executeCommand(`rm -f ${pidPath}`).catch(() => {
133
+ });
73
134
  }
74
135
  }
75
136
  const response = await sandbox.process.executeCommand(
@@ -78,7 +139,7 @@ var daytona = (options) => createIsolatedSandboxProvider({
78
139
  );
79
140
  return {
80
141
  stdout: response.result,
81
- stderr: "",
142
+ stderr: response.exitCode === 0 ? "" : response.result,
82
143
  exitC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AA,CAAK,IAAI,CAAE,CAAA;AAAA,cAClC,CAAA,MAAO;AACL,gBAAAA,MAAAA,CAAM,KAAK,IAAI,CAAA;AAAA,cACjB;AAAA,YACF;AACA,YAAA,OAAOA,MAAAA;AAAA,UACT,CAAA;AACA,UAAA,MAAM,KAAA,GAAQ,MAAM,IAAA,CAAK,QAAQ,CAAA;AACjC,UAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,YAAA,MAAM,GAAA,GAAM,QAAA,CAAS,QAAA,EAAU,IAAI,CAAA;AACnC,YAAA,MAAM,QAAQ,EAAA,CAAG,UAAA,CAAW,MAAM,IAAA,CAAK,WAAA,EAAa,GAAG,CAAC,CAAA;AAAA,UAC1D;AAAA,QACF,CAAA,MAAO;AACL,UAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,UAAA,CAAW,QAAA,EAAU,WAAW,CAAA;AAAA,QACnD;AAAA,MACF,CAAA;AAAA,MAEA,WAAA,EAAa,OACX,WAAA,EACA,QAAA,KACkB;AAClB,QAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,MACrD,CAAA;AAAA,MAEA,OAAO,YAA2B;AAChC,QAAA,MAAM,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AACF,CAAC","file":"daytona.js","sourcesContent":["/**\n * Daytona isolated sandbox provider.\n *\n * Creates ephemeral Daytona sandboxes via `@daytona/sdk`.\n * Requires `@daytona/sdk` as a peer dependency.\n */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport {\n createIsolatedSandboxProvider,\n type ExecResult,\n type IsolatedSandboxHandle,\n type IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\nimport type {\n Daytona as DaytonaClient,\n DaytonaConfig,\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n} from \"@daytona/sdk\";\n\n/** Options for the Daytona sandbox provider. */\nexport interface DaytonaOptions {\n /**\n * Daytona API key for authentication.\n * Falls back to the `DAYTONA_API_KEY` environment variable if not provided.\n */\n readonly apiKey?: string;\n\n /**\n * Daytona API URL.\n * Falls back to the `DAYTONA_API_URL` environment variable if not provided.\n */\n readonly apiUrl?: string;\n\n /**\n * Target environment for sandboxes.\n * Falls back to the `DAYTONA_TARGET` environment variable if not provided.\n */\n readonly target?: string;\n\n /**\n * Options passed through to the Daytona SDK when creating a sandbox.\n * Supports both image-based and snapshot-based creation.\n */\n readonly create?:\n | CreateSandboxFromImageParams\n | CreateSandboxFromSnapshotParams;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/**\n * Create a Daytona isolated sandbox provider.\n *\n * Sandboxes are ephemeral — each `create()` call spins up a new Daytona\n * sandbox and `close()` destroys it.\n *\n * @example\n * ```ts\n * import { daytona } from \"@ai-hero/sandcastle/sandboxes/daytona\";\n *\n * const provider = daytona({ apiKey: \"dyt_my_key\" });\n * ```\n */\nexport const daytona = (options?: DaytonaOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"daytona\",\n env: options?.env,\n create: async (): Promise<IsolatedSandboxHandle> => {\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const { Daytona } =\n (await import(\"@daytona/sdk\")) as typeof import(\"@daytona/sdk\");\n\n const config: DaytonaConfig = {};\n if (options?.apiKey) config.apiKey = options.apiKey;\n if (options?.apiUrl) config.apiUrl = options.apiUrl;\n if (options?.target) config.target = options.target;\n\n const client: DaytonaClient = new Daytona(config);\n const sandbox = await client.create(options?.create as any);\n\n const worktreePath =\n (await sandbox.getWorkDir()) ??\n (await sandbox.getUserHomeDir()) ??\n \"/home/daytona\";\n\n return {\n worktreePath,\n\n exec: async (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n },\n ): Promise<ExecResult> => {\n const effectiveCommand = opts?.sudo ? `sudo ${command}` : command;\n if (opts?.onLine) {\n const onLine = opts.onLine;\n const sessionId = `sandcastle-${crypto.randomUUID()}`;\n await sandbox.process.createSession(sessionId);\n\n try {\n const execResponse = await sandbox.process.executeSessionCommand(\n sessionId,\n {\n command: `cd ${opts?.cwd ?? worktreePath} && ${effectiveCommand}`,\n async: true,\n },\n );\n\n const cmdId = execResponse.cmdId!;\n\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n let partial = \"\";\n\n await sandbox.process.getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => {\n const text = partial + chunk;\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n },\n (chunk: string) => {\n stderrTail.push(chunk);\n },\n );\n\n if (partial) {\n stdoutTail.push(partial);\n onLine(partial);\n }\n\n const cmdInfo = await sandbox.process.getSessionCommand(\n sessionId,\n cmdId,\n );\n\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: cmdInfo.exitCode ?? 0,\n };\n } finally {\n await sandbox.process.deleteSession(sessionId).catch(() => {});\n }\n }\n\n const response = await sandbox.process.executeCommand(\n effectiveCommand,\n opts?.cwd ?? worktreePath,\n );\n return {\n stdout: response.result,\n stderr: \"\",\n exitCode: response.exitCode,\n };\n },\n\n copyIn: async (\n hostPath: string,\n sandboxPath: string,\n ): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n const walk = async (dir: string): Promise<string[]> => {\n const entries = await readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...(await walk(full)));\n } else {\n files.push(full);\n }\n }\n return files;\n };\n const files = await walk(hostPath);\n for (const file of files) {\n const rel = relative(hostPath, file);\n await sandbox.fs.uploadFile(file, join(sandboxPath, rel));\n }\n } else {\n await sandbox.fs.uploadFile(hostPath, sandboxPath);\n }\n },\n\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> => {\n await sandbox.fs.downloadFile(sandboxPath, hostPath);\n },\n\n close: async (): Promise<void> => {\n await client.delete(sandbox);\n },\n };\n },\n });\n"]}
1
+ {"version":3,"sources":["../../src/sandboxes/daytona.ts"],"names":["files"],"mappings":";;;;;;;AAwBA,IAAM,WAAA,GAAc,CAAC,CAAA,KACnB,CAAA,CAAA,EAAI,EAAE,UAAA,CAAW,GAAA,EAAK,MAAA,CAAO,GAAA,CAAA,IAAA,CAAS,CAAC,CAAA,CAAA,CAAA;AA6CzC,IAAM,yBAAA,GAA4B,IAAA;AAGlC,IAAM,eAAA,GAAkB,CAAC,OAAA,KAA4C;AACnE,EAAA,MAAM,EAAE,MAAA,EAAQ,MAAA,EAAQ,MAAA,EAAO,GAAI,WAAW,EAAC;AAC/C,EAAA,MAAM,SAAwB,EAAC;AAC/B,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,EAAA,EAAI;AACzC,IAAA,MAAA,CAAO,MAAA,GAAS,MAAA;AAAA,EAClB;AACA,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,EAAA,EAAI;AACzC,IAAA,MAAA,CAAO,MAAA,GAAS,MAAA;AAAA,EAClB;AACA,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,EAAA,EAAI;AACzC,IAAA,MAAA,CAAO,MAAA,GAAS,MAAA;AAAA,EAClB;AACA,EAAA,OAAO,MAAA;AACT,C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AG,CAAC,CAAA;AAAA,UAC1D;AAAA,QACF,CAAA,MAAO;AACL,UAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,UAAA,CAAW,QAAA,EAAU,WAAW,CAAA;AAAA,QACnD;AAAA,MACF,CAAA;AAAA,MAEA,WAAA,EAAa,OACX,WAAA,EACA,QAAA,KACkB;AAClB,QAAA,MAAM,OAAA,CAAQ,EAAA,CAAG,YAAA,CAAa,WAAA,EAAa,QAAQ,CAAA;AAAA,MACrD,CAAA;AAAA,MAEA,OAAO,YAA2B;AAChC,QAAA,MAAM,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,MAC7B;AAAA,KACF;AAAA,EACF;AACF,CAAC","file":"daytona.js","sourcesContent":["/**\n * Daytona isolated sandbox provider.\n *\n * Creates ephemeral Daytona sandboxes via `@daytona/sdk`.\n * Requires `@daytona/sdk` as a peer dependency.\n */\n\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, posix, relative } from \"node:path\";\nimport { createIsolatedSandboxProvider } from \"../SandboxProvider.js\";\nimport type {\n ExecResult,\n IsolatedSandboxHandle,\n IsolatedSandboxProvider,\n} from \"../SandboxProvider.js\";\nimport { BoundedTail, MAX_TAIL_CHARS } from \"../boundedTail.js\";\n\nimport type {\n Daytona as DaytonaClient,\n DaytonaConfig,\n CreateSandboxFromImageParams,\n CreateSandboxFromSnapshotParams,\n} from \"@daytona/sdk\";\n\nconst shellEscape = (s: string): string =>\n `'${s.replaceAll(\"'\", String.raw`'\\''`)}'`;\n\n/** Options for the Daytona sandbox provider. */\nexport interface DaytonaOptions {\n /**\n * Daytona API key for authentication.\n * Falls back to the `DAYTONA_API_KEY` environment variable if not provided.\n */\n readonly apiKey?: string;\n\n /**\n * Daytona API URL.\n * Falls back to the `DAYTONA_API_URL` environment variable if not provided.\n */\n readonly apiUrl?: string;\n\n /**\n * Target environment for sandboxes.\n * Falls back to the `DAYTONA_TARGET` environment variable if not provided.\n */\n readonly target?: string;\n\n /**\n * Options passed through to the Daytona SDK when creating a sandbox.\n * Supports both image-based and snapshot-based creation.\n */\n readonly create?:\n | CreateSandboxFromImageParams\n | CreateSandboxFromSnapshotParams;\n\n /** Environment variables injected by this provider. Merged at launch time with env resolver and agent provider env. */\n readonly env?: Record<string, string>;\n\n /**\n * Maximum number of characters of streamed `exec` output retained per stream\n * (stdout and stderr) when an `onLine` callback is supplied (default: 64KiB).\n *\n * Output is delivered live to `onLine` regardless; this only bounds the tail\n * returned in `ExecResult`, preventing a long-running agent's output from\n * overflowing V8's max string length and crashing the run.\n */\n readonly maxOutputTailChars?: number;\n}\n\n/** How often a streamed `exec` checks that its session shell is still alive. */\nconst SESSION_WATCH_INTERVAL_MS = 15_000;\n\n/** The Daytona client config: only the connection options that are set. */\nconst toDaytonaConfig = (options?: DaytonaOptions): DaytonaConfig => {\n const { apiKey, apiUrl, target } = options ?? {};\n const config: DaytonaConfig = {};\n if (apiKey !== undefined && apiKey !== \"\") {\n config.apiKey = apiKey;\n }\n if (apiUrl !== undefined && apiUrl !== \"\") {\n config.apiUrl = apiUrl;\n }\n if (target !== undefined && target !== \"\") {\n config.target = target;\n }\n return config;\n};\n\n/**\n * Create a Daytona isolated sandbox provider.\n *\n * Sandboxes are ephemeral — each `create()` call spins up a new Daytona\n * sandbox and `close()` destroys it.\n *\n * @example\n * ```ts\n * import { daytona } from \"@ai-hero/sandcastle/sandboxes/daytona\";\n *\n * const provider = daytona({ apiKey: \"dyt_my_key\" });\n * ```\n */\nexport const daytona = (options?: DaytonaOptions): IsolatedSandboxProvider =>\n createIsolatedSandboxProvider({\n name: \"daytona\",\n env: options?.env,\n create: async (createOptions): Promise<IsolatedSandboxHandle> => {\n const maxOutputTailChars = options?.maxOutputTailChars ?? MAX_TAIL_CHARS;\n const { Daytona } = (await import(\n \"@daytona/sdk\"\n )) as typeof import(\"@daytona/sdk\");\n\n const client: DaytonaClient = new Daytona(toDaytonaConfig(options));\n // Pass the resolved env (env resolver + provider + agent) to the\n // sandbox. Explicit `create.envVars` win, as the most specific source.\n const createParams = options?.create;\n const envVars = { ...createOptions.env, ...createParams?.envVars };\n // `client.create` is overloaded per params shape, so call the overload\n // that matches instead of passing the union.\n const sandbox =\n createParams !== undefined && \"image\" in createParams\n ? await client.create({ ...createParams, envVars })\n : await client.create({ ...createParams, envVars });\n\n const workDir =\n (await sandbox.getWorkDir()) ??\n (await sandbox.getUserHomeDir()) ??\n \"/home/daytona\";\n\n // Use a subdirectory of the work dir, not the work dir itself: sync-in\n // clones into `${worktreePath}_clone` and then replaces worktreePath,\n // which needs a parent the sandbox user can write. On the default\n // snapshot the work dir is the user's home (/home/daytona), and /home\n // is root-owned.\n const worktreePath = posix.join(workDir, \"workspace\");\n await sandbox.fs.createFolder(worktreePath, \"755\");\n\n return {\n worktreePath,\n sandboxId: sandbox.id,\n\n exec: async (\n command: string,\n opts?: {\n onLine?: (line: string) => void;\n cwd?: string;\n sudo?: boolean;\n stdin?: string;\n },\n ): Promise<ExecResult> => {\n // Wrap the whole command in `sh -c`, so sudo elevates all of it\n // (`a && b`, not just `a`).\n let effectiveCommand =\n opts?.sudo === true\n ? `sudo sh -c ${shellEscape(command)}`\n : command;\n if (opts?.stdin !== undefined) {\n // Daytona's exec APIs have no stdin channel: the command reads\n // EOF. So write stdin to a file in the sandbox and redirect it in\n // (a file, not an argument, keeps clear of the per-arg size\n // limit). The redirect opens the file before the group runs, so\n // the group can delete it straight away and leave nothing behind.\n const stdinPath = `/tmp/sandcastle-stdin-${crypto.randomUUID()}`;\n await sandbox.fs.uploadFile(Buffer.from(opts.stdin), stdinPath);\n effectiveCommand = `{ rm -f ${stdinPath}; ${effectiveCommand}\\n} < ${stdinPath}`;\n }\n if (opts?.onLine) {\n const { onLine } = opts;\n const sessionId = `sandcastle-${crypto.randomUUID()}`;\n const pidPath = `/tmp/${sessionId}.pid`;\n await sandbox.process.createSession(sessionId);\n\n try {\n // A session runs its commands in one long-lived shell, which\n // records each command's exit code once it returns. A command\n // that ends that shell (a top-level `exit`) never gets one, and\n // its log stream never closes. So run the command in a subshell,\n // where `exit` ends only the subshell. The newline before `)`\n // keeps a trailing comment from swallowing it. The session\n // shell's PID goes to a file, to check it is still alive.\n const execResponse = await sandbox.process.executeSessionCommand(\n sessionId,\n {\n command: `echo $$ > ${pidPath}; ( cd ${opts?.cwd ?? worktreePath} && ${effectiveCommand}\\n)`,\n async: true,\n },\n );\n\n const { cmdId } = execResponse;\n\n const stdoutTail = new BoundedTail(maxOutputTailChars, \"\\n\");\n const stderrTail = new BoundedTail(maxOutputTailChars, \"\");\n let partial = \"\";\n\n const logsDone = sandbox.process.getSessionCommandLogs(\n sessionId,\n cmdId,\n (chunk: string) => {\n const text = partial + chunk;\n const lines = text.split(\"\\n\");\n partial = lines.pop() ?? \"\";\n for (const line of lines) {\n stdoutTail.push(line);\n onLine(line);\n }\n },\n (chunk: string) => {\n stderrTail.push(chunk);\n },\n );\n\n // Once the race below is lost, a late failure of the stream\n // must not surface as an unhandled rejection.\n logsDone.catch(() => {});\n\n // If the session shell dies anyway (killed, say), the stream\n // would wait forever. Watch the shell, and once it is gone stop\n // waiting: fail if the command recorded no exit code. A missing\n // PID file counts as alive, so it can never fail a command.\n let watchTimer: ReturnType<typeof setTimeout> | undefined;\n let watching = true;\n const sessionGone = new Promise<void>((resolve, reject) => {\n const check = async () => {\n const alive = await sandbox.process\n .executeCommand(\n `test ! -f ${pidPath} || kill -0 \"$(cat ${pidPath})\"`,\n )\n .then((r) => r.exitCode === 0)\n .catch(() => true);\n const cmd = alive\n ? undefined\n : await sandbox.process\n .getSessionCommand(sessionId, cmdId)\n .catch(() => undefined);\n if (!watching) {\n return;\n }\n if (alive) {\n watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);\n return;\n }\n if (typeof cmd?.exitCode === \"number\") {\n return resolve();\n }\n reject(\n new Error(\n `Daytona session shell exited before the command finished, so its exit code is unknown: ${command}`,\n ),\n );\n };\n watchTimer = setTimeout(check, SESSION_WATCH_INTERVAL_MS);\n });\n\n try {\n await Promise.race([logsDone, sessionGone]);\n } finally {\n watching = false;\n clearTimeout(watchTimer);\n }\n\n if (partial) {\n stdoutTail.push(partial);\n onLine(partial);\n }\n\n const cmdInfo = await sandbox.process.getSessionCommand(\n sessionId,\n cmdId,\n );\n\n return {\n stdout: stdoutTail.toString(),\n stderr: stderrTail.toString(),\n exitCode: cmdInfo.exitCode ?? 0,\n };\n } finally {\n await sandbox.process.deleteSession(sessionId).catch(() => {});\n await sandbox.process\n .executeCommand(`rm -f ${pidPath}`)\n .catch(() => {});\n }\n }\n\n const response = await sandbox.process.executeCommand(\n effectiveCommand,\n opts?.cwd ?? worktreePath,\n );\n // `executeCommand` merges stdout and stderr into `result` and has\n // no separate stderr. On failure, surface that output as stderr\n // too, so the error says why the command failed, not just its exit\n // code.\n return {\n stdout: response.result,\n stderr: response.exitCode === 0 ? \"\" : response.result,\n exitCode: response.exitCode,\n };\n },\n\n copyIn: async (\n hostPath: string,\n sandboxPath: string,\n ): Promise<void> => {\n const info = await stat(hostPath);\n if (info.isDirectory()) {\n const walk = async (dir: string): Promise<string[]> => {\n const entries = await readdir(dir, { withFileTypes: true });\n const files: string[] = [];\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...(await walk(full)));\n } else {\n files.push(full);\n }\n }\n return files;\n };\n const files = await walk(hostPath);\n for (const file of files) {\n const rel = relative(hostPath, file);\n await sandbox.fs.uploadFile(file, join(sandboxPath, rel));\n }\n } else {\n await sandbox.fs.uploadFile(hostPath, sandboxPath);\n }\n },\n\n copyFileOut: async (\n sandboxPath: string,\n hostPath: string,\n ): Promise<void> => {\n await sandbox.fs.downloadFile(sandboxPath, hostPath);\n },\n\n close: async (): Promise<void> => {\n await client.delete(sandbox);\n },\n };\n },\n });\n"]}