@computesdk/buddy 1.0.8 → 1.0.9
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 +4 -2
- package/dist/index.d.mts +17 -6
- package/dist/index.d.ts +17 -6
- package/dist/index.js +46 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +46 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -190,7 +190,7 @@ The handle's `fs` and `client` call the API directly, without the provider's fir
|
|
|
190
190
|
| `getById` | ✅ | Returns `null` when the sandbox no longer exists. |
|
|
191
191
|
| `list` | ✅ | Lists the sandboxes in the configured project. |
|
|
192
192
|
| `destroy` | ✅ | Retries on server errors; a no-op if the sandbox is already gone. |
|
|
193
|
-
| `runCommand` | ✅ |
|
|
193
|
+
| `runCommand` | ✅ | One round trip via `exec` for plain calls; streams stdout/stderr separately when callbacks are passed. Real exit codes either way. |
|
|
194
194
|
| `getInfo` | ✅ | Reports Buddy's own status and setup status, plus every tunnel, in `metadata`. |
|
|
195
195
|
| `getUrl` | ✅ | Opens a tunnel if the port has none yet, keeping the existing ones. |
|
|
196
196
|
| `filesystem` | ✅ | Uses Buddy's native content endpoints, not the shell — no quoting or size limits of a command line, one round trip each. |
|
|
@@ -200,8 +200,10 @@ The handle's `fs` and `client` call the API directly, without the provider's fir
|
|
|
200
200
|
## Notes
|
|
201
201
|
|
|
202
202
|
- `create` does not wait for the sandbox to reach `RUNNING`. Buddy queues commands submitted against a starting sandbox, so waiting would only add latency to the first command. For the same reason the provider calls the SDK's `BuddyApiClient` directly instead of `Sandbox.create()`, which polls for readiness once a second.
|
|
203
|
+
- `runCommand(cmd)` without streaming callbacks or a `timeout` runs through Buddy's synchronous `exec` endpoint: one request that returns stdout, stderr and the exit code together. Such a command leaves no entry in the sandbox's command history. The server waits at most 60 s for it; past that the call returns exit code 124 with the server's message in `stderr`, and the process keeps running in the sandbox. Pass a `timeout` for commands that may run longer or must be stopped.
|
|
204
|
+
- `runCommand(cmd, { onStdout, onStderr })`, `streamCommand`, `background: true` and any `timeout` use the asynchronous `commands` resource with its log stream instead, so output arrives as it is produced, the command shows up in the history, and a timeout kills it.
|
|
203
205
|
- `runCommand(cmd, { background: true })` returns as soon as Buddy has queued the command, without reading its output.
|
|
204
|
-
- `runCommand(cmd, { timeout })`
|
|
206
|
+
- `runCommand(cmd, { timeout })` returns the timeout result when the timeout passes and terminates the command.
|
|
205
207
|
- Sandbox placement inside an installation is not selectable; `region` picks the installation and the tunnel location.
|
|
206
208
|
|
|
207
209
|
## License
|
package/dist/index.d.mts
CHANGED
|
@@ -109,12 +109,23 @@ interface BuddySandboxHandle {
|
|
|
109
109
|
/**
|
|
110
110
|
* Command execution.
|
|
111
111
|
*
|
|
112
|
-
* Buddy
|
|
113
|
-
*
|
|
114
|
-
* `
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
112
|
+
* Buddy has two ways to run a command:
|
|
113
|
+
*
|
|
114
|
+
* - `POST .../exec` runs it synchronously and answers with stdout, stderr and
|
|
115
|
+
* the exit code in one round trip. It keeps no history, cannot stream and
|
|
116
|
+
* cannot be interrupted. After 60 s the server stops waiting and answers
|
|
117
|
+
* 400 without output or exit code; the process itself keeps running.
|
|
118
|
+
* - `POST .../commands` accepts the command and returns its id immediately;
|
|
119
|
+
* output arrives over a JSONL log stream. The provider consumes that stream
|
|
120
|
+
* once through the SDK's `Command` entity, splits it into stdout/stderr and
|
|
121
|
+
* forwards chunks to the streaming callbacks, then reads the exit code from
|
|
122
|
+
* the command details. `Command.wait()` is deliberately unused — it polls
|
|
123
|
+
* once a second, which would add up to a second to every call.
|
|
124
|
+
*
|
|
125
|
+
* A foreground call without streaming callbacks and without a `timeout` takes
|
|
126
|
+
* the first route (one request instead of three). Anything else — callbacks,
|
|
127
|
+
* `background`, any `timeout` — takes the second, where a timeout can kill the
|
|
128
|
+
* command by its id.
|
|
118
129
|
*/
|
|
119
130
|
|
|
120
131
|
interface BuddyRunCommandOptions extends RunCommandOptions {
|
package/dist/index.d.ts
CHANGED
|
@@ -109,12 +109,23 @@ interface BuddySandboxHandle {
|
|
|
109
109
|
/**
|
|
110
110
|
* Command execution.
|
|
111
111
|
*
|
|
112
|
-
* Buddy
|
|
113
|
-
*
|
|
114
|
-
* `
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
112
|
+
* Buddy has two ways to run a command:
|
|
113
|
+
*
|
|
114
|
+
* - `POST .../exec` runs it synchronously and answers with stdout, stderr and
|
|
115
|
+
* the exit code in one round trip. It keeps no history, cannot stream and
|
|
116
|
+
* cannot be interrupted. After 60 s the server stops waiting and answers
|
|
117
|
+
* 400 without output or exit code; the process itself keeps running.
|
|
118
|
+
* - `POST .../commands` accepts the command and returns its id immediately;
|
|
119
|
+
* output arrives over a JSONL log stream. The provider consumes that stream
|
|
120
|
+
* once through the SDK's `Command` entity, splits it into stdout/stderr and
|
|
121
|
+
* forwards chunks to the streaming callbacks, then reads the exit code from
|
|
122
|
+
* the command details. `Command.wait()` is deliberately unused — it polls
|
|
123
|
+
* once a second, which would add up to a second to every call.
|
|
124
|
+
*
|
|
125
|
+
* A foreground call without streaming callbacks and without a `timeout` takes
|
|
126
|
+
* the first route (one request instead of three). Anything else — callbacks,
|
|
127
|
+
* `background`, any `timeout` — takes the second, where a timeout can kill the
|
|
128
|
+
* command by its id.
|
|
118
129
|
*/
|
|
119
130
|
|
|
120
131
|
interface BuddyRunCommandOptions extends RunCommandOptions {
|
package/dist/index.js
CHANGED
|
@@ -133,7 +133,7 @@ function isUnroutableId(error) {
|
|
|
133
133
|
return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));
|
|
134
134
|
}
|
|
135
135
|
function isInstanceNotRunning(error) {
|
|
136
|
-
return statusOf(error) === 400 && /instance is not running/i.test(messageOf(error));
|
|
136
|
+
return statusOf(error) === 400 && /instance is not running|sandbox must be running/i.test(messageOf(error));
|
|
137
137
|
}
|
|
138
138
|
function isOperationInProgress(error) {
|
|
139
139
|
return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));
|
|
@@ -287,14 +287,17 @@ async function untilSettled(sandbox) {
|
|
|
287
287
|
}
|
|
288
288
|
async function whenBooted(sandbox, operation) {
|
|
289
289
|
await untilSettled(sandbox);
|
|
290
|
-
|
|
290
|
+
return retryBootRaces(operation, Date.now() + BOOT_WAIT_TIMEOUT_MS);
|
|
291
|
+
}
|
|
292
|
+
async function retryBootRaces(operation, deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS) {
|
|
291
293
|
for (; ; ) {
|
|
292
294
|
try {
|
|
293
295
|
return await operation();
|
|
294
296
|
} catch (error) {
|
|
295
297
|
const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);
|
|
296
298
|
if (!retryable || Date.now() >= deadline) throw error;
|
|
297
|
-
await sleep(BOOT_WAIT_POLL_MS);
|
|
299
|
+
await sleep(Math.min(BOOT_WAIT_POLL_MS, deadline - Date.now()));
|
|
300
|
+
if (Date.now() >= deadline) throw error;
|
|
298
301
|
}
|
|
299
302
|
}
|
|
300
303
|
}
|
|
@@ -350,6 +353,25 @@ async function runCommand(sandbox, command, options = {}) {
|
|
|
350
353
|
exitCode: TIMEOUT_EXIT_CODE,
|
|
351
354
|
durationMs: Date.now() - startedAt
|
|
352
355
|
});
|
|
356
|
+
if (usesExec(options)) {
|
|
357
|
+
let result;
|
|
358
|
+
try {
|
|
359
|
+
result = await retryBootRaces(() => execCommand(sandbox, payload, runtime));
|
|
360
|
+
} catch (error) {
|
|
361
|
+
if (isExecTimeout(error)) return timedOutResult("", `${messageOf(error)}
|
|
362
|
+
`);
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
if (typeof result.exit_code !== "number") {
|
|
366
|
+
throw new Error("Buddy ran the command but returned no exit code.");
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
stdout: result.stdout ?? "",
|
|
370
|
+
stderr: result.stderr ?? "",
|
|
371
|
+
exitCode: result.exit_code,
|
|
372
|
+
durationMs: Date.now() - startedAt
|
|
373
|
+
};
|
|
374
|
+
}
|
|
353
375
|
const submission = sandbox.client.executeCommand({
|
|
354
376
|
path: { sandbox_id: sandbox.sandboxId },
|
|
355
377
|
body: { command: payload, runtime }
|
|
@@ -413,13 +435,33 @@ async function runCommand(sandbox, command, options = {}) {
|
|
|
413
435
|
void killCommand(running);
|
|
414
436
|
throw error;
|
|
415
437
|
}
|
|
438
|
+
const exit = waitForExitCode(sandbox, commandId);
|
|
439
|
+
const exitCode = deadline ? await raceDeadline(exit, deadline) : await exit;
|
|
440
|
+
if (exitCode === DEADLINE_PASSED) {
|
|
441
|
+
exit.catch(() => {
|
|
442
|
+
});
|
|
443
|
+
void killCommand(running);
|
|
444
|
+
return timedOutResult(stdout.join(""), stderr.join(""));
|
|
445
|
+
}
|
|
416
446
|
return {
|
|
417
447
|
stdout: stdout.join(""),
|
|
418
448
|
stderr: stderr.join(""),
|
|
419
|
-
exitCode
|
|
449
|
+
exitCode,
|
|
420
450
|
durationMs: Date.now() - startedAt
|
|
421
451
|
};
|
|
422
452
|
}
|
|
453
|
+
function isExecTimeout(error) {
|
|
454
|
+
return statusOf(error) === 400 && /did not finish on instance .* within \d+s/i.test(messageOf(error));
|
|
455
|
+
}
|
|
456
|
+
function usesExec(options) {
|
|
457
|
+
return !options.background && !options.onStdout && !options.onStderr && !options.timeout;
|
|
458
|
+
}
|
|
459
|
+
function execCommand(sandbox, command, runtime) {
|
|
460
|
+
return sandbox.client.execCommand({
|
|
461
|
+
body: { command, runtime },
|
|
462
|
+
path: { sandbox_id: sandbox.sandboxId }
|
|
463
|
+
});
|
|
464
|
+
}
|
|
423
465
|
var DEADLINE_PASSED = /* @__PURE__ */ Symbol("deadline passed");
|
|
424
466
|
async function raceDeadline(work, deadline) {
|
|
425
467
|
let timer;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/boot.ts","../src/commands.ts","../src/filesystem.ts","../src/snapshots.ts"],"sourcesContent":["/**\n * Buddy provider for ComputeSDK.\n *\n * Buddy serves Ubuntu sandboxes from a pre-warmed pool, so `create` returns a\n * sandbox that is already booting and commands submitted to it are queued until\n * it is up. The provider does not wait for `RUNNING` on create — that keeps\n * time-to-first-command at the warm-pool latency instead of a poll interval.\n *\n * Snapshots are Buddy's only reusable image, so `compute.template.*` is mapped\n * onto them.\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateSandboxOptions,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n SandboxInfo,\n} from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport type { BuddyApiClient } from '@buddy-works/sandbox-sdk';\nimport { whenBooted } from './boot.js';\nimport { runCommand, type BuddyRunCommandOptions } from './commands.js';\nimport * as fs from './filesystem.js';\nimport { createSnapshot, deleteSnapshot, listSnapshots } from './snapshots.js';\nimport {\n PROVIDER,\n applyProtocol,\n endpointMatchesPort,\n endpointPublicUrl,\n generateSandboxName,\n getClient,\n getSandboxData,\n isNotFound,\n isUnroutableId,\n mapStatus,\n normalizePort,\n resolveConfig,\n resolveResources,\n sleep,\n statusOf,\n toEndpointPayload,\n toEndpointUpdate,\n toHandle,\n toIdentifier,\n type BuddyConfig,\n type BuddyEndpoint,\n type BuddyPortInput,\n type BuddySandboxHandle,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\n/** Deleting a just-created sandbox occasionally answers 5xx while succeeding. */\nconst DESTROY_ATTEMPTS = 3;\nconst DESTROY_RETRY_DELAY_MS = 500;\n\n/** A tunnel is registered instantly but takes a moment to get its public URL. */\nconst URL_WAIT_TIMEOUT_MS = 15_000;\nconst URL_WAIT_POLL_MS = 250;\n\n/**\n * Deletes a sandbox, retrying transient server failures. \"Already gone\" is the\n * state the caller asked for, so it counts as success.\n */\nexport async function deleteSandbox(client: BuddyApiClient, sandboxId: string): Promise<void> {\n for (let attempt = 1; attempt <= DESTROY_ATTEMPTS; attempt++) {\n try {\n await client.deleteSandboxById({ path: { id: sandboxId } });\n return;\n } catch (error) {\n if (isNotFound(error)) return;\n const status = statusOf(error);\n const retryable = status !== undefined && status >= 500;\n if (!retryable || attempt === DESTROY_ATTEMPTS) throw error;\n await sleep(DESTROY_RETRY_DELAY_MS);\n }\n }\n}\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n methods: {\n sandbox: {\n create: async (config: BuddyConfig, options?: CreateSandboxOptions) => {\n const resolved = resolveConfig(config);\n const created = await getClient(resolved).addSandbox({\n body: buildCreateBody(resolved, options),\n });\n\n const sandbox = toHandle(resolved, created, new Date(), false);\n try {\n await ensureTimeout(sandbox, options?.timeout ?? resolved.timeout);\n } catch (error) {\n // The framework has no id yet, so nothing else could clean this up.\n await deleteSandbox(sandbox.client, sandbox.sandboxId).catch(() => {});\n throw error;\n }\n return { sandbox, sandboxId: sandbox.sandboxId };\n },\n\n getById: async (config: BuddyConfig, sandboxId: string) => {\n const resolved = resolveConfig(config);\n try {\n const data = await getSandboxData(resolved, sandboxId);\n const sandbox = toHandle(resolved, data);\n return { sandbox, sandboxId: sandbox.sandboxId };\n } catch (error) {\n if (isNotFound(error) || isUnroutableId(error)) return null;\n throw error;\n }\n },\n\n list: async (config: BuddyConfig) => {\n const resolved = resolveConfig(config);\n const response = await getClient(resolved).getSandboxes({});\n\n // The listing carries ids only; details are fetched on demand by\n // getInfo, so listing a hundred sandboxes stays a single request.\n return (response.sandboxes ?? [])\n .filter(entry => Boolean(entry.id))\n .map(entry => {\n const sandbox = toHandle(resolved, entry);\n return { sandbox, sandboxId: sandbox.sandboxId };\n });\n },\n\n destroy: async (config: BuddyConfig, sandboxId: string) =>\n deleteSandbox(getClient(resolveConfig(config)), sandboxId),\n\n runCommand: async (\n sandbox: BuddySandboxHandle,\n command: string,\n options?: BuddyRunCommandOptions,\n ) => runCommand(sandbox, command, options),\n\n // `runCommand` already forwards `onStdout`/`onStderr` from Buddy's own\n // log stream. Without this the factory would ignore that and bootstrap\n // its Node-based streaming daemon inside the sandbox instead.\n streamCommand: runCommand,\n\n getInfo: async (sandbox: BuddySandboxHandle): Promise<SandboxInfo> => {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? sandbox.endpoints;\n\n return {\n id: sandbox.sandboxId,\n provider: PROVIDER,\n status: mapStatus(data.status),\n createdAt: sandbox.createdAt,\n timeout: data.timeout != null ? data.timeout * 1000 : sandbox.timeout,\n metadata: {\n createdAtIsReconnectTime: sandbox.createdAtIsReconnectTime,\n identifier: data.identifier ?? sandbox.identifier,\n name: data.name,\n os: data.os,\n resources: data.resources,\n buddyStatus: data.status,\n setupStatus: data.setup_status,\n workspace: sandbox.config.workspace,\n project: sandbox.config.project,\n region: sandbox.config.region,\n endpoints: (data.endpoints ?? []).map(endpoint => ({\n name: endpoint.name,\n port: Number(endpoint.endpoint),\n type: endpoint.type,\n url: endpointPublicUrl(endpoint),\n })),\n },\n };\n },\n\n getUrl: async (sandbox: BuddySandboxHandle, options: { port: number; protocol?: string }) =>\n getUrl(sandbox, options),\n\n getInstance: (sandbox: BuddySandboxHandle) => sandbox,\n\n filesystem: {\n readFile: (sandbox: BuddySandboxHandle, path: string) => fs.readFile(sandbox, path),\n writeFile: (sandbox: BuddySandboxHandle, path: string, content: string) =>\n fs.writeFile(sandbox, path, content),\n mkdir: (sandbox: BuddySandboxHandle, path: string) => fs.mkdir(sandbox, path),\n readdir: (sandbox: BuddySandboxHandle, path: string) => fs.readdir(sandbox, path),\n exists: (sandbox: BuddySandboxHandle, path: string) => fs.exists(sandbox, path),\n remove: (sandbox: BuddySandboxHandle, path: string) => fs.remove(sandbox, path),\n },\n },\n\n snapshot: {\n create: (config: BuddyConfig, sandboxId: string, options?: { name?: string }) =>\n createSnapshot(resolveConfig(config), sandboxId, options),\n list: (config: BuddyConfig, options?: ListSnapshotsOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, snapshotId: string) =>\n deleteSnapshot(resolveConfig(config), snapshotId),\n },\n\n /**\n * Buddy has no separate template entity — a snapshot is the reusable image,\n * and `create({ templateId })` boots from one. So listing and deleting\n * templates operate on snapshots, and creating one points the caller at\n * `compute.snapshot.create`, which is where an image comes from.\n */\n template: {\n create: async () => {\n throw new Error(\n 'Buddy does not have templates as a separate entity. Snapshot a ' +\n 'configured sandbox instead: const snapshot = await compute.snapshot.create(sandboxId), ' +\n 'then boot from it with compute.sandbox.create({ snapshotId: snapshot.id }).',\n );\n },\n list: (config: BuddyConfig, options?: ListTemplatesOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, templateId: string) =>\n deleteSnapshot(resolveConfig(config), templateId),\n },\n },\n});\n\n/** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */\nexport function toSeconds(ms: number): number {\n return Math.max(1, Math.ceil(ms / 1000));\n}\n\nfunction buildCreateBody(config: ResolvedBuddyConfig, options: CreateSandboxOptions = {}) {\n const name = options.name ?? generateSandboxName();\n const timeoutMs = options.timeout ?? config.timeout;\n // `templateId` is accepted alongside `snapshotId` because Buddy's template\n // methods are backed by snapshots — both carry a snapshot id.\n const snapshotId = options.snapshotId ?? options.templateId;\n\n const body: Record<string, unknown> = {\n name,\n identifier: toIdentifier(name),\n os: options.image ?? config.os,\n timeout: toSeconds(timeoutMs),\n };\n\n const resources = resolveResources(options, config.resources);\n if (resources) body.resources = resources;\n\n // Buddy-specific create options, passed through as they are named in the API.\n if (options.firstBootCommands) body.first_boot_commands = options.firstBootCommands;\n if (options.appDir) body.app_dir = options.appDir;\n if (options.tags) body.tags = options.tags;\n\n const ports = options.ports ?? config.ports;\n if (ports?.length) {\n body.endpoints = ports.map((port: BuddyPortInput) =>\n toEndpointPayload(normalizePort(port, config)));\n }\n if (options.envs && Object.keys(options.envs).length > 0) {\n body.variables = Object.entries(options.envs).map(([key, value]) => ({ key, value }));\n }\n if (snapshotId) body.snapshot_id = snapshotId;\n\n return body as any;\n}\n\n/**\n * Buddy's create-from-snapshot request has no `timeout` field (the SDK schema\n * strips it), so a sandbox booted from a snapshot comes back with whatever the\n * snapshot carried. Patch it afterwards when it differs from what was asked.\n */\nexport async function ensureTimeout(\n sandbox: BuddySandboxHandle,\n timeoutMs: number,\n): Promise<void> {\n const seconds = toSeconds(timeoutMs);\n if (toSeconds(sandbox.timeout) === seconds) return;\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { timeout: seconds } as any,\n }));\n sandbox.timeout = updated.timeout != null ? updated.timeout * 1000 : seconds * 1000;\n}\n\n/**\n * Endpoint updates in flight, per remote sandbox. Buddy replaces the whole\n * endpoint list on update, so two concurrent `getUrl` calls built from the same\n * list would each drop the other's port — they run one after another instead.\n * Keyed by installation + sandbox id rather than by handle: `getById` and\n * `list` hand out a fresh handle each time for the same remote sandbox.\n */\nconst endpointUpdates = new Map<string, Promise<unknown>>();\n\nfunction endpointUpdateKey(sandbox: BuddySandboxHandle): string {\n return `${sandbox.config.apiUrl}|${sandbox.config.workspace}|${sandbox.sandboxId}`;\n}\n\nfunction getUrl(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const key = endpointUpdateKey(sandbox);\n const previous = endpointUpdates.get(key) ?? Promise.resolve();\n const next = previous.catch(() => {}).then(() => openPort(sandbox, options));\n endpointUpdates.set(key, next);\n // Drop the entry once nothing newer is queued behind it, so the map only\n // ever holds sandboxes with an update actually in flight.\n next.catch(() => {}).finally(() => {\n if (endpointUpdates.get(key) === next) endpointUpdates.delete(key);\n });\n return next;\n}\n\nasync function openPort(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const { port, protocol } = options;\n const existing = await findEndpointUrl(sandbox, port);\n if (existing) return applyProtocol(existing, protocol);\n\n const desired = normalizePort({ port }, sandbox.config);\n // Buddy replaces the whole endpoint list on update, so previously opened\n // tunnels have to be sent back or they would be torn down here.\n const kept = sandbox.endpoints\n .filter(endpoint => !endpointMatchesPort(endpoint, port))\n .map(toEndpointUpdate);\n\n // Buddy refuses configuration changes while the sandbox is still starting.\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { endpoints: [...kept, toEndpointPayload(desired)] } as any,\n }));\n sandbox.endpoints = (updated.endpoints ?? sandbox.endpoints) as BuddyEndpoint[];\n\n const deadline = Date.now() + URL_WAIT_TIMEOUT_MS;\n for (;;) {\n const url = await findEndpointUrl(sandbox, port);\n if (url) return applyProtocol(url, protocol);\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy opened a tunnel to port ${port} on sandbox ${sandbox.sandboxId} ` +\n `but published no public URL within ${URL_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(URL_WAIT_POLL_MS);\n }\n}\n\nasync function findEndpointUrl(\n sandbox: BuddySandboxHandle,\n port: number,\n): Promise<string | undefined> {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? [];\n const match = sandbox.endpoints.find(endpoint => endpointMatchesPort(endpoint, port));\n return match ? endpointPublicUrl(match) : undefined;\n}\n\nexport type { BuddyConfig, BuddySandboxHandle as BuddySandbox } from './utils.js';\nexport type { BuddyRunCommandOptions } from './commands.js';\n","/**\n * Shared types, config resolution and SDK plumbing for the Buddy provider.\n *\n * All API access goes through `@buddy-works/sandbox-sdk`. The provider uses the\n * SDK's `BuddyApiClient` rather than its high-level `Sandbox` façade for sandbox\n * creation: `Sandbox.create()` waits for `setup_status: SUCCESS` and\n * `status: RUNNING` with a 1 s poll, and since a sandbox from Buddy's warm pool\n * is usable in ~400 ms that wait would dominate time-to-first-command. The\n * façade's `Command`, `FileSystem` and snapshot helpers are used as-is.\n */\n\nimport { API_URLS, BuddyApiClient, FileSystem } from '@buddy-works/sandbox-sdk';\n\nexport const PROVIDER = 'buddy' as const;\nexport const DEFAULT_OS = 'ubuntu:24.04';\nexport const DEFAULT_REGION: BuddyRegion = 'US';\n/** Buddy stops a sandbox after this many ms of life unless overridden. */\nexport const DEFAULT_TIMEOUT_MS = 3_600_000;\n/** Working directory of the default `buddy` user — relative paths resolve here. */\nexport const SANDBOX_HOME = '/buddy';\n\n/**\n * Buddy installation, in the spelling its tunnel API uses. Each installation is\n * a separate deployment with its own API host, workspaces and tokens — `US` is\n * not a placement hint within one API.\n */\nexport type BuddyRegion = 'US' | 'EU';\n\n/** Interpreter Buddy runs a command with. `BASH` is the default. */\nexport type BuddyCommandRuntime = 'BASH' | 'JAVASCRIPT' | 'TYPESCRIPT' | 'PYTHON';\n\n/** Tunnel protocol. Only `HTTP` yields a public `endpoint_url`. */\nexport type BuddyTunnelType = 'HTTP' | 'TLS' | 'TCP' | 'SSH';\n\n/**\n * Buddy resource preset, `\"{vCPU}x{RAM in GB}\"`. RAM is always 2 GB per vCPU.\n */\nexport type BuddyResources =\n | '1x2' | '2x4' | '3x6' | '4x8' | '5x10' | '6x12'\n | '7x14' | '8x16' | '9x18' | '10x20' | '11x22' | '12x24';\n\nexport const MAX_CPU = 12;\n\n/** A port to expose publicly. A bare number means `{ port, type: 'HTTP' }`. */\nexport interface BuddyPort {\n port: number;\n /** Tunnel name. Becomes the first label of the public hostname. */\n name?: string;\n type?: BuddyTunnelType;\n region?: BuddyRegion;\n}\n\nexport type BuddyPortInput = number | BuddyPort;\n\nexport interface BuddyConfig {\n /** API token with the `SANDBOX_MANAGE` scope. Falls back to `BUDDY_TOKEN`. */\n token?: string;\n /** Workspace domain. Falls back to `BUDDY_WORKSPACE`. */\n workspace?: string;\n /** Project the sandboxes belong to. Falls back to `BUDDY_PROJECT`. */\n project?: string;\n /** Base OS image — `'ubuntu:24.04'` (default) or `'ubuntu:22.04'`. */\n os?: string;\n /** Resource preset. Buddy's own default applies when omitted. */\n resources?: BuddyResources;\n /**\n * Buddy installation to use. Selects both the API host and where tunnels\n * terminate. Defaults to `'US'`. A token is only valid on its own\n * installation.\n */\n region?: BuddyRegion;\n /** Sandbox lifetime in milliseconds, after which Buddy stops it. */\n timeout?: number;\n /** Ports to expose on every sandbox this provider creates. */\n ports?: BuddyPortInput[];\n /** API base URL. Overrides `region` — set it for on-premise installations. */\n apiUrl?: string;\n}\n\n/** Config after env-var fallbacks and validation — what the methods receive. */\nexport interface ResolvedBuddyConfig {\n token: string;\n workspace: string;\n project: string;\n os: string;\n resources?: BuddyResources;\n region: BuddyRegion;\n timeout: number;\n ports?: BuddyPortInput[];\n apiUrl: string;\n}\n\nconst SETUP_HINT =\n 'Create a token with the SANDBOX_MANAGE scope at ' +\n 'https://app.buddy.works/my-id/tokens';\n\n/** The SDK's API host table is keyed by the same region names we use. */\nexport function apiUrlForRegion(region: BuddyRegion): string {\n return API_URLS[region];\n}\n\n/**\n * One resolved config per config object handed to `buddy()`. The provider\n * methods each receive the raw config, and resolving it to a stable object is\n * what lets the SDK client below be reused across calls — a fresh client per\n * call would give up Node's keep-alive connections between `create` and the\n * first command.\n */\nconst resolved = new WeakMap<BuddyConfig, ResolvedBuddyConfig>();\n/**\n * `buddy()` with no config reads the environment on every call, so a token\n * rotated in `process.env` is picked up; the result is cached by value so the\n * SDK client (and its connection pool) is still shared while nothing changed.\n */\nconst resolvedFromEnv = new Map<string, ResolvedBuddyConfig>();\n\nexport function resolveConfig(config?: BuddyConfig): ResolvedBuddyConfig {\n if (!config) {\n const key = [\n process.env.BUDDY_TOKEN, process.env.BUDDY_WORKSPACE, process.env.BUDDY_PROJECT,\n ].join('\\u0000');\n let value = resolvedFromEnv.get(key);\n if (!value) {\n value = buildConfig({});\n resolvedFromEnv.clear();\n resolvedFromEnv.set(key, value);\n }\n return value;\n }\n const cached = resolved.get(config);\n if (cached) return cached;\n const value = buildConfig(config);\n resolved.set(config, value);\n return value;\n}\n\nfunction buildConfig(config: BuddyConfig): ResolvedBuddyConfig {\n const token = config.token ?? process.env.BUDDY_TOKEN;\n const workspace = config.workspace ?? process.env.BUDDY_WORKSPACE;\n const project = config.project ?? process.env.BUDDY_PROJECT;\n\n if (!token) {\n throw new Error(\n 'Missing Buddy API token.\\n\\n' +\n `${SETUP_HINT}\\n` +\n 'Then pass it: buddy({ token: \"xxx\" })\\n' +\n 'Or set BUDDY_TOKEN in your environment.',\n );\n }\n if (!workspace) {\n throw new Error(\n 'Missing Buddy workspace domain.\\n\\n' +\n 'It is the workspace segment of your Buddy URL ' +\n '(https://app.buddy.works/<workspace>/...).\\n' +\n 'Pass it: buddy({ workspace: \"my-workspace\" }) or set BUDDY_WORKSPACE.',\n );\n }\n if (!project) {\n throw new Error(\n 'Missing Buddy project name.\\n\\n' +\n 'Sandboxes always belong to a project. Create one in the Buddy UI, then\\n' +\n 'pass it: buddy({ project: \"my-project\" }) or set BUDDY_PROJECT.',\n );\n }\n\n const region = config.region ?? DEFAULT_REGION;\n\n return {\n token,\n workspace,\n project,\n os: config.os ?? DEFAULT_OS,\n resources: config.resources,\n region,\n timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,\n ports: config.ports,\n apiUrl: (config.apiUrl ?? apiUrlForRegion(region)).replace(/\\/+$/, ''),\n };\n}\n\n/**\n * One SDK client per resolved config. Reusing it matters: creating a sandbox\n * and running the first command is several round trips, and a shared client\n * keeps Node's connection pool warm across them.\n */\nconst clients = new WeakMap<ResolvedBuddyConfig, BuddyApiClient>();\n\n/**\n * Per-request timeout for the SDK client. Its default is 30 s, which is too\n * short for `POST /commands`: Buddy holds that request until the sandbox has\n * booted, and a drained warm pool has been measured to take over 10 s. On a\n * timeout the SDK retries the POST, which would submit the command twice.\n */\nexport const CLIENT_REQUEST_TIMEOUT_MS = 120_000;\n\nexport function getClient(config: ResolvedBuddyConfig): BuddyApiClient {\n let client = clients.get(config);\n if (!client) {\n client = new BuddyApiClient({\n workspace: config.workspace,\n project_name: config.project,\n apiUrl: config.apiUrl,\n token: config.token,\n timeout: CLIENT_REQUEST_TIMEOUT_MS,\n });\n clients.set(config, client);\n }\n return client;\n}\n\n/**\n * HTTP status behind an SDK error. `BuddySDKError` carries `statusCode`; the\n * lower-level `HttpError` the raw client throws carries `status` and is not\n * exported, so both are read structurally.\n */\nexport function statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const candidate = error as { statusCode?: unknown; status?: unknown };\n const status = candidate.statusCode ?? candidate.status;\n return typeof status === 'number' && status > 0 ? status : undefined;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isNotFound(error: unknown): boolean {\n const status = statusOf(error);\n if (status === 404) return true;\n // The content endpoints answer 400 \"Path not find in browser\" for a missing\n // path instead of 404, so the message has to be inspected as well.\n return status === 400 && /not (found|find)/i.test(messageOf(error));\n}\n\n/**\n * Buddy sandbox ids are fixed-length, so an id of any other shape never reaches\n * the handler and comes back as 400 \"Invalid url\" rather than 404. For a lookup\n * both answers mean the same thing: no such sandbox.\n */\nexport function isUnroutableId(error: unknown): boolean {\n return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));\n}\n\n/**\n * A sandbox that has not finished booting yet. Commands submitted to a\n * `STARTING` sandbox are queued by Buddy, but the `content/` and `download/`\n * endpoints reject outright with 400 \"Instance is not running\" — measured to\n * last up to ~8 s when the warm pool is drained.\n */\nexport function isInstanceNotRunning(error: unknown): boolean {\n return statusOf(error) === 400 && /instance is not running/i.test(messageOf(error));\n}\n\n/**\n * A sandbox with a lifecycle operation in flight. Buddy rejects configuration\n * changes, including opening a tunnel, until the boot or snapshot finishes.\n */\nexport function isOperationInProgress(error: unknown): boolean {\n return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));\n}\n\nexport function isAuthError(error: unknown): boolean {\n const status = statusOf(error);\n return status === 401 || status === 403;\n}\n\n/**\n * Resolves a caller-supplied path to an absolute one: relative paths are taken\n * from the sandbox home, `.` and `..` are resolved, and repeated slashes are\n * collapsed, so `/tmp/..` is rejected the same way `/` is.\n */\nexport function normalizeSandboxPath(path: string): string {\n const absolute = path.startsWith('/') ? path : `${SANDBOX_HOME}/${path}`;\n const segments: string[] = [];\n for (const segment of absolute.split('/')) {\n if (segment === '' || segment === '.') continue;\n if (segment === '..') segments.pop();\n else segments.push(segment);\n }\n if (segments.length === 0) {\n throw new Error('Path must not be empty or the filesystem root.');\n }\n return `/${segments.join('/')}`;\n}\n\n/**\n * The SDK takes content paths as a single URL segment it encodes itself, with\n * no leading slash — a leading slash produces an empty segment and a 400 from\n * the gateway.\n */\nexport function toContentPath(path: string): string {\n return normalizeSandboxPath(path).slice(1);\n}\n\nexport type SandboxStatus = 'running' | 'stopped' | 'error';\n\n/**\n * Buddy exposes more states than ComputeSDK. `STARTING` and `RESTORING` map to\n * `running` on purpose: the API queues commands submitted against a sandbox in\n * those states, so it is already usable.\n */\nexport function mapStatus(status: string | undefined): SandboxStatus {\n switch (status) {\n case 'RUNNING':\n case 'STARTING':\n case 'RESTORING':\n return 'running';\n case 'STOPPED':\n case 'STOPPING':\n return 'stopped';\n case 'FAILED':\n return 'error';\n default:\n return 'stopped';\n }\n}\n\n/**\n * Picks a resource preset from the cross-provider `cpu`/`memory` knobs.\n * Buddy only offers `N` vCPU with `2N` GB RAM, so whichever request is larger\n * wins and the result is clamped to the largest preset.\n */\nexport function resolveResources(\n options: Record<string, unknown> = {},\n fallback?: BuddyResources,\n): BuddyResources | undefined {\n if (typeof options.resources === 'string') return options.resources as BuddyResources;\n\n const requestedCpu = firstPositiveNumber([options.cpu, options.vcpus, options.cpus]);\n const requestedMemoryGb = memoryToGb(options);\n if (requestedCpu === undefined && requestedMemoryGb === undefined) return fallback;\n\n const cpuForMemory = requestedMemoryGb === undefined ? 0 : Math.ceil(requestedMemoryGb / 2);\n const cpu = Math.min(MAX_CPU, Math.max(1, requestedCpu ?? 0, cpuForMemory));\n return `${cpu}x${cpu * 2}` as BuddyResources;\n}\n\nfunction firstPositiveNumber(values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.ceil(value);\n }\n return undefined;\n}\n\n/** Memory knobs are unnormalized across providers — MB for some, MiB for others. */\nfunction memoryToGb(options: Record<string, unknown>): number | undefined {\n const mb = firstPositiveNumber([options.memory, options.memoryMb]);\n if (mb !== undefined) return mb / 1024;\n const mib = firstPositiveNumber([options.memoryMiB, options.memMiB]);\n if (mib !== undefined) return (mib * 1024 * 1024) / 1e9;\n return undefined;\n}\n\n/** Buddy identifiers allow alphanumerics, `_` and inner `-` only. */\nexport function toIdentifier(value: string): string {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9_-]+/g, '-');\n // Trim after truncating, or the cut can leave a hyphen in the last position.\n return cleaned.slice(0, 60).replace(/^-+|-+$/g, '') || 'computesdk';\n}\n\nexport function generateSandboxName(): string {\n return `computesdk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function normalizePort(input: BuddyPortInput, config: ResolvedBuddyConfig): Required<BuddyPort> {\n const port = typeof input === 'number' ? { port: input } : input;\n return {\n port: port.port,\n name: port.name ?? `p${port.port}`,\n type: port.type ?? 'HTTP',\n region: port.region ?? config.region,\n };\n}\n\n/** Buddy's tunnel object. `endpoint` holds the sandbox-side port as a string. */\nexport interface BuddyEndpoint {\n name?: string;\n endpoint?: string;\n type?: BuddyTunnelType;\n /** As reported by the API, which may know installations this provider does not offer. */\n region?: string;\n endpoint_url?: string;\n active?: boolean;\n whitelist?: string[];\n [key: string]: unknown;\n}\n\nexport function toEndpointPayload(port: Required<BuddyPort>): BuddyEndpoint {\n return {\n name: port.name,\n endpoint: String(port.port),\n type: port.type,\n region: port.region,\n };\n}\n\n/** Only HTTP and TLS tunnels get a public URL; TCP and SSH report host and port. */\nexport function endpointPublicUrl(endpoint: BuddyEndpoint): string | undefined {\n return endpoint.endpoint_url;\n}\n\nexport function endpointMatchesPort(endpoint: BuddyEndpoint, port: number): boolean {\n return Number(endpoint.endpoint) === port;\n}\n\n/** Fields Buddy reports but rejects when an endpoint is sent back in an update. */\nconst READ_ONLY_ENDPOINT_FIELDS = ['endpoint_url', 'active', 'target_latency'] as const;\n\n/**\n * Prepares an existing endpoint for the replace-all update. Everything\n * writable — `whitelist`, `timeout`, `http`, `tls` and whatever Buddy adds\n * later — has to survive, or opening a new port would reset those tunnels.\n */\nexport function toEndpointUpdate(endpoint: BuddyEndpoint): BuddyEndpoint {\n const update: BuddyEndpoint = { ...endpoint };\n for (const field of READ_ONLY_ENDPOINT_FIELDS) delete update[field];\n return update;\n}\n\n/** Swaps the scheme of a URL, for callers asking for `wss` on an HTTP tunnel. */\nexport function applyProtocol(url: string, protocol?: string): string {\n if (!protocol) return url;\n const normalized = protocol.replace(/:$/, '');\n return url.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, `${normalized}://`);\n}\n\n/**\n * What the provider passes between its own methods, and what `getInstance()`\n * hands back to callers. `client` and `fs` come straight from the SDK, so\n * consumers can drop down to it without building their own client.\n */\nexport interface BuddySandboxHandle {\n sandboxId: string;\n identifier: string;\n config: ResolvedBuddyConfig;\n client: BuddyApiClient;\n fs: FileSystem;\n createdAt: Date;\n /** True unless this process created the sandbox; Buddy reports no creation date. */\n createdAtIsReconnectTime: boolean;\n timeout: number;\n os?: string;\n resources?: string;\n /** Tunnels known so far. `getUrl` extends this when it opens a new one. */\n endpoints: BuddyEndpoint[];\n}\n\n/** Sandbox as the API returns it, narrowed to the fields the provider reads. */\nexport interface BuddySandboxData {\n id?: string;\n identifier?: string;\n name?: string;\n status?: string;\n setup_status?: string;\n os?: string;\n resources?: string;\n timeout?: number;\n endpoints?: BuddyEndpoint[];\n ssh_host?: string;\n ssh_port?: number;\n}\n\n/**\n * Buddy's sandbox resource carries no creation date (only projects and\n * snapshots do), and `SandboxInfo.createdAt` is a required `Date`, so a handle\n * rebuilt by `getById` or `list` can only record when it was reconnected.\n * `getInfo` marks that case with `metadata.createdAtIsReconnectTime`.\n */\nexport function toHandle(\n config: ResolvedBuddyConfig,\n sandbox: BuddySandboxData,\n createdAt = new Date(),\n createdAtIsReconnectTime = true,\n): BuddySandboxHandle {\n const sandboxId = sandbox.id;\n if (!sandboxId) {\n throw new Error('Buddy API returned a sandbox without an id.');\n }\n const client = getClient(config);\n\n return {\n sandboxId,\n identifier: sandbox.identifier ?? sandboxId,\n config,\n client,\n fs: new FileSystem(client, sandboxId),\n createdAt,\n createdAtIsReconnectTime,\n timeout: sandbox.timeout != null ? sandbox.timeout * 1000 : config.timeout,\n os: sandbox.os,\n resources: sandbox.resources,\n endpoints: sandbox.endpoints ?? [],\n };\n}\n\nexport async function getSandboxData(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n): Promise<BuddySandboxData> {\n return await getClient(config).getSandboxById({ path: { id: sandboxId } }) as BuddySandboxData;\n}\n\nexport async function sleep(ms: number): Promise<void> {\n await new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * The boot gate.\n *\n * `create` deliberately returns while the sandbox is still starting, because\n * Buddy queues commands submitted against a starting sandbox. Two other groups\n * of endpoints do not queue:\n *\n * - the content endpoints answer 400 \"Instance is not running\", or answer 2xx to\n * a write whose bytes never land (observed roughly once in twelve sandboxes);\n * - `updateSandbox` answers 400 \"Cannot update sandbox, operation in progress\".\n *\n * So those calls wait here for `RUNNING` + `setup_status: SUCCESS` once per\n * sandbox, and retry the two races until the deadline.\n */\n\nimport {\n getSandboxData,\n isInstanceNotRunning,\n isOperationInProgress,\n sleep,\n type BuddySandboxHandle,\n} from './utils.js';\n\n/** Long enough to cover a drained warm pool; a real boot failure surfaces sooner. */\nconst BOOT_WAIT_TIMEOUT_MS = 90_000;\nconst BOOT_WAIT_POLL_MS = 250;\n\n/** Sandboxes already known to have booted — the gate runs at most once each. */\nconst settled = new WeakSet<BuddySandboxHandle>();\n\nexport async function untilSettled(sandbox: BuddySandboxHandle): Promise<void> {\n if (settled.has(sandbox)) return;\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n if (data.status === 'RUNNING' && data.setup_status === 'SUCCESS') {\n settled.add(sandbox);\n return;\n }\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} failed to start ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} was still starting after ` +\n `${BOOT_WAIT_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(BOOT_WAIT_POLL_MS);\n }\n}\n\n/**\n * Runs an operation once the sandbox has booted, retrying the races that remain\n * afterwards — Buddy reports a snapshot or app operation still in flight the\n * same way.\n */\nexport async function whenBooted<T>(\n sandbox: BuddySandboxHandle,\n operation: () => Promise<T>,\n): Promise<T> {\n await untilSettled(sandbox);\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n try {\n return await operation();\n } catch (error) {\n const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);\n if (!retryable || Date.now() >= deadline) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\n }\n }\n}\n","/**\n * Command execution.\n *\n * Buddy accepts a command and returns its id immediately; output arrives over a\n * JSONL log stream. The provider consumes that stream once through the SDK's\n * `Command` entity, splits it into stdout/stderr and forwards chunks to the\n * streaming callbacks, then reads the exit code from the command details.\n * `Command.wait()` is deliberately unused — it polls once a second, which would\n * add up to a second to every call.\n */\n\nimport { Command } from '@buddy-works/sandbox-sdk';\nimport { escapeShellArg } from '@computesdk/provider';\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\n\nimport { sleep, type BuddyCommandRuntime, type BuddySandboxHandle } from './utils.js';\n\nexport interface BuddyRunCommandOptions extends RunCommandOptions {\n /**\n * Interpreter Buddy runs the command with. Defaults to `BASH`; the other\n * runtimes take a script instead of a shell line, so `cwd` and `env` do not\n * apply to them.\n */\n runtime?: BuddyCommandRuntime;\n}\n\n/** What a POSIX shell accepts as a variable name. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Prepends `cd` and `export` when the caller asked for a cwd or env. Values are\n * escaped; names cannot be, so a name that is not a valid identifier is\n * rejected instead of being spliced into the shell line.\n */\nexport function buildShellCommand(command: string, options: RunCommandOptions = {}): string {\n let line = command;\n\n if (options.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([key, value]) => {\n if (!ENV_NAME.test(key)) {\n throw new TypeError(\n `Invalid environment variable name ${JSON.stringify(key)}: `\n + 'names must match /^[A-Za-z_][A-Za-z0-9_]*$/.',\n );\n }\n return `${key}=\"${escapeShellArg(String(value))}\"`;\n })\n .join(' ');\n line = `export ${exports} && ${line}`;\n }\n if (options.cwd) {\n line = `cd \"${escapeShellArg(options.cwd)}\" && ${line}`;\n }\n return line;\n}\n\n/** A termination that fails leaves the command running remotely, so retry. */\nconst KILL_ATTEMPTS = 3;\nconst KILL_RETRY_DELAY_MS = 500;\n\n/** Best-effort kill: never throws, gives up after `KILL_ATTEMPTS`. */\nexport async function killCommand(running: Pick<Command, 'kill'>): Promise<boolean> {\n for (let attempt = 1; attempt <= KILL_ATTEMPTS; attempt++) {\n try {\n await running.kill();\n return true;\n } catch {\n if (attempt < KILL_ATTEMPTS) await sleep(KILL_RETRY_DELAY_MS);\n }\n }\n return false;\n}\n\nexport async function runCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n options: BuddyRunCommandOptions = {},\n): Promise<CommandResult> {\n // `ADD-PROVIDER.md` still documents an older `runCommand(command, args)`\n // shape. Called that way, the array arrives here as `options`, where only\n // `cwd` and `env` are read — the arguments would be dropped silently and the\n // bare command would still exit 0. Fail loudly instead.\n if (Array.isArray(options)) {\n throw new TypeError(\n `runCommand takes a command line and an options object, not an argument array. `\n + `Pass the arguments inside the command, e.g. '${command} ${options.join(' ')}'.`,\n );\n }\n\n const startedAt = Date.now();\n const runtime = options.runtime ?? 'BASH';\n const payload = runtime === 'BASH' ? buildShellCommand(command, options) : command;\n\n const deadline = options.timeout ? startedAt + options.timeout : undefined;\n const timedOutResult = (stdout = '', stderr = '') => ({\n stdout, stderr, exitCode: TIMEOUT_EXIT_CODE, durationMs: Date.now() - startedAt,\n });\n\n // Buddy may hold the submission while the sandbox boots (up to the client's\n // request timeout), so the deadline applies here too: when it passes first,\n // the timeout result is returned and the command is killed once (if ever)\n // Buddy reports it accepted.\n const submission = sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command: payload, runtime },\n });\n const commandResponse = deadline ? await raceDeadline(submission, deadline) : await submission;\n if (commandResponse === DEADLINE_PASSED) {\n void submission.then(\n response => {\n if (!response.id) return;\n void killCommand(new Command({\n commandResponse: response,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n }));\n },\n () => {},\n );\n return timedOutResult();\n }\n\n const commandId = commandResponse.id;\n if (!commandId) {\n throw new Error('Buddy accepted the command but returned no command id.');\n }\n\n const running = new Command({\n commandResponse,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n });\n\n // Fire-and-forget: return as soon as Buddy has the command queued.\n if (options.background) {\n return { stdout: '', stderr: '', exitCode: 0, durationMs: Date.now() - startedAt };\n }\n\n const stdout: string[] = [];\n const stderr: string[] = [];\n\n // `follow: true` holds the connection open until the command exits, so this\n // loop is the wait — nothing is polled. Each record is one line without its\n // terminator, so the newline goes back on here. Once the caller has been\n // given the timeout result the loop stops at the next record instead of\n // buffering output and firing callbacks for a result nobody will read.\n let timedOut = false;\n const drain = (async () => {\n for await (const log of running.logs({ follow: true })) {\n if (timedOut) break;\n if (log.data == null) continue;\n const chunk = `${log.data}\\n`;\n if (log.type === 'STDERR') {\n stderr.push(chunk);\n options.onStderr?.(chunk);\n } else {\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n }\n })();\n\n // The SDK stream cannot be aborted, so on timeout the result is returned\n // right away — with whatever output arrived before the deadline — and the\n // reader is left to finish on its own once the kill (best effort, retried)\n // closes it or the next record arrives.\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n void killCommand(running);\n drain.catch(() => {});\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n } catch (error) {\n // The stream broke mid-command. Buddy keeps running it, so stop it — best\n // effort and not awaited, so a hanging kill cannot delay the error.\n void killCommand(running);\n throw error;\n }\n\n return {\n stdout: stdout.join(''),\n stderr: stderr.join(''),\n exitCode: await waitForExitCode(sandbox, commandId),\n durationMs: Date.now() - startedAt,\n };\n}\n\nconst DEADLINE_PASSED = Symbol('deadline passed');\n\n/** Resolves to `DEADLINE_PASSED` if `deadline` (epoch ms) arrives first. */\nasync function raceDeadline<T>(work: Promise<T>, deadline: number): Promise<T | typeof DEADLINE_PASSED> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expiry = new Promise<typeof DEADLINE_PASSED>(resolve => {\n timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));\n });\n try {\n return await Promise.race([work, expiry]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** What a shell reports for a command killed by `timeout(1)`. */\nexport const TIMEOUT_EXIT_CODE = 124;\n\nconst EXIT_CODE_WAIT_MS = 5_000;\nconst EXIT_CODE_POLL_MS = 200;\n\nexport interface BuddyCommandDetails {\n exit_code?: number;\n status?: string;\n}\n\n/**\n * The log stream can close a moment before Buddy records the result, so the\n * details may still say `INPROGRESS` without an `exit_code`. Treating that as\n * success would hide failures; poll briefly until a terminal state shows up.\n */\nexport async function waitForExitCode(\n sandbox: Pick<BuddySandboxHandle, 'client' | 'sandboxId'>,\n commandId: string,\n deadlineMs = EXIT_CODE_WAIT_MS,\n): Promise<number> {\n const deadline = Date.now() + deadlineMs;\n for (;;) {\n const details: BuddyCommandDetails = await sandbox.client.getCommandDetails({\n path: { sandbox_id: sandbox.sandboxId, id: commandId },\n });\n if (typeof details.exit_code === 'number') return details.exit_code;\n if (details.status === 'FAILED') return 1;\n if (details.status === 'SUCCESSFUL') return 0;\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy command ${commandId} on sandbox ${sandbox.sandboxId} reported no exit code `\n + `within ${deadlineMs / 1000}s of its log stream closing (status: ${details.status ?? 'unknown'}).`,\n );\n }\n await new Promise(resolve => setTimeout(resolve, EXIT_CODE_POLL_MS));\n }\n}\n","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — one round trip per operation and binary-safe, unlike shelling out\n * to `cat`/`tee`.\n *\n * Every call goes through the boot gate in `boot.ts`, because unlike commands\n * these endpoints do not queue against a sandbox that is still starting.\n */\n\nimport type { FileEntry } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n toContentPath,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport async function readFile(sandbox: BuddySandboxHandle, path: string): Promise<string> {\n const target = normalizeSandboxPath(path);\n const buffer = await whenBooted(sandbox, () => sandbox.fs.downloadFile(target));\n return buffer.toString('utf-8');\n}\n\nexport async function writeFile(\n sandbox: BuddySandboxHandle,\n path: string,\n content: string,\n): Promise<void> {\n const target = normalizeSandboxPath(path);\n const parent = target.slice(0, target.lastIndexOf('/'));\n\n await whenBooted(sandbox, async () => {\n // Buddy will not create missing parents for an upload, and mirroring\n // `fs.writeFile` here is what callers expect.\n if (parent) {\n await sandbox.fs.createFolder(parent).catch(() => {});\n }\n await sandbox.fs.uploadFile(Buffer.from(content, 'utf-8'), target);\n });\n}\n\nexport async function mkdir(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n await whenBooted(sandbox, () => sandbox.fs.createFolder(target));\n}\n\nexport async function readdir(sandbox: BuddySandboxHandle, path: string): Promise<FileEntry[]> {\n const target = normalizeSandboxPath(path);\n const entries = await whenBooted(sandbox, () => sandbox.fs.listFiles(target));\n\n return entries.map(entry => ({\n name: entry.name ?? '',\n type: entry.type === 'DIR' ? 'directory' as const : 'file' as const,\n // The API reports sizes as bigint; ComputeSDK wants a number.\n ...(entry.size == null ? {} : { size: Number(entry.size) }),\n }));\n}\n\nexport async function exists(sandbox: BuddySandboxHandle, path: string): Promise<boolean> {\n const target = toContentPath(path);\n try {\n await whenBooted(sandbox, () =>\n sandbox.client.getSandboxContent({ path: { sandbox_id: sandbox.sandboxId, path: target } }));\n return true;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n}\n\nexport async function remove(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n try {\n await whenBooted(sandbox, () => sandbox.fs.deleteFile(target));\n } catch (error) {\n // Removing something that is already gone is not an error for callers.\n if (!isNotFound(error)) throw error;\n }\n}\n","/**\n * Snapshots — filesystem images of a sandbox that a new sandbox can boot from.\n *\n * Buddy creates them asynchronously: the create call returns `status: CREATING`\n * and the snapshot cannot be restored until it turns `CREATED`. The provider\n * waits for that here so callers get a snapshot they can actually use. The\n * wait uses a 500 ms poll rather than the SDK entity's 2 s one, because typical\n * snapshots settle in well under a second.\n */\n\nimport type { CreateSnapshotOptions, ListSnapshotsOptions } from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport {\n PROVIDER,\n getClient,\n isNotFound,\n sleep,\n toIdentifier,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\nconst SNAPSHOT_WAIT_TIMEOUT_MS = 180_000;\nconst SNAPSHOT_WAIT_POLL_MS = 500;\n\ninterface BuddySnapshotData {\n id?: string;\n name?: string;\n size?: number;\n status?: string;\n create_date?: Date | string;\n}\n\nfunction toSnapshot(data: BuddySnapshotData, sandboxId?: string): Snapshot {\n if (!data.id) {\n throw new Error('Buddy API returned a snapshot without an id.');\n }\n return {\n id: data.id,\n provider: PROVIDER,\n createdAt: data.create_date ? new Date(data.create_date) : new Date(),\n metadata: {\n name: data.name,\n status: data.status,\n sizeGb: data.size,\n ...(sandboxId ? { sandboxId } : {}),\n },\n };\n}\n\nexport async function createSnapshot(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n options: CreateSnapshotOptions = {},\n): Promise<Snapshot> {\n const client = getClient(config);\n const created = await client.addSandboxSnapshot({\n path: { sandbox_id: sandboxId },\n body: { name: toIdentifier(options.name ?? `computesdk-${Date.now()}`) },\n });\n\n const snapshotId = created.id;\n if (!snapshotId) {\n throw new Error('Buddy accepted the snapshot but returned no snapshot id.');\n }\n\n const ready = await waitUntilCreated(config, sandboxId, snapshotId, created);\n return toSnapshot(ready, sandboxId);\n}\n\nasync function waitUntilCreated(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n snapshotId: string,\n initial: BuddySnapshotData,\n): Promise<BuddySnapshotData> {\n if (initial.status === 'CREATED') return initial;\n\n const client = getClient(config);\n const deadline = Date.now() + SNAPSHOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await client.getSandboxSnapshot({\n path: { sandbox_id: sandboxId, id: snapshotId },\n }) as BuddySnapshotData;\n\n if (data.status === 'CREATED') return data;\n if (data.status === 'FAILED') {\n throw new Error(`Buddy snapshot ${snapshotId} failed to be created.`);\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy snapshot ${snapshotId} was still ${data.status} after ` +\n `${SNAPSHOT_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(SNAPSHOT_WAIT_POLL_MS);\n }\n}\n\nexport async function listSnapshots(\n config: ResolvedBuddyConfig,\n options: ListSnapshotsOptions = {},\n): Promise<Snapshot[]> {\n const client = getClient(config);\n // Default to the project-wide listing: snapshots outlive the sandbox they were\n // taken from, so the per-sandbox endpoint would hide most of them.\n const response = options.sandboxId\n ? await client.getSandboxSnapshots({ path: { sandbox_id: options.sandboxId } })\n : await client.getProjectSnapshots({});\n\n const snapshots = (response.snapshots ?? [])\n .map(snapshot => toSnapshot(snapshot as BuddySnapshotData, options.sandboxId));\n return options.limit ? snapshots.slice(0, options.limit) : snapshots;\n}\n\nexport async function deleteSnapshot(\n config: ResolvedBuddyConfig,\n snapshotId: string,\n): Promise<void> {\n try {\n await getClient(config).deleteSnapshot({ path: { id: snapshotId } });\n } catch (error) {\n // Deleting an already-deleted snapshot is the state the caller wanted.\n if (!isNotFound(error)) throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAAA,mBAA+B;;;ACH/B,yBAAqD;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,iBAA8B;AAEpC,IAAM,qBAAqB;AAE3B,IAAM,eAAe;AAsBrB,IAAM,UAAU;AAmDvB,IAAM,aACJ;AAIK,SAAS,gBAAgB,QAA6B;AAC3D,SAAO,4BAAS,MAAM;AACxB;AASA,IAAM,WAAW,oBAAI,QAA0C;AAM/D,IAAM,kBAAkB,oBAAI,IAAiC;AAEtD,SAAS,cAAc,QAA2C;AACvE,MAAI,CAAC,QAAQ;AACX,UAAM,MAAM;AAAA,MACV,QAAQ,IAAI;AAAA,MAAa,QAAQ,IAAI;AAAA,MAAiB,QAAQ,IAAI;AAAA,IACpE,EAAE,KAAK,IAAQ;AACf,QAAIC,SAAQ,gBAAgB,IAAI,GAAG;AACnC,QAAI,CAACA,QAAO;AACV,MAAAA,SAAQ,YAAY,CAAC,CAAC;AACtB,sBAAgB,MAAM;AACtB,sBAAgB,IAAI,KAAKA,MAAK;AAAA,IAChC;AACA,WAAOA;AAAA,EACT;AACA,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,MAAI,OAAQ,QAAO;AACnB,QAAM,QAAQ,YAAY,MAAM;AAChC,WAAS,IAAI,QAAQ,KAAK;AAC1B,SAAO;AACT;AAEA,SAAS,YAAY,QAA0C;AAC7D,QAAM,QAAQ,OAAO,SAAS,QAAQ,IAAI;AAC1C,QAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAClD,QAAM,UAAU,OAAO,WAAW,QA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AM,WAAW,MAAM,gBAAgB,SAAS,IAAI;AACpD,MAAI,SAAU,QAAO,cAAc,UAAU,QAAQ;AAErD,QAAM,UAAU,cAAc,EAAE,KAAK,GAAG,QAAQ,MAAM;AAGtD,QAAM,OAAO,QAAQ,UAClB,OAAO,cAAY,CAAC,oBAAoB,UAAU,IAAI,CAAC,EACvD,IAAI,gBAAgB;AAGvB,QAAM,UAAU,MAAM,WAAW,SAAS,MAAM,QAAQ,OAAO,cAAc;AAAA,IAC3E,MAAM,EAAE,IAAI,QAAQ,UAAU;AAAA,IAC9B,MAAM,EAAE,WAAW,CAAC,GAAG,MAAM,kBAAkB,OAAO,CAAC,EAAE;AAAA,EAC3D,CAAC,CAAC;AACF,UAAQ,YAAa,QAAQ,aAAa,QAAQ;AAElD,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,UAAM,MAAM,MAAM,gBAAgB,SAAS,IAAI;AAC/C,QAAI,IAAK,QAAO,cAAc,KAAK,QAAQ;AAC3C,QAAI,KAAK,IAAI,KAAK,UAAU;AAC1B,YAAM,IAAI;AAAA,QACR,iCAAiC,IAAI,eAAe,QAAQ,SAAS,uCAC/B,sBAAsB,GAAI;AAAA,MAClE;AAAA,IACF;AACA,UAAM,MAAM,gBAAgB;AAAA,EAC9B;AACF;AAEA,eAAe,gBACb,SACA,MAC6B;AAC7B,QAAM,OAAO,MAAM,eAAe,QAAQ,QAAQ,QAAQ,SAAS;AACnE,UAAQ,YAAY,KAAK,aAAa,CAAC;AACvC,QAAM,QAAQ,QAAQ,UAAU,KAAK,cAAY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["import_provider","value","import_sandbox_sdk","exports","stdout","stderr","resolved"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/boot.ts","../src/commands.ts","../src/filesystem.ts","../src/snapshots.ts"],"sourcesContent":["/**\n * Buddy provider for ComputeSDK.\n *\n * Buddy serves Ubuntu sandboxes from a pre-warmed pool, so `create` returns a\n * sandbox that is already booting and commands submitted to it are queued until\n * it is up. The provider does not wait for `RUNNING` on create — that keeps\n * time-to-first-command at the warm-pool latency instead of a poll interval.\n *\n * Snapshots are Buddy's only reusable image, so `compute.template.*` is mapped\n * onto them.\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateSandboxOptions,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n SandboxInfo,\n} from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport type { BuddyApiClient } from '@buddy-works/sandbox-sdk';\nimport { whenBooted } from './boot.js';\nimport { runCommand, type BuddyRunCommandOptions } from './commands.js';\nimport * as fs from './filesystem.js';\nimport { createSnapshot, deleteSnapshot, listSnapshots } from './snapshots.js';\nimport {\n PROVIDER,\n applyProtocol,\n endpointMatchesPort,\n endpointPublicUrl,\n generateSandboxName,\n getClient,\n getSandboxData,\n isNotFound,\n isUnroutableId,\n mapStatus,\n normalizePort,\n resolveConfig,\n resolveResources,\n sleep,\n statusOf,\n toEndpointPayload,\n toEndpointUpdate,\n toHandle,\n toIdentifier,\n type BuddyConfig,\n type BuddyEndpoint,\n type BuddyPortInput,\n type BuddySandboxHandle,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\n/** Deleting a just-created sandbox occasionally answers 5xx while succeeding. */\nconst DESTROY_ATTEMPTS = 3;\nconst DESTROY_RETRY_DELAY_MS = 500;\n\n/** A tunnel is registered instantly but takes a moment to get its public URL. */\nconst URL_WAIT_TIMEOUT_MS = 15_000;\nconst URL_WAIT_POLL_MS = 250;\n\n/**\n * Deletes a sandbox, retrying transient server failures. \"Already gone\" is the\n * state the caller asked for, so it counts as success.\n */\nexport async function deleteSandbox(client: BuddyApiClient, sandboxId: string): Promise<void> {\n for (let attempt = 1; attempt <= DESTROY_ATTEMPTS; attempt++) {\n try {\n await client.deleteSandboxById({ path: { id: sandboxId } });\n return;\n } catch (error) {\n if (isNotFound(error)) return;\n const status = statusOf(error);\n const retryable = status !== undefined && status >= 500;\n if (!retryable || attempt === DESTROY_ATTEMPTS) throw error;\n await sleep(DESTROY_RETRY_DELAY_MS);\n }\n }\n}\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n methods: {\n sandbox: {\n create: async (config: BuddyConfig, options?: CreateSandboxOptions) => {\n const resolved = resolveConfig(config);\n const created = await getClient(resolved).addSandbox({\n body: buildCreateBody(resolved, options),\n });\n\n const sandbox = toHandle(resolved, created, new Date(), false);\n try {\n await ensureTimeout(sandbox, options?.timeout ?? resolved.timeout);\n } catch (error) {\n // The framework has no id yet, so nothing else could clean this up.\n await deleteSandbox(sandbox.client, sandbox.sandboxId).catch(() => {});\n throw error;\n }\n return { sandbox, sandboxId: sandbox.sandboxId };\n },\n\n getById: async (config: BuddyConfig, sandboxId: string) => {\n const resolved = resolveConfig(config);\n try {\n const data = await getSandboxData(resolved, sandboxId);\n const sandbox = toHandle(resolved, data);\n return { sandbox, sandboxId: sandbox.sandboxId };\n } catch (error) {\n if (isNotFound(error) || isUnroutableId(error)) return null;\n throw error;\n }\n },\n\n list: async (config: BuddyConfig) => {\n const resolved = resolveConfig(config);\n const response = await getClient(resolved).getSandboxes({});\n\n // The listing carries ids only; details are fetched on demand by\n // getInfo, so listing a hundred sandboxes stays a single request.\n return (response.sandboxes ?? [])\n .filter(entry => Boolean(entry.id))\n .map(entry => {\n const sandbox = toHandle(resolved, entry);\n return { sandbox, sandboxId: sandbox.sandboxId };\n });\n },\n\n destroy: async (config: BuddyConfig, sandboxId: string) =>\n deleteSandbox(getClient(resolveConfig(config)), sandboxId),\n\n runCommand: async (\n sandbox: BuddySandboxHandle,\n command: string,\n options?: BuddyRunCommandOptions,\n ) => runCommand(sandbox, command, options),\n\n // `runCommand` already forwards `onStdout`/`onStderr` from Buddy's own\n // log stream. Without this the factory would ignore that and bootstrap\n // its Node-based streaming daemon inside the sandbox instead.\n streamCommand: runCommand,\n\n getInfo: async (sandbox: BuddySandboxHandle): Promise<SandboxInfo> => {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? sandbox.endpoints;\n\n return {\n id: sandbox.sandboxId,\n provider: PROVIDER,\n status: mapStatus(data.status),\n createdAt: sandbox.createdAt,\n timeout: data.timeout != null ? data.timeout * 1000 : sandbox.timeout,\n metadata: {\n createdAtIsReconnectTime: sandbox.createdAtIsReconnectTime,\n identifier: data.identifier ?? sandbox.identifier,\n name: data.name,\n os: data.os,\n resources: data.resources,\n buddyStatus: data.status,\n setupStatus: data.setup_status,\n workspace: sandbox.config.workspace,\n project: sandbox.config.project,\n region: sandbox.config.region,\n endpoints: (data.endpoints ?? []).map(endpoint => ({\n name: endpoint.name,\n port: Number(endpoint.endpoint),\n type: endpoint.type,\n url: endpointPublicUrl(endpoint),\n })),\n },\n };\n },\n\n getUrl: async (sandbox: BuddySandboxHandle, options: { port: number; protocol?: string }) =>\n getUrl(sandbox, options),\n\n getInstance: (sandbox: BuddySandboxHandle) => sandbox,\n\n filesystem: {\n readFile: (sandbox: BuddySandboxHandle, path: string) => fs.readFile(sandbox, path),\n writeFile: (sandbox: BuddySandboxHandle, path: string, content: string) =>\n fs.writeFile(sandbox, path, content),\n mkdir: (sandbox: BuddySandboxHandle, path: string) => fs.mkdir(sandbox, path),\n readdir: (sandbox: BuddySandboxHandle, path: string) => fs.readdir(sandbox, path),\n exists: (sandbox: BuddySandboxHandle, path: string) => fs.exists(sandbox, path),\n remove: (sandbox: BuddySandboxHandle, path: string) => fs.remove(sandbox, path),\n },\n },\n\n snapshot: {\n create: (config: BuddyConfig, sandboxId: string, options?: { name?: string }) =>\n createSnapshot(resolveConfig(config), sandboxId, options),\n list: (config: BuddyConfig, options?: ListSnapshotsOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, snapshotId: string) =>\n deleteSnapshot(resolveConfig(config), snapshotId),\n },\n\n /**\n * Buddy has no separate template entity — a snapshot is the reusable image,\n * and `create({ templateId })` boots from one. So listing and deleting\n * templates operate on snapshots, and creating one points the caller at\n * `compute.snapshot.create`, which is where an image comes from.\n */\n template: {\n create: async () => {\n throw new Error(\n 'Buddy does not have templates as a separate entity. Snapshot a ' +\n 'configured sandbox instead: const snapshot = await compute.snapshot.create(sandboxId), ' +\n 'then boot from it with compute.sandbox.create({ snapshotId: snapshot.id }).',\n );\n },\n list: (config: BuddyConfig, options?: ListTemplatesOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, templateId: string) =>\n deleteSnapshot(resolveConfig(config), templateId),\n },\n },\n});\n\n/** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */\nexport function toSeconds(ms: number): number {\n return Math.max(1, Math.ceil(ms / 1000));\n}\n\nfunction buildCreateBody(config: ResolvedBuddyConfig, options: CreateSandboxOptions = {}) {\n const name = options.name ?? generateSandboxName();\n const timeoutMs = options.timeout ?? config.timeout;\n // `templateId` is accepted alongside `snapshotId` because Buddy's template\n // methods are backed by snapshots — both carry a snapshot id.\n const snapshotId = options.snapshotId ?? options.templateId;\n\n const body: Record<string, unknown> = {\n name,\n identifier: toIdentifier(name),\n os: options.image ?? config.os,\n timeout: toSeconds(timeoutMs),\n };\n\n const resources = resolveResources(options, config.resources);\n if (resources) body.resources = resources;\n\n // Buddy-specific create options, passed through as they are named in the API.\n if (options.firstBootCommands) body.first_boot_commands = options.firstBootCommands;\n if (options.appDir) body.app_dir = options.appDir;\n if (options.tags) body.tags = options.tags;\n\n const ports = options.ports ?? config.ports;\n if (ports?.length) {\n body.endpoints = ports.map((port: BuddyPortInput) =>\n toEndpointPayload(normalizePort(port, config)));\n }\n if (options.envs && Object.keys(options.envs).length > 0) {\n body.variables = Object.entries(options.envs).map(([key, value]) => ({ key, value }));\n }\n if (snapshotId) body.snapshot_id = snapshotId;\n\n return body as any;\n}\n\n/**\n * Buddy's create-from-snapshot request has no `timeout` field (the SDK schema\n * strips it), so a sandbox booted from a snapshot comes back with whatever the\n * snapshot carried. Patch it afterwards when it differs from what was asked.\n */\nexport async function ensureTimeout(\n sandbox: BuddySandboxHandle,\n timeoutMs: number,\n): Promise<void> {\n const seconds = toSeconds(timeoutMs);\n if (toSeconds(sandbox.timeout) === seconds) return;\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { timeout: seconds } as any,\n }));\n sandbox.timeout = updated.timeout != null ? updated.timeout * 1000 : seconds * 1000;\n}\n\n/**\n * Endpoint updates in flight, per remote sandbox. Buddy replaces the whole\n * endpoint list on update, so two concurrent `getUrl` calls built from the same\n * list would each drop the other's port — they run one after another instead.\n * Keyed by installation + sandbox id rather than by handle: `getById` and\n * `list` hand out a fresh handle each time for the same remote sandbox.\n */\nconst endpointUpdates = new Map<string, Promise<unknown>>();\n\nfunction endpointUpdateKey(sandbox: BuddySandboxHandle): string {\n return `${sandbox.config.apiUrl}|${sandbox.config.workspace}|${sandbox.sandboxId}`;\n}\n\nfunction getUrl(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const key = endpointUpdateKey(sandbox);\n const previous = endpointUpdates.get(key) ?? Promise.resolve();\n const next = previous.catch(() => {}).then(() => openPort(sandbox, options));\n endpointUpdates.set(key, next);\n // Drop the entry once nothing newer is queued behind it, so the map only\n // ever holds sandboxes with an update actually in flight.\n next.catch(() => {}).finally(() => {\n if (endpointUpdates.get(key) === next) endpointUpdates.delete(key);\n });\n return next;\n}\n\nasync function openPort(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const { port, protocol } = options;\n const existing = await findEndpointUrl(sandbox, port);\n if (existing) return applyProtocol(existing, protocol);\n\n const desired = normalizePort({ port }, sandbox.config);\n // Buddy replaces the whole endpoint list on update, so previously opened\n // tunnels have to be sent back or they would be torn down here.\n const kept = sandbox.endpoints\n .filter(endpoint => !endpointMatchesPort(endpoint, port))\n .map(toEndpointUpdate);\n\n // Buddy refuses configuration changes while the sandbox is still starting.\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { endpoints: [...kept, toEndpointPayload(desired)] } as any,\n }));\n sandbox.endpoints = (updated.endpoints ?? sandbox.endpoints) as BuddyEndpoint[];\n\n const deadline = Date.now() + URL_WAIT_TIMEOUT_MS;\n for (;;) {\n const url = await findEndpointUrl(sandbox, port);\n if (url) return applyProtocol(url, protocol);\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy opened a tunnel to port ${port} on sandbox ${sandbox.sandboxId} ` +\n `but published no public URL within ${URL_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(URL_WAIT_POLL_MS);\n }\n}\n\nasync function findEndpointUrl(\n sandbox: BuddySandboxHandle,\n port: number,\n): Promise<string | undefined> {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? [];\n const match = sandbox.endpoints.find(endpoint => endpointMatchesPort(endpoint, port));\n return match ? endpointPublicUrl(match) : undefined;\n}\n\nexport type { BuddyConfig, BuddySandboxHandle as BuddySandbox } from './utils.js';\nexport type { BuddyRunCommandOptions } from './commands.js';\n","/**\n * Shared types, config resolution and SDK plumbing for the Buddy provider.\n *\n * All API access goes through `@buddy-works/sandbox-sdk`. The provider uses the\n * SDK's `BuddyApiClient` rather than its high-level `Sandbox` façade for sandbox\n * creation: `Sandbox.create()` waits for `setup_status: SUCCESS` and\n * `status: RUNNING` with a 1 s poll, and since a sandbox from Buddy's warm pool\n * is usable in ~400 ms that wait would dominate time-to-first-command. The\n * façade's `Command`, `FileSystem` and snapshot helpers are used as-is.\n */\n\nimport { API_URLS, BuddyApiClient, FileSystem } from '@buddy-works/sandbox-sdk';\n\nexport const PROVIDER = 'buddy' as const;\nexport const DEFAULT_OS = 'ubuntu:24.04';\nexport const DEFAULT_REGION: BuddyRegion = 'US';\n/** Buddy stops a sandbox after this many ms of life unless overridden. */\nexport const DEFAULT_TIMEOUT_MS = 3_600_000;\n/** Working directory of the default `buddy` user — relative paths resolve here. */\nexport const SANDBOX_HOME = '/buddy';\n\n/**\n * Buddy installation, in the spelling its tunnel API uses. Each installation is\n * a separate deployment with its own API host, workspaces and tokens — `US` is\n * not a placement hint within one API.\n */\nexport type BuddyRegion = 'US' | 'EU';\n\n/** Interpreter Buddy runs a command with. `BASH` is the default. */\nexport type BuddyCommandRuntime = 'BASH' | 'JAVASCRIPT' | 'TYPESCRIPT' | 'PYTHON';\n\n/** Tunnel protocol. Only `HTTP` yields a public `endpoint_url`. */\nexport type BuddyTunnelType = 'HTTP' | 'TLS' | 'TCP' | 'SSH';\n\n/**\n * Buddy resource preset, `\"{vCPU}x{RAM in GB}\"`. RAM is always 2 GB per vCPU.\n */\nexport type BuddyResources =\n | '1x2' | '2x4' | '3x6' | '4x8' | '5x10' | '6x12'\n | '7x14' | '8x16' | '9x18' | '10x20' | '11x22' | '12x24';\n\nexport const MAX_CPU = 12;\n\n/** A port to expose publicly. A bare number means `{ port, type: 'HTTP' }`. */\nexport interface BuddyPort {\n port: number;\n /** Tunnel name. Becomes the first label of the public hostname. */\n name?: string;\n type?: BuddyTunnelType;\n region?: BuddyRegion;\n}\n\nexport type BuddyPortInput = number | BuddyPort;\n\nexport interface BuddyConfig {\n /** API token with the `SANDBOX_MANAGE` scope. Falls back to `BUDDY_TOKEN`. */\n token?: string;\n /** Workspace domain. Falls back to `BUDDY_WORKSPACE`. */\n workspace?: string;\n /** Project the sandboxes belong to. Falls back to `BUDDY_PROJECT`. */\n project?: string;\n /** Base OS image — `'ubuntu:24.04'` (default) or `'ubuntu:22.04'`. */\n os?: string;\n /** Resource preset. Buddy's own default applies when omitted. */\n resources?: BuddyResources;\n /**\n * Buddy installation to use. Selects both the API host and where tunnels\n * terminate. Defaults to `'US'`. A token is only valid on its own\n * installation.\n */\n region?: BuddyRegion;\n /** Sandbox lifetime in milliseconds, after which Buddy stops it. */\n timeout?: number;\n /** Ports to expose on every sandbox this provider creates. */\n ports?: BuddyPortInput[];\n /** API base URL. Overrides `region` — set it for on-premise installations. */\n apiUrl?: string;\n}\n\n/** Config after env-var fallbacks and validation — what the methods receive. */\nexport interface ResolvedBuddyConfig {\n token: string;\n workspace: string;\n project: string;\n os: string;\n resources?: BuddyResources;\n region: BuddyRegion;\n timeout: number;\n ports?: BuddyPortInput[];\n apiUrl: string;\n}\n\nconst SETUP_HINT =\n 'Create a token with the SANDBOX_MANAGE scope at ' +\n 'https://app.buddy.works/my-id/tokens';\n\n/** The SDK's API host table is keyed by the same region names we use. */\nexport function apiUrlForRegion(region: BuddyRegion): string {\n return API_URLS[region];\n}\n\n/**\n * One resolved config per config object handed to `buddy()`. The provider\n * methods each receive the raw config, and resolving it to a stable object is\n * what lets the SDK client below be reused across calls — a fresh client per\n * call would give up Node's keep-alive connections between `create` and the\n * first command.\n */\nconst resolved = new WeakMap<BuddyConfig, ResolvedBuddyConfig>();\n/**\n * `buddy()` with no config reads the environment on every call, so a token\n * rotated in `process.env` is picked up; the result is cached by value so the\n * SDK client (and its connection pool) is still shared while nothing changed.\n */\nconst resolvedFromEnv = new Map<string, ResolvedBuddyConfig>();\n\nexport function resolveConfig(config?: BuddyConfig): ResolvedBuddyConfig {\n if (!config) {\n const key = [\n process.env.BUDDY_TOKEN, process.env.BUDDY_WORKSPACE, process.env.BUDDY_PROJECT,\n ].join('\\u0000');\n let value = resolvedFromEnv.get(key);\n if (!value) {\n value = buildConfig({});\n resolvedFromEnv.clear();\n resolvedFromEnv.set(key, value);\n }\n return value;\n }\n const cached = resolved.get(config);\n if (cached) return cached;\n const value = buildConfig(config);\n resolved.set(config, value);\n return value;\n}\n\nfunction buildConfig(config: BuddyConfig): ResolvedBuddyConfig {\n const token = config.token ?? process.env.BUDDY_TOKEN;\n const workspace = config.workspace ?? process.env.BUDDY_WORKSPACE;\n const project = config.project ?? process.env.BUDDY_PROJECT;\n\n if (!token) {\n throw new Error(\n 'Missing Buddy API token.\\n\\n' +\n `${SETUP_HINT}\\n` +\n 'Then pass it: buddy({ token: \"xxx\" })\\n' +\n 'Or set BUDDY_TOKEN in your environment.',\n );\n }\n if (!workspace) {\n throw new Error(\n 'Missing Buddy workspace domain.\\n\\n' +\n 'It is the workspace segment of your Buddy URL ' +\n '(https://app.buddy.works/<workspace>/...).\\n' +\n 'Pass it: buddy({ workspace: \"my-workspace\" }) or set BUDDY_WORKSPACE.',\n );\n }\n if (!project) {\n throw new Error(\n 'Missing Buddy project name.\\n\\n' +\n 'Sandboxes always belong to a project. Create one in the Buddy UI, then\\n' +\n 'pass it: buddy({ project: \"my-project\" }) or set BUDDY_PROJECT.',\n );\n }\n\n const region = config.region ?? DEFAULT_REGION;\n\n return {\n token,\n workspace,\n project,\n os: config.os ?? DEFAULT_OS,\n resources: config.resources,\n region,\n timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,\n ports: config.ports,\n apiUrl: (config.apiUrl ?? apiUrlForRegion(region)).replace(/\\/+$/, ''),\n };\n}\n\n/**\n * One SDK client per resolved config. Reusing it matters: creating a sandbox\n * and running the first command is several round trips, and a shared client\n * keeps Node's connection pool warm across them.\n */\nconst clients = new WeakMap<ResolvedBuddyConfig, BuddyApiClient>();\n\n/**\n * Per-request timeout for the SDK client. Its default is 30 s, which is too\n * short for `POST /commands`: Buddy holds that request until the sandbox has\n * booted, and a drained warm pool has been measured to take over 10 s. On a\n * timeout the SDK retries the POST, which would submit the command twice.\n */\nexport const CLIENT_REQUEST_TIMEOUT_MS = 120_000;\n\nexport function getClient(config: ResolvedBuddyConfig): BuddyApiClient {\n let client = clients.get(config);\n if (!client) {\n client = new BuddyApiClient({\n workspace: config.workspace,\n project_name: config.project,\n apiUrl: config.apiUrl,\n token: config.token,\n timeout: CLIENT_REQUEST_TIMEOUT_MS,\n });\n clients.set(config, client);\n }\n return client;\n}\n\n/**\n * HTTP status behind an SDK error. `BuddySDKError` carries `statusCode`; the\n * lower-level `HttpError` the raw client throws carries `status` and is not\n * exported, so both are read structurally.\n */\nexport function statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const candidate = error as { statusCode?: unknown; status?: unknown };\n const status = candidate.statusCode ?? candidate.status;\n return typeof status === 'number' && status > 0 ? status : undefined;\n}\n\nexport function messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isNotFound(error: unknown): boolean {\n const status = statusOf(error);\n if (status === 404) return true;\n // The content endpoints answer 400 \"Path not find in browser\" for a missing\n // path instead of 404, so the message has to be inspected as well.\n return status === 400 && /not (found|find)/i.test(messageOf(error));\n}\n\n/**\n * Buddy sandbox ids are fixed-length, so an id of any other shape never reaches\n * the handler and comes back as 400 \"Invalid url\" rather than 404. For a lookup\n * both answers mean the same thing: no such sandbox.\n */\nexport function isUnroutableId(error: unknown): boolean {\n return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));\n}\n\n/**\n * A sandbox that has not finished booting yet. Commands submitted to a\n * `STARTING` sandbox are queued by Buddy, but the `content/` and `download/`\n * endpoints reject outright with 400 \"Instance is not running\" — measured to\n * last up to ~8 s when the warm pool is drained. The synchronous `exec`\n * endpoint words the same state as 400 \"Sandbox must be running\".\n */\nexport function isInstanceNotRunning(error: unknown): boolean {\n return statusOf(error) === 400 && /instance is not running|sandbox must be running/i.test(messageOf(error));\n}\n\n/**\n * A sandbox with a lifecycle operation in flight. Buddy rejects configuration\n * changes, including opening a tunnel, until the boot or snapshot finishes.\n */\nexport function isOperationInProgress(error: unknown): boolean {\n return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));\n}\n\nexport function isAuthError(error: unknown): boolean {\n const status = statusOf(error);\n return status === 401 || status === 403;\n}\n\n/**\n * Resolves a caller-supplied path to an absolute one: relative paths are taken\n * from the sandbox home, `.` and `..` are resolved, and repeated slashes are\n * collapsed, so `/tmp/..` is rejected the same way `/` is.\n */\nexport function normalizeSandboxPath(path: string): string {\n const absolute = path.startsWith('/') ? path : `${SANDBOX_HOME}/${path}`;\n const segments: string[] = [];\n for (const segment of absolute.split('/')) {\n if (segment === '' || segment === '.') continue;\n if (segment === '..') segments.pop();\n else segments.push(segment);\n }\n if (segments.length === 0) {\n throw new Error('Path must not be empty or the filesystem root.');\n }\n return `/${segments.join('/')}`;\n}\n\n/**\n * The SDK takes content paths as a single URL segment it encodes itself, with\n * no leading slash — a leading slash produces an empty segment and a 400 from\n * the gateway.\n */\nexport function toContentPath(path: string): string {\n return normalizeSandboxPath(path).slice(1);\n}\n\nexport type SandboxStatus = 'running' | 'stopped' | 'error';\n\n/**\n * Buddy exposes more states than ComputeSDK. `STARTING` and `RESTORING` map to\n * `running` on purpose: the API queues commands submitted against a sandbox in\n * those states, so it is already usable.\n */\nexport function mapStatus(status: string | undefined): SandboxStatus {\n switch (status) {\n case 'RUNNING':\n case 'STARTING':\n case 'RESTORING':\n return 'running';\n case 'STOPPED':\n case 'STOPPING':\n return 'stopped';\n case 'FAILED':\n return 'error';\n default:\n return 'stopped';\n }\n}\n\n/**\n * Picks a resource preset from the cross-provider `cpu`/`memory` knobs.\n * Buddy only offers `N` vCPU with `2N` GB RAM, so whichever request is larger\n * wins and the result is clamped to the largest preset.\n */\nexport function resolveResources(\n options: Record<string, unknown> = {},\n fallback?: BuddyResources,\n): BuddyResources | undefined {\n if (typeof options.resources === 'string') return options.resources as BuddyResources;\n\n const requestedCpu = firstPositiveNumber([options.cpu, options.vcpus, options.cpus]);\n const requestedMemoryGb = memoryToGb(options);\n if (requestedCpu === undefined && requestedMemoryGb === undefined) return fallback;\n\n const cpuForMemory = requestedMemoryGb === undefined ? 0 : Math.ceil(requestedMemoryGb / 2);\n const cpu = Math.min(MAX_CPU, Math.max(1, requestedCpu ?? 0, cpuForMemory));\n return `${cpu}x${cpu * 2}` as BuddyResources;\n}\n\nfunction firstPositiveNumber(values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.ceil(value);\n }\n return undefined;\n}\n\n/** Memory knobs are unnormalized across providers — MB for some, MiB for others. */\nfunction memoryToGb(options: Record<string, unknown>): number | undefined {\n const mb = firstPositiveNumber([options.memory, options.memoryMb]);\n if (mb !== undefined) return mb / 1024;\n const mib = firstPositiveNumber([options.memoryMiB, options.memMiB]);\n if (mib !== undefined) return (mib * 1024 * 1024) / 1e9;\n return undefined;\n}\n\n/** Buddy identifiers allow alphanumerics, `_` and inner `-` only. */\nexport function toIdentifier(value: string): string {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9_-]+/g, '-');\n // Trim after truncating, or the cut can leave a hyphen in the last position.\n return cleaned.slice(0, 60).replace(/^-+|-+$/g, '') || 'computesdk';\n}\n\nexport function generateSandboxName(): string {\n return `computesdk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function normalizePort(input: BuddyPortInput, config: ResolvedBuddyConfig): Required<BuddyPort> {\n const port = typeof input === 'number' ? { port: input } : input;\n return {\n port: port.port,\n name: port.name ?? `p${port.port}`,\n type: port.type ?? 'HTTP',\n region: port.region ?? config.region,\n };\n}\n\n/** Buddy's tunnel object. `endpoint` holds the sandbox-side port as a string. */\nexport interface BuddyEndpoint {\n name?: string;\n endpoint?: string;\n type?: BuddyTunnelType;\n /** As reported by the API, which may know installations this provider does not offer. */\n region?: string;\n endpoint_url?: string;\n active?: boolean;\n whitelist?: string[];\n [key: string]: unknown;\n}\n\nexport function toEndpointPayload(port: Required<BuddyPort>): BuddyEndpoint {\n return {\n name: port.name,\n endpoint: String(port.port),\n type: port.type,\n region: port.region,\n };\n}\n\n/** Only HTTP and TLS tunnels get a public URL; TCP and SSH report host and port. */\nexport function endpointPublicUrl(endpoint: BuddyEndpoint): string | undefined {\n return endpoint.endpoint_url;\n}\n\nexport function endpointMatchesPort(endpoint: BuddyEndpoint, port: number): boolean {\n return Number(endpoint.endpoint) === port;\n}\n\n/** Fields Buddy reports but rejects when an endpoint is sent back in an update. */\nconst READ_ONLY_ENDPOINT_FIELDS = ['endpoint_url', 'active', 'target_latency'] as const;\n\n/**\n * Prepares an existing endpoint for the replace-all update. Everything\n * writable — `whitelist`, `timeout`, `http`, `tls` and whatever Buddy adds\n * later — has to survive, or opening a new port would reset those tunnels.\n */\nexport function toEndpointUpdate(endpoint: BuddyEndpoint): BuddyEndpoint {\n const update: BuddyEndpoint = { ...endpoint };\n for (const field of READ_ONLY_ENDPOINT_FIELDS) delete update[field];\n return update;\n}\n\n/** Swaps the scheme of a URL, for callers asking for `wss` on an HTTP tunnel. */\nexport function applyProtocol(url: string, protocol?: string): string {\n if (!protocol) return url;\n const normalized = protocol.replace(/:$/, '');\n return url.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, `${normalized}://`);\n}\n\n/**\n * What the provider passes between its own methods, and what `getInstance()`\n * hands back to callers. `client` and `fs` come straight from the SDK, so\n * consumers can drop down to it without building their own client.\n */\nexport interface BuddySandboxHandle {\n sandboxId: string;\n identifier: string;\n config: ResolvedBuddyConfig;\n client: BuddyApiClient;\n fs: FileSystem;\n createdAt: Date;\n /** True unless this process created the sandbox; Buddy reports no creation date. */\n createdAtIsReconnectTime: boolean;\n timeout: number;\n os?: string;\n resources?: string;\n /** Tunnels known so far. `getUrl` extends this when it opens a new one. */\n endpoints: BuddyEndpoint[];\n}\n\n/** Sandbox as the API returns it, narrowed to the fields the provider reads. */\nexport interface BuddySandboxData {\n id?: string;\n identifier?: string;\n name?: string;\n status?: string;\n setup_status?: string;\n os?: string;\n resources?: string;\n timeout?: number;\n endpoints?: BuddyEndpoint[];\n ssh_host?: string;\n ssh_port?: number;\n}\n\n/**\n * Buddy's sandbox resource carries no creation date (only projects and\n * snapshots do), and `SandboxInfo.createdAt` is a required `Date`, so a handle\n * rebuilt by `getById` or `list` can only record when it was reconnected.\n * `getInfo` marks that case with `metadata.createdAtIsReconnectTime`.\n */\nexport function toHandle(\n config: ResolvedBuddyConfig,\n sandbox: BuddySandboxData,\n createdAt = new Date(),\n createdAtIsReconnectTime = true,\n): BuddySandboxHandle {\n const sandboxId = sandbox.id;\n if (!sandboxId) {\n throw new Error('Buddy API returned a sandbox without an id.');\n }\n const client = getClient(config);\n\n return {\n sandboxId,\n identifier: sandbox.identifier ?? sandboxId,\n config,\n client,\n fs: new FileSystem(client, sandboxId),\n createdAt,\n createdAtIsReconnectTime,\n timeout: sandbox.timeout != null ? sandbox.timeout * 1000 : config.timeout,\n os: sandbox.os,\n resources: sandbox.resources,\n endpoints: sandbox.endpoints ?? [],\n };\n}\n\nexport async function getSandboxData(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n): Promise<BuddySandboxData> {\n return await getClient(config).getSandboxById({ path: { id: sandboxId } }) as BuddySandboxData;\n}\n\nexport async function sleep(ms: number): Promise<void> {\n await new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * The boot gate.\n *\n * `create` deliberately returns while the sandbox is still starting, because\n * Buddy queues commands submitted against a starting sandbox. Two other groups\n * of endpoints do not queue:\n *\n * - the content endpoints answer 400 \"Instance is not running\", or answer 2xx to\n * a write whose bytes never land (observed roughly once in twelve sandboxes);\n * - `updateSandbox` answers 400 \"Cannot update sandbox, operation in progress\".\n *\n * So those calls wait here for `RUNNING` + `setup_status: SUCCESS` once per\n * sandbox, and retry the two races until the deadline.\n */\n\nimport {\n getSandboxData,\n isInstanceNotRunning,\n isOperationInProgress,\n sleep,\n type BuddySandboxHandle,\n} from './utils.js';\n\n/** Long enough to cover a drained warm pool; a real boot failure surfaces sooner. */\nconst BOOT_WAIT_TIMEOUT_MS = 90_000;\nconst BOOT_WAIT_POLL_MS = 250;\n\n/** Sandboxes already known to have booted — the gate runs at most once each. */\nconst settled = new WeakSet<BuddySandboxHandle>();\n\nexport async function untilSettled(sandbox: BuddySandboxHandle): Promise<void> {\n if (settled.has(sandbox)) return;\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n if (data.status === 'RUNNING' && data.setup_status === 'SUCCESS') {\n settled.add(sandbox);\n return;\n }\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} failed to start ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} was still starting after ` +\n `${BOOT_WAIT_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(BOOT_WAIT_POLL_MS);\n }\n}\n\n/**\n * Runs an operation once the sandbox has booted, retrying the races that remain\n * afterwards — Buddy reports a snapshot or app operation still in flight the\n * same way.\n */\nexport async function whenBooted<T>(\n sandbox: BuddySandboxHandle,\n operation: () => Promise<T>,\n): Promise<T> {\n await untilSettled(sandbox);\n return retryBootRaces(operation, Date.now() + BOOT_WAIT_TIMEOUT_MS);\n}\n\n/**\n * Retries `operation` while Buddy reports the sandbox as not running or busy,\n * without first polling the sandbox for `RUNNING`. For an endpoint that\n * answers in one round trip the failed attempt *is* the readiness check, so a\n * warm sandbox costs no extra request.\n */\nexport async function retryBootRaces<T>(\n operation: () => Promise<T>,\n deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS,\n): Promise<T> {\n for (;;) {\n try {\n return await operation();\n } catch (error) {\n const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);\n if (!retryable || Date.now() >= deadline) throw error;\n // The caller may have given up at the deadline, so never start another\n // attempt past it.\n await sleep(Math.min(BOOT_WAIT_POLL_MS, deadline - Date.now()));\n if (Date.now() >= deadline) throw error;\n }\n }\n}\n","/**\n * Command execution.\n *\n * Buddy has two ways to run a command:\n *\n * - `POST .../exec` runs it synchronously and answers with stdout, stderr and\n * the exit code in one round trip. It keeps no history, cannot stream and\n * cannot be interrupted. After 60 s the server stops waiting and answers\n * 400 without output or exit code; the process itself keeps running.\n * - `POST .../commands` accepts the command and returns its id immediately;\n * output arrives over a JSONL log stream. The provider consumes that stream\n * once through the SDK's `Command` entity, splits it into stdout/stderr and\n * forwards chunks to the streaming callbacks, then reads the exit code from\n * the command details. `Command.wait()` is deliberately unused — it polls\n * once a second, which would add up to a second to every call.\n *\n * A foreground call without streaming callbacks and without a `timeout` takes\n * the first route (one request instead of three). Anything else — callbacks,\n * `background`, any `timeout` — takes the second, where a timeout can kill the\n * command by its id.\n */\n\nimport { Command, type SandboxCommandResultView } from '@buddy-works/sandbox-sdk';\nimport { escapeShellArg } from '@computesdk/provider';\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\n\nimport { retryBootRaces } from './boot.js';\nimport {\n messageOf,\n sleep,\n statusOf,\n type BuddyCommandRuntime,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport interface BuddyRunCommandOptions extends RunCommandOptions {\n /**\n * Interpreter Buddy runs the command with. Defaults to `BASH`; the other\n * runtimes take a script instead of a shell line, so `cwd` and `env` do not\n * apply to them.\n */\n runtime?: BuddyCommandRuntime;\n}\n\n/** What a POSIX shell accepts as a variable name. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Prepends `cd` and `export` when the caller asked for a cwd or env. Values are\n * escaped; names cannot be, so a name that is not a valid identifier is\n * rejected instead of being spliced into the shell line.\n */\nexport function buildShellCommand(command: string, options: RunCommandOptions = {}): string {\n let line = command;\n\n if (options.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([key, value]) => {\n if (!ENV_NAME.test(key)) {\n throw new TypeError(\n `Invalid environment variable name ${JSON.stringify(key)}: `\n + 'names must match /^[A-Za-z_][A-Za-z0-9_]*$/.',\n );\n }\n return `${key}=\"${escapeShellArg(String(value))}\"`;\n })\n .join(' ');\n line = `export ${exports} && ${line}`;\n }\n if (options.cwd) {\n line = `cd \"${escapeShellArg(options.cwd)}\" && ${line}`;\n }\n return line;\n}\n\n/** A termination that fails leaves the command running remotely, so retry. */\nconst KILL_ATTEMPTS = 3;\nconst KILL_RETRY_DELAY_MS = 500;\n\n/** Best-effort kill: never throws, gives up after `KILL_ATTEMPTS`. */\nexport async function killCommand(running: Pick<Command, 'kill'>): Promise<boolean> {\n for (let attempt = 1; attempt <= KILL_ATTEMPTS; attempt++) {\n try {\n await running.kill();\n return true;\n } catch {\n if (attempt < KILL_ATTEMPTS) await sleep(KILL_RETRY_DELAY_MS);\n }\n }\n return false;\n}\n\nexport async function runCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n options: BuddyRunCommandOptions = {},\n): Promise<CommandResult> {\n // `ADD-PROVIDER.md` still documents an older `runCommand(command, args)`\n // shape. Called that way, the array arrives here as `options`, where only\n // `cwd` and `env` are read — the arguments would be dropped silently and the\n // bare command would still exit 0. Fail loudly instead.\n if (Array.isArray(options)) {\n throw new TypeError(\n `runCommand takes a command line and an options object, not an argument array. `\n + `Pass the arguments inside the command, e.g. '${command} ${options.join(' ')}'.`,\n );\n }\n\n const startedAt = Date.now();\n const runtime = options.runtime ?? 'BASH';\n const payload = runtime === 'BASH' ? buildShellCommand(command, options) : command;\n\n const deadline = options.timeout ? startedAt + options.timeout : undefined;\n const timedOutResult = (stdout = '', stderr = '') => ({\n stdout, stderr, exitCode: TIMEOUT_EXIT_CODE, durationMs: Date.now() - startedAt,\n });\n\n if (usesExec(options)) {\n // The exec endpoint rejects a booting sandbox instead of queueing, so the\n // 400 is retried. Exec has no command id to kill, which is why only untimed\n // calls come here; when the server gives up at its own limit, the process\n // is left running.\n let result: SandboxCommandResultView;\n try {\n result = await retryBootRaces(() => execCommand(sandbox, payload, runtime));\n } catch (error) {\n if (isExecTimeout(error)) return timedOutResult('', `${messageOf(error)}\\n`);\n throw error;\n }\n if (typeof result.exit_code !== 'number') {\n throw new Error('Buddy ran the command but returned no exit code.');\n }\n return {\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n exitCode: result.exit_code,\n durationMs: Date.now() - startedAt,\n };\n }\n\n // Buddy may hold the submission while the sandbox boots (up to the client's\n // request timeout), so the deadline applies here too: when it passes first,\n // the timeout result is returned and the command is killed once (if ever)\n // Buddy reports it accepted.\n const submission = sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command: payload, runtime },\n });\n const commandResponse = deadline ? await raceDeadline(submission, deadline) : await submission;\n if (commandResponse === DEADLINE_PASSED) {\n void submission.then(\n response => {\n if (!response.id) return;\n void killCommand(new Command({\n commandResponse: response,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n }));\n },\n () => {},\n );\n return timedOutResult();\n }\n\n const commandId = commandResponse.id;\n if (!commandId) {\n throw new Error('Buddy accepted the command but returned no command id.');\n }\n\n const running = new Command({\n commandResponse,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n });\n\n // Fire-and-forget: return as soon as Buddy has the command queued.\n if (options.background) {\n return { stdout: '', stderr: '', exitCode: 0, durationMs: Date.now() - startedAt };\n }\n\n const stdout: string[] = [];\n const stderr: string[] = [];\n\n // `follow: true` holds the connection open until the command exits, so this\n // loop is the wait — nothing is polled. Each record is one line without its\n // terminator, so the newline goes back on here. Once the caller has been\n // given the timeout result the loop stops at the next record instead of\n // buffering output and firing callbacks for a result nobody will read.\n let timedOut = false;\n const drain = (async () => {\n for await (const log of running.logs({ follow: true })) {\n if (timedOut) break;\n if (log.data == null) continue;\n const chunk = `${log.data}\\n`;\n if (log.type === 'STDERR') {\n stderr.push(chunk);\n options.onStderr?.(chunk);\n } else {\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n }\n })();\n\n // The SDK stream cannot be aborted, so on timeout the result is returned\n // right away — with whatever output arrived before the deadline — and the\n // reader is left to finish on its own once the kill (best effort, retried)\n // closes it or the next record arrives.\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n void killCommand(running);\n drain.catch(() => {});\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n } catch (error) {\n // The stream broke mid-command. Buddy keeps running it, so stop it — best\n // effort and not awaited, so a hanging kill cannot delay the error.\n void killCommand(running);\n throw error;\n }\n\n // The stream can close before Buddy records the result, so the deadline\n // governs the exit-code poll as well: past it, the caller gets the timeout\n // result and the command is stopped in case it is still running.\n const exit = waitForExitCode(sandbox, commandId);\n const exitCode = deadline ? await raceDeadline(exit, deadline) : await exit;\n if (exitCode === DEADLINE_PASSED) {\n exit.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n\n return {\n stdout: stdout.join(''),\n stderr: stderr.join(''),\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/** The server gave up waiting for an `exec` command at its own limit. */\nexport function isExecTimeout(error: unknown): boolean {\n return statusOf(error) === 400 && /did not finish on instance .* within \\d+s/i.test(messageOf(error));\n}\n\n/**\n * Foreground, no streaming callbacks and no `timeout`. Callbacks force the log\n * stream because exec only has the output once the command has finished; a\n * timeout needs a command id to kill, which exec does not return.\n */\nexport function usesExec(options: BuddyRunCommandOptions): boolean {\n return !options.background && !options.onStdout && !options.onStderr && !options.timeout;\n}\n\n/**\n * `POST /workspaces/{workspace}/sandboxes/{id}/exec`. The SDK client waits\n * just past the server's own limit, so the server decides the outcome.\n */\nfunction execCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<SandboxCommandResultView> {\n return sandbox.client.execCommand({\n body: { command, runtime },\n path: { sandbox_id: sandbox.sandboxId },\n });\n}\n\nconst DEADLINE_PASSED = Symbol('deadline passed');\n\n/** Resolves to `DEADLINE_PASSED` if `deadline` (epoch ms) arrives first. */\nasync function raceDeadline<T>(work: Promise<T>, deadline: number): Promise<T | typeof DEADLINE_PASSED> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expiry = new Promise<typeof DEADLINE_PASSED>(resolve => {\n timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));\n });\n try {\n return await Promise.race([work, expiry]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The exit code `timeout(1)` uses for a killed command; reported for every timeout. */\nexport const TIMEOUT_EXIT_CODE = 124;\n\nconst EXIT_CODE_WAIT_MS = 5_000;\nconst EXIT_CODE_POLL_MS = 200;\n\nexport interface BuddyCommandDetails {\n exit_code?: number;\n status?: string;\n}\n\n/**\n * The log stream can close a moment before Buddy records the result, so the\n * details may still say `INPROGRESS` without an `exit_code`. Treating that as\n * success would hide failures; poll briefly until a terminal state shows up.\n */\nexport async function waitForExitCode(\n sandbox: Pick<BuddySandboxHandle, 'client' | 'sandboxId'>,\n commandId: string,\n deadlineMs = EXIT_CODE_WAIT_MS,\n): Promise<number> {\n const deadline = Date.now() + deadlineMs;\n for (;;) {\n const details: BuddyCommandDetails = await sandbox.client.getCommandDetails({\n path: { sandbox_id: sandbox.sandboxId, id: commandId },\n });\n if (typeof details.exit_code === 'number') return details.exit_code;\n if (details.status === 'FAILED') return 1;\n if (details.status === 'SUCCESSFUL') return 0;\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy command ${commandId} on sandbox ${sandbox.sandboxId} reported no exit code `\n + `within ${deadlineMs / 1000}s of its log stream closing (status: ${details.status ?? 'unknown'}).`,\n );\n }\n await new Promise(resolve => setTimeout(resolve, EXIT_CODE_POLL_MS));\n }\n}\n","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — one round trip per operation and binary-safe, unlike shelling out\n * to `cat`/`tee`.\n *\n * Every call goes through the boot gate in `boot.ts`, because unlike commands\n * these endpoints do not queue against a sandbox that is still starting.\n */\n\nimport type { FileEntry } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n toContentPath,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport async function readFile(sandbox: BuddySandboxHandle, path: string): Promise<string> {\n const target = normalizeSandboxPath(path);\n const buffer = await whenBooted(sandbox, () => sandbox.fs.downloadFile(target));\n return buffer.toString('utf-8');\n}\n\nexport async function writeFile(\n sandbox: BuddySandboxHandle,\n path: string,\n content: string,\n): Promise<void> {\n const target = normalizeSandboxPath(path);\n const parent = target.slice(0, target.lastIndexOf('/'));\n\n await whenBooted(sandbox, async () => {\n // Buddy will not create missing parents for an upload, and mirroring\n // `fs.writeFile` here is what callers expect.\n if (parent) {\n await sandbox.fs.createFolder(parent).catch(() => {});\n }\n await sandbox.fs.uploadFile(Buffer.from(content, 'utf-8'), target);\n });\n}\n\nexport async function mkdir(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n await whenBooted(sandbox, () => sandbox.fs.createFolder(target));\n}\n\nexport async function readdir(sandbox: BuddySandboxHandle, path: string): Promise<FileEntry[]> {\n const target = normalizeSandboxPath(path);\n const entries = await whenBooted(sandbox, () => sandbox.fs.listFiles(target));\n\n return entries.map(entry => ({\n name: entry.name ?? '',\n type: entry.type === 'DIR' ? 'directory' as const : 'file' as const,\n // The API reports sizes as bigint; ComputeSDK wants a number.\n ...(entry.size == null ? {} : { size: Number(entry.size) }),\n }));\n}\n\nexport async function exists(sandbox: BuddySandboxHandle, path: string): Promise<boolean> {\n const target = toContentPath(path);\n try {\n await whenBooted(sandbox, () =>\n sandbox.client.getSandboxContent({ path: { sandbox_id: sandbox.sandboxId, path: target } }));\n return true;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n}\n\nexport async function remove(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n try {\n await whenBooted(sandbox, () => sandbox.fs.deleteFile(target));\n } catch (error) {\n // Removing something that is already gone is not an error for callers.\n if (!isNotFound(error)) throw error;\n }\n}\n","/**\n * Snapshots — filesystem images of a sandbox that a new sandbox can boot from.\n *\n * Buddy creates them asynchronously: the create call returns `status: CREATING`\n * and the snapshot cannot be restored until it turns `CREATED`. The provider\n * waits for that here so callers get a snapshot they can actually use. The\n * wait uses a 500 ms poll rather than the SDK entity's 2 s one, because typical\n * snapshots settle in well under a second.\n */\n\nimport type { CreateSnapshotOptions, ListSnapshotsOptions } from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport {\n PROVIDER,\n getClient,\n isNotFound,\n sleep,\n toIdentifier,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\nconst SNAPSHOT_WAIT_TIMEOUT_MS = 180_000;\nconst SNAPSHOT_WAIT_POLL_MS = 500;\n\ninterface BuddySnapshotData {\n id?: string;\n name?: string;\n size?: number;\n status?: string;\n create_date?: Date | string;\n}\n\nfunction toSnapshot(data: BuddySnapshotData, sandboxId?: string): Snapshot {\n if (!data.id) {\n throw new Error('Buddy API returned a snapshot without an id.');\n }\n return {\n id: data.id,\n provider: PROVIDER,\n createdAt: data.create_date ? new Date(data.create_date) : new Date(),\n metadata: {\n name: data.name,\n status: data.status,\n sizeGb: data.size,\n ...(sandboxId ? { sandboxId } : {}),\n },\n };\n}\n\nexport async function createSnapshot(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n options: CreateSnapshotOptions = {},\n): Promise<Snapshot> {\n const client = getClient(config);\n const created = await client.addSandboxSnapshot({\n path: { sandbox_id: sandboxId },\n body: { name: toIdentifier(options.name ?? `computesdk-${Date.now()}`) },\n });\n\n const snapshotId = created.id;\n if (!snapshotId) {\n throw new Error('Buddy accepted the snapshot but returned no snapshot id.');\n }\n\n const ready = await waitUntilCreated(config, sandboxId, snapshotId, created);\n return toSnapshot(ready, sandboxId);\n}\n\nasync function waitUntilCreated(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n snapshotId: string,\n initial: BuddySnapshotData,\n): Promise<BuddySnapshotData> {\n if (initial.status === 'CREATED') return initial;\n\n const client = getClient(config);\n const deadline = Date.now() + SNAPSHOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await client.getSandboxSnapshot({\n path: { sandbox_id: sandboxId, id: snapshotId },\n }) as BuddySnapshotData;\n\n if (data.status === 'CREATED') return data;\n if (data.status === 'FAILED') {\n throw new Error(`Buddy snapshot ${snapshotId} failed to be created.`);\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy snapshot ${snapshotId} was still ${data.status} after ` +\n `${SNAPSHOT_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(SNAPSHOT_WAIT_POLL_MS);\n }\n}\n\nexport async function listSnapshots(\n config: ResolvedBuddyConfig,\n options: ListSnapshotsOptions = {},\n): Promise<Snapshot[]> {\n const client = getClient(config);\n // Default to the project-wide listing: snapshots outlive the sandbox they were\n // taken from, so the per-sandbox endpoint would hide most of them.\n const response = options.sandboxId\n ? await client.getSandboxSnapshots({ path: { sandbox_id: options.sandboxId } })\n : await client.getProjectSnapshots({});\n\n const snapshots = (response.snapshots ?? [])\n .map(snapshot => toSnapshot(snapshot as BuddySnapshotData, options.sandboxId));\n return options.limit ? snapshots.slice(0, options.limit) : snapshots;\n}\n\nexport async function deleteSnapshot(\n config: ResolvedBuddyConfig,\n snapshotId: string,\n): Promise<void> {\n try {\n await getClient(config).deleteSnapshot({ path: { id: snapshotId } });\n } catch (error) {\n // Deleting an already-deleted snapshot is the state the caller wanted.\n if (!isNotFound(error)) throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,IAAAA,mBAA+B;;;ACH/B,yBAAqD;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,iBAA8B;AAEpC,IAAM,qBAAqB;AAE3B,IAAM,eAAe;AAsBrB,IAAM,UAAU;AAmDvB,IAAM,aACJ;AAIK,SAAS,gBAAgB,QAA6B;AAC3D,SAAO,4BAAS,MAAM;AACxB;AASA,IAAM,WAAW,oBAAI,QAA0C;AAM/D,IAAM,kBAAkB,oBAAI,IAAiC;AAEtD,SAAS,cAAc,QAA2C;AACvE,MAAI,CAAC,QAAQ;AACX,UAAM,MAAM;AAAA,MACV,QAAQ,IAAI;AAAA,MAAa,QAAQ,IAAI;AAAA,MAAiB,QAAQ,IAA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AAiC,IAAI,eAAe,QAAQ,SAAS,uCAC/B,sBAAsB,GAAI;AAAA,MAClE;AAAA,IACF;AACA,UAAM,MAAM,gBAAgB;AAAA,EAC9B;AACF;AAEA,eAAe,gBACb,SACA,MAC6B;AAC7B,QAAM,OAAO,MAAM,eAAe,QAAQ,QAAQ,QAAQ,SAAS;AACnE,UAAQ,YAAY,KAAK,aAAa,CAAC;AACvC,QAAM,QAAQ,QAAQ,UAAU,KAAK,cAAY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["import_provider","value","import_sandbox_sdk","exports","stdout","stderr","resolved"]}
|
package/dist/index.mjs
CHANGED
|
@@ -106,7 +106,7 @@ function isUnroutableId(error) {
|
|
|
106
106
|
return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));
|
|
107
107
|
}
|
|
108
108
|
function isInstanceNotRunning(error) {
|
|
109
|
-
return statusOf(error) === 400 && /instance is not running/i.test(messageOf(error));
|
|
109
|
+
return statusOf(error) === 400 && /instance is not running|sandbox must be running/i.test(messageOf(error));
|
|
110
110
|
}
|
|
111
111
|
function isOperationInProgress(error) {
|
|
112
112
|
return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));
|
|
@@ -260,14 +260,17 @@ async function untilSettled(sandbox) {
|
|
|
260
260
|
}
|
|
261
261
|
async function whenBooted(sandbox, operation) {
|
|
262
262
|
await untilSettled(sandbox);
|
|
263
|
-
|
|
263
|
+
return retryBootRaces(operation, Date.now() + BOOT_WAIT_TIMEOUT_MS);
|
|
264
|
+
}
|
|
265
|
+
async function retryBootRaces(operation, deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS) {
|
|
264
266
|
for (; ; ) {
|
|
265
267
|
try {
|
|
266
268
|
return await operation();
|
|
267
269
|
} catch (error) {
|
|
268
270
|
const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);
|
|
269
271
|
if (!retryable || Date.now() >= deadline) throw error;
|
|
270
|
-
await sleep(BOOT_WAIT_POLL_MS);
|
|
272
|
+
await sleep(Math.min(BOOT_WAIT_POLL_MS, deadline - Date.now()));
|
|
273
|
+
if (Date.now() >= deadline) throw error;
|
|
271
274
|
}
|
|
272
275
|
}
|
|
273
276
|
}
|
|
@@ -323,6 +326,25 @@ async function runCommand(sandbox, command, options = {}) {
|
|
|
323
326
|
exitCode: TIMEOUT_EXIT_CODE,
|
|
324
327
|
durationMs: Date.now() - startedAt
|
|
325
328
|
});
|
|
329
|
+
if (usesExec(options)) {
|
|
330
|
+
let result;
|
|
331
|
+
try {
|
|
332
|
+
result = await retryBootRaces(() => execCommand(sandbox, payload, runtime));
|
|
333
|
+
} catch (error) {
|
|
334
|
+
if (isExecTimeout(error)) return timedOutResult("", `${messageOf(error)}
|
|
335
|
+
`);
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
if (typeof result.exit_code !== "number") {
|
|
339
|
+
throw new Error("Buddy ran the command but returned no exit code.");
|
|
340
|
+
}
|
|
341
|
+
return {
|
|
342
|
+
stdout: result.stdout ?? "",
|
|
343
|
+
stderr: result.stderr ?? "",
|
|
344
|
+
exitCode: result.exit_code,
|
|
345
|
+
durationMs: Date.now() - startedAt
|
|
346
|
+
};
|
|
347
|
+
}
|
|
326
348
|
const submission = sandbox.client.executeCommand({
|
|
327
349
|
path: { sandbox_id: sandbox.sandboxId },
|
|
328
350
|
body: { command: payload, runtime }
|
|
@@ -386,13 +408,33 @@ async function runCommand(sandbox, command, options = {}) {
|
|
|
386
408
|
void killCommand(running);
|
|
387
409
|
throw error;
|
|
388
410
|
}
|
|
411
|
+
const exit = waitForExitCode(sandbox, commandId);
|
|
412
|
+
const exitCode = deadline ? await raceDeadline(exit, deadline) : await exit;
|
|
413
|
+
if (exitCode === DEADLINE_PASSED) {
|
|
414
|
+
exit.catch(() => {
|
|
415
|
+
});
|
|
416
|
+
void killCommand(running);
|
|
417
|
+
return timedOutResult(stdout.join(""), stderr.join(""));
|
|
418
|
+
}
|
|
389
419
|
return {
|
|
390
420
|
stdout: stdout.join(""),
|
|
391
421
|
stderr: stderr.join(""),
|
|
392
|
-
exitCode
|
|
422
|
+
exitCode,
|
|
393
423
|
durationMs: Date.now() - startedAt
|
|
394
424
|
};
|
|
395
425
|
}
|
|
426
|
+
function isExecTimeout(error) {
|
|
427
|
+
return statusOf(error) === 400 && /did not finish on instance .* within \d+s/i.test(messageOf(error));
|
|
428
|
+
}
|
|
429
|
+
function usesExec(options) {
|
|
430
|
+
return !options.background && !options.onStdout && !options.onStderr && !options.timeout;
|
|
431
|
+
}
|
|
432
|
+
function execCommand(sandbox, command, runtime) {
|
|
433
|
+
return sandbox.client.execCommand({
|
|
434
|
+
body: { command, runtime },
|
|
435
|
+
path: { sandbox_id: sandbox.sandboxId }
|
|
436
|
+
});
|
|
437
|
+
}
|
|
396
438
|
var DEADLINE_PASSED = /* @__PURE__ */ Symbol("deadline passed");
|
|
397
439
|
async function raceDeadline(work, deadline) {
|
|
398
440
|
let timer;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/boot.ts","../src/commands.ts","../src/filesystem.ts","../src/snapshots.ts"],"sourcesContent":["/**\n * Buddy provider for ComputeSDK.\n *\n * Buddy serves Ubuntu sandboxes from a pre-warmed pool, so `create` returns a\n * sandbox that is already booting and commands submitted to it are queued until\n * it is up. The provider does not wait for `RUNNING` on create — that keeps\n * time-to-first-command at the warm-pool latency instead of a poll interval.\n *\n * Snapshots are Buddy's only reusable image, so `compute.template.*` is mapped\n * onto them.\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateSandboxOptions,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n SandboxInfo,\n} from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport type { BuddyApiClient } from '@buddy-works/sandbox-sdk';\nimport { whenBooted } from './boot.js';\nimport { runCommand, type BuddyRunCommandOptions } from './commands.js';\nimport * as fs from './filesystem.js';\nimport { createSnapshot, deleteSnapshot, listSnapshots } from './snapshots.js';\nimport {\n PROVIDER,\n applyProtocol,\n endpointMatchesPort,\n endpointPublicUrl,\n generateSandboxName,\n getClient,\n getSandboxData,\n isNotFound,\n isUnroutableId,\n mapStatus,\n normalizePort,\n resolveConfig,\n resolveResources,\n sleep,\n statusOf,\n toEndpointPayload,\n toEndpointUpdate,\n toHandle,\n toIdentifier,\n type BuddyConfig,\n type BuddyEndpoint,\n type BuddyPortInput,\n type BuddySandboxHandle,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\n/** Deleting a just-created sandbox occasionally answers 5xx while succeeding. */\nconst DESTROY_ATTEMPTS = 3;\nconst DESTROY_RETRY_DELAY_MS = 500;\n\n/** A tunnel is registered instantly but takes a moment to get its public URL. */\nconst URL_WAIT_TIMEOUT_MS = 15_000;\nconst URL_WAIT_POLL_MS = 250;\n\n/**\n * Deletes a sandbox, retrying transient server failures. \"Already gone\" is the\n * state the caller asked for, so it counts as success.\n */\nexport async function deleteSandbox(client: BuddyApiClient, sandboxId: string): Promise<void> {\n for (let attempt = 1; attempt <= DESTROY_ATTEMPTS; attempt++) {\n try {\n await client.deleteSandboxById({ path: { id: sandboxId } });\n return;\n } catch (error) {\n if (isNotFound(error)) return;\n const status = statusOf(error);\n const retryable = status !== undefined && status >= 500;\n if (!retryable || attempt === DESTROY_ATTEMPTS) throw error;\n await sleep(DESTROY_RETRY_DELAY_MS);\n }\n }\n}\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n methods: {\n sandbox: {\n create: async (config: BuddyConfig, options?: CreateSandboxOptions) => {\n const resolved = resolveConfig(config);\n const created = await getClient(resolved).addSandbox({\n body: buildCreateBody(resolved, options),\n });\n\n const sandbox = toHandle(resolved, created, new Date(), false);\n try {\n await ensureTimeout(sandbox, options?.timeout ?? resolved.timeout);\n } catch (error) {\n // The framework has no id yet, so nothing else could clean this up.\n await deleteSandbox(sandbox.client, sandbox.sandboxId).catch(() => {});\n throw error;\n }\n return { sandbox, sandboxId: sandbox.sandboxId };\n },\n\n getById: async (config: BuddyConfig, sandboxId: string) => {\n const resolved = resolveConfig(config);\n try {\n const data = await getSandboxData(resolved, sandboxId);\n const sandbox = toHandle(resolved, data);\n return { sandbox, sandboxId: sandbox.sandboxId };\n } catch (error) {\n if (isNotFound(error) || isUnroutableId(error)) return null;\n throw error;\n }\n },\n\n list: async (config: BuddyConfig) => {\n const resolved = resolveConfig(config);\n const response = await getClient(resolved).getSandboxes({});\n\n // The listing carries ids only; details are fetched on demand by\n // getInfo, so listing a hundred sandboxes stays a single request.\n return (response.sandboxes ?? [])\n .filter(entry => Boolean(entry.id))\n .map(entry => {\n const sandbox = toHandle(resolved, entry);\n return { sandbox, sandboxId: sandbox.sandboxId };\n });\n },\n\n destroy: async (config: BuddyConfig, sandboxId: string) =>\n deleteSandbox(getClient(resolveConfig(config)), sandboxId),\n\n runCommand: async (\n sandbox: BuddySandboxHandle,\n command: string,\n options?: BuddyRunCommandOptions,\n ) => runCommand(sandbox, command, options),\n\n // `runCommand` already forwards `onStdout`/`onStderr` from Buddy's own\n // log stream. Without this the factory would ignore that and bootstrap\n // its Node-based streaming daemon inside the sandbox instead.\n streamCommand: runCommand,\n\n getInfo: async (sandbox: BuddySandboxHandle): Promise<SandboxInfo> => {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? sandbox.endpoints;\n\n return {\n id: sandbox.sandboxId,\n provider: PROVIDER,\n status: mapStatus(data.status),\n createdAt: sandbox.createdAt,\n timeout: data.timeout != null ? data.timeout * 1000 : sandbox.timeout,\n metadata: {\n createdAtIsReconnectTime: sandbox.createdAtIsReconnectTime,\n identifier: data.identifier ?? sandbox.identifier,\n name: data.name,\n os: data.os,\n resources: data.resources,\n buddyStatus: data.status,\n setupStatus: data.setup_status,\n workspace: sandbox.config.workspace,\n project: sandbox.config.project,\n region: sandbox.config.region,\n endpoints: (data.endpoints ?? []).map(endpoint => ({\n name: endpoint.name,\n port: Number(endpoint.endpoint),\n type: endpoint.type,\n url: endpointPublicUrl(endpoint),\n })),\n },\n };\n },\n\n getUrl: async (sandbox: BuddySandboxHandle, options: { port: number; protocol?: string }) =>\n getUrl(sandbox, options),\n\n getInstance: (sandbox: BuddySandboxHandle) => sandbox,\n\n filesystem: {\n readFile: (sandbox: BuddySandboxHandle, path: string) => fs.readFile(sandbox, path),\n writeFile: (sandbox: BuddySandboxHandle, path: string, content: string) =>\n fs.writeFile(sandbox, path, content),\n mkdir: (sandbox: BuddySandboxHandle, path: string) => fs.mkdir(sandbox, path),\n readdir: (sandbox: BuddySandboxHandle, path: string) => fs.readdir(sandbox, path),\n exists: (sandbox: BuddySandboxHandle, path: string) => fs.exists(sandbox, path),\n remove: (sandbox: BuddySandboxHandle, path: string) => fs.remove(sandbox, path),\n },\n },\n\n snapshot: {\n create: (config: BuddyConfig, sandboxId: string, options?: { name?: string }) =>\n createSnapshot(resolveConfig(config), sandboxId, options),\n list: (config: BuddyConfig, options?: ListSnapshotsOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, snapshotId: string) =>\n deleteSnapshot(resolveConfig(config), snapshotId),\n },\n\n /**\n * Buddy has no separate template entity — a snapshot is the reusable image,\n * and `create({ templateId })` boots from one. So listing and deleting\n * templates operate on snapshots, and creating one points the caller at\n * `compute.snapshot.create`, which is where an image comes from.\n */\n template: {\n create: async () => {\n throw new Error(\n 'Buddy does not have templates as a separate entity. Snapshot a ' +\n 'configured sandbox instead: const snapshot = await compute.snapshot.create(sandboxId), ' +\n 'then boot from it with compute.sandbox.create({ snapshotId: snapshot.id }).',\n );\n },\n list: (config: BuddyConfig, options?: ListTemplatesOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, templateId: string) =>\n deleteSnapshot(resolveConfig(config), templateId),\n },\n },\n});\n\n/** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */\nexport function toSeconds(ms: number): number {\n return Math.max(1, Math.ceil(ms / 1000));\n}\n\nfunction buildCreateBody(config: ResolvedBuddyConfig, options: CreateSandboxOptions = {}) {\n const name = options.name ?? generateSandboxName();\n const timeoutMs = options.timeout ?? config.timeout;\n // `templateId` is accepted alongside `snapshotId` because Buddy's template\n // methods are backed by snapshots — both carry a snapshot id.\n const snapshotId = options.snapshotId ?? options.templateId;\n\n const body: Record<string, unknown> = {\n name,\n identifier: toIdentifier(name),\n os: options.image ?? config.os,\n timeout: toSeconds(timeoutMs),\n };\n\n const resources = resolveResources(options, config.resources);\n if (resources) body.resources = resources;\n\n // Buddy-specific create options, passed through as they are named in the API.\n if (options.firstBootCommands) body.first_boot_commands = options.firstBootCommands;\n if (options.appDir) body.app_dir = options.appDir;\n if (options.tags) body.tags = options.tags;\n\n const ports = options.ports ?? config.ports;\n if (ports?.length) {\n body.endpoints = ports.map((port: BuddyPortInput) =>\n toEndpointPayload(normalizePort(port, config)));\n }\n if (options.envs && Object.keys(options.envs).length > 0) {\n body.variables = Object.entries(options.envs).map(([key, value]) => ({ key, value }));\n }\n if (snapshotId) body.snapshot_id = snapshotId;\n\n return body as any;\n}\n\n/**\n * Buddy's create-from-snapshot request has no `timeout` field (the SDK schema\n * strips it), so a sandbox booted from a snapshot comes back with whatever the\n * snapshot carried. Patch it afterwards when it differs from what was asked.\n */\nexport async function ensureTimeout(\n sandbox: BuddySandboxHandle,\n timeoutMs: number,\n): Promise<void> {\n const seconds = toSeconds(timeoutMs);\n if (toSeconds(sandbox.timeout) === seconds) return;\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { timeout: seconds } as any,\n }));\n sandbox.timeout = updated.timeout != null ? updated.timeout * 1000 : seconds * 1000;\n}\n\n/**\n * Endpoint updates in flight, per remote sandbox. Buddy replaces the whole\n * endpoint list on update, so two concurrent `getUrl` calls built from the same\n * list would each drop the other's port — they run one after another instead.\n * Keyed by installation + sandbox id rather than by handle: `getById` and\n * `list` hand out a fresh handle each time for the same remote sandbox.\n */\nconst endpointUpdates = new Map<string, Promise<unknown>>();\n\nfunction endpointUpdateKey(sandbox: BuddySandboxHandle): string {\n return `${sandbox.config.apiUrl}|${sandbox.config.workspace}|${sandbox.sandboxId}`;\n}\n\nfunction getUrl(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const key = endpointUpdateKey(sandbox);\n const previous = endpointUpdates.get(key) ?? Promise.resolve();\n const next = previous.catch(() => {}).then(() => openPort(sandbox, options));\n endpointUpdates.set(key, next);\n // Drop the entry once nothing newer is queued behind it, so the map only\n // ever holds sandboxes with an update actually in flight.\n next.catch(() => {}).finally(() => {\n if (endpointUpdates.get(key) === next) endpointUpdates.delete(key);\n });\n return next;\n}\n\nasync function openPort(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const { port, protocol } = options;\n const existing = await findEndpointUrl(sandbox, port);\n if (existing) return applyProtocol(existing, protocol);\n\n const desired = normalizePort({ port }, sandbox.config);\n // Buddy replaces the whole endpoint list on update, so previously opened\n // tunnels have to be sent back or they would be torn down here.\n const kept = sandbox.endpoints\n .filter(endpoint => !endpointMatchesPort(endpoint, port))\n .map(toEndpointUpdate);\n\n // Buddy refuses configuration changes while the sandbox is still starting.\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { endpoints: [...kept, toEndpointPayload(desired)] } as any,\n }));\n sandbox.endpoints = (updated.endpoints ?? sandbox.endpoints) as BuddyEndpoint[];\n\n const deadline = Date.now() + URL_WAIT_TIMEOUT_MS;\n for (;;) {\n const url = await findEndpointUrl(sandbox, port);\n if (url) return applyProtocol(url, protocol);\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy opened a tunnel to port ${port} on sandbox ${sandbox.sandboxId} ` +\n `but published no public URL within ${URL_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(URL_WAIT_POLL_MS);\n }\n}\n\nasync function findEndpointUrl(\n sandbox: BuddySandboxHandle,\n port: number,\n): Promise<string | undefined> {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? [];\n const match = sandbox.endpoints.find(endpoint => endpointMatchesPort(endpoint, port));\n return match ? endpointPublicUrl(match) : undefined;\n}\n\nexport type { BuddyConfig, BuddySandboxHandle as BuddySandbox } from './utils.js';\nexport type { BuddyRunCommandOptions } from './commands.js';\n","/**\n * Shared types, config resolution and SDK plumbing for the Buddy provider.\n *\n * All API access goes through `@buddy-works/sandbox-sdk`. The provider uses the\n * SDK's `BuddyApiClient` rather than its high-level `Sandbox` façade for sandbox\n * creation: `Sandbox.create()` waits for `setup_status: SUCCESS` and\n * `status: RUNNING` with a 1 s poll, and since a sandbox from Buddy's warm pool\n * is usable in ~400 ms that wait would dominate time-to-first-command. The\n * façade's `Command`, `FileSystem` and snapshot helpers are used as-is.\n */\n\nimport { API_URLS, BuddyApiClient, FileSystem } from '@buddy-works/sandbox-sdk';\n\nexport const PROVIDER = 'buddy' as const;\nexport const DEFAULT_OS = 'ubuntu:24.04';\nexport const DEFAULT_REGION: BuddyRegion = 'US';\n/** Buddy stops a sandbox after this many ms of life unless overridden. */\nexport const DEFAULT_TIMEOUT_MS = 3_600_000;\n/** Working directory of the default `buddy` user — relative paths resolve here. */\nexport const SANDBOX_HOME = '/buddy';\n\n/**\n * Buddy installation, in the spelling its tunnel API uses. Each installation is\n * a separate deployment with its own API host, workspaces and tokens — `US` is\n * not a placement hint within one API.\n */\nexport type BuddyRegion = 'US' | 'EU';\n\n/** Interpreter Buddy runs a command with. `BASH` is the default. */\nexport type BuddyCommandRuntime = 'BASH' | 'JAVASCRIPT' | 'TYPESCRIPT' | 'PYTHON';\n\n/** Tunnel protocol. Only `HTTP` yields a public `endpoint_url`. */\nexport type BuddyTunnelType = 'HTTP' | 'TLS' | 'TCP' | 'SSH';\n\n/**\n * Buddy resource preset, `\"{vCPU}x{RAM in GB}\"`. RAM is always 2 GB per vCPU.\n */\nexport type BuddyResources =\n | '1x2' | '2x4' | '3x6' | '4x8' | '5x10' | '6x12'\n | '7x14' | '8x16' | '9x18' | '10x20' | '11x22' | '12x24';\n\nexport const MAX_CPU = 12;\n\n/** A port to expose publicly. A bare number means `{ port, type: 'HTTP' }`. */\nexport interface BuddyPort {\n port: number;\n /** Tunnel name. Becomes the first label of the public hostname. */\n name?: string;\n type?: BuddyTunnelType;\n region?: BuddyRegion;\n}\n\nexport type BuddyPortInput = number | BuddyPort;\n\nexport interface BuddyConfig {\n /** API token with the `SANDBOX_MANAGE` scope. Falls back to `BUDDY_TOKEN`. */\n token?: string;\n /** Workspace domain. Falls back to `BUDDY_WORKSPACE`. */\n workspace?: string;\n /** Project the sandboxes belong to. Falls back to `BUDDY_PROJECT`. */\n project?: string;\n /** Base OS image — `'ubuntu:24.04'` (default) or `'ubuntu:22.04'`. */\n os?: string;\n /** Resource preset. Buddy's own default applies when omitted. */\n resources?: BuddyResources;\n /**\n * Buddy installation to use. Selects both the API host and where tunnels\n * terminate. Defaults to `'US'`. A token is only valid on its own\n * installation.\n */\n region?: BuddyRegion;\n /** Sandbox lifetime in milliseconds, after which Buddy stops it. */\n timeout?: number;\n /** Ports to expose on every sandbox this provider creates. */\n ports?: BuddyPortInput[];\n /** API base URL. Overrides `region` — set it for on-premise installations. */\n apiUrl?: string;\n}\n\n/** Config after env-var fallbacks and validation — what the methods receive. */\nexport interface ResolvedBuddyConfig {\n token: string;\n workspace: string;\n project: string;\n os: string;\n resources?: BuddyResources;\n region: BuddyRegion;\n timeout: number;\n ports?: BuddyPortInput[];\n apiUrl: string;\n}\n\nconst SETUP_HINT =\n 'Create a token with the SANDBOX_MANAGE scope at ' +\n 'https://app.buddy.works/my-id/tokens';\n\n/** The SDK's API host table is keyed by the same region names we use. */\nexport function apiUrlForRegion(region: BuddyRegion): string {\n return API_URLS[region];\n}\n\n/**\n * One resolved config per config object handed to `buddy()`. The provider\n * methods each receive the raw config, and resolving it to a stable object is\n * what lets the SDK client below be reused across calls — a fresh client per\n * call would give up Node's keep-alive connections between `create` and the\n * first command.\n */\nconst resolved = new WeakMap<BuddyConfig, ResolvedBuddyConfig>();\n/**\n * `buddy()` with no config reads the environment on every call, so a token\n * rotated in `process.env` is picked up; the result is cached by value so the\n * SDK client (and its connection pool) is still shared while nothing changed.\n */\nconst resolvedFromEnv = new Map<string, ResolvedBuddyConfig>();\n\nexport function resolveConfig(config?: BuddyConfig): ResolvedBuddyConfig {\n if (!config) {\n const key = [\n process.env.BUDDY_TOKEN, process.env.BUDDY_WORKSPACE, process.env.BUDDY_PROJECT,\n ].join('\\u0000');\n let value = resolvedFromEnv.get(key);\n if (!value) {\n value = buildConfig({});\n resolvedFromEnv.clear();\n resolvedFromEnv.set(key, value);\n }\n return value;\n }\n const cached = resolved.get(config);\n if (cached) return cached;\n const value = buildConfig(config);\n resolved.set(config, value);\n return value;\n}\n\nfunction buildConfig(config: BuddyConfig): ResolvedBuddyConfig {\n const token = config.token ?? process.env.BUDDY_TOKEN;\n const workspace = config.workspace ?? process.env.BUDDY_WORKSPACE;\n const project = config.project ?? process.env.BUDDY_PROJECT;\n\n if (!token) {\n throw new Error(\n 'Missing Buddy API token.\\n\\n' +\n `${SETUP_HINT}\\n` +\n 'Then pass it: buddy({ token: \"xxx\" })\\n' +\n 'Or set BUDDY_TOKEN in your environment.',\n );\n }\n if (!workspace) {\n throw new Error(\n 'Missing Buddy workspace domain.\\n\\n' +\n 'It is the workspace segment of your Buddy URL ' +\n '(https://app.buddy.works/<workspace>/...).\\n' +\n 'Pass it: buddy({ workspace: \"my-workspace\" }) or set BUDDY_WORKSPACE.',\n );\n }\n if (!project) {\n throw new Error(\n 'Missing Buddy project name.\\n\\n' +\n 'Sandboxes always belong to a project. Create one in the Buddy UI, then\\n' +\n 'pass it: buddy({ project: \"my-project\" }) or set BUDDY_PROJECT.',\n );\n }\n\n const region = config.region ?? DEFAULT_REGION;\n\n return {\n token,\n workspace,\n project,\n os: config.os ?? DEFAULT_OS,\n resources: config.resources,\n region,\n timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,\n ports: config.ports,\n apiUrl: (config.apiUrl ?? apiUrlForRegion(region)).replace(/\\/+$/, ''),\n };\n}\n\n/**\n * One SDK client per resolved config. Reusing it matters: creating a sandbox\n * and running the first command is several round trips, and a shared client\n * keeps Node's connection pool warm across them.\n */\nconst clients = new WeakMap<ResolvedBuddyConfig, BuddyApiClient>();\n\n/**\n * Per-request timeout for the SDK client. Its default is 30 s, which is too\n * short for `POST /commands`: Buddy holds that request until the sandbox has\n * booted, and a drained warm pool has been measured to take over 10 s. On a\n * timeout the SDK retries the POST, which would submit the command twice.\n */\nexport const CLIENT_REQUEST_TIMEOUT_MS = 120_000;\n\nexport function getClient(config: ResolvedBuddyConfig): BuddyApiClient {\n let client = clients.get(config);\n if (!client) {\n client = new BuddyApiClient({\n workspace: config.workspace,\n project_name: config.project,\n apiUrl: config.apiUrl,\n token: config.token,\n timeout: CLIENT_REQUEST_TIMEOUT_MS,\n });\n clients.set(config, client);\n }\n return client;\n}\n\n/**\n * HTTP status behind an SDK error. `BuddySDKError` carries `statusCode`; the\n * lower-level `HttpError` the raw client throws carries `status` and is not\n * exported, so both are read structurally.\n */\nexport function statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const candidate = error as { statusCode?: unknown; status?: unknown };\n const status = candidate.statusCode ?? candidate.status;\n return typeof status === 'number' && status > 0 ? status : undefined;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isNotFound(error: unknown): boolean {\n const status = statusOf(error);\n if (status === 404) return true;\n // The content endpoints answer 400 \"Path not find in browser\" for a missing\n // path instead of 404, so the message has to be inspected as well.\n return status === 400 && /not (found|find)/i.test(messageOf(error));\n}\n\n/**\n * Buddy sandbox ids are fixed-length, so an id of any other shape never reaches\n * the handler and comes back as 400 \"Invalid url\" rather than 404. For a lookup\n * both answers mean the same thing: no such sandbox.\n */\nexport function isUnroutableId(error: unknown): boolean {\n return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));\n}\n\n/**\n * A sandbox that has not finished booting yet. Commands submitted to a\n * `STARTING` sandbox are queued by Buddy, but the `content/` and `download/`\n * endpoints reject outright with 400 \"Instance is not running\" — measured to\n * last up to ~8 s when the warm pool is drained.\n */\nexport function isInstanceNotRunning(error: unknown): boolean {\n return statusOf(error) === 400 && /instance is not running/i.test(messageOf(error));\n}\n\n/**\n * A sandbox with a lifecycle operation in flight. Buddy rejects configuration\n * changes, including opening a tunnel, until the boot or snapshot finishes.\n */\nexport function isOperationInProgress(error: unknown): boolean {\n return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));\n}\n\nexport function isAuthError(error: unknown): boolean {\n const status = statusOf(error);\n return status === 401 || status === 403;\n}\n\n/**\n * Resolves a caller-supplied path to an absolute one: relative paths are taken\n * from the sandbox home, `.` and `..` are resolved, and repeated slashes are\n * collapsed, so `/tmp/..` is rejected the same way `/` is.\n */\nexport function normalizeSandboxPath(path: string): string {\n const absolute = path.startsWith('/') ? path : `${SANDBOX_HOME}/${path}`;\n const segments: string[] = [];\n for (const segment of absolute.split('/')) {\n if (segment === '' || segment === '.') continue;\n if (segment === '..') segments.pop();\n else segments.push(segment);\n }\n if (segments.length === 0) {\n throw new Error('Path must not be empty or the filesystem root.');\n }\n return `/${segments.join('/')}`;\n}\n\n/**\n * The SDK takes content paths as a single URL segment it encodes itself, with\n * no leading slash — a leading slash produces an empty segment and a 400 from\n * the gateway.\n */\nexport function toContentPath(path: string): string {\n return normalizeSandboxPath(path).slice(1);\n}\n\nexport type SandboxStatus = 'running' | 'stopped' | 'error';\n\n/**\n * Buddy exposes more states than ComputeSDK. `STARTING` and `RESTORING` map to\n * `running` on purpose: the API queues commands submitted against a sandbox in\n * those states, so it is already usable.\n */\nexport function mapStatus(status: string | undefined): SandboxStatus {\n switch (status) {\n case 'RUNNING':\n case 'STARTING':\n case 'RESTORING':\n return 'running';\n case 'STOPPED':\n case 'STOPPING':\n return 'stopped';\n case 'FAILED':\n return 'error';\n default:\n return 'stopped';\n }\n}\n\n/**\n * Picks a resource preset from the cross-provider `cpu`/`memory` knobs.\n * Buddy only offers `N` vCPU with `2N` GB RAM, so whichever request is larger\n * wins and the result is clamped to the largest preset.\n */\nexport function resolveResources(\n options: Record<string, unknown> = {},\n fallback?: BuddyResources,\n): BuddyResources | undefined {\n if (typeof options.resources === 'string') return options.resources as BuddyResources;\n\n const requestedCpu = firstPositiveNumber([options.cpu, options.vcpus, options.cpus]);\n const requestedMemoryGb = memoryToGb(options);\n if (requestedCpu === undefined && requestedMemoryGb === undefined) return fallback;\n\n const cpuForMemory = requestedMemoryGb === undefined ? 0 : Math.ceil(requestedMemoryGb / 2);\n const cpu = Math.min(MAX_CPU, Math.max(1, requestedCpu ?? 0, cpuForMemory));\n return `${cpu}x${cpu * 2}` as BuddyResources;\n}\n\nfunction firstPositiveNumber(values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.ceil(value);\n }\n return undefined;\n}\n\n/** Memory knobs are unnormalized across providers — MB for some, MiB for others. */\nfunction memoryToGb(options: Record<string, unknown>): number | undefined {\n const mb = firstPositiveNumber([options.memory, options.memoryMb]);\n if (mb !== undefined) return mb / 1024;\n const mib = firstPositiveNumber([options.memoryMiB, options.memMiB]);\n if (mib !== undefined) return (mib * 1024 * 1024) / 1e9;\n return undefined;\n}\n\n/** Buddy identifiers allow alphanumerics, `_` and inner `-` only. */\nexport function toIdentifier(value: string): string {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9_-]+/g, '-');\n // Trim after truncating, or the cut can leave a hyphen in the last position.\n return cleaned.slice(0, 60).replace(/^-+|-+$/g, '') || 'computesdk';\n}\n\nexport function generateSandboxName(): string {\n return `computesdk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function normalizePort(input: BuddyPortInput, config: ResolvedBuddyConfig): Required<BuddyPort> {\n const port = typeof input === 'number' ? { port: input } : input;\n return {\n port: port.port,\n name: port.name ?? `p${port.port}`,\n type: port.type ?? 'HTTP',\n region: port.region ?? config.region,\n };\n}\n\n/** Buddy's tunnel object. `endpoint` holds the sandbox-side port as a string. */\nexport interface BuddyEndpoint {\n name?: string;\n endpoint?: string;\n type?: BuddyTunnelType;\n /** As reported by the API, which may know installations this provider does not offer. */\n region?: string;\n endpoint_url?: string;\n active?: boolean;\n whitelist?: string[];\n [key: string]: unknown;\n}\n\nexport function toEndpointPayload(port: Required<BuddyPort>): BuddyEndpoint {\n return {\n name: port.name,\n endpoint: String(port.port),\n type: port.type,\n region: port.region,\n };\n}\n\n/** Only HTTP and TLS tunnels get a public URL; TCP and SSH report host and port. */\nexport function endpointPublicUrl(endpoint: BuddyEndpoint): string | undefined {\n return endpoint.endpoint_url;\n}\n\nexport function endpointMatchesPort(endpoint: BuddyEndpoint, port: number): boolean {\n return Number(endpoint.endpoint) === port;\n}\n\n/** Fields Buddy reports but rejects when an endpoint is sent back in an update. */\nconst READ_ONLY_ENDPOINT_FIELDS = ['endpoint_url', 'active', 'target_latency'] as const;\n\n/**\n * Prepares an existing endpoint for the replace-all update. Everything\n * writable — `whitelist`, `timeout`, `http`, `tls` and whatever Buddy adds\n * later — has to survive, or opening a new port would reset those tunnels.\n */\nexport function toEndpointUpdate(endpoint: BuddyEndpoint): BuddyEndpoint {\n const update: BuddyEndpoint = { ...endpoint };\n for (const field of READ_ONLY_ENDPOINT_FIELDS) delete update[field];\n return update;\n}\n\n/** Swaps the scheme of a URL, for callers asking for `wss` on an HTTP tunnel. */\nexport function applyProtocol(url: string, protocol?: string): string {\n if (!protocol) return url;\n const normalized = protocol.replace(/:$/, '');\n return url.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, `${normalized}://`);\n}\n\n/**\n * What the provider passes between its own methods, and what `getInstance()`\n * hands back to callers. `client` and `fs` come straight from the SDK, so\n * consumers can drop down to it without building their own client.\n */\nexport interface BuddySandboxHandle {\n sandboxId: string;\n identifier: string;\n config: ResolvedBuddyConfig;\n client: BuddyApiClient;\n fs: FileSystem;\n createdAt: Date;\n /** True unless this process created the sandbox; Buddy reports no creation date. */\n createdAtIsReconnectTime: boolean;\n timeout: number;\n os?: string;\n resources?: string;\n /** Tunnels known so far. `getUrl` extends this when it opens a new one. */\n endpoints: BuddyEndpoint[];\n}\n\n/** Sandbox as the API returns it, narrowed to the fields the provider reads. */\nexport interface BuddySandboxData {\n id?: string;\n identifier?: string;\n name?: string;\n status?: string;\n setup_status?: string;\n os?: string;\n resources?: string;\n timeout?: number;\n endpoints?: BuddyEndpoint[];\n ssh_host?: string;\n ssh_port?: number;\n}\n\n/**\n * Buddy's sandbox resource carries no creation date (only projects and\n * snapshots do), and `SandboxInfo.createdAt` is a required `Date`, so a handle\n * rebuilt by `getById` or `list` can only record when it was reconnected.\n * `getInfo` marks that case with `metadata.createdAtIsReconnectTime`.\n */\nexport function toHandle(\n config: ResolvedBuddyConfig,\n sandbox: BuddySandboxData,\n createdAt = new Date(),\n createdAtIsReconnectTime = true,\n): BuddySandboxHandle {\n const sandboxId = sandbox.id;\n if (!sandboxId) {\n throw new Error('Buddy API returned a sandbox without an id.');\n }\n const client = getClient(config);\n\n return {\n sandboxId,\n identifier: sandbox.identifier ?? sandboxId,\n config,\n client,\n fs: new FileSystem(client, sandboxId),\n createdAt,\n createdAtIsReconnectTime,\n timeout: sandbox.timeout != null ? sandbox.timeout * 1000 : config.timeout,\n os: sandbox.os,\n resources: sandbox.resources,\n endpoints: sandbox.endpoints ?? [],\n };\n}\n\nexport async function getSandboxData(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n): Promise<BuddySandboxData> {\n return await getClient(config).getSandboxById({ path: { id: sandboxId } }) as BuddySandboxData;\n}\n\nexport async function sleep(ms: number): Promise<void> {\n await new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * The boot gate.\n *\n * `create` deliberately returns while the sandbox is still starting, because\n * Buddy queues commands submitted against a starting sandbox. Two other groups\n * of endpoints do not queue:\n *\n * - the content endpoints answer 400 \"Instance is not running\", or answer 2xx to\n * a write whose bytes never land (observed roughly once in twelve sandboxes);\n * - `updateSandbox` answers 400 \"Cannot update sandbox, operation in progress\".\n *\n * So those calls wait here for `RUNNING` + `setup_status: SUCCESS` once per\n * sandbox, and retry the two races until the deadline.\n */\n\nimport {\n getSandboxData,\n isInstanceNotRunning,\n isOperationInProgress,\n sleep,\n type BuddySandboxHandle,\n} from './utils.js';\n\n/** Long enough to cover a drained warm pool; a real boot failure surfaces sooner. */\nconst BOOT_WAIT_TIMEOUT_MS = 90_000;\nconst BOOT_WAIT_POLL_MS = 250;\n\n/** Sandboxes already known to have booted — the gate runs at most once each. */\nconst settled = new WeakSet<BuddySandboxHandle>();\n\nexport async function untilSettled(sandbox: BuddySandboxHandle): Promise<void> {\n if (settled.has(sandbox)) return;\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n if (data.status === 'RUNNING' && data.setup_status === 'SUCCESS') {\n settled.add(sandbox);\n return;\n }\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} failed to start ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} was still starting after ` +\n `${BOOT_WAIT_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(BOOT_WAIT_POLL_MS);\n }\n}\n\n/**\n * Runs an operation once the sandbox has booted, retrying the races that remain\n * afterwards — Buddy reports a snapshot or app operation still in flight the\n * same way.\n */\nexport async function whenBooted<T>(\n sandbox: BuddySandboxHandle,\n operation: () => Promise<T>,\n): Promise<T> {\n await untilSettled(sandbox);\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n try {\n return await operation();\n } catch (error) {\n const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);\n if (!retryable || Date.now() >= deadline) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\n }\n }\n}\n","/**\n * Command execution.\n *\n * Buddy accepts a command and returns its id immediately; output arrives over a\n * JSONL log stream. The provider consumes that stream once through the SDK's\n * `Command` entity, splits it into stdout/stderr and forwards chunks to the\n * streaming callbacks, then reads the exit code from the command details.\n * `Command.wait()` is deliberately unused — it polls once a second, which would\n * add up to a second to every call.\n */\n\nimport { Command } from '@buddy-works/sandbox-sdk';\nimport { escapeShellArg } from '@computesdk/provider';\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\n\nimport { sleep, type BuddyCommandRuntime, type BuddySandboxHandle } from './utils.js';\n\nexport interface BuddyRunCommandOptions extends RunCommandOptions {\n /**\n * Interpreter Buddy runs the command with. Defaults to `BASH`; the other\n * runtimes take a script instead of a shell line, so `cwd` and `env` do not\n * apply to them.\n */\n runtime?: BuddyCommandRuntime;\n}\n\n/** What a POSIX shell accepts as a variable name. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Prepends `cd` and `export` when the caller asked for a cwd or env. Values are\n * escaped; names cannot be, so a name that is not a valid identifier is\n * rejected instead of being spliced into the shell line.\n */\nexport function buildShellCommand(command: string, options: RunCommandOptions = {}): string {\n let line = command;\n\n if (options.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([key, value]) => {\n if (!ENV_NAME.test(key)) {\n throw new TypeError(\n `Invalid environment variable name ${JSON.stringify(key)}: `\n + 'names must match /^[A-Za-z_][A-Za-z0-9_]*$/.',\n );\n }\n return `${key}=\"${escapeShellArg(String(value))}\"`;\n })\n .join(' ');\n line = `export ${exports} && ${line}`;\n }\n if (options.cwd) {\n line = `cd \"${escapeShellArg(options.cwd)}\" && ${line}`;\n }\n return line;\n}\n\n/** A termination that fails leaves the command running remotely, so retry. */\nconst KILL_ATTEMPTS = 3;\nconst KILL_RETRY_DELAY_MS = 500;\n\n/** Best-effort kill: never throws, gives up after `KILL_ATTEMPTS`. */\nexport async function killCommand(running: Pick<Command, 'kill'>): Promise<boolean> {\n for (let attempt = 1; attempt <= KILL_ATTEMPTS; attempt++) {\n try {\n await running.kill();\n return true;\n } catch {\n if (attempt < KILL_ATTEMPTS) await sleep(KILL_RETRY_DELAY_MS);\n }\n }\n return false;\n}\n\nexport async function runCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n options: BuddyRunCommandOptions = {},\n): Promise<CommandResult> {\n // `ADD-PROVIDER.md` still documents an older `runCommand(command, args)`\n // shape. Called that way, the array arrives here as `options`, where only\n // `cwd` and `env` are read — the arguments would be dropped silently and the\n // bare command would still exit 0. Fail loudly instead.\n if (Array.isArray(options)) {\n throw new TypeError(\n `runCommand takes a command line and an options object, not an argument array. `\n + `Pass the arguments inside the command, e.g. '${command} ${options.join(' ')}'.`,\n );\n }\n\n const startedAt = Date.now();\n const runtime = options.runtime ?? 'BASH';\n const payload = runtime === 'BASH' ? buildShellCommand(command, options) : command;\n\n const deadline = options.timeout ? startedAt + options.timeout : undefined;\n const timedOutResult = (stdout = '', stderr = '') => ({\n stdout, stderr, exitCode: TIMEOUT_EXIT_CODE, durationMs: Date.now() - startedAt,\n });\n\n // Buddy may hold the submission while the sandbox boots (up to the client's\n // request timeout), so the deadline applies here too: when it passes first,\n // the timeout result is returned and the command is killed once (if ever)\n // Buddy reports it accepted.\n const submission = sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command: payload, runtime },\n });\n const commandResponse = deadline ? await raceDeadline(submission, deadline) : await submission;\n if (commandResponse === DEADLINE_PASSED) {\n void submission.then(\n response => {\n if (!response.id) return;\n void killCommand(new Command({\n commandResponse: response,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n }));\n },\n () => {},\n );\n return timedOutResult();\n }\n\n const commandId = commandResponse.id;\n if (!commandId) {\n throw new Error('Buddy accepted the command but returned no command id.');\n }\n\n const running = new Command({\n commandResponse,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n });\n\n // Fire-and-forget: return as soon as Buddy has the command queued.\n if (options.background) {\n return { stdout: '', stderr: '', exitCode: 0, durationMs: Date.now() - startedAt };\n }\n\n const stdout: string[] = [];\n const stderr: string[] = [];\n\n // `follow: true` holds the connection open until the command exits, so this\n // loop is the wait — nothing is polled. Each record is one line without its\n // terminator, so the newline goes back on here. Once the caller has been\n // given the timeout result the loop stops at the next record instead of\n // buffering output and firing callbacks for a result nobody will read.\n let timedOut = false;\n const drain = (async () => {\n for await (const log of running.logs({ follow: true })) {\n if (timedOut) break;\n if (log.data == null) continue;\n const chunk = `${log.data}\\n`;\n if (log.type === 'STDERR') {\n stderr.push(chunk);\n options.onStderr?.(chunk);\n } else {\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n }\n })();\n\n // The SDK stream cannot be aborted, so on timeout the result is returned\n // right away — with whatever output arrived before the deadline — and the\n // reader is left to finish on its own once the kill (best effort, retried)\n // closes it or the next record arrives.\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n void killCommand(running);\n drain.catch(() => {});\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n } catch (error) {\n // The stream broke mid-command. Buddy keeps running it, so stop it — best\n // effort and not awaited, so a hanging kill cannot delay the error.\n void killCommand(running);\n throw error;\n }\n\n return {\n stdout: stdout.join(''),\n stderr: stderr.join(''),\n exitCode: await waitForExitCode(sandbox, commandId),\n durationMs: Date.now() - startedAt,\n };\n}\n\nconst DEADLINE_PASSED = Symbol('deadline passed');\n\n/** Resolves to `DEADLINE_PASSED` if `deadline` (epoch ms) arrives first. */\nasync function raceDeadline<T>(work: Promise<T>, deadline: number): Promise<T | typeof DEADLINE_PASSED> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expiry = new Promise<typeof DEADLINE_PASSED>(resolve => {\n timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));\n });\n try {\n return await Promise.race([work, expiry]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** What a shell reports for a command killed by `timeout(1)`. */\nexport const TIMEOUT_EXIT_CODE = 124;\n\nconst EXIT_CODE_WAIT_MS = 5_000;\nconst EXIT_CODE_POLL_MS = 200;\n\nexport interface BuddyCommandDetails {\n exit_code?: number;\n status?: string;\n}\n\n/**\n * The log stream can close a moment before Buddy records the result, so the\n * details may still say `INPROGRESS` without an `exit_code`. Treating that as\n * success would hide failures; poll briefly until a terminal state shows up.\n */\nexport async function waitForExitCode(\n sandbox: Pick<BuddySandboxHandle, 'client' | 'sandboxId'>,\n commandId: string,\n deadlineMs = EXIT_CODE_WAIT_MS,\n): Promise<number> {\n const deadline = Date.now() + deadlineMs;\n for (;;) {\n const details: BuddyCommandDetails = await sandbox.client.getCommandDetails({\n path: { sandbox_id: sandbox.sandboxId, id: commandId },\n });\n if (typeof details.exit_code === 'number') return details.exit_code;\n if (details.status === 'FAILED') return 1;\n if (details.status === 'SUCCESSFUL') return 0;\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy command ${commandId} on sandbox ${sandbox.sandboxId} reported no exit code `\n + `within ${deadlineMs / 1000}s of its log stream closing (status: ${details.status ?? 'unknown'}).`,\n );\n }\n await new Promise(resolve => setTimeout(resolve, EXIT_CODE_POLL_MS));\n }\n}\n","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — one round trip per operation and binary-safe, unlike shelling out\n * to `cat`/`tee`.\n *\n * Every call goes through the boot gate in `boot.ts`, because unlike commands\n * these endpoints do not queue against a sandbox that is still starting.\n */\n\nimport type { FileEntry } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n toContentPath,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport async function readFile(sandbox: BuddySandboxHandle, path: string): Promise<string> {\n const target = normalizeSandboxPath(path);\n const buffer = await whenBooted(sandbox, () => sandbox.fs.downloadFile(target));\n return buffer.toString('utf-8');\n}\n\nexport async function writeFile(\n sandbox: BuddySandboxHandle,\n path: string,\n content: string,\n): Promise<void> {\n const target = normalizeSandboxPath(path);\n const parent = target.slice(0, target.lastIndexOf('/'));\n\n await whenBooted(sandbox, async () => {\n // Buddy will not create missing parents for an upload, and mirroring\n // `fs.writeFile` here is what callers expect.\n if (parent) {\n await sandbox.fs.createFolder(parent).catch(() => {});\n }\n await sandbox.fs.uploadFile(Buffer.from(content, 'utf-8'), target);\n });\n}\n\nexport async function mkdir(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n await whenBooted(sandbox, () => sandbox.fs.createFolder(target));\n}\n\nexport async function readdir(sandbox: BuddySandboxHandle, path: string): Promise<FileEntry[]> {\n const target = normalizeSandboxPath(path);\n const entries = await whenBooted(sandbox, () => sandbox.fs.listFiles(target));\n\n return entries.map(entry => ({\n name: entry.name ?? '',\n type: entry.type === 'DIR' ? 'directory' as const : 'file' as const,\n // The API reports sizes as bigint; ComputeSDK wants a number.\n ...(entry.size == null ? {} : { size: Number(entry.size) }),\n }));\n}\n\nexport async function exists(sandbox: BuddySandboxHandle, path: string): Promise<boolean> {\n const target = toContentPath(path);\n try {\n await whenBooted(sandbox, () =>\n sandbox.client.getSandboxContent({ path: { sandbox_id: sandbox.sandboxId, path: target } }));\n return true;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n}\n\nexport async function remove(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n try {\n await whenBooted(sandbox, () => sandbox.fs.deleteFile(target));\n } catch (error) {\n // Removing something that is already gone is not an error for callers.\n if (!isNotFound(error)) throw error;\n }\n}\n","/**\n * Snapshots — filesystem images of a sandbox that a new sandbox can boot from.\n *\n * Buddy creates them asynchronously: the create call returns `status: CREATING`\n * and the snapshot cannot be restored until it turns `CREATED`. The provider\n * waits for that here so callers get a snapshot they can actually use. The\n * wait uses a 500 ms poll rather than the SDK entity's 2 s one, because typical\n * snapshots settle in well under a second.\n */\n\nimport type { CreateSnapshotOptions, ListSnapshotsOptions } from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport {\n PROVIDER,\n getClient,\n isNotFound,\n sleep,\n toIdentifier,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\nconst SNAPSHOT_WAIT_TIMEOUT_MS = 180_000;\nconst SNAPSHOT_WAIT_POLL_MS = 500;\n\ninterface BuddySnapshotData {\n id?: string;\n name?: string;\n size?: number;\n status?: string;\n create_date?: Date | string;\n}\n\nfunction toSnapshot(data: BuddySnapshotData, sandboxId?: string): Snapshot {\n if (!data.id) {\n throw new Error('Buddy API returned a snapshot without an id.');\n }\n return {\n id: data.id,\n provider: PROVIDER,\n createdAt: data.create_date ? new Date(data.create_date) : new Date(),\n metadata: {\n name: data.name,\n status: data.status,\n sizeGb: data.size,\n ...(sandboxId ? { sandboxId } : {}),\n },\n };\n}\n\nexport async function createSnapshot(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n options: CreateSnapshotOptions = {},\n): Promise<Snapshot> {\n const client = getClient(config);\n const created = await client.addSandboxSnapshot({\n path: { sandbox_id: sandboxId },\n body: { name: toIdentifier(options.name ?? `computesdk-${Date.now()}`) },\n });\n\n const snapshotId = created.id;\n if (!snapshotId) {\n throw new Error('Buddy accepted the snapshot but returned no snapshot id.');\n }\n\n const ready = await waitUntilCreated(config, sandboxId, snapshotId, created);\n return toSnapshot(ready, sandboxId);\n}\n\nasync function waitUntilCreated(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n snapshotId: string,\n initial: BuddySnapshotData,\n): Promise<BuddySnapshotData> {\n if (initial.status === 'CREATED') return initial;\n\n const client = getClient(config);\n const deadline = Date.now() + SNAPSHOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await client.getSandboxSnapshot({\n path: { sandbox_id: sandboxId, id: snapshotId },\n }) as BuddySnapshotData;\n\n if (data.status === 'CREATED') return data;\n if (data.status === 'FAILED') {\n throw new Error(`Buddy snapshot ${snapshotId} failed to be created.`);\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy snapshot ${snapshotId} was still ${data.status} after ` +\n `${SNAPSHOT_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(SNAPSHOT_WAIT_POLL_MS);\n }\n}\n\nexport async function listSnapshots(\n config: ResolvedBuddyConfig,\n options: ListSnapshotsOptions = {},\n): Promise<Snapshot[]> {\n const client = getClient(config);\n // Default to the project-wide listing: snapshots outlive the sandbox they were\n // taken from, so the per-sandbox endpoint would hide most of them.\n const response = options.sandboxId\n ? await client.getSandboxSnapshots({ path: { sandbox_id: options.sandboxId } })\n : await client.getProjectSnapshots({});\n\n const snapshots = (response.snapshots ?? [])\n .map(snapshot => toSnapshot(snapshot as BuddySnapshotData, options.sandboxId));\n return options.limit ? snapshots.slice(0, options.limit) : snapshots;\n}\n\nexport async function deleteSnapshot(\n config: ResolvedBuddyConfig,\n snapshotId: string,\n): Promise<void> {\n try {\n await getClient(config).deleteSnapshot({ path: { id: snapshotId } });\n } catch (error) {\n // Deleting an already-deleted snapshot is the state the caller wanted.\n if (!isNotFound(error)) throw error;\n }\n}\n"],"mappings":";AAcA,SAAS,sBAAsB;;;ACH/B,SAAS,UAAU,gBAAgB,kBAAkB;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,iBAA8B;AAEpC,IAAM,qBAAqB;AAE3B,IAAM,eAAe;AAsBrB,IAAM,UAAU;AAmDvB,IAAM,aACJ;AAIK,SAAS,gBAAgB,QAA6B;AAC3D,SAAO,SAAS,MAAM;AACxB;AASA,IAAM,WAAW,oBAAI,QAA0C;AAM/D,IAAM,kBAAkB,oBAAI,IAAiC;AAEtD,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AO,cAAc,KAAK,QAAQ;AAC3C,QAAI,KAAK,IAAI,KAAK,UAAU;AAC1B,YAAM,IAAI;AAAA,QACR,iCAAiC,IAAI,eAAe,QAAQ,SAAS,uCAC/B,sBAAsB,GAAI;AAAA,MAClE;AAAA,IACF;AACA,UAAM,MAAM,gBAAgB;AAAA,EAC9B;AACF;AAEA,eAAe,gBACb,SACA,MAC6B;AAC7B,QAAM,OAAO,MAAM,eAAe,QAAQ,QAAQ,QAAQ,SAAS;AACnE,UAAQ,YAAY,KAAK,aAAa,CAAC;AACvC,QAAM,QAAQ,QAAQ,UAAU,KAAK,cAAY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["value","stdout","stderr","resolved"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/boot.ts","../src/commands.ts","../src/filesystem.ts","../src/snapshots.ts"],"sourcesContent":["/**\n * Buddy provider for ComputeSDK.\n *\n * Buddy serves Ubuntu sandboxes from a pre-warmed pool, so `create` returns a\n * sandbox that is already booting and commands submitted to it are queued until\n * it is up. The provider does not wait for `RUNNING` on create — that keeps\n * time-to-first-command at the warm-pool latency instead of a poll interval.\n *\n * Snapshots are Buddy's only reusable image, so `compute.template.*` is mapped\n * onto them.\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateSandboxOptions,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n SandboxInfo,\n} from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport type { BuddyApiClient } from '@buddy-works/sandbox-sdk';\nimport { whenBooted } from './boot.js';\nimport { runCommand, type BuddyRunCommandOptions } from './commands.js';\nimport * as fs from './filesystem.js';\nimport { createSnapshot, deleteSnapshot, listSnapshots } from './snapshots.js';\nimport {\n PROVIDER,\n applyProtocol,\n endpointMatchesPort,\n endpointPublicUrl,\n generateSandboxName,\n getClient,\n getSandboxData,\n isNotFound,\n isUnroutableId,\n mapStatus,\n normalizePort,\n resolveConfig,\n resolveResources,\n sleep,\n statusOf,\n toEndpointPayload,\n toEndpointUpdate,\n toHandle,\n toIdentifier,\n type BuddyConfig,\n type BuddyEndpoint,\n type BuddyPortInput,\n type BuddySandboxHandle,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\n/** Deleting a just-created sandbox occasionally answers 5xx while succeeding. */\nconst DESTROY_ATTEMPTS = 3;\nconst DESTROY_RETRY_DELAY_MS = 500;\n\n/** A tunnel is registered instantly but takes a moment to get its public URL. */\nconst URL_WAIT_TIMEOUT_MS = 15_000;\nconst URL_WAIT_POLL_MS = 250;\n\n/**\n * Deletes a sandbox, retrying transient server failures. \"Already gone\" is the\n * state the caller asked for, so it counts as success.\n */\nexport async function deleteSandbox(client: BuddyApiClient, sandboxId: string): Promise<void> {\n for (let attempt = 1; attempt <= DESTROY_ATTEMPTS; attempt++) {\n try {\n await client.deleteSandboxById({ path: { id: sandboxId } });\n return;\n } catch (error) {\n if (isNotFound(error)) return;\n const status = statusOf(error);\n const retryable = status !== undefined && status >= 500;\n if (!retryable || attempt === DESTROY_ATTEMPTS) throw error;\n await sleep(DESTROY_RETRY_DELAY_MS);\n }\n }\n}\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n methods: {\n sandbox: {\n create: async (config: BuddyConfig, options?: CreateSandboxOptions) => {\n const resolved = resolveConfig(config);\n const created = await getClient(resolved).addSandbox({\n body: buildCreateBody(resolved, options),\n });\n\n const sandbox = toHandle(resolved, created, new Date(), false);\n try {\n await ensureTimeout(sandbox, options?.timeout ?? resolved.timeout);\n } catch (error) {\n // The framework has no id yet, so nothing else could clean this up.\n await deleteSandbox(sandbox.client, sandbox.sandboxId).catch(() => {});\n throw error;\n }\n return { sandbox, sandboxId: sandbox.sandboxId };\n },\n\n getById: async (config: BuddyConfig, sandboxId: string) => {\n const resolved = resolveConfig(config);\n try {\n const data = await getSandboxData(resolved, sandboxId);\n const sandbox = toHandle(resolved, data);\n return { sandbox, sandboxId: sandbox.sandboxId };\n } catch (error) {\n if (isNotFound(error) || isUnroutableId(error)) return null;\n throw error;\n }\n },\n\n list: async (config: BuddyConfig) => {\n const resolved = resolveConfig(config);\n const response = await getClient(resolved).getSandboxes({});\n\n // The listing carries ids only; details are fetched on demand by\n // getInfo, so listing a hundred sandboxes stays a single request.\n return (response.sandboxes ?? [])\n .filter(entry => Boolean(entry.id))\n .map(entry => {\n const sandbox = toHandle(resolved, entry);\n return { sandbox, sandboxId: sandbox.sandboxId };\n });\n },\n\n destroy: async (config: BuddyConfig, sandboxId: string) =>\n deleteSandbox(getClient(resolveConfig(config)), sandboxId),\n\n runCommand: async (\n sandbox: BuddySandboxHandle,\n command: string,\n options?: BuddyRunCommandOptions,\n ) => runCommand(sandbox, command, options),\n\n // `runCommand` already forwards `onStdout`/`onStderr` from Buddy's own\n // log stream. Without this the factory would ignore that and bootstrap\n // its Node-based streaming daemon inside the sandbox instead.\n streamCommand: runCommand,\n\n getInfo: async (sandbox: BuddySandboxHandle): Promise<SandboxInfo> => {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? sandbox.endpoints;\n\n return {\n id: sandbox.sandboxId,\n provider: PROVIDER,\n status: mapStatus(data.status),\n createdAt: sandbox.createdAt,\n timeout: data.timeout != null ? data.timeout * 1000 : sandbox.timeout,\n metadata: {\n createdAtIsReconnectTime: sandbox.createdAtIsReconnectTime,\n identifier: data.identifier ?? sandbox.identifier,\n name: data.name,\n os: data.os,\n resources: data.resources,\n buddyStatus: data.status,\n setupStatus: data.setup_status,\n workspace: sandbox.config.workspace,\n project: sandbox.config.project,\n region: sandbox.config.region,\n endpoints: (data.endpoints ?? []).map(endpoint => ({\n name: endpoint.name,\n port: Number(endpoint.endpoint),\n type: endpoint.type,\n url: endpointPublicUrl(endpoint),\n })),\n },\n };\n },\n\n getUrl: async (sandbox: BuddySandboxHandle, options: { port: number; protocol?: string }) =>\n getUrl(sandbox, options),\n\n getInstance: (sandbox: BuddySandboxHandle) => sandbox,\n\n filesystem: {\n readFile: (sandbox: BuddySandboxHandle, path: string) => fs.readFile(sandbox, path),\n writeFile: (sandbox: BuddySandboxHandle, path: string, content: string) =>\n fs.writeFile(sandbox, path, content),\n mkdir: (sandbox: BuddySandboxHandle, path: string) => fs.mkdir(sandbox, path),\n readdir: (sandbox: BuddySandboxHandle, path: string) => fs.readdir(sandbox, path),\n exists: (sandbox: BuddySandboxHandle, path: string) => fs.exists(sandbox, path),\n remove: (sandbox: BuddySandboxHandle, path: string) => fs.remove(sandbox, path),\n },\n },\n\n snapshot: {\n create: (config: BuddyConfig, sandboxId: string, options?: { name?: string }) =>\n createSnapshot(resolveConfig(config), sandboxId, options),\n list: (config: BuddyConfig, options?: ListSnapshotsOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, snapshotId: string) =>\n deleteSnapshot(resolveConfig(config), snapshotId),\n },\n\n /**\n * Buddy has no separate template entity — a snapshot is the reusable image,\n * and `create({ templateId })` boots from one. So listing and deleting\n * templates operate on snapshots, and creating one points the caller at\n * `compute.snapshot.create`, which is where an image comes from.\n */\n template: {\n create: async () => {\n throw new Error(\n 'Buddy does not have templates as a separate entity. Snapshot a ' +\n 'configured sandbox instead: const snapshot = await compute.snapshot.create(sandboxId), ' +\n 'then boot from it with compute.sandbox.create({ snapshotId: snapshot.id }).',\n );\n },\n list: (config: BuddyConfig, options?: ListTemplatesOptions) =>\n listSnapshots(resolveConfig(config), options),\n delete: (config: BuddyConfig, templateId: string) =>\n deleteSnapshot(resolveConfig(config), templateId),\n },\n },\n});\n\n/** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */\nexport function toSeconds(ms: number): number {\n return Math.max(1, Math.ceil(ms / 1000));\n}\n\nfunction buildCreateBody(config: ResolvedBuddyConfig, options: CreateSandboxOptions = {}) {\n const name = options.name ?? generateSandboxName();\n const timeoutMs = options.timeout ?? config.timeout;\n // `templateId` is accepted alongside `snapshotId` because Buddy's template\n // methods are backed by snapshots — both carry a snapshot id.\n const snapshotId = options.snapshotId ?? options.templateId;\n\n const body: Record<string, unknown> = {\n name,\n identifier: toIdentifier(name),\n os: options.image ?? config.os,\n timeout: toSeconds(timeoutMs),\n };\n\n const resources = resolveResources(options, config.resources);\n if (resources) body.resources = resources;\n\n // Buddy-specific create options, passed through as they are named in the API.\n if (options.firstBootCommands) body.first_boot_commands = options.firstBootCommands;\n if (options.appDir) body.app_dir = options.appDir;\n if (options.tags) body.tags = options.tags;\n\n const ports = options.ports ?? config.ports;\n if (ports?.length) {\n body.endpoints = ports.map((port: BuddyPortInput) =>\n toEndpointPayload(normalizePort(port, config)));\n }\n if (options.envs && Object.keys(options.envs).length > 0) {\n body.variables = Object.entries(options.envs).map(([key, value]) => ({ key, value }));\n }\n if (snapshotId) body.snapshot_id = snapshotId;\n\n return body as any;\n}\n\n/**\n * Buddy's create-from-snapshot request has no `timeout` field (the SDK schema\n * strips it), so a sandbox booted from a snapshot comes back with whatever the\n * snapshot carried. Patch it afterwards when it differs from what was asked.\n */\nexport async function ensureTimeout(\n sandbox: BuddySandboxHandle,\n timeoutMs: number,\n): Promise<void> {\n const seconds = toSeconds(timeoutMs);\n if (toSeconds(sandbox.timeout) === seconds) return;\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { timeout: seconds } as any,\n }));\n sandbox.timeout = updated.timeout != null ? updated.timeout * 1000 : seconds * 1000;\n}\n\n/**\n * Endpoint updates in flight, per remote sandbox. Buddy replaces the whole\n * endpoint list on update, so two concurrent `getUrl` calls built from the same\n * list would each drop the other's port — they run one after another instead.\n * Keyed by installation + sandbox id rather than by handle: `getById` and\n * `list` hand out a fresh handle each time for the same remote sandbox.\n */\nconst endpointUpdates = new Map<string, Promise<unknown>>();\n\nfunction endpointUpdateKey(sandbox: BuddySandboxHandle): string {\n return `${sandbox.config.apiUrl}|${sandbox.config.workspace}|${sandbox.sandboxId}`;\n}\n\nfunction getUrl(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const key = endpointUpdateKey(sandbox);\n const previous = endpointUpdates.get(key) ?? Promise.resolve();\n const next = previous.catch(() => {}).then(() => openPort(sandbox, options));\n endpointUpdates.set(key, next);\n // Drop the entry once nothing newer is queued behind it, so the map only\n // ever holds sandboxes with an update actually in flight.\n next.catch(() => {}).finally(() => {\n if (endpointUpdates.get(key) === next) endpointUpdates.delete(key);\n });\n return next;\n}\n\nasync function openPort(\n sandbox: BuddySandboxHandle,\n options: { port: number; protocol?: string },\n): Promise<string> {\n const { port, protocol } = options;\n const existing = await findEndpointUrl(sandbox, port);\n if (existing) return applyProtocol(existing, protocol);\n\n const desired = normalizePort({ port }, sandbox.config);\n // Buddy replaces the whole endpoint list on update, so previously opened\n // tunnels have to be sent back or they would be torn down here.\n const kept = sandbox.endpoints\n .filter(endpoint => !endpointMatchesPort(endpoint, port))\n .map(toEndpointUpdate);\n\n // Buddy refuses configuration changes while the sandbox is still starting.\n const updated = await whenBooted(sandbox, () => sandbox.client.updateSandbox({\n path: { id: sandbox.sandboxId },\n body: { endpoints: [...kept, toEndpointPayload(desired)] } as any,\n }));\n sandbox.endpoints = (updated.endpoints ?? sandbox.endpoints) as BuddyEndpoint[];\n\n const deadline = Date.now() + URL_WAIT_TIMEOUT_MS;\n for (;;) {\n const url = await findEndpointUrl(sandbox, port);\n if (url) return applyProtocol(url, protocol);\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy opened a tunnel to port ${port} on sandbox ${sandbox.sandboxId} ` +\n `but published no public URL within ${URL_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(URL_WAIT_POLL_MS);\n }\n}\n\nasync function findEndpointUrl(\n sandbox: BuddySandboxHandle,\n port: number,\n): Promise<string | undefined> {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n sandbox.endpoints = data.endpoints ?? [];\n const match = sandbox.endpoints.find(endpoint => endpointMatchesPort(endpoint, port));\n return match ? endpointPublicUrl(match) : undefined;\n}\n\nexport type { BuddyConfig, BuddySandboxHandle as BuddySandbox } from './utils.js';\nexport type { BuddyRunCommandOptions } from './commands.js';\n","/**\n * Shared types, config resolution and SDK plumbing for the Buddy provider.\n *\n * All API access goes through `@buddy-works/sandbox-sdk`. The provider uses the\n * SDK's `BuddyApiClient` rather than its high-level `Sandbox` façade for sandbox\n * creation: `Sandbox.create()` waits for `setup_status: SUCCESS` and\n * `status: RUNNING` with a 1 s poll, and since a sandbox from Buddy's warm pool\n * is usable in ~400 ms that wait would dominate time-to-first-command. The\n * façade's `Command`, `FileSystem` and snapshot helpers are used as-is.\n */\n\nimport { API_URLS, BuddyApiClient, FileSystem } from '@buddy-works/sandbox-sdk';\n\nexport const PROVIDER = 'buddy' as const;\nexport const DEFAULT_OS = 'ubuntu:24.04';\nexport const DEFAULT_REGION: BuddyRegion = 'US';\n/** Buddy stops a sandbox after this many ms of life unless overridden. */\nexport const DEFAULT_TIMEOUT_MS = 3_600_000;\n/** Working directory of the default `buddy` user — relative paths resolve here. */\nexport const SANDBOX_HOME = '/buddy';\n\n/**\n * Buddy installation, in the spelling its tunnel API uses. Each installation is\n * a separate deployment with its own API host, workspaces and tokens — `US` is\n * not a placement hint within one API.\n */\nexport type BuddyRegion = 'US' | 'EU';\n\n/** Interpreter Buddy runs a command with. `BASH` is the default. */\nexport type BuddyCommandRuntime = 'BASH' | 'JAVASCRIPT' | 'TYPESCRIPT' | 'PYTHON';\n\n/** Tunnel protocol. Only `HTTP` yields a public `endpoint_url`. */\nexport type BuddyTunnelType = 'HTTP' | 'TLS' | 'TCP' | 'SSH';\n\n/**\n * Buddy resource preset, `\"{vCPU}x{RAM in GB}\"`. RAM is always 2 GB per vCPU.\n */\nexport type BuddyResources =\n | '1x2' | '2x4' | '3x6' | '4x8' | '5x10' | '6x12'\n | '7x14' | '8x16' | '9x18' | '10x20' | '11x22' | '12x24';\n\nexport const MAX_CPU = 12;\n\n/** A port to expose publicly. A bare number means `{ port, type: 'HTTP' }`. */\nexport interface BuddyPort {\n port: number;\n /** Tunnel name. Becomes the first label of the public hostname. */\n name?: string;\n type?: BuddyTunnelType;\n region?: BuddyRegion;\n}\n\nexport type BuddyPortInput = number | BuddyPort;\n\nexport interface BuddyConfig {\n /** API token with the `SANDBOX_MANAGE` scope. Falls back to `BUDDY_TOKEN`. */\n token?: string;\n /** Workspace domain. Falls back to `BUDDY_WORKSPACE`. */\n workspace?: string;\n /** Project the sandboxes belong to. Falls back to `BUDDY_PROJECT`. */\n project?: string;\n /** Base OS image — `'ubuntu:24.04'` (default) or `'ubuntu:22.04'`. */\n os?: string;\n /** Resource preset. Buddy's own default applies when omitted. */\n resources?: BuddyResources;\n /**\n * Buddy installation to use. Selects both the API host and where tunnels\n * terminate. Defaults to `'US'`. A token is only valid on its own\n * installation.\n */\n region?: BuddyRegion;\n /** Sandbox lifetime in milliseconds, after which Buddy stops it. */\n timeout?: number;\n /** Ports to expose on every sandbox this provider creates. */\n ports?: BuddyPortInput[];\n /** API base URL. Overrides `region` — set it for on-premise installations. */\n apiUrl?: string;\n}\n\n/** Config after env-var fallbacks and validation — what the methods receive. */\nexport interface ResolvedBuddyConfig {\n token: string;\n workspace: string;\n project: string;\n os: string;\n resources?: BuddyResources;\n region: BuddyRegion;\n timeout: number;\n ports?: BuddyPortInput[];\n apiUrl: string;\n}\n\nconst SETUP_HINT =\n 'Create a token with the SANDBOX_MANAGE scope at ' +\n 'https://app.buddy.works/my-id/tokens';\n\n/** The SDK's API host table is keyed by the same region names we use. */\nexport function apiUrlForRegion(region: BuddyRegion): string {\n return API_URLS[region];\n}\n\n/**\n * One resolved config per config object handed to `buddy()`. The provider\n * methods each receive the raw config, and resolving it to a stable object is\n * what lets the SDK client below be reused across calls — a fresh client per\n * call would give up Node's keep-alive connections between `create` and the\n * first command.\n */\nconst resolved = new WeakMap<BuddyConfig, ResolvedBuddyConfig>();\n/**\n * `buddy()` with no config reads the environment on every call, so a token\n * rotated in `process.env` is picked up; the result is cached by value so the\n * SDK client (and its connection pool) is still shared while nothing changed.\n */\nconst resolvedFromEnv = new Map<string, ResolvedBuddyConfig>();\n\nexport function resolveConfig(config?: BuddyConfig): ResolvedBuddyConfig {\n if (!config) {\n const key = [\n process.env.BUDDY_TOKEN, process.env.BUDDY_WORKSPACE, process.env.BUDDY_PROJECT,\n ].join('\\u0000');\n let value = resolvedFromEnv.get(key);\n if (!value) {\n value = buildConfig({});\n resolvedFromEnv.clear();\n resolvedFromEnv.set(key, value);\n }\n return value;\n }\n const cached = resolved.get(config);\n if (cached) return cached;\n const value = buildConfig(config);\n resolved.set(config, value);\n return value;\n}\n\nfunction buildConfig(config: BuddyConfig): ResolvedBuddyConfig {\n const token = config.token ?? process.env.BUDDY_TOKEN;\n const workspace = config.workspace ?? process.env.BUDDY_WORKSPACE;\n const project = config.project ?? process.env.BUDDY_PROJECT;\n\n if (!token) {\n throw new Error(\n 'Missing Buddy API token.\\n\\n' +\n `${SETUP_HINT}\\n` +\n 'Then pass it: buddy({ token: \"xxx\" })\\n' +\n 'Or set BUDDY_TOKEN in your environment.',\n );\n }\n if (!workspace) {\n throw new Error(\n 'Missing Buddy workspace domain.\\n\\n' +\n 'It is the workspace segment of your Buddy URL ' +\n '(https://app.buddy.works/<workspace>/...).\\n' +\n 'Pass it: buddy({ workspace: \"my-workspace\" }) or set BUDDY_WORKSPACE.',\n );\n }\n if (!project) {\n throw new Error(\n 'Missing Buddy project name.\\n\\n' +\n 'Sandboxes always belong to a project. Create one in the Buddy UI, then\\n' +\n 'pass it: buddy({ project: \"my-project\" }) or set BUDDY_PROJECT.',\n );\n }\n\n const region = config.region ?? DEFAULT_REGION;\n\n return {\n token,\n workspace,\n project,\n os: config.os ?? DEFAULT_OS,\n resources: config.resources,\n region,\n timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,\n ports: config.ports,\n apiUrl: (config.apiUrl ?? apiUrlForRegion(region)).replace(/\\/+$/, ''),\n };\n}\n\n/**\n * One SDK client per resolved config. Reusing it matters: creating a sandbox\n * and running the first command is several round trips, and a shared client\n * keeps Node's connection pool warm across them.\n */\nconst clients = new WeakMap<ResolvedBuddyConfig, BuddyApiClient>();\n\n/**\n * Per-request timeout for the SDK client. Its default is 30 s, which is too\n * short for `POST /commands`: Buddy holds that request until the sandbox has\n * booted, and a drained warm pool has been measured to take over 10 s. On a\n * timeout the SDK retries the POST, which would submit the command twice.\n */\nexport const CLIENT_REQUEST_TIMEOUT_MS = 120_000;\n\nexport function getClient(config: ResolvedBuddyConfig): BuddyApiClient {\n let client = clients.get(config);\n if (!client) {\n client = new BuddyApiClient({\n workspace: config.workspace,\n project_name: config.project,\n apiUrl: config.apiUrl,\n token: config.token,\n timeout: CLIENT_REQUEST_TIMEOUT_MS,\n });\n clients.set(config, client);\n }\n return client;\n}\n\n/**\n * HTTP status behind an SDK error. `BuddySDKError` carries `statusCode`; the\n * lower-level `HttpError` the raw client throws carries `status` and is not\n * exported, so both are read structurally.\n */\nexport function statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const candidate = error as { statusCode?: unknown; status?: unknown };\n const status = candidate.statusCode ?? candidate.status;\n return typeof status === 'number' && status > 0 ? status : undefined;\n}\n\nexport function messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function isNotFound(error: unknown): boolean {\n const status = statusOf(error);\n if (status === 404) return true;\n // The content endpoints answer 400 \"Path not find in browser\" for a missing\n // path instead of 404, so the message has to be inspected as well.\n return status === 400 && /not (found|find)/i.test(messageOf(error));\n}\n\n/**\n * Buddy sandbox ids are fixed-length, so an id of any other shape never reaches\n * the handler and comes back as 400 \"Invalid url\" rather than 404. For a lookup\n * both answers mean the same thing: no such sandbox.\n */\nexport function isUnroutableId(error: unknown): boolean {\n return statusOf(error) === 400 && /invalid url/i.test(messageOf(error));\n}\n\n/**\n * A sandbox that has not finished booting yet. Commands submitted to a\n * `STARTING` sandbox are queued by Buddy, but the `content/` and `download/`\n * endpoints reject outright with 400 \"Instance is not running\" — measured to\n * last up to ~8 s when the warm pool is drained. The synchronous `exec`\n * endpoint words the same state as 400 \"Sandbox must be running\".\n */\nexport function isInstanceNotRunning(error: unknown): boolean {\n return statusOf(error) === 400 && /instance is not running|sandbox must be running/i.test(messageOf(error));\n}\n\n/**\n * A sandbox with a lifecycle operation in flight. Buddy rejects configuration\n * changes, including opening a tunnel, until the boot or snapshot finishes.\n */\nexport function isOperationInProgress(error: unknown): boolean {\n return statusOf(error) === 400 && /operation in progress/i.test(messageOf(error));\n}\n\nexport function isAuthError(error: unknown): boolean {\n const status = statusOf(error);\n return status === 401 || status === 403;\n}\n\n/**\n * Resolves a caller-supplied path to an absolute one: relative paths are taken\n * from the sandbox home, `.` and `..` are resolved, and repeated slashes are\n * collapsed, so `/tmp/..` is rejected the same way `/` is.\n */\nexport function normalizeSandboxPath(path: string): string {\n const absolute = path.startsWith('/') ? path : `${SANDBOX_HOME}/${path}`;\n const segments: string[] = [];\n for (const segment of absolute.split('/')) {\n if (segment === '' || segment === '.') continue;\n if (segment === '..') segments.pop();\n else segments.push(segment);\n }\n if (segments.length === 0) {\n throw new Error('Path must not be empty or the filesystem root.');\n }\n return `/${segments.join('/')}`;\n}\n\n/**\n * The SDK takes content paths as a single URL segment it encodes itself, with\n * no leading slash — a leading slash produces an empty segment and a 400 from\n * the gateway.\n */\nexport function toContentPath(path: string): string {\n return normalizeSandboxPath(path).slice(1);\n}\n\nexport type SandboxStatus = 'running' | 'stopped' | 'error';\n\n/**\n * Buddy exposes more states than ComputeSDK. `STARTING` and `RESTORING` map to\n * `running` on purpose: the API queues commands submitted against a sandbox in\n * those states, so it is already usable.\n */\nexport function mapStatus(status: string | undefined): SandboxStatus {\n switch (status) {\n case 'RUNNING':\n case 'STARTING':\n case 'RESTORING':\n return 'running';\n case 'STOPPED':\n case 'STOPPING':\n return 'stopped';\n case 'FAILED':\n return 'error';\n default:\n return 'stopped';\n }\n}\n\n/**\n * Picks a resource preset from the cross-provider `cpu`/`memory` knobs.\n * Buddy only offers `N` vCPU with `2N` GB RAM, so whichever request is larger\n * wins and the result is clamped to the largest preset.\n */\nexport function resolveResources(\n options: Record<string, unknown> = {},\n fallback?: BuddyResources,\n): BuddyResources | undefined {\n if (typeof options.resources === 'string') return options.resources as BuddyResources;\n\n const requestedCpu = firstPositiveNumber([options.cpu, options.vcpus, options.cpus]);\n const requestedMemoryGb = memoryToGb(options);\n if (requestedCpu === undefined && requestedMemoryGb === undefined) return fallback;\n\n const cpuForMemory = requestedMemoryGb === undefined ? 0 : Math.ceil(requestedMemoryGb / 2);\n const cpu = Math.min(MAX_CPU, Math.max(1, requestedCpu ?? 0, cpuForMemory));\n return `${cpu}x${cpu * 2}` as BuddyResources;\n}\n\nfunction firstPositiveNumber(values: unknown[]): number | undefined {\n for (const value of values) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return Math.ceil(value);\n }\n return undefined;\n}\n\n/** Memory knobs are unnormalized across providers — MB for some, MiB for others. */\nfunction memoryToGb(options: Record<string, unknown>): number | undefined {\n const mb = firstPositiveNumber([options.memory, options.memoryMb]);\n if (mb !== undefined) return mb / 1024;\n const mib = firstPositiveNumber([options.memoryMiB, options.memMiB]);\n if (mib !== undefined) return (mib * 1024 * 1024) / 1e9;\n return undefined;\n}\n\n/** Buddy identifiers allow alphanumerics, `_` and inner `-` only. */\nexport function toIdentifier(value: string): string {\n const cleaned = value.toLowerCase().replace(/[^a-z0-9_-]+/g, '-');\n // Trim after truncating, or the cut can leave a hyphen in the last position.\n return cleaned.slice(0, 60).replace(/^-+|-+$/g, '') || 'computesdk';\n}\n\nexport function generateSandboxName(): string {\n return `computesdk-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nexport function normalizePort(input: BuddyPortInput, config: ResolvedBuddyConfig): Required<BuddyPort> {\n const port = typeof input === 'number' ? { port: input } : input;\n return {\n port: port.port,\n name: port.name ?? `p${port.port}`,\n type: port.type ?? 'HTTP',\n region: port.region ?? config.region,\n };\n}\n\n/** Buddy's tunnel object. `endpoint` holds the sandbox-side port as a string. */\nexport interface BuddyEndpoint {\n name?: string;\n endpoint?: string;\n type?: BuddyTunnelType;\n /** As reported by the API, which may know installations this provider does not offer. */\n region?: string;\n endpoint_url?: string;\n active?: boolean;\n whitelist?: string[];\n [key: string]: unknown;\n}\n\nexport function toEndpointPayload(port: Required<BuddyPort>): BuddyEndpoint {\n return {\n name: port.name,\n endpoint: String(port.port),\n type: port.type,\n region: port.region,\n };\n}\n\n/** Only HTTP and TLS tunnels get a public URL; TCP and SSH report host and port. */\nexport function endpointPublicUrl(endpoint: BuddyEndpoint): string | undefined {\n return endpoint.endpoint_url;\n}\n\nexport function endpointMatchesPort(endpoint: BuddyEndpoint, port: number): boolean {\n return Number(endpoint.endpoint) === port;\n}\n\n/** Fields Buddy reports but rejects when an endpoint is sent back in an update. */\nconst READ_ONLY_ENDPOINT_FIELDS = ['endpoint_url', 'active', 'target_latency'] as const;\n\n/**\n * Prepares an existing endpoint for the replace-all update. Everything\n * writable — `whitelist`, `timeout`, `http`, `tls` and whatever Buddy adds\n * later — has to survive, or opening a new port would reset those tunnels.\n */\nexport function toEndpointUpdate(endpoint: BuddyEndpoint): BuddyEndpoint {\n const update: BuddyEndpoint = { ...endpoint };\n for (const field of READ_ONLY_ENDPOINT_FIELDS) delete update[field];\n return update;\n}\n\n/** Swaps the scheme of a URL, for callers asking for `wss` on an HTTP tunnel. */\nexport function applyProtocol(url: string, protocol?: string): string {\n if (!protocol) return url;\n const normalized = protocol.replace(/:$/, '');\n return url.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, `${normalized}://`);\n}\n\n/**\n * What the provider passes between its own methods, and what `getInstance()`\n * hands back to callers. `client` and `fs` come straight from the SDK, so\n * consumers can drop down to it without building their own client.\n */\nexport interface BuddySandboxHandle {\n sandboxId: string;\n identifier: string;\n config: ResolvedBuddyConfig;\n client: BuddyApiClient;\n fs: FileSystem;\n createdAt: Date;\n /** True unless this process created the sandbox; Buddy reports no creation date. */\n createdAtIsReconnectTime: boolean;\n timeout: number;\n os?: string;\n resources?: string;\n /** Tunnels known so far. `getUrl` extends this when it opens a new one. */\n endpoints: BuddyEndpoint[];\n}\n\n/** Sandbox as the API returns it, narrowed to the fields the provider reads. */\nexport interface BuddySandboxData {\n id?: string;\n identifier?: string;\n name?: string;\n status?: string;\n setup_status?: string;\n os?: string;\n resources?: string;\n timeout?: number;\n endpoints?: BuddyEndpoint[];\n ssh_host?: string;\n ssh_port?: number;\n}\n\n/**\n * Buddy's sandbox resource carries no creation date (only projects and\n * snapshots do), and `SandboxInfo.createdAt` is a required `Date`, so a handle\n * rebuilt by `getById` or `list` can only record when it was reconnected.\n * `getInfo` marks that case with `metadata.createdAtIsReconnectTime`.\n */\nexport function toHandle(\n config: ResolvedBuddyConfig,\n sandbox: BuddySandboxData,\n createdAt = new Date(),\n createdAtIsReconnectTime = true,\n): BuddySandboxHandle {\n const sandboxId = sandbox.id;\n if (!sandboxId) {\n throw new Error('Buddy API returned a sandbox without an id.');\n }\n const client = getClient(config);\n\n return {\n sandboxId,\n identifier: sandbox.identifier ?? sandboxId,\n config,\n client,\n fs: new FileSystem(client, sandboxId),\n createdAt,\n createdAtIsReconnectTime,\n timeout: sandbox.timeout != null ? sandbox.timeout * 1000 : config.timeout,\n os: sandbox.os,\n resources: sandbox.resources,\n endpoints: sandbox.endpoints ?? [],\n };\n}\n\nexport async function getSandboxData(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n): Promise<BuddySandboxData> {\n return await getClient(config).getSandboxById({ path: { id: sandboxId } }) as BuddySandboxData;\n}\n\nexport async function sleep(ms: number): Promise<void> {\n await new Promise(resolve => setTimeout(resolve, ms));\n}\n","/**\n * The boot gate.\n *\n * `create` deliberately returns while the sandbox is still starting, because\n * Buddy queues commands submitted against a starting sandbox. Two other groups\n * of endpoints do not queue:\n *\n * - the content endpoints answer 400 \"Instance is not running\", or answer 2xx to\n * a write whose bytes never land (observed roughly once in twelve sandboxes);\n * - `updateSandbox` answers 400 \"Cannot update sandbox, operation in progress\".\n *\n * So those calls wait here for `RUNNING` + `setup_status: SUCCESS` once per\n * sandbox, and retry the two races until the deadline.\n */\n\nimport {\n getSandboxData,\n isInstanceNotRunning,\n isOperationInProgress,\n sleep,\n type BuddySandboxHandle,\n} from './utils.js';\n\n/** Long enough to cover a drained warm pool; a real boot failure surfaces sooner. */\nconst BOOT_WAIT_TIMEOUT_MS = 90_000;\nconst BOOT_WAIT_POLL_MS = 250;\n\n/** Sandboxes already known to have booted — the gate runs at most once each. */\nconst settled = new WeakSet<BuddySandboxHandle>();\n\nexport async function untilSettled(sandbox: BuddySandboxHandle): Promise<void> {\n if (settled.has(sandbox)) return;\n\n const deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await getSandboxData(sandbox.config, sandbox.sandboxId);\n if (data.status === 'RUNNING' && data.setup_status === 'SUCCESS') {\n settled.add(sandbox);\n return;\n }\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} failed to start ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandbox.sandboxId} was still starting after ` +\n `${BOOT_WAIT_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(BOOT_WAIT_POLL_MS);\n }\n}\n\n/**\n * Runs an operation once the sandbox has booted, retrying the races that remain\n * afterwards — Buddy reports a snapshot or app operation still in flight the\n * same way.\n */\nexport async function whenBooted<T>(\n sandbox: BuddySandboxHandle,\n operation: () => Promise<T>,\n): Promise<T> {\n await untilSettled(sandbox);\n return retryBootRaces(operation, Date.now() + BOOT_WAIT_TIMEOUT_MS);\n}\n\n/**\n * Retries `operation` while Buddy reports the sandbox as not running or busy,\n * without first polling the sandbox for `RUNNING`. For an endpoint that\n * answers in one round trip the failed attempt *is* the readiness check, so a\n * warm sandbox costs no extra request.\n */\nexport async function retryBootRaces<T>(\n operation: () => Promise<T>,\n deadline = Date.now() + BOOT_WAIT_TIMEOUT_MS,\n): Promise<T> {\n for (;;) {\n try {\n return await operation();\n } catch (error) {\n const retryable = isInstanceNotRunning(error) || isOperationInProgress(error);\n if (!retryable || Date.now() >= deadline) throw error;\n // The caller may have given up at the deadline, so never start another\n // attempt past it.\n await sleep(Math.min(BOOT_WAIT_POLL_MS, deadline - Date.now()));\n if (Date.now() >= deadline) throw error;\n }\n }\n}\n","/**\n * Command execution.\n *\n * Buddy has two ways to run a command:\n *\n * - `POST .../exec` runs it synchronously and answers with stdout, stderr and\n * the exit code in one round trip. It keeps no history, cannot stream and\n * cannot be interrupted. After 60 s the server stops waiting and answers\n * 400 without output or exit code; the process itself keeps running.\n * - `POST .../commands` accepts the command and returns its id immediately;\n * output arrives over a JSONL log stream. The provider consumes that stream\n * once through the SDK's `Command` entity, splits it into stdout/stderr and\n * forwards chunks to the streaming callbacks, then reads the exit code from\n * the command details. `Command.wait()` is deliberately unused — it polls\n * once a second, which would add up to a second to every call.\n *\n * A foreground call without streaming callbacks and without a `timeout` takes\n * the first route (one request instead of three). Anything else — callbacks,\n * `background`, any `timeout` — takes the second, where a timeout can kill the\n * command by its id.\n */\n\nimport { Command, type SandboxCommandResultView } from '@buddy-works/sandbox-sdk';\nimport { escapeShellArg } from '@computesdk/provider';\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\n\nimport { retryBootRaces } from './boot.js';\nimport {\n messageOf,\n sleep,\n statusOf,\n type BuddyCommandRuntime,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport interface BuddyRunCommandOptions extends RunCommandOptions {\n /**\n * Interpreter Buddy runs the command with. Defaults to `BASH`; the other\n * runtimes take a script instead of a shell line, so `cwd` and `env` do not\n * apply to them.\n */\n runtime?: BuddyCommandRuntime;\n}\n\n/** What a POSIX shell accepts as a variable name. */\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Prepends `cd` and `export` when the caller asked for a cwd or env. Values are\n * escaped; names cannot be, so a name that is not a valid identifier is\n * rejected instead of being spliced into the shell line.\n */\nexport function buildShellCommand(command: string, options: RunCommandOptions = {}): string {\n let line = command;\n\n if (options.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([key, value]) => {\n if (!ENV_NAME.test(key)) {\n throw new TypeError(\n `Invalid environment variable name ${JSON.stringify(key)}: `\n + 'names must match /^[A-Za-z_][A-Za-z0-9_]*$/.',\n );\n }\n return `${key}=\"${escapeShellArg(String(value))}\"`;\n })\n .join(' ');\n line = `export ${exports} && ${line}`;\n }\n if (options.cwd) {\n line = `cd \"${escapeShellArg(options.cwd)}\" && ${line}`;\n }\n return line;\n}\n\n/** A termination that fails leaves the command running remotely, so retry. */\nconst KILL_ATTEMPTS = 3;\nconst KILL_RETRY_DELAY_MS = 500;\n\n/** Best-effort kill: never throws, gives up after `KILL_ATTEMPTS`. */\nexport async function killCommand(running: Pick<Command, 'kill'>): Promise<boolean> {\n for (let attempt = 1; attempt <= KILL_ATTEMPTS; attempt++) {\n try {\n await running.kill();\n return true;\n } catch {\n if (attempt < KILL_ATTEMPTS) await sleep(KILL_RETRY_DELAY_MS);\n }\n }\n return false;\n}\n\nexport async function runCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n options: BuddyRunCommandOptions = {},\n): Promise<CommandResult> {\n // `ADD-PROVIDER.md` still documents an older `runCommand(command, args)`\n // shape. Called that way, the array arrives here as `options`, where only\n // `cwd` and `env` are read — the arguments would be dropped silently and the\n // bare command would still exit 0. Fail loudly instead.\n if (Array.isArray(options)) {\n throw new TypeError(\n `runCommand takes a command line and an options object, not an argument array. `\n + `Pass the arguments inside the command, e.g. '${command} ${options.join(' ')}'.`,\n );\n }\n\n const startedAt = Date.now();\n const runtime = options.runtime ?? 'BASH';\n const payload = runtime === 'BASH' ? buildShellCommand(command, options) : command;\n\n const deadline = options.timeout ? startedAt + options.timeout : undefined;\n const timedOutResult = (stdout = '', stderr = '') => ({\n stdout, stderr, exitCode: TIMEOUT_EXIT_CODE, durationMs: Date.now() - startedAt,\n });\n\n if (usesExec(options)) {\n // The exec endpoint rejects a booting sandbox instead of queueing, so the\n // 400 is retried. Exec has no command id to kill, which is why only untimed\n // calls come here; when the server gives up at its own limit, the process\n // is left running.\n let result: SandboxCommandResultView;\n try {\n result = await retryBootRaces(() => execCommand(sandbox, payload, runtime));\n } catch (error) {\n if (isExecTimeout(error)) return timedOutResult('', `${messageOf(error)}\\n`);\n throw error;\n }\n if (typeof result.exit_code !== 'number') {\n throw new Error('Buddy ran the command but returned no exit code.');\n }\n return {\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n exitCode: result.exit_code,\n durationMs: Date.now() - startedAt,\n };\n }\n\n // Buddy may hold the submission while the sandbox boots (up to the client's\n // request timeout), so the deadline applies here too: when it passes first,\n // the timeout result is returned and the command is killed once (if ever)\n // Buddy reports it accepted.\n const submission = sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command: payload, runtime },\n });\n const commandResponse = deadline ? await raceDeadline(submission, deadline) : await submission;\n if (commandResponse === DEADLINE_PASSED) {\n void submission.then(\n response => {\n if (!response.id) return;\n void killCommand(new Command({\n commandResponse: response,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n }));\n },\n () => {},\n );\n return timedOutResult();\n }\n\n const commandId = commandResponse.id;\n if (!commandId) {\n throw new Error('Buddy accepted the command but returned no command id.');\n }\n\n const running = new Command({\n commandResponse,\n client: sandbox.client,\n sandboxId: sandbox.sandboxId,\n });\n\n // Fire-and-forget: return as soon as Buddy has the command queued.\n if (options.background) {\n return { stdout: '', stderr: '', exitCode: 0, durationMs: Date.now() - startedAt };\n }\n\n const stdout: string[] = [];\n const stderr: string[] = [];\n\n // `follow: true` holds the connection open until the command exits, so this\n // loop is the wait — nothing is polled. Each record is one line without its\n // terminator, so the newline goes back on here. Once the caller has been\n // given the timeout result the loop stops at the next record instead of\n // buffering output and firing callbacks for a result nobody will read.\n let timedOut = false;\n const drain = (async () => {\n for await (const log of running.logs({ follow: true })) {\n if (timedOut) break;\n if (log.data == null) continue;\n const chunk = `${log.data}\\n`;\n if (log.type === 'STDERR') {\n stderr.push(chunk);\n options.onStderr?.(chunk);\n } else {\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n }\n })();\n\n // The SDK stream cannot be aborted, so on timeout the result is returned\n // right away — with whatever output arrived before the deadline — and the\n // reader is left to finish on its own once the kill (best effort, retried)\n // closes it or the next record arrives.\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n void killCommand(running);\n drain.catch(() => {});\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n } catch (error) {\n // The stream broke mid-command. Buddy keeps running it, so stop it — best\n // effort and not awaited, so a hanging kill cannot delay the error.\n void killCommand(running);\n throw error;\n }\n\n // The stream can close before Buddy records the result, so the deadline\n // governs the exit-code poll as well: past it, the caller gets the timeout\n // result and the command is stopped in case it is still running.\n const exit = waitForExitCode(sandbox, commandId);\n const exitCode = deadline ? await raceDeadline(exit, deadline) : await exit;\n if (exitCode === DEADLINE_PASSED) {\n exit.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''), stderr.join(''));\n }\n\n return {\n stdout: stdout.join(''),\n stderr: stderr.join(''),\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/** The server gave up waiting for an `exec` command at its own limit. */\nexport function isExecTimeout(error: unknown): boolean {\n return statusOf(error) === 400 && /did not finish on instance .* within \\d+s/i.test(messageOf(error));\n}\n\n/**\n * Foreground, no streaming callbacks and no `timeout`. Callbacks force the log\n * stream because exec only has the output once the command has finished; a\n * timeout needs a command id to kill, which exec does not return.\n */\nexport function usesExec(options: BuddyRunCommandOptions): boolean {\n return !options.background && !options.onStdout && !options.onStderr && !options.timeout;\n}\n\n/**\n * `POST /workspaces/{workspace}/sandboxes/{id}/exec`. The SDK client waits\n * just past the server's own limit, so the server decides the outcome.\n */\nfunction execCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<SandboxCommandResultView> {\n return sandbox.client.execCommand({\n body: { command, runtime },\n path: { sandbox_id: sandbox.sandboxId },\n });\n}\n\nconst DEADLINE_PASSED = Symbol('deadline passed');\n\n/** Resolves to `DEADLINE_PASSED` if `deadline` (epoch ms) arrives first. */\nasync function raceDeadline<T>(work: Promise<T>, deadline: number): Promise<T | typeof DEADLINE_PASSED> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expiry = new Promise<typeof DEADLINE_PASSED>(resolve => {\n timer = setTimeout(() => resolve(DEADLINE_PASSED), Math.max(0, deadline - Date.now()));\n });\n try {\n return await Promise.race([work, expiry]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** The exit code `timeout(1)` uses for a killed command; reported for every timeout. */\nexport const TIMEOUT_EXIT_CODE = 124;\n\nconst EXIT_CODE_WAIT_MS = 5_000;\nconst EXIT_CODE_POLL_MS = 200;\n\nexport interface BuddyCommandDetails {\n exit_code?: number;\n status?: string;\n}\n\n/**\n * The log stream can close a moment before Buddy records the result, so the\n * details may still say `INPROGRESS` without an `exit_code`. Treating that as\n * success would hide failures; poll briefly until a terminal state shows up.\n */\nexport async function waitForExitCode(\n sandbox: Pick<BuddySandboxHandle, 'client' | 'sandboxId'>,\n commandId: string,\n deadlineMs = EXIT_CODE_WAIT_MS,\n): Promise<number> {\n const deadline = Date.now() + deadlineMs;\n for (;;) {\n const details: BuddyCommandDetails = await sandbox.client.getCommandDetails({\n path: { sandbox_id: sandbox.sandboxId, id: commandId },\n });\n if (typeof details.exit_code === 'number') return details.exit_code;\n if (details.status === 'FAILED') return 1;\n if (details.status === 'SUCCESSFUL') return 0;\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy command ${commandId} on sandbox ${sandbox.sandboxId} reported no exit code `\n + `within ${deadlineMs / 1000}s of its log stream closing (status: ${details.status ?? 'unknown'}).`,\n );\n }\n await new Promise(resolve => setTimeout(resolve, EXIT_CODE_POLL_MS));\n }\n}\n","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — one round trip per operation and binary-safe, unlike shelling out\n * to `cat`/`tee`.\n *\n * Every call goes through the boot gate in `boot.ts`, because unlike commands\n * these endpoints do not queue against a sandbox that is still starting.\n */\n\nimport type { FileEntry } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n toContentPath,\n type BuddySandboxHandle,\n} from './utils.js';\n\nexport async function readFile(sandbox: BuddySandboxHandle, path: string): Promise<string> {\n const target = normalizeSandboxPath(path);\n const buffer = await whenBooted(sandbox, () => sandbox.fs.downloadFile(target));\n return buffer.toString('utf-8');\n}\n\nexport async function writeFile(\n sandbox: BuddySandboxHandle,\n path: string,\n content: string,\n): Promise<void> {\n const target = normalizeSandboxPath(path);\n const parent = target.slice(0, target.lastIndexOf('/'));\n\n await whenBooted(sandbox, async () => {\n // Buddy will not create missing parents for an upload, and mirroring\n // `fs.writeFile` here is what callers expect.\n if (parent) {\n await sandbox.fs.createFolder(parent).catch(() => {});\n }\n await sandbox.fs.uploadFile(Buffer.from(content, 'utf-8'), target);\n });\n}\n\nexport async function mkdir(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n await whenBooted(sandbox, () => sandbox.fs.createFolder(target));\n}\n\nexport async function readdir(sandbox: BuddySandboxHandle, path: string): Promise<FileEntry[]> {\n const target = normalizeSandboxPath(path);\n const entries = await whenBooted(sandbox, () => sandbox.fs.listFiles(target));\n\n return entries.map(entry => ({\n name: entry.name ?? '',\n type: entry.type === 'DIR' ? 'directory' as const : 'file' as const,\n // The API reports sizes as bigint; ComputeSDK wants a number.\n ...(entry.size == null ? {} : { size: Number(entry.size) }),\n }));\n}\n\nexport async function exists(sandbox: BuddySandboxHandle, path: string): Promise<boolean> {\n const target = toContentPath(path);\n try {\n await whenBooted(sandbox, () =>\n sandbox.client.getSandboxContent({ path: { sandbox_id: sandbox.sandboxId, path: target } }));\n return true;\n } catch (error) {\n if (isNotFound(error)) return false;\n throw error;\n }\n}\n\nexport async function remove(sandbox: BuddySandboxHandle, path: string): Promise<void> {\n const target = normalizeSandboxPath(path);\n try {\n await whenBooted(sandbox, () => sandbox.fs.deleteFile(target));\n } catch (error) {\n // Removing something that is already gone is not an error for callers.\n if (!isNotFound(error)) throw error;\n }\n}\n","/**\n * Snapshots — filesystem images of a sandbox that a new sandbox can boot from.\n *\n * Buddy creates them asynchronously: the create call returns `status: CREATING`\n * and the snapshot cannot be restored until it turns `CREATED`. The provider\n * waits for that here so callers get a snapshot they can actually use. The\n * wait uses a 500 ms poll rather than the SDK entity's 2 s one, because typical\n * snapshots settle in well under a second.\n */\n\nimport type { CreateSnapshotOptions, ListSnapshotsOptions } from '@computesdk/provider';\nimport type { Snapshot } from 'computesdk';\n\nimport {\n PROVIDER,\n getClient,\n isNotFound,\n sleep,\n toIdentifier,\n type ResolvedBuddyConfig,\n} from './utils.js';\n\nconst SNAPSHOT_WAIT_TIMEOUT_MS = 180_000;\nconst SNAPSHOT_WAIT_POLL_MS = 500;\n\ninterface BuddySnapshotData {\n id?: string;\n name?: string;\n size?: number;\n status?: string;\n create_date?: Date | string;\n}\n\nfunction toSnapshot(data: BuddySnapshotData, sandboxId?: string): Snapshot {\n if (!data.id) {\n throw new Error('Buddy API returned a snapshot without an id.');\n }\n return {\n id: data.id,\n provider: PROVIDER,\n createdAt: data.create_date ? new Date(data.create_date) : new Date(),\n metadata: {\n name: data.name,\n status: data.status,\n sizeGb: data.size,\n ...(sandboxId ? { sandboxId } : {}),\n },\n };\n}\n\nexport async function createSnapshot(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n options: CreateSnapshotOptions = {},\n): Promise<Snapshot> {\n const client = getClient(config);\n const created = await client.addSandboxSnapshot({\n path: { sandbox_id: sandboxId },\n body: { name: toIdentifier(options.name ?? `computesdk-${Date.now()}`) },\n });\n\n const snapshotId = created.id;\n if (!snapshotId) {\n throw new Error('Buddy accepted the snapshot but returned no snapshot id.');\n }\n\n const ready = await waitUntilCreated(config, sandboxId, snapshotId, created);\n return toSnapshot(ready, sandboxId);\n}\n\nasync function waitUntilCreated(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n snapshotId: string,\n initial: BuddySnapshotData,\n): Promise<BuddySnapshotData> {\n if (initial.status === 'CREATED') return initial;\n\n const client = getClient(config);\n const deadline = Date.now() + SNAPSHOT_WAIT_TIMEOUT_MS;\n for (;;) {\n const data = await client.getSandboxSnapshot({\n path: { sandbox_id: sandboxId, id: snapshotId },\n }) as BuddySnapshotData;\n\n if (data.status === 'CREATED') return data;\n if (data.status === 'FAILED') {\n throw new Error(`Buddy snapshot ${snapshotId} failed to be created.`);\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy snapshot ${snapshotId} was still ${data.status} after ` +\n `${SNAPSHOT_WAIT_TIMEOUT_MS / 1000}s.`,\n );\n }\n await sleep(SNAPSHOT_WAIT_POLL_MS);\n }\n}\n\nexport async function listSnapshots(\n config: ResolvedBuddyConfig,\n options: ListSnapshotsOptions = {},\n): Promise<Snapshot[]> {\n const client = getClient(config);\n // Default to the project-wide listing: snapshots outlive the sandbox they were\n // taken from, so the per-sandbox endpoint would hide most of them.\n const response = options.sandboxId\n ? await client.getSandboxSnapshots({ path: { sandbox_id: options.sandboxId } })\n : await client.getProjectSnapshots({});\n\n const snapshots = (response.snapshots ?? [])\n .map(snapshot => toSnapshot(snapshot as BuddySnapshotData, options.sandboxId));\n return options.limit ? snapshots.slice(0, options.limit) : snapshots;\n}\n\nexport async function deleteSnapshot(\n config: ResolvedBuddyConfig,\n snapshotId: string,\n): Promise<void> {\n try {\n await getClient(config).deleteSnapshot({ path: { id: snapshotId } });\n } catch (error) {\n // Deleting an already-deleted snapshot is the state the caller wanted.\n if (!isNotFound(error)) throw error;\n }\n}\n"],"mappings":";AAcA,SAAS,sBAAsB;;;ACH/B,SAAS,UAAU,gBAAgB,kBAAkB;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,iBAA8B;AAEpC,IAAM,qBAAqB;AAE3B,IAAM,eAAe;AAsBrB,IAAM,UAAU;AAmDvB,IAAM,aACJ;AAIK,SAAS,gBAAgB,QAA6B;AAC3D,SAAO,SAAS,MAAM;AACxB;AASA,IAAM,WAAW,oBAAI,QAA0C;AAM/D,IAAM,kBAAkB,oBAAI,IAAiC;AAEtD,SAAS,cAAc,QAA2C;AACvE,MAAI,CAAC,QAAQ;AACX,UAAM,MAAM;AAAA,MACV,QAAQ,IAAI;AAAA,MAAa,QAAQ,IAAI;AAAA,MAAiB,QAAQ,IAAI;AAAA,IACpE,EAAE,KAAK,IAAQ;AACf,QAAIA,SAAQ,gBAAgB,IAAI,GAAG;AACnC,QAAI,CAACA,QAAO;AACV,MAAAA,SAAQ,YAAY,CAAC,CAAC;AACtB,sBAAgB,MAAM;AACtB,sBAAgB,IAAI,KAAKA,MAAK;AAAA,IAChC;AACA,WAAOA;AAAA,EACT;AACA,QAAM,SAAS,SAAS,IAAI,MAAM;AAClC,MAAI,OAAQ,QAAO;AACnB,QAAM,QAAQ,YAAY,MAAM;AAChC,WAAS,IAAI,QAAQ,KAAK;AAC1B,SAAO;AACT;AAEA,SAAS,YAAY,QAA0C;AAC7D,QAAM,QAAQ,OAAO,SAAS,QAAQ,IAAI;AAC1C,QAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAClD,QAAM,UAAU,OAAO,WAAW,QAAQ,IAAI;AAE9C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA;AAAA,EACG,UAAU;AAAA;AAAA;AAAA,IAGf;AAAA,EACF;AACA,MAAI,CAAC,WAAW;AACd,UAAM,I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AAM;AAGtD,QAAM,OAAO,QAAQ,UAClB,OAAO,cAAY,CAAC,oBAAoB,UAAU,IAAI,CAAC,EACvD,IAAI,gBAAgB;AAGvB,QAAM,UAAU,MAAM,WAAW,SAAS,MAAM,QAAQ,OAAO,cAAc;AAAA,IAC3E,MAAM,EAAE,IAAI,QAAQ,UAAU;AAAA,IAC9B,MAAM,EAAE,WAAW,CAAC,GAAG,MAAM,kBAAkB,OAAO,CAAC,EAAE;AAAA,EAC3D,CAAC,CAAC;AACF,UAAQ,YAAa,QAAQ,aAAa,QAAQ;AAElD,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,aAAS;AACP,UAAM,MAAM,MAAM,gBAAgB,SAAS,IAAI;AAC/C,QAAI,IAAK,QAAO,cAAc,KAAK,QAAQ;AAC3C,QAAI,KAAK,IAAI,KAAK,UAAU;AAC1B,YAAM,IAAI;AAAA,QACR,iCAAiC,IAAI,eAAe,QAAQ,SAAS,uCAC/B,sBAAsB,GAAI;AAAA,MAClE;AAAA,IACF;AACA,UAAM,MAAM,gBAAgB;AAAA,EAC9B;AACF;AAEA,eAAe,gBACb,SACA,MAC6B;AAC7B,QAAM,OAAO,MAAM,eAAe,QAAQ,QAAQ,QAAQ,SAAS;AACnE,UAAQ,YAAY,KAAK,aAAa,CAAC;AACvC,QAAM,QAAQ,QAAQ,UAAU,KAAK,cAAY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["value","stdout","stderr","resolved"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@computesdk/buddy",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.9",
|
|
4
4
|
"description": "Buddy provider for ComputeSDK - Persistent Ubuntu sandboxes for agents, booting in milliseconds, with preview URLs and snapshots",
|
|
5
5
|
"author": "Lucas Czulak",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@buddy-works/sandbox-sdk": "^0.1.
|
|
21
|
+
"@buddy-works/sandbox-sdk": "^0.1.10",
|
|
22
22
|
"computesdk": "4.1.10",
|
|
23
23
|
"@computesdk/provider": "2.1.11"
|
|
24
24
|
},
|