@computesdk/buddy 1.0.1
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/LICENSE +21 -0
- package/README.md +209 -0
- package/dist/index.d.mts +144 -0
- package/dist/index.d.ts +144 -0
- package/dist/index.js +786 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +758 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { defineProvider } from "@computesdk/provider";
|
|
3
|
+
|
|
4
|
+
// src/utils.ts
|
|
5
|
+
import { API_URLS, BuddyApiClient, FileSystem } from "@buddy-works/sandbox-sdk";
|
|
6
|
+
var PROVIDER = "buddy";
|
|
7
|
+
var DEFAULT_OS = "ubuntu:24.04";
|
|
8
|
+
var DEFAULT_REGION = "US";
|
|
9
|
+
var DEFAULT_TIMEOUT_MS = 36e5;
|
|
10
|
+
var SANDBOX_HOME = "/buddy";
|
|
11
|
+
var MAX_CPU = 12;
|
|
12
|
+
var SETUP_HINT = "Create a token with the SANDBOX_MANAGE scope at https://app.buddy.works/my-id/tokens";
|
|
13
|
+
function apiUrlForRegion(region) {
|
|
14
|
+
return API_URLS[region];
|
|
15
|
+
}
|
|
16
|
+
var resolved = /* @__PURE__ */ new WeakMap();
|
|
17
|
+
var resolvedFromEnv = /* @__PURE__ */ new Map();
|
|
18
|
+
function resolveConfig(config) {
|
|
19
|
+
if (!config) {
|
|
20
|
+
const key = [
|
|
21
|
+
process.env.BUDDY_TOKEN,
|
|
22
|
+
process.env.BUDDY_WORKSPACE,
|
|
23
|
+
process.env.BUDDY_PROJECT
|
|
24
|
+
].join("\0");
|
|
25
|
+
let value2 = resolvedFromEnv.get(key);
|
|
26
|
+
if (!value2) {
|
|
27
|
+
value2 = buildConfig({});
|
|
28
|
+
resolvedFromEnv.clear();
|
|
29
|
+
resolvedFromEnv.set(key, value2);
|
|
30
|
+
}
|
|
31
|
+
return value2;
|
|
32
|
+
}
|
|
33
|
+
const cached = resolved.get(config);
|
|
34
|
+
if (cached) return cached;
|
|
35
|
+
const value = buildConfig(config);
|
|
36
|
+
resolved.set(config, value);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
function buildConfig(config) {
|
|
40
|
+
const token = config.token ?? process.env.BUDDY_TOKEN;
|
|
41
|
+
const workspace = config.workspace ?? process.env.BUDDY_WORKSPACE;
|
|
42
|
+
const project = config.project ?? process.env.BUDDY_PROJECT;
|
|
43
|
+
if (!token) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`Missing Buddy API token.
|
|
46
|
+
|
|
47
|
+
${SETUP_HINT}
|
|
48
|
+
Then pass it: buddy({ token: "xxx" })
|
|
49
|
+
Or set BUDDY_TOKEN in your environment.`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (!workspace) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
'Missing Buddy workspace domain.\n\nIt is the workspace segment of your Buddy URL (https://app.buddy.works/<workspace>/...).\nPass it: buddy({ workspace: "my-workspace" }) or set BUDDY_WORKSPACE.'
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
if (!project) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
'Missing Buddy project name.\n\nSandboxes always belong to a project. Create one in the Buddy UI, then\npass it: buddy({ project: "my-project" }) or set BUDDY_PROJECT.'
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const region = config.region ?? DEFAULT_REGION;
|
|
63
|
+
return {
|
|
64
|
+
token,
|
|
65
|
+
workspace,
|
|
66
|
+
project,
|
|
67
|
+
os: config.os ?? DEFAULT_OS,
|
|
68
|
+
resources: config.resources,
|
|
69
|
+
region,
|
|
70
|
+
timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
|
|
71
|
+
ports: config.ports,
|
|
72
|
+
apiUrl: (config.apiUrl ?? apiUrlForRegion(region)).replace(/\/+$/, "")
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
var clients = /* @__PURE__ */ new WeakMap();
|
|
76
|
+
var CLIENT_REQUEST_TIMEOUT_MS = 12e4;
|
|
77
|
+
function getClient(config) {
|
|
78
|
+
let client = clients.get(config);
|
|
79
|
+
if (!client) {
|
|
80
|
+
client = new BuddyApiClient({
|
|
81
|
+
workspace: config.workspace,
|
|
82
|
+
project_name: config.project,
|
|
83
|
+
apiUrl: config.apiUrl,
|
|
84
|
+
token: config.token,
|
|
85
|
+
timeout: CLIENT_REQUEST_TIMEOUT_MS
|
|
86
|
+
});
|
|
87
|
+
clients.set(config, client);
|
|
88
|
+
}
|
|
89
|
+
return client;
|
|
90
|
+
}
|
|
91
|
+
function statusOf(error) {
|
|
92
|
+
if (typeof error !== "object" || error === null) return void 0;
|
|
93
|
+
const candidate = error;
|
|
94
|
+
const status = candidate.statusCode ?? candidate.status;
|
|
95
|
+
return typeof status === "number" && status > 0 ? status : void 0;
|
|
96
|
+
}
|
|
97
|
+
function messageOf(error) {
|
|
98
|
+
return error instanceof Error ? error.message : String(error);
|
|
99
|
+
}
|
|
100
|
+
function isNotFound(error) {
|
|
101
|
+
const status = statusOf(error);
|
|
102
|
+
if (status === 404) return true;
|
|
103
|
+
return status === 400 && /not (found|find)/i.test(messageOf(error));
|
|
104
|
+
}
|
|
105
|
+
function isUnroutableId(error) {
|
|
106
|
+
return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));
|
|
107
|
+
}
|
|
108
|
+
function isInstanceNotRunning(error) {
|
|
109
|
+
return statusOf(error) === 400 && /instance is not running/i.test(messageOf(error));
|
|
110
|
+
}
|
|
111
|
+
function isOperationInProgress(error) {
|
|
112
|
+
return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));
|
|
113
|
+
}
|
|
114
|
+
function normalizeSandboxPath(path) {
|
|
115
|
+
const absolute = path.startsWith("/") ? path : `${SANDBOX_HOME}/${path}`;
|
|
116
|
+
const segments = [];
|
|
117
|
+
for (const segment of absolute.split("/")) {
|
|
118
|
+
if (segment === "" || segment === ".") continue;
|
|
119
|
+
if (segment === "..") segments.pop();
|
|
120
|
+
else segments.push(segment);
|
|
121
|
+
}
|
|
122
|
+
if (segments.length === 0) {
|
|
123
|
+
throw new Error("Path must not be empty or the filesystem root.");
|
|
124
|
+
}
|
|
125
|
+
return `/${segments.join("/")}`;
|
|
126
|
+
}
|
|
127
|
+
function toContentPath(path) {
|
|
128
|
+
return normalizeSandboxPath(path).slice(1);
|
|
129
|
+
}
|
|
130
|
+
function mapStatus(status) {
|
|
131
|
+
switch (status) {
|
|
132
|
+
case "RUNNING":
|
|
133
|
+
case "STARTING":
|
|
134
|
+
case "RESTORING":
|
|
135
|
+
return "running";
|
|
136
|
+
case "STOPPED":
|
|
137
|
+
case "STOPPING":
|
|
138
|
+
return "stopped";
|
|
139
|
+
case "FAILED":
|
|
140
|
+
return "error";
|
|
141
|
+
default:
|
|
142
|
+
return "stopped";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function resolveResources(options = {}, fallback) {
|
|
146
|
+
if (typeof options.resources === "string") return options.resources;
|
|
147
|
+
const requestedCpu = firstPositiveNumber([options.cpu, options.vcpus, options.cpus]);
|
|
148
|
+
const requestedMemoryGb = memoryToGb(options);
|
|
149
|
+
if (requestedCpu === void 0 && requestedMemoryGb === void 0) return fallback;
|
|
150
|
+
const cpuForMemory = requestedMemoryGb === void 0 ? 0 : Math.ceil(requestedMemoryGb / 2);
|
|
151
|
+
const cpu = Math.min(MAX_CPU, Math.max(1, requestedCpu ?? 0, cpuForMemory));
|
|
152
|
+
return `${cpu}x${cpu * 2}`;
|
|
153
|
+
}
|
|
154
|
+
function firstPositiveNumber(values) {
|
|
155
|
+
for (const value of values) {
|
|
156
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) return Math.ceil(value);
|
|
157
|
+
}
|
|
158
|
+
return void 0;
|
|
159
|
+
}
|
|
160
|
+
function memoryToGb(options) {
|
|
161
|
+
const mb = firstPositiveNumber([options.memory, options.memoryMb]);
|
|
162
|
+
if (mb !== void 0) return mb / 1024;
|
|
163
|
+
const mib = firstPositiveNumber([options.memoryMiB, options.memMiB]);
|
|
164
|
+
if (mib !== void 0) return mib * 1024 * 1024 / 1e9;
|
|
165
|
+
return void 0;
|
|
166
|
+
}
|
|
167
|
+
function toIdentifier(value) {
|
|
168
|
+
const cleaned = value.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
|
|
169
|
+
return cleaned.slice(0, 60).replace(/^-+|-+$/g, "") || "computesdk";
|
|
170
|
+
}
|
|
171
|
+
function generateSandboxName() {
|
|
172
|
+
return `computesdk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
173
|
+
}
|
|
174
|
+
function normalizePort(input, config) {
|
|
175
|
+
const port = typeof input === "number" ? { port: input } : input;
|
|
176
|
+
return {
|
|
177
|
+
port: port.port,
|
|
178
|
+
name: port.name ?? `p${port.port}`,
|
|
179
|
+
type: port.type ?? "HTTP",
|
|
180
|
+
region: port.region ?? config.region
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function toEndpointPayload(port) {
|
|
184
|
+
return {
|
|
185
|
+
name: port.name,
|
|
186
|
+
endpoint: String(port.port),
|
|
187
|
+
type: port.type,
|
|
188
|
+
region: port.region
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function endpointPublicUrl(endpoint) {
|
|
192
|
+
return endpoint.endpoint_url;
|
|
193
|
+
}
|
|
194
|
+
function endpointMatchesPort(endpoint, port) {
|
|
195
|
+
return Number(endpoint.endpoint) === port;
|
|
196
|
+
}
|
|
197
|
+
var READ_ONLY_ENDPOINT_FIELDS = ["endpoint_url", "active", "target_latency"];
|
|
198
|
+
function toEndpointUpdate(endpoint) {
|
|
199
|
+
const update = { ...endpoint };
|
|
200
|
+
for (const field of READ_ONLY_ENDPOINT_FIELDS) delete update[field];
|
|
201
|
+
return update;
|
|
202
|
+
}
|
|
203
|
+
function applyProtocol(url, protocol) {
|
|
204
|
+
if (!protocol) return url;
|
|
205
|
+
const normalized = protocol.replace(/:$/, "");
|
|
206
|
+
return url.replace(/^[a-z][a-z0-9+.-]*:\/\//i, `${normalized}://`);
|
|
207
|
+
}
|
|
208
|
+
function toHandle(config, sandbox, createdAt = /* @__PURE__ */ new Date(), createdAtIsReconnectTime = true) {
|
|
209
|
+
const sandboxId = sandbox.id;
|
|
210
|
+
if (!sandboxId) {
|
|
211
|
+
throw new Error("Buddy API returned a sandbox without an id.");
|
|
212
|
+
}
|
|
213
|
+
const client = getClient(config);
|
|
214
|
+
return {
|
|
215
|
+
sandboxId,
|
|
216
|
+
identifier: sandbox.identifier ?? sandboxId,
|
|
217
|
+
config,
|
|
218
|
+
client,
|
|
219
|
+
fs: new FileSystem(client, sandboxId),
|
|
220
|
+
createdAt,
|
|
221
|
+
createdAtIsReconnectTime,
|
|
222
|
+
timeout: sandbox.timeout != null ? sandbox.timeout * 1e3 : config.timeout,
|
|
223
|
+
os: sandbox.os,
|
|
224
|
+
resources: sandbox.resources,
|
|
225
|
+
endpoints: sandbox.endpoints ?? []
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
async function getSandboxData(config, sandboxId) {
|
|
229
|
+
return await getClient(config).getSandboxById({ path: { id: sandboxId } });
|
|
230
|
+
}
|
|
231
|
+
async function sleep(ms) {
|
|
232
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/boot.ts
|
|
236
|
+
var BOOT_WAIT_TIMEOUT_MS = 9e4;
|
|
237
|
+
var BOOT_WAIT_POLL_MS = 250;
|
|
238
|
+
var settled = /* @__PURE__ */ new WeakSet();
|
|
239
|
+
async function untilSettled(sandbox) {
|
|
240
|
+
if (settled.has(sandbox)) return;
|
|
241
|
+
const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;
|
|
242
|
+
for (; ; ) {
|
|
243
|
+
const data = await getSandboxData(sandbox.config, sandbox.sandboxId);
|
|
244
|
+
if (data.status === "RUNNING" && data.setup_status === "SUCCESS") {
|
|
245
|
+
settled.add(sandbox);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (data.status === "FAILED" || data.setup_status === "FAILED") {
|
|
249
|
+
throw new Error(
|
|
250
|
+
`Buddy sandbox ${sandbox.sandboxId} failed to start (status: ${data.status}, setup: ${data.setup_status}).`
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
if (Date.now() >= deadline) {
|
|
254
|
+
throw new Error(
|
|
255
|
+
`Buddy sandbox ${sandbox.sandboxId} was still starting after ${BOOT_WAIT_TIMEOUT_MS / 1e3}s (status: ${data.status}, setup: ${data.setup_status}).`
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
await sleep(BOOT_WAIT_POLL_MS);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async function whenBooted(sandbox, operation) {
|
|
262
|
+
await untilSettled(sandbox);
|
|
263
|
+
const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;
|
|
264
|
+
for (; ; ) {
|
|
265
|
+
try {
|
|
266
|
+
return await operation();
|
|
267
|
+
} catch (error) {
|
|
268
|
+
const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);
|
|
269
|
+
if (!retryable || Date.now() >= deadline) throw error;
|
|
270
|
+
await sleep(BOOT_WAIT_POLL_MS);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// src/commands.ts
|
|
276
|
+
import { Command } from "@buddy-works/sandbox-sdk";
|
|
277
|
+
import { escapeShellArg } from "@computesdk/provider";
|
|
278
|
+
var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
279
|
+
function buildShellCommand(command, options = {}) {
|
|
280
|
+
let line = command;
|
|
281
|
+
if (options.env && Object.keys(options.env).length > 0) {
|
|
282
|
+
const exports = Object.entries(options.env).map(([key, value]) => {
|
|
283
|
+
if (!ENV_NAME.test(key)) {
|
|
284
|
+
throw new TypeError(
|
|
285
|
+
`Invalid environment variable name ${JSON.stringify(key)}: names must match /^[A-Za-z_][A-Za-z0-9_]*$/.`
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
return `${key}="${escapeShellArg(String(value))}"`;
|
|
289
|
+
}).join(" ");
|
|
290
|
+
line = `export ${exports} && ${line}`;
|
|
291
|
+
}
|
|
292
|
+
if (options.cwd) {
|
|
293
|
+
line = `cd "${escapeShellArg(options.cwd)}" && ${line}`;
|
|
294
|
+
}
|
|
295
|
+
return line;
|
|
296
|
+
}
|
|
297
|
+
var KILL_ATTEMPTS = 3;
|
|
298
|
+
var KILL_RETRY_DELAY_MS = 500;
|
|
299
|
+
async function killCommand(running) {
|
|
300
|
+
for (let attempt = 1; attempt <= KILL_ATTEMPTS; attempt++) {
|
|
301
|
+
try {
|
|
302
|
+
await running.kill();
|
|
303
|
+
return true;
|
|
304
|
+
} catch {
|
|
305
|
+
if (attempt < KILL_ATTEMPTS) await sleep(KILL_RETRY_DELAY_MS);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
async function runCommand(sandbox, command, options = {}) {
|
|
311
|
+
if (Array.isArray(options)) {
|
|
312
|
+
throw new TypeError(
|
|
313
|
+
`runCommand takes a command line and an options object, not an argument array. Pass the arguments inside the command, e.g. '${command} ${options.join(" ")}'.`
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
const startedAt = Date.now();
|
|
317
|
+
const runtime = options.runtime ?? "BASH";
|
|
318
|
+
const payload = runtime === "BASH" ? buildShellCommand(command, options) : command;
|
|
319
|
+
const deadline = options.timeout ? startedAt + options.timeout : void 0;
|
|
320
|
+
const timedOutResult = (stdout2 = "", stderr2 = "") => ({
|
|
321
|
+
stdout: stdout2,
|
|
322
|
+
stderr: stderr2,
|
|
323
|
+
exitCode: TIMEOUT_EXIT_CODE,
|
|
324
|
+
durationMs: Date.now() - startedAt
|
|
325
|
+
});
|
|
326
|
+
const submission = sandbox.client.executeCommand({
|
|
327
|
+
path: { sandbox_id: sandbox.sandboxId },
|
|
328
|
+
body: { command: payload, runtime }
|
|
329
|
+
});
|
|
330
|
+
const commandResponse = deadline ? await raceDeadline(submission, deadline) : await submission;
|
|
331
|
+
if (commandResponse === DEADLINE_PASSED) {
|
|
332
|
+
void submission.then(
|
|
333
|
+
(response) => {
|
|
334
|
+
if (!response.id) return;
|
|
335
|
+
void killCommand(new Command({
|
|
336
|
+
commandResponse: response,
|
|
337
|
+
client: sandbox.client,
|
|
338
|
+
sandboxId: sandbox.sandboxId
|
|
339
|
+
}));
|
|
340
|
+
},
|
|
341
|
+
() => {
|
|
342
|
+
}
|
|
343
|
+
);
|
|
344
|
+
return timedOutResult();
|
|
345
|
+
}
|
|
346
|
+
const commandId = commandResponse.id;
|
|
347
|
+
if (!commandId) {
|
|
348
|
+
throw new Error("Buddy accepted the command but returned no command id.");
|
|
349
|
+
}
|
|
350
|
+
const running = new Command({
|
|
351
|
+
commandResponse,
|
|
352
|
+
client: sandbox.client,
|
|
353
|
+
sandboxId: sandbox.sandboxId
|
|
354
|
+
});
|
|
355
|
+
if (options.background) {
|
|
356
|
+
return { stdout: "", stderr: "", exitCode: 0, durationMs: Date.now() - startedAt };
|
|
357
|
+
}
|
|
358
|
+
const stdout = [];
|
|
359
|
+
const stderr = [];
|
|
360
|
+
let timedOut = false;
|
|
361
|
+
const drain = (async () => {
|
|
362
|
+
for await (const log of running.logs({ follow: true })) {
|
|
363
|
+
if (timedOut) break;
|
|
364
|
+
if (log.data == null) continue;
|
|
365
|
+
const chunk = `${log.data}
|
|
366
|
+
`;
|
|
367
|
+
if (log.type === "STDERR") {
|
|
368
|
+
stderr.push(chunk);
|
|
369
|
+
options.onStderr?.(chunk);
|
|
370
|
+
} else {
|
|
371
|
+
stdout.push(chunk);
|
|
372
|
+
options.onStdout?.(chunk);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
})();
|
|
376
|
+
try {
|
|
377
|
+
const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;
|
|
378
|
+
if (outcome === DEADLINE_PASSED) {
|
|
379
|
+
timedOut = true;
|
|
380
|
+
void killCommand(running);
|
|
381
|
+
drain.catch(() => {
|
|
382
|
+
});
|
|
383
|
+
return timedOutResult(stdout.join(""), stderr.join(""));
|
|
384
|
+
}
|
|
385
|
+
} catch (error) {
|
|
386
|
+
void killCommand(running);
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
stdout: stdout.join(""),
|
|
391
|
+
stderr: stderr.join(""),
|
|
392
|
+
exitCode: await waitForExitCode(sandbox, commandId),
|
|
393
|
+
durationMs: Date.now() - startedAt
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
var DEADLINE_PASSED = /* @__PURE__ */ Symbol("deadline passed");
|
|
397
|
+
async function raceDeadline(work, deadline) {
|
|
398
|
+
let timer;
|
|
399
|
+
const expiry = new Promise((resolve) => {
|
|
400
|
+
timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));
|
|
401
|
+
});
|
|
402
|
+
try {
|
|
403
|
+
return await Promise.race([work, expiry]);
|
|
404
|
+
} finally {
|
|
405
|
+
clearTimeout(timer);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
var TIMEOUT_EXIT_CODE = 124;
|
|
409
|
+
var EXIT_CODE_WAIT_MS = 5e3;
|
|
410
|
+
var EXIT_CODE_POLL_MS = 200;
|
|
411
|
+
async function waitForExitCode(sandbox, commandId, deadlineMs = EXIT_CODE_WAIT_MS) {
|
|
412
|
+
const deadline = Date.now() + deadlineMs;
|
|
413
|
+
for (; ; ) {
|
|
414
|
+
const details = await sandbox.client.getCommandDetails({
|
|
415
|
+
path: { sandbox_id: sandbox.sandboxId, id: commandId }
|
|
416
|
+
});
|
|
417
|
+
if (typeof details.exit_code === "number") return details.exit_code;
|
|
418
|
+
if (details.status === "FAILED") return 1;
|
|
419
|
+
if (details.status === "SUCCESSFUL") return 0;
|
|
420
|
+
if (Date.now() >= deadline) {
|
|
421
|
+
throw new Error(
|
|
422
|
+
`Buddy command ${commandId} on sandbox ${sandbox.sandboxId} reported no exit code within ${deadlineMs / 1e3}s of its log stream closing (status: ${details.status ?? "unknown"}).`
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
await new Promise((resolve) => setTimeout(resolve, EXIT_CODE_POLL_MS));
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// src/filesystem.ts
|
|
430
|
+
async function readFile(sandbox, path) {
|
|
431
|
+
const target = normalizeSandboxPath(path);
|
|
432
|
+
const buffer = await whenBooted(sandbox, () => sandbox.fs.downloadFile(target));
|
|
433
|
+
return buffer.toString("utf-8");
|
|
434
|
+
}
|
|
435
|
+
async function writeFile(sandbox, path, content) {
|
|
436
|
+
const target = normalizeSandboxPath(path);
|
|
437
|
+
const parent = target.slice(0, target.lastIndexOf("/"));
|
|
438
|
+
await whenBooted(sandbox, async () => {
|
|
439
|
+
if (parent) {
|
|
440
|
+
await sandbox.fs.createFolder(parent).catch(() => {
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
await sandbox.fs.uploadFile(Buffer.from(content, "utf-8"), target);
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
async function mkdir(sandbox, path) {
|
|
447
|
+
const target = normalizeSandboxPath(path);
|
|
448
|
+
await whenBooted(sandbox, () => sandbox.fs.createFolder(target));
|
|
449
|
+
}
|
|
450
|
+
async function readdir(sandbox, path) {
|
|
451
|
+
const target = normalizeSandboxPath(path);
|
|
452
|
+
const entries = await whenBooted(sandbox, () => sandbox.fs.listFiles(target));
|
|
453
|
+
return entries.map((entry) => ({
|
|
454
|
+
name: entry.name ?? "",
|
|
455
|
+
type: entry.type === "DIR" ? "directory" : "file",
|
|
456
|
+
// The API reports sizes as bigint; ComputeSDK wants a number.
|
|
457
|
+
...entry.size == null ? {} : { size: Number(entry.size) }
|
|
458
|
+
}));
|
|
459
|
+
}
|
|
460
|
+
async function exists(sandbox, path) {
|
|
461
|
+
const target = toContentPath(path);
|
|
462
|
+
try {
|
|
463
|
+
await whenBooted(sandbox, () => sandbox.client.getSandboxContent({ path: { sandbox_id: sandbox.sandboxId, path: target } }));
|
|
464
|
+
return true;
|
|
465
|
+
} catch (error) {
|
|
466
|
+
if (isNotFound(error)) return false;
|
|
467
|
+
throw error;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
async function remove(sandbox, path) {
|
|
471
|
+
const target = normalizeSandboxPath(path);
|
|
472
|
+
try {
|
|
473
|
+
await whenBooted(sandbox, () => sandbox.fs.deleteFile(target));
|
|
474
|
+
} catch (error) {
|
|
475
|
+
if (!isNotFound(error)) throw error;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// src/snapshots.ts
|
|
480
|
+
var SNAPSHOT_WAIT_TIMEOUT_MS = 18e4;
|
|
481
|
+
var SNAPSHOT_WAIT_POLL_MS = 500;
|
|
482
|
+
function toSnapshot(data, sandboxId) {
|
|
483
|
+
if (!data.id) {
|
|
484
|
+
throw new Error("Buddy API returned a snapshot without an id.");
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
id: data.id,
|
|
488
|
+
provider: PROVIDER,
|
|
489
|
+
createdAt: data.create_date ? new Date(data.create_date) : /* @__PURE__ */ new Date(),
|
|
490
|
+
metadata: {
|
|
491
|
+
name: data.name,
|
|
492
|
+
status: data.status,
|
|
493
|
+
sizeGb: data.size,
|
|
494
|
+
...sandboxId ? { sandboxId } : {}
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
async function createSnapshot(config, sandboxId, options = {}) {
|
|
499
|
+
const client = getClient(config);
|
|
500
|
+
const created = await client.addSandboxSnapshot({
|
|
501
|
+
path: { sandbox_id: sandboxId },
|
|
502
|
+
body: { name: toIdentifier(options.name ?? `computesdk-${Date.now()}`) }
|
|
503
|
+
});
|
|
504
|
+
const snapshotId = created.id;
|
|
505
|
+
if (!snapshotId) {
|
|
506
|
+
throw new Error("Buddy accepted the snapshot but returned no snapshot id.");
|
|
507
|
+
}
|
|
508
|
+
const ready = await waitUntilCreated(config, sandboxId, snapshotId, created);
|
|
509
|
+
return toSnapshot(ready, sandboxId);
|
|
510
|
+
}
|
|
511
|
+
async function waitUntilCreated(config, sandboxId, snapshotId, initial) {
|
|
512
|
+
if (initial.status === "CREATED") return initial;
|
|
513
|
+
const client = getClient(config);
|
|
514
|
+
const deadline = Date.now() + SNAPSHOT_WAIT_TIMEOUT_MS;
|
|
515
|
+
for (; ; ) {
|
|
516
|
+
const data = await client.getSandboxSnapshot({
|
|
517
|
+
path: { sandbox_id: sandboxId, id: snapshotId }
|
|
518
|
+
});
|
|
519
|
+
if (data.status === "CREATED") return data;
|
|
520
|
+
if (data.status === "FAILED") {
|
|
521
|
+
throw new Error(`Buddy snapshot ${snapshotId} failed to be created.`);
|
|
522
|
+
}
|
|
523
|
+
if (Date.now() >= deadline) {
|
|
524
|
+
throw new Error(
|
|
525
|
+
`Buddy snapshot ${snapshotId} was still ${data.status} after ${SNAPSHOT_WAIT_TIMEOUT_MS / 1e3}s.`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
await sleep(SNAPSHOT_WAIT_POLL_MS);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
async function listSnapshots(config, options = {}) {
|
|
532
|
+
const client = getClient(config);
|
|
533
|
+
const response = options.sandboxId ? await client.getSandboxSnapshots({ path: { sandbox_id: options.sandboxId } }) : await client.getProjectSnapshots({});
|
|
534
|
+
const snapshots = (response.snapshots ?? []).map((snapshot) => toSnapshot(snapshot, options.sandboxId));
|
|
535
|
+
return options.limit ? snapshots.slice(0, options.limit) : snapshots;
|
|
536
|
+
}
|
|
537
|
+
async function deleteSnapshot(config, snapshotId) {
|
|
538
|
+
try {
|
|
539
|
+
await getClient(config).deleteSnapshot({ path: { id: snapshotId } });
|
|
540
|
+
} catch (error) {
|
|
541
|
+
if (!isNotFound(error)) throw error;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/index.ts
|
|
546
|
+
var DESTROY_ATTEMPTS = 3;
|
|
547
|
+
var DESTROY_RETRY_DELAY_MS = 500;
|
|
548
|
+
var URL_WAIT_TIMEOUT_MS = 15e3;
|
|
549
|
+
var URL_WAIT_POLL_MS = 250;
|
|
550
|
+
async function deleteSandbox(client, sandboxId) {
|
|
551
|
+
for (let attempt = 1; attempt <= DESTROY_ATTEMPTS; attempt++) {
|
|
552
|
+
try {
|
|
553
|
+
await client.deleteSandboxById({ path: { id: sandboxId } });
|
|
554
|
+
return;
|
|
555
|
+
} catch (error) {
|
|
556
|
+
if (isNotFound(error)) return;
|
|
557
|
+
const status = statusOf(error);
|
|
558
|
+
const retryable = status !== void 0 && status >= 500;
|
|
559
|
+
if (!retryable || attempt === DESTROY_ATTEMPTS) throw error;
|
|
560
|
+
await sleep(DESTROY_RETRY_DELAY_MS);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
var buddy = defineProvider({
|
|
565
|
+
name: PROVIDER,
|
|
566
|
+
methods: {
|
|
567
|
+
sandbox: {
|
|
568
|
+
create: async (config, options) => {
|
|
569
|
+
const resolved2 = resolveConfig(config);
|
|
570
|
+
const created = await getClient(resolved2).addSandbox({
|
|
571
|
+
body: buildCreateBody(resolved2, options)
|
|
572
|
+
});
|
|
573
|
+
const sandbox = toHandle(resolved2, created, /* @__PURE__ */ new Date(), false);
|
|
574
|
+
try {
|
|
575
|
+
await ensureTimeout(sandbox, options?.timeout ?? resolved2.timeout);
|
|
576
|
+
} catch (error) {
|
|
577
|
+
await deleteSandbox(sandbox.client, sandbox.sandboxId).catch(() => {
|
|
578
|
+
});
|
|
579
|
+
throw error;
|
|
580
|
+
}
|
|
581
|
+
return { sandbox, sandboxId: sandbox.sandboxId };
|
|
582
|
+
},
|
|
583
|
+
getById: async (config, sandboxId) => {
|
|
584
|
+
const resolved2 = resolveConfig(config);
|
|
585
|
+
try {
|
|
586
|
+
const data = await getSandboxData(resolved2, sandboxId);
|
|
587
|
+
const sandbox = toHandle(resolved2, data);
|
|
588
|
+
return { sandbox, sandboxId: sandbox.sandboxId };
|
|
589
|
+
} catch (error) {
|
|
590
|
+
if (isNotFound(error) || isUnroutableId(error)) return null;
|
|
591
|
+
throw error;
|
|
592
|
+
}
|
|
593
|
+
},
|
|
594
|
+
list: async (config) => {
|
|
595
|
+
const resolved2 = resolveConfig(config);
|
|
596
|
+
const response = await getClient(resolved2).getSandboxes({});
|
|
597
|
+
return (response.sandboxes ?? []).filter((entry) => Boolean(entry.id)).map((entry) => {
|
|
598
|
+
const sandbox = toHandle(resolved2, entry);
|
|
599
|
+
return { sandbox, sandboxId: sandbox.sandboxId };
|
|
600
|
+
});
|
|
601
|
+
},
|
|
602
|
+
destroy: async (config, sandboxId) => deleteSandbox(getClient(resolveConfig(config)), sandboxId),
|
|
603
|
+
runCommand: async (sandbox, command, options) => runCommand(sandbox, command, options),
|
|
604
|
+
// `runCommand` already forwards `onStdout`/`onStderr` from Buddy's own
|
|
605
|
+
// log stream. Without this the factory would ignore that and bootstrap
|
|
606
|
+
// its Node-based streaming daemon inside the sandbox instead.
|
|
607
|
+
streamCommand: runCommand,
|
|
608
|
+
getInfo: async (sandbox) => {
|
|
609
|
+
const data = await getSandboxData(sandbox.config, sandbox.sandboxId);
|
|
610
|
+
sandbox.endpoints = data.endpoints ?? sandbox.endpoints;
|
|
611
|
+
return {
|
|
612
|
+
id: sandbox.sandboxId,
|
|
613
|
+
provider: PROVIDER,
|
|
614
|
+
status: mapStatus(data.status),
|
|
615
|
+
createdAt: sandbox.createdAt,
|
|
616
|
+
timeout: data.timeout != null ? data.timeout * 1e3 : sandbox.timeout,
|
|
617
|
+
metadata: {
|
|
618
|
+
createdAtIsReconnectTime: sandbox.createdAtIsReconnectTime,
|
|
619
|
+
identifier: data.identifier ?? sandbox.identifier,
|
|
620
|
+
name: data.name,
|
|
621
|
+
os: data.os,
|
|
622
|
+
resources: data.resources,
|
|
623
|
+
buddyStatus: data.status,
|
|
624
|
+
setupStatus: data.setup_status,
|
|
625
|
+
workspace: sandbox.config.workspace,
|
|
626
|
+
project: sandbox.config.project,
|
|
627
|
+
region: sandbox.config.region,
|
|
628
|
+
endpoints: (data.endpoints ?? []).map((endpoint) => ({
|
|
629
|
+
name: endpoint.name,
|
|
630
|
+
port: Number(endpoint.endpoint),
|
|
631
|
+
type: endpoint.type,
|
|
632
|
+
url: endpointPublicUrl(endpoint)
|
|
633
|
+
}))
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
},
|
|
637
|
+
getUrl: async (sandbox, options) => getUrl(sandbox, options),
|
|
638
|
+
getInstance: (sandbox) => sandbox,
|
|
639
|
+
filesystem: {
|
|
640
|
+
readFile: (sandbox, path) => readFile(sandbox, path),
|
|
641
|
+
writeFile: (sandbox, path, content) => writeFile(sandbox, path, content),
|
|
642
|
+
mkdir: (sandbox, path) => mkdir(sandbox, path),
|
|
643
|
+
readdir: (sandbox, path) => readdir(sandbox, path),
|
|
644
|
+
exists: (sandbox, path) => exists(sandbox, path),
|
|
645
|
+
remove: (sandbox, path) => remove(sandbox, path)
|
|
646
|
+
}
|
|
647
|
+
},
|
|
648
|
+
snapshot: {
|
|
649
|
+
create: (config, sandboxId, options) => createSnapshot(resolveConfig(config), sandboxId, options),
|
|
650
|
+
list: (config, options) => listSnapshots(resolveConfig(config), options),
|
|
651
|
+
delete: (config, snapshotId) => deleteSnapshot(resolveConfig(config), snapshotId)
|
|
652
|
+
},
|
|
653
|
+
/**
|
|
654
|
+
* Buddy has no separate template entity — a snapshot is the reusable image,
|
|
655
|
+
* and `create({ templateId })` boots from one. So listing and deleting
|
|
656
|
+
* templates operate on snapshots, and creating one points the caller at
|
|
657
|
+
* `compute.snapshot.create`, which is where an image comes from.
|
|
658
|
+
*/
|
|
659
|
+
template: {
|
|
660
|
+
create: async () => {
|
|
661
|
+
throw new Error(
|
|
662
|
+
"Buddy does not have templates as a separate entity. Snapshot a configured sandbox instead: const snapshot = await compute.snapshot.create(sandboxId), then boot from it with compute.sandbox.create({ snapshotId: snapshot.id })."
|
|
663
|
+
);
|
|
664
|
+
},
|
|
665
|
+
list: (config, options) => listSnapshots(resolveConfig(config), options),
|
|
666
|
+
delete: (config, templateId) => deleteSnapshot(resolveConfig(config), templateId)
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
function toSeconds(ms) {
|
|
671
|
+
return Math.max(1, Math.ceil(ms / 1e3));
|
|
672
|
+
}
|
|
673
|
+
function buildCreateBody(config, options = {}) {
|
|
674
|
+
const name = options.name ?? generateSandboxName();
|
|
675
|
+
const timeoutMs = options.timeout ?? config.timeout;
|
|
676
|
+
const snapshotId = options.snapshotId ?? options.templateId;
|
|
677
|
+
const body = {
|
|
678
|
+
name,
|
|
679
|
+
identifier: toIdentifier(name),
|
|
680
|
+
os: options.image ?? config.os,
|
|
681
|
+
timeout: toSeconds(timeoutMs)
|
|
682
|
+
};
|
|
683
|
+
const resources = resolveResources(options, config.resources);
|
|
684
|
+
if (resources) body.resources = resources;
|
|
685
|
+
if (options.firstBootCommands) body.first_boot_commands = options.firstBootCommands;
|
|
686
|
+
if (options.appDir) body.app_dir = options.appDir;
|
|
687
|
+
if (options.tags) body.tags = options.tags;
|
|
688
|
+
const ports = options.ports ?? config.ports;
|
|
689
|
+
if (ports?.length) {
|
|
690
|
+
body.endpoints = ports.map((port) => toEndpointPayload(normalizePort(port, config)));
|
|
691
|
+
}
|
|
692
|
+
if (options.envs && Object.keys(options.envs).length > 0) {
|
|
693
|
+
body.variables = Object.entries(options.envs).map(([key, value]) => ({ key, value }));
|
|
694
|
+
}
|
|
695
|
+
if (snapshotId) body.snapshot_id = snapshotId;
|
|
696
|
+
return body;
|
|
697
|
+
}
|
|
698
|
+
async function ensureTimeout(sandbox, timeoutMs) {
|
|
699
|
+
const seconds = toSeconds(timeoutMs);
|
|
700
|
+
if (toSeconds(sandbox.timeout) === seconds) return;
|
|
701
|
+
const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({
|
|
702
|
+
path: { id: sandbox.sandboxId },
|
|
703
|
+
body: { timeout: seconds }
|
|
704
|
+
}));
|
|
705
|
+
sandbox.timeout = updated.timeout != null ? updated.timeout * 1e3 : seconds * 1e3;
|
|
706
|
+
}
|
|
707
|
+
var endpointUpdates = /* @__PURE__ */ new Map();
|
|
708
|
+
function endpointUpdateKey(sandbox) {
|
|
709
|
+
return `${sandbox.config.apiUrl}|${sandbox.config.workspace}|${sandbox.sandboxId}`;
|
|
710
|
+
}
|
|
711
|
+
function getUrl(sandbox, options) {
|
|
712
|
+
const key = endpointUpdateKey(sandbox);
|
|
713
|
+
const previous = endpointUpdates.get(key) ?? Promise.resolve();
|
|
714
|
+
const next = previous.catch(() => {
|
|
715
|
+
}).then(() => openPort(sandbox, options));
|
|
716
|
+
endpointUpdates.set(key, next);
|
|
717
|
+
next.catch(() => {
|
|
718
|
+
}).finally(() => {
|
|
719
|
+
if (endpointUpdates.get(key) === next) endpointUpdates.delete(key);
|
|
720
|
+
});
|
|
721
|
+
return next;
|
|
722
|
+
}
|
|
723
|
+
async function openPort(sandbox, options) {
|
|
724
|
+
const { port, protocol } = options;
|
|
725
|
+
const existing = await findEndpointUrl(sandbox, port);
|
|
726
|
+
if (existing) return applyProtocol(existing, protocol);
|
|
727
|
+
const desired = normalizePort({ port }, sandbox.config);
|
|
728
|
+
const kept = sandbox.endpoints.filter((endpoint) => !endpointMatchesPort(endpoint, port)).map(toEndpointUpdate);
|
|
729
|
+
const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({
|
|
730
|
+
path: { id: sandbox.sandboxId },
|
|
731
|
+
body: { endpoints: [...kept, toEndpointPayload(desired)] }
|
|
732
|
+
}));
|
|
733
|
+
sandbox.endpoints = updated.endpoints ?? sandbox.endpoints;
|
|
734
|
+
const deadline = Date.now() + URL_WAIT_TIMEOUT_MS;
|
|
735
|
+
for (; ; ) {
|
|
736
|
+
const url = await findEndpointUrl(sandbox, port);
|
|
737
|
+
if (url) return applyProtocol(url, protocol);
|
|
738
|
+
if (Date.now() >= deadline) {
|
|
739
|
+
throw new Error(
|
|
740
|
+
`Buddy opened a tunnel to port ${port} on sandbox ${sandbox.sandboxId} but published no public URL within ${URL_WAIT_TIMEOUT_MS / 1e3}s.`
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
await sleep(URL_WAIT_POLL_MS);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
async function findEndpointUrl(sandbox, port) {
|
|
747
|
+
const data = await getSandboxData(sandbox.config, sandbox.sandboxId);
|
|
748
|
+
sandbox.endpoints = data.endpoints ?? [];
|
|
749
|
+
const match = sandbox.endpoints.find((endpoint) => endpointMatchesPort(endpoint, port));
|
|
750
|
+
return match ? endpointPublicUrl(match) : void 0;
|
|
751
|
+
}
|
|
752
|
+
export {
|
|
753
|
+
buddy,
|
|
754
|
+
deleteSandbox,
|
|
755
|
+
ensureTimeout,
|
|
756
|
+
toSeconds
|
|
757
|
+
};
|
|
758
|
+
//# sourceMappingURL=index.mjs.map
|