@computesdk/buddy 1.0.32 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -160,6 +160,7 @@ declare const BUDDY_DISK_MIB: number;
160
160
  declare const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>>;
161
161
  declare const buddy: (config: BuddyConfig & computesdk.ProcessRuntimeOptions) => computesdk.Provider<BuddySandboxHandle, any, Snapshot, computesdk.Volume> & {
162
162
  readonly sizes: computesdk.InstanceSizeManager;
163
+ readonly regions: computesdk.RegionManager;
163
164
  };
164
165
  /** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */
165
166
  declare function toSeconds(ms: number): number;
package/dist/index.d.ts CHANGED
@@ -160,6 +160,7 @@ declare const BUDDY_DISK_MIB: number;
160
160
  declare const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>>;
161
161
  declare const buddy: (config: BuddyConfig & computesdk.ProcessRuntimeOptions) => computesdk.Provider<BuddySandboxHandle, any, Snapshot, computesdk.Volume> & {
162
162
  readonly sizes: computesdk.InstanceSizeManager;
163
+ readonly regions: computesdk.RegionManager;
163
164
  };
164
165
  /** Buddy takes whole seconds; rounding up keeps the sandbox alive at least as long as asked. */
165
166
  declare function toSeconds(ms: number): number;
package/dist/index.js CHANGED
@@ -702,6 +702,12 @@ var BUDDY_SIZE_PRESETS = Object.freeze({
702
702
  });
