operon-sandbox 0.1.0-alpha.32 → 0.1.0-alpha.34
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/dist/cloudflare/environment.d.ts +7 -4
- package/dist/cloudflare/environment.js +87 -91
- package/dist/cloudflare/lifecycle.js +2 -2
- package/dist/e2b/e2b-api.d.ts +52 -5
- package/dist/e2b/e2b-api.js +0 -8
- package/dist/e2b/environment.d.ts +12 -6
- package/dist/e2b/environment.js +244 -133
- package/dist/e2b/lifecycle.js +8 -0
- package/dist/shared/remote-file-ops.js +1 -1
- package/dist/shared/sandbox-environment.js +1 -1
- package/package.json +3 -3
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Command, CommandHandle, CommandStartOptions, EnvironmentCommands } from 'operon-agents-core';
|
|
2
|
+
import type { DirEntry, OsInfo, Environment, ByteRange } from "operon-agents-core";
|
|
2
3
|
import type { CloudflareClientRef, CloudflareSandboxClient } from "./cf-api.ts";
|
|
3
4
|
import { SandboxEnvironment } from "../shared/sandbox-environment.ts";
|
|
4
5
|
export interface CloudflareEnvironmentOptions {
|
|
@@ -51,11 +52,13 @@ export declare class CloudflareEnvironment extends SandboxEnvironment {
|
|
|
51
52
|
* asked for cancellation, incremental output or an output cap takes the process path. The
|
|
52
53
|
* caller states intent once; which mechanism delivers it stays in here.
|
|
53
54
|
*/
|
|
54
|
-
|
|
55
|
+
private live;
|
|
56
|
+
private nextPid;
|
|
57
|
+
readonly commands: EnvironmentCommands;
|
|
58
|
+
protected startCommand(command: Command, options: CommandStartOptions): Promise<CommandHandle>;
|
|
59
|
+
private connectProcess;
|
|
55
60
|
/** Cheap path: one request, native timeout, no cancellation. */
|
|
56
61
|
private runViaExecute;
|
|
57
|
-
/** Cancellable path: a processId to kill, plus an SSE log stream for incremental output. */
|
|
58
|
-
private runViaProcess;
|
|
59
62
|
/** Real termination, reported honestly: `false` means the command may still be running. */
|
|
60
63
|
private kill;
|
|
61
64
|
private exitCodeOf;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { commandLine, runViaHandle, wrapForTaskLog, codedError as processError } from 'operon-agents-core';
|
|
1
2
|
import { posix } from "node:path";
|
|
2
3
|
import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
|
|
3
4
|
import { SandboxEnvironment } from "../shared/sandbox-environment.js";
|
|
@@ -78,18 +79,87 @@ export class CloudflareEnvironment extends SandboxEnvironment {
|
|
|
78
79
|
* asked for cancellation, incremental output or an output cap takes the process path. The
|
|
79
80
|
* caller states intent once; which mechanism delivers it stays in here.
|
|
80
81
|
*/
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
live = new Map();
|
|
83
|
+
nextPid = -1;
|
|
84
|
+
commands = {
|
|
85
|
+
run: (command, options = {}) => {
|
|
86
|
+
if (options.stdin !== undefined)
|
|
87
|
+
return Promise.reject(new Error('CloudflareEnvironment: this transport has no stdin channel'));
|
|
88
|
+
if (!options.signal && !options.onOutput && options.maxOutputBytes === undefined)
|
|
89
|
+
return this.runViaExecute(typeof command === 'string' ? [this.osInfo.shellPath, '-c', command] : command, options);
|
|
90
|
+
return runViaHandle((cmd, opts) => this.startCommand(cmd, opts), command, { ...options, timeoutMs: options.timeoutMs ?? this.defaultTimeoutMs });
|
|
91
|
+
},
|
|
92
|
+
start: (cmd, opts) => this.startCommand(cmd, opts ?? {}),
|
|
93
|
+
list: async () => [...this.live.values()].map(entry => entry.info),
|
|
94
|
+
connect: async (pid, opts) => {
|
|
95
|
+
const entry = this.live.get(pid);
|
|
96
|
+
if (!entry)
|
|
97
|
+
throw processError(`No such process: ${pid}`, 'ESRCH');
|
|
98
|
+
return this.connectProcess(pid, entry.id, opts ?? {});
|
|
99
|
+
},
|
|
100
|
+
kill: async (pid) => { const entry = this.live.get(pid); return entry ? this.kill(entry.id) : false; },
|
|
101
|
+
sendStdin: async () => { throw new Error('CloudflareEnvironment: stdin unavailable'); },
|
|
102
|
+
closeStdin: async () => { throw new Error('CloudflareEnvironment: stdin unavailable'); },
|
|
103
|
+
};
|
|
104
|
+
async startCommand(command, options) {
|
|
105
|
+
if (options.stdin)
|
|
106
|
+
throw new Error('CloudflareEnvironment: this transport has no stdin channel');
|
|
107
|
+
if (options.outputFile) {
|
|
108
|
+
await this.files.write(options.outputFile, '');
|
|
109
|
+
await this.files.remove(`${options.outputFile}.exit`);
|
|
110
|
+
if (options.stderrFile)
|
|
111
|
+
await this.files.write(options.stderrFile, '');
|
|
112
|
+
command = wrapForTaskLog(commandLine(command), options.outputFile, options.stderrFile, true);
|
|
84
113
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
114
|
+
const started = await this.client.processes.startProcess(commandLine(command), this.sessionId, { cwd: options.cwd === undefined ? this.cwd : this.resolve(options.cwd), env: options.env });
|
|
115
|
+
const pid = started.pid ?? this.nextPid--;
|
|
116
|
+
this.live.set(pid, { id: started.processId, info: { pid, cmd: commandLine(command), args: [], envs: options.env ?? {}, cwd: options.cwd ?? this.cwd } });
|
|
117
|
+
return this.connectProcess(pid, started.processId, options);
|
|
118
|
+
}
|
|
119
|
+
async connectProcess(pid, id, options) {
|
|
120
|
+
let stdout = '', stderr = '', exitCode;
|
|
121
|
+
let disconnected = false, stopped = false;
|
|
122
|
+
const controller = new AbortController();
|
|
123
|
+
const stream = await this.client.processes.streamProcessLogs(id);
|
|
124
|
+
const done = (async () => {
|
|
125
|
+
try {
|
|
126
|
+
for await (const event of readLogEvents(stream, controller.signal)) {
|
|
127
|
+
if (event.type === 'exit')
|
|
128
|
+
exitCode = event.exitCode;
|
|
129
|
+
else if (!disconnected && (event.type === 'stdout' || event.type === 'stderr')) {
|
|
130
|
+
const data = event.data ?? '';
|
|
131
|
+
if (event.type === 'stdout') {
|
|
132
|
+
if (options.retainOutput !== false)
|
|
133
|
+
stdout += data;
|
|
134
|
+
options.onStdout?.(data);
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
if (options.retainOutput !== false)
|
|
138
|
+
stderr += data;
|
|
139
|
+
options.onStderr?.(data);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else if (event.type === 'error' && !stopped)
|
|
143
|
+
throw new Error(event.data ?? 'Cloudflare command stream failed');
|
|
144
|
+
}
|
|
145
|
+
if (exitCode === undefined && !stopped && !disconnected)
|
|
146
|
+
exitCode = await this.exitCodeOf(id);
|
|
147
|
+
return { stdout, stderr, exitCode: stopped ? undefined : exitCode };
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
if (!disconnected)
|
|
151
|
+
this.live.delete(pid);
|
|
152
|
+
}
|
|
153
|
+
})();
|
|
154
|
+
done.catch(() => { });
|
|
155
|
+
return {
|
|
156
|
+
pid, get stdout() { return stdout; }, get stderr() { return stderr; }, get exitCode() { return exitCode; },
|
|
157
|
+
wait: () => done,
|
|
158
|
+
kill: async () => { stopped = true; return this.kill(id); },
|
|
159
|
+
disconnect: async () => { disconnected = true; controller.abort(); await done; },
|
|
160
|
+
sendStdin: async () => { throw new Error('CloudflareEnvironment: stdin unavailable'); },
|
|
161
|
+
closeStdin: async () => { throw new Error('CloudflareEnvironment: stdin unavailable'); },
|
|
162
|
+
};
|
|
93
163
|
}
|
|
94
164
|
/** Cheap path: one request, native timeout, no cancellation. */
|
|
95
165
|
async runViaExecute(argv, options) {
|
|
@@ -109,85 +179,6 @@ export class CloudflareEnvironment extends SandboxEnvironment {
|
|
|
109
179
|
terminated: false,
|
|
110
180
|
};
|
|
111
181
|
}
|
|
112
|
-
/** Cancellable path: a processId to kill, plus an SSE log stream for incremental output. */
|
|
113
|
-
async runViaProcess(argv, options) {
|
|
114
|
-
const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;
|
|
115
|
-
const started = await this.client.processes.startProcess(shellJoin(argv), this.sessionId, {
|
|
116
|
-
cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
|
|
117
|
-
...(options.env !== undefined ? { env: options.env } : {}),
|
|
118
|
-
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
119
|
-
});
|
|
120
|
-
const processId = started.processId;
|
|
121
|
-
const cap = options.maxOutputBytes ?? Number.POSITIVE_INFINITY;
|
|
122
|
-
let out = "";
|
|
123
|
-
let err = "";
|
|
124
|
-
let bytes = 0;
|
|
125
|
-
let truncated = false;
|
|
126
|
-
let exitCode;
|
|
127
|
-
let timedOut = false;
|
|
128
|
-
let terminated = false;
|
|
129
|
-
let stopping;
|
|
130
|
-
const stop = () => (stopping ??= this.kill(processId).then((ok) => void (terminated = ok)));
|
|
131
|
-
const collect = (stream, data) => {
|
|
132
|
-
options.onOutput?.({ stream, data });
|
|
133
|
-
if (truncated)
|
|
134
|
-
return;
|
|
135
|
-
const room = cap - bytes;
|
|
136
|
-
if (data.length >= room) {
|
|
137
|
-
const kept = data.slice(0, Math.max(0, room));
|
|
138
|
-
if (stream === "stdout")
|
|
139
|
-
out += kept;
|
|
140
|
-
else
|
|
141
|
-
err += kept;
|
|
142
|
-
bytes = cap;
|
|
143
|
-
truncated = true;
|
|
144
|
-
// Cap reached; stop the command rather than let it keep producing output nobody reads.
|
|
145
|
-
void stop();
|
|
146
|
-
return;
|
|
147
|
-
}
|
|
148
|
-
bytes += data.length;
|
|
149
|
-
if (stream === "stdout")
|
|
150
|
-
out += data;
|
|
151
|
-
else
|
|
152
|
-
err += data;
|
|
153
|
-
};
|
|
154
|
-
const onAbort = () => void stop();
|
|
155
|
-
options.signal?.addEventListener("abort", onAbort);
|
|
156
|
-
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
157
|
-
timedOut = true;
|
|
158
|
-
void stop();
|
|
159
|
-
}, timeoutMs);
|
|
160
|
-
try {
|
|
161
|
-
const stream = await this.client.processes.streamProcessLogs(processId);
|
|
162
|
-
for await (const event of readLogEvents(stream)) {
|
|
163
|
-
if (event.type === "stdout" || event.type === "stderr")
|
|
164
|
-
collect(event.type, event.data ?? "");
|
|
165
|
-
else if (event.type === "exit")
|
|
166
|
-
exitCode = event.exitCode;
|
|
167
|
-
}
|
|
168
|
-
// A kill makes the log stream end at once, so without joining the in-flight stop here
|
|
169
|
-
// we would read `terminated` before it resolved and under-report every termination.
|
|
170
|
-
await stopping;
|
|
171
|
-
// The stream can end without an `exit` event (killed, or the transport dropped it);
|
|
172
|
-
// ask the process registry rather than assume success.
|
|
173
|
-
if (exitCode === undefined && !terminated && !timedOut)
|
|
174
|
-
exitCode = await this.exitCodeOf(processId);
|
|
175
|
-
return {
|
|
176
|
-
stdout: out,
|
|
177
|
-
stderr: err,
|
|
178
|
-
// A killed or timed-out command has no meaningful completion status.
|
|
179
|
-
exitCode: timedOut || terminated ? undefined : exitCode,
|
|
180
|
-
timedOut,
|
|
181
|
-
truncated,
|
|
182
|
-
terminated,
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
finally {
|
|
186
|
-
if (timer !== undefined)
|
|
187
|
-
clearTimeout(timer);
|
|
188
|
-
options.signal?.removeEventListener("abort", onAbort);
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
182
|
/** Real termination, reported honestly: `false` means the command may still be running. */
|
|
192
183
|
async kill(processId) {
|
|
193
184
|
try {
|
|
@@ -270,10 +261,14 @@ export class CloudflareEnvironment extends SandboxEnvironment {
|
|
|
270
261
|
}
|
|
271
262
|
}
|
|
272
263
|
/** Decode an SSE byte stream into the `LogEvent`s the process log endpoint emits. */
|
|
273
|
-
async function* readLogEvents(stream) {
|
|
264
|
+
async function* readLogEvents(stream, signal) {
|
|
274
265
|
const decoder = new TextDecoder();
|
|
275
266
|
let buffer = "";
|
|
276
267
|
const reader = stream.getReader();
|
|
268
|
+
const cancel = () => { void reader.cancel().catch(() => { }); };
|
|
269
|
+
signal?.addEventListener('abort', cancel);
|
|
270
|
+
if (signal?.aborted)
|
|
271
|
+
cancel();
|
|
277
272
|
try {
|
|
278
273
|
while (true) {
|
|
279
274
|
const { done, value } = await reader.read();
|
|
@@ -295,6 +290,7 @@ async function* readLogEvents(stream) {
|
|
|
295
290
|
yield last;
|
|
296
291
|
}
|
|
297
292
|
finally {
|
|
293
|
+
signal?.removeEventListener('abort', cancel);
|
|
298
294
|
reader.releaseLock();
|
|
299
295
|
}
|
|
300
296
|
}
|
|
@@ -26,7 +26,7 @@ export class CloudflareWorkspace {
|
|
|
26
26
|
}
|
|
27
27
|
static async open(options) {
|
|
28
28
|
const workspace = new CloudflareWorkspace(options);
|
|
29
|
-
await workspace.environment.
|
|
29
|
+
await workspace.environment.files.makeDir(workspace.root);
|
|
30
30
|
if (options.prepare !== undefined)
|
|
31
31
|
await options.prepare(workspace.environment);
|
|
32
32
|
return workspace;
|
|
@@ -62,7 +62,7 @@ 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.environment.
|
|
65
|
+
await this.environment.files.makeDir(SNAPSHOT_DIR);
|
|
66
66
|
await backup.createArchive(this.root, archivePath, this.id, { gitignore: false });
|
|
67
67
|
return archivePath;
|
|
68
68
|
}
|
package/dist/e2b/e2b-api.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { FileData, FilesystemEvent, WatchHandle, WatchOptions, ProcessInfo, CommandConnectOptions, PtySize, SandboxInfo, SandboxMetrics } from 'operon-agents-core';
|
|
1
2
|
/**
|
|
2
3
|
* The slice of the E2B SDK this adapter uses, described structurally rather than imported.
|
|
3
4
|
*
|
|
@@ -25,6 +26,7 @@ export interface E2BCommandHandle extends E2BCommandResult {
|
|
|
25
26
|
disconnect?(): Promise<void>;
|
|
26
27
|
}
|
|
27
28
|
export interface E2BRunOpts {
|
|
29
|
+
retainOutput?: boolean;
|
|
28
30
|
background?: boolean;
|
|
29
31
|
cwd?: string;
|
|
30
32
|
envs?: Record<string, string>;
|
|
@@ -37,12 +39,16 @@ export interface E2BRunOpts {
|
|
|
37
39
|
stdin?: boolean;
|
|
38
40
|
}
|
|
39
41
|
export interface E2BCommandsApi {
|
|
42
|
+
list?(): Promise<readonly ProcessInfo[]>;
|
|
43
|
+
connect?(pid: number, options?: CommandConnectOptions & {
|
|
44
|
+
timeoutMs?: number;
|
|
45
|
+
}): Promise<E2BCommandHandle>;
|
|
40
46
|
run(command: string, opts?: E2BRunOpts): Promise<E2BCommandResult | E2BCommandHandle>;
|
|
41
47
|
/** Real SIGKILL by pid; resolves to whether a process was actually killed. */
|
|
42
48
|
kill?(pid: number, opts?: {
|
|
43
49
|
requestTimeoutMs?: number;
|
|
44
50
|
}): Promise<boolean>;
|
|
45
|
-
sendStdin?(pid: number, data: string, opts?: {
|
|
51
|
+
sendStdin?(pid: number, data: string | Uint8Array, opts?: {
|
|
46
52
|
requestTimeoutMs?: number;
|
|
47
53
|
}): Promise<void>;
|
|
48
54
|
/** EOF on the command's stdin. */
|
|
@@ -52,7 +58,7 @@ export interface E2BCommandsApi {
|
|
|
52
58
|
}
|
|
53
59
|
/** `type` is only ever file or dir. A symlink is marked by `symlinkTarget` instead, and
|
|
54
60
|
* `list()` drops entries of any other kind altogether. */
|
|
55
|
-
export type E2BFileType = "file" | "dir";
|
|
61
|
+
export type E2BFileType = "file" | "dir" | "symlink";
|
|
56
62
|
/** SDK `EntryInfo`, as returned by both `files.getInfo` and `files.list`. */
|
|
57
63
|
export interface E2BEntryInfo {
|
|
58
64
|
readonly name: string;
|
|
@@ -63,18 +69,31 @@ export interface E2BEntryInfo {
|
|
|
63
69
|
readonly modifiedTime?: Date;
|
|
64
70
|
/** Present when the entry is a symlink. */
|
|
65
71
|
readonly symlinkTarget?: string;
|
|
72
|
+
readonly mode?: number;
|
|
73
|
+
readonly permissions?: string;
|
|
74
|
+
readonly owner?: string;
|
|
75
|
+
readonly group?: string;
|
|
76
|
+
readonly metadata?: Record<string, string>;
|
|
66
77
|
}
|
|
67
78
|
export interface E2BFilesystemApi {
|
|
79
|
+
writeFiles?(files: {
|
|
80
|
+
path: string;
|
|
81
|
+
data: FileData;
|
|
82
|
+
}[]): Promise<unknown>;
|
|
83
|
+
rename?(oldPath: string, newPath: string): Promise<E2BEntryInfo>;
|
|
84
|
+
watchDir?(path: string, onEvent: (event: FilesystemEvent) => void, options?: WatchOptions & {
|
|
85
|
+
timeoutMs?: number;
|
|
86
|
+
}): Promise<WatchHandle>;
|
|
68
87
|
list(path: string, opts?: Record<string, unknown>): Promise<readonly E2BEntryInfo[]>;
|
|
69
88
|
read(path: string, opts?: {
|
|
70
|
-
format?: "text" | "bytes";
|
|
71
|
-
}): Promise<string | Uint8Array
|
|
89
|
+
format?: "text" | "bytes" | "stream";
|
|
90
|
+
}): Promise<string | Uint8Array | ReadableStream<Uint8Array>>;
|
|
72
91
|
/**
|
|
73
92
|
* `data` is deliberately NOT `Uint8Array`: the SDK takes `string | ArrayBuffer | Blob |
|
|
74
93
|
* ReadableStream`, so declaring the wider type here would let a `Buffer` typecheck against
|
|
75
94
|
* a signature that rejects it. See `E2BEnvironment.writeBytes` for the conversion.
|
|
76
95
|
*/
|
|
77
|
-
write(path: string, data:
|
|
96
|
+
write(path: string, data: FileData, opts?: Record<string, unknown>): Promise<unknown>;
|
|
78
97
|
/** Creates missing parents too. `false` = the path already existed (the SDK maps AlreadyExists). */
|
|
79
98
|
makeDir?(path: string): Promise<boolean>;
|
|
80
99
|
/** One envd stat RPC. Rejects with `FileNotFoundError` for a missing path. */
|
|
@@ -82,8 +101,36 @@ export interface E2BFilesystemApi {
|
|
|
82
101
|
remove?(path: string): Promise<void>;
|
|
83
102
|
exists?(path: string): Promise<boolean>;
|
|
84
103
|
}
|
|
104
|
+
export interface E2BPtyApi {
|
|
105
|
+
create(options: PtySize & {
|
|
106
|
+
onData: (data: Uint8Array) => void;
|
|
107
|
+
cwd?: string;
|
|
108
|
+
envs?: Record<string, string>;
|
|
109
|
+
user?: string;
|
|
110
|
+
timeoutMs?: number;
|
|
111
|
+
}): Promise<E2BCommandHandle>;
|
|
112
|
+
connect(pid: number, options?: {
|
|
113
|
+
onData?: (data: Uint8Array) => void;
|
|
114
|
+
timeoutMs?: number;
|
|
115
|
+
}): Promise<E2BCommandHandle>;
|
|
116
|
+
sendInput(pid: number, data: Uint8Array): Promise<void>;
|
|
117
|
+
resize(pid: number, size: PtySize): Promise<void>;
|
|
118
|
+
kill(pid: number): Promise<boolean>;
|
|
119
|
+
}
|
|
85
120
|
export interface E2BSandbox {
|
|
121
|
+
readonly pty?: E2BPtyApi;
|
|
86
122
|
readonly sandboxId: string;
|
|
123
|
+
isRunning?(): Promise<boolean>;
|
|
124
|
+
getInfo?(): Promise<Omit<SandboxInfo, "id"> & {
|
|
125
|
+
sandboxId: string;
|
|
126
|
+
}>;
|
|
127
|
+
getMetrics?(): Promise<SandboxMetrics[]>;
|
|
128
|
+
setTimeout?(timeoutMs: number): Promise<void>;
|
|
129
|
+
uploadUrl?(path?: string): Promise<string>;
|
|
130
|
+
downloadUrl?(path: string): Promise<string>;
|
|
131
|
+
fork?(options?: {
|
|
132
|
+
count?: number;
|
|
133
|
+
}): Promise<(E2BSandbox | Error)[]>;
|
|
87
134
|
readonly commands: E2BCommandsApi;
|
|
88
135
|
readonly files: E2BFilesystemApi;
|
|
89
136
|
/** Public URL for a port exposed inside the sandbox. */
|
package/dist/e2b/e2b-api.js
CHANGED
|
@@ -1,10 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The slice of the E2B SDK this adapter uses, described structurally rather than imported.
|
|
3
|
-
*
|
|
4
|
-
* Structural typing keeps `e2b` an OPTIONAL peer: the package compiles without it, tests can
|
|
5
|
-
* inject a fake, and a minor SDK release cannot break our build. The shapes mirror the E2B
|
|
6
|
-
* JS SDK v1.4 reference (`Sandbox.commands` / `Sandbox.files`); anything optional here is
|
|
7
|
-
* optional in the SDK too, or is a method we degrade gracefully without.
|
|
8
|
-
*/
|
|
9
1
|
export {};
|
|
10
2
|
//# sourceMappingURL=e2b-api.js.map
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { EnvironmentPty, EnvironmentFiles } from 'operon-agents-core';
|
|
2
|
+
import type { Command, CommandStartOptions, CommandHandle, EnvironmentCommands, EnvironmentSandbox } from 'operon-agents-core';
|
|
3
|
+
import type { DirEntry, OsInfo, FileInfo, Environment, ByteRange } from "operon-agents-core";
|
|
2
4
|
import type { E2BSandbox, SandboxRef } from "./e2b-api.ts";
|
|
3
5
|
import { SandboxEnvironment } from "../shared/sandbox-environment.ts";
|
|
4
6
|
export interface E2BEnvironmentOptions {
|
|
@@ -26,12 +28,14 @@ export interface E2BEnvironmentOptions {
|
|
|
26
28
|
export declare class E2BEnvironment extends SandboxEnvironment {
|
|
27
29
|
readonly name = "e2b";
|
|
28
30
|
readonly osInfo: OsInfo;
|
|
29
|
-
private readonly
|
|
31
|
+
private readonly sdkRef;
|
|
30
32
|
private readonly cwd;
|
|
31
33
|
private readonly runAs;
|
|
32
34
|
private readonly defaultTimeoutMs;
|
|
33
35
|
constructor(sandbox: SandboxRef | E2BSandbox, options?: E2BEnvironmentOptions);
|
|
34
|
-
private get
|
|
36
|
+
private get sdk();
|
|
37
|
+
readonly files: EnvironmentFiles;
|
|
38
|
+
readonly pty: EnvironmentPty | undefined;
|
|
35
39
|
pathClass(): "posix";
|
|
36
40
|
normpath(path: string): string;
|
|
37
41
|
gethome(): string;
|
|
@@ -41,9 +45,11 @@ export declare class E2BEnvironment extends SandboxEnvironment {
|
|
|
41
45
|
* The whole reason this adapter exists: every intent maps to a native E2B feature.
|
|
42
46
|
* `background: true` is what yields a pid, and a pid is what makes cancellation real.
|
|
43
47
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
private
|
|
48
|
+
readonly commands: EnvironmentCommands;
|
|
49
|
+
protected startCommand(command: Command, options: CommandStartOptions): Promise<CommandHandle>;
|
|
50
|
+
private wrapPty;
|
|
51
|
+
private wrapHandle;
|
|
52
|
+
readonly sandbox: EnvironmentSandbox;
|
|
47
53
|
/**
|
|
48
54
|
* One `files.getInfo` RPC — no command, no shell. A symlink is the exception: the SDK marks one
|
|
49
55
|
* with `symlinkTarget` but does not say whether the size and mtime it reports are the link's or
|
package/dist/e2b/environment.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { commandLine, runViaHandle, EnvironmentFilesAdapter, toBuffer, wrapForTaskLog, shellQuote as quoteArgument } from 'operon-agents-core';
|
|
1
2
|
import { posix } from "node:path";
|
|
2
3
|
import { readWindowViaShell, sliceRange } from "../shared/remote-file-ops.js";
|
|
3
4
|
import { SandboxEnvironment } from "../shared/sandbox-environment.js";
|
|
@@ -19,16 +20,25 @@ const DEFAULT_CWD = "/home/user";
|
|
|
19
20
|
export class E2BEnvironment extends SandboxEnvironment {
|
|
20
21
|
name = "e2b";
|
|
21
22
|
osInfo;
|
|
22
|
-
|
|
23
|
+
sdkRef;
|
|
23
24
|
cwd;
|
|
24
25
|
runAs;
|
|
25
26
|
defaultTimeoutMs;
|
|
26
27
|
constructor(sandbox, options = {}) {
|
|
27
28
|
super();
|
|
28
|
-
this.
|
|
29
|
+
this.files = new E2BFiles(this, () => this.sdk);
|
|
30
|
+
this.sdkRef = typeof sandbox === "function" ? sandbox : () => sandbox;
|
|
29
31
|
this.cwd = normalizeAbs(options.cwd ?? DEFAULT_CWD);
|
|
30
32
|
this.runAs = options.runAs;
|
|
31
33
|
this.defaultTimeoutMs = options.defaultTimeoutMs;
|
|
34
|
+
if (this.sdk.pty)
|
|
35
|
+
this.pty = {
|
|
36
|
+
create: async (options) => this.wrapPty(await this.sdk.pty.create({ ...options, cwd: options.cwd ?? this.cwd, envs: options.env, user: this.runAs, timeoutMs: 0 })),
|
|
37
|
+
connect: async (pid, options) => this.wrapPty(await this.sdk.pty.connect(pid, { ...options, timeoutMs: 0 })),
|
|
38
|
+
sendInput: async (pid, data) => this.sdk.pty.sendInput(pid, typeof data === 'string' ? Buffer.from(data) : data),
|
|
39
|
+
resize: async (pid, size) => this.sdk.pty.resize(pid, size),
|
|
40
|
+
kill: async (pid) => this.sdk.pty.kill(pid),
|
|
41
|
+
};
|
|
32
42
|
const shellPath = options.shellPath ?? "/bin/bash";
|
|
33
43
|
this.osInfo = {
|
|
34
44
|
osKind: "Linux",
|
|
@@ -38,9 +48,11 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
38
48
|
shellPath,
|
|
39
49
|
};
|
|
40
50
|
}
|
|
41
|
-
get
|
|
42
|
-
return this.
|
|
51
|
+
get sdk() {
|
|
52
|
+
return this.sdkRef();
|
|
43
53
|
}
|
|
54
|
+
files;
|
|
55
|
+
pty = undefined;
|
|
44
56
|
// ---- identity & paths ----
|
|
45
57
|
pathClass() {
|
|
46
58
|
return "posix";
|
|
@@ -55,7 +67,7 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
55
67
|
return this.cwd;
|
|
56
68
|
}
|
|
57
69
|
withCwd(cwd) {
|
|
58
|
-
const clone = new E2BEnvironment(this.
|
|
70
|
+
const clone = new E2BEnvironment(this.sdkRef, {
|
|
59
71
|
cwd: this.resolve(cwd),
|
|
60
72
|
...(this.runAs !== undefined ? { runAs: this.runAs } : {}),
|
|
61
73
|
shellPath: this.osInfo.shellPath,
|
|
@@ -68,127 +80,110 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
68
80
|
* The whole reason this adapter exists: every intent maps to a native E2B feature.
|
|
69
81
|
* `background: true` is what yields a pid, and a pid is what makes cancellation real.
|
|
70
82
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const collect = (stream) => (data) => {
|
|
82
|
-
options.onOutput?.({ stream, data });
|
|
83
|
-
if (truncated)
|
|
84
|
-
return;
|
|
85
|
-
const room = cap - bytes;
|
|
86
|
-
if (data.length >= room) {
|
|
87
|
-
const kept = data.slice(0, Math.max(0, room));
|
|
88
|
-
if (stream === "stdout")
|
|
89
|
-
out += kept;
|
|
90
|
-
else
|
|
91
|
-
err += kept;
|
|
92
|
-
bytes = cap;
|
|
93
|
-
truncated = true;
|
|
94
|
-
return;
|
|
83
|
+
commands = {
|
|
84
|
+
run: (command, options) => runViaHandle((cmd, opts) => this.startCommand(cmd, opts), command, { ...options, timeoutMs: options?.timeoutMs ?? this.defaultTimeoutMs }),
|
|
85
|
+
start: (command, options) => this.startCommand(command, options ?? {}),
|
|
86
|
+
list: async () => { if (!this.sdk.commands.list)
|
|
87
|
+
throw new Error('E2B commands.list unavailable'); return this.sdk.commands.list(); },
|
|
88
|
+
connect: async (pid, options) => {
|
|
89
|
+
if (!this.sdk.commands.connect)
|
|
90
|
+
throw new Error('E2B commands.connect unavailable');
|
|
91
|
+
try {
|
|
92
|
+
return this.wrapHandle(await this.sdk.commands.connect(pid, { ...options, timeoutMs: 0 }));
|
|
95
93
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error.name === 'NotFoundError')
|
|
96
|
+
throw codedError(`No such process: ${pid}`, 'ESRCH');
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
kill: async (pid) => this.sdk.commands.kill?.(pid) ?? false,
|
|
101
|
+
sendStdin: async (pid, data) => {
|
|
102
|
+
if (!this.sdk.commands.sendStdin)
|
|
103
|
+
throw new Error('E2B stdin unavailable');
|
|
104
|
+
await this.sdk.commands.sendStdin(pid, data);
|
|
105
|
+
},
|
|
106
|
+
closeStdin: async (pid) => {
|
|
107
|
+
if (!this.sdk.commands.closeStdin)
|
|
108
|
+
throw new Error('E2B closeStdin unavailable');
|
|
109
|
+
await this.sdk.commands.closeStdin(pid);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
async startCommand(command, options) {
|
|
113
|
+
if (options.outputFile) {
|
|
114
|
+
await this.files.write(options.outputFile, '');
|
|
115
|
+
await this.files.remove(`${options.outputFile}.exit`);
|
|
116
|
+
if (options.stderrFile)
|
|
117
|
+
await this.files.write(options.stderrFile, '');
|
|
118
|
+
const durable = wrapForTaskLog(commandLine(command), options.outputFile, options.stderrFile, true);
|
|
119
|
+
const handle = await this.startCommand(durable, { ...options, outputFile: undefined, stderrFile: undefined, onStderr: undefined });
|
|
120
|
+
return handle;
|
|
106
121
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
background: true, // resolves immediately with a pid so cancellation has a target
|
|
114
|
-
cwd: options.cwd !== undefined ? this.resolve(options.cwd) : this.cwd,
|
|
115
|
-
...(options.env !== undefined ? { envs: options.env } : {}),
|
|
116
|
-
...(this.runAs !== undefined ? { user: this.runAs } : {}),
|
|
117
|
-
...(options.stdin !== undefined ? { stdin: true } : {}),
|
|
118
|
-
timeoutMs: 0,
|
|
119
|
-
onStdout: collect("stdout"),
|
|
120
|
-
onStderr: collect("stderr"),
|
|
122
|
+
if (options.stdin && !this.sdk.commands.sendStdin)
|
|
123
|
+
throw new Error('E2B stdin unavailable');
|
|
124
|
+
const started = await this.sdk.commands.run(commandLine(command), {
|
|
125
|
+
background: true, timeoutMs: 0, cwd: options.cwd === undefined ? this.cwd : this.resolve(options.cwd),
|
|
126
|
+
envs: options.env, user: this.runAs, stdin: options.stdin,
|
|
127
|
+
retainOutput: options.retainOutput, onStdout: options.onStdout, onStderr: options.onStderr,
|
|
121
128
|
});
|
|
122
|
-
|
|
123
|
-
if (options.stdin !== undefined && typeof handle.pid === "number") {
|
|
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);
|
|
128
|
-
}
|
|
129
|
-
// No pid means the SDK ran it to completion synchronously — nothing to cancel.
|
|
130
|
-
if (typeof handle.pid !== "number" || handle.wait === undefined) {
|
|
131
|
-
const done = started;
|
|
132
|
-
return {
|
|
133
|
-
stdout: out || done.stdout || "",
|
|
134
|
-
stderr: err || done.stderr || "",
|
|
135
|
-
exitCode: done.exitCode ?? undefined,
|
|
136
|
-
timedOut: false,
|
|
137
|
-
truncated,
|
|
138
|
-
terminated: false,
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
let timedOut = false;
|
|
142
|
-
let terminated = false;
|
|
143
|
-
let stopping;
|
|
144
|
-
const stop = () => (stopping ??= this.killPid(sandbox, handle).then((ok) => void (terminated = ok)));
|
|
145
|
-
const onAbort = () => void stop();
|
|
146
|
-
options.signal?.addEventListener("abort", onAbort);
|
|
147
|
-
const timer = timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
148
|
-
timedOut = true;
|
|
149
|
-
void stop();
|
|
150
|
-
}, timeoutMs);
|
|
151
|
-
try {
|
|
152
|
-
const finished = await settledResult(handle, () => stopping !== undefined);
|
|
153
|
-
// Cap reached but the command outlived it — stop it rather than let it keep producing.
|
|
154
|
-
if (truncated && !terminated)
|
|
155
|
-
await stop();
|
|
156
|
-
// A kill makes wait() settle immediately, so without joining the in-flight stop here we
|
|
157
|
-
// would read `terminated` before killPid resolved and under-report every termination.
|
|
158
|
-
await stopping;
|
|
159
|
-
return {
|
|
160
|
-
stdout: out || finished.stdout || "",
|
|
161
|
-
stderr: err || finished.stderr || "",
|
|
162
|
-
// A killed command's exit status is not a real completion code.
|
|
163
|
-
exitCode: timedOut || terminated ? undefined : finished.exitCode ?? undefined,
|
|
164
|
-
timedOut,
|
|
165
|
-
truncated,
|
|
166
|
-
terminated,
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
finally {
|
|
170
|
-
if (timer !== undefined)
|
|
171
|
-
clearTimeout(timer);
|
|
172
|
-
options.signal?.removeEventListener("abort", onAbort);
|
|
173
|
-
}
|
|
129
|
+
return this.wrapHandle(started);
|
|
174
130
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
131
|
+
wrapPty(native) {
|
|
132
|
+
const handle = this.wrapHandle(native);
|
|
133
|
+
return { pid: handle.pid, wait: async () => ({ exitCode: (await handle.wait()).exitCode }),
|
|
134
|
+
sendInput: data => this.sdk.pty.sendInput(handle.pid, typeof data === 'string' ? Buffer.from(data) : data),
|
|
135
|
+
resize: size => this.sdk.pty.resize(handle.pid, size),
|
|
136
|
+
kill: () => this.sdk.pty.kill(handle.pid), disconnect: () => handle.disconnect() };
|
|
137
|
+
}
|
|
138
|
+
wrapHandle(handle) {
|
|
139
|
+
const sdk = this.sdk;
|
|
140
|
+
let stopping = false;
|
|
141
|
+
return {
|
|
142
|
+
pid: handle.pid,
|
|
143
|
+
get stdout() { return handle.stdout ?? ''; }, get stderr() { return handle.stderr ?? ''; },
|
|
144
|
+
get exitCode() { return handle.exitCode ?? undefined; },
|
|
145
|
+
wait: async () => {
|
|
146
|
+
const result = handle.wait ? await settledResult(handle, () => stopping) : handle;
|
|
147
|
+
return { stdout: result.stdout ?? '', stderr: result.stderr ?? '', exitCode: stopping ? undefined : result.exitCode ?? undefined, error: result.error };
|
|
148
|
+
},
|
|
149
|
+
kill: async () => {
|
|
150
|
+
stopping = true;
|
|
151
|
+
try {
|
|
152
|
+
return handle.kill ? await handle.kill() : await sdk.commands.kill?.(handle.pid) ?? false;
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
await handle.disconnect?.();
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
disconnect: async () => { await handle.disconnect?.(); },
|
|
160
|
+
sendStdin: async (data) => {
|
|
161
|
+
if (!sdk.commands.sendStdin)
|
|
162
|
+
throw new Error('E2B stdin unavailable');
|
|
163
|
+
await sdk.commands.sendStdin(handle.pid, data);
|
|
164
|
+
},
|
|
165
|
+
closeStdin: async () => {
|
|
166
|
+
if (!sdk.commands.closeStdin)
|
|
167
|
+
throw new Error('E2B closeStdin unavailable');
|
|
168
|
+
await sdk.commands.closeStdin(handle.pid);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
187
171
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
172
|
+
sandbox = (() => {
|
|
173
|
+
const owner = this;
|
|
174
|
+
return {
|
|
175
|
+
get id() { return owner.sdk.sandboxId; },
|
|
176
|
+
getHost: async (port) => this.sdk.getHost?.(port),
|
|
177
|
+
getUrl: async (port) => this.exposedPortUrl(port),
|
|
178
|
+
isRunning: async () => this.sdk.isRunning ? this.sdk.isRunning() : true,
|
|
179
|
+
getInfo: async () => { const info = await this.sdk.getInfo?.(); return { ...info, id: this.sdk.sandboxId, state: info?.state ?? 'running' }; },
|
|
180
|
+
getMetrics: async () => (await this.sdk.getMetrics?.())?.at(-1),
|
|
181
|
+
setTimeout: async (ms) => { if (!this.sdk.setTimeout)
|
|
182
|
+
return false; await this.sdk.setTimeout(ms); return true; },
|
|
183
|
+
uploadUrl: async (path) => this.sdk.uploadUrl?.(path),
|
|
184
|
+
downloadUrl: async (path) => this.sdk.downloadUrl?.(path),
|
|
185
|
+
};
|
|
186
|
+
})();
|
|
192
187
|
// ---- files & metadata ----
|
|
193
188
|
/**
|
|
194
189
|
* One `files.getInfo` RPC — no command, no shell. A symlink is the exception: the SDK marks one
|
|
@@ -197,13 +192,13 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
197
192
|
* states it exactly. An SDK build without `getInfo` takes that path for everything.
|
|
198
193
|
*/
|
|
199
194
|
async fileInfo(path, options) {
|
|
200
|
-
const getInfo = this.
|
|
195
|
+
const getInfo = this.sdk.files.getInfo;
|
|
201
196
|
if (getInfo === undefined)
|
|
202
197
|
return await super.fileInfo(path, options);
|
|
203
198
|
const target = this.resolve(path);
|
|
204
199
|
let entry;
|
|
205
200
|
try {
|
|
206
|
-
entry = await getInfo.call(this.
|
|
201
|
+
entry = await getInfo.call(this.sdk.files, target);
|
|
207
202
|
}
|
|
208
203
|
catch (error) {
|
|
209
204
|
throw asErrnoError(error, target);
|
|
@@ -226,7 +221,7 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
226
221
|
* reported as `"other"`.
|
|
227
222
|
*/
|
|
228
223
|
async listDir(path) {
|
|
229
|
-
const entries = await this.
|
|
224
|
+
const entries = await this.sdk.files.list(this.resolve(path));
|
|
230
225
|
return entries.map((entry) => ({
|
|
231
226
|
name: entry.name,
|
|
232
227
|
kind: entry.symlinkTarget !== undefined ? "symlink" : entry.type === "dir" ? "dir" : entry.type === "file" ? "file" : "other",
|
|
@@ -234,7 +229,7 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
234
229
|
}
|
|
235
230
|
async mkdir(path, options) {
|
|
236
231
|
const target = this.resolve(path);
|
|
237
|
-
const makeDir = this.
|
|
232
|
+
const makeDir = this.sdk.files.makeDir;
|
|
238
233
|
if (options?.parents === true) {
|
|
239
234
|
if (makeDir === undefined) {
|
|
240
235
|
const { exitCode } = await this.run(["mkdir", "-p", "--", target]);
|
|
@@ -244,7 +239,7 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
244
239
|
}
|
|
245
240
|
// `makeDir` already creates the parents — one RPC instead of a `mkdir -p` command. When the
|
|
246
241
|
// path existed, it must be a directory: `mkdir -p` over a file fails, and so does this.
|
|
247
|
-
if (await makeDir.call(this.
|
|
242
|
+
if (await makeDir.call(this.sdk.files, target))
|
|
248
243
|
return;
|
|
249
244
|
if ((await this.fileInfo(target).catch(() => undefined))?.kind === "dir")
|
|
250
245
|
return;
|
|
@@ -252,7 +247,7 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
252
247
|
}
|
|
253
248
|
// Plain mkdir must fail on an existing path; `files.makeDir` returns false instead of
|
|
254
249
|
// throwing, so translate that into the EEXIST the contract promises.
|
|
255
|
-
const created = (await makeDir?.call(this.
|
|
250
|
+
const created = (await makeDir?.call(this.sdk.files, target)) ?? false;
|
|
256
251
|
if (created)
|
|
257
252
|
return;
|
|
258
253
|
if (options?.existOk === true && (await this.fileInfo(target).catch(() => undefined))?.kind === "dir")
|
|
@@ -269,24 +264,24 @@ export class E2BEnvironment extends SandboxEnvironment {
|
|
|
269
264
|
}
|
|
270
265
|
let payload;
|
|
271
266
|
try {
|
|
272
|
-
payload = await this.
|
|
267
|
+
payload = await this.sdk.files.read(this.resolve(path), { format: "bytes" });
|
|
273
268
|
}
|
|
274
269
|
catch (error) {
|
|
275
270
|
// Callers branch on ENOENT (an append to a file that does not exist yet); the SDK's
|
|
276
271
|
// FileNotFoundError carries no code.
|
|
277
272
|
throw asErrnoError(error, this.resolve(path));
|
|
278
273
|
}
|
|
279
|
-
const bytes =
|
|
274
|
+
const bytes = await toBuffer(payload);
|
|
280
275
|
return sliceRange(bytes, range);
|
|
281
276
|
}
|
|
282
277
|
async writeBytes(path, data) {
|
|
283
|
-
await this.
|
|
278
|
+
await this.sdk.files.write(this.resolve(path), toArrayBuffer(data));
|
|
284
279
|
}
|
|
285
280
|
/** Public URL for a port listening inside the sandbox (dev servers, previews). */
|
|
286
281
|
async exposedPortUrl(port, scheme = "https") {
|
|
287
|
-
if (this.
|
|
282
|
+
if (this.sdk.getHost === undefined)
|
|
288
283
|
return undefined;
|
|
289
|
-
return `${scheme}://${await this.
|
|
284
|
+
return `${scheme}://${await this.sdk.getHost(port)}`;
|
|
290
285
|
}
|
|
291
286
|
resolve(path) {
|
|
292
287
|
return normalizeAbs(path.startsWith("/") ? path : posix.join(this.cwd, path));
|
|
@@ -304,7 +299,8 @@ async function settledResult(handle, stopRequested) {
|
|
|
304
299
|
return await handle.wait();
|
|
305
300
|
}
|
|
306
301
|
catch (error) {
|
|
307
|
-
const result = error?.result
|
|
302
|
+
const result = error?.result
|
|
303
|
+
?? (typeof error?.exitCode === 'number' ? error : undefined);
|
|
308
304
|
if (result !== undefined && typeof result.exitCode === "number")
|
|
309
305
|
return result;
|
|
310
306
|
if (stopRequested())
|
|
@@ -353,4 +349,119 @@ function codedError(message, code) {
|
|
|
353
349
|
error.code = code;
|
|
354
350
|
return error;
|
|
355
351
|
}
|
|
352
|
+
class E2BFiles extends EnvironmentFilesAdapter {
|
|
353
|
+
sdk;
|
|
354
|
+
constructor(environment, sdk) { super(environment); this.sdk = sdk; }
|
|
355
|
+
// Initialized lazily: the sandbox reference is assigned after this adapter is constructed.
|
|
356
|
+
get watchDir() {
|
|
357
|
+
const api = this.sdk().files;
|
|
358
|
+
if (!api.watchDir)
|
|
359
|
+
return undefined;
|
|
360
|
+
return async (path, onEvent, options) => api.watchDir(this.absolute(path), onEvent, { ...options, timeoutMs: 0 });
|
|
361
|
+
}
|
|
362
|
+
async getInfo(path, options) {
|
|
363
|
+
const api = this.sdk().files;
|
|
364
|
+
if (!api.getInfo)
|
|
365
|
+
return super.getInfo(path, options);
|
|
366
|
+
try {
|
|
367
|
+
const info = await api.getInfo(this.absolute(path));
|
|
368
|
+
if (info.symlinkTarget || info.type === 'symlink')
|
|
369
|
+
return { ...entryInfo(info), ...await this.environment.fileInfo(path, options) };
|
|
370
|
+
return entryInfo(info);
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
throw asErrnoError(error, path);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async write(path, data) {
|
|
377
|
+
const target = this.absolute(path);
|
|
378
|
+
try {
|
|
379
|
+
await this.sdk().files.write(target, data);
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
throw asErrnoError(error, target);
|
|
383
|
+
}
|
|
384
|
+
return { path: target, name: posix.basename(target) };
|
|
385
|
+
}
|
|
386
|
+
async readStream(path) {
|
|
387
|
+
const target = this.absolute(path);
|
|
388
|
+
try {
|
|
389
|
+
const data = await this.sdk().files.read(target, { format: 'stream' });
|
|
390
|
+
if (typeof data === 'object' && 'getReader' in data)
|
|
391
|
+
return data;
|
|
392
|
+
const bytes = await toBuffer(data);
|
|
393
|
+
return new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); } });
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
throw asErrnoError(error, target);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async makeDir(path) {
|
|
400
|
+
const api = this.sdk().files;
|
|
401
|
+
if (!api.makeDir)
|
|
402
|
+
return super.makeDir(path);
|
|
403
|
+
try {
|
|
404
|
+
const made = await api.makeDir(this.absolute(path));
|
|
405
|
+
if (!made && (await this.getInfo(path)).kind !== 'dir')
|
|
406
|
+
throw codedError(`Not a directory: ${path}`, 'EEXIST');
|
|
407
|
+
return made;
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
throw asErrnoError(error, path);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async writeFiles(files) {
|
|
414
|
+
const api = this.sdk().files;
|
|
415
|
+
if (!api.writeFiles)
|
|
416
|
+
return super.writeFiles(files);
|
|
417
|
+
const entries = [];
|
|
418
|
+
for (const file of files)
|
|
419
|
+
entries.push({ path: this.absolute(file.path), data: await toBuffer(file.data) });
|
|
420
|
+
try {
|
|
421
|
+
await api.writeFiles(entries);
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
throw asErrnoError(error, 'writeFiles');
|
|
425
|
+
}
|
|
426
|
+
return entries.map(entry => ({ path: entry.path, name: posix.basename(entry.path) }));
|
|
427
|
+
}
|
|
428
|
+
async list(path, options) {
|
|
429
|
+
const depth = options?.depth ?? 1;
|
|
430
|
+
if (!Number.isInteger(depth) || depth < 1)
|
|
431
|
+
throw new RangeError('depth must be a positive integer');
|
|
432
|
+
try {
|
|
433
|
+
return (await this.sdk().files.list(this.absolute(path), { depth })).map(entryInfo);
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
throw asErrnoError(error, path);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
async rename(oldPath, newPath) {
|
|
440
|
+
const api = this.sdk().files;
|
|
441
|
+
if (!api.rename)
|
|
442
|
+
return super.rename(oldPath, newPath);
|
|
443
|
+
try {
|
|
444
|
+
return entryInfo(await api.rename(this.absolute(oldPath), this.absolute(newPath)));
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
throw asErrnoError(error, oldPath);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async remove(path) {
|
|
451
|
+
const api = this.sdk().files;
|
|
452
|
+
if (!api.remove)
|
|
453
|
+
return super.remove(path);
|
|
454
|
+
try {
|
|
455
|
+
await api.remove(this.absolute(path));
|
|
456
|
+
}
|
|
457
|
+
catch (error) {
|
|
458
|
+
const mapped = asErrnoError(error, path);
|
|
459
|
+
if (mapped.code !== 'ENOENT')
|
|
460
|
+
throw mapped;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
function entryInfo(entry) {
|
|
465
|
+
return { ...entry, name: entry.name, path: entry.path, kind: entry.symlinkTarget !== undefined || entry.type === 'symlink' ? 'symlink' : entry.type ?? 'other', size: entry.size ?? 0, ...mtimeOf(entry) };
|
|
466
|
+
}
|
|
356
467
|
//# sourceMappingURL=environment.js.map
|
package/dist/e2b/lifecycle.js
CHANGED
|
@@ -57,6 +57,14 @@ export class E2BWorkspace {
|
|
|
57
57
|
}
|
|
58
58
|
/** Fork the workspace: snapshot, then start an independent sandbox from that snapshot. */
|
|
59
59
|
async fork() {
|
|
60
|
+
if (this.current.fork) {
|
|
61
|
+
const [clone] = await this.current.fork({ count: 1 });
|
|
62
|
+
if (clone instanceof Error)
|
|
63
|
+
throw clone;
|
|
64
|
+
if (!clone)
|
|
65
|
+
throw new Error('E2B fork returned no sandbox');
|
|
66
|
+
return { environment: new E2BEnvironment(() => clone, this.options), dispose: async () => { await clone.kill(); } };
|
|
67
|
+
}
|
|
60
68
|
const snapshotId = await this.snapshot();
|
|
61
69
|
if (snapshotId === undefined)
|
|
62
70
|
return undefined;
|
|
@@ -28,7 +28,7 @@ export async function readWindowViaShell(environment, absPath, range) {
|
|
|
28
28
|
// The path goes through `$0` rather than string interpolation, so no quoting scheme has to
|
|
29
29
|
// be trusted with a filename containing quotes, spaces or newlines. The numbers are ours.
|
|
30
30
|
const result = await environment
|
|
31
|
-
.run(["sh", "-c", `tail -c +${String(offset + 1)} -- "$0"${cut} | base64`, absPath])
|
|
31
|
+
.commands.run(["sh", "-c", `tail -c +${String(offset + 1)} -- "$0"${cut} | base64`, absPath])
|
|
32
32
|
.catch(() => undefined);
|
|
33
33
|
if (result === undefined || result.exitCode !== 0)
|
|
34
34
|
return undefined;
|
|
@@ -58,7 +58,7 @@ export class SandboxEnvironment extends BaseEnvironment {
|
|
|
58
58
|
const argv = (options?.followSymlinks ?? true)
|
|
59
59
|
? ["stat", "-L", "-c", format, "--", target]
|
|
60
60
|
: ["stat", "-c", format, "--", target];
|
|
61
|
-
const { stdout, exitCode } = await this.run(argv);
|
|
61
|
+
const { stdout, exitCode } = await this.commands.run(argv);
|
|
62
62
|
if (exitCode !== 0)
|
|
63
63
|
throw codedError(`No such file or directory: ${target}`, "ENOENT");
|
|
64
64
|
// Last line only: a shell that prepends a banner would otherwise poison the parse.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "operon-sandbox",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.34",
|
|
4
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": {
|
|
@@ -25,11 +25,11 @@
|
|
|
25
25
|
}
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"operon-agents-core": "0.1.0-alpha.
|
|
28
|
+
"operon-agents-core": "0.1.0-alpha.34"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@cloudflare/sandbox": ">=0.12",
|
|
32
|
-
"e2b": ">=
|
|
32
|
+
"e2b": ">=2.63.0"
|
|
33
33
|
},
|
|
34
34
|
"peerDependenciesMeta": {
|
|
35
35
|
"@cloudflare/sandbox": {
|