@alineo-labs/opensandbox 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +337 -0
- package/dist/index.mjs +492 -0
- package/package.json +38 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
interface Resources {
|
|
3
|
+
cpu?: string;
|
|
4
|
+
memory?: string;
|
|
5
|
+
gpu?: string;
|
|
6
|
+
}
|
|
7
|
+
interface ImageAuth {
|
|
8
|
+
username: string;
|
|
9
|
+
password: string;
|
|
10
|
+
}
|
|
11
|
+
interface ImageSpec {
|
|
12
|
+
uri: string;
|
|
13
|
+
auth?: ImageAuth;
|
|
14
|
+
}
|
|
15
|
+
declare enum SandboxState {
|
|
16
|
+
Pending = "Pending",
|
|
17
|
+
Running = "Running",
|
|
18
|
+
Pausing = "Pausing",
|
|
19
|
+
Paused = "Paused",
|
|
20
|
+
Resuming = "Resuming",
|
|
21
|
+
Stopping = "Stopping",
|
|
22
|
+
Terminated = "Terminated",
|
|
23
|
+
Failed = "Failed",
|
|
24
|
+
Unknown = "Unknown"
|
|
25
|
+
}
|
|
26
|
+
interface SandboxStatus {
|
|
27
|
+
state: SandboxState;
|
|
28
|
+
reason?: string;
|
|
29
|
+
message?: string;
|
|
30
|
+
lastTransitionAt?: string;
|
|
31
|
+
}
|
|
32
|
+
interface Sandbox {
|
|
33
|
+
id: string;
|
|
34
|
+
status: SandboxStatus;
|
|
35
|
+
createdAt: string;
|
|
36
|
+
expiresAt?: string | null;
|
|
37
|
+
image?: ImageSpec;
|
|
38
|
+
snapshotId?: string;
|
|
39
|
+
entrypoint?: string[];
|
|
40
|
+
metadata?: Record<string, string>;
|
|
41
|
+
platform?: unknown;
|
|
42
|
+
}
|
|
43
|
+
interface CreateSandboxOptions {
|
|
44
|
+
image?: ImageSpec;
|
|
45
|
+
snapshotId?: string;
|
|
46
|
+
timeout?: number;
|
|
47
|
+
resourceLimits?: Resources;
|
|
48
|
+
entrypoint?: string[];
|
|
49
|
+
env?: Record<string, string>;
|
|
50
|
+
metadata?: Record<string, string>;
|
|
51
|
+
secureAccess?: boolean;
|
|
52
|
+
}
|
|
53
|
+
interface ListSandboxesOptions {
|
|
54
|
+
state?: SandboxState;
|
|
55
|
+
limit?: number;
|
|
56
|
+
offset?: number;
|
|
57
|
+
}
|
|
58
|
+
declare enum SnapshotState {
|
|
59
|
+
Pending = "Pending",
|
|
60
|
+
Committing = "Committing",
|
|
61
|
+
Pushing = "Pushing",
|
|
62
|
+
Ready = "Ready",
|
|
63
|
+
Failed = "Failed"
|
|
64
|
+
}
|
|
65
|
+
interface Snapshot {
|
|
66
|
+
id: string;
|
|
67
|
+
sandboxId: string;
|
|
68
|
+
state: SnapshotState;
|
|
69
|
+
createdAt: string;
|
|
70
|
+
}
|
|
71
|
+
interface ListSnapshotsOptions {
|
|
72
|
+
sandboxId?: string;
|
|
73
|
+
limit?: number;
|
|
74
|
+
offset?: number;
|
|
75
|
+
}
|
|
76
|
+
interface SandboxEndpoint {
|
|
77
|
+
endpoint: string;
|
|
78
|
+
headers?: Record<string, string>;
|
|
79
|
+
}
|
|
80
|
+
interface DiagnosticLog {
|
|
81
|
+
name: string;
|
|
82
|
+
size: number;
|
|
83
|
+
url?: string;
|
|
84
|
+
inline?: string;
|
|
85
|
+
}
|
|
86
|
+
interface DiagnosticEvent {
|
|
87
|
+
timestamp: string;
|
|
88
|
+
type: string;
|
|
89
|
+
message: string;
|
|
90
|
+
}
|
|
91
|
+
declare enum SSEEventType {
|
|
92
|
+
Init = "init",
|
|
93
|
+
Status = "status",
|
|
94
|
+
Stdout = "stdout",
|
|
95
|
+
Stderr = "stderr",
|
|
96
|
+
Result = "result",
|
|
97
|
+
ExecutionComplete = "execution_complete",
|
|
98
|
+
ExecutionCount = "execution_count",
|
|
99
|
+
Error = "error",
|
|
100
|
+
Ping = "ping",
|
|
101
|
+
Message = "message"
|
|
102
|
+
}
|
|
103
|
+
interface SSEEvent {
|
|
104
|
+
type: SSEEventType;
|
|
105
|
+
text?: string;
|
|
106
|
+
results?: Record<string, string>;
|
|
107
|
+
error?: {
|
|
108
|
+
name?: string;
|
|
109
|
+
message: string;
|
|
110
|
+
evalue?: string;
|
|
111
|
+
};
|
|
112
|
+
execution_count?: number;
|
|
113
|
+
execution_time?: number;
|
|
114
|
+
timestamp: number;
|
|
115
|
+
}
|
|
116
|
+
declare enum CodeLanguage {
|
|
117
|
+
Python = "python",
|
|
118
|
+
JavaScript = "javascript",
|
|
119
|
+
TypeScript = "typescript",
|
|
120
|
+
Go = "go",
|
|
121
|
+
Java = "java",
|
|
122
|
+
Bash = "bash"
|
|
123
|
+
}
|
|
124
|
+
interface CodeContext {
|
|
125
|
+
id: string;
|
|
126
|
+
language: CodeLanguage;
|
|
127
|
+
}
|
|
128
|
+
interface ExecuteCodeOptions {
|
|
129
|
+
code: string;
|
|
130
|
+
context?: {
|
|
131
|
+
id: string;
|
|
132
|
+
language: CodeLanguage;
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
interface ExecuteCommandOptions {
|
|
136
|
+
command: string;
|
|
137
|
+
cwd?: string;
|
|
138
|
+
background?: boolean;
|
|
139
|
+
timeout?: number;
|
|
140
|
+
uid?: number;
|
|
141
|
+
gid?: number;
|
|
142
|
+
envs?: Record<string, string>;
|
|
143
|
+
}
|
|
144
|
+
interface CommandStatus {
|
|
145
|
+
session: string;
|
|
146
|
+
status: "running" | "completed" | "failed";
|
|
147
|
+
exitCode?: number;
|
|
148
|
+
}
|
|
149
|
+
interface FileInfo {
|
|
150
|
+
path: string;
|
|
151
|
+
type: "file" | "directory" | "symlink";
|
|
152
|
+
size: number;
|
|
153
|
+
mode: number;
|
|
154
|
+
modified_at: string;
|
|
155
|
+
created_at: string;
|
|
156
|
+
owner: string;
|
|
157
|
+
group: string;
|
|
158
|
+
}
|
|
159
|
+
interface FileReplacement {
|
|
160
|
+
path: string;
|
|
161
|
+
old: string;
|
|
162
|
+
new: string;
|
|
163
|
+
}
|
|
164
|
+
interface Metrics {
|
|
165
|
+
cpu: number;
|
|
166
|
+
memory: number;
|
|
167
|
+
timestamp: string;
|
|
168
|
+
}
|
|
169
|
+
interface CreateSessionRequest {
|
|
170
|
+
cwd?: string;
|
|
171
|
+
}
|
|
172
|
+
interface RunInSessionRequest {
|
|
173
|
+
command: string;
|
|
174
|
+
cwd?: string;
|
|
175
|
+
timeout?: number;
|
|
176
|
+
}
|
|
177
|
+
interface CreateSessionResponse {
|
|
178
|
+
session_id: string;
|
|
179
|
+
}
|
|
180
|
+
interface CreatePtyOptions {
|
|
181
|
+
cwd?: string;
|
|
182
|
+
command?: string;
|
|
183
|
+
}
|
|
184
|
+
interface CreatePtyResponse {
|
|
185
|
+
session_id: string;
|
|
186
|
+
}
|
|
187
|
+
type PtyClientMessage = {
|
|
188
|
+
type: "stdin";
|
|
189
|
+
data: string;
|
|
190
|
+
} | {
|
|
191
|
+
type: "resize";
|
|
192
|
+
cols: number;
|
|
193
|
+
rows: number;
|
|
194
|
+
} | {
|
|
195
|
+
type: "signal";
|
|
196
|
+
signal: string;
|
|
197
|
+
} | {
|
|
198
|
+
type: "ping";
|
|
199
|
+
};
|
|
200
|
+
type PtyServerMessage = {
|
|
201
|
+
type: "exit";
|
|
202
|
+
exit_code: number;
|
|
203
|
+
} | {
|
|
204
|
+
type: "pong";
|
|
205
|
+
} | {
|
|
206
|
+
type: "connected";
|
|
207
|
+
session_id: string;
|
|
208
|
+
mode: string;
|
|
209
|
+
};
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/control.d.ts
|
|
212
|
+
declare class OpenSandboxError extends Error {
|
|
213
|
+
readonly status: number;
|
|
214
|
+
constructor(message: string, status: number);
|
|
215
|
+
}
|
|
216
|
+
declare class ControlClient {
|
|
217
|
+
private baseUrl;
|
|
218
|
+
private apiKey;
|
|
219
|
+
private signal?;
|
|
220
|
+
constructor(options: {
|
|
221
|
+
baseUrl: string;
|
|
222
|
+
apiKey: string;
|
|
223
|
+
signal?: AbortSignal;
|
|
224
|
+
});
|
|
225
|
+
/** Return a new `ControlClient` instance that passes `signal` to every fetch call. */
|
|
226
|
+
withSignal(signal: AbortSignal): ControlClient;
|
|
227
|
+
private request;
|
|
228
|
+
createSandbox(options: CreateSandboxOptions): Promise<Sandbox>;
|
|
229
|
+
listSandboxes(options?: ListSandboxesOptions): Promise<Sandbox[]>;
|
|
230
|
+
getSandbox(id: string): Promise<Sandbox>;
|
|
231
|
+
deleteSandbox(id: string): Promise<void>;
|
|
232
|
+
pauseSandbox(id: string): Promise<void>;
|
|
233
|
+
resumeSandbox(id: string): Promise<void>;
|
|
234
|
+
renewExpiration(id: string): Promise<void>;
|
|
235
|
+
getEndpoint(sandboxId: string, port: number, useServerProxy?: boolean): Promise<SandboxEndpoint>;
|
|
236
|
+
getDiagnosticLogs(sandboxId: string): Promise<DiagnosticLog[]>;
|
|
237
|
+
getDiagnosticEvents(sandboxId: string): Promise<DiagnosticEvent[]>;
|
|
238
|
+
createSnapshot(sandboxId: string): Promise<Snapshot>;
|
|
239
|
+
listSnapshots(options?: ListSnapshotsOptions): Promise<Snapshot[]>;
|
|
240
|
+
getSnapshot(id: string): Promise<Snapshot>;
|
|
241
|
+
deleteSnapshot(id: string): Promise<void>;
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/exec.d.ts
|
|
245
|
+
declare class ExecClient {
|
|
246
|
+
private baseUrl;
|
|
247
|
+
private accessToken;
|
|
248
|
+
private signal?;
|
|
249
|
+
/** Readers left dangling by `parseSSE`'s early-return optimization — see `disposeConnections()`. */
|
|
250
|
+
private pendingReaders;
|
|
251
|
+
constructor(options: {
|
|
252
|
+
baseUrl?: string;
|
|
253
|
+
accessToken: string;
|
|
254
|
+
signal?: AbortSignal;
|
|
255
|
+
});
|
|
256
|
+
/** Return a new `ExecClient` instance that passes `signal` to every fetch call. */
|
|
257
|
+
withSignal(signal: AbortSignal): ExecClient;
|
|
258
|
+
/**
|
|
259
|
+
* Force-cancel any exec streams `parseSSE` deliberately left open (its early return
|
|
260
|
+
* on `isTerminal`, to dodge OpenSandbox#1277's proxy behavior — see its comment).
|
|
261
|
+
* Those connections sit ESTABLISHED, keeping Bun's event loop alive, until execd's
|
|
262
|
+
* own fixed post-completion sleep elapses server-side; calling this once the sandbox
|
|
263
|
+
* is being torn down anyway (e.g. from `Sandbox.close()`) skips that wait instead of
|
|
264
|
+
* leaving the process to hang on whichever exec's delay hadn't yet elapsed.
|
|
265
|
+
*/
|
|
266
|
+
disposeConnections(): void;
|
|
267
|
+
private get authHeader();
|
|
268
|
+
private request;
|
|
269
|
+
private streamRequest;
|
|
270
|
+
ping(): Promise<{
|
|
271
|
+
status: string;
|
|
272
|
+
}>;
|
|
273
|
+
listContexts(language?: string): Promise<CodeContext[]>;
|
|
274
|
+
clearContexts(language?: string): Promise<void>;
|
|
275
|
+
deleteContext(contextId: string): Promise<void>;
|
|
276
|
+
createContext(language: string): Promise<CodeContext>;
|
|
277
|
+
executeCode(options: ExecuteCodeOptions): AsyncGenerator<SSEEvent>;
|
|
278
|
+
interruptCode(): Promise<void>;
|
|
279
|
+
executeCommand(options: ExecuteCommandOptions): AsyncGenerator<SSEEvent>;
|
|
280
|
+
interruptCommand(): Promise<void>;
|
|
281
|
+
getCommandStatus(session: string): Promise<CommandStatus>;
|
|
282
|
+
getCommandOutput(session: string): Promise<{
|
|
283
|
+
stdout: string;
|
|
284
|
+
stderr: string;
|
|
285
|
+
}>;
|
|
286
|
+
getFileInfo(path: string): Promise<FileInfo>;
|
|
287
|
+
deleteFile(path: string): Promise<void>;
|
|
288
|
+
setPermissions(path: string, mode: string): Promise<void>;
|
|
289
|
+
moveFile(from: string, to: string): Promise<void>;
|
|
290
|
+
searchFiles(pattern: string, path?: string): Promise<string[]>;
|
|
291
|
+
replaceInFiles(replacements: FileReplacement[]): Promise<void>;
|
|
292
|
+
uploadFile(path: string, content: Blob | BufferSource | string): Promise<void>;
|
|
293
|
+
downloadFile(path: string): Promise<ReadableStream<Uint8Array>>;
|
|
294
|
+
listDirectory(path: string, depth?: number): Promise<FileInfo[]>;
|
|
295
|
+
createDirectory(path: string): Promise<void>;
|
|
296
|
+
deleteDirectory(path: string): Promise<void>;
|
|
297
|
+
getMetrics(): Promise<Metrics>;
|
|
298
|
+
watchMetrics(): AsyncGenerator<SSEEvent>;
|
|
299
|
+
createSession(opts?: CreateSessionRequest): Promise<CreateSessionResponse>;
|
|
300
|
+
runInSession(sessionId: string, opts: RunInSessionRequest): AsyncGenerator<SSEEvent>;
|
|
301
|
+
deleteSession(sessionId: string): Promise<void>;
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
//#region src/pty.d.ts
|
|
305
|
+
type PtyOutputListener = (chunk: string) => void;
|
|
306
|
+
type PtyExitListener = (exitCode: number) => void;
|
|
307
|
+
/**
|
|
308
|
+
* Wraps execd's `/pty` REST + WebSocket protocol.
|
|
309
|
+
*
|
|
310
|
+
* One instance per live interactive session: `create()` opens the session,
|
|
311
|
+
* `connect()` opens the WebSocket and starts dispatching output/exit
|
|
312
|
+
* callbacks, `write()`/`resize()`/`signal()` send input, `close()` tears
|
|
313
|
+
* down the socket.
|
|
314
|
+
*/
|
|
315
|
+
declare class PtyClient {
|
|
316
|
+
private readonly baseUrl;
|
|
317
|
+
private readonly accessToken;
|
|
318
|
+
private ws;
|
|
319
|
+
constructor(options: {
|
|
320
|
+
baseUrl: string;
|
|
321
|
+
accessToken: string;
|
|
322
|
+
});
|
|
323
|
+
create(opts?: CreatePtyOptions): Promise<string>;
|
|
324
|
+
/**
|
|
325
|
+
* Open the WebSocket for a session created via `create()`. Resolves once the connection is open.
|
|
326
|
+
* `onExit` fires with the real exit code on a normal `{"type":"exit"}` frame, or with `-1` if
|
|
327
|
+
* the socket closes for any other reason (network drop, container restart, etc.) — callers
|
|
328
|
+
* should not treat `-1` as a real process exit code.
|
|
329
|
+
*/
|
|
330
|
+
connect(sessionId: string, onOutput: PtyOutputListener, onExit: PtyExitListener): Promise<void>;
|
|
331
|
+
write(data: string): void;
|
|
332
|
+
resize(cols: number, rows: number): void;
|
|
333
|
+
signal(name: string): void;
|
|
334
|
+
close(): void;
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
export { type CodeContext, CodeLanguage, type CommandStatus, ControlClient, type CreatePtyOptions, type CreatePtyResponse, type CreateSandboxOptions, type CreateSessionRequest, type CreateSessionResponse, type DiagnosticEvent, type DiagnosticLog, ExecClient, type ExecuteCodeOptions, type ExecuteCommandOptions, type FileInfo, type FileReplacement, type ImageAuth, type ImageSpec, type ListSandboxesOptions, type ListSnapshotsOptions, type Metrics, OpenSandboxError, PtyClient, type PtyClientMessage, type PtyExitListener, type PtyOutputListener, type PtyServerMessage, type Resources, type RunInSessionRequest, type SSEEvent, SSEEventType, type Sandbox, type SandboxEndpoint, SandboxState, type SandboxStatus, type Snapshot, SnapshotState };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
//#region src/control.ts
|
|
2
|
+
function flattenSnapshot(raw) {
|
|
3
|
+
return {
|
|
4
|
+
id: raw.id,
|
|
5
|
+
sandboxId: raw.sandboxId,
|
|
6
|
+
state: raw.status.state,
|
|
7
|
+
createdAt: raw.createdAt
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
var OpenSandboxError = class extends Error {
|
|
11
|
+
status;
|
|
12
|
+
constructor(message, status) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.name = "OpenSandboxError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
var ControlClient = class ControlClient {
|
|
19
|
+
baseUrl;
|
|
20
|
+
apiKey;
|
|
21
|
+
signal;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
24
|
+
this.apiKey = options.apiKey;
|
|
25
|
+
this.signal = options.signal;
|
|
26
|
+
}
|
|
27
|
+
/** Return a new `ControlClient` instance that passes `signal` to every fetch call. */
|
|
28
|
+
withSignal(signal) {
|
|
29
|
+
return new ControlClient({
|
|
30
|
+
baseUrl: this.baseUrl,
|
|
31
|
+
apiKey: this.apiKey,
|
|
32
|
+
signal
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
async request(method, path, body) {
|
|
36
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
37
|
+
method,
|
|
38
|
+
headers: {
|
|
39
|
+
"OPEN-SANDBOX-API-KEY": this.apiKey,
|
|
40
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {}
|
|
41
|
+
},
|
|
42
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
43
|
+
signal: this.signal
|
|
44
|
+
});
|
|
45
|
+
if (!res.ok) throw new OpenSandboxError(await res.text().catch(() => "") || "OpenSandbox API error", res.status);
|
|
46
|
+
if (res.status === 204) return void 0;
|
|
47
|
+
return res.json();
|
|
48
|
+
}
|
|
49
|
+
createSandbox(options) {
|
|
50
|
+
return this.request("POST", "/v1/sandboxes", options);
|
|
51
|
+
}
|
|
52
|
+
async listSandboxes(options = {}) {
|
|
53
|
+
const params = new URLSearchParams();
|
|
54
|
+
if (options.state) params.set("state", options.state);
|
|
55
|
+
if (options.limit !== void 0) params.set("limit", String(options.limit));
|
|
56
|
+
if (options.offset !== void 0) params.set("offset", String(options.offset));
|
|
57
|
+
const qs = params.toString();
|
|
58
|
+
return (await this.request("GET", `/v1/sandboxes${qs ? `?${qs}` : ""}`)).items;
|
|
59
|
+
}
|
|
60
|
+
getSandbox(id) {
|
|
61
|
+
return this.request("GET", `/v1/sandboxes/${id}`);
|
|
62
|
+
}
|
|
63
|
+
deleteSandbox(id) {
|
|
64
|
+
return this.request("DELETE", `/v1/sandboxes/${id}`);
|
|
65
|
+
}
|
|
66
|
+
pauseSandbox(id) {
|
|
67
|
+
return this.request("POST", `/v1/sandboxes/${id}/pause`);
|
|
68
|
+
}
|
|
69
|
+
resumeSandbox(id) {
|
|
70
|
+
return this.request("POST", `/v1/sandboxes/${id}/resume`);
|
|
71
|
+
}
|
|
72
|
+
renewExpiration(id) {
|
|
73
|
+
return this.request("POST", `/v1/sandboxes/${id}/renew-expiration`);
|
|
74
|
+
}
|
|
75
|
+
getEndpoint(sandboxId, port, useServerProxy) {
|
|
76
|
+
const qs = useServerProxy ? "?use_server_proxy=true" : "";
|
|
77
|
+
return this.request("GET", `/v1/sandboxes/${sandboxId}/endpoints/${port}${qs}`);
|
|
78
|
+
}
|
|
79
|
+
getDiagnosticLogs(sandboxId) {
|
|
80
|
+
return this.request("GET", `/v1/sandboxes/${sandboxId}/diagnostics/logs`);
|
|
81
|
+
}
|
|
82
|
+
getDiagnosticEvents(sandboxId) {
|
|
83
|
+
return this.request("GET", `/v1/sandboxes/${sandboxId}/diagnostics/events`);
|
|
84
|
+
}
|
|
85
|
+
async createSnapshot(sandboxId) {
|
|
86
|
+
return flattenSnapshot(await this.request("POST", `/v1/sandboxes/${sandboxId}/snapshots`));
|
|
87
|
+
}
|
|
88
|
+
async listSnapshots(options = {}) {
|
|
89
|
+
const params = new URLSearchParams();
|
|
90
|
+
if (options.sandboxId) params.set("sandboxId", options.sandboxId);
|
|
91
|
+
if (options.limit !== void 0) params.set("limit", String(options.limit));
|
|
92
|
+
if (options.offset !== void 0) params.set("offset", String(options.offset));
|
|
93
|
+
const qs = params.toString();
|
|
94
|
+
return (await this.request("GET", `/v1/snapshots${qs ? `?${qs}` : ""}`)).items.map(flattenSnapshot);
|
|
95
|
+
}
|
|
96
|
+
async getSnapshot(id) {
|
|
97
|
+
return flattenSnapshot(await this.request("GET", `/v1/snapshots/${id}`));
|
|
98
|
+
}
|
|
99
|
+
deleteSnapshot(id) {
|
|
100
|
+
return this.request("DELETE", `/v1/snapshots/${id}`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/types.ts
|
|
105
|
+
let SandboxState = /* @__PURE__ */ function(SandboxState) {
|
|
106
|
+
SandboxState["Pending"] = "Pending";
|
|
107
|
+
SandboxState["Running"] = "Running";
|
|
108
|
+
SandboxState["Pausing"] = "Pausing";
|
|
109
|
+
SandboxState["Paused"] = "Paused";
|
|
110
|
+
SandboxState["Resuming"] = "Resuming";
|
|
111
|
+
SandboxState["Stopping"] = "Stopping";
|
|
112
|
+
SandboxState["Terminated"] = "Terminated";
|
|
113
|
+
SandboxState["Failed"] = "Failed";
|
|
114
|
+
SandboxState["Unknown"] = "Unknown";
|
|
115
|
+
return SandboxState;
|
|
116
|
+
}({});
|
|
117
|
+
let SnapshotState = /* @__PURE__ */ function(SnapshotState) {
|
|
118
|
+
SnapshotState["Pending"] = "Pending";
|
|
119
|
+
SnapshotState["Committing"] = "Committing";
|
|
120
|
+
SnapshotState["Pushing"] = "Pushing";
|
|
121
|
+
SnapshotState["Ready"] = "Ready";
|
|
122
|
+
SnapshotState["Failed"] = "Failed";
|
|
123
|
+
return SnapshotState;
|
|
124
|
+
}({});
|
|
125
|
+
let SSEEventType = /* @__PURE__ */ function(SSEEventType) {
|
|
126
|
+
SSEEventType["Init"] = "init";
|
|
127
|
+
SSEEventType["Status"] = "status";
|
|
128
|
+
SSEEventType["Stdout"] = "stdout";
|
|
129
|
+
SSEEventType["Stderr"] = "stderr";
|
|
130
|
+
SSEEventType["Result"] = "result";
|
|
131
|
+
SSEEventType["ExecutionComplete"] = "execution_complete";
|
|
132
|
+
SSEEventType["ExecutionCount"] = "execution_count";
|
|
133
|
+
SSEEventType["Error"] = "error";
|
|
134
|
+
SSEEventType["Ping"] = "ping";
|
|
135
|
+
SSEEventType["Message"] = "message";
|
|
136
|
+
return SSEEventType;
|
|
137
|
+
}({});
|
|
138
|
+
let CodeLanguage = /* @__PURE__ */ function(CodeLanguage) {
|
|
139
|
+
CodeLanguage["Python"] = "python";
|
|
140
|
+
CodeLanguage["JavaScript"] = "javascript";
|
|
141
|
+
CodeLanguage["TypeScript"] = "typescript";
|
|
142
|
+
CodeLanguage["Go"] = "go";
|
|
143
|
+
CodeLanguage["Java"] = "java";
|
|
144
|
+
CodeLanguage["Bash"] = "bash";
|
|
145
|
+
return CodeLanguage;
|
|
146
|
+
}({});
|
|
147
|
+
//#endregion
|
|
148
|
+
//#region src/exec.ts
|
|
149
|
+
/**
|
|
150
|
+
* `isTerminal` lets one-shot command/code streams cancel the underlying
|
|
151
|
+
* connection as soon as their terminal event arrives, instead of reading to
|
|
152
|
+
* EOF: execd holds the HTTP stream open for a fixed interval after the last
|
|
153
|
+
* event is sent (a server-side post-completion sleep — see
|
|
154
|
+
* opensandbox-group/OpenSandbox#1277: `/command`'s handler does a blind
|
|
155
|
+
* `time.Sleep` instead of signalling completion the way `/code` and
|
|
156
|
+
* `/session/:id/run` do), so waiting for `done` tacks that delay onto every
|
|
157
|
+
* exec. Long-lived streams (metrics watch) pass no predicate and read until
|
|
158
|
+
* the server actually closes the connection.
|
|
159
|
+
*
|
|
160
|
+
* `pendingReaders` lets the owning `ExecClient` force these dangling readers
|
|
161
|
+
* shut later (see `disposeConnections()`) instead of leaving them open until
|
|
162
|
+
* the server's own delayed close — see that method's doc comment for why.
|
|
163
|
+
*/
|
|
164
|
+
async function* parseSSE(stream, pendingReaders, isTerminal) {
|
|
165
|
+
const reader = stream.getReader();
|
|
166
|
+
pendingReaders.add(reader);
|
|
167
|
+
const decoder = new TextDecoder();
|
|
168
|
+
let buffer = "";
|
|
169
|
+
let terminatedEarly = false;
|
|
170
|
+
try {
|
|
171
|
+
while (true) {
|
|
172
|
+
const { done, value } = await reader.read();
|
|
173
|
+
if (done) break;
|
|
174
|
+
buffer += decoder.decode(value, { stream: true });
|
|
175
|
+
const blocks = buffer.split("\n\n");
|
|
176
|
+
buffer = blocks.pop() ?? "";
|
|
177
|
+
for (const block of blocks) {
|
|
178
|
+
const trimmed = block.trim();
|
|
179
|
+
if (!trimmed) continue;
|
|
180
|
+
let event;
|
|
181
|
+
if (trimmed.startsWith("{")) try {
|
|
182
|
+
event = JSON.parse(trimmed);
|
|
183
|
+
} catch {
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
let type;
|
|
188
|
+
let data;
|
|
189
|
+
for (const line of block.split("\n")) if (line.startsWith("event:")) type = line.slice(6).trim();
|
|
190
|
+
else if (line.startsWith("data:")) data = line.slice(5).trim();
|
|
191
|
+
if (data !== void 0) event = {
|
|
192
|
+
type: type ?? "message",
|
|
193
|
+
...JSON.parse(data)
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (!event) continue;
|
|
197
|
+
yield event;
|
|
198
|
+
if (isTerminal?.(event)) {
|
|
199
|
+
terminatedEarly = true;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
} finally {
|
|
205
|
+
if (!terminatedEarly) {
|
|
206
|
+
pendingReaders.delete(reader);
|
|
207
|
+
reader.releaseLock();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function isExecTerminal(event) {
|
|
212
|
+
return event.type === "execution_complete" || event.type === "error";
|
|
213
|
+
}
|
|
214
|
+
var ExecClient = class ExecClient {
|
|
215
|
+
baseUrl;
|
|
216
|
+
accessToken;
|
|
217
|
+
signal;
|
|
218
|
+
/** Readers left dangling by `parseSSE`'s early-return optimization — see `disposeConnections()`. */
|
|
219
|
+
pendingReaders = /* @__PURE__ */ new Set();
|
|
220
|
+
constructor(options) {
|
|
221
|
+
this.baseUrl = (options.baseUrl ?? "http://localhost:44772").replace(/\/$/, "");
|
|
222
|
+
this.accessToken = options.accessToken;
|
|
223
|
+
this.signal = options.signal;
|
|
224
|
+
}
|
|
225
|
+
/** Return a new `ExecClient` instance that passes `signal` to every fetch call. */
|
|
226
|
+
withSignal(signal) {
|
|
227
|
+
return new ExecClient({
|
|
228
|
+
baseUrl: this.baseUrl,
|
|
229
|
+
accessToken: this.accessToken,
|
|
230
|
+
signal
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Force-cancel any exec streams `parseSSE` deliberately left open (its early return
|
|
235
|
+
* on `isTerminal`, to dodge OpenSandbox#1277's proxy behavior — see its comment).
|
|
236
|
+
* Those connections sit ESTABLISHED, keeping Bun's event loop alive, until execd's
|
|
237
|
+
* own fixed post-completion sleep elapses server-side; calling this once the sandbox
|
|
238
|
+
* is being torn down anyway (e.g. from `Sandbox.close()`) skips that wait instead of
|
|
239
|
+
* leaving the process to hang on whichever exec's delay hadn't yet elapsed.
|
|
240
|
+
*/
|
|
241
|
+
disposeConnections() {
|
|
242
|
+
for (const reader of this.pendingReaders) reader.cancel().catch(() => {});
|
|
243
|
+
this.pendingReaders.clear();
|
|
244
|
+
}
|
|
245
|
+
get authHeader() {
|
|
246
|
+
return { "X-EXECD-ACCESS-TOKEN": this.accessToken };
|
|
247
|
+
}
|
|
248
|
+
async request(method, path, body) {
|
|
249
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
250
|
+
method,
|
|
251
|
+
headers: {
|
|
252
|
+
...this.authHeader,
|
|
253
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {}
|
|
254
|
+
},
|
|
255
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
256
|
+
signal: this.signal
|
|
257
|
+
});
|
|
258
|
+
if (!res.ok) {
|
|
259
|
+
const text = await res.text().catch(() => "");
|
|
260
|
+
throw new Error(text || `execd error ${res.status}`);
|
|
261
|
+
}
|
|
262
|
+
if (res.status === 204) return void 0;
|
|
263
|
+
return res.json();
|
|
264
|
+
}
|
|
265
|
+
async *streamRequest(method, path, body, isTerminal) {
|
|
266
|
+
const res = await fetch(`${this.baseUrl}${path}`, {
|
|
267
|
+
method,
|
|
268
|
+
headers: {
|
|
269
|
+
...this.authHeader,
|
|
270
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {}
|
|
271
|
+
},
|
|
272
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
273
|
+
signal: this.signal
|
|
274
|
+
});
|
|
275
|
+
if (!res.ok) {
|
|
276
|
+
const text = await res.text().catch(() => "");
|
|
277
|
+
throw new Error(text || `execd error ${res.status}`);
|
|
278
|
+
}
|
|
279
|
+
if (!res.body) return;
|
|
280
|
+
yield* parseSSE(res.body, this.pendingReaders, isTerminal);
|
|
281
|
+
}
|
|
282
|
+
ping() {
|
|
283
|
+
return this.request("GET", "/ping");
|
|
284
|
+
}
|
|
285
|
+
listContexts(language) {
|
|
286
|
+
const qs = language ? `?language=${encodeURIComponent(language)}` : "";
|
|
287
|
+
return this.request("GET", `/code/contexts${qs}`);
|
|
288
|
+
}
|
|
289
|
+
clearContexts(language) {
|
|
290
|
+
const qs = language ? `?language=${encodeURIComponent(language)}` : "";
|
|
291
|
+
return this.request("DELETE", `/code/contexts${qs}`);
|
|
292
|
+
}
|
|
293
|
+
deleteContext(contextId) {
|
|
294
|
+
return this.request("DELETE", `/code/contexts/${contextId}`);
|
|
295
|
+
}
|
|
296
|
+
createContext(language) {
|
|
297
|
+
return this.request("POST", "/code/context", { language });
|
|
298
|
+
}
|
|
299
|
+
async *executeCode(options) {
|
|
300
|
+
yield* this.streamRequest("POST", "/code", options, isExecTerminal);
|
|
301
|
+
}
|
|
302
|
+
interruptCode() {
|
|
303
|
+
return this.request("DELETE", "/code");
|
|
304
|
+
}
|
|
305
|
+
async *executeCommand(options) {
|
|
306
|
+
yield* this.streamRequest("POST", "/command", options, isExecTerminal);
|
|
307
|
+
}
|
|
308
|
+
interruptCommand() {
|
|
309
|
+
return this.request("DELETE", "/command");
|
|
310
|
+
}
|
|
311
|
+
getCommandStatus(session) {
|
|
312
|
+
return this.request("GET", `/command/status/${session}`);
|
|
313
|
+
}
|
|
314
|
+
getCommandOutput(session) {
|
|
315
|
+
return this.request("GET", `/command/output/${session}`);
|
|
316
|
+
}
|
|
317
|
+
async getFileInfo(path) {
|
|
318
|
+
const entry = (await this.request("GET", `/files/info?path=${encodeURIComponent(path)}`))[path];
|
|
319
|
+
if (!entry) throw new Error(`getFileInfo: no entry for path ${path}`);
|
|
320
|
+
return entry;
|
|
321
|
+
}
|
|
322
|
+
deleteFile(path) {
|
|
323
|
+
return this.request("DELETE", `/files?path=${encodeURIComponent(path)}`);
|
|
324
|
+
}
|
|
325
|
+
setPermissions(path, mode) {
|
|
326
|
+
return this.request("POST", "/files/permissions", { [path]: { mode: parseInt(mode, 10) } });
|
|
327
|
+
}
|
|
328
|
+
moveFile(from, to) {
|
|
329
|
+
return this.request("POST", "/files/mv", [{
|
|
330
|
+
src: from,
|
|
331
|
+
dest: to
|
|
332
|
+
}]);
|
|
333
|
+
}
|
|
334
|
+
async searchFiles(pattern, path = "/") {
|
|
335
|
+
const params = new URLSearchParams({
|
|
336
|
+
path,
|
|
337
|
+
pattern
|
|
338
|
+
});
|
|
339
|
+
return (await this.request("GET", `/files/search?${params}`)).map((e) => e.path);
|
|
340
|
+
}
|
|
341
|
+
replaceInFiles(replacements) {
|
|
342
|
+
const body = {};
|
|
343
|
+
for (const r of replacements) body[r.path] = {
|
|
344
|
+
old: r.old,
|
|
345
|
+
new: r.new
|
|
346
|
+
};
|
|
347
|
+
return this.request("POST", "/files/replace", body);
|
|
348
|
+
}
|
|
349
|
+
async uploadFile(path, content) {
|
|
350
|
+
const formData = new FormData();
|
|
351
|
+
formData.append("metadata", new File([JSON.stringify({ path })], "metadata.json", { type: "application/json" }));
|
|
352
|
+
formData.append("file", new File([content], path.split("/").pop() ?? "file", { type: "application/octet-stream" }));
|
|
353
|
+
const res = await fetch(`${this.baseUrl}/files/upload`, {
|
|
354
|
+
method: "POST",
|
|
355
|
+
headers: this.authHeader,
|
|
356
|
+
body: formData,
|
|
357
|
+
signal: this.signal
|
|
358
|
+
});
|
|
359
|
+
if (!res.ok) {
|
|
360
|
+
const text = await res.text().catch(() => "");
|
|
361
|
+
throw new Error(text || `execd error ${res.status}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async downloadFile(path) {
|
|
365
|
+
const res = await fetch(`${this.baseUrl}/files/download?path=${encodeURIComponent(path)}`, {
|
|
366
|
+
headers: this.authHeader,
|
|
367
|
+
signal: this.signal
|
|
368
|
+
});
|
|
369
|
+
if (!res.ok) throw new Error(`execd error ${res.status}`);
|
|
370
|
+
if (!res.body) throw new Error("empty response body");
|
|
371
|
+
return res.body;
|
|
372
|
+
}
|
|
373
|
+
listDirectory(path, depth) {
|
|
374
|
+
const params = new URLSearchParams({ path });
|
|
375
|
+
if (depth !== void 0) params.set("depth", String(depth));
|
|
376
|
+
return this.request("GET", `/directories/list?${params}`);
|
|
377
|
+
}
|
|
378
|
+
createDirectory(path) {
|
|
379
|
+
return this.request("POST", "/directories", { [path]: { mode: 755 } });
|
|
380
|
+
}
|
|
381
|
+
deleteDirectory(path) {
|
|
382
|
+
return this.request("DELETE", `/directories?path=${encodeURIComponent(path)}`);
|
|
383
|
+
}
|
|
384
|
+
getMetrics() {
|
|
385
|
+
return this.request("GET", "/metrics");
|
|
386
|
+
}
|
|
387
|
+
async *watchMetrics() {
|
|
388
|
+
yield* this.streamRequest("GET", "/metrics/watch");
|
|
389
|
+
}
|
|
390
|
+
createSession(opts) {
|
|
391
|
+
return this.request("POST", "/session", opts ?? {});
|
|
392
|
+
}
|
|
393
|
+
async *runInSession(sessionId, opts) {
|
|
394
|
+
yield* this.streamRequest("POST", `/session/${sessionId}/run`, opts, isExecTerminal);
|
|
395
|
+
}
|
|
396
|
+
deleteSession(sessionId) {
|
|
397
|
+
return this.request("DELETE", `/session/${sessionId}`);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/pty.ts
|
|
402
|
+
/**
|
|
403
|
+
* Wraps execd's `/pty` REST + WebSocket protocol.
|
|
404
|
+
*
|
|
405
|
+
* One instance per live interactive session: `create()` opens the session,
|
|
406
|
+
* `connect()` opens the WebSocket and starts dispatching output/exit
|
|
407
|
+
* callbacks, `write()`/`resize()`/`signal()` send input, `close()` tears
|
|
408
|
+
* down the socket.
|
|
409
|
+
*/
|
|
410
|
+
var PtyClient = class {
|
|
411
|
+
baseUrl;
|
|
412
|
+
accessToken;
|
|
413
|
+
ws = null;
|
|
414
|
+
constructor(options) {
|
|
415
|
+
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
416
|
+
this.accessToken = options.accessToken;
|
|
417
|
+
}
|
|
418
|
+
async create(opts = {}) {
|
|
419
|
+
const res = await fetch(`${this.baseUrl}/pty`, {
|
|
420
|
+
method: "POST",
|
|
421
|
+
headers: {
|
|
422
|
+
"Content-Type": "application/json",
|
|
423
|
+
"X-EXECD-ACCESS-TOKEN": this.accessToken
|
|
424
|
+
},
|
|
425
|
+
body: JSON.stringify(opts)
|
|
426
|
+
});
|
|
427
|
+
if (!res.ok) {
|
|
428
|
+
const text = await res.text().catch(() => "");
|
|
429
|
+
throw new Error(text || `execd error ${res.status}`);
|
|
430
|
+
}
|
|
431
|
+
const { session_id } = await res.json();
|
|
432
|
+
return session_id;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Open the WebSocket for a session created via `create()`. Resolves once the connection is open.
|
|
436
|
+
* `onExit` fires with the real exit code on a normal `{"type":"exit"}` frame, or with `-1` if
|
|
437
|
+
* the socket closes for any other reason (network drop, container restart, etc.) — callers
|
|
438
|
+
* should not treat `-1` as a real process exit code.
|
|
439
|
+
*/
|
|
440
|
+
connect(sessionId, onOutput, onExit) {
|
|
441
|
+
const url = `${this.baseUrl.replace(/^http/, "ws")}/pty/${sessionId}/ws?token=${encodeURIComponent(this.accessToken)}`;
|
|
442
|
+
const ws = new WebSocket(url);
|
|
443
|
+
ws.binaryType = "arraybuffer";
|
|
444
|
+
this.ws = ws;
|
|
445
|
+
const decoder = new TextDecoder();
|
|
446
|
+
let gotExitFrame = false;
|
|
447
|
+
return new Promise((resolve, reject) => {
|
|
448
|
+
ws.onopen = () => resolve();
|
|
449
|
+
ws.onerror = (ev) => reject(/* @__PURE__ */ new Error(`pty websocket error: ${String(ev)}`));
|
|
450
|
+
ws.onclose = () => {
|
|
451
|
+
if (!gotExitFrame) onExit(-1);
|
|
452
|
+
};
|
|
453
|
+
ws.onmessage = (ev) => {
|
|
454
|
+
if (typeof ev.data === "string") {
|
|
455
|
+
const msg = JSON.parse(ev.data);
|
|
456
|
+
if (msg.type === "exit") {
|
|
457
|
+
gotExitFrame = true;
|
|
458
|
+
onExit(msg.exit_code);
|
|
459
|
+
}
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const bytes = new Uint8Array(ev.data);
|
|
463
|
+
onOutput(decoder.decode(bytes.slice(1)));
|
|
464
|
+
};
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
write(data) {
|
|
468
|
+
this.ws?.send(JSON.stringify({
|
|
469
|
+
type: "stdin",
|
|
470
|
+
data
|
|
471
|
+
}));
|
|
472
|
+
}
|
|
473
|
+
resize(cols, rows) {
|
|
474
|
+
this.ws?.send(JSON.stringify({
|
|
475
|
+
type: "resize",
|
|
476
|
+
cols,
|
|
477
|
+
rows
|
|
478
|
+
}));
|
|
479
|
+
}
|
|
480
|
+
signal(name) {
|
|
481
|
+
this.ws?.send(JSON.stringify({
|
|
482
|
+
type: "signal",
|
|
483
|
+
signal: name
|
|
484
|
+
}));
|
|
485
|
+
}
|
|
486
|
+
close() {
|
|
487
|
+
this.ws?.close();
|
|
488
|
+
this.ws = null;
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
//#endregion
|
|
492
|
+
export { CodeLanguage, ControlClient, ExecClient, OpenSandboxError, PtyClient, SSEEventType, SandboxState, SnapshotState };
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@alineo-labs/opensandbox",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/DrejT/alineo.git",
|
|
8
|
+
"directory": "packages/opensandbox"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "./dist/index.mjs",
|
|
15
|
+
"types": "./dist/index.d.mts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"import": "./dist/index.mjs",
|
|
19
|
+
"types": "./dist/index.d.mts"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public",
|
|
24
|
+
"provenance": true
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsdown",
|
|
28
|
+
"typecheck": "bunx tsc --noEmit",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"test:watch": "vitest"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"bun-types": "1.3.14",
|
|
34
|
+
"tsdown": "0.22.3",
|
|
35
|
+
"typescript": "6.0.3",
|
|
36
|
+
"vitest": "4.1.9"
|
|
37
|
+
}
|
|
38
|
+
}
|