703
703
  var buddy = (0, import_provider3.defineProvider)({
704
704
  name: PROVIDER,
705
+ regions: {
706
+ support: (config) => ({
707
+ placement: "per-account",
708
+ regions: (config.apiUrl?.replace(/\/+$/, "") ?? apiUrlForRegion(config.region ?? "US")) === apiUrlForRegion("US") ? { us: ["US"] } : {}
709
+ })
710
+ },
705
711
  // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,
706
712
  // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.
707
713
  sizes: (_config, profile) => {
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. `pause()`/`resume()` stop a sandbox and start the same one again\n * (also reachable as `stop()`/`start()` on `getInstance()`).\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateInstanceOptions,\n InstanceSizeClass,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n InstanceInfo,\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 BuddyResources,\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\n/** Buddy gives every sandbox a 50 GB disk; it is not configurable. */\nexport const BUDDY_DISK_MIB = 50 * 1024;\n\n/**\n * Smallest `resources` preset (`{vCPU}x{RAM GB}`, 1x2 through 12x24) whose vCPU\n * puts it in each standard size. `xs` takes 1x2 (extra RAM); 12x24 has too few\n * vCPU for `2xl`.\n */\nexport const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>> = Object.freeze({\n xs: '1x2',\n sm: '1x2',\n md: '2x4',\n lg: '4x8',\n xl: '8x16',\n});\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,\n // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.\n sizes: (_config, profile) => {\n const preset = BUDDY_SIZE_PRESETS[profile.sizeClass];\n if (!preset) {\n return {\n status: 'unsupported',\n reason: `Buddy's largest preset is 12x24 (12 vCPU / 24 GB RAM), below ${profile.sizeClass} (${profile.vcpus} vCPU / ${profile.memoryMiB} MiB).`,\n };\n }\n const [vcpus, memoryGb] = preset.split('x').map(Number);\n return {\n status: 'supported',\n nativeOptions: { resources: preset },\n resolved: { vcpus, memoryMiB: memoryGb * 1024, diskMiB: BUDDY_DISK_MIB },\n };\n },\n\n methods: {\n instances: {\n create: async (config: BuddyConfig, options?: CreateInstanceOptions) => {\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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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<InstanceInfo> => {\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 // Stop/start under the same id. The disk survives except `/tmp`, which\n // is cleared on boot; running processes do not.\n pause: (sandbox: BuddySandboxHandle) => sandbox.stop(),\n resume: (sandbox: BuddySandboxHandle) => sandbox.start(),\n pauseCapabilities: { memory: false },\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 // A restore boots a new sandbox from the whole root disk; processes and\n // the `/dev/shm` tmpfs are not kept. The source keeps running.\n capabilities: { scope: 'rootfs', memory: false, destroysSource: false },\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: CreateInstanceOptions = {}) {\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 * Stops the sandbox and resolves once Buddy reports `STOPPED`. The disk is\n * kept (except `/tmp`, which is cleared on boot); running processes are not.\n */\n stop(): Promise<void>;\n /** Starts a stopped sandbox under the same id and resolves once it is ready. */\n start(): Promise<void>;\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 `InstanceInfo.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 stop: () => stopSandbox(config, sandboxId),\n start: () => startSandbox(config, sandboxId),\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/** Measured at ~1 s to stop and ~3 s to start; the margin covers a busy pool. */\nconst LIFECYCLE_TIMEOUT_MS = 120_000;\nconst LIFECYCLE_POLL_MS = 250;\n\nconst isStopped = (data: BuddySandboxData) => data.status === 'STOPPED';\nconst isReady = (data: BuddySandboxData) =>\n data.status === 'RUNNING' && data.setup_status === 'SUCCESS';\n\n/**\n * Buddy's start and stop endpoints return as soon as the transition is\n * accepted, so both are followed by a poll for the target state. A sandbox\n * already in that state is left alone, and an operation still in flight (a\n * boot, a snapshot) is retried until it clears.\n */\nasync function transition(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n verb: 'start' | 'stop',\n reached: (data: BuddySandboxData) => boolean,\n): Promise<void> {\n const client = getClient(config);\n const deadline = Date.now() + LIFECYCLE_TIMEOUT_MS;\n let data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n\n for (;;) {\n try {\n const path = { path: { sandbox_id: sandboxId } };\n await (verb === 'stop' ? client.stopSandbox(path) : client.startSandbox(path));\n break;\n } catch (error) {\n if (!isOperationInProgress(error) || Date.now() >= deadline) throw error;\n await sleep(LIFECYCLE_POLL_MS);\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n }\n }\n\n for (;;) {\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandboxId} failed to ${verb} ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandboxId} did not ${verb} within ` +\n `${LIFECYCLE_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(LIFECYCLE_POLL_MS);\n }\n}\n\nexport function stopSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'stop', isStopped);\n}\n\nexport function startSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'start', isReady);\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 // The caller may have given up at the deadline, so never start another\n // attempt past it. Timers can fire a millisecond early, so a retry is\n // only made when a whole poll interval still fits.\n if (!retryable || deadline - Date.now() < BOOT_WAIT_POLL_MS) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\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 .../execs` accepts the command and returns its execution id\n * immediately. The SDK's `Command` entity reads the log page by page and in\n * between lets the API hold a status request until the command finishes, so\n * nothing is polled on a fixed interval. The log does not tell stdout from\n * stderr: every line is reported as stdout. Buddy runs at most 3 such\n * commands at once per member in one sandbox and 10 per workspace, and stops\n * each one after 90 minutes.\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 ExecView, 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 = retryBootRaces(\n () => submitCommand(sandbox, payload, runtime),\n deadline,\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.execution_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 if (!commandResponse.execution_id) {\n throw new Error('Buddy accepted the command but returned no execution 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\n // `follow: true` reads until the command has finished, so this loop is the\n // wait; `wait()` afterwards only returns the final state the loop already\n // saw. Each line comes without its terminator, so the newline goes back on\n // here. Aborting at the deadline stops the SDK's requests; the flag stops\n // the loop from firing callbacks for a result nobody will read.\n const abort = new AbortController();\n let timedOut = false;\n const drain = (async () => {\n for await (const line of running.logs({ follow: true, signal: abort.signal })) {\n if (timedOut) break;\n const chunk = `${line}\\n`;\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n return running.wait({ signal: abort.signal });\n })();\n\n let finished: Command;\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n abort.abort();\n drain.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''));\n }\n finished = outcome;\n } catch (error) {\n // Reading the log or the status broke mid-command. Buddy keeps running it,\n // so stop it — best effort and not awaited, so a hanging kill cannot delay\n // the error.\n void killCommand(running);\n throw error;\n }\n\n const { exitCode, message } = outcomeOf(finished.data);\n return {\n stdout: stdout.join(''),\n stderr: message ? `${message}\\n` : '',\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/**\n * `POST .../execs`. Over Buddy's concurrency limit the API answers 409; that\n * becomes an error saying what to do about it instead of a bare HTTP status.\n */\nasync function submitCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<ExecView> {\n try {\n return await sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command, runtime },\n });\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n throw new Error(\n `Buddy refused to start the command on sandbox ${sandbox.sandboxId}: too many commands `\n + 'are running (at most 3 per member in one sandbox and 10 per workspace). '\n + `Retry once one of them finishes. (${messageOf(error)})`,\n );\n }\n}\n\n/**\n * The exit code of a finished command. A command Buddy failed or cancelled\n * without an exit code — e.g. stopped at the 90-minute limit — counts as a\n * failure, with Buddy's explanation as the message.\n */\nexport function outcomeOf(view: ExecView): { exitCode: number; message?: string } {\n if (typeof view.exit_code === 'number') return { exitCode: view.exit_code };\n if (view.status === 'SUCCESSFUL') return { exitCode: 0 };\n const reason = view.error_message ?? view.failure_reason;\n return {\n exitCode: 1,\n message: `Buddy command ${view.execution_id ?? ''} ended ${view.status ?? 'without a status'}`\n + (reason ? `: ${reason}` : ' without an exit code'),\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","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — binary-safe, unlike shelling out to `cat`/`tee`. Reads first\n * resolve links because Buddy downloads a link's target path, not its bytes.\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';\nimport { escapeShellArg } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport { runCommand } from './commands.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n statusOf,\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, async () => {\n const resolved = await runCommand(sandbox, `readlink -e -z -- \"${escapeShellArg(target)}\"`);\n if (resolved.exitCode !== 0) {\n throw new Error(`Failed to resolve file ${target}: ${resolved.stderr || 'path is missing or inaccessible'}`);\n }\n const output = resolved.stdout;\n if (!output.startsWith('/') || !output.endsWith('\\0') || output.indexOf('\\0') !== output.length - 1) {\n throw new Error(`Buddy returned an invalid resolved path for ${target}.`);\n }\n return sandbox.fs.downloadFile(normalizeSandboxPath(output.slice(0, -1)));\n });\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 createFolder(sandbox, parent);\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, () => createFolder(sandbox, target));\n}\n\nasync function createFolder(sandbox: BuddySandboxHandle, target: string): Promise<void> {\n try {\n await sandbox.fs.createFolder(target);\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n const separator = target.lastIndexOf('/');\n const entries = await sandbox.fs.listFiles(target.slice(0, separator) || '/');\n if (!entries.some(entry => entry.name === target.slice(separator + 1) && entry.type === 'DIR')) {\n throw error;\n }\n }\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;AAAA;AAAA;AAeA,IAAAA,mBAA+B;;;ACJ/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,QAAQ,IAAI;AAE9C,MAAI,CAAC,OAAO;AACV,UAAM,IAA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KAAK,cAAY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["import_provider","value","import_sandbox_sdk","exports","stdout","import_provider","resolved","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. `pause()`/`resume()` stop a sandbox and start the same one again\n * (also reachable as `stop()`/`start()` on `getInstance()`).\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateInstanceOptions,\n InstanceSizeClass,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n InstanceInfo,\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 apiUrlForRegion,\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 BuddyResources,\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\n/** Buddy gives every sandbox a 50 GB disk; it is not configurable. */\nexport const BUDDY_DISK_MIB = 50 * 1024;\n\n/**\n * Smallest `resources` preset (`{vCPU}x{RAM GB}`, 1x2 through 12x24) whose vCPU\n * puts it in each standard size. `xs` takes 1x2 (extra RAM); 12x24 has too few\n * vCPU for `2xl`.\n */\nexport const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>> = Object.freeze({\n xs: '1x2',\n sm: '1x2',\n md: '2x4',\n lg: '4x8',\n xl: '8x16',\n});\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n regions: {\n support: config => ({\n placement: 'per-account',\n regions: (config.apiUrl?.replace(/\\/+$/, '') ?? apiUrlForRegion(config.region ?? 'US')) === apiUrlForRegion('US')\n ? { us: ['US'] }\n : {},\n }),\n },\n\n // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,\n // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.\n sizes: (_config, profile) => {\n const preset = BUDDY_SIZE_PRESETS[profile.sizeClass];\n if (!preset) {\n return {\n status: 'unsupported',\n reason: `Buddy's largest preset is 12x24 (12 vCPU / 24 GB RAM), below ${profile.sizeClass} (${profile.vcpus} vCPU / ${profile.memoryMiB} MiB).`,\n };\n }\n const [vcpus, memoryGb] = preset.split('x').map(Number);\n return {\n status: 'supported',\n nativeOptions: { resources: preset },\n resolved: { vcpus, memoryMiB: memoryGb * 1024, diskMiB: BUDDY_DISK_MIB },\n };\n },\n\n methods: {\n instances: {\n create: async (config: BuddyConfig, options?: CreateInstanceOptions) => {\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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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<InstanceInfo> => {\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 // Stop/start under the same id. The disk survives except `/tmp`, which\n // is cleared on boot; running processes do not.\n pause: (sandbox: BuddySandboxHandle) => sandbox.stop(),\n resume: (sandbox: BuddySandboxHandle) => sandbox.start(),\n pauseCapabilities: { memory: false },\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 // A restore boots a new sandbox from the whole root disk; processes and\n // the `/dev/shm` tmpfs are not kept. The source keeps running.\n capabilities: { scope: 'rootfs', memory: false, destroysSource: false },\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: CreateInstanceOptions = {}) {\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 * Stops the sandbox and resolves once Buddy reports `STOPPED`. The disk is\n * kept (except `/tmp`, which is cleared on boot); running processes are not.\n */\n stop(): Promise<void>;\n /** Starts a stopped sandbox under the same id and resolves once it is ready. */\n start(): Promise<void>;\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 `InstanceInfo.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 stop: () => stopSandbox(config, sandboxId),\n start: () => startSandbox(config, sandboxId),\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/** Measured at ~1 s to stop and ~3 s to start; the margin covers a busy pool. */\nconst LIFECYCLE_TIMEOUT_MS = 120_000;\nconst LIFECYCLE_POLL_MS = 250;\n\nconst isStopped = (data: BuddySandboxData) => data.status === 'STOPPED';\nconst isReady = (data: BuddySandboxData) =>\n data.status === 'RUNNING' && data.setup_status === 'SUCCESS';\n\n/**\n * Buddy's start and stop endpoints return as soon as the transition is\n * accepted, so both are followed by a poll for the target state. A sandbox\n * already in that state is left alone, and an operation still in flight (a\n * boot, a snapshot) is retried until it clears.\n */\nasync function transition(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n verb: 'start' | 'stop',\n reached: (data: BuddySandboxData) => boolean,\n): Promise<void> {\n const client = getClient(config);\n const deadline = Date.now() + LIFECYCLE_TIMEOUT_MS;\n let data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n\n for (;;) {\n try {\n const path = { path: { sandbox_id: sandboxId } };\n await (verb === 'stop' ? client.stopSandbox(path) : client.startSandbox(path));\n break;\n } catch (error) {\n if (!isOperationInProgress(error) || Date.now() >= deadline) throw error;\n await sleep(LIFECYCLE_POLL_MS);\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n }\n }\n\n for (;;) {\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandboxId} failed to ${verb} ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandboxId} did not ${verb} within ` +\n `${LIFECYCLE_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(LIFECYCLE_POLL_MS);\n }\n}\n\nexport function stopSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'stop', isStopped);\n}\n\nexport function startSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'start', isReady);\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 // The caller may have given up at the deadline, so never start another\n // attempt past it. Timers can fire a millisecond early, so a retry is\n // only made when a whole poll interval still fits.\n if (!retryable || deadline - Date.now() < BOOT_WAIT_POLL_MS) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\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 .../execs` accepts the command and returns its execution id\n * immediately. The SDK's `Command` entity reads the log page by page and in\n * between lets the API hold a status request until the command finishes, so\n * nothing is polled on a fixed interval. The log does not tell stdout from\n * stderr: every line is reported as stdout. Buddy runs at most 3 such\n * commands at once per member in one sandbox and 10 per workspace, and stops\n * each one after 90 minutes.\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 ExecView, 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 = retryBootRaces(\n () => submitCommand(sandbox, payload, runtime),\n deadline,\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.execution_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 if (!commandResponse.execution_id) {\n throw new Error('Buddy accepted the command but returned no execution 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\n // `follow: true` reads until the command has finished, so this loop is the\n // wait; `wait()` afterwards only returns the final state the loop already\n // saw. Each line comes without its terminator, so the newline goes back on\n // here. Aborting at the deadline stops the SDK's requests; the flag stops\n // the loop from firing callbacks for a result nobody will read.\n const abort = new AbortController();\n let timedOut = false;\n const drain = (async () => {\n for await (const line of running.logs({ follow: true, signal: abort.signal })) {\n if (timedOut) break;\n const chunk = `${line}\\n`;\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n return running.wait({ signal: abort.signal });\n })();\n\n let finished: Command;\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n abort.abort();\n drain.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''));\n }\n finished = outcome;\n } catch (error) {\n // Reading the log or the status broke mid-command. Buddy keeps running it,\n // so stop it — best effort and not awaited, so a hanging kill cannot delay\n // the error.\n void killCommand(running);\n throw error;\n }\n\n const { exitCode, message } = outcomeOf(finished.data);\n return {\n stdout: stdout.join(''),\n stderr: message ? `${message}\\n` : '',\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/**\n * `POST .../execs`. Over Buddy's concurrency limit the API answers 409; that\n * becomes an error saying what to do about it instead of a bare HTTP status.\n */\nasync function submitCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<ExecView> {\n try {\n return await sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command, runtime },\n });\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n throw new Error(\n `Buddy refused to start the command on sandbox ${sandbox.sandboxId}: too many commands `\n + 'are running (at most 3 per member in one sandbox and 10 per workspace). '\n + `Retry once one of them finishes. (${messageOf(error)})`,\n );\n }\n}\n\n/**\n * The exit code of a finished command. A command Buddy failed or cancelled\n * without an exit code — e.g. stopped at the 90-minute limit — counts as a\n * failure, with Buddy's explanation as the message.\n */\nexport function outcomeOf(view: ExecView): { exitCode: number; message?: string } {\n if (typeof view.exit_code === 'number') return { exitCode: view.exit_code };\n if (view.status === 'SUCCESSFUL') return { exitCode: 0 };\n const reason = view.error_message ?? view.failure_reason;\n return {\n exitCode: 1,\n message: `Buddy command ${view.execution_id ?? ''} ended ${view.status ?? 'without a status'}`\n + (reason ? `: ${reason}` : ' without an exit code'),\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","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — binary-safe, unlike shelling out to `cat`/`tee`. Reads first\n * resolve links because Buddy downloads a link's target path, not its bytes.\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';\nimport { escapeShellArg } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport { runCommand } from './commands.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n statusOf,\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, async () => {\n const resolved = await runCommand(sandbox, `readlink -e -z -- \"${escapeShellArg(target)}\"`);\n if (resolved.exitCode !== 0) {\n throw new Error(`Failed to resolve file ${target}: ${resolved.stderr || 'path is missing or inaccessible'}`);\n }\n const output = resolved.stdout;\n if (!output.startsWith('/') || !output.endsWith('\\0') || output.indexOf('\\0') !== output.length - 1) {\n throw new Error(`Buddy returned an invalid resolved path for ${target}.`);\n }\n return sandbox.fs.downloadFile(normalizeSandboxPath(output.slice(0, -1)));\n });\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 createFolder(sandbox, parent);\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, () => createFolder(sandbox, target));\n}\n\nasync function createFolder(sandbox: BuddySandboxHandle, target: string): Promise<void> {\n try {\n await sandbox.fs.createFolder(target);\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n const separator = target.lastIndexOf('/');\n const entries = await sandbox.fs.listFiles(target.slice(0, separator) || '/');\n if (!entries.some(entry => entry.name === target.slice(separator + 1) && entry.type === 'DIR')) {\n throw error;\n }\n }\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;AAAA;AAAA;AAeA,IAAAA,mBAA+B;;;ACJ/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;A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9B,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","import_provider","resolved","resolved"]}
package/dist/index.mjs CHANGED
@@ -673,6 +673,12 @@ var BUDDY_SIZE_PRESETS = Object.freeze({
673
673
  });
674
674
  var buddy = defineProvider({
675
675
  name: PROVIDER,
676
+ regions: {
677
+ support: (config) => ({
678
+ placement: "per-account",
679
+ regions: (config.apiUrl?.replace(/\/+$/, "") ?? apiUrlForRegion(config.region ?? "US")) === apiUrlForRegion("US") ? { us: ["US"] } : {}
680
+ })
681
+ },
676
682
  // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,
677
683
  // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.
678
684
  sizes: (_config, profile) => {
@@ -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. `pause()`/`resume()` stop a sandbox and start the same one again\n * (also reachable as `stop()`/`start()` on `getInstance()`).\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateInstanceOptions,\n InstanceSizeClass,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n InstanceInfo,\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 BuddyResources,\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\n/** Buddy gives every sandbox a 50 GB disk; it is not configurable. */\nexport const BUDDY_DISK_MIB = 50 * 1024;\n\n/**\n * Smallest `resources` preset (`{vCPU}x{RAM GB}`, 1x2 through 12x24) whose vCPU\n * puts it in each standard size. `xs` takes 1x2 (extra RAM); 12x24 has too few\n * vCPU for `2xl`.\n */\nexport const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>> = Object.freeze({\n xs: '1x2',\n sm: '1x2',\n md: '2x4',\n lg: '4x8',\n xl: '8x16',\n});\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n\n // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,\n // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.\n sizes: (_config, profile) => {\n const preset = BUDDY_SIZE_PRESETS[profile.sizeClass];\n if (!preset) {\n return {\n status: 'unsupported',\n reason: `Buddy's largest preset is 12x24 (12 vCPU / 24 GB RAM), below ${profile.sizeClass} (${profile.vcpus} vCPU / ${profile.memoryMiB} MiB).`,\n };\n }\n const [vcpus, memoryGb] = preset.split('x').map(Number);\n return {\n status: 'supported',\n nativeOptions: { resources: preset },\n resolved: { vcpus, memoryMiB: memoryGb * 1024, diskMiB: BUDDY_DISK_MIB },\n };\n },\n\n methods: {\n instances: {\n create: async (config: BuddyConfig, options?: CreateInstanceOptions) => {\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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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<InstanceInfo> => {\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 // Stop/start under the same id. The disk survives except `/tmp`, which\n // is cleared on boot; running processes do not.\n pause: (sandbox: BuddySandboxHandle) => sandbox.stop(),\n resume: (sandbox: BuddySandboxHandle) => sandbox.start(),\n pauseCapabilities: { memory: false },\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 // A restore boots a new sandbox from the whole root disk; processes and\n // the `/dev/shm` tmpfs are not kept. The source keeps running.\n capabilities: { scope: 'rootfs', memory: false, destroysSource: false },\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: CreateInstanceOptions = {}) {\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 * Stops the sandbox and resolves once Buddy reports `STOPPED`. The disk is\n * kept (except `/tmp`, which is cleared on boot); running processes are not.\n */\n stop(): Promise<void>;\n /** Starts a stopped sandbox under the same id and resolves once it is ready. */\n start(): Promise<void>;\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 `InstanceInfo.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 stop: () => stopSandbox(config, sandboxId),\n start: () => startSandbox(config, sandboxId),\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/** Measured at ~1 s to stop and ~3 s to start; the margin covers a busy pool. */\nconst LIFECYCLE_TIMEOUT_MS = 120_000;\nconst LIFECYCLE_POLL_MS = 250;\n\nconst isStopped = (data: BuddySandboxData) => data.status === 'STOPPED';\nconst isReady = (data: BuddySandboxData) =>\n data.status === 'RUNNING' && data.setup_status === 'SUCCESS';\n\n/**\n * Buddy's start and stop endpoints return as soon as the transition is\n * accepted, so both are followed by a poll for the target state. A sandbox\n * already in that state is left alone, and an operation still in flight (a\n * boot, a snapshot) is retried until it clears.\n */\nasync function transition(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n verb: 'start' | 'stop',\n reached: (data: BuddySandboxData) => boolean,\n): Promise<void> {\n const client = getClient(config);\n const deadline = Date.now() + LIFECYCLE_TIMEOUT_MS;\n let data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n\n for (;;) {\n try {\n const path = { path: { sandbox_id: sandboxId } };\n await (verb === 'stop' ? client.stopSandbox(path) : client.startSandbox(path));\n break;\n } catch (error) {\n if (!isOperationInProgress(error) || Date.now() >= deadline) throw error;\n await sleep(LIFECYCLE_POLL_MS);\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n }\n }\n\n for (;;) {\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandboxId} failed to ${verb} ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandboxId} did not ${verb} within ` +\n `${LIFECYCLE_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(LIFECYCLE_POLL_MS);\n }\n}\n\nexport function stopSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'stop', isStopped);\n}\n\nexport function startSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'start', isReady);\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 // The caller may have given up at the deadline, so never start another\n // attempt past it. Timers can fire a millisecond early, so a retry is\n // only made when a whole poll interval still fits.\n if (!retryable || deadline - Date.now() < BOOT_WAIT_POLL_MS) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\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 .../execs` accepts the command and returns its execution id\n * immediately. The SDK's `Command` entity reads the log page by page and in\n * between lets the API hold a status request until the command finishes, so\n * nothing is polled on a fixed interval. The log does not tell stdout from\n * stderr: every line is reported as stdout. Buddy runs at most 3 such\n * commands at once per member in one sandbox and 10 per workspace, and stops\n * each one after 90 minutes.\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 ExecView, 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 = retryBootRaces(\n () => submitCommand(sandbox, payload, runtime),\n deadline,\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.execution_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 if (!commandResponse.execution_id) {\n throw new Error('Buddy accepted the command but returned no execution 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\n // `follow: true` reads until the command has finished, so this loop is the\n // wait; `wait()` afterwards only returns the final state the loop already\n // saw. Each line comes without its terminator, so the newline goes back on\n // here. Aborting at the deadline stops the SDK's requests; the flag stops\n // the loop from firing callbacks for a result nobody will read.\n const abort = new AbortController();\n let timedOut = false;\n const drain = (async () => {\n for await (const line of running.logs({ follow: true, signal: abort.signal })) {\n if (timedOut) break;\n const chunk = `${line}\\n`;\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n return running.wait({ signal: abort.signal });\n })();\n\n let finished: Command;\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n abort.abort();\n drain.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''));\n }\n finished = outcome;\n } catch (error) {\n // Reading the log or the status broke mid-command. Buddy keeps running it,\n // so stop it — best effort and not awaited, so a hanging kill cannot delay\n // the error.\n void killCommand(running);\n throw error;\n }\n\n const { exitCode, message } = outcomeOf(finished.data);\n return {\n stdout: stdout.join(''),\n stderr: message ? `${message}\\n` : '',\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/**\n * `POST .../execs`. Over Buddy's concurrency limit the API answers 409; that\n * becomes an error saying what to do about it instead of a bare HTTP status.\n */\nasync function submitCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<ExecView> {\n try {\n return await sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command, runtime },\n });\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n throw new Error(\n `Buddy refused to start the command on sandbox ${sandbox.sandboxId}: too many commands `\n + 'are running (at most 3 per member in one sandbox and 10 per workspace). '\n + `Retry once one of them finishes. (${messageOf(error)})`,\n );\n }\n}\n\n/**\n * The exit code of a finished command. A command Buddy failed or cancelled\n * without an exit code — e.g. stopped at the 90-minute limit — counts as a\n * failure, with Buddy's explanation as the message.\n */\nexport function outcomeOf(view: ExecView): { exitCode: number; message?: string } {\n if (typeof view.exit_code === 'number') return { exitCode: view.exit_code };\n if (view.status === 'SUCCESSFUL') return { exitCode: 0 };\n const reason = view.error_message ?? view.failure_reason;\n return {\n exitCode: 1,\n message: `Buddy command ${view.execution_id ?? ''} ended ${view.status ?? 'without a status'}`\n + (reason ? `: ${reason}` : ' without an exit code'),\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","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — binary-safe, unlike shelling out to `cat`/`tee`. Reads first\n * resolve links because Buddy downloads a link's target path, not its bytes.\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';\nimport { escapeShellArg } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport { runCommand } from './commands.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n statusOf,\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, async () => {\n const resolved = await runCommand(sandbox, `readlink -e -z -- \"${escapeShellArg(target)}\"`);\n if (resolved.exitCode !== 0) {\n throw new Error(`Failed to resolve file ${target}: ${resolved.stderr || 'path is missing or inaccessible'}`);\n }\n const output = resolved.stdout;\n if (!output.startsWith('/') || !output.endsWith('\\0') || output.indexOf('\\0') !== output.length - 1) {\n throw new Error(`Buddy returned an invalid resolved path for ${target}.`);\n }\n return sandbox.fs.downloadFile(normalizeSandboxPath(output.slice(0, -1)));\n });\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 createFolder(sandbox, parent);\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, () => createFolder(sandbox, target));\n}\n\nasync function createFolder(sandbox: BuddySandboxHandle, target: string): Promise<void> {\n try {\n await sandbox.fs.createFolder(target);\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n const separator = target.lastIndexOf('/');\n const entries = await sandbox.fs.listFiles(target.slice(0, separator) || '/');\n if (!entries.some(entry => entry.name === target.slice(separator + 1) && entry.type === 'DIR')) {\n throw error;\n }\n }\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":";AAeA,SAAS,sBAAsB;;;ACJ/B,SAAS,UAAU,gBAAgB,kBAAkB;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,iBAA8B;AAEpC,IAAM,qBAAqB;AAE3B,IAAM,eAAe;AAsBrB,IAAM,UAA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AK,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":["value","stdout","escapeShellArg","resolved","escapeShellArg","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. `pause()`/`resume()` stop a sandbox and start the same one again\n * (also reachable as `stop()`/`start()` on `getInstance()`).\n *\n * @see https://buddy.works/docs/api/sandboxes\n */\n\nimport { defineProvider } from '@computesdk/provider';\nimport type {\n CreateInstanceOptions,\n InstanceSizeClass,\n ListSnapshotsOptions,\n ListTemplatesOptions,\n InstanceInfo,\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 apiUrlForRegion,\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 BuddyResources,\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\n/** Buddy gives every sandbox a 50 GB disk; it is not configurable. */\nexport const BUDDY_DISK_MIB = 50 * 1024;\n\n/**\n * Smallest `resources` preset (`{vCPU}x{RAM GB}`, 1x2 through 12x24) whose vCPU\n * puts it in each standard size. `xs` takes 1x2 (extra RAM); 12x24 has too few\n * vCPU for `2xl`.\n */\nexport const BUDDY_SIZE_PRESETS: Readonly<Partial<Record<InstanceSizeClass, BuddyResources>>> = Object.freeze({\n xs: '1x2',\n sm: '1x2',\n md: '2x4',\n lg: '4x8',\n xl: '8x16',\n});\n\nexport const buddy = defineProvider<BuddySandboxHandle, BuddyConfig, any, Snapshot>({\n name: PROVIDER,\n regions: {\n support: config => ({\n placement: 'per-account',\n regions: (config.apiUrl?.replace(/\\/+$/, '') ?? apiUrlForRegion(config.region ?? 'US')) === apiUrlForRegion('US')\n ? { us: ['US'] }\n : {},\n }),\n },\n\n // The framework rejects `sizeClass` combined with `resources`, `cpu`, `cpus`,\n // `vcpus`, `memory`, `memoryMb`, `memoryMiB` or `memMiB` before this runs.\n sizes: (_config, profile) => {\n const preset = BUDDY_SIZE_PRESETS[profile.sizeClass];\n if (!preset) {\n return {\n status: 'unsupported',\n reason: `Buddy's largest preset is 12x24 (12 vCPU / 24 GB RAM), below ${profile.sizeClass} (${profile.vcpus} vCPU / ${profile.memoryMiB} MiB).`,\n };\n }\n const [vcpus, memoryGb] = preset.split('x').map(Number);\n return {\n status: 'supported',\n nativeOptions: { resources: preset },\n resolved: { vcpus, memoryMiB: memoryGb * 1024, diskMiB: BUDDY_DISK_MIB },\n };\n },\n\n methods: {\n instances: {\n create: async (config: BuddyConfig, options?: CreateInstanceOptions) => {\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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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 { instance: sandbox, instanceId: 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<InstanceInfo> => {\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 // Stop/start under the same id. The disk survives except `/tmp`, which\n // is cleared on boot; running processes do not.\n pause: (sandbox: BuddySandboxHandle) => sandbox.stop(),\n resume: (sandbox: BuddySandboxHandle) => sandbox.start(),\n pauseCapabilities: { memory: false },\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 // A restore boots a new sandbox from the whole root disk; processes and\n // the `/dev/shm` tmpfs are not kept. The source keeps running.\n capabilities: { scope: 'rootfs', memory: false, destroysSource: false },\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: CreateInstanceOptions = {}) {\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 * Stops the sandbox and resolves once Buddy reports `STOPPED`. The disk is\n * kept (except `/tmp`, which is cleared on boot); running processes are not.\n */\n stop(): Promise<void>;\n /** Starts a stopped sandbox under the same id and resolves once it is ready. */\n start(): Promise<void>;\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 `InstanceInfo.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 stop: () => stopSandbox(config, sandboxId),\n start: () => startSandbox(config, sandboxId),\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/** Measured at ~1 s to stop and ~3 s to start; the margin covers a busy pool. */\nconst LIFECYCLE_TIMEOUT_MS = 120_000;\nconst LIFECYCLE_POLL_MS = 250;\n\nconst isStopped = (data: BuddySandboxData) => data.status === 'STOPPED';\nconst isReady = (data: BuddySandboxData) =>\n data.status === 'RUNNING' && data.setup_status === 'SUCCESS';\n\n/**\n * Buddy's start and stop endpoints return as soon as the transition is\n * accepted, so both are followed by a poll for the target state. A sandbox\n * already in that state is left alone, and an operation still in flight (a\n * boot, a snapshot) is retried until it clears.\n */\nasync function transition(\n config: ResolvedBuddyConfig,\n sandboxId: string,\n verb: 'start' | 'stop',\n reached: (data: BuddySandboxData) => boolean,\n): Promise<void> {\n const client = getClient(config);\n const deadline = Date.now() + LIFECYCLE_TIMEOUT_MS;\n let data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n\n for (;;) {\n try {\n const path = { path: { sandbox_id: sandboxId } };\n await (verb === 'stop' ? client.stopSandbox(path) : client.startSandbox(path));\n break;\n } catch (error) {\n if (!isOperationInProgress(error) || Date.now() >= deadline) throw error;\n await sleep(LIFECYCLE_POLL_MS);\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n }\n }\n\n for (;;) {\n data = await getSandboxData(config, sandboxId);\n if (reached(data)) return;\n if (data.status === 'FAILED' || data.setup_status === 'FAILED') {\n throw new Error(\n `Buddy sandbox ${sandboxId} failed to ${verb} ` +\n `(status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Buddy sandbox ${sandboxId} did not ${verb} within ` +\n `${LIFECYCLE_TIMEOUT_MS / 1000}s (status: ${data.status}, setup: ${data.setup_status}).`,\n );\n }\n await sleep(LIFECYCLE_POLL_MS);\n }\n}\n\nexport function stopSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'stop', isStopped);\n}\n\nexport function startSandbox(config: ResolvedBuddyConfig, sandboxId: string): Promise<void> {\n return transition(config, sandboxId, 'start', isReady);\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 // The caller may have given up at the deadline, so never start another\n // attempt past it. Timers can fire a millisecond early, so a retry is\n // only made when a whole poll interval still fits.\n if (!retryable || deadline - Date.now() < BOOT_WAIT_POLL_MS) throw error;\n await sleep(BOOT_WAIT_POLL_MS);\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 .../execs` accepts the command and returns its execution id\n * immediately. The SDK's `Command` entity reads the log page by page and in\n * between lets the API hold a status request until the command finishes, so\n * nothing is polled on a fixed interval. The log does not tell stdout from\n * stderr: every line is reported as stdout. Buddy runs at most 3 such\n * commands at once per member in one sandbox and 10 per workspace, and stops\n * each one after 90 minutes.\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 ExecView, 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 = retryBootRaces(\n () => submitCommand(sandbox, payload, runtime),\n deadline,\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.execution_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 if (!commandResponse.execution_id) {\n throw new Error('Buddy accepted the command but returned no execution 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\n // `follow: true` reads until the command has finished, so this loop is the\n // wait; `wait()` afterwards only returns the final state the loop already\n // saw. Each line comes without its terminator, so the newline goes back on\n // here. Aborting at the deadline stops the SDK's requests; the flag stops\n // the loop from firing callbacks for a result nobody will read.\n const abort = new AbortController();\n let timedOut = false;\n const drain = (async () => {\n for await (const line of running.logs({ follow: true, signal: abort.signal })) {\n if (timedOut) break;\n const chunk = `${line}\\n`;\n stdout.push(chunk);\n options.onStdout?.(chunk);\n }\n return running.wait({ signal: abort.signal });\n })();\n\n let finished: Command;\n try {\n const outcome = deadline ? await raceDeadline(drain, deadline) : await drain;\n if (outcome === DEADLINE_PASSED) {\n timedOut = true;\n abort.abort();\n drain.catch(() => {});\n void killCommand(running);\n return timedOutResult(stdout.join(''));\n }\n finished = outcome;\n } catch (error) {\n // Reading the log or the status broke mid-command. Buddy keeps running it,\n // so stop it — best effort and not awaited, so a hanging kill cannot delay\n // the error.\n void killCommand(running);\n throw error;\n }\n\n const { exitCode, message } = outcomeOf(finished.data);\n return {\n stdout: stdout.join(''),\n stderr: message ? `${message}\\n` : '',\n exitCode,\n durationMs: Date.now() - startedAt,\n };\n}\n\n/**\n * `POST .../execs`. Over Buddy's concurrency limit the API answers 409; that\n * becomes an error saying what to do about it instead of a bare HTTP status.\n */\nasync function submitCommand(\n sandbox: BuddySandboxHandle,\n command: string,\n runtime: BuddyCommandRuntime,\n): Promise<ExecView> {\n try {\n return await sandbox.client.executeCommand({\n path: { sandbox_id: sandbox.sandboxId },\n body: { command, runtime },\n });\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n throw new Error(\n `Buddy refused to start the command on sandbox ${sandbox.sandboxId}: too many commands `\n + 'are running (at most 3 per member in one sandbox and 10 per workspace). '\n + `Retry once one of them finishes. (${messageOf(error)})`,\n );\n }\n}\n\n/**\n * The exit code of a finished command. A command Buddy failed or cancelled\n * without an exit code — e.g. stopped at the 90-minute limit — counts as a\n * failure, with Buddy's explanation as the message.\n */\nexport function outcomeOf(view: ExecView): { exitCode: number; message?: string } {\n if (typeof view.exit_code === 'number') return { exitCode: view.exit_code };\n if (view.status === 'SUCCESSFUL') return { exitCode: 0 };\n const reason = view.error_message ?? view.failure_reason;\n return {\n exitCode: 1,\n message: `Buddy command ${view.execution_id ?? ''} ended ${view.status ?? 'without a status'}`\n + (reason ? `: ${reason}` : ' without an exit code'),\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","/**\n * Filesystem operations.\n *\n * These go through the SDK's `FileSystem`, which talks to Buddy's `content/`\n * endpoints — binary-safe, unlike shelling out to `cat`/`tee`. Reads first\n * resolve links because Buddy downloads a link's target path, not its bytes.\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';\nimport { escapeShellArg } from '@computesdk/provider';\n\nimport { whenBooted } from './boot.js';\nimport { runCommand } from './commands.js';\nimport {\n isNotFound,\n normalizeSandboxPath,\n statusOf,\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, async () => {\n const resolved = await runCommand(sandbox, `readlink -e -z -- \"${escapeShellArg(target)}\"`);\n if (resolved.exitCode !== 0) {\n throw new Error(`Failed to resolve file ${target}: ${resolved.stderr || 'path is missing or inaccessible'}`);\n }\n const output = resolved.stdout;\n if (!output.startsWith('/') || !output.endsWith('\\0') || output.indexOf('\\0') !== output.length - 1) {\n throw new Error(`Buddy returned an invalid resolved path for ${target}.`);\n }\n return sandbox.fs.downloadFile(normalizeSandboxPath(output.slice(0, -1)));\n });\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 createFolder(sandbox, parent);\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, () => createFolder(sandbox, target));\n}\n\nasync function createFolder(sandbox: BuddySandboxHandle, target: string): Promise<void> {\n try {\n await sandbox.fs.createFolder(target);\n } catch (error) {\n if (statusOf(error) !== 409) throw error;\n const separator = target.lastIndexOf('/');\n const entries = await sandbox.fs.listFiles(target.slice(0, separator) || '/');\n if (!entries.some(entry => entry.name === target.slice(separator + 1) && entry.type === 'DIR')) {\n throw error;\n }\n }\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":";AAeA,SAAS,sBAAsB;;;ACJ/B,SAAS,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AY,oBAAoB,UAAU,IAAI,CAAC;AACpF,SAAO,QAAQ,kBAAkB,KAAK,IAAI;AAC5C;","names":["value","stdout","escapeShellArg","resolved","escapeShellArg","resolved"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@computesdk/buddy",
3
- "version": "1.0.32",
3
+ "version": "1.0.33",
4
4
  "description": "Buddy sandbox adapter for ComputeSDK. Run code in Ubuntu microVMs with snapshots and preview URLs.",
5
5
  "author": "Lucas Czulak",
6
6
  "license": "MIT",
@@ -19,8 +19,8 @@
19
19
  ],
20
20
  "dependencies": {
21
21
  "@buddy-works/sandbox-sdk": "^0.3.0",
22
- "@computesdk/provider": "2.1.32",
23
- "computesdk": "4.1.26"
22
+ "@computesdk/provider": "2.1.33",
23
+ "computesdk": "4.1.27"
24
24
  },
25
25
  "engines": {
26
26
  "node": "^20.19.0 || >=22.12.0"