@b3os/sdk 0.0.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -42
- package/dist/cjs/core/bytes.d.ts +30 -0
- package/dist/cjs/core/bytes.js +115 -0
- package/dist/cjs/core/bytes.js.map +1 -0
- package/dist/cjs/core/client.d.ts +61 -3
- package/dist/cjs/core/client.js +211 -33
- package/dist/cjs/core/client.js.map +1 -1
- package/dist/cjs/core/errors.d.ts +16 -4
- package/dist/cjs/core/errors.js +9 -6
- package/dist/cjs/core/errors.js.map +1 -1
- package/dist/cjs/core/handle.d.ts +31 -0
- package/dist/cjs/core/handle.js +86 -0
- package/dist/cjs/core/handle.js.map +1 -0
- package/dist/cjs/core/index.d.ts +6 -4
- package/dist/cjs/core/index.js +8 -1
- package/dist/cjs/core/index.js.map +1 -1
- package/dist/cjs/core/login.d.ts +24 -0
- package/dist/cjs/core/login.js +93 -0
- package/dist/cjs/core/login.js.map +1 -0
- package/dist/cjs/core/namespace.d.ts +1 -1
- package/dist/cjs/core/namespace.js +1 -1
- package/dist/cjs/core/op.d.ts +11 -1
- package/dist/cjs/core/timing.d.ts +1 -1
- package/dist/cjs/core/timing.js +8 -1
- package/dist/cjs/core/timing.js.map +1 -1
- package/dist/cjs/core/transport.js +1 -1
- package/dist/cjs/core/transport.js.map +1 -1
- package/dist/cjs/core/util.d.ts +15 -3
- package/dist/cjs/core/util.js +54 -2
- package/dist/cjs/core/util.js.map +1 -1
- package/dist/cjs/core/ws.d.ts +4 -0
- package/dist/cjs/core/ws.js +7 -4
- package/dist/cjs/core/ws.js.map +1 -1
- package/dist/cjs/generated/client.d.ts +2 -2
- package/dist/cjs/generated/client.js +2 -2
- package/dist/cjs/generated/errors.d.ts +1 -1
- package/dist/cjs/generated/errors.js +30 -0
- package/dist/cjs/generated/errors.js.map +1 -1
- package/dist/cjs/generated/jobs.js +1 -1
- package/dist/cjs/generated/ns/actions.d.ts +48 -6
- package/dist/cjs/generated/ns/actions.js +59 -6
- package/dist/cjs/generated/ns/actions.js.map +1 -1
- package/dist/cjs/generated/ns/infer.d.ts +185 -54
- package/dist/cjs/generated/ns/infer.js +28 -74
- package/dist/cjs/generated/ns/infer.js.map +1 -1
- package/dist/cjs/generated/ns/keys.d.ts +12 -0
- package/dist/cjs/generated/ns/keys.js +22 -0
- package/dist/cjs/generated/ns/keys.js.map +1 -1
- package/dist/cjs/generated/ns/render.d.ts +95 -6
- package/dist/cjs/generated/ns/render.js +124 -7
- package/dist/cjs/generated/ns/render.js.map +1 -1
- package/dist/cjs/generated/ns/requests.d.ts +3 -1
- package/dist/cjs/generated/ns/requests.js +3 -1
- package/dist/cjs/generated/ns/requests.js.map +1 -1
- package/dist/cjs/generated/ns/routines.d.ts +131 -9
- package/dist/cjs/generated/ns/routines.js +186 -9
- package/dist/cjs/generated/ns/routines.js.map +1 -1
- package/dist/cjs/generated/ns/sandboxes.d.ts +298 -31
- package/dist/cjs/generated/ns/sandboxes.js +368 -29
- package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
- package/dist/cjs/generated/ns/vision.d.ts +133 -14
- package/dist/cjs/generated/ns/vision.js +158 -12
- package/dist/cjs/generated/ns/vision.js.map +1 -1
- package/dist/cjs/generated/ns/webhooks.d.ts +8 -5
- package/dist/cjs/generated/ns/webhooks.js +8 -5
- package/dist/cjs/generated/ns/webhooks.js.map +1 -1
- package/dist/cjs/generated/types.d.ts +1956 -301
- package/dist/cjs/helpers/agents.d.ts +95 -0
- package/dist/cjs/helpers/agents.js +205 -0
- package/dist/cjs/helpers/agents.js.map +1 -0
- package/dist/cjs/helpers/render.d.ts +15 -0
- package/dist/cjs/helpers/render.js +74 -0
- package/dist/cjs/helpers/render.js.map +1 -0
- package/dist/cjs/helpers/routines.d.ts +61 -0
- package/dist/cjs/helpers/routines.js +234 -0
- package/dist/cjs/helpers/routines.js.map +1 -0
- package/dist/cjs/helpers/sandboxes.d.ts +237 -0
- package/dist/cjs/helpers/sandboxes.js +608 -0
- package/dist/cjs/helpers/sandboxes.js.map +1 -0
- package/dist/cjs/index.d.ts +4 -1
- package/dist/cjs/index.js +8 -5
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/routines.d.ts +1 -0
- package/dist/cjs/routines.js +21 -0
- package/dist/cjs/routines.js.map +1 -0
- package/dist/cjs/webhooks.js.map +1 -1
- package/dist/esm/core/bytes.d.ts +30 -0
- package/dist/esm/core/bytes.js +111 -0
- package/dist/esm/core/bytes.js.map +1 -0
- package/dist/esm/core/client.d.ts +61 -3
- package/dist/esm/core/client.js +208 -31
- package/dist/esm/core/client.js.map +1 -1
- package/dist/esm/core/errors.d.ts +16 -4
- package/dist/esm/core/errors.js +9 -6
- package/dist/esm/core/errors.js.map +1 -1
- package/dist/esm/core/handle.d.ts +31 -0
- package/dist/esm/core/handle.js +82 -0
- package/dist/esm/core/handle.js.map +1 -0
- package/dist/esm/core/index.d.ts +6 -4
- package/dist/esm/core/index.js +4 -2
- package/dist/esm/core/index.js.map +1 -1
- package/dist/esm/core/login.d.ts +24 -0
- package/dist/esm/core/login.js +85 -0
- package/dist/esm/core/login.js.map +1 -0
- package/dist/esm/core/namespace.d.ts +1 -1
- package/dist/esm/core/namespace.js +1 -1
- package/dist/esm/core/op.d.ts +11 -1
- package/dist/esm/core/timing.d.ts +1 -1
- package/dist/esm/core/timing.js +8 -1
- package/dist/esm/core/timing.js.map +1 -1
- package/dist/esm/core/transport.js +1 -1
- package/dist/esm/core/transport.js.map +1 -1
- package/dist/esm/core/util.d.ts +15 -3
- package/dist/esm/core/util.js +48 -1
- package/dist/esm/core/util.js.map +1 -1
- package/dist/esm/core/ws.d.ts +4 -0
- package/dist/esm/core/ws.js +7 -4
- package/dist/esm/core/ws.js.map +1 -1
- package/dist/esm/generated/client.d.ts +2 -2
- package/dist/esm/generated/client.js +2 -2
- package/dist/esm/generated/errors.d.ts +1 -1
- package/dist/esm/generated/errors.js +30 -0
- package/dist/esm/generated/errors.js.map +1 -1
- package/dist/esm/generated/jobs.js +1 -1
- package/dist/esm/generated/ns/actions.d.ts +48 -6
- package/dist/esm/generated/ns/actions.js +59 -6
- package/dist/esm/generated/ns/actions.js.map +1 -1
- package/dist/esm/generated/ns/infer.d.ts +185 -54
- package/dist/esm/generated/ns/infer.js +28 -74
- package/dist/esm/generated/ns/infer.js.map +1 -1
- package/dist/esm/generated/ns/keys.d.ts +12 -0
- package/dist/esm/generated/ns/keys.js +22 -0
- package/dist/esm/generated/ns/keys.js.map +1 -1
- package/dist/esm/generated/ns/render.d.ts +95 -6
- package/dist/esm/generated/ns/render.js +124 -7
- package/dist/esm/generated/ns/render.js.map +1 -1
- package/dist/esm/generated/ns/requests.d.ts +3 -1
- package/dist/esm/generated/ns/requests.js +3 -1
- package/dist/esm/generated/ns/requests.js.map +1 -1
- package/dist/esm/generated/ns/routines.d.ts +131 -9
- package/dist/esm/generated/ns/routines.js +186 -9
- package/dist/esm/generated/ns/routines.js.map +1 -1
- package/dist/esm/generated/ns/sandboxes.d.ts +298 -31
- package/dist/esm/generated/ns/sandboxes.js +368 -29
- package/dist/esm/generated/ns/sandboxes.js.map +1 -1
- package/dist/esm/generated/ns/vision.d.ts +133 -14
- package/dist/esm/generated/ns/vision.js +158 -12
- package/dist/esm/generated/ns/vision.js.map +1 -1
- package/dist/esm/generated/ns/webhooks.d.ts +8 -5
- package/dist/esm/generated/ns/webhooks.js +8 -5
- package/dist/esm/generated/ns/webhooks.js.map +1 -1
- package/dist/esm/generated/types.d.ts +1956 -301
- package/dist/esm/helpers/agents.d.ts +95 -0
- package/dist/esm/helpers/agents.js +199 -0
- package/dist/esm/helpers/agents.js.map +1 -0
- package/dist/esm/helpers/render.d.ts +15 -0
- package/dist/esm/helpers/render.js +70 -0
- package/dist/esm/helpers/render.js.map +1 -0
- package/dist/esm/helpers/routines.d.ts +61 -0
- package/dist/esm/helpers/routines.js +226 -0
- package/dist/esm/helpers/routines.js.map +1 -0
- package/dist/esm/helpers/sandboxes.d.ts +237 -0
- package/dist/esm/helpers/sandboxes.js +600 -0
- package/dist/esm/helpers/sandboxes.js.map +1 -0
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.js +6 -5
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/routines.d.ts +1 -0
- package/dist/esm/routines.js +5 -0
- package/dist/esm/routines.js.map +1 -0
- package/dist/esm/webhooks.js.map +1 -1
- package/package.json +18 -7
- package/src/core/bytes.ts +112 -0
- package/src/core/client.ts +253 -33
- package/src/core/errors.ts +27 -10
- package/src/core/handle.ts +97 -0
- package/src/core/index.ts +7 -2
- package/src/core/login.ts +98 -0
- package/src/core/namespace.ts +1 -1
- package/src/core/op.ts +11 -1
- package/src/core/timing.ts +7 -2
- package/src/core/transport.ts +1 -1
- package/src/core/util.ts +53 -3
- package/src/core/ws.ts +11 -4
- package/src/generated/client.ts +2 -2
- package/src/generated/errors.ts +60 -0
- package/src/generated/jobs.ts +1 -1
- package/src/generated/ns/actions.ts +69 -6
- package/src/generated/ns/infer.ts +229 -61
- package/src/generated/ns/keys.ts +23 -0
- package/src/generated/ns/render.ts +152 -7
- package/src/generated/ns/requests.ts +3 -1
- package/src/generated/ns/routines.ts +205 -9
- package/src/generated/ns/sandboxes.ts +434 -34
- package/src/generated/ns/vision.ts +168 -14
- package/src/generated/ns/webhooks.ts +8 -5
- package/src/generated/types.ts +2211 -422
- package/src/helpers/agents.ts +300 -0
- package/src/helpers/render.ts +91 -0
- package/src/helpers/routines.ts +278 -0
- package/src/helpers/sandboxes.ts +788 -0
- package/src/index.ts +29 -5
- package/src/routines.ts +5 -0
- package/src/webhooks.ts +5 -1
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
// Hand-written sandbox helpers, exposed as methods of `b3os.sandboxes` (the generator adds thin delegates):
|
|
3
|
+
// readiness (`waitUntilReady`, research A14), long-running services (`startService`), and the processes hosted
|
|
4
|
+
// agent harnesses run inside a sandbox (research A15). Everything here is built on the generated operations
|
|
5
|
+
// (exec, listProcesses, streamLogs, createPortUrl), so it works over every route the SDK has: the node socket, a
|
|
6
|
+
// sandbox's B3OS_API_URL and the edge.
|
|
7
|
+
|
|
8
|
+
import type { BinaryInput, RequestOptions } from "../core/client.ts";
|
|
9
|
+
import { B3OSError } from "../core/errors.ts";
|
|
10
|
+
import { APIPromise, type WithResponse } from "../core/promise.ts";
|
|
11
|
+
import { ResponseInfo, remember } from "../core/response.ts";
|
|
12
|
+
import { uuid } from "../core/util.ts";
|
|
13
|
+
import type { PtySession } from "../core/ws.ts";
|
|
14
|
+
import type { RenderAPI } from "../generated/ns/render.ts";
|
|
15
|
+
import type { SandboxesAPI } from "../generated/ns/sandboxes.ts";
|
|
16
|
+
import type { VisionAPI } from "../generated/ns/vision.ts";
|
|
17
|
+
import type * as T from "../generated/types.ts";
|
|
18
|
+
|
|
19
|
+
/** What "ready" means for a sandbox. */
|
|
20
|
+
export type ReadyProbe =
|
|
21
|
+
/** A TCP connection to `host:port` inside the sandbox succeeds (default host 127.0.0.1). */
|
|
22
|
+
| { port: number; host?: string }
|
|
23
|
+
/** An HTTP GET inside the sandbox answers `status` (a code, a list, or a test; default 200-399). */
|
|
24
|
+
| { http: string | { port: number; path?: string }; status?: number | readonly number[] | ((s: number) => boolean) }
|
|
25
|
+
/** A command exits 0 (argv array, or a string run with /bin/sh -c). */
|
|
26
|
+
| { exec: string | readonly string[] }
|
|
27
|
+
/** A background process prints a whole line matching `log` (stdout or stderr; tested once the line is complete). */
|
|
28
|
+
| { log: string | RegExp; pid: number };
|
|
29
|
+
|
|
30
|
+
export interface ReadyOptions extends RequestOptions {
|
|
31
|
+
/** Give up after this long (default 60 s). */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** First retry after this long, then backing off (default 25 ms). */
|
|
34
|
+
intervalMs?: number;
|
|
35
|
+
/** Longest gap between attempts (default 250 ms). */
|
|
36
|
+
maxIntervalMs?: number;
|
|
37
|
+
/** A background process the readiness depends on: fail at once if it exits before the probe passes. */
|
|
38
|
+
pid?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ReadyResult {
|
|
42
|
+
/** Milliseconds from the call to the first passing probe (client side). */
|
|
43
|
+
readyMs: number;
|
|
44
|
+
/** Probe attempts made (1 when it was ready on the first try). */
|
|
45
|
+
attempts: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const sleep = (ms: number, signal?: AbortSignal) =>
|
|
49
|
+
new Promise<void>((resolve, reject) => {
|
|
50
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
51
|
+
const t = setTimeout(() => {
|
|
52
|
+
signal?.removeEventListener("abort", onAbort);
|
|
53
|
+
resolve();
|
|
54
|
+
}, ms);
|
|
55
|
+
const onAbort = () => {
|
|
56
|
+
clearTimeout(t);
|
|
57
|
+
reject(signal?.reason);
|
|
58
|
+
};
|
|
59
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/** The per-request options inside readiness and service options (their `timeoutMs` is the overall wait). */
|
|
63
|
+
function requestOptions(o: RequestOptions): RequestOptions {
|
|
64
|
+
const out: RequestOptions = {};
|
|
65
|
+
if (o.signal) out.signal = o.signal;
|
|
66
|
+
if (o.headers) out.headers = o.headers;
|
|
67
|
+
if (o.traceparent) out.traceparent = o.traceparent;
|
|
68
|
+
if (o.maxRetries !== undefined) out.maxRetries = o.maxRetries;
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function q(s: string): string {
|
|
73
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The command one probe runs inside the sandbox, and how to read its result. */
|
|
77
|
+
function probeCommand(p: Exclude<ReadyProbe, { log: unknown }>): { cmd: string[]; ok: (r: T.ExecResult) => boolean } {
|
|
78
|
+
if ("port" in p) {
|
|
79
|
+
const host = p.host ?? "127.0.0.1";
|
|
80
|
+
if (!Number.isInteger(p.port) || p.port < 1 || p.port > 65535) {
|
|
81
|
+
throw new B3OSError({ code: "invalid_request", status: null, detail: `port must be 1-65535, got ${p.port}` });
|
|
82
|
+
}
|
|
83
|
+
if (!/^[A-Za-z0-9.:-]+$/.test(host)) {
|
|
84
|
+
throw new B3OSError({
|
|
85
|
+
code: "invalid_request",
|
|
86
|
+
status: null,
|
|
87
|
+
detail: `host ${JSON.stringify(host)} is not a host`,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
// bash's /dev/tcp connects without any extra binary; python3 is the fallback (every template has one).
|
|
91
|
+
const py = `import socket,sys;socket.create_connection((sys.argv[1],int(sys.argv[2])),1).close()`;
|
|
92
|
+
return {
|
|
93
|
+
cmd: [
|
|
94
|
+
"/bin/sh",
|
|
95
|
+
"-c",
|
|
96
|
+
`if command -v bash >/dev/null 2>&1; then exec bash -c 'exec 3<>/dev/tcp/${host}/${p.port}' 2>/dev/null; ` +
|
|
97
|
+
`else exec python3 -c ${q(py)} ${q(host)} ${p.port} 2>/dev/null; fi`,
|
|
98
|
+
],
|
|
99
|
+
ok: (r) => r.exit_code === 0,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if ("http" in p) {
|
|
103
|
+
const url =
|
|
104
|
+
typeof p.http === "string"
|
|
105
|
+
? p.http
|
|
106
|
+
: `http://127.0.0.1:${p.http.port}${(p.http.path ?? "/").startsWith("/") ? (p.http.path ?? "/") : `/${p.http.path}`}`;
|
|
107
|
+
if (!/^https?:\/\//.test(url)) {
|
|
108
|
+
throw new B3OSError({
|
|
109
|
+
code: "invalid_request",
|
|
110
|
+
status: null,
|
|
111
|
+
detail: `http probe needs an http(s) URL, got ${url}`,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const want = p.status;
|
|
115
|
+
const accept = (s: number) =>
|
|
116
|
+
typeof want === "function"
|
|
117
|
+
? want(s)
|
|
118
|
+
: typeof want === "number"
|
|
119
|
+
? s === want
|
|
120
|
+
: Array.isArray(want)
|
|
121
|
+
? want.includes(s)
|
|
122
|
+
: s >= 200 && s < 400;
|
|
123
|
+
// Prints the status code (000 when nothing answered); urllib reports 4xx/5xx through HTTPError.
|
|
124
|
+
const py =
|
|
125
|
+
"import sys,urllib.request as u,urllib.error as e\n" +
|
|
126
|
+
"try:\n print(u.urlopen(u.Request(sys.argv[1],method='GET'),timeout=2).status)\n" +
|
|
127
|
+
"except e.HTTPError as x:\n print(x.code)\nexcept Exception:\n print('000')";
|
|
128
|
+
return {
|
|
129
|
+
cmd: ["python3", "-c", py, url],
|
|
130
|
+
ok: (r) => r.exit_code === 0 && accept(Number.parseInt(r.stdout.trim(), 10) || 0),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
const c = p.exec;
|
|
134
|
+
return { cmd: typeof c === "string" ? ["/bin/sh", "-c", c] : [...c], ok: (r) => r.exit_code === 0 };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function processExited(api: SandboxesAPI, sandboxId: string, pid: number, o: RequestOptions) {
|
|
138
|
+
const list = await api.listProcesses(sandboxId, o);
|
|
139
|
+
const p = list.data.find((x) => x.pid === pid);
|
|
140
|
+
return !p || p.status === "exited" ? (p ?? null) : undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function exitedError(sandboxId: string, pid: number, p: T.SandboxProcess | null): B3OSError {
|
|
144
|
+
const how = p
|
|
145
|
+
? p.exit_code !== null
|
|
146
|
+
? `exited ${p.exit_code}`
|
|
147
|
+
: `was killed by ${p.signal ?? "a signal"}`
|
|
148
|
+
: "is gone";
|
|
149
|
+
return new B3OSError({
|
|
150
|
+
code: "process_exited",
|
|
151
|
+
status: null,
|
|
152
|
+
detail: `process ${pid} in ${sandboxId} ${how} before the sandbox was ready; its output: sandboxes.streamLogs(id, { pid })`,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Polls a probe inside the sandbox until it passes, the process it depends on exits, or `timeoutMs` passes.
|
|
158
|
+
* The first attempt runs at once; later ones back off from `intervalMs` to `maxIntervalMs`.
|
|
159
|
+
*/
|
|
160
|
+
export async function waitUntilReady(
|
|
161
|
+
api: SandboxesAPI,
|
|
162
|
+
sandboxId: string,
|
|
163
|
+
probe: ReadyProbe,
|
|
164
|
+
options: ReadyOptions = {},
|
|
165
|
+
): Promise<ReadyResult> {
|
|
166
|
+
const { timeoutMs = 60_000, intervalMs = 25, maxIntervalMs = 250, pid } = options;
|
|
167
|
+
const o = requestOptions(options);
|
|
168
|
+
const t0 = performance.now();
|
|
169
|
+
const deadline = t0 + timeoutMs;
|
|
170
|
+
if ("log" in probe) return waitForLog(api, sandboxId, probe, timeoutMs, o, t0);
|
|
171
|
+
const { cmd, ok } = probeCommand(probe);
|
|
172
|
+
let attempts = 0;
|
|
173
|
+
let delay = intervalMs;
|
|
174
|
+
let last = "";
|
|
175
|
+
for (;;) {
|
|
176
|
+
attempts++;
|
|
177
|
+
const left = deadline - performance.now();
|
|
178
|
+
const r = await api.exec(sandboxId, { cmd, timeout_ms: Math.max(100, Math.min(5_000, Math.floor(left))) }, o);
|
|
179
|
+
if (ok(r)) return { readyMs: performance.now() - t0, attempts };
|
|
180
|
+
if (r.exit_code === 127) {
|
|
181
|
+
throw new B3OSError({
|
|
182
|
+
code: "unsupported_transport",
|
|
183
|
+
status: null,
|
|
184
|
+
detail: `the readiness probe needs a program the sandbox lacks: ${r.stderr.trim().slice(0, 200)}`,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
last = (r.stderr || r.stdout).trim().slice(0, 200);
|
|
188
|
+
if (pid !== undefined) {
|
|
189
|
+
const gone = await processExited(api, sandboxId, pid, o);
|
|
190
|
+
if (gone !== undefined) throw exitedError(sandboxId, pid, gone);
|
|
191
|
+
}
|
|
192
|
+
if (performance.now() + delay >= deadline) {
|
|
193
|
+
throw new B3OSError({
|
|
194
|
+
code: "timeout",
|
|
195
|
+
status: null,
|
|
196
|
+
detail: `${sandboxId} was not ready after ${timeoutMs} ms (${attempts} probes${last ? `; last: ${last}` : ""})`,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
await sleep(delay, o.signal);
|
|
200
|
+
delay = Math.min(maxIntervalMs, delay * 2);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function waitForLog(
|
|
205
|
+
api: SandboxesAPI,
|
|
206
|
+
sandboxId: string,
|
|
207
|
+
probe: { log: string | RegExp; pid: number },
|
|
208
|
+
timeoutMs: number,
|
|
209
|
+
o: RequestOptions,
|
|
210
|
+
t0: number,
|
|
211
|
+
): Promise<ReadyResult> {
|
|
212
|
+
const match =
|
|
213
|
+
typeof probe.log === "string"
|
|
214
|
+
? (s: string) => s.includes(probe.log as string)
|
|
215
|
+
: (s: string) => (probe.log as RegExp).test(s);
|
|
216
|
+
const ac = new AbortController();
|
|
217
|
+
const onAbort = () => ac.abort(o.signal?.reason);
|
|
218
|
+
o.signal?.addEventListener("abort", onAbort, { once: true });
|
|
219
|
+
const timer = setTimeout(() => ac.abort(new Error("timeout")), timeoutMs);
|
|
220
|
+
// Complete lines only, one buffer per stream (log.stdout, log.stderr): a chunk can end mid-line, and a pattern
|
|
221
|
+
// must not match a fragment of a line that is still being written. What is left unterminated is tested once,
|
|
222
|
+
// when the process exits or the stream ends.
|
|
223
|
+
let lines = 0;
|
|
224
|
+
const bufs = new Map<string, string>();
|
|
225
|
+
const test = (line: string) => {
|
|
226
|
+
lines++;
|
|
227
|
+
return match(line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
228
|
+
};
|
|
229
|
+
const rest = () => {
|
|
230
|
+
for (const [k, b] of bufs) {
|
|
231
|
+
bufs.delete(k);
|
|
232
|
+
if (b && test(b)) return true;
|
|
233
|
+
}
|
|
234
|
+
return false;
|
|
235
|
+
};
|
|
236
|
+
const ready = () => ({ readyMs: performance.now() - t0, attempts: lines });
|
|
237
|
+
try {
|
|
238
|
+
for await (const ev of api.streamLogs(sandboxId, { pid: probe.pid, follow: true }, { ...o, signal: ac.signal })) {
|
|
239
|
+
const e = ev as { type: string; data?: string };
|
|
240
|
+
if (e.type === "process.exited") {
|
|
241
|
+
if (rest()) return ready();
|
|
242
|
+
const gone = await processExited(api, sandboxId, probe.pid, o).catch(() => null);
|
|
243
|
+
throw exitedError(sandboxId, probe.pid, gone ?? null);
|
|
244
|
+
}
|
|
245
|
+
if (typeof e.data !== "string") continue;
|
|
246
|
+
const parts = ((bufs.get(e.type) ?? "") + e.data).split("\n");
|
|
247
|
+
bufs.set(e.type, parts.pop() ?? "");
|
|
248
|
+
for (const line of parts) if (test(line)) return ready();
|
|
249
|
+
}
|
|
250
|
+
if (rest()) return ready();
|
|
251
|
+
throw exitedError(sandboxId, probe.pid, null);
|
|
252
|
+
} catch (e) {
|
|
253
|
+
if (ac.signal.aborted && !o.signal?.aborted) {
|
|
254
|
+
throw new B3OSError({
|
|
255
|
+
code: "timeout",
|
|
256
|
+
status: null,
|
|
257
|
+
detail: `process ${probe.pid} in ${sandboxId} printed nothing matching ${String(probe.log)} in ${timeoutMs} ms`,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
throw e;
|
|
261
|
+
} finally {
|
|
262
|
+
clearTimeout(timer);
|
|
263
|
+
o.signal?.removeEventListener("abort", onAbort);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export interface ServiceOptions extends ReadyOptions {
|
|
268
|
+
cmd: string | readonly string[];
|
|
269
|
+
cwd?: string;
|
|
270
|
+
env?: Record<string, string>;
|
|
271
|
+
user?: "user" | "root";
|
|
272
|
+
/** When the service counts as up; without one, startService returns once the process started. */
|
|
273
|
+
ready?: ReadyProbe;
|
|
274
|
+
/** Mint a preview URL for this port once ready (the port must be in the sandbox's `ports`). */
|
|
275
|
+
previewPort?: number;
|
|
276
|
+
/** Lifetime of a private preview URL, in seconds. */
|
|
277
|
+
previewTtlS?: number;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export interface Service {
|
|
281
|
+
pid: number;
|
|
282
|
+
process: T.SandboxProcess;
|
|
283
|
+
/** Client-side milliseconds from the start request to the passing probe (absent without `ready`). */
|
|
284
|
+
readyMs?: number;
|
|
285
|
+
/** The preview URL, when `previewPort` was given. */
|
|
286
|
+
url?: string;
|
|
287
|
+
/** Sends TERM (or the given signal) to the service's process group. */
|
|
288
|
+
stop(signal?: "TERM" | "KILL" | "INT" | "HUP"): Promise<T.SandboxProcess>;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Starts a background process (a server, a worker) and waits until it is ready. */
|
|
292
|
+
export async function startService(api: SandboxesAPI, sandboxId: string, options: ServiceOptions): Promise<Service> {
|
|
293
|
+
const { cmd, cwd, env, user, ready, previewPort, previewTtlS, ...waitOptions } = options;
|
|
294
|
+
const wait = requestOptions(options);
|
|
295
|
+
const t0 = performance.now();
|
|
296
|
+
const body: T.ExecRequest & { background: true } = {
|
|
297
|
+
cmd: typeof cmd === "string" ? cmd : [...cmd],
|
|
298
|
+
background: true,
|
|
299
|
+
...(cwd ? { cwd } : {}),
|
|
300
|
+
...(env ? { env } : {}),
|
|
301
|
+
...(user ? { user } : {}),
|
|
302
|
+
};
|
|
303
|
+
const proc = await api.exec(sandboxId, body, wait);
|
|
304
|
+
const stop = (signal: "TERM" | "KILL" | "INT" | "HUP" = "TERM") =>
|
|
305
|
+
api.killProcess(sandboxId, proc.pid, { signal }, wait) as Promise<T.SandboxProcess>;
|
|
306
|
+
let readyMs: number | undefined;
|
|
307
|
+
if (ready) {
|
|
308
|
+
try {
|
|
309
|
+
await waitUntilReady(api, sandboxId, ready, { ...waitOptions, pid: proc.pid });
|
|
310
|
+
readyMs = performance.now() - t0;
|
|
311
|
+
} catch (e) {
|
|
312
|
+
await stop().catch(() => undefined);
|
|
313
|
+
throw e;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
let url: string | undefined;
|
|
317
|
+
if (previewPort !== undefined) {
|
|
318
|
+
const u = await api.createPortUrl(
|
|
319
|
+
sandboxId,
|
|
320
|
+
previewPort,
|
|
321
|
+
previewTtlS === undefined ? undefined : { ttl_s: previewTtlS },
|
|
322
|
+
wait,
|
|
323
|
+
);
|
|
324
|
+
url = u.url;
|
|
325
|
+
}
|
|
326
|
+
return { pid: proc.pid, process: proc, ...(readyMs !== undefined ? { readyMs } : {}), ...(url ? { url } : {}), stop };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Answers that refused the create before it ran: retried as they are. */
|
|
330
|
+
const NEVER_RAN = new Set([
|
|
331
|
+
"rate_limited",
|
|
332
|
+
"concurrency_limited",
|
|
333
|
+
"node_unavailable",
|
|
334
|
+
"product_unavailable",
|
|
335
|
+
"capacity_unavailable",
|
|
336
|
+
"auth_unavailable",
|
|
337
|
+
]);
|
|
338
|
+
|
|
339
|
+
/** After these the create may have run: the request left and no answer came back (or a CDN's 5xx page did). */
|
|
340
|
+
function ambiguous(e: B3OSError): boolean {
|
|
341
|
+
return e.code === "connection_error" || (e.status !== null && e.status >= 500 && e.code === "internal");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** What happens to a sandbox at `expires_at`: `stop` (the default) or `pause`. */
|
|
345
|
+
export type OnTimeout = "stop" | "pause";
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* The body `createSandbox` and `sandboxes.create` take: the API's `SandboxCreateRequest`, with `on_timeout` for
|
|
349
|
+
* what happens at `expires_at`. The API calls that setting `on_idle`, a name that suggests idleness; it is renamed
|
|
350
|
+
* `on_timeout` before it becomes a stored setting (dx#7). The SDK sends it as `on_idle` until the API takes the
|
|
351
|
+
* new name too, and `on_idle` keeps working.
|
|
352
|
+
*/
|
|
353
|
+
export type SandboxCreateBody = Omit<T.SandboxCreateRequest, "on_idle"> & {
|
|
354
|
+
/**
|
|
355
|
+
* What happens at `expires_at`: `stop` (default) destroys the sandbox; `pause` pauses it and keeps it for one
|
|
356
|
+
* hour, so you can extend its timeout and resume it.
|
|
357
|
+
*/
|
|
358
|
+
on_timeout?: OnTimeout;
|
|
359
|
+
/** @deprecated The old name of `on_timeout`; it does the same. */
|
|
360
|
+
on_idle?: OnTimeout;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
/** The create body as the API reads it today: `on_timeout` goes as `on_idle`. Both, set differently, is refused. */
|
|
364
|
+
export function createBodyOnWire(body: SandboxCreateBody | undefined): T.SandboxCreateRequest {
|
|
365
|
+
if (!body || body.on_timeout === undefined) return (body ?? {}) as T.SandboxCreateRequest;
|
|
366
|
+
const { on_timeout, ...rest } = body;
|
|
367
|
+
if (rest.on_idle !== undefined && rest.on_idle !== on_timeout) {
|
|
368
|
+
throw new B3OSError({
|
|
369
|
+
code: "invalid_request",
|
|
370
|
+
status: null,
|
|
371
|
+
detail: `on_timeout is "${on_timeout}" and on_idle, its old name, is "${rest.on_idle}": pass on_timeout alone`,
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
return { ...rest, on_idle: on_timeout };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** The longest the SDK waits, in total, for the first create of a key that is still running. */
|
|
378
|
+
const IN_PROGRESS_WAIT_MS = 60_000;
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* createSandbox, sent again with the same Idempotency-Key after a lost answer. b3osd runs a keyed create to the end
|
|
382
|
+
* and stores its answer even when the client goes away (crates/b3os-core/src/web.rs `run_detached`; b3osd test
|
|
383
|
+
* `idempotent_requests_finish_when_the_client_disconnects`), so the resend gets the first create's sandbox
|
|
384
|
+
* (`Idempotent-Replayed: true`) instead of making a second one. While that create still runs the node answers
|
|
385
|
+
* 409 `idempotency_request_in_progress`; those waits (Retry-After, at most 60 s in all) are not counted as
|
|
386
|
+
* retries. Answers that refused the create before it ran (429, 503 with a problem body) are retried too. The body
|
|
387
|
+
* goes as you gave it, with `on_timeout` sent as `on_idle` (createBodyOnWire): the key never enters your
|
|
388
|
+
* `metadata` (dx#9). `options.maxRetries` overrides the client's `maxRetries` (`clientMaxRetries`), as for every
|
|
389
|
+
* other call.
|
|
390
|
+
*/
|
|
391
|
+
export function createSandboxSafely(
|
|
392
|
+
send: (body: T.SandboxCreateRequest, o: RequestOptions) => APIPromise<T.Sandbox>,
|
|
393
|
+
body: SandboxCreateBody | undefined,
|
|
394
|
+
options: RequestOptions = {},
|
|
395
|
+
clientMaxRetries = 2,
|
|
396
|
+
): APIPromise<T.Sandbox> {
|
|
397
|
+
const key = options.idempotencyKey ?? uuid();
|
|
398
|
+
const retries = options.maxRetries ?? clientMaxRetries;
|
|
399
|
+
const run = async (): Promise<WithResponse<T.Sandbox>> => {
|
|
400
|
+
const b = createBodyOnWire(body);
|
|
401
|
+
let attempt = 0;
|
|
402
|
+
let sent = 0;
|
|
403
|
+
let waitedMs = 0;
|
|
404
|
+
for (;;) {
|
|
405
|
+
try {
|
|
406
|
+
sent++;
|
|
407
|
+
// No retries inside the client: this loop decides, so an ambiguous failure is never resent without its key.
|
|
408
|
+
const r = await send(b, { ...options, idempotencyKey: key, maxRetries: 0 }).withResponse();
|
|
409
|
+
if (sent === 1) return r;
|
|
410
|
+
const x = r.response;
|
|
411
|
+
const response = new ResponseInfo({
|
|
412
|
+
operationId: x.operationId,
|
|
413
|
+
method: x.method,
|
|
414
|
+
url: x.url,
|
|
415
|
+
status: x.status,
|
|
416
|
+
headers: x.headers,
|
|
417
|
+
transport: x.transport,
|
|
418
|
+
attempts: sent,
|
|
419
|
+
elapsedMs: x.elapsedMs,
|
|
420
|
+
idempotencyKey: x.idempotencyKey,
|
|
421
|
+
});
|
|
422
|
+
remember(r.data, response);
|
|
423
|
+
return { data: r.data, response };
|
|
424
|
+
} catch (e) {
|
|
425
|
+
if (!(e instanceof B3OSError)) throw e;
|
|
426
|
+
if (e.code === "idempotency_request_in_progress") {
|
|
427
|
+
// The first create of this key is still running on the node: wait for its stored answer.
|
|
428
|
+
const wait = e.retryAfterMs ?? 1000;
|
|
429
|
+
if (waitedMs + wait > IN_PROGRESS_WAIT_MS) throw e;
|
|
430
|
+
waitedMs += wait;
|
|
431
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (attempt >= retries) throw e;
|
|
435
|
+
attempt++;
|
|
436
|
+
if (NEVER_RAN.has(e.code) || (e.status === 429 && e.retryable)) {
|
|
437
|
+
const wait = e.retryAfterMs ?? 500 * 2 ** (attempt - 1);
|
|
438
|
+
if (wait > 60_000) throw e;
|
|
439
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (!ambiguous(e)) throw e;
|
|
443
|
+
await new Promise((r) => setTimeout(r, 250 * 2 ** (attempt - 1)));
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
return new APIPromise<T.Sandbox>(run());
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// ------------------------------------------------------------------------------------------------ Sandbox handle
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* What a {@link Sandbox} handle needs of a client: `new B3OS()` has all of it. `render` and `vision` are used only
|
|
454
|
+
* by `ports.screenshot` and `ports.scrape`.
|
|
455
|
+
*/
|
|
456
|
+
export interface SandboxClient {
|
|
457
|
+
sandboxes: SandboxesAPI;
|
|
458
|
+
render?: Pick<RenderAPI, "createScreenshot">;
|
|
459
|
+
vision?: Pick<VisionAPI, "scrape">;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export interface SandboxExecOptions extends RequestOptions {
|
|
463
|
+
/** Called with each stdout chunk as it arrives (the command is then streamed: up to an hour). */
|
|
464
|
+
onStdout?: (data: string) => void;
|
|
465
|
+
/** Called with each stderr chunk as it arrives (the command is then streamed). */
|
|
466
|
+
onStderr?: (data: string) => void;
|
|
467
|
+
cwd?: string;
|
|
468
|
+
env?: Record<string, string>;
|
|
469
|
+
/** Written to standard input, which is then closed. */
|
|
470
|
+
stdin?: string;
|
|
471
|
+
/** Kill the command after this long (default 30 s; at most 60 s unless streamed). */
|
|
472
|
+
commandTimeoutMs?: number;
|
|
473
|
+
user?: "user" | "root";
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** A finished command. */
|
|
477
|
+
export interface SandboxExecOutput {
|
|
478
|
+
/** The exit status; `null` when a signal killed it. */
|
|
479
|
+
exitCode: number | null;
|
|
480
|
+
signal: string | null;
|
|
481
|
+
timedOut: boolean;
|
|
482
|
+
stdout: string;
|
|
483
|
+
stderr: string;
|
|
484
|
+
durationMs: number | null;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Files inside the sandbox (`/v1/sandboxes/{id}/files`, `files/stat`, `files/move`, `files/mkdir`). */
|
|
488
|
+
export interface SandboxFiles {
|
|
489
|
+
/** The file's bytes. */
|
|
490
|
+
read(path: string, options?: RequestOptions): Promise<Uint8Array>;
|
|
491
|
+
/** The file as UTF-8 text. */
|
|
492
|
+
readText(path: string, options?: RequestOptions): Promise<string>;
|
|
493
|
+
/** Write (replace) a file; `mkdir` creates missing parent directories. */
|
|
494
|
+
write(
|
|
495
|
+
path: string,
|
|
496
|
+
data: string | BinaryInput,
|
|
497
|
+
options?: RequestOptions & { mkdir?: boolean; mode?: string },
|
|
498
|
+
): Promise<T.FileEntry>;
|
|
499
|
+
/** The entries of a directory (or the one entry of a file). */
|
|
500
|
+
list(path: string, options?: RequestOptions): Promise<T.FileEntry[]>;
|
|
501
|
+
/** The entry at `path`, not following a final symlink; a missing path throws `file_not_found`. */
|
|
502
|
+
stat(path: string, options?: RequestOptions): Promise<T.FileEntry>;
|
|
503
|
+
/** Delete a file, a symlink or an empty directory; `recursive` deletes a directory and everything in it. */
|
|
504
|
+
delete(path: string, options?: RequestOptions & { recursive?: boolean }): Promise<T.FileDeleted>;
|
|
505
|
+
/** Move or rename; an existing `to` throws `file_exists` unless `overwrite`. Answers the entry at `to`. */
|
|
506
|
+
move(from: string, to: string, options?: RequestOptions & { overwrite?: boolean }): Promise<T.FileEntry>;
|
|
507
|
+
/** Create a directory and its missing parents (`mkdir -p`); an existing directory is answered as it is. */
|
|
508
|
+
mkdir(path: string, options?: RequestOptions & { mode?: string }): Promise<T.FileEntry>;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Ports inside the sandbox, reached through preview URLs. */
|
|
512
|
+
export interface SandboxPorts {
|
|
513
|
+
/** A URL that reaches `port` (it must be declared in `ports` at create): signed, valid `ttlS` (default 600 s). */
|
|
514
|
+
url(port: number, options?: RequestOptions & { ttlS?: number }): Promise<string>;
|
|
515
|
+
/**
|
|
516
|
+
* A styled screenshot of the app on `port` (render), through a fresh preview URL. `path` is appended to it;
|
|
517
|
+
* `body` takes every other screenshot field.
|
|
518
|
+
*/
|
|
519
|
+
screenshot(
|
|
520
|
+
port: number,
|
|
521
|
+
body?: Omit<T.ScreenshotCreateRequest, "url" | "html"> & { path?: string },
|
|
522
|
+
options?: RequestOptions,
|
|
523
|
+
): Promise<T.Screenshot>;
|
|
524
|
+
/** The page on `port` at `path`, scraped (vision), through a fresh preview URL. */
|
|
525
|
+
scrape(
|
|
526
|
+
port: number,
|
|
527
|
+
path?: string,
|
|
528
|
+
body?: Omit<T.ScrapeRequest, "url">,
|
|
529
|
+
options?: RequestOptions,
|
|
530
|
+
): Promise<T.ScrapeResult>;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const textDecoder = new TextDecoder();
|
|
534
|
+
|
|
535
|
+
function joinPath(base: string, path: string | undefined): string {
|
|
536
|
+
if (!path) return base;
|
|
537
|
+
return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function execBody(cmd: string | readonly string[], o: SandboxExecOptions): T.ExecRequest {
|
|
541
|
+
const b: T.ExecRequest = { cmd: typeof cmd === "string" ? cmd : [...cmd] };
|
|
542
|
+
if (o.cwd !== undefined) b.cwd = o.cwd;
|
|
543
|
+
if (o.env !== undefined) b.env = o.env;
|
|
544
|
+
if (o.stdin !== undefined) b.stdin = o.stdin;
|
|
545
|
+
if (o.commandTimeoutMs !== undefined) b.timeout_ms = o.commandTimeoutMs;
|
|
546
|
+
if (o.user !== undefined) b.user = o.user;
|
|
547
|
+
return b;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function execRequestOptions(o: SandboxExecOptions): RequestOptions {
|
|
551
|
+
const { onStdout: _o, onStderr: _e, cwd: _c, env: _v, stdin: _s, commandTimeoutMs: _t, user: _u, ...rest } = o;
|
|
552
|
+
return rest;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* A sandbox you hold: every operation of `b3os.sandboxes` bound to one id, plus `files`, `ports` and disposal. The
|
|
557
|
+
* API's sandbox object (what `createSandbox` and `getSandbox` return) is the type `SandboxInfo`, in `sbx.info`.
|
|
558
|
+
*
|
|
559
|
+
* await using sbx = await Sandbox.create(b3os, { template: "base" });
|
|
560
|
+
* await sbx.exec("echo hi", { onStdout: (d) => process.stdout.write(d) });
|
|
561
|
+
* // leaving the scope deletes the sandbox
|
|
562
|
+
*
|
|
563
|
+
* `create` is idempotent across retries (createSandboxSafely). Disposal deletes the sandbox and treats an
|
|
564
|
+
* already-gone one as deleted; call `detach()` first to keep it running past the scope.
|
|
565
|
+
*/
|
|
566
|
+
export class Sandbox implements AsyncDisposable {
|
|
567
|
+
readonly id: string;
|
|
568
|
+
/** The sandbox as last seen (create, fork, refresh, pause, resume, extend): a `SandboxInfo`. */
|
|
569
|
+
info: T.Sandbox;
|
|
570
|
+
readonly files: SandboxFiles;
|
|
571
|
+
readonly ports: SandboxPorts;
|
|
572
|
+
readonly #client: SandboxClient;
|
|
573
|
+
#disposed = false;
|
|
574
|
+
#detached = false;
|
|
575
|
+
|
|
576
|
+
protected constructor(client: SandboxClient, info: T.Sandbox) {
|
|
577
|
+
this.#client = client;
|
|
578
|
+
this.id = info.id;
|
|
579
|
+
this.info = info;
|
|
580
|
+
const api = client.sandboxes;
|
|
581
|
+
const id = info.id;
|
|
582
|
+
this.files = {
|
|
583
|
+
read: (path, options) => api.readFile(id, { path }, options).then((b) => b),
|
|
584
|
+
readText: (path, options) => api.readFile(id, { path }, options).then((b) => textDecoder.decode(b)),
|
|
585
|
+
write: (path, data, options = {}) => {
|
|
586
|
+
const { mkdir, mode, ...o } = options;
|
|
587
|
+
const params: T.SandboxesWriteFileParams = { path };
|
|
588
|
+
if (mkdir) params.mkdir = 1;
|
|
589
|
+
if (mode !== undefined) params.mode = mode;
|
|
590
|
+
const body = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
591
|
+
return api.writeFile(id, params, body, o).then((e) => e);
|
|
592
|
+
},
|
|
593
|
+
list: (path, options) => api.readFile(id, { path, list: 1 }, options).then((l) => l.data),
|
|
594
|
+
stat: (path, options) => api.statFile(id, { path }, options).then((e) => e),
|
|
595
|
+
delete: (path, options = {}) => {
|
|
596
|
+
const { recursive, ...o } = options;
|
|
597
|
+
const params: T.SandboxesDeleteFileParams = { path };
|
|
598
|
+
if (recursive) params.recursive = 1;
|
|
599
|
+
return api.deleteFile(id, params, o).then((d) => d);
|
|
600
|
+
},
|
|
601
|
+
move: (from, to, options = {}) => {
|
|
602
|
+
const { overwrite, ...o } = options;
|
|
603
|
+
const body: T.MoveFileRequest = { from, to };
|
|
604
|
+
if (overwrite !== undefined) body.overwrite = overwrite;
|
|
605
|
+
return api.moveFile(id, body, o).then((e) => e);
|
|
606
|
+
},
|
|
607
|
+
mkdir: (path, options = {}) => {
|
|
608
|
+
const { mode, ...o } = options;
|
|
609
|
+
const body: T.MakeDirectoryRequest = { path };
|
|
610
|
+
if (mode !== undefined) body.mode = mode;
|
|
611
|
+
return api.makeDirectory(id, body, o).then((e) => e);
|
|
612
|
+
},
|
|
613
|
+
};
|
|
614
|
+
const url = async (port: number, options: RequestOptions & { ttlS?: number } = {}) => {
|
|
615
|
+
const { ttlS, ...o } = options;
|
|
616
|
+
const r = await api.createPortUrl(id, port, ttlS === undefined ? {} : { ttl_s: ttlS }, o);
|
|
617
|
+
return r.url;
|
|
618
|
+
};
|
|
619
|
+
this.ports = {
|
|
620
|
+
url,
|
|
621
|
+
screenshot: async (port, body = {}, options) => {
|
|
622
|
+
const render = this.#need("render", client.render);
|
|
623
|
+
const { path, ...rest } = body;
|
|
624
|
+
return render.createScreenshot({ ...rest, url: joinPath(await url(port), path) }, options);
|
|
625
|
+
},
|
|
626
|
+
scrape: async (port, path, body = {}, options) => {
|
|
627
|
+
const vision = this.#need("vision", client.vision);
|
|
628
|
+
return vision.scrape({ ...body, url: joinPath(await url(port), path) }, options);
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
#need<X>(what: string, x: X | undefined): X {
|
|
634
|
+
if (!x) {
|
|
635
|
+
throw new B3OSError({
|
|
636
|
+
code: "invalid_request",
|
|
637
|
+
status: null,
|
|
638
|
+
detail: `this Sandbox handle was made from a client without ${what}: pass a B3OS client`,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
return x;
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** Create a sandbox and return its handle (`POST /v1/sandboxes`, idempotent across retries). */
|
|
645
|
+
static async create(client: SandboxClient, body?: SandboxCreateBody, options?: RequestOptions): Promise<Sandbox> {
|
|
646
|
+
return new Sandbox(client, await client.sandboxes.createSandbox(body, options));
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** A handle for an existing sandbox (`GET /v1/sandboxes/{id}`). */
|
|
650
|
+
static async connect(client: SandboxClient, sandboxId: string, options?: RequestOptions): Promise<Sandbox> {
|
|
651
|
+
return new Sandbox(client, await client.sandboxes.getSandbox(sandboxId, options));
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Run a command and wait for it. With `onStdout` or `onStderr` the output streams to them as it arrives;
|
|
656
|
+
* either way the result carries all of it. A string runs through `/bin/sh -c`, an array is executed directly.
|
|
657
|
+
*/
|
|
658
|
+
async exec(cmd: string | readonly string[], options: SandboxExecOptions = {}): Promise<SandboxExecOutput> {
|
|
659
|
+
const api = this.#client.sandboxes;
|
|
660
|
+
const body = execBody(cmd, options);
|
|
661
|
+
const o = execRequestOptions(options);
|
|
662
|
+
if (!options.onStdout && !options.onStderr) {
|
|
663
|
+
const r = await api.exec(this.id, body, o);
|
|
664
|
+
return {
|
|
665
|
+
exitCode: r.exit_code,
|
|
666
|
+
signal: r.signal ?? null,
|
|
667
|
+
timedOut: r.timed_out ?? false,
|
|
668
|
+
stdout: r.stdout ?? "",
|
|
669
|
+
stderr: r.stderr ?? "",
|
|
670
|
+
durationMs: r.duration_ms ?? null,
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
let stdout = "";
|
|
674
|
+
let stderr = "";
|
|
675
|
+
for await (const ev of api.exec(this.id, body, { ...o, stream: true })) {
|
|
676
|
+
if (ev.type === "exec.stdout" && typeof ev.data === "string") {
|
|
677
|
+
stdout += ev.data;
|
|
678
|
+
options.onStdout?.(ev.data);
|
|
679
|
+
} else if (ev.type === "exec.stderr" && typeof ev.data === "string") {
|
|
680
|
+
stderr += ev.data;
|
|
681
|
+
options.onStderr?.(ev.data);
|
|
682
|
+
} else if (ev.type === "exec.exit") {
|
|
683
|
+
const err = (ev as { error?: { code?: string; reason?: string; detail?: string } }).error;
|
|
684
|
+
if (err?.code) {
|
|
685
|
+
throw new B3OSError({
|
|
686
|
+
code: err.code,
|
|
687
|
+
status: null,
|
|
688
|
+
detail: err.detail ?? `the command in ${this.id} was cut (${err.reason ?? err.code})`,
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
return {
|
|
692
|
+
exitCode: ev.exit_code ?? null,
|
|
693
|
+
signal: ev.signal ?? null,
|
|
694
|
+
timedOut: ev.timed_out ?? false,
|
|
695
|
+
stdout,
|
|
696
|
+
stderr,
|
|
697
|
+
durationMs: ev.duration_ms ?? null,
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
throw new B3OSError({
|
|
702
|
+
code: "stream_ended",
|
|
703
|
+
status: null,
|
|
704
|
+
detail: `the exec stream of ${this.id} ended before the command exited`,
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** Start a background process (a server, a worker); read its output with `logs`. */
|
|
709
|
+
background(cmd: string | readonly string[], options: SandboxExecOptions = {}): Promise<T.SandboxProcess> {
|
|
710
|
+
return this.#client.sandboxes.exec(
|
|
711
|
+
this.id,
|
|
712
|
+
{ ...execBody(cmd, options), background: true },
|
|
713
|
+
execRequestOptions(options),
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Start a service and wait until it is ready (`startService`). */
|
|
718
|
+
service(options: ServiceOptions): Promise<Service> {
|
|
719
|
+
return startService(this.#client.sandboxes, this.id, options);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Wait until a probe passes inside the sandbox (`waitUntilReady`). */
|
|
723
|
+
waitUntilReady(probe: ReadyProbe, options?: ReadyOptions): Promise<ReadyResult> {
|
|
724
|
+
return waitUntilReady(this.#client.sandboxes, this.id, probe, options);
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** Open a terminal (WebSocket PTY). */
|
|
728
|
+
pty(params?: T.SandboxesOpenPtyParams, options?: RequestOptions): Promise<PtySession> {
|
|
729
|
+
return this.#client.sandboxes.openPty(this.id, params, options);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** Snapshot the sandbox (it keeps running). */
|
|
733
|
+
snapshot(body?: T.SnapshotCreateRequest, options?: RequestOptions): Promise<T.Snapshot> {
|
|
734
|
+
return this.#client.sandboxes.createSnapshot(this.id, body, options).then((x) => x);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Fork into `count` new sandboxes (the source must be `forkable`); one handle each. */
|
|
738
|
+
async fork(count = 1, body: Omit<T.ForkRequest, "count"> = {}, options?: RequestOptions): Promise<Sandbox[]> {
|
|
739
|
+
const r = await this.#client.sandboxes.forkSandbox(this.id, { ...body, count }, options);
|
|
740
|
+
return r.data.map((x) => new Sandbox(this.#client, x));
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Keep the sandbox alive `seconds` from now (`POST …/timeout`). */
|
|
744
|
+
async extend(seconds: number, options?: RequestOptions): Promise<T.Sandbox> {
|
|
745
|
+
this.info = await this.#client.sandboxes.setTimeout(this.id, { timeout_s: seconds }, options);
|
|
746
|
+
return this.info;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
async pause(options?: RequestOptions): Promise<T.Sandbox> {
|
|
750
|
+
this.info = await this.#client.sandboxes.pauseSandbox(this.id, options);
|
|
751
|
+
return this.info;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async resume(options?: RequestOptions): Promise<T.Sandbox> {
|
|
755
|
+
this.info = await this.#client.sandboxes.resumeSandbox(this.id, options);
|
|
756
|
+
return this.info;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** Read the sandbox again (`GET`). */
|
|
760
|
+
async refresh(options?: RequestOptions): Promise<T.Sandbox> {
|
|
761
|
+
this.info = await this.#client.sandboxes.getSandbox(this.id, options);
|
|
762
|
+
return this.info;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** Keep the sandbox running when the handle is disposed. */
|
|
766
|
+
detach(): this {
|
|
767
|
+
this.#detached = true;
|
|
768
|
+
return this;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Delete the sandbox. Once only; a sandbox that is already gone counts as deleted. */
|
|
772
|
+
async kill(options?: RequestOptions): Promise<void> {
|
|
773
|
+
if (this.#disposed) return;
|
|
774
|
+
this.#disposed = true;
|
|
775
|
+
try {
|
|
776
|
+
await this.#client.sandboxes.deleteSandbox(this.id, options);
|
|
777
|
+
} catch (e) {
|
|
778
|
+
if (e instanceof B3OSError && e.status === 404) return;
|
|
779
|
+
this.#disposed = false;
|
|
780
|
+
throw e;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** `await using`: delete the sandbox when the scope ends, unless `detach()` was called. */
|
|
785
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
786
|
+
if (!this.#detached) await this.kill();
|
|
787
|
+
}
|
|
788
|
+
}
|