@alineo-labs/opensandbox 0.3.1 → 0.4.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 +102 -15
- package/dist/index.mjs +425 -43
- package/package.json +5 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { AlineoError, ErrorCode } from "@alineo-labs/errors";
|
|
2
|
+
import { CodeLanguage, CodeLanguage as CodeLanguage$1, CreateSandboxRequest, EgressChannel, ExecChannel, ListSandboxesFilter, PtyChannel, SandboxInfo, SandboxProvider, SandboxProviderDescriptor, SandboxState as SandboxState$1, SnapshotInfo, SnapshotState as SnapshotState$1 } from "@alineo-labs/provider";
|
|
1
3
|
//#region src/types.d.ts
|
|
2
4
|
interface Resources {
|
|
3
5
|
cpu?: string;
|
|
@@ -140,28 +142,24 @@ interface SSEEvent {
|
|
|
140
142
|
name?: string;
|
|
141
143
|
message: string;
|
|
142
144
|
evalue?: string;
|
|
145
|
+
/** execd's error class, e.g. `CommandExecError`. Present on a command that did not exit 0. */
|
|
146
|
+
ename?: string;
|
|
147
|
+
/** For a command: `["exit status 3"]`, or `["signal: killed"]` when it was killed. */
|
|
148
|
+
traceback?: string[];
|
|
143
149
|
};
|
|
144
150
|
execution_count?: number;
|
|
145
151
|
execution_time?: number;
|
|
146
152
|
timestamp: number;
|
|
147
153
|
}
|
|
148
|
-
export declare enum CodeLanguage {
|
|
149
|
-
Python = "python",
|
|
150
|
-
JavaScript = "javascript",
|
|
151
|
-
TypeScript = "typescript",
|
|
152
|
-
Go = "go",
|
|
153
|
-
Java = "java",
|
|
154
|
-
Bash = "bash"
|
|
155
|
-
}
|
|
156
154
|
interface CodeContext {
|
|
157
155
|
id: string;
|
|
158
|
-
language: CodeLanguage;
|
|
156
|
+
language: CodeLanguage$1;
|
|
159
157
|
}
|
|
160
158
|
interface ExecuteCodeOptions {
|
|
161
159
|
code: string;
|
|
162
160
|
context?: {
|
|
163
161
|
id: string;
|
|
164
|
-
language: CodeLanguage;
|
|
162
|
+
language: CodeLanguage$1;
|
|
165
163
|
};
|
|
166
164
|
}
|
|
167
165
|
interface ExecuteCommandOptions {
|
|
@@ -241,13 +239,19 @@ type PtyServerMessage = {
|
|
|
241
239
|
};
|
|
242
240
|
//#endregion
|
|
243
241
|
//#region src/control.d.ts
|
|
244
|
-
|
|
242
|
+
/**
|
|
243
|
+
* A non-2xx answer from the OpenSandbox server.
|
|
244
|
+
*
|
|
245
|
+
* `code` is the alineo code ({@link AlineoError}). OpenSandbox's own code, when the response
|
|
246
|
+
* carried one, is `upstreamCode`.
|
|
247
|
+
*/
|
|
248
|
+
export declare class OpenSandboxError extends AlineoError {
|
|
245
249
|
readonly status: number;
|
|
246
250
|
/** OpenSandbox's error code, e.g. `DOCKER::SANDBOX_NOT_FOUND`, when the response carried one. */
|
|
247
|
-
readonly
|
|
251
|
+
readonly upstreamCode?: string | undefined;
|
|
248
252
|
constructor(message: string, status: number,
|
|
249
253
|
/** OpenSandbox's error code, e.g. `DOCKER::SANDBOX_NOT_FOUND`, when the response carried one. */
|
|
250
|
-
|
|
254
|
+
upstreamCode?: string | undefined, code?: ErrorCode, path?: string);
|
|
251
255
|
}
|
|
252
256
|
export declare class ControlClient {
|
|
253
257
|
private baseUrl;
|
|
@@ -262,12 +266,24 @@ export declare class ControlClient {
|
|
|
262
266
|
withSignal(signal: AbortSignal): ControlClient;
|
|
263
267
|
private request;
|
|
264
268
|
createSandbox(options: CreateSandboxOptions): Promise<Sandbox>;
|
|
269
|
+
/**
|
|
270
|
+
* Every sandbox, optionally filtered by state. OpenSandbox paginates with `page`/`pageSize`
|
|
271
|
+
* (default 20, max 200) and ignores `limit`/`offset`, so this walks every page and applies
|
|
272
|
+
* `offset`/`limit` itself. Sending `limit`/`offset` as query parameters silently capped every
|
|
273
|
+
* listing at the server's first 20.
|
|
274
|
+
*/
|
|
265
275
|
listSandboxes(options?: ListSandboxesOptions): Promise<Sandbox[]>;
|
|
266
276
|
getSandbox(id: string): Promise<Sandbox>;
|
|
267
277
|
deleteSandbox(id: string): Promise<void>;
|
|
268
278
|
pauseSandbox(id: string): Promise<void>;
|
|
269
279
|
resumeSandbox(id: string): Promise<void>;
|
|
270
|
-
|
|
280
|
+
/**
|
|
281
|
+
* Move a sandbox's expiry to `expiresAt`, which must be in the future and later than its current
|
|
282
|
+
* expiry. Only meaningful for a sandbox created with a `timeout`: one created without it never
|
|
283
|
+
* expires (OpenSandbox's `CreateSandboxRequest.timeout` — "when omitted or null, the sandbox will
|
|
284
|
+
* not auto-terminate"). The countdown keeps running while a sandbox is paused.
|
|
285
|
+
*/
|
|
286
|
+
renewExpiration(id: string, expiresAt: Date | string): Promise<void>;
|
|
271
287
|
getEndpoint(sandboxId: string, port: number, useServerProxy?: boolean): Promise<SandboxEndpoint>;
|
|
272
288
|
getDiagnosticLogs(sandboxId: string): Promise<DiagnosticLog[]>;
|
|
273
289
|
getDiagnosticEvents(sandboxId: string): Promise<DiagnosticEvent[]>;
|
|
@@ -395,6 +411,77 @@ export declare class ExecClient {
|
|
|
395
411
|
deleteSession(sessionId: string): Promise<void>;
|
|
396
412
|
}
|
|
397
413
|
//#endregion
|
|
414
|
+
//#region src/provider.d.ts
|
|
415
|
+
/**
|
|
416
|
+
* Where an OpenSandbox state sits in alineo's states.
|
|
417
|
+
*
|
|
418
|
+
* `Unknown`, and any state added after this was written, is `provisioning`, never `running`:
|
|
419
|
+
* calling a sandbox running before it is would hide its startup deadline.
|
|
420
|
+
*/
|
|
421
|
+
export declare function stateOf(native: SandboxState | string): SandboxState$1;
|
|
422
|
+
/** Committing and Pushing are both "not ready yet". */
|
|
423
|
+
export declare function snapshotStateOf(native: SnapshotState | string): SnapshotState$1;
|
|
424
|
+
interface OpenSandboxProviderOptions {
|
|
425
|
+
baseUrl: string;
|
|
426
|
+
/** Empty or absent for a local server with no auth. */
|
|
427
|
+
apiKey?: string;
|
|
428
|
+
/**
|
|
429
|
+
* Send `execd` and sidecar traffic through the server. Required when the server runs in Docker
|
|
430
|
+
* (`alineo init`), because the sandbox's own address is not reachable from the host.
|
|
431
|
+
*/
|
|
432
|
+
useServerProxy?: boolean;
|
|
433
|
+
/** How patiently `connectExec` waits for `execd`. The defaults give about 80 seconds. */
|
|
434
|
+
execReadiness?: {
|
|
435
|
+
retries?: number;
|
|
436
|
+
delayMs?: number;
|
|
437
|
+
};
|
|
438
|
+
/** A prepared control client, for tests. Otherwise one is built from `baseUrl` and `apiKey`. */
|
|
439
|
+
control?: ControlClient;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* OpenSandbox as a {@link SandboxProvider}.
|
|
443
|
+
*
|
|
444
|
+
* A thin adapter over the three HTTP clients in this package: it holds their configuration,
|
|
445
|
+
* maps OpenSandbox's states onto alineo's states, and owns the one piece of logic that is not a
|
|
446
|
+
* pass-through, which is waiting for `execd` to accept a connection.
|
|
447
|
+
*/
|
|
448
|
+
export declare class OpenSandboxProvider implements SandboxProvider {
|
|
449
|
+
readonly id = "opensandbox";
|
|
450
|
+
readonly descriptor: SandboxProviderDescriptor;
|
|
451
|
+
/** The underlying client, for the few callers that need an OpenSandbox-only call. Not portable. */
|
|
452
|
+
readonly control: ControlClient;
|
|
453
|
+
readonly egress: EgressChannel;
|
|
454
|
+
private readonly useServerProxy;
|
|
455
|
+
private readonly retries;
|
|
456
|
+
private readonly delayMs;
|
|
457
|
+
constructor(options: OpenSandboxProviderOptions);
|
|
458
|
+
createSandbox(request: CreateSandboxRequest): Promise<SandboxInfo>;
|
|
459
|
+
getSandbox(sandboxId: string): Promise<SandboxInfo>;
|
|
460
|
+
listSandboxes(filter?: ListSandboxesFilter): Promise<SandboxInfo[]>;
|
|
461
|
+
deleteSandbox(sandboxId: string): Promise<void>;
|
|
462
|
+
pauseSandbox(sandboxId: string): Promise<void>;
|
|
463
|
+
resumeSandbox(sandboxId: string): Promise<void>;
|
|
464
|
+
createSnapshot(sandboxId: string): Promise<SnapshotInfo>;
|
|
465
|
+
getSnapshot(snapshotId: string): Promise<SnapshotInfo>;
|
|
466
|
+
getEndpoint(sandboxId: string, port: number, useServerProxy?: boolean | undefined): Promise<SandboxEndpoint>;
|
|
467
|
+
getDiagnosticLogs(sandboxId: string): Promise<DiagnosticLog[]>;
|
|
468
|
+
getDiagnosticEvents(sandboxId: string): Promise<DiagnosticEvent[]>;
|
|
469
|
+
/**
|
|
470
|
+
* Resolve `execd`'s address once (each lookup can return a different ephemeral proxy port),
|
|
471
|
+
* then probe it until it answers.
|
|
472
|
+
*
|
|
473
|
+
* OpenSandbox reports a sandbox `Running` before `execd` inside it is accepting connections,
|
|
474
|
+
* and on a loaded host the gap is long: a fork taken while its parent ran a real Chrome
|
|
475
|
+
* session needed about 35 seconds to reach `Running` and then burned the old 11 second
|
|
476
|
+
* readiness budget (issue #32). The probe starts fast and backs off to `delayMs`, since
|
|
477
|
+
* `execd` is usually ready within one tick.
|
|
478
|
+
*/
|
|
479
|
+
connectExec(sandboxId: string, options?: {
|
|
480
|
+
signal?: AbortSignal;
|
|
481
|
+
}): Promise<ExecChannel>;
|
|
482
|
+
connectPty(sandboxId: string): Promise<PtyChannel>;
|
|
483
|
+
}
|
|
484
|
+
//#endregion
|
|
398
485
|
//#region src/pty.d.ts
|
|
399
486
|
type PtyOutputListener = (chunk: string) => void;
|
|
400
487
|
type PtyExitListener = (exitCode: number) => void;
|
|
@@ -428,4 +515,4 @@ export declare class PtyClient {
|
|
|
428
515
|
close(): void;
|
|
429
516
|
}
|
|
430
517
|
//#endregion
|
|
431
|
-
export type
|
|
518
|
+
export { type CodeContext, CodeLanguage, type CommandStatus, type CreatePtyOptions, type CreatePtyResponse, type CreateSandboxOptions, type CreateSessionRequest, type CreateSessionResponse, type CredentialProxyConfig, type DiagnosticEvent, type DiagnosticLog, type EgressPolicyStatus, type ExecuteCodeOptions, type ExecuteCommandOptions, type FileInfo, type FileReplacement, type ImageAuth, type ImageSpec, type ListSandboxesOptions, type ListSnapshotsOptions, type Metrics, type NetworkPolicy, type NetworkRule, type OpenSandboxProviderOptions, type PtyClientMessage, type PtyExitListener, type PtyOutputListener, type PtyServerMessage, type Resources, type RunInSessionRequest, type SSEEvent, type Sandbox, type SandboxEndpoint, type SandboxStatus, type Snapshot };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { AlineoError } from "@alineo-labs/errors";
|
|
2
|
+
import { CodeLanguage } from "@alineo-labs/provider";
|
|
1
3
|
//#region src/control.ts
|
|
2
4
|
function flattenSnapshot(raw) {
|
|
3
5
|
return {
|
|
@@ -7,30 +9,62 @@ function flattenSnapshot(raw) {
|
|
|
7
9
|
createdAt: raw.createdAt
|
|
8
10
|
};
|
|
9
11
|
}
|
|
10
|
-
|
|
12
|
+
/** True for `/v1/sandboxes/<id>`, with an optional trailing slash or query string. */
|
|
13
|
+
function isSandboxRoute(path) {
|
|
14
|
+
const queryAt = path.indexOf("?");
|
|
15
|
+
const route = queryAt === -1 ? path : path.slice(0, queryAt);
|
|
16
|
+
if (!route.startsWith("/v1/sandboxes/")) return false;
|
|
17
|
+
const id = route.endsWith("/") ? route.slice(14, -1) : route.slice(14);
|
|
18
|
+
return id.length > 0 && !id.includes("/");
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Which alineo code an OpenSandbox response stands for.
|
|
22
|
+
*
|
|
23
|
+
* `upstreamCode` is OpenSandbox's own code (`DOCKER::SANDBOX_NOT_FOUND`), which says what the
|
|
24
|
+
* server meant. The status and the route say what it means to alineo. A 404 on a sandbox route
|
|
25
|
+
* is a missing sandbox even when the body carries no code.
|
|
26
|
+
*/
|
|
27
|
+
function codeForResponse(status, upstreamCode, path) {
|
|
28
|
+
if (upstreamCode?.endsWith("SANDBOX_NOT_FOUND")) return "SANDBOX_NOT_FOUND";
|
|
29
|
+
if (status === 404 && path !== void 0 && isSandboxRoute(path)) return "SANDBOX_NOT_FOUND";
|
|
30
|
+
if (status === 401 || status === 403) return "PROVIDER_AUTH";
|
|
31
|
+
if (status === 429) return "PROVIDER_RATE_LIMITED";
|
|
32
|
+
if (status >= 500) return "PROVIDER_UNAVAILABLE";
|
|
33
|
+
return "PROVIDER_ERROR";
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A non-2xx answer from the OpenSandbox server.
|
|
37
|
+
*
|
|
38
|
+
* `code` is the alineo code ({@link AlineoError}). OpenSandbox's own code, when the response
|
|
39
|
+
* carried one, is `upstreamCode`.
|
|
40
|
+
*/
|
|
41
|
+
var OpenSandboxError = class extends AlineoError {
|
|
11
42
|
status;
|
|
12
|
-
|
|
13
|
-
constructor(message, status, code) {
|
|
14
|
-
super(message
|
|
43
|
+
upstreamCode;
|
|
44
|
+
constructor(message, status, upstreamCode, code, path) {
|
|
45
|
+
super(code ?? codeForResponse(status, upstreamCode, path), message, { details: {
|
|
46
|
+
status,
|
|
47
|
+
...upstreamCode ? { upstreamCode } : {}
|
|
48
|
+
} });
|
|
15
49
|
this.status = status;
|
|
16
|
-
this.
|
|
50
|
+
this.upstreamCode = upstreamCode;
|
|
17
51
|
this.name = "OpenSandboxError";
|
|
18
52
|
}
|
|
19
53
|
};
|
|
20
54
|
/**
|
|
21
55
|
* OpenSandbox answers an error with a JSON body, `{"code": "...", "message": "..."}`. Put the
|
|
22
|
-
* sentence in `message` (with the code after it), keep the code on `.
|
|
23
|
-
* raw text when the body isn't that shape.
|
|
56
|
+
* sentence in `message` (with the code after it), keep the code on `.upstreamCode`, and fall back
|
|
57
|
+
* to the raw text when the body isn't that shape.
|
|
24
58
|
*/
|
|
25
|
-
function errorFromBody(text, status) {
|
|
59
|
+
function errorFromBody(text, status, path, fallback = "OpenSandbox API error") {
|
|
26
60
|
try {
|
|
27
61
|
const body = JSON.parse(text);
|
|
28
62
|
if (typeof body?.message === "string" && body.message) {
|
|
29
|
-
const
|
|
30
|
-
return new OpenSandboxError(
|
|
63
|
+
const upstream = typeof body.code === "string" && body.code ? body.code : void 0;
|
|
64
|
+
return new OpenSandboxError(upstream ? `${body.message} (${upstream})` : body.message, status, upstream, void 0, path);
|
|
31
65
|
}
|
|
32
66
|
} catch {}
|
|
33
|
-
return new OpenSandboxError(text ||
|
|
67
|
+
return new OpenSandboxError(text || fallback, status, void 0, void 0, path);
|
|
34
68
|
}
|
|
35
69
|
var ControlClient = class ControlClient {
|
|
36
70
|
baseUrl;
|
|
@@ -59,20 +93,33 @@ var ControlClient = class ControlClient {
|
|
|
59
93
|
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
60
94
|
signal: this.signal
|
|
61
95
|
});
|
|
62
|
-
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status);
|
|
96
|
+
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status, path);
|
|
63
97
|
if (res.status === 204) return void 0;
|
|
64
98
|
return res.json();
|
|
65
99
|
}
|
|
66
100
|
createSandbox(options) {
|
|
67
101
|
return this.request("POST", "/v1/sandboxes", options);
|
|
68
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Every sandbox, optionally filtered by state. OpenSandbox paginates with `page`/`pageSize`
|
|
105
|
+
* (default 20, max 200) and ignores `limit`/`offset`, so this walks every page and applies
|
|
106
|
+
* `offset`/`limit` itself. Sending `limit`/`offset` as query parameters silently capped every
|
|
107
|
+
* listing at the server's first 20.
|
|
108
|
+
*/
|
|
69
109
|
async listSandboxes(options = {}) {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
110
|
+
const all = [];
|
|
111
|
+
for (let page = 1;; page++) {
|
|
112
|
+
const params = new URLSearchParams({
|
|
113
|
+
page: String(page),
|
|
114
|
+
pageSize: "200"
|
|
115
|
+
});
|
|
116
|
+
if (options.state) params.set("state", options.state);
|
|
117
|
+
const res = await this.request("GET", `/v1/sandboxes?${params}`);
|
|
118
|
+
all.push(...res.items);
|
|
119
|
+
if (!res.pagination?.hasNextPage) break;
|
|
120
|
+
}
|
|
121
|
+
const start = options.offset ?? 0;
|
|
122
|
+
return all.slice(start, options.limit === void 0 ? void 0 : start + options.limit);
|
|
76
123
|
}
|
|
77
124
|
getSandbox(id) {
|
|
78
125
|
return this.request("GET", `/v1/sandboxes/${id}`);
|
|
@@ -86,8 +133,15 @@ var ControlClient = class ControlClient {
|
|
|
86
133
|
resumeSandbox(id) {
|
|
87
134
|
return this.request("POST", `/v1/sandboxes/${id}/resume`);
|
|
88
135
|
}
|
|
89
|
-
|
|
90
|
-
|
|
136
|
+
/**
|
|
137
|
+
* Move a sandbox's expiry to `expiresAt`, which must be in the future and later than its current
|
|
138
|
+
* expiry. Only meaningful for a sandbox created with a `timeout`: one created without it never
|
|
139
|
+
* expires (OpenSandbox's `CreateSandboxRequest.timeout` — "when omitted or null, the sandbox will
|
|
140
|
+
* not auto-terminate"). The countdown keeps running while a sandbox is paused.
|
|
141
|
+
*/
|
|
142
|
+
renewExpiration(id, expiresAt) {
|
|
143
|
+
const at = typeof expiresAt === "string" ? expiresAt : expiresAt.toISOString();
|
|
144
|
+
return this.request("POST", `/v1/sandboxes/${id}/renew-expiration`, { expiresAt: at });
|
|
91
145
|
}
|
|
92
146
|
getEndpoint(sandboxId, port, useServerProxy) {
|
|
93
147
|
const qs = useServerProxy ? "?use_server_proxy=true" : "";
|
|
@@ -276,15 +330,6 @@ let SSEEventType = /* @__PURE__ */ function(SSEEventType) {
|
|
|
276
330
|
SSEEventType["Message"] = "message";
|
|
277
331
|
return SSEEventType;
|
|
278
332
|
}({});
|
|
279
|
-
let CodeLanguage = /* @__PURE__ */ function(CodeLanguage) {
|
|
280
|
-
CodeLanguage["Python"] = "python";
|
|
281
|
-
CodeLanguage["JavaScript"] = "javascript";
|
|
282
|
-
CodeLanguage["TypeScript"] = "typescript";
|
|
283
|
-
CodeLanguage["Go"] = "go";
|
|
284
|
-
CodeLanguage["Java"] = "java";
|
|
285
|
-
CodeLanguage["Bash"] = "bash";
|
|
286
|
-
return CodeLanguage;
|
|
287
|
-
}({});
|
|
288
333
|
//#endregion
|
|
289
334
|
//#region src/exec.ts
|
|
290
335
|
/**
|
|
@@ -349,6 +394,27 @@ async function* parseSSE(stream, pendingReaders, isTerminal) {
|
|
|
349
394
|
}
|
|
350
395
|
}
|
|
351
396
|
}
|
|
397
|
+
/**
|
|
398
|
+
* The largest string Linux passes as one argument to `execve` (`MAX_ARG_STRLEN`, 32 pages)
|
|
399
|
+
* leaves room for the terminating NUL: 131,071 bytes. execd starts a command as
|
|
400
|
+
* `bash -c <command>`, so a longer command cannot start. execd then answers with an `error`
|
|
401
|
+
* event ("argument list too long") and no output, which read as exit 0 before core learned to
|
|
402
|
+
* tell a start failure from an exit status.
|
|
403
|
+
*
|
|
404
|
+
* `sb.exec()` sends `echo <base64> | base64 -d | sh`, so it can carry about 98 KB of command.
|
|
405
|
+
*/
|
|
406
|
+
const MAX_COMMAND_BYTES = 131071;
|
|
407
|
+
function assertCommandSize(command) {
|
|
408
|
+
const bytes = new TextEncoder().encode(command).length;
|
|
409
|
+
if (bytes <= 131071) return;
|
|
410
|
+
throw new AlineoError("INVALID_ARGUMENT", `command is ${bytes} bytes, over the ${MAX_COMMAND_BYTES} byte limit Linux sets for one argument`, {
|
|
411
|
+
hint: "Write the content with writeFile() and run a short command that reads it. sb.exec() sends the command base64-encoded, so about 98 KB is the most it can carry.",
|
|
412
|
+
details: {
|
|
413
|
+
bytes,
|
|
414
|
+
limit: MAX_COMMAND_BYTES
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
352
418
|
function isExecTerminal(event) {
|
|
353
419
|
return event.type === "execution_complete" || event.type === "error";
|
|
354
420
|
}
|
|
@@ -396,10 +462,7 @@ var ExecClient = class ExecClient {
|
|
|
396
462
|
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
397
463
|
signal: this.signal
|
|
398
464
|
});
|
|
399
|
-
if (!res.ok) {
|
|
400
|
-
const text = await res.text().catch(() => "");
|
|
401
|
-
throw new Error(text || `execd error ${res.status}`);
|
|
402
|
-
}
|
|
465
|
+
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status, void 0, `execd error ${res.status}`);
|
|
403
466
|
if (res.status === 204) return void 0;
|
|
404
467
|
return res.json();
|
|
405
468
|
}
|
|
@@ -413,10 +476,7 @@ var ExecClient = class ExecClient {
|
|
|
413
476
|
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
414
477
|
signal: this.signal
|
|
415
478
|
});
|
|
416
|
-
if (!res.ok) {
|
|
417
|
-
const text = await res.text().catch(() => "");
|
|
418
|
-
throw new Error(text || `execd error ${res.status}`);
|
|
419
|
-
}
|
|
479
|
+
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status, void 0, `execd error ${res.status}`);
|
|
420
480
|
if (!res.body) return;
|
|
421
481
|
yield* parseSSE(res.body, this.pendingReaders, isTerminal);
|
|
422
482
|
}
|
|
@@ -444,6 +504,7 @@ var ExecClient = class ExecClient {
|
|
|
444
504
|
return this.request("DELETE", "/code");
|
|
445
505
|
}
|
|
446
506
|
async *executeCommand(options) {
|
|
507
|
+
assertCommandSize(options.command);
|
|
447
508
|
yield* this.streamRequest("POST", "/command", options, isExecTerminal);
|
|
448
509
|
}
|
|
449
510
|
interruptCommand() {
|
|
@@ -497,17 +558,14 @@ var ExecClient = class ExecClient {
|
|
|
497
558
|
body: formData,
|
|
498
559
|
signal: this.signal
|
|
499
560
|
});
|
|
500
|
-
if (!res.ok) {
|
|
501
|
-
const text = await res.text().catch(() => "");
|
|
502
|
-
throw new Error(text || `execd error ${res.status}`);
|
|
503
|
-
}
|
|
561
|
+
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status, void 0, `execd error ${res.status}`);
|
|
504
562
|
}
|
|
505
563
|
async downloadFile(path) {
|
|
506
564
|
const res = await fetch(`${this.baseUrl}/files/download?path=${encodeURIComponent(path)}`, {
|
|
507
565
|
headers: this.authHeader,
|
|
508
566
|
signal: this.signal
|
|
509
567
|
});
|
|
510
|
-
if (!res.ok) throw
|
|
568
|
+
if (!res.ok) throw errorFromBody(await res.text().catch(() => ""), res.status, void 0, `execd error ${res.status}`);
|
|
511
569
|
if (!res.body) throw new Error("empty response body");
|
|
512
570
|
return res.body;
|
|
513
571
|
}
|
|
@@ -539,6 +597,118 @@ var ExecClient = class ExecClient {
|
|
|
539
597
|
}
|
|
540
598
|
};
|
|
541
599
|
//#endregion
|
|
600
|
+
//#region src/line-endings.ts
|
|
601
|
+
const hasEnding = (text) => /[\r\n]/.test(text);
|
|
602
|
+
const isOutput = (ev) => (ev.type === "stdout" || ev.type === "stderr") && typeof ev.text === "string";
|
|
603
|
+
const isTerminal = (ev) => ev.type === "error" || ev.type === "execution_complete";
|
|
604
|
+
/**
|
|
605
|
+
* Restores the line endings that `execd` before 1.1.1 dropped.
|
|
606
|
+
*
|
|
607
|
+
* Those versions send one stdout event per line with the newline removed, so `echo one; echo
|
|
608
|
+
* two` arrives as `"one"` then `"two"` and anything that concatenates events reads `"onetwo"`
|
|
609
|
+
* (fixed upstream in OpenSandbox 380322ba). `alineo init` pins a version that is fine, but an
|
|
610
|
+
* install keeps the `execd_image` in its own `server.toml`, so old servers are still out there.
|
|
611
|
+
*
|
|
612
|
+
* This is an OpenSandbox quirk, so it lives here and not in core, which joins events as they are.
|
|
613
|
+
*
|
|
614
|
+
* **How it decides.** A server that keeps endings sends every complete line with one, and sends
|
|
615
|
+
* an ending-less event only as the last fragment. So a stream with two or more ending-less events
|
|
616
|
+
* of one kind and *no event of that kind that has an ending* can only be a server that dropped
|
|
617
|
+
* them. Those events are held until the stream's terminal event, and then released with `\n`
|
|
618
|
+
* appended. The first event that does carry an ending proves the server keeps them: held events
|
|
619
|
+
* are released as they were, and the rest of the stream is not touched. A single ending-less
|
|
620
|
+
* event is left alone, because it is also what `printf abc` looks like on a good server.
|
|
621
|
+
*
|
|
622
|
+
* **What it learns.** One verdict per instance, which is one per channel and so per sandbox.
|
|
623
|
+
* Once a stream has proved the server drops endings, later streams are repaired as they arrive,
|
|
624
|
+
* not held. Once one has proved it keeps them, nothing is ever held again.
|
|
625
|
+
*
|
|
626
|
+
* **Known limit.** On a server that drops endings, a final fragment printed on purpose without a
|
|
627
|
+
* newline (`printf abc`) gets one added after the first stream has taught this instance. There is
|
|
628
|
+
* no telling the two apart from the events alone.
|
|
629
|
+
*/
|
|
630
|
+
var LineEndingRepair = class {
|
|
631
|
+
dropsEndings;
|
|
632
|
+
async *repair(events) {
|
|
633
|
+
if (this.dropsEndings === false) {
|
|
634
|
+
yield* events;
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
if (this.dropsEndings === true) {
|
|
638
|
+
for await (const ev of events) yield isOutput(ev) && !hasEnding(ev.text) ? terminated(ev) : ev;
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
const held = [];
|
|
642
|
+
let sawEnding = false;
|
|
643
|
+
for await (const ev of events) {
|
|
644
|
+
if (isOutput(ev)) {
|
|
645
|
+
if (hasEnding(ev.text)) {
|
|
646
|
+
if (!sawEnding) {
|
|
647
|
+
sawEnding = true;
|
|
648
|
+
this.dropsEndings = false;
|
|
649
|
+
for (const h of held.splice(0)) yield h;
|
|
650
|
+
}
|
|
651
|
+
yield ev;
|
|
652
|
+
} else if (sawEnding) yield ev;
|
|
653
|
+
else held.push(ev);
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
if (isTerminal(ev) && held.length > 0) yield* this.release(held);
|
|
657
|
+
yield ev;
|
|
658
|
+
}
|
|
659
|
+
if (held.length > 0) yield* this.release(held);
|
|
660
|
+
}
|
|
661
|
+
/** Decide, for each kind of output, whether the held events were stripped lines. */
|
|
662
|
+
*release(held) {
|
|
663
|
+
const count = {
|
|
664
|
+
stdout: 0,
|
|
665
|
+
stderr: 0
|
|
666
|
+
};
|
|
667
|
+
for (const ev of held) count[ev.type] = (count[ev.type] ?? 0) + 1;
|
|
668
|
+
const stripped = (type) => (count[type] ?? 0) >= 2;
|
|
669
|
+
if (stripped("stdout") || stripped("stderr")) this.dropsEndings = true;
|
|
670
|
+
for (const ev of held.splice(0)) yield stripped(ev.type) ? terminated(ev) : ev;
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
function terminated(ev) {
|
|
674
|
+
return {
|
|
675
|
+
...ev,
|
|
676
|
+
text: `${ev.text}\n`
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* `inner`, with the line endings of command and session output restored where `execd` dropped
|
|
681
|
+
* them. Everything else, code execution included, is passed through unchanged.
|
|
682
|
+
*
|
|
683
|
+
* `withSignal` copies share one {@link LineEndingRepair}: they talk to the same server.
|
|
684
|
+
*/
|
|
685
|
+
function withLineEndingRepair(inner, repair = new LineEndingRepair()) {
|
|
686
|
+
return {
|
|
687
|
+
withSignal: (signal) => withLineEndingRepair(inner.withSignal(signal), repair),
|
|
688
|
+
disposeConnections: () => inner.disposeConnections(),
|
|
689
|
+
executeCommand: (request) => repair.repair(inner.executeCommand(request)),
|
|
690
|
+
runInSession: (sessionId, request) => repair.repair(inner.runInSession(sessionId, request)),
|
|
691
|
+
executeCode: (request) => inner.executeCode(request),
|
|
692
|
+
interruptCommand: () => inner.interruptCommand(),
|
|
693
|
+
listContexts: (language) => inner.listContexts(language),
|
|
694
|
+
createContext: (language) => inner.createContext(language),
|
|
695
|
+
createSession: (request) => inner.createSession(request),
|
|
696
|
+
deleteSession: (sessionId) => inner.deleteSession(sessionId),
|
|
697
|
+
getFileInfo: (path) => inner.getFileInfo(path),
|
|
698
|
+
deleteFile: (path) => inner.deleteFile(path),
|
|
699
|
+
moveFile: (from, to) => inner.moveFile(from, to),
|
|
700
|
+
searchFiles: (pattern, path) => inner.searchFiles(pattern, path),
|
|
701
|
+
replaceInFiles: (replacements) => inner.replaceInFiles(replacements),
|
|
702
|
+
uploadFile: (path, content) => inner.uploadFile(path, content),
|
|
703
|
+
downloadFile: (path) => inner.downloadFile(path),
|
|
704
|
+
listDirectory: (path, depth) => inner.listDirectory(path, depth),
|
|
705
|
+
createDirectory: (path) => inner.createDirectory(path),
|
|
706
|
+
deleteDirectory: (path) => inner.deleteDirectory(path),
|
|
707
|
+
getMetrics: () => inner.getMetrics(),
|
|
708
|
+
watchMetrics: () => inner.watchMetrics()
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
//#endregion
|
|
542
712
|
//#region src/pty.ts
|
|
543
713
|
/**
|
|
544
714
|
* Wraps execd's `/pty` REST + WebSocket protocol.
|
|
@@ -634,4 +804,216 @@ var PtyClient = class {
|
|
|
634
804
|
}
|
|
635
805
|
};
|
|
636
806
|
//#endregion
|
|
637
|
-
|
|
807
|
+
//#region src/provider.ts
|
|
808
|
+
/** The port `execd` listens on inside a sandbox. */
|
|
809
|
+
const EXECD_PORT = 44772;
|
|
810
|
+
/**
|
|
811
|
+
* Where an OpenSandbox state sits in alineo's states.
|
|
812
|
+
*
|
|
813
|
+
* `Unknown`, and any state added after this was written, is `provisioning`, never `running`:
|
|
814
|
+
* calling a sandbox running before it is would hide its startup deadline.
|
|
815
|
+
*/
|
|
816
|
+
function stateOf(native) {
|
|
817
|
+
switch (native) {
|
|
818
|
+
case "Running": return "running";
|
|
819
|
+
case "Pausing": return "pausing";
|
|
820
|
+
case "Paused": return "paused";
|
|
821
|
+
case "Resuming": return "resuming";
|
|
822
|
+
case "Stopping": return "stopping";
|
|
823
|
+
case "Terminated": return "terminated";
|
|
824
|
+
case "Failed": return "failed";
|
|
825
|
+
default: return "provisioning";
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* The OpenSandbox state a state filter means. The inverse of {@link stateOf}, for list filters.
|
|
830
|
+
*
|
|
831
|
+
* Not a true inverse: `stateOf` also maps `Unknown` and any state it has not heard of to
|
|
832
|
+
* `provisioning`, and this maps `provisioning` to `Pending` only. A `provisioning` filter
|
|
833
|
+
* therefore misses sandboxes the adapter would report as provisioning from an unrecognised state.
|
|
834
|
+
*/
|
|
835
|
+
function nativeStateOf(state) {
|
|
836
|
+
switch (state) {
|
|
837
|
+
case "running": return "Running";
|
|
838
|
+
case "pausing": return "Pausing";
|
|
839
|
+
case "paused": return "Paused";
|
|
840
|
+
case "resuming": return "Resuming";
|
|
841
|
+
case "stopping": return "Stopping";
|
|
842
|
+
case "terminated": return "Terminated";
|
|
843
|
+
case "failed": return "Failed";
|
|
844
|
+
case "provisioning": return "Pending";
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
/** Committing and Pushing are both "not ready yet". */
|
|
848
|
+
function snapshotStateOf(native) {
|
|
849
|
+
if (native === "Ready") return "ready";
|
|
850
|
+
if (native === "Failed") return "failed";
|
|
851
|
+
return "pending";
|
|
852
|
+
}
|
|
853
|
+
function toSandboxInfo(raw) {
|
|
854
|
+
return {
|
|
855
|
+
id: raw.id,
|
|
856
|
+
state: stateOf(raw.status.state),
|
|
857
|
+
nativeState: raw.status.state,
|
|
858
|
+
...raw.status.reason !== void 0 ? { reason: raw.status.reason } : {},
|
|
859
|
+
...raw.status.message !== void 0 ? { message: raw.status.message } : {},
|
|
860
|
+
createdAt: raw.createdAt,
|
|
861
|
+
...raw.expiresAt !== void 0 ? { expiresAt: raw.expiresAt } : {},
|
|
862
|
+
...raw.metadata !== void 0 ? { metadata: raw.metadata } : {},
|
|
863
|
+
...raw.snapshotId !== void 0 ? { snapshotId: raw.snapshotId } : {}
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
function toSnapshotInfo(raw) {
|
|
867
|
+
return {
|
|
868
|
+
id: raw.id,
|
|
869
|
+
sandboxId: raw.sandboxId,
|
|
870
|
+
state: snapshotStateOf(raw.state),
|
|
871
|
+
createdAt: raw.createdAt
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* OpenSandbox as a {@link SandboxProvider}.
|
|
876
|
+
*
|
|
877
|
+
* A thin adapter over the three HTTP clients in this package: it holds their configuration,
|
|
878
|
+
* maps OpenSandbox's states onto alineo's states, and owns the one piece of logic that is not a
|
|
879
|
+
* pass-through, which is waiting for `execd` to accept a connection.
|
|
880
|
+
*/
|
|
881
|
+
var OpenSandboxProvider = class {
|
|
882
|
+
id = "opensandbox";
|
|
883
|
+
descriptor = {
|
|
884
|
+
id: "opensandbox",
|
|
885
|
+
label: "OpenSandbox",
|
|
886
|
+
capabilities: {
|
|
887
|
+
snapshot: { kind: "filesystem" },
|
|
888
|
+
pause: true,
|
|
889
|
+
egress: "unverified",
|
|
890
|
+
credentials: "unverified",
|
|
891
|
+
pty: true,
|
|
892
|
+
code: true
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
/** The underlying client, for the few callers that need an OpenSandbox-only call. Not portable. */
|
|
896
|
+
control;
|
|
897
|
+
egress;
|
|
898
|
+
useServerProxy;
|
|
899
|
+
retries;
|
|
900
|
+
delayMs;
|
|
901
|
+
constructor(options) {
|
|
902
|
+
this.control = options.control ?? new ControlClient({
|
|
903
|
+
baseUrl: options.baseUrl,
|
|
904
|
+
apiKey: options.apiKey ?? ""
|
|
905
|
+
});
|
|
906
|
+
this.useServerProxy = options.useServerProxy;
|
|
907
|
+
this.retries = options.execReadiness?.retries ?? 45;
|
|
908
|
+
this.delayMs = options.execReadiness?.delayMs ?? 2e3;
|
|
909
|
+
this.egress = new EgressClient(this.control, this.useServerProxy);
|
|
910
|
+
}
|
|
911
|
+
async createSandbox(request) {
|
|
912
|
+
return toSandboxInfo(await this.control.createSandbox(request));
|
|
913
|
+
}
|
|
914
|
+
async getSandbox(sandboxId) {
|
|
915
|
+
return toSandboxInfo(await this.control.getSandbox(sandboxId));
|
|
916
|
+
}
|
|
917
|
+
async listSandboxes(filter = {}) {
|
|
918
|
+
return (await this.control.listSandboxes({
|
|
919
|
+
...filter.state !== void 0 ? { state: nativeStateOf(filter.state) } : {},
|
|
920
|
+
...filter.limit !== void 0 ? { limit: filter.limit } : {},
|
|
921
|
+
...filter.offset !== void 0 ? { offset: filter.offset } : {}
|
|
922
|
+
})).map(toSandboxInfo);
|
|
923
|
+
}
|
|
924
|
+
deleteSandbox(sandboxId) {
|
|
925
|
+
return this.control.deleteSandbox(sandboxId);
|
|
926
|
+
}
|
|
927
|
+
pauseSandbox(sandboxId) {
|
|
928
|
+
return this.control.pauseSandbox(sandboxId);
|
|
929
|
+
}
|
|
930
|
+
resumeSandbox(sandboxId) {
|
|
931
|
+
return this.control.resumeSandbox(sandboxId);
|
|
932
|
+
}
|
|
933
|
+
async createSnapshot(sandboxId) {
|
|
934
|
+
return toSnapshotInfo(await this.control.createSnapshot(sandboxId));
|
|
935
|
+
}
|
|
936
|
+
async getSnapshot(snapshotId) {
|
|
937
|
+
return toSnapshotInfo(await this.control.getSnapshot(snapshotId));
|
|
938
|
+
}
|
|
939
|
+
getEndpoint(sandboxId, port, useServerProxy = this.useServerProxy) {
|
|
940
|
+
return this.control.getEndpoint(sandboxId, port, useServerProxy);
|
|
941
|
+
}
|
|
942
|
+
getDiagnosticLogs(sandboxId) {
|
|
943
|
+
return this.control.getDiagnosticLogs(sandboxId);
|
|
944
|
+
}
|
|
945
|
+
getDiagnosticEvents(sandboxId) {
|
|
946
|
+
return this.control.getDiagnosticEvents(sandboxId);
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Resolve `execd`'s address once (each lookup can return a different ephemeral proxy port),
|
|
950
|
+
* then probe it until it answers.
|
|
951
|
+
*
|
|
952
|
+
* OpenSandbox reports a sandbox `Running` before `execd` inside it is accepting connections,
|
|
953
|
+
* and on a loaded host the gap is long: a fork taken while its parent ran a real Chrome
|
|
954
|
+
* session needed about 35 seconds to reach `Running` and then burned the old 11 second
|
|
955
|
+
* readiness budget (issue #32). The probe starts fast and backs off to `delayMs`, since
|
|
956
|
+
* `execd` is usually ready within one tick.
|
|
957
|
+
*/
|
|
958
|
+
async connectExec(sandboxId, options = {}) {
|
|
959
|
+
const { signal } = options;
|
|
960
|
+
signal?.throwIfAborted();
|
|
961
|
+
const ep = await this.control.getEndpoint(sandboxId, EXECD_PORT, this.useServerProxy);
|
|
962
|
+
const client = new ExecClient({
|
|
963
|
+
baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
|
|
964
|
+
accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
|
|
965
|
+
});
|
|
966
|
+
let delay = Math.min(100, this.delayMs);
|
|
967
|
+
const startedAt = Date.now();
|
|
968
|
+
for (let attempt = 0; attempt <= this.retries; attempt++) {
|
|
969
|
+
signal?.throwIfAborted();
|
|
970
|
+
try {
|
|
971
|
+
await client.listContexts();
|
|
972
|
+
return withLineEndingRepair(client);
|
|
973
|
+
} catch (err) {
|
|
974
|
+
if (attempt === this.retries) {
|
|
975
|
+
const attempts = attempt + 1;
|
|
976
|
+
const waitedMs = Date.now() - startedAt;
|
|
977
|
+
throw new AlineoError("EXEC_NOT_READY", `execd not ready for sandbox ${sandboxId} after ${attempts} attempts over ${(waitedMs / 1e3).toFixed(0)}s`, {
|
|
978
|
+
cause: err,
|
|
979
|
+
details: {
|
|
980
|
+
sandboxId,
|
|
981
|
+
attempts,
|
|
982
|
+
waitedMs
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
}
|
|
986
|
+
await abortableDelay(delay, signal);
|
|
987
|
+
delay = Math.min(delay * 1.5, this.delayMs);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
throw new Error("unreachable");
|
|
991
|
+
}
|
|
992
|
+
async connectPty(sandboxId) {
|
|
993
|
+
const ep = await this.control.getEndpoint(sandboxId, EXECD_PORT, this.useServerProxy);
|
|
994
|
+
return new PtyClient({
|
|
995
|
+
baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
|
|
996
|
+
accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
};
|
|
1000
|
+
/** Wait `ms`, or reject with the signal's reason as soon as it aborts. */
|
|
1001
|
+
function abortableDelay(ms, signal) {
|
|
1002
|
+
return new Promise((resolve, reject) => {
|
|
1003
|
+
if (!signal) {
|
|
1004
|
+
setTimeout(resolve, ms);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
const onAbort = () => {
|
|
1008
|
+
clearTimeout(timer);
|
|
1009
|
+
reject(signal.reason);
|
|
1010
|
+
};
|
|
1011
|
+
const timer = setTimeout(() => {
|
|
1012
|
+
signal.removeEventListener("abort", onAbort);
|
|
1013
|
+
resolve();
|
|
1014
|
+
}, ms);
|
|
1015
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1016
|
+
});
|
|
1017
|
+
}
|
|
1018
|
+
//#endregion
|
|
1019
|
+
export { CodeLanguage, ControlClient, EgressClient, EgressClientError, ExecClient, OpenSandboxError, OpenSandboxProvider, PtyClient, SSEEventType, SandboxState, SnapshotState, isValidEgressTarget, snapshotStateOf, stateOf };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alineo-labs/opensandbox",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,6 +29,10 @@
|
|
|
29
29
|
"test": "vitest run",
|
|
30
30
|
"test:watch": "vitest"
|
|
31
31
|
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@alineo-labs/errors": "0.1.0",
|
|
34
|
+
"@alineo-labs/provider": "0.1.0"
|
|
35
|
+
},
|
|
32
36
|
"devDependencies": {
|
|
33
37
|
"bun-types": "1.4.2",
|
|
34
38
|
"tsdown": "0.23.0",
|