operon-sandbox 0.1.0-alpha.2 → 0.1.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # operon-sandbox
2
2
 
3
3
  Host-side sandbox lifecycle for [operon-agents](https://github.com/nickqiaoo/operon-agents): create,
4
- snapshot, pause and destroy a vendor sandbox, and hand the framework a `Machine` driven by the
4
+ snapshot, pause and destroy a vendor sandbox, and hand the framework an `Environment` driven by the
5
5
  vendor SDK directly — native per-command timeouts, incremental output, and a real kill.
6
6
 
7
7
  Supported vendors: **E2B** and **Cloudflare**.
@@ -11,12 +11,12 @@ import { Sandbox } from "e2b";
11
11
  import { createHarness } from "operon-agents";
12
12
  import { E2BWorkspace } from "operon-sandbox";
13
13
 
14
- // The host owns the sandbox lifecycle; the framework only ever sees a Machine.
14
+ // The host owns the sandbox lifecycle; the framework only ever sees an Environment.
15
15
  const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
16
16
 
17
17
  const harness = createHarness({
18
18
  model,
19
- machine: workspace.machine, // tools now run inside the sandbox
19
+ environment: workspace.environment, // tools now run inside the sandbox
20
20
  });
21
21
 
22
22
  // … run sessions …
@@ -37,7 +37,7 @@ Vendor SDKs are optional peer dependencies — install `e2b` or `@cloudflare/san
37
37
  actually use.
38
38
 
39
39
  Nothing else about the agent changes: sessions, events, permissions and tools are identical to a
40
- local run. That is the point of the `Machine` seam — where a command executes is an adapter choice,
40
+ local run. That is the point of the `Environment` seam — where a command executes is an adapter choice,
41
41
  not a mode the engine knows about.
42
42
 
43
43
  The lifecycle deliberately stays with the host rather than the framework, because only the host
@@ -1,16 +1,16 @@
1
- import type { DirEntry, Environment, Machine, ByteRange, RunCommandOptions, RunCommandResult } from "operon-agents-core";
1
+ import type { DirEntry, OsInfo, Environment, ByteRange, RunCommandOptions, RunCommandResult } from "operon-agents-core";
2
2
  import type { CloudflareClientRef, CloudflareSandboxClient } from "./cf-api.ts";
3
- import { SandboxMachine } from "../shared/sandbox-machine.ts";
4
- export interface CloudflareMachineOptions {
3
+ import { SandboxEnvironment } from "../shared/sandbox-environment.ts";
4
+ export interface CloudflareEnvironmentOptions {
5
5
  readonly cwd?: string;
6
- /** Cloudflare scopes every call to a session id; one machine, one session. */
6
+ /** Cloudflare scopes every call to a session id; one environment, one session. */
7
7
  readonly sessionId?: string;
8
8
  readonly shellPath?: string;
9
9
  /** Applied when `RunCommandOptions.timeoutMs` is absent. */
10
10
  readonly defaultTimeoutMs?: number;
11
11
  }
12
12
  /**
13
- * A `Machine` backed directly by `@cloudflare/sandbox`'s route-transport client.
13
+ * An `Environment` backed directly by `@cloudflare/sandbox`'s route-transport client.
14
14
  *
15
15
  * Direct rather than through a general sandbox abstraction for the same reason as the E2B
16
16
  * adapter: the vendor natively provides a per-command timeout, incremental output and a real
@@ -24,20 +24,20 @@ export interface CloudflareMachineOptions {
24
24
  * - No stat API, so `fileInfo` costs one `stat(1)` command.
25
25
  * - Bytes move as base64: the transport takes a string, and `writeFileStream` is RPC-only.
26
26
  */
27
- export declare class CloudflareMachine extends SandboxMachine {
27
+ export declare class CloudflareEnvironment extends SandboxEnvironment {
28
28
  readonly name = "cloudflare";
29
- readonly osEnv: Environment;
29
+ readonly osInfo: OsInfo;
30
30
  private readonly clientRef;
31
31
  private readonly cwd;
32
32
  private readonly sessionId;
33
33
  private readonly defaultTimeoutMs;
34
- constructor(client: CloudflareClientRef | CloudflareSandboxClient, options?: CloudflareMachineOptions);
34
+ constructor(client: CloudflareClientRef | CloudflareSandboxClient, options?: CloudflareEnvironmentOptions);
35
35
  private get client();
36
36
  pathClass(): "posix";
37
37
  normpath(path: string): string;
38
38
  gethome(): string;
39
39
  getcwd(): string;
40
- withCwd(cwd: string): Machine;
40
+ withCwd(cwd: string): Environment;
41
41
  /**
42
42
  * Two paths, because the vendor splits the capability in two:
43
43
  *
@@ -84,4 +84,4 @@ export declare class CloudflareMachine extends SandboxMachine {
84
84
  }
85
85
  /** Cloudflare takes a command STRING; quote every argv element so nothing is re-split. */
86
86
  export declare function shellJoin(argv: readonly string[]): string;
87
- //# sourceMappingURL=machine.d.ts.map
87
+ //# sourceMappingURL=environment.d.ts.map
@@ -1,9 +1,9 @@
1
1
  import { posix } from "node:path";
2
2
  import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
3
- import { SandboxMachine } from "../shared/sandbox-machine.js";
3
+ import { SandboxEnvironment } from "../shared/sandbox-environment.js";
4
4
  const DEFAULT_CWD = "/workspace";
5
5
  /**
6
- * A `Machine` backed directly by `@cloudflare/sandbox`'s route-transport client.
6
+ * An `Environment` backed directly by `@cloudflare/sandbox`'s route-transport client.
7
7
  *
8
8
  * Direct rather than through a general sandbox abstraction for the same reason as the E2B
9
9
  * adapter: the vendor natively provides a per-command timeout, incremental output and a real
@@ -17,9 +17,9 @@ const DEFAULT_CWD = "/workspace";
17
17
  * - No stat API, so `fileInfo` costs one `stat(1)` command.
18
18
  * - Bytes move as base64: the transport takes a string, and `writeFileStream` is RPC-only.
19
19
  */
20
- export class CloudflareMachine extends SandboxMachine {
20
+ export class CloudflareEnvironment extends SandboxEnvironment {
21
21
  name = "cloudflare";
22
- osEnv;
22
+ osInfo;
23
23
  clientRef;
24
24
  cwd;
25
25
  sessionId;
@@ -31,7 +31,7 @@ export class CloudflareMachine extends SandboxMachine {
31
31
  this.sessionId = options.sessionId ?? "default";
32
32
  this.defaultTimeoutMs = options.defaultTimeoutMs;
33
33
  const shellPath = options.shellPath ?? "/bin/bash";
34
- this.osEnv = {
34
+ this.osInfo = {
35
35
  osKind: "Linux",
36
36
  osArch: "unknown",
37
37
  osVersion: "unknown",
@@ -56,14 +56,12 @@ export class CloudflareMachine extends SandboxMachine {
56
56
  return this.cwd;
57
57
  }
58
58
  withCwd(cwd) {
59
- const clone = new CloudflareMachine(this.clientRef, {
59
+ const clone = new CloudflareEnvironment(this.clientRef, {
60
60
  cwd: this.resolve(cwd),
61
61
  sessionId: this.sessionId,
62
- shellPath: this.osEnv.shellPath,
62
+ shellPath: this.osInfo.shellPath,
63
63
  ...(this.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: this.defaultTimeoutMs } : {}),
64
64
  });
65
- // One sandbox, one file namespace — clones must share write locks.
66
- clone.pathLocks = this.pathLocks;
67
65
  return clone;
68
66
  }
69
67
  // ---- commands ----
@@ -88,7 +86,7 @@ export class CloudflareMachine extends SandboxMachine {
88
86
  // `processes.startProcess` accepts one. Refuse rather than drop it: a command fed no
89
87
  // input would see EOF and "succeed" on empty data.
90
88
  if (options.stdin !== undefined) {
91
- throw new Error("CloudflareMachine: this transport has no stdin channel, so run({ stdin }) cannot be honored.");
89
+ throw new Error("CloudflareEnvironment: this transport has no stdin channel, so run({ stdin }) cannot be honored.");
92
90
  }
93
91
  const needsHandle = options.onOutput !== undefined || options.signal !== undefined || options.maxOutputBytes !== undefined;
94
92
  return needsHandle ? await this.runViaProcess(argv, options) : await this.runViaExecute(argv, options);
@@ -211,7 +209,7 @@ export class CloudflareMachine extends SandboxMachine {
211
209
  // No `spawn`: this transport hands back no OS process, so the base class's process SPI stays
212
210
  // unimplemented and `run` above — which every caller uses — is native instead.
213
211
  // ---- files & metadata ----
214
- // `fileInfo` comes from SandboxMachine: no stat API here either, so it costs one `stat(1)`.
212
+ // `fileInfo` comes from SandboxEnvironment: no stat API here either, so it costs one `stat(1)`.
215
213
  /**
216
214
  * One `listFiles` round trip — the vendor listing already says directory-or-not, so no
217
215
  * stat per entry.
@@ -339,4 +337,4 @@ function codedError(message, code) {
339
337
  error.code = code;
340
338
  return error;
341
339
  }
342
- //# sourceMappingURL=machine.js.map
340
+ //# sourceMappingURL=environment.js.map
@@ -1,17 +1,17 @@
1
1
  import type { SandboxWorkspace } from "../types.ts";
2
2
  import type { CloudflareSandboxClient } from "./cf-api.ts";
3
- import { CloudflareMachine, type CloudflareMachineOptions } from "./machine.ts";
4
- export interface CloudflareWorkspaceOptions extends CloudflareMachineOptions {
3
+ import { CloudflareEnvironment, type CloudflareEnvironmentOptions } from "./environment.ts";
4
+ export interface CloudflareWorkspaceOptions extends CloudflareEnvironmentOptions {
5
5
  /**
6
6
  * A `SandboxClient` from `@cloudflare/sandbox`, constructed against YOUR Worker:
7
7
  * `new SandboxClient({ baseUrl })`. The Worker must expose the SDK's routes (wrap your
8
8
  * handlers with `bridge()` from `@cloudflare/sandbox/bridge`).
9
9
  */
10
10
  readonly client: CloudflareSandboxClient;
11
- /** Workspace root that snapshots capture and restore. Defaults to the machine's cwd. */
11
+ /** Workspace root that snapshots capture and restore. Defaults to the environment's cwd. */
12
12
  readonly root?: string;
13
13
  /** Prepare a fresh workspace (clone a repo, drop config files). Runs only on creation. */
14
- readonly prepare?: (machine: CloudflareMachine) => Promise<void>;
14
+ readonly prepare?: (environment: CloudflareEnvironment) => Promise<void>;
15
15
  }
16
16
  /**
17
17
  * Host-side lifecycle for a Cloudflare sandbox.
@@ -27,7 +27,7 @@ export interface CloudflareWorkspaceOptions extends CloudflareMachineOptions {
27
27
  * container's own idle policy retires it or you `kill()` it.
28
28
  */
29
29
  export declare class CloudflareWorkspace implements SandboxWorkspace {
30
- readonly machine: CloudflareMachine;
30
+ readonly environment: CloudflareEnvironment;
31
31
  private readonly options;
32
32
  private readonly root;
33
33
  private snapshotSeq;
@@ -51,7 +51,7 @@ export declare class CloudflareWorkspace implements SandboxWorkspace {
51
51
  * the caller then knows to fall back instead of believing a snapshot exists.
52
52
  */
53
53
  snapshot(): Promise<string | undefined>;
54
- /** Unpack an archive back over the workspace root. The machine stays valid throughout. */
54
+ /** Unpack an archive back over the workspace root. The environment stays valid throughout. */
55
55
  restore(snapshotId: string): Promise<void>;
56
56
  /** Cloudflare containers have no suspend primitive — the sandbox is still running. */
57
57
  pause(): Promise<boolean>;
@@ -1,4 +1,4 @@
1
- import { CloudflareMachine } from "./machine.js";
1
+ import { CloudflareEnvironment } from "./environment.js";
2
2
  /** Where squashfs archives live inside the sandbox when no explicit path is given. */
3
3
  const SNAPSHOT_DIR = "/tmp/operon-snapshots";
4
4
  /**
@@ -15,20 +15,20 @@ const SNAPSHOT_DIR = "/tmp/operon-snapshots";
15
15
  * container's own idle policy retires it or you `kill()` it.
16
16
  */
17
17
  export class CloudflareWorkspace {
18
- machine;
18
+ environment;
19
19
  options;
20
20
  root;
21
21
  snapshotSeq = 0;
22
22
  constructor(options) {
23
23
  this.options = options;
24
- this.machine = new CloudflareMachine(options.client, options);
25
- this.root = options.root ?? this.machine.getcwd();
24
+ this.environment = new CloudflareEnvironment(options.client, options);
25
+ this.root = options.root ?? this.environment.getcwd();
26
26
  }
27
27
  static async open(options) {
28
28
  const workspace = new CloudflareWorkspace(options);
29
- await workspace.machine.mkdir(workspace.root, { parents: true });
29
+ await workspace.environment.mkdir(workspace.root, { parents: true });
30
30
  if (options.prepare !== undefined)
31
- await options.prepare(workspace.machine);
31
+ await options.prepare(workspace.environment);
32
32
  return workspace;
33
33
  }
34
34
  /** The session id every vendor call is scoped to — Cloudflare's unit of sandbox identity. */
@@ -62,11 +62,11 @@ export class CloudflareWorkspace {
62
62
  // millisecond cannot collide onto one archive.
63
63
  this.snapshotSeq += 1;
64
64
  const archivePath = `${SNAPSHOT_DIR}/snap-${String(this.snapshotSeq)}.sqfs`;
65
- await this.machine.mkdir(SNAPSHOT_DIR, { parents: true });
65
+ await this.environment.mkdir(SNAPSHOT_DIR, { parents: true });
66
66
  await backup.createArchive(this.root, archivePath, this.id, { gitignore: false });
67
67
  return archivePath;
68
68
  }
69
- /** Unpack an archive back over the workspace root. The machine stays valid throughout. */
69
+ /** Unpack an archive back over the workspace root. The environment stays valid throughout. */
70
70
  async restore(snapshotId) {
71
71
  const backup = this.options.client.backup;
72
72
  if (backup === undefined)
@@ -16,6 +16,10 @@ export interface E2BCommandResult {
16
16
  /** `background: true` resolves to this instead of a finished result. */
17
17
  export interface E2BCommandHandle extends E2BCommandResult {
18
18
  readonly pid: number;
19
+ /**
20
+ * Rejects for any nonzero exit with a `CommandExitError` whose `result` is the finished
21
+ * result, and with a plain error when the event stream fails (a kill, a dropped connection).
22
+ */
19
23
  wait?(): Promise<E2BCommandResult>;
20
24
  kill?(): Promise<boolean>;
21
25
  disconnect?(): Promise<void>;
@@ -25,6 +29,7 @@ export interface E2BRunOpts {
25
29
  cwd?: string;
26
30
  envs?: Record<string, string>;
27
31
  user?: string;
32
+ /** SDK default 60 000 when omitted; `0` = no deadline. */
28
33
  timeoutMs?: number;
29
34
  /** Incremental stdout. Present natively — this is what the OpenAI adapter never passes. */
30
35
  onStdout?: (data: string) => void | Promise<void>;
@@ -40,13 +45,24 @@ export interface E2BCommandsApi {
40
45
  sendStdin?(pid: number, data: string, opts?: {
41
46
  requestTimeoutMs?: number;
42
47
  }): Promise<void>;
48
+ /** EOF on the command's stdin. */
49
+ closeStdin?(pid: number, opts?: {
50
+ requestTimeoutMs?: number;
51
+ }): Promise<void>;
43
52
  }
44
- /** `list()` reports only file/dir — there is no symlink value and no stat method (see machine.ts). */
53
+ /** `type` is only ever file or dir. A symlink is marked by `symlinkTarget` instead, and
54
+ * `list()` drops entries of any other kind altogether. */
45
55
  export type E2BFileType = "file" | "dir";
56
+ /** SDK `EntryInfo`, as returned by both `files.getInfo` and `files.list`. */
46
57
  export interface E2BEntryInfo {
47
58
  readonly name: string;
48
59
  readonly path: string;
49
60
  readonly type?: E2BFileType;
61
+ readonly size?: number;
62
+ /** Millisecond precision (the SDK floors envd's nanoseconds). */
63
+ readonly modifiedTime?: Date;
64
+ /** Present when the entry is a symlink. */
65
+ readonly symlinkTarget?: string;
50
66
  }
51
67
  export interface E2BFilesystemApi {
52
68
  list(path: string, opts?: Record<string, unknown>): Promise<readonly E2BEntryInfo[]>;
@@ -59,7 +75,10 @@ export interface E2BFilesystemApi {
59
75
  * a signature that rejects it. See `writeBytesRaw` for the conversion.
60
76
  */
61
77
  write(path: string, data: string | ArrayBuffer, opts?: Record<string, unknown>): Promise<unknown>;
78
+ /** Creates missing parents too. `false` = the path already existed (the SDK maps AlreadyExists). */
62
79
  makeDir?(path: string): Promise<boolean>;
80
+ /** One envd stat RPC. Rejects with `FileNotFoundError` for a missing path. */
81
+ getInfo?(path: string): Promise<E2BEntryInfo>;
63
82
  remove?(path: string): Promise<void>;
64
83
  exists?(path: string): Promise<boolean>;
65
84
  }
@@ -77,7 +96,7 @@ export interface E2BSandbox {
77
96
  }
78
97
  /**
79
98
  * How to obtain the CURRENT sandbox. Deliberately a function, not a value: restoring a
80
- * snapshot replaces the underlying instance (the old one gets killed), so a machine holding
99
+ * snapshot replaces the underlying instance (the old one gets killed), so an environment holding
81
100
  * a captured reference would keep talking to a dead sandbox.
82
101
  */
83
102
  export type SandboxRef = () => E2BSandbox;
@@ -0,0 +1,85 @@
1
+ import type { DirEntry, OsInfo, FileInfo, FileVersion, Environment, ByteRange, RunCommandOptions, RunCommandResult } from "operon-agents-core";
2
+ import type { E2BSandbox, SandboxRef } from "./e2b-api.ts";
3
+ import { SandboxEnvironment } from "../shared/sandbox-environment.ts";
4
+ export interface E2BEnvironmentOptions {
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. Unset = no deadline. */
10
+ readonly defaultTimeoutMs?: number;
11
+ }
12
+ /**
13
+ * An `Environment` 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()` drops entries that are neither a file nor a directory (see `listDir`).
23
+ * - `files.getInfo` does not say whether a symlink's size/mtime are its own or its target's, so
24
+ * symlinks still cost one `stat(1)` command (see `fileInfo`); everything else is one RPC.
25
+ */
26
+ export declare class E2BEnvironment extends SandboxEnvironment {
27
+ readonly name = "e2b";
28
+ readonly osInfo: OsInfo;
29
+ private readonly sandboxRef;
30
+ private readonly cwd;
31
+ private readonly runAs;
32
+ private readonly defaultTimeoutMs;
33
+ constructor(sandbox: SandboxRef | E2BSandbox, options?: E2BEnvironmentOptions);
34
+ private get sandbox();
35
+ pathClass(): "posix";
36
+ normpath(path: string): string;
37
+ gethome(): string;
38
+ getcwd(): string;
39
+ withCwd(cwd: string): Environment;
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.getInfo` RPC — no command, no shell. A symlink is the exception: the SDK marks one
49
+ * with `symlinkTarget` but does not say whether the size and mtime it reports are the link's or
50
+ * the target's, so the follow/no-follow distinction goes to `stat(1)` (SandboxEnvironment), which
51
+ * states it exactly. An SDK build without `getInfo` takes that path for everything.
52
+ */
53
+ fileInfo(path: string, options?: {
54
+ followSymlinks?: boolean;
55
+ }): Promise<FileInfo>;
56
+ /**
57
+ * The version a write produced, from one `getInfo` — the same source `fileInfo` reads, so the
58
+ * two compare equal. Without it every E2B write left the read-state record versionless, and
59
+ * the next Write had to download the file to compare contents. Symlinked targets report
60
+ * nothing: their `fileInfo` comes from `stat(1)`, a different source.
61
+ */
62
+ protected versionAfterWrite(path: string): Promise<FileVersion | undefined>;
63
+ /**
64
+ * One `files.list()` round trip — the vendor listing already carries each entry's kind, so there
65
+ * is no stat per entry. A symlink is reported as `"symlink"` (lstat semantics, per `DirEntry`)
66
+ * from its `symlinkTarget`.
67
+ *
68
+ * Caveat worth knowing: the SDK drops entries that are neither a file nor a directory (a socket,
69
+ * a FIFO, possibly a dangling symlink), so those are absent from the listing rather than
70
+ * reported as `"other"`.
71
+ */
72
+ listDir(path: string): Promise<readonly DirEntry[]>;
73
+ mkdir(path: string, options?: {
74
+ parents?: boolean;
75
+ existOk?: boolean;
76
+ }): Promise<void>;
77
+ readBytes(path: string, range?: ByteRange): Promise<Buffer>;
78
+ protected writeBytesRaw(path: string, data: Buffer): Promise<void>;
79
+ /** Public URL for a port listening inside the sandbox (dev servers, previews). */
80
+ exposedPortUrl(port: number, scheme?: "http" | "https"): Promise<string | undefined>;
81
+ protected resolve(path: string): string;
82
+ }
83
+ /** E2B takes a command STRING; quote every argv element so no arg is re-split by the shell. */
84
+ export declare function shellJoin(argv: readonly string[]): string;
85
+ //# sourceMappingURL=environment.d.ts.map
@@ -1,9 +1,9 @@
1
1
  import { posix } from "node:path";
2
2
  import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
3
- import { SandboxMachine } from "../shared/sandbox-machine.js";
3
+ import { SandboxEnvironment } from "../shared/sandbox-environment.js";
4
4
  const DEFAULT_CWD = "/home/user";
5
5
  /**
6
- * A `Machine` backed directly by the E2B SDK.
6
+ * An `Environment` backed directly by the E2B SDK.
7
7
  *
8
8
  * Direct on purpose: E2B natively provides exactly what tool execution needs — `timeoutMs`,
9
9
  * incremental `onStdout`/`onStderr`, and a real `commands.kill(pid)`. Routing through a
@@ -12,13 +12,13 @@ const DEFAULT_CWD = "/home/user";
12
12
  * whose timeout and output cap silently do nothing.
13
13
  *
14
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.
15
+ * - `files.list()` drops entries that are neither a file nor a directory (see `listDir`).
16
+ * - `files.getInfo` does not say whether a symlink's size/mtime are its own or its target's, so
17
+ * symlinks still cost one `stat(1)` command (see `fileInfo`); everything else is one RPC.
18
18
  */
19
- export class E2BMachine extends SandboxMachine {
19
+ export class E2BEnvironment extends SandboxEnvironment {
20
20
  name = "e2b";
21
- osEnv;
21
+ osInfo;
22
22
  sandboxRef;
23
23
  cwd;
24
24
  runAs;
@@ -30,7 +30,7 @@ export class E2BMachine extends SandboxMachine {
30
30
  this.runAs = options.runAs;
31
31
  this.defaultTimeoutMs = options.defaultTimeoutMs;
32
32
  const shellPath = options.shellPath ?? "/bin/bash";
33
- this.osEnv = {
33
+ this.osInfo = {
34
34
  osKind: "Linux",
35
35
  osArch: "unknown",
36
36
  osVersion: "unknown",
@@ -55,14 +55,12 @@ export class E2BMachine extends SandboxMachine {
55
55
  return this.cwd;
56
56
  }
57
57
  withCwd(cwd) {
58
- const clone = new E2BMachine(this.sandboxRef, {
58
+ const clone = new E2BEnvironment(this.sandboxRef, {
59
59
  cwd: this.resolve(cwd),
60
60
  ...(this.runAs !== undefined ? { runAs: this.runAs } : {}),
61
- shellPath: this.osEnv.shellPath,
61
+ shellPath: this.osInfo.shellPath,
62
62
  ...(this.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: this.defaultTimeoutMs } : {}),
63
63
  });
64
- // One sandbox, one file namespace — clones must share write locks.
65
- clone.pathLocks = this.pathLocks;
66
64
  return clone;
67
65
  }
68
66
  // ---- commands ----
@@ -104,23 +102,29 @@ export class E2BMachine extends SandboxMachine {
104
102
  // Refuse stdin we cannot deliver instead of dropping it: a hook or a filter fed no input
105
103
  // would silently see EOF and "succeed" on empty data.
106
104
  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.");
105
+ throw new Error("E2BEnvironment: this SDK build exposes no commands.sendStdin, so run({ stdin }) cannot be honored.");
108
106
  }
107
+ // Our own deadline, not the SDK's. Left unset, the SDK applies a 60-second deadline to every
108
+ // command — a build, a test run, a background dev server all cut off at one minute — and
109
+ // when it fires the stream just errors, with no kill and no `timedOut`. `0` disables it, and
110
+ // the timer below enforces the caller's timeout with a real kill instead.
111
+ const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;
109
112
  const started = await sandbox.commands.run(shellJoin(argv), {
110
113
  background: true, // resolves immediately with a pid so cancellation has a target
111
114
  cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
112
115
  ...(options.env !== undefined ? { envs: options.env } : {}),
113
116
  ...(this.runAs !== undefined ? { user: this.runAs } : {}),
114
117
  ...(options.stdin !== undefined ? { stdin: true } : {}),
115
- ...(pickTimeout(options.timeoutMs, this.defaultTimeoutMs) !== undefined
116
- ? { timeoutMs: pickTimeout(options.timeoutMs, this.defaultTimeoutMs) }
117
- : {}),
118
+ timeoutMs: 0,
118
119
  onStdout: collect("stdout"),
119
120
  onStderr: collect("stderr"),
120
121
  });
121
122
  const handle = started;
122
123
  if (options.stdin !== undefined && typeof handle.pid === "number") {
123
124
  await sandbox.commands.sendStdin(handle.pid, options.stdin);
125
+ // EOF. Without it a stdin reader — a hook piping its JSON through `jq`, a plain `cat` —
126
+ // waits for more input until the command is killed.
127
+ await sandbox.commands.closeStdin?.(handle.pid);
124
128
  }
125
129
  // No pid means the SDK ran it to completion synchronously — nothing to cancel.
126
130
  if (typeof handle.pid !== "number" || handle.wait === undefined) {
@@ -140,12 +144,12 @@ export class E2BMachine extends SandboxMachine {
140
144
  const stop = () => (stopping ??= this.killPid(sandbox, handle).then((ok) => void (terminated = ok)));
141
145
  const onAbort = () => void stop();
142
146
  options.signal?.addEventListener("abort", onAbort);
143
- const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => {
147
+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
144
148
  timedOut = true;
145
149
  void stop();
146
- }, options.timeoutMs);
150
+ }, timeoutMs);
147
151
  try {
148
- const finished = await handle.wait();
152
+ const finished = await settledResult(handle, () => stopping !== undefined);
149
153
  // Cap reached but the command outlived it — stop it rather than let it keep producing.
150
154
  if (truncated && !terminated)
151
155
  await stop();
@@ -186,36 +190,87 @@ export class E2BMachine extends SandboxMachine {
186
190
  // this replaced faked a process handle whose `kill()` did nothing, and the Bash tool trusted
187
191
  // it, so a user's interrupt left the command running inside the sandbox.
188
192
  // ---- 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
  /**
193
- * One `files.list()` round trip — the vendor listing already carries `type`, so there is no
194
- * stat per entry.
194
+ * One `files.getInfo` RPC — no command, no shell. A symlink is the exception: the SDK marks one
195
+ * with `symlinkTarget` but does not say whether the size and mtime it reports are the link's or
196
+ * the target's, so the follow/no-follow distinction goes to `stat(1)` (SandboxEnvironment), which
197
+ * states it exactly. An SDK build without `getInfo` takes that path for everything.
198
+ */
199
+ async fileInfo(path, options) {
200
+ const getInfo = this.sandbox.files.getInfo;
201
+ if (getInfo === undefined)
202
+ return await super.fileInfo(path, options);
203
+ const target = this.resolve(path);
204
+ let entry;
205
+ try {
206
+ entry = await getInfo.call(this.sandbox.files, target);
207
+ }
208
+ catch (error) {
209
+ throw asErrnoError(error, target);
210
+ }
211
+ if (entry.symlinkTarget !== undefined)
212
+ return await super.fileInfo(path, options);
213
+ return {
214
+ kind: entry.type === "dir" ? "dir" : entry.type === "file" ? "file" : "other",
215
+ size: entry.size ?? 0,
216
+ ...mtimeOf(entry),
217
+ };
218
+ }
219
+ /**
220
+ * The version a write produced, from one `getInfo` — the same source `fileInfo` reads, so the
221
+ * two compare equal. Without it every E2B write left the read-state record versionless, and
222
+ * the next Write had to download the file to compare contents. Symlinked targets report
223
+ * nothing: their `fileInfo` comes from `stat(1)`, a different source.
224
+ */
225
+ async versionAfterWrite(path) {
226
+ const getInfo = this.sandbox.files.getInfo;
227
+ if (getInfo === undefined)
228
+ return undefined;
229
+ try {
230
+ const entry = await getInfo.call(this.sandbox.files, this.resolve(path));
231
+ return entry.symlinkTarget === undefined ? mtimeOf(entry) : undefined;
232
+ }
233
+ catch {
234
+ return undefined; // the write succeeded; this only costs the fast path
235
+ }
236
+ }
237
+ /**
238
+ * One `files.list()` round trip — the vendor listing already carries each entry's kind, so there
239
+ * is no stat per entry. A symlink is reported as `"symlink"` (lstat semantics, per `DirEntry`)
240
+ * from its `symlinkTarget`.
195
241
  *
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.
242
+ * Caveat worth knowing: the SDK drops entries that are neither a file nor a directory (a socket,
243
+ * a FIFO, possibly a dangling symlink), so those are absent from the listing rather than
244
+ * reported as `"other"`.
200
245
  */
201
246
  async listDir(path) {
202
247
  const entries = await this.sandbox.files.list(this.resolve(path));
203
248
  return entries.map((entry) => ({
204
249
  name: entry.name,
205
- kind: entry.type === "dir" ? "dir" : entry.type === "file" ? "file" : "other",
250
+ kind: entry.symlinkTarget !== undefined ? "symlink" : entry.type === "dir" ? "dir" : entry.type === "file" ? "file" : "other",
206
251
  }));
207
252
  }
208
253
  async mkdir(path, options) {
209
254
  const target = this.resolve(path);
255
+ const makeDir = this.sandbox.files.makeDir;
210
256
  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;
257
+ if (makeDir === undefined) {
258
+ const { exitCode } = await this.run(["mkdir", "-p", "--", target]);
259
+ if (exitCode !== 0)
260
+ throw codedError(`mkdir -p failed: ${target}`, "EIO");
261
+ return;
262
+ }
263
+ // `makeDir` already creates the parents — one RPC instead of a `mkdir -p` command. When the
264
+ // path existed, it must be a directory: `mkdir -p` over a file fails, and so does this.
265
+ if (await makeDir.call(this.sandbox.files, target))
266
+ return;
267
+ if ((await this.fileInfo(target).catch(() => undefined))?.kind === "dir")
268
+ return;
269
+ throw codedError(`EEXIST: path exists and is not a directory: ${target}`, "EEXIST");
215
270
  }
216
271
  // Plain mkdir must fail on an existing path; `files.makeDir` returns false instead of
217
272
  // throwing, so translate that into the EEXIST the contract promises.
218
- const created = (await this.sandbox.files.makeDir?.(target)) ?? false;
273
+ const created = (await makeDir?.call(this.sandbox.files, target)) ?? false;
219
274
  if (created)
220
275
  return;
221
276
  if (options?.existOk === true && (await this.fileInfo(target).catch(() => undefined))?.kind === "dir")
@@ -230,7 +285,15 @@ export class E2BMachine extends SandboxMachine {
230
285
  // Fall through: no `tail`/`head`/`base64` in this image. Correct, just expensive — and
231
286
  // the caller is told nothing, because the contract only promises the bytes.
232
287
  }
233
- const payload = await this.sandbox.files.read(this.resolve(path), { format: "bytes" });
288
+ let payload;
289
+ try {
290
+ payload = await this.sandbox.files.read(this.resolve(path), { format: "bytes" });
291
+ }
292
+ catch (error) {
293
+ // Callers branch on ENOENT (an append to a file that does not exist yet); the SDK's
294
+ // FileNotFoundError carries no code.
295
+ throw asErrnoError(error, this.resolve(path));
296
+ }
234
297
  const bytes = typeof payload === "string" ? Buffer.from(payload, "utf8") : Buffer.from(payload);
235
298
  return sliceRange(bytes, range);
236
299
  }
@@ -247,8 +310,25 @@ export class E2BMachine extends SandboxMachine {
247
310
  return normalizeAbs(path.startsWith("/") ? path : posix.join(this.cwd, path));
248
311
  }
249
312
  }
250
- function pickTimeout(explicit, fallback) {
251
- return explicit ?? fallback;
313
+ /**
314
+ * How the command ended, as a RESULT. The SDK's `wait()` rejects for every nonzero exit with a
315
+ * `CommandExitError` carrying the result — for `run`, whose callers branch on `exitCode` (a
316
+ * `stat` that found nothing, a `grep` with no match), that is an ordinary outcome, not a failure.
317
+ * A rejection without a result is a failure unless we were stopping the command: a kill ends the
318
+ * event stream too, and that is the ending we asked for.
319
+ */
320
+ async function settledResult(handle, stopRequested) {
321
+ try {
322
+ return await handle.wait();
323
+ }
324
+ catch (error) {
325
+ const result = error?.result;
326
+ if (result !== undefined && typeof result.exitCode === "number")
327
+ return result;
328
+ if (stopRequested())
329
+ return { exitCode: null };
330
+ throw error;
331
+ }
252
332
  }
253
333
  /**
254
334
  * Copy a Buffer's bytes into a standalone ArrayBuffer, which is what the E2B SDK accepts.
@@ -260,6 +340,19 @@ function pickTimeout(explicit, fallback) {
260
340
  function toArrayBuffer(data) {
261
341
  return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
262
342
  }
343
+ /** `modifiedTime` as the contract's optional `mtimeMs` — absent, not 0, when there is none. */
344
+ function mtimeOf(entry) {
345
+ const ms = entry.modifiedTime?.getTime();
346
+ return ms === undefined || !Number.isFinite(ms) || ms === 0 ? {} : { mtimeMs: ms };
347
+ }
348
+ /** The SDK's not-found error, given the ENOENT code every Environment caller branches on. */
349
+ function asErrnoError(error, path) {
350
+ const name = error?.name;
351
+ if (name === "FileNotFoundError" || name === "NotFoundError") {
352
+ return codedError(`No such file or directory: ${path}`, "ENOENT");
353
+ }
354
+ return error;
355
+ }
263
356
  function normalizeAbs(path) {
264
357
  const normalized = posix.normalize(path);
265
358
  return normalized.startsWith("/") ? normalized : `/${normalized}`;
@@ -278,4 +371,4 @@ function codedError(message, code) {
278
371
  error.code = code;
279
372
  return error;
280
373
  }
281
- //# sourceMappingURL=machine.js.map
374
+ //# sourceMappingURL=environment.js.map
@@ -1,6 +1,6 @@
1
1
  import type { SandboxWorkspace } from "../types.ts";
2
2
  import type { E2BSandbox } from "./e2b-api.ts";
3
- import { E2BMachine, type E2BMachineOptions } from "./machine.ts";
3
+ import { E2BEnvironment, type E2BEnvironmentOptions } from "./environment.ts";
4
4
  /**
5
5
  * The bits of the `Sandbox` class we call. Structural, so `e2b` stays an optional peer and
6
6
  * tests can inject a fake factory.
@@ -10,12 +10,12 @@ export interface E2BSandboxFactory {
10
10
  connect?(sandboxId: string, opts?: Record<string, unknown>): Promise<E2BSandbox>;
11
11
  }
12
12
  /** Persisted between sessions so a reopen reconnects instead of starting a fresh sandbox. */
13
- export interface E2BMachineState {
13
+ export interface E2BEnvironmentState {
14
14
  readonly sandboxId: string;
15
15
  /** Snapshot the sandbox was last restored from, if any. */
16
16
  readonly snapshotId?: string;
17
17
  }
18
- export interface E2BWorkspaceOptions extends E2BMachineOptions {
18
+ export interface E2BWorkspaceOptions extends E2BEnvironmentOptions {
19
19
  /** Usually the `Sandbox` class from the `e2b` package. */
20
20
  readonly sandbox: E2BSandboxFactory;
21
21
  /** Template/base image id for a fresh sandbox. */
@@ -24,7 +24,7 @@ export interface E2BWorkspaceOptions extends E2BMachineOptions {
24
24
  /** Sandbox-level inactivity timeout (distinct from a command's timeout). */
25
25
  readonly timeoutMs?: number;
26
26
  /** Prepare a fresh workspace (clone a repo, drop config files). Runs only on creation. */
27
- readonly prepare?: (machine: E2BMachine) => Promise<void>;
27
+ readonly prepare?: (environment: E2BEnvironment) => Promise<void>;
28
28
  }
29
29
  /**
30
30
  * Lifecycle for a directly-driven E2B sandbox: create or reconnect on open, snapshot on
@@ -32,28 +32,28 @@ export interface E2BWorkspaceOptions extends E2BMachineOptions {
32
32
  *
33
33
  * Restore is the subtle part. E2B restores a snapshot by starting a NEW sandbox from it, so
34
34
  * the old instance is dead afterwards. Everything therefore reads the sandbox through a
35
- * mutable cell rather than capturing it — `E2BMachine` holds `() => current`, so a restore
36
- * is transparent to every tool already holding the machine.
35
+ * mutable cell rather than capturing it — `E2BEnvironment` holds `() => current`, so a restore
36
+ * is transparent to every tool already holding the environment.
37
37
  */
38
38
  export declare class E2BWorkspace implements SandboxWorkspace {
39
39
  private current;
40
40
  private readonly factory;
41
41
  private readonly options;
42
- readonly machine: E2BMachine;
42
+ readonly environment: E2BEnvironment;
43
43
  private constructor();
44
- static open(options: E2BWorkspaceOptions, state?: E2BMachineState): Promise<E2BWorkspace>;
44
+ static open(options: E2BWorkspaceOptions, state?: E2BEnvironmentState): Promise<E2BWorkspace>;
45
45
  get id(): string;
46
- state(): E2BMachineState;
46
+ state(): E2BEnvironmentState;
47
47
  /** Capture the workspace. Returns undefined when the plan/template has no snapshot support. */
48
48
  snapshot(): Promise<string | undefined>;
49
49
  /**
50
50
  * Restore a snapshot by starting a replacement sandbox from it and retiring the old one.
51
- * The machine keeps working because it reads `current` through a closure.
51
+ * The environment keeps working because it reads `current` through a closure.
52
52
  */
53
53
  restore(snapshotId: string): Promise<void>;
54
54
  /** Fork the workspace: snapshot, then start an independent sandbox from that snapshot. */
55
55
  fork(): Promise<{
56
- machine: E2BMachine;
56
+ environment: E2BEnvironment;
57
57
  dispose: () => Promise<void>;
58
58
  } | undefined>;
59
59
  /** E2B supports pause on some plans only; `false` means the sandbox is still running. */
@@ -61,7 +61,7 @@ export declare class E2BWorkspace implements SandboxWorkspace {
61
61
  kill(): Promise<void>;
62
62
  }
63
63
  /**
64
- * No `e2bMachineFactory` here on purpose.
64
+ * No `e2bEnvironmentFactory` here on purpose.
65
65
  *
66
66
  * A factory that created a sandbox per session, stored its id in the session's state and
67
67
  * killed it on session close got three things wrong at once: every new session started a
@@ -72,8 +72,8 @@ export declare class E2BWorkspace implements SandboxWorkspace {
72
72
  * A sandbox is a user- or workspace-scoped resource. So the host owns it:
73
73
  *
74
74
  * const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
75
- * await materializeWorkspace(workspace.machine, spec); // prepare it once
76
- * const harness = new Harness({ machine: workspace.machine });
75
+ * await materializeWorkspace(workspace.environment, spec); // prepare it once
76
+ * const harness = new Harness({ environment: workspace.environment });
77
77
  * // ...every session — new, resumed, forked — runs in that one sandbox, and the host
78
78
  * // calls workspace.close() when the USER is done, not when a session is.
79
79
  *
@@ -1,29 +1,29 @@
1
- import { E2BMachine } from "./machine.js";
1
+ import { E2BEnvironment } from "./environment.js";
2
2
  /**
3
3
  * Lifecycle for a directly-driven E2B sandbox: create or reconnect on open, snapshot on
4
4
  * demand, restore by replacing the instance.
5
5
  *
6
6
  * Restore is the subtle part. E2B restores a snapshot by starting a NEW sandbox from it, so
7
7
  * the old instance is dead afterwards. Everything therefore reads the sandbox through a
8
- * mutable cell rather than capturing it — `E2BMachine` holds `() => current`, so a restore
9
- * is transparent to every tool already holding the machine.
8
+ * mutable cell rather than capturing it — `E2BEnvironment` holds `() => current`, so a restore
9
+ * is transparent to every tool already holding the environment.
10
10
  */
11
11
  export class E2BWorkspace {
12
12
  current;
13
13
  factory;
14
14
  options;
15
- machine;
15
+ environment;
16
16
  constructor(sandbox, options) {
17
17
  this.current = sandbox;
18
18
  this.factory = options.sandbox;
19
19
  this.options = options;
20
- this.machine = new E2BMachine(() => this.current, options);
20
+ this.environment = new E2BEnvironment(() => this.current, options);
21
21
  }
22
22
  static async open(options, state) {
23
23
  const sandbox = await openSandbox(options, state);
24
24
  const workspace = new E2BWorkspace(sandbox, options);
25
25
  if (state === undefined && options.prepare !== undefined)
26
- await options.prepare(workspace.machine);
26
+ await options.prepare(workspace.environment);
27
27
  return workspace;
28
28
  }
29
29
  get id() {
@@ -41,7 +41,7 @@ export class E2BWorkspace {
41
41
  }
42
42
  /**
43
43
  * Restore a snapshot by starting a replacement sandbox from it and retiring the old one.
44
- * The machine keeps working because it reads `current` through a closure.
44
+ * The environment keeps working because it reads `current` through a closure.
45
45
  */
46
46
  async restore(snapshotId) {
47
47
  const replacement = await this.factory.create({
@@ -65,7 +65,7 @@ export class E2BWorkspace {
65
65
  ...(this.options.envs !== undefined ? { envs: this.options.envs } : {}),
66
66
  });
67
67
  return {
68
- machine: new E2BMachine(() => clone, this.options),
68
+ environment: new E2BEnvironment(() => clone, this.options),
69
69
  dispose: async () => void (await clone.kill().catch(() => undefined)),
70
70
  };
71
71
  }
@@ -98,7 +98,7 @@ async function openSandbox(options, state) {
98
98
  });
99
99
  }
100
100
  /**
101
- * No `e2bMachineFactory` here on purpose.
101
+ * No `e2bEnvironmentFactory` here on purpose.
102
102
  *
103
103
  * A factory that created a sandbox per session, stored its id in the session's state and
104
104
  * killed it on session close got three things wrong at once: every new session started a
@@ -109,8 +109,8 @@ async function openSandbox(options, state) {
109
109
  * A sandbox is a user- or workspace-scoped resource. So the host owns it:
110
110
  *
111
111
  * const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
112
- * await materializeWorkspace(workspace.machine, spec); // prepare it once
113
- * const harness = new Harness({ machine: workspace.machine });
112
+ * await materializeWorkspace(workspace.environment, spec); // prepare it once
113
+ * const harness = new Harness({ environment: workspace.environment });
114
114
  * // ...every session — new, resumed, forked — runs in that one sandbox, and the host
115
115
  * // calls workspace.close() when the USER is done, not when a session is.
116
116
  *
package/dist/index.d.ts CHANGED
@@ -6,24 +6,24 @@
6
6
  * - **Lifecycle** (`SandboxWorkspace`) — create, snapshot, pause, destroy. Lives HERE, on the
7
7
  * host's side of the line, because a sandbox is a user- or workspace-scoped resource that
8
8
  * outlives any single agent session.
9
- * - **Operation** (`Machine`) — commands and file I/O, driven by each vendor's SDK directly,
9
+ * - **Operation** (`Environment`) — commands and file I/O, driven by each vendor's SDK directly,
10
10
  * so a per-command timeout, incremental output and a real kill actually take effect.
11
11
  *
12
- * Wire the two together by handing the machine in:
12
+ * Wire the two together by handing the environment in:
13
13
  *
14
14
  * const workspace = await E2BWorkspace.open({ sandbox: Sandbox, template: "node20" });
15
- * await materializeWorkspace(workspace.machine, spec);
16
- * const harness = new Harness({ machine: workspace.machine });
15
+ * await materializeWorkspace(workspace.environment, spec);
16
+ * const harness = new Harness({ environment: workspace.environment });
17
17
  * // ...and the host calls workspace.pause()/kill() when the USER is done, not when a
18
18
  * // session is.
19
19
  *
20
20
  * Vendor SDKs are optional peers: install `e2b` or `@cloudflare/sandbox` for the ones you use.
21
21
  */
22
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";
23
+ export { E2BEnvironment, shellJoin, type E2BEnvironmentOptions } from "./e2b/environment.ts";
24
+ export { E2BWorkspace, type E2BWorkspaceOptions, type E2BEnvironmentState, type E2BSandboxFactory, } from "./e2b/lifecycle.ts";
25
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";
26
+ export { CloudflareEnvironment, type CloudflareEnvironmentOptions } from "./cloudflare/environment.ts";
27
27
  export { CloudflareWorkspace, type CloudflareWorkspaceOptions } from "./cloudflare/lifecycle.ts";
28
28
  export type { CloudflareBackupApi, CloudflareClientRef, CloudflareCommandsApi, CloudflareFileEntry, CloudflareFilesApi, CloudflareGitApi, CloudflareLogEvent, CloudflareProcessesApi, CloudflareSandboxClient, } from "./cloudflare/cf-api.ts";
29
29
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export { E2BMachine, shellJoin } from "./e2b/machine.js";
1
+ export { E2BEnvironment, shellJoin } from "./e2b/environment.js";
2
2
  export { E2BWorkspace, } from "./e2b/lifecycle.js";
3
- export { CloudflareMachine } from "./cloudflare/machine.js";
3
+ export { CloudflareEnvironment } from "./cloudflare/environment.js";
4
4
  export { CloudflareWorkspace } from "./cloudflare/lifecycle.js";
5
5
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import type { Machine } from "operon-agents-core";
1
+ import type { Environment } from "operon-agents-core";
2
2
  /**
3
3
  * Read a byte WINDOW of a remote file without transferring the rest.
4
4
  *
@@ -18,21 +18,8 @@ export declare function sliceRange(bytes: Buffer, range?: {
18
18
  readonly offset?: number;
19
19
  readonly length?: number;
20
20
  }): Buffer;
21
- export declare function readWindowViaShell(machine: Machine, absPath: string, range: {
21
+ export declare function readWindowViaShell(environment: Environment, absPath: string, range: {
22
22
  readonly offset?: number;
23
23
  readonly length?: number;
24
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
25
  //# sourceMappingURL=remote-file-ops.d.ts.map
@@ -1,4 +1,3 @@
1
- import { posix } from "node:path";
2
1
  /**
3
2
  * Read a byte WINDOW of a remote file without transferring the rest.
4
3
  *
@@ -20,7 +19,7 @@ export function sliceRange(bytes, range) {
20
19
  const offset = Math.max(0, Math.trunc(range.offset ?? 0));
21
20
  return range.length === undefined ? bytes.subarray(offset) : bytes.subarray(offset, offset + Math.max(0, Math.trunc(range.length)));
22
21
  }
23
- export async function readWindowViaShell(machine, absPath, range) {
22
+ export async function readWindowViaShell(environment, absPath, range) {
24
23
  const offset = Math.max(0, Math.trunc(range.offset ?? 0));
25
24
  const length = range.length === undefined ? undefined : Math.max(0, Math.trunc(range.length));
26
25
  if (length === 0)
@@ -28,7 +27,7 @@ export async function readWindowViaShell(machine, absPath, range) {
28
27
  const cut = length === undefined ? "" : ` | head -c ${String(length)}`;
29
28
  // The path goes through `$0` rather than string interpolation, so no quoting scheme has to
30
29
  // be trusted with a filename containing quotes, spaces or newlines. The numbers are ours.
31
- const result = await machine
30
+ const result = await environment
32
31
  .run(["sh", "-c", `tail -c +${String(offset + 1)} -- "$0"${cut} | base64`, absPath])
33
32
  .catch(() => undefined);
34
33
  if (result === undefined || result.exitCode !== 0)
@@ -36,31 +35,4 @@ export async function readWindowViaShell(machine, absPath, range) {
36
35
  // base64(1) wraps its output; strip every kind of whitespace before decoding.
37
36
  return Buffer.from(result.stdout.replace(/\s+/g, ""), "base64");
38
37
  }
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
38
  //# sourceMappingURL=remote-file-ops.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared base for the vendor sandbox Environments (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 share one fallback: file
6
+ * metadata from `stat(1)` through the shell. Cloudflare has no stat API at all; E2B has one and
7
+ * uses it, falling back here only where it is ambiguous (symlinks). The derivation is identical
8
+ * for both, so it is stated once here instead of twice in the backends.
9
+ */
10
+ import { BaseEnvironment } from "operon-agents-core";
11
+ import type { FileInfo } from "operon-agents-core";
12
+ export declare abstract class SandboxEnvironment extends BaseEnvironment {
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
+ /**
19
+ * One `stat(1)` command. `-L` follows the
20
+ * symlink; without it the link itself is described, which is what `DirEntry` wants.
21
+ */
22
+ fileInfo(path: string, options?: {
23
+ followSymlinks?: boolean;
24
+ }): Promise<FileInfo>;
25
+ }
26
+ //# sourceMappingURL=sandbox-environment.d.ts.map
@@ -1,14 +1,13 @@
1
1
  /**
2
- * Shared base for the vendor sandbox Machines (E2B, Cloudflare).
2
+ * Shared base for the vendor sandbox Environments (E2B, Cloudflare).
3
3
  *
4
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.
5
+ * other an HTTP API; one takes bytes, the other base64 — but they share one fallback: file
6
+ * metadata from `stat(1)` through the shell. Cloudflare has no stat API at all; E2B has one and
7
+ * uses it, falling back here only where it is ambiguous (symlinks). The derivation is identical
8
+ * for both, so it is stated once here instead of twice in the backends.
9
9
  */
10
- import { BaseMachine } from "operon-agents-core";
11
- import { writeViaTempSwap } from "./remote-file-ops.js";
10
+ import { BaseEnvironment } from "operon-agents-core";
12
11
  function codedError(message, code) {
13
12
  const error = new Error(message);
14
13
  error.code = code;
@@ -48,13 +47,9 @@ function parseMtimeSeconds(wholeRaw, fractionalRaw) {
48
47
  return fractional;
49
48
  return whole;
50
49
  }
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
- }
50
+ export class SandboxEnvironment extends BaseEnvironment {
56
51
  /**
57
- * Neither vendor exposes a stat API, so this costs one `stat(1)`. `-L` follows the
52
+ * One `stat(1)` command. `-L` follows the
58
53
  * symlink; without it the link itself is described, which is what `DirEntry` wants.
59
54
  */
60
55
  async fileInfo(path, options) {
@@ -75,23 +70,9 @@ export class SandboxMachine extends BaseMachine {
75
70
  }
76
71
  // mtime 0 means "the backend has no clock for this file" — report it as absent
77
72
  // 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);
73
+ // Rounded: `1726480000.123 * 1000` is not always an exact integer in floating point, and an
74
+ // mtime that is off by a hair never equals the same instant read from a native API.
75
+ return { kind: statKind(kindRaw), size, ...(mtimeSec === 0 ? {} : { mtimeMs: Math.round(mtimeSec * 1000) }) };
95
76
  }
96
77
  }
97
- //# sourceMappingURL=sandbox-machine.js.map
78
+ //# sourceMappingURL=sandbox-environment.js.map
package/dist/types.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- import type { Machine } from "operon-agents-core";
1
+ import type { Environment } from "operon-agents-core";
2
2
  /**
3
3
  * A sandbox the HOST owns: created here, disposed of here, and handed to the agent
4
- * framework only as a {@link Machine}.
4
+ * framework only as a {@link Environment}.
5
5
  *
6
6
  * This layer exists because sandbox lifetime and agent-session lifetime are different
7
7
  * things. A sandbox is normally scoped to a user or a workspace and outlives any single
8
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.
9
+ * `environment: workspace.environment`; the framework then only ever operates the
10
+ * environment, and closing a session cannot take the workspace down with it.
11
11
  *
12
12
  * Every method states an INTENT and answers honestly about whether the backend could
13
13
  * deliver it — `undefined`/`false` rather than a throw or a pretend success. That is why
@@ -17,7 +17,7 @@ import type { Machine } from "operon-agents-core";
17
17
  */
18
18
  export interface SandboxWorkspace {
19
19
  /** The agent-facing handle. Stays valid across {@link restore}, which may swap the sandbox. */
20
- readonly machine: Machine;
20
+ readonly environment: Environment;
21
21
  /** Vendor id of the live sandbox. Changes when `restore` replaces it. */
22
22
  readonly id: string;
23
23
  /**
@@ -25,7 +25,7 @@ export interface SandboxWorkspace {
25
25
  * snapshot mechanism — the caller then knows to fall back rather than assume it worked.
26
26
  */
27
27
  snapshot(): Promise<string | undefined>;
28
- /** Replace the workspace's contents with a snapshot. `machine` keeps working across it. */
28
+ /** Replace the workspace's contents with a snapshot. `environment` keeps working across it. */
29
29
  restore(snapshotId: string): Promise<void>;
30
30
  /**
31
31
  * Suspend the sandbox, keeping its filesystem, so reopening is cheaper than a cold start.
@@ -33,7 +33,7 @@ export interface SandboxWorkspace {
33
33
  * has to decide between paying for it and killing it.
34
34
  */
35
35
  pause(): Promise<boolean>;
36
- /** Destroy the sandbox. Terminal: the machine is unusable afterwards. */
36
+ /** Destroy the sandbox. Terminal: the environment is unusable afterwards. */
37
37
  kill(): Promise<void>;
38
38
  }
39
39
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "operon-sandbox",
3
- "version": "0.1.0-alpha.2",
4
- "description": "Host-side sandbox lifecycle for operon-agents: create, snapshot, pause and destroy a vendor sandbox, and hand the framework a Machine driven by the vendor SDK directly (native per-command timeout, incremental output, real kill).",
3
+ "version": "0.1.0-alpha.20",
4
+ "description": "Host-side sandbox lifecycle for operon-agents: create, snapshot, pause and destroy a vendor sandbox, and hand the framework an Environment driven by the vendor SDK directly (native per-command timeout, incremental output, real kill).",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": ">=22"
@@ -25,7 +25,7 @@
25
25
  }
26
26
  },
27
27
  "dependencies": {
28
- "operon-agents-core": "0.1.0-alpha.2"
28
+ "operon-agents-core": "0.1.0-alpha.20"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@cloudflare/sandbox": ">=0.12",
@@ -1,69 +0,0 @@
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
@@ -1,38 +0,0 @@
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