operon-sandbox 0.1.0-alpha.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.
@@ -0,0 +1,69 @@
1
+ import type { DirEntry, Environment, Machine, ByteRange, RunCommandOptions, RunCommandResult } from "operon-agents-core";
2
+ import type { E2BSandbox, SandboxRef } from "./e2b-api.ts";
3
+ import { SandboxMachine } from "../shared/sandbox-machine.ts";
4
+ export interface E2BMachineOptions {
5
+ readonly cwd?: string;
6
+ /** Runs commands and file ops as this user (E2B `user` option). */
7
+ readonly runAs?: string;
8
+ readonly shellPath?: string;
9
+ /** Applied when `RunCommandOptions.timeoutMs` is absent. */
10
+ readonly defaultTimeoutMs?: number;
11
+ }
12
+ /**
13
+ * A `Machine` backed directly by the E2B SDK.
14
+ *
15
+ * Direct on purpose: E2B natively provides exactly what tool execution needs — `timeoutMs`,
16
+ * incremental `onStdout`/`onStderr`, and a real `commands.kill(pid)`. Routing through a
17
+ * general-purpose sandbox abstraction loses all three (its non-PTY path passes no callbacks
18
+ * and exposes no kill), which is what forces other adapters to fabricate a fake process
19
+ * whose timeout and output cap silently do nothing.
20
+ *
21
+ * Known backend limits, surfaced rather than papered over:
22
+ * - `files.list()` reports only `file`/`dir` — a symlink arrives as its target's kind or
23
+ * with `type` absent, so `DirEntry.kind` cannot be true lstat semantics here (see `listDir`).
24
+ * - There is no stat API, so `fileInfo` costs one `stat(1)` command.
25
+ */
26
+ export declare class E2BMachine extends SandboxMachine {
27
+ readonly name = "e2b";
28
+ readonly osEnv: Environment;
29
+ private readonly sandboxRef;
30
+ private readonly cwd;
31
+ private readonly runAs;
32
+ private readonly defaultTimeoutMs;
33
+ constructor(sandbox: SandboxRef | E2BSandbox, options?: E2BMachineOptions);
34
+ private get sandbox();
35
+ pathClass(): "posix";
36
+ normpath(path: string): string;
37
+ gethome(): string;
38
+ getcwd(): string;
39
+ withCwd(cwd: string): Machine;
40
+ /**
41
+ * The whole reason this adapter exists: every intent maps to a native E2B feature.
42
+ * `background: true` is what yields a pid, and a pid is what makes cancellation real.
43
+ */
44
+ run(argv: readonly string[], options?: RunCommandOptions): Promise<RunCommandResult>;
45
+ /** Real termination, reported honestly: `false` means the command may still be running. */
46
+ private killPid;
47
+ /**
48
+ * One `files.list()` round trip — the vendor listing already carries `type`, so there is no
49
+ * stat per entry.
50
+ *
51
+ * Caveat worth knowing: E2B's `FileType` has only `file` and `dir`. A symlink comes back as
52
+ * whatever it resolves to, or with `type` absent (mapped to `"other"`). So on this backend
53
+ * `DirEntry.kind` is NOT strict lstat semantics — callers that must distinguish a symlink
54
+ * have to stat explicitly. Reported as-is rather than guessed.
55
+ */
56
+ listDir(path: string): Promise<readonly DirEntry[]>;
57
+ mkdir(path: string, options?: {
58
+ parents?: boolean;
59
+ existOk?: boolean;
60
+ }): Promise<void>;
61
+ readBytes(path: string, range?: ByteRange): Promise<Buffer>;
62
+ protected writeBytesRaw(path: string, data: Buffer): Promise<void>;
63
+ /** Public URL for a port listening inside the sandbox (dev servers, previews). */
64
+ exposedPortUrl(port: number, scheme?: "http" | "https"): Promise<string | undefined>;
65
+ protected resolve(path: string): string;
66
+ }
67
+ /** E2B takes a command STRING; quote every argv element so no arg is re-split by the shell. */
68
+ export declare function shellJoin(argv: readonly string[]): string;
69
+ //# sourceMappingURL=machine.d.ts.map
@@ -0,0 +1,281 @@
1
+ import { posix } from "node:path";
2
+ import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
3
+ import { SandboxMachine } from "../shared/sandbox-machine.js";
4
+ const DEFAULT_CWD = "/home/user";
5
+ /**
6
+ * A `Machine` backed directly by the E2B SDK.
7
+ *
8
+ * Direct on purpose: E2B natively provides exactly what tool execution needs — `timeoutMs`,
9
+ * incremental `onStdout`/`onStderr`, and a real `commands.kill(pid)`. Routing through a
10
+ * general-purpose sandbox abstraction loses all three (its non-PTY path passes no callbacks
11
+ * and exposes no kill), which is what forces other adapters to fabricate a fake process
12
+ * whose timeout and output cap silently do nothing.
13
+ *
14
+ * Known backend limits, surfaced rather than papered over:
15
+ * - `files.list()` reports only `file`/`dir` — a symlink arrives as its target's kind or
16
+ * with `type` absent, so `DirEntry.kind` cannot be true lstat semantics here (see `listDir`).
17
+ * - There is no stat API, so `fileInfo` costs one `stat(1)` command.
18
+ */
19
+ export class E2BMachine extends SandboxMachine {
20
+ name = "e2b";
21
+ osEnv;
22
+ sandboxRef;
23
+ cwd;
24
+ runAs;
25
+ defaultTimeoutMs;
26
+ constructor(sandbox, options = {}) {
27
+ super();
28
+ this.sandboxRef = typeof sandbox === "function" ? sandbox : () => sandbox;
29
+ this.cwd = normalizeAbs(options.cwd ?? DEFAULT_CWD);
30
+ this.runAs = options.runAs;
31
+ this.defaultTimeoutMs = options.defaultTimeoutMs;
32
+ const shellPath = options.shellPath ?? "/bin/bash";
33
+ this.osEnv = {
34
+ osKind: "Linux",
35
+ osArch: "unknown",
36
+ osVersion: "unknown",
37
+ shellName: posix.basename(shellPath),
38
+ shellPath,
39
+ };
40
+ }
41
+ get sandbox() {
42
+ return this.sandboxRef();
43
+ }
44
+ // ---- identity & paths ----
45
+ pathClass() {
46
+ return "posix";
47
+ }
48
+ normpath(path) {
49
+ return posix.normalize(path);
50
+ }
51
+ gethome() {
52
+ return DEFAULT_CWD;
53
+ }
54
+ getcwd() {
55
+ return this.cwd;
56
+ }
57
+ withCwd(cwd) {
58
+ const clone = new E2BMachine(this.sandboxRef, {
59
+ cwd: this.resolve(cwd),
60
+ ...(this.runAs !== undefined ? { runAs: this.runAs } : {}),
61
+ shellPath: this.osEnv.shellPath,
62
+ ...(this.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: this.defaultTimeoutMs } : {}),
63
+ });
64
+ // One sandbox, one file namespace — clones must share write locks.
65
+ clone.pathLocks = this.pathLocks;
66
+ return clone;
67
+ }
68
+ // ---- commands ----
69
+ /**
70
+ * The whole reason this adapter exists: every intent maps to a native E2B feature.
71
+ * `background: true` is what yields a pid, and a pid is what makes cancellation real.
72
+ */
73
+ async run(argv, options = {}) {
74
+ if (options.signal?.aborted) {
75
+ return { stdout: "", stderr: "", exitCode: undefined, timedOut: false, truncated: false, terminated: true };
76
+ }
77
+ const sandbox = this.sandbox;
78
+ const cap = options.maxOutputBytes ?? Number.POSITIVE_INFINITY;
79
+ let out = "";
80
+ let err = "";
81
+ let bytes = 0;
82
+ let truncated = false;
83
+ const collect = (stream) => (data) => {
84
+ options.onOutput?.({ stream, data });
85
+ if (truncated)
86
+ return;
87
+ const room = cap - bytes;
88
+ if (data.length >= room) {
89
+ const kept = data.slice(0, Math.max(0, room));
90
+ if (stream === "stdout")
91
+ out += kept;
92
+ else
93
+ err += kept;
94
+ bytes = cap;
95
+ truncated = true;
96
+ return;
97
+ }
98
+ bytes += data.length;
99
+ if (stream === "stdout")
100
+ out += data;
101
+ else
102
+ err += data;
103
+ };
104
+ // Refuse stdin we cannot deliver instead of dropping it: a hook or a filter fed no input
105
+ // would silently see EOF and "succeed" on empty data.
106
+ if (options.stdin !== undefined && sandbox.commands.sendStdin === undefined) {
107
+ throw new Error("E2BMachine: this SDK build exposes no commands.sendStdin, so run({ stdin }) cannot be honored.");
108
+ }
109
+ const started = await sandbox.commands.run(shellJoin(argv), {
110
+ background: true, // resolves immediately with a pid so cancellation has a target
111
+ cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
112
+ ...(options.env !== undefined ? { envs: options.env } : {}),
113
+ ...(this.runAs !== undefined ? { user: this.runAs } : {}),
114
+ ...(options.stdin !== undefined ? { stdin: true } : {}),
115
+ ...(pickTimeout(options.timeoutMs, this.defaultTimeoutMs) !== undefined
116
+ ? { timeoutMs: pickTimeout(options.timeoutMs, this.defaultTimeoutMs) }
117
+ : {}),
118
+ onStdout: collect("stdout"),
119
+ onStderr: collect("stderr"),
120
+ });
121
+ const handle = started;
122
+ if (options.stdin !== undefined && typeof handle.pid === "number") {
123
+ await sandbox.commands.sendStdin(handle.pid, options.stdin);
124
+ }
125
+ // No pid means the SDK ran it to completion synchronously — nothing to cancel.
126
+ if (typeof handle.pid !== "number" || handle.wait === undefined) {
127
+ const done = started;
128
+ return {
129
+ stdout: out || done.stdout || "",
130
+ stderr: err || done.stderr || "",
131
+ exitCode: done.exitCode ?? undefined,
132
+ timedOut: false,
133
+ truncated,
134
+ terminated: false,
135
+ };
136
+ }
137
+ let timedOut = false;
138
+ let terminated = false;
139
+ let stopping;
140
+ const stop = () => (stopping ??= this.killPid(sandbox, handle).then((ok) => void (terminated = ok)));
141
+ const onAbort = () => void stop();
142
+ options.signal?.addEventListener("abort", onAbort);
143
+ const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => {
144
+ timedOut = true;
145
+ void stop();
146
+ }, options.timeoutMs);
147
+ try {
148
+ const finished = await handle.wait();
149
+ // Cap reached but the command outlived it — stop it rather than let it keep producing.
150
+ if (truncated && !terminated)
151
+ await stop();
152
+ // A kill makes wait() settle immediately, so without joining the in-flight stop here we
153
+ // would read `terminated` before killPid resolved and under-report every termination.
154
+ await stopping;
155
+ return {
156
+ stdout: out || finished.stdout || "",
157
+ stderr: err || finished.stderr || "",
158
+ // A killed command's exit status is not a real completion code.
159
+ exitCode: timedOut || terminated ? undefined : finished.exitCode ?? undefined,
160
+ timedOut,
161
+ truncated,
162
+ terminated,
163
+ };
164
+ }
165
+ finally {
166
+ if (timer !== undefined)
167
+ clearTimeout(timer);
168
+ options.signal?.removeEventListener("abort", onAbort);
169
+ }
170
+ }
171
+ /** Real termination, reported honestly: `false` means the command may still be running. */
172
+ async killPid(sandbox, handle) {
173
+ try {
174
+ if (handle.kill !== undefined)
175
+ return await handle.kill();
176
+ if (sandbox.commands.kill !== undefined)
177
+ return await sandbox.commands.kill(handle.pid);
178
+ }
179
+ catch {
180
+ /* fall through — treat as not terminated */
181
+ }
182
+ return false;
183
+ }
184
+ // No `spawn`: this transport hands back no OS process, so the base class's process SPI stays
185
+ // unimplemented and `run` above — which every caller uses — is native instead. The adapter
186
+ // this replaced faked a process handle whose `kill()` did nothing, and the Bash tool trusted
187
+ // it, so a user's interrupt left the command running inside the sandbox.
188
+ // ---- files & metadata ----
189
+ // `fileInfo` comes from SandboxMachine: E2B exposes no stat API, so it costs one
190
+ // `stat(1)` — the same trade Cloudflare makes, and the reason `listDir` below avoids
191
+ // per-entry metadata.
192
+ /**
193
+ * One `files.list()` round trip — the vendor listing already carries `type`, so there is no
194
+ * stat per entry.
195
+ *
196
+ * Caveat worth knowing: E2B's `FileType` has only `file` and `dir`. A symlink comes back as
197
+ * whatever it resolves to, or with `type` absent (mapped to `"other"`). So on this backend
198
+ * `DirEntry.kind` is NOT strict lstat semantics — callers that must distinguish a symlink
199
+ * have to stat explicitly. Reported as-is rather than guessed.
200
+ */
201
+ async listDir(path) {
202
+ const entries = await this.sandbox.files.list(this.resolve(path));
203
+ return entries.map((entry) => ({
204
+ name: entry.name,
205
+ kind: entry.type === "dir" ? "dir" : entry.type === "file" ? "file" : "other",
206
+ }));
207
+ }
208
+ async mkdir(path, options) {
209
+ const target = this.resolve(path);
210
+ if (options?.parents === true) {
211
+ const { exitCode } = await this.run(["mkdir", "-p", "--", target]);
212
+ if (exitCode !== 0)
213
+ throw codedError(`mkdir -p failed: ${target}`, "EIO");
214
+ return;
215
+ }
216
+ // Plain mkdir must fail on an existing path; `files.makeDir` returns false instead of
217
+ // throwing, so translate that into the EEXIST the contract promises.
218
+ const created = (await this.sandbox.files.makeDir?.(target)) ?? false;
219
+ if (created)
220
+ return;
221
+ if (options?.existOk === true && (await this.fileInfo(target).catch(() => undefined))?.kind === "dir")
222
+ return;
223
+ throw codedError(`EEXIST: path already exists: ${target}`, "EEXIST");
224
+ }
225
+ async readBytes(path, range) {
226
+ if (range !== undefined) {
227
+ const window = await readWindowViaShell(this, this.resolve(path), range);
228
+ if (window !== undefined)
229
+ return window;
230
+ // Fall through: no `tail`/`head`/`base64` in this image. Correct, just expensive — and
231
+ // the caller is told nothing, because the contract only promises the bytes.
232
+ }
233
+ const payload = await this.sandbox.files.read(this.resolve(path), { format: "bytes" });
234
+ const bytes = typeof payload === "string" ? Buffer.from(payload, "utf8") : Buffer.from(payload);
235
+ return sliceRange(bytes, range);
236
+ }
237
+ async writeBytesRaw(path, data) {
238
+ await this.sandbox.files.write(this.resolve(path), toArrayBuffer(data));
239
+ }
240
+ /** Public URL for a port listening inside the sandbox (dev servers, previews). */
241
+ async exposedPortUrl(port, scheme = "https") {
242
+ if (this.sandbox.getHost === undefined)
243
+ return undefined;
244
+ return `${scheme}://${await this.sandbox.getHost(port)}`;
245
+ }
246
+ resolve(path) {
247
+ return normalizeAbs(path.startsWith("/") ? path : posix.join(this.cwd, path));
248
+ }
249
+ }
250
+ function pickTimeout(explicit, fallback) {
251
+ return explicit ?? fallback;
252
+ }
253
+ /**
254
+ * Copy a Buffer's bytes into a standalone ArrayBuffer, which is what the E2B SDK accepts.
255
+ *
256
+ * The slice is not optional. Node pools small Buffers, so `data.buffer` is usually an 8 KiB
257
+ * slab shared with unrelated allocations — handing it over whole would write that slab's
258
+ * contents to the file instead of the caller's bytes.
259
+ */
260
+ function toArrayBuffer(data) {
261
+ return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
262
+ }
263
+ function normalizeAbs(path) {
264
+ const normalized = posix.normalize(path);
265
+ return normalized.startsWith("/") ? normalized : `/${normalized}`;
266
+ }
267
+ /** E2B takes a command STRING; quote every argv element so no arg is re-split by the shell. */
268
+ export function shellJoin(argv) {
269
+ return argv.map(shellQuote).join(" ");
270
+ }
271
+ function shellQuote(value) {
272
+ if (/^[A-Za-z0-9_/@%+=:,.-]+$/.test(value))
273
+ return value;
274
+ return `'${value.replace(/'/g, `'\\''`)}'`;
275
+ }
276
+ function codedError(message, code) {
277
+ const error = new Error(message);
278
+ error.code = code;
279
+ return error;
280
+ }
281
+ //# sourceMappingURL=machine.js.map
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Host-side sandbox lifecycle for operon-agents.
3
+ *
4
+ * Two halves, deliberately split:
5
+ *
6
+ * - **Lifecycle** (`SandboxWorkspace`) — create, snapshot, pause, destroy. Lives HERE, on the
7
+ * host's side of the line, because a sandbox is a user- or workspace-scoped resource that
8
+ * outlives any single agent session.
9
+ * - **Operation** (`Machine`) — commands and file I/O, driven by each vendor's SDK directly,
10
+ * so a per-command timeout, incremental output and a real kill actually take effect.
11
+ *
12
+ * Wire the two together by handing the machine in:
13
+ *
14
+ * const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
15
+ * await materializeWorkspace(workspace.machine, spec);
16
+ * const harness = new Harness({ machine: workspace.machine });
17
+ * // ...and the host calls workspace.pause()/kill() when the USER is done, not when a
18
+ * // session is.
19
+ *
20
+ * Vendor SDKs are optional peers: install `e2b` or `@cloudflare/sandbox` for the ones you use.
21
+ */
22
+ export type { SandboxWorkspace } from "./types.ts";
23
+ export { E2BMachine, shellJoin, type E2BMachineOptions } from "./e2b/machine.ts";
24
+ export { E2BWorkspace, type E2BWorkspaceOptions, type E2BMachineState, type E2BSandboxFactory, } from "./e2b/lifecycle.ts";
25
+ export type { E2BCommandHandle, E2BCommandResult, E2BCommandsApi, E2BEntryInfo, E2BFilesystemApi, E2BFileType, E2BRunOpts, E2BSandbox, SandboxRef, } from "./e2b/e2b-api.ts";
26
+ export { CloudflareMachine, type CloudflareMachineOptions } from "./cloudflare/machine.ts";
27
+ export { CloudflareWorkspace, type CloudflareWorkspaceOptions } from "./cloudflare/lifecycle.ts";
28
+ export type { CloudflareBackupApi, CloudflareClientRef, CloudflareCommandsApi, CloudflareFileEntry, CloudflareFilesApi, CloudflareGitApi, CloudflareLogEvent, CloudflareProcessesApi, CloudflareSandboxClient, } from "./cloudflare/cf-api.ts";
29
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { E2BMachine, shellJoin } from "./e2b/machine.js";
2
+ export { E2BWorkspace, } from "./e2b/lifecycle.js";
3
+ export { CloudflareMachine } from "./cloudflare/machine.js";
4
+ export { CloudflareWorkspace } from "./cloudflare/lifecycle.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,38 @@
1
+ import type { Machine } from "operon-agents-core";
2
+ /**
3
+ * Read a byte WINDOW of a remote file without transferring the rest.
4
+ *
5
+ * Neither vendor's file API takes a byte range, so the window is cut on the far side and
6
+ * only that much comes back. The bytes ride home base64-encoded because `run` hands back
7
+ * `stdout` as a STRING — raw binary through that path would be mangled by UTF-8 decoding,
8
+ * and both callers (a media header sniff, a log follower) are binary reads.
9
+ *
10
+ * `tail -c +N` is 1-indexed, so a 0-based offset becomes `N = offset + 1`; at offset 0 it is
11
+ * a pass-through, which keeps one command shape for every case.
12
+ *
13
+ * `undefined` means the image lacks these coreutils; the caller falls back to a whole-file
14
+ * read. Returning a value it cannot vouch for would be worse than being slow.
15
+ */
16
+ /** Apply a byte range to bytes already in hand — the fallback path's share of the contract. */
17
+ export declare function sliceRange(bytes: Buffer, range?: {
18
+ readonly offset?: number;
19
+ readonly length?: number;
20
+ }): Buffer;
21
+ export declare function readWindowViaShell(machine: Machine, absPath: string, range: {
22
+ readonly offset?: number;
23
+ readonly length?: number;
24
+ }): Promise<Buffer | undefined>;
25
+ /**
26
+ * Put `data` at `absPath` so a concurrent reader sees the old file or the new one, never a
27
+ * half-written one: upload to a sibling temp path, then `mv` over the target. Within one
28
+ * filesystem that rename is indivisible, which is the guarantee the CAS write needs and
29
+ * neither vendor's file API offers on its own.
30
+ *
31
+ * The temp file is a SIBLING, not `/tmp` — a cross-device `mv` degrades to copy-then-unlink
32
+ * and loses exactly the atomicity this exists for.
33
+ *
34
+ * Returns false when the swap could not be completed, leaving the caller to fall back to a
35
+ * plain write; the temp file is cleaned up either way.
36
+ */
37
+ export declare function writeViaTempSwap(machine: Machine, absPath: string, data: Buffer, writeRaw: (path: string, data: Buffer) => Promise<void>, tempSuffix: string): Promise<boolean>;
38
+ //# sourceMappingURL=remote-file-ops.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { posix } from "node:path";
2
+ /**
3
+ * Read a byte WINDOW of a remote file without transferring the rest.
4
+ *
5
+ * Neither vendor's file API takes a byte range, so the window is cut on the far side and
6
+ * only that much comes back. The bytes ride home base64-encoded because `run` hands back
7
+ * `stdout` as a STRING — raw binary through that path would be mangled by UTF-8 decoding,
8
+ * and both callers (a media header sniff, a log follower) are binary reads.
9
+ *
10
+ * `tail -c +N` is 1-indexed, so a 0-based offset becomes `N = offset + 1`; at offset 0 it is
11
+ * a pass-through, which keeps one command shape for every case.
12
+ *
13
+ * `undefined` means the image lacks these coreutils; the caller falls back to a whole-file
14
+ * read. Returning a value it cannot vouch for would be worse than being slow.
15
+ */
16
+ /** Apply a byte range to bytes already in hand — the fallback path's share of the contract. */
17
+ export function sliceRange(bytes, range) {
18
+ if (range === undefined)
19
+ return bytes;
20
+ const offset = Math.max(0, Math.trunc(range.offset ?? 0));
21
+ return range.length === undefined ? bytes.subarray(offset) : bytes.subarray(offset, offset + Math.max(0, Math.trunc(range.length)));
22
+ }
23
+ export async function readWindowViaShell(machine, absPath, range) {
24
+ const offset = Math.max(0, Math.trunc(range.offset ?? 0));
25
+ const length = range.length === undefined ? undefined : Math.max(0, Math.trunc(range.length));
26
+ if (length === 0)
27
+ return Buffer.alloc(0);
28
+ const cut = length === undefined ? "" : ` | head -c ${String(length)}`;
29
+ // The path goes through `$0` rather than string interpolation, so no quoting scheme has to
30
+ // be trusted with a filename containing quotes, spaces or newlines. The numbers are ours.
31
+ const result = await machine
32
+ .run(["sh", "-c", `tail -c +${String(offset + 1)} -- "$0"${cut} | base64`, absPath])
33
+ .catch(() => undefined);
34
+ if (result === undefined || result.exitCode !== 0)
35
+ return undefined;
36
+ // base64(1) wraps its output; strip every kind of whitespace before decoding.
37
+ return Buffer.from(result.stdout.replace(/\s+/g, ""), "base64");
38
+ }
39
+ /**
40
+ * Put `data` at `absPath` so a concurrent reader sees the old file or the new one, never a
41
+ * half-written one: upload to a sibling temp path, then `mv` over the target. Within one
42
+ * filesystem that rename is indivisible, which is the guarantee the CAS write needs and
43
+ * neither vendor's file API offers on its own.
44
+ *
45
+ * The temp file is a SIBLING, not `/tmp` — a cross-device `mv` degrades to copy-then-unlink
46
+ * and loses exactly the atomicity this exists for.
47
+ *
48
+ * Returns false when the swap could not be completed, leaving the caller to fall back to a
49
+ * plain write; the temp file is cleaned up either way.
50
+ */
51
+ export async function writeViaTempSwap(machine, absPath, data, writeRaw, tempSuffix) {
52
+ const temp = `${posix.join(posix.dirname(absPath), `.${posix.basename(absPath)}`)}.${tempSuffix}.tmp`;
53
+ try {
54
+ await writeRaw(temp, data);
55
+ }
56
+ catch {
57
+ return false; // nothing landed; nothing to clean up
58
+ }
59
+ const moved = await machine.run(["mv", "-f", "--", temp, absPath]).catch(() => undefined);
60
+ if (moved?.exitCode === 0)
61
+ return true;
62
+ // `mv` unavailable or refused — drop the temp file rather than leave litter in the workspace.
63
+ await machine.run(["rm", "-f", "--", temp]).catch(() => undefined);
64
+ return false;
65
+ }
66
+ //# sourceMappingURL=remote-file-ops.js.map
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Shared base for the vendor sandbox Machines (E2B, Cloudflare).
3
+ *
4
+ * The two transports differ in almost everything — one has a native process handle, the
5
+ * other an HTTP API; one takes bytes, the other base64 — but they agree on the one shape
6
+ * that matters here: a file API that writes DIRECTLY to the target path, plus a shell to
7
+ * run `mv` in. That combination determines the CAS write identically for both, so it is
8
+ * stated once here instead of twice in the backends.
9
+ */
10
+ import { BaseMachine } from "operon-agents-core";
11
+ import type { FileInfo } from "operon-agents-core";
12
+ export declare abstract class SandboxMachine extends BaseMachine {
13
+ /**
14
+ * Absolutize against the sandbox cwd. Both backends resolve identically; it is abstract
15
+ * only because the cwd is a subclass constructor argument, not because the rule differs.
16
+ */
17
+ protected abstract resolve(path: string): string;
18
+ /** Same file → same lock across path spellings: key on the resolved path. */
19
+ protected lockKeyFor(path: string): string;
20
+ /**
21
+ * Neither vendor exposes a stat API, so this costs one `stat(1)`. `-L` follows the
22
+ * symlink; without it the link itself is described, which is what `DirEntry` wants.
23
+ */
24
+ fileInfo(path: string, options?: {
25
+ followSymlinks?: boolean;
26
+ }): Promise<FileInfo>;
27
+ /**
28
+ * Both vendors' file APIs land on the target directly, so the CAS path swaps through a
29
+ * sibling temp file instead — otherwise a failure mid-upload (a crashed sandbox, a dropped
30
+ * request) leaves a truncated file where the caller was just promised all-or-nothing.
31
+ *
32
+ * Falls back to the direct write when the swap could not be completed — an image without
33
+ * `mv`. Torn state is the lesser risk against not writing at all, and `writeViaTempSwap`
34
+ * has already cleaned up after itself by then.
35
+ */
36
+ protected writeBytesSwap(path: string, data: Buffer): Promise<void>;
37
+ }
38
+ //# sourceMappingURL=sandbox-machine.d.ts.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Shared base for the vendor sandbox Machines (E2B, Cloudflare).
3
+ *
4
+ * The two transports differ in almost everything — one has a native process handle, the
5
+ * other an HTTP API; one takes bytes, the other base64 — but they agree on the one shape
6
+ * that matters here: a file API that writes DIRECTLY to the target path, plus a shell to
7
+ * run `mv` in. That combination determines the CAS write identically for both, so it is
8
+ * stated once here instead of twice in the backends.
9
+ */
10
+ import { BaseMachine } from "operon-agents-core";
11
+ import { writeViaTempSwap } from "./remote-file-ops.js";
12
+ function codedError(message, code) {
13
+ const error = new Error(message);
14
+ error.code = code;
15
+ return error;
16
+ }
17
+ function statKind(raw) {
18
+ if (/directory/.test(raw))
19
+ return "dir";
20
+ if (/regular/.test(raw))
21
+ return "file";
22
+ if (/symbolic link/.test(raw))
23
+ return "symlink";
24
+ return "other";
25
+ }
26
+ /**
27
+ * Seconds-since-epoch from `stat`, at the best precision the image's `stat` offered.
28
+ *
29
+ * `%Y` is whole seconds, and whole seconds are not enough to decide freshness: a linter
30
+ * that rewrites a file in the same second the agent read it leaves the mtime IDENTICAL,
31
+ * so the write sails through the version check and silently discards the linter's work.
32
+ * `%.3Y` adds the millisecond fraction — the precision a local stat gives and the
33
+ * resolution the freshness check is designed around.
34
+ *
35
+ * Not every image's `stat` understands the precision specifier — BusyBox echoes the
36
+ * format string back verbatim. So both fields are requested and the fraction is used
37
+ * only when it parses AND agrees with the whole-second value. A backend that can't
38
+ * offer it degrades to second resolution rather than to a wrong timestamp.
39
+ */
40
+ function parseMtimeSeconds(wholeRaw, fractionalRaw) {
41
+ const whole = Number(wholeRaw);
42
+ if (!Number.isFinite(whole))
43
+ return undefined;
44
+ const fractional = Number(fractionalRaw);
45
+ // Math.floor, not a tolerance: the two fields come from ONE stat call, so a fraction
46
+ // that doesn't floor to its own whole-second field isn't imprecise, it's unparsed.
47
+ if (Number.isFinite(fractional) && Math.floor(fractional) === whole)
48
+ return fractional;
49
+ return whole;
50
+ }
51
+ export class SandboxMachine extends BaseMachine {
52
+ /** Same file → same lock across path spellings: key on the resolved path. */
53
+ lockKeyFor(path) {
54
+ return this.resolve(path);
55
+ }
56
+ /**
57
+ * Neither vendor exposes a stat API, so this costs one `stat(1)`. `-L` follows the
58
+ * symlink; without it the link itself is described, which is what `DirEntry` wants.
59
+ */
60
+ async fileInfo(path, options) {
61
+ const target = this.resolve(path);
62
+ const format = "%F|%s|%Y|%.3Y";
63
+ const argv = (options?.followSymlinks ?? true)
64
+ ? ["stat", "-L", "-c", format, "--", target]
65
+ : ["stat", "-c", format, "--", target];
66
+ const { stdout, exitCode } = await this.run(argv);
67
+ if (exitCode !== 0)
68
+ throw codedError(`No such file or directory: ${target}`, "ENOENT");
69
+ // Last line only: a shell that prepends a banner would otherwise poison the parse.
70
+ const [kindRaw = "", sizeRaw = "", mtimeRaw = "", mtimeFracRaw = ""] = (stdout.trim().split("\n").pop() ?? "").split("|");
71
+ const size = Number(sizeRaw);
72
+ const mtimeSec = parseMtimeSeconds(mtimeRaw, mtimeFracRaw);
73
+ if (!Number.isFinite(size) || mtimeSec === undefined) {
74
+ throw codedError(`Unparsable stat output for ${target}`, "EIO");
75
+ }
76
+ // mtime 0 means "the backend has no clock for this file" — report it as absent
77
+ // rather than as 1970, so the freshness check falls back to content comparison.
78
+ return { kind: statKind(kindRaw), size, ...(mtimeSec === 0 ? {} : { mtimeMs: mtimeSec * 1000 }) };
79
+ }
80
+ /**
81
+ * Both vendors' file APIs land on the target directly, so the CAS path swaps through a
82
+ * sibling temp file instead — otherwise a failure mid-upload (a crashed sandbox, a dropped
83
+ * request) leaves a truncated file where the caller was just promised all-or-nothing.
84
+ *
85
+ * Falls back to the direct write when the swap could not be completed — an image without
86
+ * `mv`. Torn state is the lesser risk against not writing at all, and `writeViaTempSwap`
87
+ * has already cleaned up after itself by then.
88
+ */
89
+ async writeBytesSwap(path, data) {
90
+ const target = this.resolve(path);
91
+ // `name` tags the temp file with the backend that left it, should one ever survive.
92
+ const swapped = await writeViaTempSwap(this, target, data, (p, d) => this.writeBytesRaw(p, d), this.name);
93
+ if (!swapped)
94
+ await this.writeBytesRaw(target, data);
95
+ }
96
+ }
97
+ //# sourceMappingURL=sandbox-machine.js.map
@@ -0,0 +1,39 @@
1
+ import type { Machine } from "operon-agents-core";
2
+ /**
3
+ * A sandbox the HOST owns: created here, disposed of here, and handed to the agent
4
+ * framework only as a {@link Machine}.
5
+ *
6
+ * This layer exists because sandbox lifetime and agent-session lifetime are different
7
+ * things. A sandbox is normally scoped to a user or a workspace and outlives any single
8
+ * session — new, resumed and forked sessions all run inside the same one. Wire it in with
9
+ * `machine: workspace.machine`; the framework then only ever operates the
10
+ * machine, and closing a session cannot take the workspace down with it.
11
+ *
12
+ * Every method states an INTENT and answers honestly about whether the backend could
13
+ * deliver it — `undefined`/`false` rather than a throw or a pretend success. That is why
14
+ * there is no capability-flags object here: a flag is a claim made in advance (and vendors
15
+ * do get it wrong — E2B's own `supportsPty()` is a runtime probe), whereas a return value
16
+ * is what actually happened. Callers write one path and read the result.
17
+ */
18
+ export interface SandboxWorkspace {
19
+ /** The agent-facing handle. Stays valid across {@link restore}, which may swap the sandbox. */
20
+ readonly machine: Machine;
21
+ /** Vendor id of the live sandbox. Changes when `restore` replaces it. */
22
+ readonly id: string;
23
+ /**
24
+ * Capture the workspace for later reuse. `undefined` when this backend/plan has no
25
+ * snapshot mechanism — the caller then knows to fall back rather than assume it worked.
26
+ */
27
+ snapshot(): Promise<string | undefined>;
28
+ /** Replace the workspace's contents with a snapshot. `machine` keeps working across it. */
29
+ restore(snapshotId: string): Promise<void>;
30
+ /**
31
+ * Suspend the sandbox, keeping its filesystem, so reopening is cheaper than a cold start.
32
+ * `false` means the backend cannot suspend and the sandbox is STILL RUNNING — the caller
33
+ * has to decide between paying for it and killing it.
34
+ */
35
+ pause(): Promise<boolean>;
36
+ /** Destroy the sandbox. Terminal: the machine is unusable afterwards. */
37
+ kill(): Promise<void>;
38
+ }
39
+ //# sourceMappingURL=types.d.ts.map