@computesdk/kosa8 1.0.7 → 1.0.8
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 +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +10 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as computesdk from 'computesdk';
|
|
2
|
-
import { RunCommandOptions, CommandResult, CreateInstanceOptions, SnapshotCapabilities } from '@computesdk/provider';
|
|
2
|
+
import { RunCommandOptions, CommandResult, InstanceSizeClass, CreateInstanceOptions, SnapshotCapabilities } from '@computesdk/provider';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* File content for the kosa8 provider.
|
|
@@ -35,6 +35,8 @@ declare const WRITE_CHUNK_CHARS: number;
|
|
|
35
35
|
declare function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void>;
|
|
36
36
|
|
|
37
37
|
interface Kosa8Config {
|
|
38
|
+
/** Template to boot per standard `sizeClass`. The template fixes CPU and memory, so build one per size. */
|
|
39
|
+
sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;
|
|
38
40
|
/** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */
|
|
39
41
|
apiKey?: string;
|
|
40
42
|
/** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as computesdk from 'computesdk';
|
|
2
|
-
import { RunCommandOptions, CommandResult, CreateInstanceOptions, SnapshotCapabilities } from '@computesdk/provider';
|
|
2
|
+
import { RunCommandOptions, CommandResult, InstanceSizeClass, CreateInstanceOptions, SnapshotCapabilities } from '@computesdk/provider';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* File content for the kosa8 provider.
|
|
@@ -35,6 +35,8 @@ declare const WRITE_CHUNK_CHARS: number;
|
|
|
35
35
|
declare function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void>;
|
|
36
36
|
|
|
37
37
|
interface Kosa8Config {
|
|
38
|
+
/** Template to boot per standard `sizeClass`. The template fixes CPU and memory, so build one per size. */
|
|
39
|
+
sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;
|
|
38
40
|
/** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */
|
|
39
41
|
apiKey?: string;
|
|
40
42
|
/** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
|
package/dist/index.js
CHANGED
|
@@ -759,6 +759,16 @@ var shellFs = (sandbox, run) => new import_provider2.ShellFileSystem((command, o
|
|
|
759
759
|
var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
|
|
760
760
|
var provider = (0, import_provider2.defineProvider)({
|
|
761
761
|
name: "kosa8",
|
|
762
|
+
sizes: (config, profile, options) => {
|
|
763
|
+
if (options?.templateId !== void 0 || options?.snapshotId !== void 0) {
|
|
764
|
+
return { status: "unsupported", reason: "A kosa8 template or snapshot fixes CPU and memory; drop templateId/snapshotId to boot the standard size template." };
|
|
765
|
+
}
|
|
766
|
+
const templateId = config.sizeTemplates?.[profile.sizeClass];
|
|
767
|
+
if (typeof templateId !== "string" || !templateId.trim()) {
|
|
768
|
+
return { status: "unconfigured", reason: `kosa8 fixes CPU and memory per template; build one at ${profile.vcpus} vCPU / ${profile.memoryMiB} MiB and set sizeTemplates.${profile.sizeClass}.` };
|
|
769
|
+
}
|
|
770
|
+
return { status: "supported", nativeOptions: { templateId } };
|
|
771
|
+
},
|
|
762
772
|
methods: {
|
|
763
773
|
instances: {
|
|
764
774
|
create: async (config, options) => {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/transport.ts","../src/files.ts"],"sourcesContent":["/**\n * kosa8 Provider - Factory-based Implementation\n *\n * Sandboxes on kosa8 Cloud (https://kosa8.com). Each sandbox runs in its own microVM with its\n * own kernel. The cloud API is a small JSON surface, so this package talks to it with `fetch`\n * and has no SDK dependency.\n *\n * Commands go through the buffered exec endpoint: straight to the sandbox's host when the create\n * answer carries a direct-exec URL and token (see runDirect), otherwise through the API. File content\n * moves through kosa8's file API (`/v1/sandboxes/{id}/files`, see files.ts), with shell commands\n * over exec for small files and for hosts without it. `pause()`/`resume()` map to kosa8's sleep and\n * wake, and `provider.snapshot` to kosa8 snapshots: both keep the VM's memory (running processes)\n * as well as its disk.\n */\n\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\nimport { httpRequest, preconnect } from './transport';\nimport { readFileNative, writeFileNative, type ExecRunner } from './files';\n\nexport { WRITE_CHUNK_CHARS, writeFileViaExec } from './files';\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateSnapshotOptions,\n InstanceInfo,\n RunCommandOptions,\n SnapshotCapabilities,\n} from '@computesdk/provider';\n\nexport interface Kosa8Config {\n /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */\n apiKey?: string;\n /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */\n baseUrl?: string;\n /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */\n region?: string;\n}\n\n/** A sandbox as the kosa8 Cloud API returns it. */\nexport interface Kosa8SandboxData {\n id: string;\n state: string;\n template: string;\n cpus: number;\n mem_mb: number;\n region: string | null;\n created_at: number;\n started_at: number | null;\n sleep_after_s: number | null;\n delete_after: number | null;\n last_error: string | null;\n [key: string]: unknown;\n}\n\n/** A template as GET /v1/templates returns it. */\nexport interface Kosa8Template {\n key: string;\n cpus: number;\n mem_mb: number;\n image?: string;\n regions: string[];\n [key: string]: unknown;\n}\n\n/** The create answer's `direct` object: the host's exec endpoint for this sandbox and a token for it. */\nexport interface Kosa8Direct {\n exec_url: string;\n /** The host's raw file endpoint for this sandbox, when the token also covers files (`files.direct`). */\n files_url?: string;\n token: string;\n /** When the token stops working, ms since the epoch. */\n expires_at: number;\n}\n\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\n /** Present while commands can go straight to the sandbox's host (runDirect). */\n direct?: Kosa8Direct;\n /** A fresh direct token being fetched (refreshDirect). */\n refreshing?: Promise<void>;\n /** False once the sandbox's host answered that it has no file API: files then go over exec. */\n files?: boolean;\n /** False once the host refused file requests with the direct token: files then go through the API. */\n directFiles?: boolean;\n}\n\n/** A snapshot as the kosa8 Cloud API returns it. */\nexport interface Kosa8SnapshotData {\n id: string;\n name: string | null;\n state: string;\n source_sandbox_id: string;\n template: string;\n cpus: number;\n mem_mb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n created_at: number;\n [key: string]: unknown;\n}\n\n/** A snapshot as `provider.snapshot` returns it. */\nexport interface Kosa8Snapshot {\n id: string;\n provider: 'kosa8';\n createdAt: Date;\n metadata: {\n name: string | null;\n sourceInstanceId: string;\n state: string;\n template: string;\n cpus: number;\n memMb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n /** How long the host took to save it, when the API reports it. */\n createMs?: number | null;\n };\n}\n\ninterface Auth {\n apiKey: string;\n baseUrl: string;\n}\n\ninterface ExecResponse {\n exit: number | null;\n stdout: string;\n stderr: string;\n /** Set when the API kept only the first part of a stream (its output limit). */\n stdout_truncated?: boolean;\n stderr_truncated?: boolean;\n /** The stream's full length, kept or not. */\n stdout_bytes?: number;\n stderr_bytes?: number;\n}\n\n/**\n * A command's result. Beyond ComputeSDK's fields it says when the API returned only the first part\n * of the output (its limit on a buffered command): `truncated`, per stream, and each stream's full\n * length in bytes. These are absent when the API does not report them.\n */\nexport interface Kosa8CommandResult extends CommandResult {\n truncated?: boolean;\n stdoutTruncated?: boolean;\n stderrTruncated?: boolean;\n stdoutBytes?: number;\n stderrBytes?: number;\n}\n\n/** The API's shortest and longest lifetime for a sandbox (ttl_s). */\nconst MIN_TTL_S = 60;\nconst MAX_TTL_S = 90 * 86400;\n\n/** Exit code reported when `runCommand`'s timeout stops a command (as coreutils `timeout` does). */\nconst TIMEOUT_EXIT = 124;\n\n/** Names the marker file a timed command creates once it returns (see execArgv). */\nconst DONE_ENV = 'KOSA8_DONE';\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template (or an image) fixes the size. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'envs', 'volumes',\n] as const;\n\n/** A snapshot name the API accepts; another name is kept only in the snapshot's metadata. */\nconst SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\nfunction resolveConfig(config: Kosa8Config): Auth {\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const apiKey = config.apiKey || env?.KOSA8_API_KEY || '';\n if (!apiKey) {\n throw new Error(\n `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. ` +\n `Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`,\n );\n }\n const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || 'https://api.kosa8.com').replace(/\\/+$/, '');\n return { apiKey, baseUrl };\n}\n\nasync function request<T>(\n auth: Auth,\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n): Promise<T | null> {\n const res = await httpRequest(`${auth.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n if (res.status === 404) return null;\n const text = res.text;\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);\n }\n return (text ? JSON.parse(text) : null) as T;\n}\n\nconst sandboxPath = (id: string, rest = '') => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;\n\nfunction toSandbox(auth: Auth, data: Kosa8SandboxData, direct?: unknown): Kosa8Sandbox {\n const sandbox: Kosa8Sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\n if (isDirect(direct)) {\n sandbox.direct = direct;\n // The first command follows at once: its host's session opens now.\n preconnect(direct.exec_url);\n }\n return sandbox;\n}\n\nfunction isDirect(d: unknown): d is Kosa8Direct {\n const x = d as Kosa8Direct | null | undefined;\n return !!x && typeof x.exec_url === 'string' && /^https:\\/\\//.test(x.exec_url) && typeof x.token === 'string' &&\n typeof x.expires_at === 'number';\n}\n\n/** A direct token this close to expiry is not used; one closer than DIRECT_REFRESH_MS is renewed in the background. */\nconst DIRECT_MARGIN_MS = 15_000;\nconst DIRECT_REFRESH_MS = 60_000;\n\n/**\n * Statuses from the direct endpoint that mean the command did not run there: the token was refused\n * (401, 403), the host does not have the sandbox (404), it is asleep and only the API wakes it\n * (409), the host does not offer it (501), or Cloudflare could not reach the host (521, 522, 523,\n * 530). The command is then sent through the API. Any other failure is reported as is, since the\n * command may have run.\n */\nconst DIRECT_NOT_RUN = new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);\n\n/**\n * The direct token and files URL for file requests, or null when files go through the API: no\n * token, a host whose token does not cover files, one that refused it, or a token about to expire\n * (renewed in the background, as for commands).\n */\nexport function directFiles(sandbox: Kosa8Sandbox): { url: string; token: string } | null {\n const d = sandbox.direct;\n if (!d?.files_url || sandbox.directFiles === false || !/^https:\\/\\//.test(d.files_url)) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };\n}\n\n/** Renews the direct token in the background; a failure leaves the API path in use. */\nfunction refreshDirect(sandbox: Kosa8Sandbox): void {\n if (sandbox.refreshing) return;\n sandbox.refreshing = request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct'))\n .then((r) => {\n if (isDirect(r?.direct)) sandbox.direct = r.direct;\n })\n .catch(() => {})\n .finally(() => {\n sandbox.refreshing = undefined;\n });\n}\n\n/**\n * Runs a command on the sandbox's host directly (the create answer's `direct`), skipping the API's\n * hop. Returns null when the command was not run there, so the caller sends it through the API;\n * the sandbox then stops using the direct path until a fresh token arrives.\n */\nasync function runDirect(sandbox: Kosa8Sandbox, body: unknown, signal?: AbortSignal): Promise<ExecResponse | null> {\n const d = sandbox.direct;\n if (!d) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n if (left < DIRECT_MARGIN_MS) return null;\n const res = await httpRequest(d.exec_url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${d.token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal,\n });\n const text = res.text;\n if (DIRECT_NOT_RUN.has(res.status)) {\n if (sandbox.direct === d) sandbox.direct = undefined;\n return null;\n }\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string };\n if (parsed?.error) detail = parsed.error;\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);\n }\n return JSON.parse(text) as ExecResponse;\n}\n\n/** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */\nexport function createBody(config: Kosa8Config, options: CreateInstanceOptions = {}): Record<string, unknown> {\n for (const key of UNSUPPORTED_CREATE_OPTIONS) {\n if (options[key] !== undefined) {\n throw new Error(\n `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; ` +\n `pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n if (options.snapshotId !== undefined) {\n // A sandbox made from a snapshot takes its template, size, image and host from the snapshot.\n for (const key of ['templateId', 'image', 'region'] as const) {\n if (options[key] !== undefined) {\n throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);\n }\n }\n body.snapshot = options.snapshotId;\n } else if (options.image !== undefined) {\n // An OCI image boots a VM of its own (the API's default size for an image, 2 vCPU / 4 GiB),\n // so the configured default template does not apply; an explicit templateId is passed on.\n body.image = options.image;\n if (options.templateId) body.template = options.templateId;\n } else {\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n }\n if (options.snapshotId === undefined) {\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\n }\n if (options.sleepAfterSeconds !== undefined) body.sleep_after_s = options.sleepAfterSeconds;\n if (typeof options.timeout === 'number' && options.timeout > 0) {\n // kosa8 deletes the sandbox when its lifetime ends; the API's shortest lifetime is 60 s.\n body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1000)));\n }\n return body;\n}\n\n/** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */\nexport function execArgv(command: string, options?: RunCommandOptions): string[] {\n let cmd = command;\n if (options?.cwd) cmd = `cd \"${escapeShellArg(options.cwd)}\" && ${cmd}`;\n if (options?.background) {\n cmd = `nohup sh -c \"${escapeShellArg(cmd)}\" >/dev/null 2>&1 &`;\n } else if (options?.timeout && options.timeout > 0) {\n // Stop the command in the sandbox, not just the wait for it. GNU timeout signals the whole\n // process group; an image without `timeout` runs the command unbounded and the request's\n // own deadline (runCommand) still applies.\n //\n // Status 137 alone does not mean the deadline passed: the command may exit 137 itself or be\n // killed early. The command runs in a subshell and a marker file is created once it returns,\n // whatever its status. Only a 137 with no marker (the shell itself was killed) once the\n // deadline has passed (whole seconds: the elapsed count cannot fall short of a real deadline)\n // is reported as a timeout.\n const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const plain = `sh -c \"${escapeShellArg(cmd)}\"`;\n const marked = `sh -c \"${escapeShellArg(`(\\n${cmd}\\n); s=$?; : > \"$${DONE_ENV}\"; exit $s`)}\"`;\n cmd =\n `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then ` +\n `rm -f \"$${DONE_ENV}\"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; ` +\n `if [ $s -eq 137 ] && [ ! -e \"$${DONE_ENV}\" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; ` +\n `rm -f \"$${DONE_ENV}\"; exit $s; ` +\n `else ${plain}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/**\n * The exec API's limit on each argv entry. Measured in UTF-8 bytes here, which is never less than\n * the API's own count, so a command with multibyte characters cannot slip over it.\n */\nconst MAX_ARG_BYTES = 8192;\n\n/** The exec API's limit on the whole request body, in bytes. */\nexport const MAX_EXEC_BODY_BYTES = 64 * 1024;\n\n/** Environment variable that carries a script too long for one argv entry; callers may not set it. */\nexport const SCRIPT_ENV = 'KOSA8_SCRIPT';\n\n/**\n * The exec request body: a script too long for one argv entry travels in an environment variable.\n * Throws before any request is made when the serialized body would exceed the exec API's limit.\n */\nexport function execBody(command: string, options?: RunCommandOptions): { cmd: string[]; env: string[] } {\n const argv = execArgv(command, options);\n const env = execEnv(options?.env);\n const body = Buffer.byteLength(argv[2], 'utf8') <= MAX_ARG_BYTES\n ? { cmd: argv, env }\n : { cmd: ['sh', '-c', `eval \"$${SCRIPT_ENV}\"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };\n const size = Buffer.byteLength(JSON.stringify(body), 'utf8');\n if (size > MAX_EXEC_BODY_BYTES) {\n throw new Error(\n `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) ` +\n `for the command and its environment together. Write a long script to a file with ` +\n `sandbox.filesystem.writeFile() and run that file instead.`,\n );\n }\n return body;\n}\n\nfunction execEnv(env?: Record<string, string>): string[] {\n if (!env) return [];\n return Object.entries(env).map(([key, value]) => {\n if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n if (key === SCRIPT_ENV) {\n throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);\n }\n return `${key}=${value}`;\n });\n}\n\nfunction infoStatus(state: string): InstanceInfo['status'] {\n if (state === 'error') return 'error';\n // A sleeping sandbox is alive: its memory and disk are saved, and any call (a command, a file\n // read or write) wakes it in about a second, so it reports as running.\n if (state === 'running' || state === 'sleeping') return 'running';\n // creating, paused, stopped, deleted and expired (past its deadline): not running now, so a\n // readiness check keeps waiting and a liveness check sees it gone.\n return 'stopped';\n}\n\nasync function getData(sandbox: Kosa8Sandbox): Promise<Kosa8SandboxData | null> {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id));\n return data?.sandbox ?? null;\n}\n\n/** How often a sandbox that is still booting (an image's cold boot) is checked, and for how long. */\nconst BOOT_POLL_MS = 150;\nconst BOOT_TIMEOUT_MS = 5 * 60_000;\n\n/**\n * Waits for a sandbox the API answered with `creating` (202: an image booted cold) to run, so the\n * create resolves to a sandbox that takes commands. Its direct exec token is fetched once it runs.\n */\nasync function waitUntilRunning(sandbox: Kosa8Sandbox, signal?: AbortSignal): Promise<void> {\n const deadline = Date.now() + BOOT_TIMEOUT_MS;\n while (sandbox.data.state === 'creating') {\n if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1000} s`);\n signal?.throwIfAborted();\n await new Promise((r) => setTimeout(r, BOOT_POLL_MS));\n const current = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id), undefined, signal);\n if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);\n sandbox.data = current.sandbox;\n }\n if (sandbox.data.state !== 'running') {\n const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : '';\n throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);\n }\n if (!sandbox.direct) {\n const r = await request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct')).catch(() => null);\n if (isDirect(r?.direct)) {\n sandbox.direct = r.direct;\n preconnect(r.direct.exec_url);\n }\n }\n}\n\nfunction toSnapshot(s: Kosa8SnapshotData, createMs?: number | null): Kosa8Snapshot {\n return {\n id: s.id,\n provider: 'kosa8',\n createdAt: new Date(s.created_at),\n metadata: {\n name: s.name ?? null,\n sourceInstanceId: s.source_sandbox_id,\n state: s.state,\n template: s.template,\n cpus: s.cpus,\n memMb: s.mem_mb,\n image: s.image ?? null,\n bytes: s.bytes ?? 0,\n region: s.region ?? null,\n ...(createMs !== undefined ? { createMs } : {}),\n },\n };\n}\n\n/**\n * kosa8 snapshots save the whole VM, memory included, so a restore resumes running processes. The\n * source keeps running, and one snapshot restores into any number of sandboxes, each copy-on-write\n * on the snapshot's host. A snapshot is ready when `create` returns.\n */\nexport const SNAPSHOT_CAPABILITIES: SnapshotCapabilities = {\n scope: 'rootfs',\n memory: true,\n destroysSource: false,\n source: 'kept',\n fork: true,\n readiness: 'immediate',\n};\n\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nconst provider = defineProvider<Kosa8Sandbox, Kosa8Config>({\n name: 'kosa8',\n methods: {\n instances: {\n create: async (config: Kosa8Config, options?: CreateInstanceOptions) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData; direct?: unknown }>(\n auth,\n 'POST',\n '/v1/sandboxes',\n createBody(config, options),\n options?.signal,\n );\n if (!data?.sandbox) throw new Error('kosa8 API returned no sandbox on create');\n const sandbox = toSandbox(auth, data.sandbox, data.direct);\n if (sandbox.data.state !== 'running') {\n try {\n await waitUntilRunning(sandbox, options?.signal);\n } catch (err) {\n // A sandbox that never ran is not left behind, billed.\n await request(auth, 'DELETE', sandboxPath(sandbox.id)).catch(() => {});\n throw err;\n }\n }\n return { instance: sandbox, instanceId: sandbox.id };\n },\n\n getById: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData }>(auth, 'GET', sandboxPath(instanceId));\n return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;\n },\n\n list: async (config: Kosa8Config) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandboxes: Kosa8SandboxData[] }>(auth, 'GET', '/v1/sandboxes');\n return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));\n },\n\n destroy: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n // A sandbox that is already gone answers 404, which request() returns as null.\n await request(auth, 'DELETE', sandboxPath(instanceId));\n },\n\n runCommand: async (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions): Promise<Kosa8CommandResult> => {\n const start = Date.now();\n const body = execBody(command, options);\n // The command is stopped in the sandbox at the deadline; the request gets a grace period on top.\n const signal = options?.timeout && options.timeout > 0 && !options.background\n ? AbortSignal.timeout(options.timeout + 30_000)\n : undefined;\n const data = (await runDirect(sandbox, body, signal)) ??\n (await request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n const result: Kosa8CommandResult = {\n stdout: data.stdout ?? '',\n stderr: data.stderr ?? '',\n exitCode: Number.isInteger(data.exit) ? (data.exit as number) : -1,\n durationMs: Date.now() - start,\n };\n if (typeof data.stdout_truncated === 'boolean' || typeof data.stderr_truncated === 'boolean') {\n result.stdoutTruncated = data.stdout_truncated === true;\n result.stderrTruncated = data.stderr_truncated === true;\n result.truncated = result.stdoutTruncated || result.stderrTruncated;\n }\n if (typeof data.stdout_bytes === 'number') result.stdoutBytes = data.stdout_bytes;\n if (typeof data.stderr_bytes === 'number') result.stderrBytes = data.stderr_bytes;\n return result;\n },\n\n getInfo: async (sandbox: Kosa8Sandbox): Promise<InstanceInfo> => {\n const current = (await getData(sandbox)) ?? { ...sandbox.data, state: 'deleted' };\n sandbox.data = current;\n return {\n id: sandbox.id,\n provider: 'kosa8',\n status: infoStatus(current.state),\n createdAt: new Date(current.created_at),\n timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,\n metadata: {\n state: current.state,\n template: current.template,\n cpus: current.cpus,\n memMb: current.mem_mb,\n region: current.region,\n sleepAfterSeconds: current.sleep_after_s,\n deleteAfter: current.delete_after,\n lastError: current.last_error,\n },\n };\n },\n\n getUrl: async (): Promise<string> => {\n throw notAvailable('port URLs');\n },\n\n // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.\n pause: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/sleep'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n resume: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/wake'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n pauseCapabilities: { memory: true },\n\n // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.\n lifetime: {},\n\n // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.\n extendLifetime: async (sandbox: Kosa8Sandbox, ms: number): Promise<void> => {\n const current = await getData(sandbox);\n if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = current;\n if (current.delete_after == null) return;\n const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1000);\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'PATCH', sandboxPath(sandbox.id), {\n delete_after: Math.floor(deleteAfter),\n });\n // A 404 here means the sandbox was deleted between the read and the update.\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n if (data.sandbox) sandbox.data = data.sandbox;\n },\n\n getInstance: (sandbox: Kosa8Sandbox): Kosa8Sandbox => sandbox,\n\n // File content straight to the sandbox's host with the direct token, else through the API's\n // file stream, else (an older host) exec (files.ts); the rest are single shell commands.\n filesystem: {\n readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),\n writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),\n mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),\n readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),\n exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),\n remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path),\n },\n },\n\n snapshot: {\n capabilities: SNAPSHOT_CAPABILITIES,\n\n // POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.\n create: async (config: Kosa8Config, instanceId: string, options?: CreateSnapshotOptions): Promise<Kosa8Snapshot> => {\n const auth = resolveConfig(config);\n const name = typeof options?.name === 'string' && SNAPSHOT_NAME.test(options.name) ? options.name : undefined;\n const data = await request<{ snapshot: Kosa8SnapshotData; ms?: number | null }>(\n auth,\n 'POST',\n sandboxPath(instanceId, '/snapshots'),\n name ? { name } : {},\n );\n if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);\n return toSnapshot(data.snapshot, typeof data.ms === 'number' ? data.ms : null);\n },\n\n list: async (config: Kosa8Config): Promise<Kosa8Snapshot[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ snapshots: Kosa8SnapshotData[] }>(auth, 'GET', '/v1/snapshots');\n return (data?.snapshots ?? []).map((s) => toSnapshot(s));\n },\n\n // A snapshot that is already gone answers 404, which request() returns as null.\n delete: async (config: Kosa8Config, snapshotId: string): Promise<void> => {\n const auth = resolveConfig(config);\n await request(auth, 'DELETE', `/v1/snapshots/${encodeURIComponent(snapshotId)}`);\n },\n },\n\n template: {\n create: async () => {\n throw notAvailable('creating templates (templates are offered by the hosts)');\n },\n list: async (config: Kosa8Config): Promise<Kosa8Template[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ templates: Kosa8Template[] }>(auth, 'GET', '/v1/templates');\n return data?.templates ?? [];\n },\n delete: async () => {\n throw notAvailable('deleting templates (templates are offered by the hosts)');\n },\n },\n },\n});\n\n/**\n * The kosa8 provider. Configuring it opens the HTTP/2 session to the API (transport.ts), so the\n * first create does not pay the connection's handshake.\n */\nexport const kosa8: typeof provider = (config) => {\n try {\n preconnect(resolveConfig(config).baseUrl);\n } catch {\n // No key yet: the first call reports it.\n }\n return provider(config);\n};\n\nexport default kosa8;\n","/**\n * HTTP for the kosa8 provider: one HTTP/2 session per origin, shared by every request, instead of\n * a TLS connection per request.\n *\n * With `fetch`, 100 sandboxes created at once open 100 connections, each paying its own TCP and\n * TLS handshake before the request is sent. On kosa8 Cloud that was ~260 ms of each create in a\n * 100-at-once burst from Virginia (2026-11-13), against ~40 ms for a request on a connection that\n * was already open. Over one HTTP/2 session the handshake is paid once, and `preconnect` pays it\n * before the first request (when the provider is configured).\n *\n * `fetch` stays the fallback: where `node:http2` is not available, for an origin whose session\n * could not be opened, and whenever the global `fetch` has been replaced (tests, proxies,\n * instrumentation), which is then honoured for every request.\n */\n\ntype Http2 = typeof import('node:http2');\ntype Session = import('node:http2').ClientHttp2Session;\n\nexport interface HttpResponse {\n status: number;\n ok: boolean;\n /** The body as UTF-8 text; empty when the request asked for `binary`. */\n text: string;\n /** The body's bytes, present when the request asked for `binary`. */\n bytes?: Uint8Array;\n /** Response headers, names in lower case. */\n headers: Record<string, string>;\n}\n\nexport interface HttpInit {\n method: string;\n headers: Record<string, string>;\n body?: string | Uint8Array;\n signal?: AbortSignal;\n /** Return the body as bytes (`bytes`) rather than text, for file content. */\n binary?: boolean;\n}\n\n/** The global fetch as it was when this module loaded; a different one later was put there on purpose. */\nconst nativeFetch: typeof fetch | undefined = typeof fetch === 'function' ? fetch : undefined;\n\nlet http2Load: Promise<Http2 | null> | undefined;\nfunction loadHttp2(): Promise<Http2 | null> {\n http2Load ??= import('node:http2').then(\n (m) => ((m as unknown as { default?: Http2 }).default ?? m) as Http2,\n () => null,\n );\n return http2Load;\n}\n\ninterface Origin {\n session?: Promise<Session | null>;\n /** Set once a session could not be opened: `fetch` for this origin from then on. */\n failed?: boolean;\n}\n\nconst origins = new Map<string, Origin>();\n\n/**\n * Requests in progress on each session. A session's socket is referenced only while this is above\n * zero, so an idle session never keeps the process alive. Counted per session, not per origin: a\n * session the origin has stopped using (GOAWAY) is still released by the requests that were on it.\n */\nconst inFlight = new WeakMap<Session, number>();\n/** Sessions that received GOAWAY: closed once their last request finishes. */\nconst retired = new WeakSet<Session>();\n\nfunction hold(s: Session): void {\n inFlight.set(s, (inFlight.get(s) ?? 0) + 1);\n s.ref();\n}\n\nfunction release(s: Session): void {\n const n = (inFlight.get(s) ?? 1) - 1;\n inFlight.set(s, n);\n if (n > 0 || s.destroyed) return;\n if (retired.has(s)) s.close();\n else s.unref();\n}\n\nfunction abortError(signal: AbortSignal): unknown {\n return signal.reason ?? new Error('The operation was aborted');\n}\n\n/** p, or the signal's abort, whichever comes first; p itself is left to settle for its other waiters. */\nfunction untilAborted<T>(p: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(abortError(signal));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** Each stream's and the whole session's receive window. */\nconst WINDOW_BYTES = 16 * 1024 * 1024;\nconst SESSION_WINDOW_BYTES = 64 * 1024 * 1024;\n\n/** How long opening a session may take before the origin falls back to `fetch`. */\nconst CONNECT_TIMEOUT_MS = 10_000;\n\n/**\n * KOSA8_HTTP_TRANSPORT: unset (auto), `fetch` (never HTTP/2), or `http2` (HTTP/2 even when the\n * global fetch was replaced, and plaintext h2c to a loopback `http:` URL, for tests).\n */\nfunction mode(): 'auto' | 'fetch' | 'http2' {\n const m = typeof process !== 'undefined' ? process.env?.KOSA8_HTTP_TRANSPORT : undefined;\n return m === 'fetch' || m === 'http2' ? m : 'auto';\n}\n\nfunction originOf(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return u.origin;\n const loopback = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';\n return u.protocol === 'http:' && loopback && mode() === 'http2' ? u.origin : null;\n } catch {\n return null;\n }\n}\n\nfunction useHttp2(): boolean {\n if (typeof process === 'undefined' || !process.versions?.node) return false;\n const m = mode();\n if (m === 'fetch') return false;\n return m === 'http2' || (typeof fetch === 'function' && fetch === nativeFetch);\n}\n\nfunction session(origin: string): Promise<Session | null> {\n let o = origins.get(origin);\n if (!o) {\n o = {};\n origins.set(origin, o);\n }\n if (o.failed) return Promise.resolve(null);\n if (o.session) return o.session;\n const entry = o;\n const opening: Promise<Session | null> = loadHttp2().then((http2) => {\n if (!http2) {\n entry.failed = true;\n return null;\n }\n return new Promise<Session | null>((resolve) => {\n let settled = false;\n // Large flow-control windows, so a big file moves at the link's speed rather than 64 KiB\n // per round trip (HTTP/2's default window).\n const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n entry.failed = true;\n s.destroy();\n resolve(null);\n }, CONNECT_TIMEOUT_MS);\n timer.unref?.();\n const forget = () => {\n if (entry.session === opening) entry.session = undefined;\n };\n s.once('connect', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n s.setLocalWindowSize(SESSION_WINDOW_BYTES);\n } catch {\n // An older Node: the default window.\n }\n // Unreferenced until a request holds it (hold), so a preconnect alone never keeps the\n // process alive.\n if (!inFlight.get(s)) s.unref();\n resolve(s);\n });\n s.on('error', () => {\n forget();\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n entry.failed = true;\n resolve(null);\n }\n });\n s.once('goaway', () => {\n // No new streams on it: later requests open a new session, and this one is closed once\n // the requests already on it finish.\n forget();\n retired.add(s);\n if (!inFlight.get(s)) s.close();\n });\n s.once('close', forget);\n });\n });\n entry.session = opening;\n return opening;\n}\n\n/** Opens the session to url's origin now, so the first request does not pay the handshake. */\nexport function preconnect(url: string): void {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return;\n void session(origin);\n}\n\nasync function viaFetch(url: string, init: HttpInit): Promise<HttpResponse> {\n const res = await fetch(url, {\n method: init.method,\n headers: init.headers,\n // A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).\n body: init.body as BodyInit | undefined,\n signal: init.signal,\n });\n const headers: Record<string, string> = {};\n res.headers?.forEach?.((v, k) => (headers[k.toLowerCase()] = v));\n if (init.binary) {\n return { status: res.status, ok: res.ok, text: '', bytes: new Uint8Array(await res.arrayBuffer()), headers };\n }\n return { status: res.status, ok: res.ok, text: await res.text(), headers };\n}\n\n/** One request: over the origin's HTTP/2 session when there is one, else `fetch`. */\nexport async function httpRequest(url: string, init: HttpInit): Promise<HttpResponse> {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return viaFetch(url, init);\n // Waiting for the session honours this request's abort; the opening itself goes on for the\n // other requests sharing it.\n const s = await untilAborted(session(origin), init.signal);\n if (!s || s.closed || s.destroyed) return viaFetch(url, init);\n hold(s);\n try {\n return await viaSession(s, url, init);\n } catch (e) {\n // The server took no part in the request (refused stream, or the session was going away\n // or gone when it was sent): sent once more, over fetch. Anything else may have been\n // processed and is reported, never repeated.\n if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);\n throw e;\n } finally {\n release(s);\n }\n}\n\nfunction notProcessed(e: unknown): boolean {\n const x = e as { code?: string; rstCode?: number } | null;\n return (\n !!x &&\n (x.code === 'ERR_HTTP2_GOAWAY_SESSION' ||\n x.code === 'ERR_HTTP2_INVALID_SESSION' ||\n x.rstCode === 7) /* REFUSED_STREAM */\n );\n}\n\nfunction viaSession(s: Session, url: string, init: HttpInit): Promise<HttpResponse> {\n const u = new URL(url);\n return new Promise<HttpResponse>((resolve, reject) => {\n const headers: Record<string, string> = {\n ':method': init.method,\n ':path': u.pathname + u.search,\n };\n for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;\n let req: import('node:http2').ClientHttp2Stream;\n try {\n req = s.request(headers);\n } catch (e) {\n reject(e);\n return;\n }\n let done = false;\n const finish = (f: () => void) => {\n if (done) return;\n done = true;\n init.signal?.removeEventListener('abort', onAbort);\n f();\n };\n const aborted = () => (init.signal ? abortError(init.signal) : new Error('The operation was aborted'));\n const onAbort = () => {\n finish(() => reject(aborted()));\n req.close(0x8); // NGHTTP2_CANCEL\n };\n if (init.signal) {\n if (init.signal.aborted) {\n onAbort();\n return;\n }\n init.signal.addEventListener('abort', onAbort, { once: true });\n }\n const chunks: Buffer[] = [];\n let status = 0;\n const got: Record<string, string> = {};\n req.on('response', (h) => {\n status = Number(h[':status'] ?? 0);\n for (const [k, v] of Object.entries(h)) if (!k.startsWith(':') && v !== undefined) got[k] = String(v);\n });\n req.on('data', (c: Buffer) => chunks.push(c));\n // Settled on 'close', the last event. Node emits 'end' even when the connection drops part way\n // through the body (the session is already destroyed by then), so only a stream that ended\n // while its session was alive, and closed without a reset (rstCode 0, NO_ERROR), is an answer.\n // Anything else (no response, an interrupted body) is an error, never a truncated answer and\n // never left pending. finish ignores this after 'error'.\n let ended = false;\n req.on('end', () => {\n ended = !s.destroyed;\n });\n req.on('close', () => {\n if (status !== 0 && ended && !req.rstCode) {\n const body = Buffer.concat(chunks);\n finish(() =>\n resolve({\n status,\n ok: status >= 200 && status < 300,\n text: init.binary ? '' : body.toString('utf8'),\n ...(init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {}),\n headers: got,\n }),\n );\n return;\n }\n const why = status === 0 ? 'without a response' : 'before the response completed';\n finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));\n });\n req.on('error', (e) =>\n finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode }))),\n );\n req.end(init.body);\n });\n}\n\n/** Closes every session (for tests and orderly shutdown). */\nexport function closeSessions(): void {\n for (const o of origins.values()) {\n void o.session?.then((s) => s?.close());\n }\n origins.clear();\n}\n","/**\n * File content for the kosa8 provider.\n *\n * kosa8's file stream takes and returns a file's raw bytes at any absolute path:\n * `PUT`/`GET …/files?path=`, with `offset=` on a PUT (the rest of the file kept) and `Range` on a\n * GET. It is reached two ways, tried in this order:\n *\n * 1. Straight on the sandbox's host, at the direct token's `files_url`, when the token covers files.\n * This skips the API's Worker and Cloudflare's 100 MB request limit.\n * 2. Through the API, `/v1/sandboxes/{id}/files`.\n *\n * A file of at most one part (64 MiB) is one request. A larger one is sent in parts to a\n * temporary name beside it — the first part creates it, the rest are written at their offsets in\n * parallel — and renamed over its path once every part landed, so a failed part leaves the file\n * it replaces intact. It is read the same way, with ranges.\n *\n * An older host has the base64 file API instead: /workspace only, 8 MiB at most, no offsets. Its\n * refusals (400 outside /workspace, 413, 501) send the file over exec instead, in base64 chunks.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { escapeShellArg } from '@computesdk/provider';\nimport { httpRequest, type HttpResponse } from './transport';\n\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\nimport type { Kosa8Sandbox } from './index';\n\nexport type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/** Where file requests go: the host's own files URL with the direct token, or the API with the key. */\nexport interface FileTarget {\n url: string;\n token: string;\n}\n\n/**\n * Bytes per request (under the API's 100 MB request body limit), and parts moved at once: reads\n * four, writes two (four 64 MiB uploads at once on one connection sometimes made the host's HTTP/2\n * server end it with ENHANCE_YOUR_CALM, and two are about as fast). A mutable object so tests can\n * use small parts.\n */\nexport const fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };\n/**\n * Times a request that failed in transit, or with a server error, is sent again. Cloudflare's\n * 52x (host unreachable) are not retried: from the files URL they send the request to the API.\n */\nconst FILE_RETRIES = 2;\nconst RETRY_STATUS = new Set([500, 502, 503, 504]);\n\n/**\n * Statuses from the host's files URL that mean the request was not served there: the token was\n * refused (401), the sandbox is asleep and only the API wakes it (409), the host does not offer it\n * (501), or Cloudflare could not reach the host. The request then goes through the API. 403 and 404\n * are not here: from the files URL they mean permission denied and no such file.\n */\nconst DIRECT_REFUSED = new Set([401, 409, 501, 521, 522, 523, 530]);\n\n/**\n * Base64 characters per write exec (the fallback for older hosts). The exec API caps each argv\n * entry at 8192 characters, so content travels in an environment variable, which counts only toward\n * the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 48 * 1024;\n/** A file this small is read inline by one exec (fallback); its base64 stays under the exec output limit. */\nexport const INLINE_READ_BYTES = 1024 * 1024;\n\nconst NOT_FOUND_EXIT = 44;\nconst MIB = 1024 * 1024;\n\nconst q = (s: string) => `\"${escapeShellArg(s)}\"`;\nconst notFound = (path: string) => new Error(`ENOENT: no such file or directory, open '${path}'`);\n\nconst apiTarget = (sandbox: Kosa8Sandbox): FileTarget => ({\n url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,\n token: sandbox.apiKey,\n});\n\nfunction errorDetail(res: HttpResponse): string {\n const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString('utf8') : '');\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n return text.slice(0, 500);\n}\n\n/** The error for a refused file request, with Node's codes for the common ones. */\nfunction fileError(res: HttpResponse, op: 'open' | 'write', path: string): Error {\n const detail = errorDetail(res);\n if (res.status === 404) return notFound(path);\n if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ''}`);\n}\n\n/**\n * A refusal from the older base64 file API (or a host without any): a path outside /workspace,\n * a file over its 8 MiB, or offsets and streams it does not have. Exec reaches those.\n */\nfunction olderFileApi(res: HttpResponse): boolean {\n return res.status === 413 || res.status === 501 || (res.status === 400 && /workspace/i.test(errorDetail(res)));\n}\n\nasync function send(\n t: FileTarget,\n method: 'GET' | 'PUT',\n path: string,\n { body, offset, range }: { body?: Uint8Array; offset?: number; range?: [number, number] } = {},\n): Promise<HttpResponse> {\n const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ''}`;\n const headers: Record<string, string> = { Authorization: `Bearer ${t.token}` };\n if (body) headers['Content-Type'] = 'application/octet-stream';\n if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;\n // Every request here is idempotent (a whole file, a part at its offset, or a read), so one that\n // failed in transit or with a server error is sent again.\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await httpRequest(url, { method, headers, body, binary: true });\n if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;\n } catch (err) {\n if (attempt >= FILE_RETRIES) throw err;\n }\n await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));\n }\n}\n\n/**\n * Runs task over items, at most `limit` at once. After a task fails no more are started, and the\n * first failure is returned (or thrown) once the ones in progress have finished.\n */\nasync function inParallel<T, R>(items: T[], limit: number, task: (item: T) => Promise<R | null>): Promise<R | null> {\n let next = 0;\n let failed: R | null = null;\n let thrown: { err: unknown } | undefined;\n const worker = async () => {\n while (!failed && !thrown && next < items.length) {\n try {\n const r = await task(items[next++]);\n if (r) failed ??= r;\n } catch (err) {\n thrown ??= { err };\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n if (thrown) throw thrown.err;\n return failed;\n}\n\n/** Writes bytes at path through t: null when written, else the refusal. */\nasync function writeTo(t: FileTarget, path: string, bytes: Uint8Array): Promise<HttpResponse | null> {\n // The first part replaces the file (creating its directories); the rest are written at their offsets.\n const first = await send(t, 'PUT', path, { body: bytes.subarray(0, fileParts.bytes) });\n if (!first.ok) return first;\n const offsets: number[] = [];\n for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);\n return inParallel(offsets, fileParts.writeConcurrency, async (at) => {\n const res = await send(t, 'PUT', path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });\n return res.ok ? null : res;\n });\n}\n\n/** Reads path through t: its bytes, or the refusal. */\nasync function readFrom(t: FileTarget, path: string): Promise<Uint8Array | HttpResponse> {\n const first = await send(t, 'GET', path, { range: [0, fileParts.bytes - 1] });\n // 416: the first byte is past the end, so the file is empty.\n if (first.status === 416) return new Uint8Array();\n // 200: the whole file (a server that ignores Range).\n if (first.status === 200) return first.bytes ?? new Uint8Array();\n if (first.status !== 206) return first;\n const head = first.bytes ?? new Uint8Array();\n const total = Number(/\\/(\\d+)\\s*$/.exec(first.headers['content-range'] ?? '')?.[1] ?? head.length);\n if (total <= head.length) return head;\n const starts: number[] = [];\n for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);\n const parts = new Map<number, Uint8Array>();\n const failed = await inParallel(starts, fileParts.concurrency, async (at) => {\n const res = await send(t, 'GET', path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });\n if (res.status !== 206 && res.status !== 200) return res;\n parts.set(at, res.bytes ?? new Uint8Array());\n return null;\n });\n if (failed) return failed;\n const all = Buffer.concat([head, ...starts.map((at) => parts.get(at)!)]);\n if (all.length !== total) {\n throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);\n }\n return all;\n}\n\n// --- write -------------------------------------------------------------------\n\n/**\n * Writes a file: straight to the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function writeFileNative(\n sandbox: Kosa8Sandbox,\n path: string,\n content: string,\n run: ExecRunner,\n direct: FileTarget | null = null,\n): Promise<void> {\n const bytes = Buffer.from(content, 'utf8');\n const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${randomBytes(6).toString('hex')}` : null;\n const dest = staged ?? path;\n const commit = async () => {\n // `[ -d ]` first: `mv` onto an existing directory would move the staged file inside it.\n if (staged) {\n await mustSucceed(\n run,\n sandbox,\n `if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,\n 'write',\n path,\n );\n }\n };\n try {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const res = await writeTo(direct, dest, bytes).catch(() => undefined);\n if (res === null) {\n await commit();\n return;\n }\n if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, 'write', path);\n if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const res = await writeTo(apiTarget(sandbox), dest, bytes);\n if (!res) {\n await commit();\n return;\n }\n if (!olderFileApi(res)) throw fileError(res, 'write', path);\n if (res.status === 501) sandbox.files = false;\n }\n return writeFileViaExec(sandbox, path, bytes, run);\n } finally {\n if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {});\n }\n}\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, what: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n if ((result as { stdoutTruncated?: boolean }).stdoutTruncated) {\n throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);\n }\n return result.stdout;\n}\n\n/**\n * Writes a file through exec (older hosts): base64 chunks into a temporary file beside it, then an\n * atomic rename. One chunk is a single command.\n */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void> {\n const target = q(path);\n const tmp = q(`${path}.computesdk-${randomBytes(6).toString('hex')}`);\n const encoded = Buffer.from(content).toString('base64');\n const mkParent = `d=$(dirname ${target}) && mkdir -p \"$d\"`;\n if (encoded.length <= WRITE_CHUNK_CHARS) {\n const cmd = `${mkParent} && printf '%s' \"$KOSA8_CHUNK\" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;\n await mustSucceed(run, sandbox, cmd, 'write', path, { KOSA8_CHUNK: encoded });\n return;\n }\n try {\n await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, 'write', path);\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, 'write', path, {\n KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS),\n });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, 'write', path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\n// --- read --------------------------------------------------------------------\n\nconst fromBase64 = (s: string) => Buffer.from(s.replace(/\\s+/g, ''), 'base64');\n\n/**\n * Reads a file: straight from the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function readFileNative(sandbox: Kosa8Sandbox, path: string, run: ExecRunner, direct: FileTarget | null = null): Promise<string> {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const got = await readFrom(direct, path).catch(() => undefined);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, 'open', path);\n if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const got = await readFrom(apiTarget(sandbox), path);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (!olderFileApi(got)) throw fileError(got, 'open', path);\n if (got.status === 501) sandbox.files = false;\n }\n return readFileViaExec(sandbox, path, run);\n}\n\n/** Reads a file through exec (older hosts): inline when small, else 1 MiB per command. */\nasync function readFileViaExec(sandbox: Kosa8Sandbox, path: string, run: ExecRunner): Promise<string> {\n const p = q(path);\n const out = await mustSucceed(\n run,\n sandbox,\n `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo \"$s\"; if [ \"$s\" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,\n 'open',\n path,\n );\n const nl = out.indexOf('\\n');\n const size = Number(out.slice(0, nl < 0 ? undefined : nl).trim());\n if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);\n if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? '' : out.slice(nl + 1)).toString('utf8');\n const chunks: Buffer[] = new Array(Math.ceil(size / INLINE_READ_BYTES));\n let next = 0;\n const worker = async () => {\n while (next < chunks.length) {\n const i = next++;\n chunks[i] = fromBase64(\n await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, 'open', path),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));\n const all = Buffer.concat(chunks);\n if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);\n return all.toString('utf8');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,IAAAA,mBAAgE;;;ACwBhE,IAAM,cAAwC,OAAO,UAAU,aAAa,QAAQ;AAEpF,IAAI;AACJ,SAAS,YAAmC;AAC1C,4BAAc,OAAO,OAAY,EAAE;AAAA,IACjC,CAAC,MAAQ,EAAqC,WAAW;AAAA,IACzD,MAAM;AAAA,EACR;AACA,SAAO;AACT;AAQA,IAAM,UAAU,oBAAI,IAAoB;AAOxC,IAAM,WAAW,oBAAI,QAAyB;AAE9C,IAAM,UAAU,oBAAI,QAAiB;AAErC,SAAS,KAAK,GAAkB;AAC9B,WAAS,IAAI,IAAI,SAAS,IAAI,CAAC,KAAK,KAAK,CAAC;AAC1C,IAAE,IAAI;AACR;AAEA,SAAS,QAAQ,GAAkB;AACjC,QAAM,KAAK,SAAS,IAAI,CAAC,KAAK,KAAK;AACnC,WAAS,IAAI,GAAG,CAAC;AACjB,MAAI,IAAI,KAAK,EAAE,UAAW;AAC1B,MAAI,QAAQ,IAAI,CAAC,EAAG,GAAE,MAAM;AAAA,MACvB,GAAE,MAAM;AACf;AAEA,SAAS,WAAW,QAA8B;AAChD,SAAO,OAAO,UAAU,IAAI,MAAM,2BAA2B;AAC/D;AAGA,SAAS,aAAgB,GAAe,QAAkC;AACxE,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,OAAO,QAAS,QAAO,QAAQ,OAAO,WAAW,MAAM,CAAC;AAC5D,SAAO,IAAI,QAA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M,QAA4C,MAAM,OAAO,eAAe;AAC3F,gBAAQ,MAAM,aAAa,CAAC,GAAG,IAAI,CAAC,MAAM,WAAW,CAAC,CAAC;AAAA,MACzD;AAAA;AAAA,MAGA,QAAQ,OAAO,QAAqB,eAAsC;AACxE,cAAM,OAAO,cAAc,MAAM;AACjC,cAAM,QAAQ,MAAM,UAAU,iBAAiB,mBAAmB,UAAU,CAAC,EAAE;AAAA,MACjF;AAAA,IACF;AAAA,IAEA,UAAU;AAAA,MACR,QAAQ,YAAY;AAClB,cAAM,aAAa,yDAAyD;AAAA,MAC9E;AAAA,MACA,MAAM,OAAO,WAAkD;AAC7D,cAAM,OAAO,cAAc,MAAM;AACjC,cAAM,OAAO,MAAM,QAAwC,MAAM,OAAO,eAAe;AACvF,eAAO,MAAM,aAAa,CAAC;AAAA,MAC7B;AAAA,MACA,QAAQ,YAAY;AAClB,cAAM,aAAa,yDAAyD;AAAA,MAC9E;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAMM,IAAM,QAAyB,CAAC,WAAW;AAChD,MAAI;AACF,eAAW,cAAc,MAAM,EAAE,OAAO;AAAA,EAC1C,QAAQ;AAAA,EAER;AACA,SAAO,SAAS,MAAM;AACxB;AAEA,IAAO,gBAAQ;","names":["import_provider"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/transport.ts","../src/files.ts"],"sourcesContent":["/**\n * kosa8 Provider - Factory-based Implementation\n *\n * Sandboxes on kosa8 Cloud (https://kosa8.com). Each sandbox runs in its own microVM with its\n * own kernel. The cloud API is a small JSON surface, so this package talks to it with `fetch`\n * and has no SDK dependency.\n *\n * Commands go through the buffered exec endpoint: straight to the sandbox's host when the create\n * answer carries a direct-exec URL and token (see runDirect), otherwise through the API. File content\n * moves through kosa8's file API (`/v1/sandboxes/{id}/files`, see files.ts), with shell commands\n * over exec for small files and for hosts without it. `pause()`/`resume()` map to kosa8's sleep and\n * wake, and `provider.snapshot` to kosa8 snapshots: both keep the VM's memory (running processes)\n * as well as its disk.\n */\n\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\nimport { httpRequest, preconnect } from './transport';\nimport { readFileNative, writeFileNative, type ExecRunner } from './files';\n\nexport { WRITE_CHUNK_CHARS, writeFileViaExec } from './files';\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateSnapshotOptions,\n InstanceInfo,\n InstanceSizeClass,\n RunCommandOptions,\n SnapshotCapabilities,\n} from '@computesdk/provider';\n\nexport interface Kosa8Config {\n /** Template to boot per standard `sizeClass`. The template fixes CPU and memory, so build one per size. */\n sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;\n /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */\n apiKey?: string;\n /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */\n baseUrl?: string;\n /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */\n region?: string;\n}\n\n/** A sandbox as the kosa8 Cloud API returns it. */\nexport interface Kosa8SandboxData {\n id: string;\n state: string;\n template: string;\n cpus: number;\n mem_mb: number;\n region: string | null;\n created_at: number;\n started_at: number | null;\n sleep_after_s: number | null;\n delete_after: number | null;\n last_error: string | null;\n [key: string]: unknown;\n}\n\n/** A template as GET /v1/templates returns it. */\nexport interface Kosa8Template {\n key: string;\n cpus: number;\n mem_mb: number;\n image?: string;\n regions: string[];\n [key: string]: unknown;\n}\n\n/** The create answer's `direct` object: the host's exec endpoint for this sandbox and a token for it. */\nexport interface Kosa8Direct {\n exec_url: string;\n /** The host's raw file endpoint for this sandbox, when the token also covers files (`files.direct`). */\n files_url?: string;\n token: string;\n /** When the token stops working, ms since the epoch. */\n expires_at: number;\n}\n\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\n /** Present while commands can go straight to the sandbox's host (runDirect). */\n direct?: Kosa8Direct;\n /** A fresh direct token being fetched (refreshDirect). */\n refreshing?: Promise<void>;\n /** False once the sandbox's host answered that it has no file API: files then go over exec. */\n files?: boolean;\n /** False once the host refused file requests with the direct token: files then go through the API. */\n directFiles?: boolean;\n}\n\n/** A snapshot as the kosa8 Cloud API returns it. */\nexport interface Kosa8SnapshotData {\n id: string;\n name: string | null;\n state: string;\n source_sandbox_id: string;\n template: string;\n cpus: number;\n mem_mb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n created_at: number;\n [key: string]: unknown;\n}\n\n/** A snapshot as `provider.snapshot` returns it. */\nexport interface Kosa8Snapshot {\n id: string;\n provider: 'kosa8';\n createdAt: Date;\n metadata: {\n name: string | null;\n sourceInstanceId: string;\n state: string;\n template: string;\n cpus: number;\n memMb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n /** How long the host took to save it, when the API reports it. */\n createMs?: number | null;\n };\n}\n\ninterface Auth {\n apiKey: string;\n baseUrl: string;\n}\n\ninterface ExecResponse {\n exit: number | null;\n stdout: string;\n stderr: string;\n /** Set when the API kept only the first part of a stream (its output limit). */\n stdout_truncated?: boolean;\n stderr_truncated?: boolean;\n /** The stream's full length, kept or not. */\n stdout_bytes?: number;\n stderr_bytes?: number;\n}\n\n/**\n * A command's result. Beyond ComputeSDK's fields it says when the API returned only the first part\n * of the output (its limit on a buffered command): `truncated`, per stream, and each stream's full\n * length in bytes. These are absent when the API does not report them.\n */\nexport interface Kosa8CommandResult extends CommandResult {\n truncated?: boolean;\n stdoutTruncated?: boolean;\n stderrTruncated?: boolean;\n stdoutBytes?: number;\n stderrBytes?: number;\n}\n\n/** The API's shortest and longest lifetime for a sandbox (ttl_s). */\nconst MIN_TTL_S = 60;\nconst MAX_TTL_S = 90 * 86400;\n\n/** Exit code reported when `runCommand`'s timeout stops a command (as coreutils `timeout` does). */\nconst TIMEOUT_EXIT = 124;\n\n/** Names the marker file a timed command creates once it returns (see execArgv). */\nconst DONE_ENV = 'KOSA8_DONE';\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template (or an image) fixes the size. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'envs', 'volumes',\n] as const;\n\n/** A snapshot name the API accepts; another name is kept only in the snapshot's metadata. */\nconst SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\nfunction resolveConfig(config: Kosa8Config): Auth {\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const apiKey = config.apiKey || env?.KOSA8_API_KEY || '';\n if (!apiKey) {\n throw new Error(\n `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. ` +\n `Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`,\n );\n }\n const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || 'https://api.kosa8.com').replace(/\\/+$/, '');\n return { apiKey, baseUrl };\n}\n\nasync function request<T>(\n auth: Auth,\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n): Promise<T | null> {\n const res = await httpRequest(`${auth.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n if (res.status === 404) return null;\n const text = res.text;\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);\n }\n return (text ? JSON.parse(text) : null) as T;\n}\n\nconst sandboxPath = (id: string, rest = '') => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;\n\nfunction toSandbox(auth: Auth, data: Kosa8SandboxData, direct?: unknown): Kosa8Sandbox {\n const sandbox: Kosa8Sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\n if (isDirect(direct)) {\n sandbox.direct = direct;\n // The first command follows at once: its host's session opens now.\n preconnect(direct.exec_url);\n }\n return sandbox;\n}\n\nfunction isDirect(d: unknown): d is Kosa8Direct {\n const x = d as Kosa8Direct | null | undefined;\n return !!x && typeof x.exec_url === 'string' && /^https:\\/\\//.test(x.exec_url) && typeof x.token === 'string' &&\n typeof x.expires_at === 'number';\n}\n\n/** A direct token this close to expiry is not used; one closer than DIRECT_REFRESH_MS is renewed in the background. */\nconst DIRECT_MARGIN_MS = 15_000;\nconst DIRECT_REFRESH_MS = 60_000;\n\n/**\n * Statuses from the direct endpoint that mean the command did not run there: the token was refused\n * (401, 403), the host does not have the sandbox (404), it is asleep and only the API wakes it\n * (409), the host does not offer it (501), or Cloudflare could not reach the host (521, 522, 523,\n * 530). The command is then sent through the API. Any other failure is reported as is, since the\n * command may have run.\n */\nconst DIRECT_NOT_RUN = new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);\n\n/**\n * The direct token and files URL for file requests, or null when files go through the API: no\n * token, a host whose token does not cover files, one that refused it, or a token about to expire\n * (renewed in the background, as for commands).\n */\nexport function directFiles(sandbox: Kosa8Sandbox): { url: string; token: string } | null {\n const d = sandbox.direct;\n if (!d?.files_url || sandbox.directFiles === false || !/^https:\\/\\//.test(d.files_url)) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };\n}\n\n/** Renews the direct token in the background; a failure leaves the API path in use. */\nfunction refreshDirect(sandbox: Kosa8Sandbox): void {\n if (sandbox.refreshing) return;\n sandbox.refreshing = request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct'))\n .then((r) => {\n if (isDirect(r?.direct)) sandbox.direct = r.direct;\n })\n .catch(() => {})\n .finally(() => {\n sandbox.refreshing = undefined;\n });\n}\n\n/**\n * Runs a command on the sandbox's host directly (the create answer's `direct`), skipping the API's\n * hop. Returns null when the command was not run there, so the caller sends it through the API;\n * the sandbox then stops using the direct path until a fresh token arrives.\n */\nasync function runDirect(sandbox: Kosa8Sandbox, body: unknown, signal?: AbortSignal): Promise<ExecResponse | null> {\n const d = sandbox.direct;\n if (!d) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n if (left < DIRECT_MARGIN_MS) return null;\n const res = await httpRequest(d.exec_url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${d.token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal,\n });\n const text = res.text;\n if (DIRECT_NOT_RUN.has(res.status)) {\n if (sandbox.direct === d) sandbox.direct = undefined;\n return null;\n }\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string };\n if (parsed?.error) detail = parsed.error;\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);\n }\n return JSON.parse(text) as ExecResponse;\n}\n\n/** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */\nexport function createBody(config: Kosa8Config, options: CreateInstanceOptions = {}): Record<string, unknown> {\n for (const key of UNSUPPORTED_CREATE_OPTIONS) {\n if (options[key] !== undefined) {\n throw new Error(\n `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; ` +\n `pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n if (options.snapshotId !== undefined) {\n // A sandbox made from a snapshot takes its template, size, image and host from the snapshot.\n for (const key of ['templateId', 'image', 'region'] as const) {\n if (options[key] !== undefined) {\n throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);\n }\n }\n body.snapshot = options.snapshotId;\n } else if (options.image !== undefined) {\n // An OCI image boots a VM of its own (the API's default size for an image, 2 vCPU / 4 GiB),\n // so the configured default template does not apply; an explicit templateId is passed on.\n body.image = options.image;\n if (options.templateId) body.template = options.templateId;\n } else {\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n }\n if (options.snapshotId === undefined) {\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\n }\n if (options.sleepAfterSeconds !== undefined) body.sleep_after_s = options.sleepAfterSeconds;\n if (typeof options.timeout === 'number' && options.timeout > 0) {\n // kosa8 deletes the sandbox when its lifetime ends; the API's shortest lifetime is 60 s.\n body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1000)));\n }\n return body;\n}\n\n/** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */\nexport function execArgv(command: string, options?: RunCommandOptions): string[] {\n let cmd = command;\n if (options?.cwd) cmd = `cd \"${escapeShellArg(options.cwd)}\" && ${cmd}`;\n if (options?.background) {\n cmd = `nohup sh -c \"${escapeShellArg(cmd)}\" >/dev/null 2>&1 &`;\n } else if (options?.timeout && options.timeout > 0) {\n // Stop the command in the sandbox, not just the wait for it. GNU timeout signals the whole\n // process group; an image without `timeout` runs the command unbounded and the request's\n // own deadline (runCommand) still applies.\n //\n // Status 137 alone does not mean the deadline passed: the command may exit 137 itself or be\n // killed early. The command runs in a subshell and a marker file is created once it returns,\n // whatever its status. Only a 137 with no marker (the shell itself was killed) once the\n // deadline has passed (whole seconds: the elapsed count cannot fall short of a real deadline)\n // is reported as a timeout.\n const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const plain = `sh -c \"${escapeShellArg(cmd)}\"`;\n const marked = `sh -c \"${escapeShellArg(`(\\n${cmd}\\n); s=$?; : > \"$${DONE_ENV}\"; exit $s`)}\"`;\n cmd =\n `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then ` +\n `rm -f \"$${DONE_ENV}\"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; ` +\n `if [ $s -eq 137 ] && [ ! -e \"$${DONE_ENV}\" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; ` +\n `rm -f \"$${DONE_ENV}\"; exit $s; ` +\n `else ${plain}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/**\n * The exec API's limit on each argv entry. Measured in UTF-8 bytes here, which is never less than\n * the API's own count, so a command with multibyte characters cannot slip over it.\n */\nconst MAX_ARG_BYTES = 8192;\n\n/** The exec API's limit on the whole request body, in bytes. */\nexport const MAX_EXEC_BODY_BYTES = 64 * 1024;\n\n/** Environment variable that carries a script too long for one argv entry; callers may not set it. */\nexport const SCRIPT_ENV = 'KOSA8_SCRIPT';\n\n/**\n * The exec request body: a script too long for one argv entry travels in an environment variable.\n * Throws before any request is made when the serialized body would exceed the exec API's limit.\n */\nexport function execBody(command: string, options?: RunCommandOptions): { cmd: string[]; env: string[] } {\n const argv = execArgv(command, options);\n const env = execEnv(options?.env);\n const body = Buffer.byteLength(argv[2], 'utf8') <= MAX_ARG_BYTES\n ? { cmd: argv, env }\n : { cmd: ['sh', '-c', `eval \"$${SCRIPT_ENV}\"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };\n const size = Buffer.byteLength(JSON.stringify(body), 'utf8');\n if (size > MAX_EXEC_BODY_BYTES) {\n throw new Error(\n `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) ` +\n `for the command and its environment together. Write a long script to a file with ` +\n `sandbox.filesystem.writeFile() and run that file instead.`,\n );\n }\n return body;\n}\n\nfunction execEnv(env?: Record<string, string>): string[] {\n if (!env) return [];\n return Object.entries(env).map(([key, value]) => {\n if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n if (key === SCRIPT_ENV) {\n throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);\n }\n return `${key}=${value}`;\n });\n}\n\nfunction infoStatus(state: string): InstanceInfo['status'] {\n if (state === 'error') return 'error';\n // A sleeping sandbox is alive: its memory and disk are saved, and any call (a command, a file\n // read or write) wakes it in about a second, so it reports as running.\n if (state === 'running' || state === 'sleeping') return 'running';\n // creating, paused, stopped, deleted and expired (past its deadline): not running now, so a\n // readiness check keeps waiting and a liveness check sees it gone.\n return 'stopped';\n}\n\nasync function getData(sandbox: Kosa8Sandbox): Promise<Kosa8SandboxData | null> {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id));\n return data?.sandbox ?? null;\n}\n\n/** How often a sandbox that is still booting (an image's cold boot) is checked, and for how long. */\nconst BOOT_POLL_MS = 150;\nconst BOOT_TIMEOUT_MS = 5 * 60_000;\n\n/**\n * Waits for a sandbox the API answered with `creating` (202: an image booted cold) to run, so the\n * create resolves to a sandbox that takes commands. Its direct exec token is fetched once it runs.\n */\nasync function waitUntilRunning(sandbox: Kosa8Sandbox, signal?: AbortSignal): Promise<void> {\n const deadline = Date.now() + BOOT_TIMEOUT_MS;\n while (sandbox.data.state === 'creating') {\n if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1000} s`);\n signal?.throwIfAborted();\n await new Promise((r) => setTimeout(r, BOOT_POLL_MS));\n const current = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id), undefined, signal);\n if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);\n sandbox.data = current.sandbox;\n }\n if (sandbox.data.state !== 'running') {\n const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : '';\n throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);\n }\n if (!sandbox.direct) {\n const r = await request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct')).catch(() => null);\n if (isDirect(r?.direct)) {\n sandbox.direct = r.direct;\n preconnect(r.direct.exec_url);\n }\n }\n}\n\nfunction toSnapshot(s: Kosa8SnapshotData, createMs?: number | null): Kosa8Snapshot {\n return {\n id: s.id,\n provider: 'kosa8',\n createdAt: new Date(s.created_at),\n metadata: {\n name: s.name ?? null,\n sourceInstanceId: s.source_sandbox_id,\n state: s.state,\n template: s.template,\n cpus: s.cpus,\n memMb: s.mem_mb,\n image: s.image ?? null,\n bytes: s.bytes ?? 0,\n region: s.region ?? null,\n ...(createMs !== undefined ? { createMs } : {}),\n },\n };\n}\n\n/**\n * kosa8 snapshots save the whole VM, memory included, so a restore resumes running processes. The\n * source keeps running, and one snapshot restores into any number of sandboxes, each copy-on-write\n * on the snapshot's host. A snapshot is ready when `create` returns.\n */\nexport const SNAPSHOT_CAPABILITIES: SnapshotCapabilities = {\n scope: 'rootfs',\n memory: true,\n destroysSource: false,\n source: 'kept',\n fork: true,\n readiness: 'immediate',\n};\n\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nconst provider = defineProvider<Kosa8Sandbox, Kosa8Config>({\n name: 'kosa8',\n sizes: (config, profile, options) => {\n if (options?.templateId !== undefined || options?.snapshotId !== undefined) {\n return { status: 'unsupported', reason: 'A kosa8 template or snapshot fixes CPU and memory; drop templateId/snapshotId to boot the standard size template.' };\n }\n const templateId = config.sizeTemplates?.[profile.sizeClass];\n if (typeof templateId !== 'string' || !templateId.trim()) {\n return { status: 'unconfigured', reason: `kosa8 fixes CPU and memory per template; build one at ${profile.vcpus} vCPU / ${profile.memoryMiB} MiB and set sizeTemplates.${profile.sizeClass}.` };\n }\n return { status: 'supported', nativeOptions: { templateId } };\n },\n methods: {\n instances: {\n create: async (config: Kosa8Config, options?: CreateInstanceOptions) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData; direct?: unknown }>(\n auth,\n 'POST',\n '/v1/sandboxes',\n createBody(config, options),\n options?.signal,\n );\n if (!data?.sandbox) throw new Error('kosa8 API returned no sandbox on create');\n const sandbox = toSandbox(auth, data.sandbox, data.direct);\n if (sandbox.data.state !== 'running') {\n try {\n await waitUntilRunning(sandbox, options?.signal);\n } catch (err) {\n // A sandbox that never ran is not left behind, billed.\n await request(auth, 'DELETE', sandboxPath(sandbox.id)).catch(() => {});\n throw err;\n }\n }\n return { instance: sandbox, instanceId: sandbox.id };\n },\n\n getById: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData }>(auth, 'GET', sandboxPath(instanceId));\n return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;\n },\n\n list: async (config: Kosa8Config) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandboxes: Kosa8SandboxData[] }>(auth, 'GET', '/v1/sandboxes');\n return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));\n },\n\n destroy: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n // A sandbox that is already gone answers 404, which request() returns as null.\n await request(auth, 'DELETE', sandboxPath(instanceId));\n },\n\n runCommand: async (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions): Promise<Kosa8CommandResult> => {\n const start = Date.now();\n const body = execBody(command, options);\n // The command is stopped in the sandbox at the deadline; the request gets a grace period on top.\n const signal = options?.timeout && options.timeout > 0 && !options.background\n ? AbortSignal.timeout(options.timeout + 30_000)\n : undefined;\n const data = (await runDirect(sandbox, body, signal)) ??\n (await request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n const result: Kosa8CommandResult = {\n stdout: data.stdout ?? '',\n stderr: data.stderr ?? '',\n exitCode: Number.isInteger(data.exit) ? (data.exit as number) : -1,\n durationMs: Date.now() - start,\n };\n if (typeof data.stdout_truncated === 'boolean' || typeof data.stderr_truncated === 'boolean') {\n result.stdoutTruncated = data.stdout_truncated === true;\n result.stderrTruncated = data.stderr_truncated === true;\n result.truncated = result.stdoutTruncated || result.stderrTruncated;\n }\n if (typeof data.stdout_bytes === 'number') result.stdoutBytes = data.stdout_bytes;\n if (typeof data.stderr_bytes === 'number') result.stderrBytes = data.stderr_bytes;\n return result;\n },\n\n getInfo: async (sandbox: Kosa8Sandbox): Promise<InstanceInfo> => {\n const current = (await getData(sandbox)) ?? { ...sandbox.data, state: 'deleted' };\n sandbox.data = current;\n return {\n id: sandbox.id,\n provider: 'kosa8',\n status: infoStatus(current.state),\n createdAt: new Date(current.created_at),\n timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,\n metadata: {\n state: current.state,\n template: current.template,\n cpus: current.cpus,\n memMb: current.mem_mb,\n region: current.region,\n sleepAfterSeconds: current.sleep_after_s,\n deleteAfter: current.delete_after,\n lastError: current.last_error,\n },\n };\n },\n\n getUrl: async (): Promise<string> => {\n throw notAvailable('port URLs');\n },\n\n // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.\n pause: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/sleep'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n resume: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/wake'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n pauseCapabilities: { memory: true },\n\n // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.\n lifetime: {},\n\n // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.\n extendLifetime: async (sandbox: Kosa8Sandbox, ms: number): Promise<void> => {\n const current = await getData(sandbox);\n if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = current;\n if (current.delete_after == null) return;\n const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1000);\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'PATCH', sandboxPath(sandbox.id), {\n delete_after: Math.floor(deleteAfter),\n });\n // A 404 here means the sandbox was deleted between the read and the update.\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n if (data.sandbox) sandbox.data = data.sandbox;\n },\n\n getInstance: (sandbox: Kosa8Sandbox): Kosa8Sandbox => sandbox,\n\n // File content straight to the sandbox's host with the direct token, else through the API's\n // file stream, else (an older host) exec (files.ts); the rest are single shell commands.\n filesystem: {\n readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),\n writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),\n mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),\n readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),\n exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),\n remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path),\n },\n },\n\n snapshot: {\n capabilities: SNAPSHOT_CAPABILITIES,\n\n // POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.\n create: async (config: Kosa8Config, instanceId: string, options?: CreateSnapshotOptions): Promise<Kosa8Snapshot> => {\n const auth = resolveConfig(config);\n const name = typeof options?.name === 'string' && SNAPSHOT_NAME.test(options.name) ? options.name : undefined;\n const data = await request<{ snapshot: Kosa8SnapshotData; ms?: number | null }>(\n auth,\n 'POST',\n sandboxPath(instanceId, '/snapshots'),\n name ? { name } : {},\n );\n if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);\n return toSnapshot(data.snapshot, typeof data.ms === 'number' ? data.ms : null);\n },\n\n list: async (config: Kosa8Config): Promise<Kosa8Snapshot[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ snapshots: Kosa8SnapshotData[] }>(auth, 'GET', '/v1/snapshots');\n return (data?.snapshots ?? []).map((s) => toSnapshot(s));\n },\n\n // A snapshot that is already gone answers 404, which request() returns as null.\n delete: async (config: Kosa8Config, snapshotId: string): Promise<void> => {\n const auth = resolveConfig(config);\n await request(auth, 'DELETE', `/v1/snapshots/${encodeURIComponent(snapshotId)}`);\n },\n },\n\n template: {\n create: async () => {\n throw notAvailable('creating templates (templates are offered by the hosts)');\n },\n list: async (config: Kosa8Config): Promise<Kosa8Template[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ templates: Kosa8Template[] }>(auth, 'GET', '/v1/templates');\n return data?.templates ?? [];\n },\n delete: async () => {\n throw notAvailable('deleting templates (templates are offered by the hosts)');\n },\n },\n },\n});\n\n/**\n * The kosa8 provider. Configuring it opens the HTTP/2 session to the API (transport.ts), so the\n * first create does not pay the connection's handshake.\n */\nexport const kosa8: typeof provider = (config) => {\n try {\n preconnect(resolveConfig(config).baseUrl);\n } catch {\n // No key yet: the first call reports it.\n }\n return provider(config);\n};\n\nexport default kosa8;\n","/**\n * HTTP for the kosa8 provider: one HTTP/2 session per origin, shared by every request, instead of\n * a TLS connection per request.\n *\n * With `fetch`, 100 sandboxes created at once open 100 connections, each paying its own TCP and\n * TLS handshake before the request is sent. On kosa8 Cloud that was ~260 ms of each create in a\n * 100-at-once burst from Virginia (2026-11-13), against ~40 ms for a request on a connection that\n * was already open. Over one HTTP/2 session the handshake is paid once, and `preconnect` pays it\n * before the first request (when the provider is configured).\n *\n * `fetch` stays the fallback: where `node:http2` is not available, for an origin whose session\n * could not be opened, and whenever the global `fetch` has been replaced (tests, proxies,\n * instrumentation), which is then honoured for every request.\n */\n\ntype Http2 = typeof import('node:http2');\ntype Session = import('node:http2').ClientHttp2Session;\n\nexport interface HttpResponse {\n status: number;\n ok: boolean;\n /** The body as UTF-8 text; empty when the request asked for `binary`. */\n text: string;\n /** The body's bytes, present when the request asked for `binary`. */\n bytes?: Uint8Array;\n /** Response headers, names in lower case. */\n headers: Record<string, string>;\n}\n\nexport interface HttpInit {\n method: string;\n headers: Record<string, string>;\n body?: string | Uint8Array;\n signal?: AbortSignal;\n /** Return the body as bytes (`bytes`) rather than text, for file content. */\n binary?: boolean;\n}\n\n/** The global fetch as it was when this module loaded; a different one later was put there on purpose. */\nconst nativeFetch: typeof fetch | undefined = typeof fetch === 'function' ? fetch : undefined;\n\nlet http2Load: Promise<Http2 | null> | undefined;\nfunction loadHttp2(): Promise<Http2 | null> {\n http2Load ??= import('node:http2').then(\n (m) => ((m as unknown as { default?: Http2 }).default ?? m) as Http2,\n () => null,\n );\n return http2Load;\n}\n\ninterface Origin {\n session?: Promise<Session | null>;\n /** Set once a session could not be opened: `fetch` for this origin from then on. */\n failed?: boolean;\n}\n\nconst origins = new Map<string, Origin>();\n\n/**\n * Requests in progress on each session. A session's socket is referenced only while this is above\n * zero, so an idle session never keeps the process alive. Counted per session, not per origin: a\n * session the origin has stopped using (GOAWAY) is still released by the requests that were on it.\n */\nconst inFlight = new WeakMap<Session, number>();\n/** Sessions that received GOAWAY: closed once their last request finishes. */\nconst retired = new WeakSet<Session>();\n\nfunction hold(s: Session): void {\n inFlight.set(s, (inFlight.get(s) ?? 0) + 1);\n s.ref();\n}\n\nfunction release(s: Session): void {\n const n = (inFlight.get(s) ?? 1) - 1;\n inFlight.set(s, n);\n if (n > 0 || s.destroyed) return;\n if (retired.has(s)) s.close();\n else s.unref();\n}\n\nfunction abortError(signal: AbortSignal): unknown {\n return signal.reason ?? new Error('The operation was aborted');\n}\n\n/** p, or the signal's abort, whichever comes first; p itself is left to settle for its other waiters. */\nfunction untilAborted<T>(p: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(abortError(signal));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** Each stream's and the whole session's receive window. */\nconst WINDOW_BYTES = 16 * 1024 * 1024;\nconst SESSION_WINDOW_BYTES = 64 * 1024 * 1024;\n\n/** How long opening a session may take before the origin falls back to `fetch`. */\nconst CONNECT_TIMEOUT_MS = 10_000;\n\n/**\n * KOSA8_HTTP_TRANSPORT: unset (auto), `fetch` (never HTTP/2), or `http2` (HTTP/2 even when the\n * global fetch was replaced, and plaintext h2c to a loopback `http:` URL, for tests).\n */\nfunction mode(): 'auto' | 'fetch' | 'http2' {\n const m = typeof process !== 'undefined' ? process.env?.KOSA8_HTTP_TRANSPORT : undefined;\n return m === 'fetch' || m === 'http2' ? m : 'auto';\n}\n\nfunction originOf(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return u.origin;\n const loopback = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';\n return u.protocol === 'http:' && loopback && mode() === 'http2' ? u.origin : null;\n } catch {\n return null;\n }\n}\n\nfunction useHttp2(): boolean {\n if (typeof process === 'undefined' || !process.versions?.node) return false;\n const m = mode();\n if (m === 'fetch') return false;\n return m === 'http2' || (typeof fetch === 'function' && fetch === nativeFetch);\n}\n\nfunction session(origin: string): Promise<Session | null> {\n let o = origins.get(origin);\n if (!o) {\n o = {};\n origins.set(origin, o);\n }\n if (o.failed) return Promise.resolve(null);\n if (o.session) return o.session;\n const entry = o;\n const opening: Promise<Session | null> = loadHttp2().then((http2) => {\n if (!http2) {\n entry.failed = true;\n return null;\n }\n return new Promise<Session | null>((resolve) => {\n let settled = false;\n // Large flow-control windows, so a big file moves at the link's speed rather than 64 KiB\n // per round trip (HTTP/2's default window).\n const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n entry.failed = true;\n s.destroy();\n resolve(null);\n }, CONNECT_TIMEOUT_MS);\n timer.unref?.();\n const forget = () => {\n if (entry.session === opening) entry.session = undefined;\n };\n s.once('connect', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n s.setLocalWindowSize(SESSION_WINDOW_BYTES);\n } catch {\n // An older Node: the default window.\n }\n // Unreferenced until a request holds it (hold), so a preconnect alone never keeps the\n // process alive.\n if (!inFlight.get(s)) s.unref();\n resolve(s);\n });\n s.on('error', () => {\n forget();\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n entry.failed = true;\n resolve(null);\n }\n });\n s.once('goaway', () => {\n // No new streams on it: later requests open a new session, and this one is closed once\n // the requests already on it finish.\n forget();\n retired.add(s);\n if (!inFlight.get(s)) s.close();\n });\n s.once('close', forget);\n });\n });\n entry.session = opening;\n return opening;\n}\n\n/** Opens the session to url's origin now, so the first request does not pay the handshake. */\nexport function preconnect(url: string): void {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return;\n void session(origin);\n}\n\nasync function viaFetch(url: string, init: HttpInit): Promise<HttpResponse> {\n const res = await fetch(url, {\n method: init.method,\n headers: init.headers,\n // A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).\n body: init.body as BodyInit | undefined,\n signal: init.signal,\n });\n const headers: Record<string, string> = {};\n res.headers?.forEach?.((v, k) => (headers[k.toLowerCase()] = v));\n if (init.binary) {\n return { status: res.status, ok: res.ok, text: '', bytes: new Uint8Array(await res.arrayBuffer()), headers };\n }\n return { status: res.status, ok: res.ok, text: await res.text(), headers };\n}\n\n/** One request: over the origin's HTTP/2 session when there is one, else `fetch`. */\nexport async function httpRequest(url: string, init: HttpInit): Promise<HttpResponse> {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return viaFetch(url, init);\n // Waiting for the session honours this request's abort; the opening itself goes on for the\n // other requests sharing it.\n const s = await untilAborted(session(origin), init.signal);\n if (!s || s.closed || s.destroyed) return viaFetch(url, init);\n hold(s);\n try {\n return await viaSession(s, url, init);\n } catch (e) {\n // The server took no part in the request (refused stream, or the session was going away\n // or gone when it was sent): sent once more, over fetch. Anything else may have been\n // processed and is reported, never repeated.\n if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);\n throw e;\n } finally {\n release(s);\n }\n}\n\nfunction notProcessed(e: unknown): boolean {\n const x = e as { code?: string; rstCode?: number } | null;\n return (\n !!x &&\n (x.code === 'ERR_HTTP2_GOAWAY_SESSION' ||\n x.code === 'ERR_HTTP2_INVALID_SESSION' ||\n x.rstCode === 7) /* REFUSED_STREAM */\n );\n}\n\nfunction viaSession(s: Session, url: string, init: HttpInit): Promise<HttpResponse> {\n const u = new URL(url);\n return new Promise<HttpResponse>((resolve, reject) => {\n const headers: Record<string, string> = {\n ':method': init.method,\n ':path': u.pathname + u.search,\n };\n for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;\n let req: import('node:http2').ClientHttp2Stream;\n try {\n req = s.request(headers);\n } catch (e) {\n reject(e);\n return;\n }\n let done = false;\n const finish = (f: () => void) => {\n if (done) return;\n done = true;\n init.signal?.removeEventListener('abort', onAbort);\n f();\n };\n const aborted = () => (init.signal ? abortError(init.signal) : new Error('The operation was aborted'));\n const onAbort = () => {\n finish(() => reject(aborted()));\n req.close(0x8); // NGHTTP2_CANCEL\n };\n if (init.signal) {\n if (init.signal.aborted) {\n onAbort();\n return;\n }\n init.signal.addEventListener('abort', onAbort, { once: true });\n }\n const chunks: Buffer[] = [];\n let status = 0;\n const got: Record<string, string> = {};\n req.on('response', (h) => {\n status = Number(h[':status'] ?? 0);\n for (const [k, v] of Object.entries(h)) if (!k.startsWith(':') && v !== undefined) got[k] = String(v);\n });\n req.on('data', (c: Buffer) => chunks.push(c));\n // Settled on 'close', the last event. Node emits 'end' even when the connection drops part way\n // through the body (the session is already destroyed by then), so only a stream that ended\n // while its session was alive, and closed without a reset (rstCode 0, NO_ERROR), is an answer.\n // Anything else (no response, an interrupted body) is an error, never a truncated answer and\n // never left pending. finish ignores this after 'error'.\n let ended = false;\n req.on('end', () => {\n ended = !s.destroyed;\n });\n req.on('close', () => {\n if (status !== 0 && ended && !req.rstCode) {\n const body = Buffer.concat(chunks);\n finish(() =>\n resolve({\n status,\n ok: status >= 200 && status < 300,\n text: init.binary ? '' : body.toString('utf8'),\n ...(init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {}),\n headers: got,\n }),\n );\n return;\n }\n const why = status === 0 ? 'without a response' : 'before the response completed';\n finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));\n });\n req.on('error', (e) =>\n finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode }))),\n );\n req.end(init.body);\n });\n}\n\n/** Closes every session (for tests and orderly shutdown). */\nexport function closeSessions(): void {\n for (const o of origins.values()) {\n void o.session?.then((s) => s?.close());\n }\n origins.clear();\n}\n","/**\n * File content for the kosa8 provider.\n *\n * kosa8's file stream takes and returns a file's raw bytes at any absolute path:\n * `PUT`/`GET …/files?path=`, with `offset=` on a PUT (the rest of the file kept) and `Range` on a\n * GET. It is reached two ways, tried in this order:\n *\n * 1. Straight on the sandbox's host, at the direct token's `files_url`, when the token covers files.\n * This skips the API's Worker and Cloudflare's 100 MB request limit.\n * 2. Through the API, `/v1/sandboxes/{id}/files`.\n *\n * A file of at most one part (64 MiB) is one request. A larger one is sent in parts to a\n * temporary name beside it — the first part creates it, the rest are written at their offsets in\n * parallel — and renamed over its path once every part landed, so a failed part leaves the file\n * it replaces intact. It is read the same way, with ranges.\n *\n * An older host has the base64 file API instead: /workspace only, 8 MiB at most, no offsets. Its\n * refusals (400 outside /workspace, 413, 501) send the file over exec instead, in base64 chunks.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { escapeShellArg } from '@computesdk/provider';\nimport { httpRequest, type HttpResponse } from './transport';\n\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\nimport type { Kosa8Sandbox } from './index';\n\nexport type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/** Where file requests go: the host's own files URL with the direct token, or the API with the key. */\nexport interface FileTarget {\n url: string;\n token: string;\n}\n\n/**\n * Bytes per request (under the API's 100 MB request body limit), and parts moved at once: reads\n * four, writes two (four 64 MiB uploads at once on one connection sometimes made the host's HTTP/2\n * server end it with ENHANCE_YOUR_CALM, and two are about as fast). A mutable object so tests can\n * use small parts.\n */\nexport const fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };\n/**\n * Times a request that failed in transit, or with a server error, is sent again. Cloudflare's\n * 52x (host unreachable) are not retried: from the files URL they send the request to the API.\n */\nconst FILE_RETRIES = 2;\nconst RETRY_STATUS = new Set([500, 502, 503, 504]);\n\n/**\n * Statuses from the host's files URL that mean the request was not served there: the token was\n * refused (401), the sandbox is asleep and only the API wakes it (409), the host does not offer it\n * (501), or Cloudflare could not reach the host. The request then goes through the API. 403 and 404\n * are not here: from the files URL they mean permission denied and no such file.\n */\nconst DIRECT_REFUSED = new Set([401, 409, 501, 521, 522, 523, 530]);\n\n/**\n * Base64 characters per write exec (the fallback for older hosts). The exec API caps each argv\n * entry at 8192 characters, so content travels in an environment variable, which counts only toward\n * the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 48 * 1024;\n/** A file this small is read inline by one exec (fallback); its base64 stays under the exec output limit. */\nexport const INLINE_READ_BYTES = 1024 * 1024;\n\nconst NOT_FOUND_EXIT = 44;\nconst MIB = 1024 * 1024;\n\nconst q = (s: string) => `\"${escapeShellArg(s)}\"`;\nconst notFound = (path: string) => new Error(`ENOENT: no such file or directory, open '${path}'`);\n\nconst apiTarget = (sandbox: Kosa8Sandbox): FileTarget => ({\n url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,\n token: sandbox.apiKey,\n});\n\nfunction errorDetail(res: HttpResponse): string {\n const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString('utf8') : '');\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n return text.slice(0, 500);\n}\n\n/** The error for a refused file request, with Node's codes for the common ones. */\nfunction fileError(res: HttpResponse, op: 'open' | 'write', path: string): Error {\n const detail = errorDetail(res);\n if (res.status === 404) return notFound(path);\n if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ''}`);\n}\n\n/**\n * A refusal from the older base64 file API (or a host without any): a path outside /workspace,\n * a file over its 8 MiB, or offsets and streams it does not have. Exec reaches those.\n */\nfunction olderFileApi(res: HttpResponse): boolean {\n return res.status === 413 || res.status === 501 || (res.status === 400 && /workspace/i.test(errorDetail(res)));\n}\n\nasync function send(\n t: FileTarget,\n method: 'GET' | 'PUT',\n path: string,\n { body, offset, range }: { body?: Uint8Array; offset?: number; range?: [number, number] } = {},\n): Promise<HttpResponse> {\n const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ''}`;\n const headers: Record<string, string> = { Authorization: `Bearer ${t.token}` };\n if (body) headers['Content-Type'] = 'application/octet-stream';\n if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;\n // Every request here is idempotent (a whole file, a part at its offset, or a read), so one that\n // failed in transit or with a server error is sent again.\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await httpRequest(url, { method, headers, body, binary: true });\n if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;\n } catch (err) {\n if (attempt >= FILE_RETRIES) throw err;\n }\n await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));\n }\n}\n\n/**\n * Runs task over items, at most `limit` at once. After a task fails no more are started, and the\n * first failure is returned (or thrown) once the ones in progress have finished.\n */\nasync function inParallel<T, R>(items: T[], limit: number, task: (item: T) => Promise<R | null>): Promise<R | null> {\n let next = 0;\n let failed: R | null = null;\n let thrown: { err: unknown } | undefined;\n const worker = async () => {\n while (!failed && !thrown && next < items.length) {\n try {\n const r = await task(items[next++]);\n if (r) failed ??= r;\n } catch (err) {\n thrown ??= { err };\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n if (thrown) throw thrown.err;\n return failed;\n}\n\n/** Writes bytes at path through t: null when written, else the refusal. */\nasync function writeTo(t: FileTarget, path: string, bytes: Uint8Array): Promise<HttpResponse | null> {\n // The first part replaces the file (creating its directories); the rest are written at their offsets.\n const first = await send(t, 'PUT', path, { body: bytes.subarray(0, fileParts.bytes) });\n if (!first.ok) return first;\n const offsets: number[] = [];\n for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);\n return inParallel(offsets, fileParts.writeConcurrency, async (at) => {\n const res = await send(t, 'PUT', path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });\n return res.ok ? null : res;\n });\n}\n\n/** Reads path through t: its bytes, or the refusal. */\nasync function readFrom(t: FileTarget, path: string): Promise<Uint8Array | HttpResponse> {\n const first = await send(t, 'GET', path, { range: [0, fileParts.bytes - 1] });\n // 416: the first byte is past the end, so the file is empty.\n if (first.status === 416) return new Uint8Array();\n // 200: the whole file (a server that ignores Range).\n if (first.status === 200) return first.bytes ?? new Uint8Array();\n if (first.status !== 206) return first;\n const head = first.bytes ?? new Uint8Array();\n const total = Number(/\\/(\\d+)\\s*$/.exec(first.headers['content-range'] ?? '')?.[1] ?? head.length);\n if (total <= head.length) return head;\n const starts: number[] = [];\n for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);\n const parts = new Map<number, Uint8Array>();\n const failed = await inParallel(starts, fileParts.concurrency, async (at) => {\n const res = await send(t, 'GET', path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });\n if (res.status !== 206 && res.status !== 200) return res;\n parts.set(at, res.bytes ?? new Uint8Array());\n return null;\n });\n if (failed) return failed;\n const all = Buffer.concat([head, ...starts.map((at) => parts.get(at)!)]);\n if (all.length !== total) {\n throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);\n }\n return all;\n}\n\n// --- write -------------------------------------------------------------------\n\n/**\n * Writes a file: straight to the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function writeFileNative(\n sandbox: Kosa8Sandbox,\n path: string,\n content: string,\n run: ExecRunner,\n direct: FileTarget | null = null,\n): Promise<void> {\n const bytes = Buffer.from(content, 'utf8');\n const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${randomBytes(6).toString('hex')}` : null;\n const dest = staged ?? path;\n const commit = async () => {\n // `[ -d ]` first: `mv` onto an existing directory would move the staged file inside it.\n if (staged) {\n await mustSucceed(\n run,\n sandbox,\n `if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,\n 'write',\n path,\n );\n }\n };\n try {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const res = await writeTo(direct, dest, bytes).catch(() => undefined);\n if (res === null) {\n await commit();\n return;\n }\n if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, 'write', path);\n if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const res = await writeTo(apiTarget(sandbox), dest, bytes);\n if (!res) {\n await commit();\n return;\n }\n if (!olderFileApi(res)) throw fileError(res, 'write', path);\n if (res.status === 501) sandbox.files = false;\n }\n return writeFileViaExec(sandbox, path, bytes, run);\n } finally {\n if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {});\n }\n}\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, what: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n if ((result as { stdoutTruncated?: boolean }).stdoutTruncated) {\n throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);\n }\n return result.stdout;\n}\n\n/**\n * Writes a file through exec (older hosts): base64 chunks into a temporary file beside it, then an\n * atomic rename. One chunk is a single command.\n */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void> {\n const target = q(path);\n const tmp = q(`${path}.computesdk-${randomBytes(6).toString('hex')}`);\n const encoded = Buffer.from(content).toString('base64');\n const mkParent = `d=$(dirname ${target}) && mkdir -p \"$d\"`;\n if (encoded.length <= WRITE_CHUNK_CHARS) {\n const cmd = `${mkParent} && printf '%s' \"$KOSA8_CHUNK\" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;\n await mustSucceed(run, sandbox, cmd, 'write', path, { KOSA8_CHUNK: encoded });\n return;\n }\n try {\n await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, 'write', path);\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, 'write', path, {\n KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS),\n });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, 'write', path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\n// --- read --------------------------------------------------------------------\n\nconst fromBase64 = (s: string) => Buffer.from(s.replace(/\\s+/g, ''), 'base64');\n\n/**\n * Reads a file: straight from the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function readFileNative(sandbox: Kosa8Sandbox, path: string, run: ExecRunner, direct: FileTarget | null = null): Promise<string> {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const got = await readFrom(direct, path).catch(() => undefined);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, 'open', path);\n if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const got = await readFrom(apiTarget(sandbox), path);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (!olderFileApi(got)) throw fileError(got, 'open', path);\n if (got.status === 501) sandbox.files = false;\n }\n return readFileViaExec(sandbox, path, run);\n}\n\n/** Reads a file through exec (older hosts): inline when small, else 1 MiB per command. */\nasync function readFileViaExec(sandbox: Kosa8Sandbox, path: string, run: ExecRunner): Promise<string> {\n const p = q(path);\n const out = await mustSucceed(\n run,\n sandbox,\n `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo \"$s\"; if [ \"$s\" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,\n 'open',\n path,\n );\n const nl = out.indexOf('\\n');\n const size = Number(out.slice(0, nl < 0 ? undefined : nl).trim());\n if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);\n if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? '' : out.slice(nl + 1)).toString('utf8');\n const chunks: Buffer[] = new Array(Math.ceil(size / INLINE_READ_BYTES));\n let next = 0;\n const worker = async () => {\n while (next < chunks.length) {\n const i = next++;\n chunks[i] = fromBase64(\n await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, 'open', path),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));\n const all = Buffer.concat(chunks);\n if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);\n return all.toString('utf8');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,IAAAA,mBAAgE;;;ACwBhE,IAAM,cAAwC,OAAO,UAAU,aAAa,QAAQ;AAEpF,IAAI;AACJ,SAAS,YAAmC;AAC1C,4BAAc,OAAO,OAAY,EAAE;AAAA,IACjC,CAAC,MAAQ,EAAqC,WAAW;AAAA,IACzD,MAAM;AAAA,EACR;AACA,SAAO;AACT;AAQA,IAAM,UAAU,oBAAI,IAAoB;AAOxC,IAAM,WAAW,oBAAI,QAAyB;AAE9C,IAAM,UAAU,oBAAI,QAAiB;AAErC,SAAS,KAAK,GAAkB;AAC9B,WAAS,IAAI,IAAI,SAAS,IAAI,CAAC,KAAK,KAAK,CAAC;AAC1C,IAAE,IAAI;AACR;AAEA,SAAS,QAAQ,GAAkB;AACjC,QAAM,KAAK,SAAS,IAAI,CAAC,KAAK,KAAK;AACnC,WAAS,IAAI,GAAG,CAAC;AACjB,MAAI,IAAI,KAAK,EAAE,UAAW;AAC1B,MAAI,QAAQ,IAAI,CAAC,EAAG,GAAE,MAAM;AAAA,MACvB,GAAE,MAAM;AACf;AAEA,SAAS,WAAW,QAA8B;AAChD,SAAO,OAAO,UAAU,IAAI,MAAM,2BAA2B;AAC/D;AAGA,SAAS,aAAgB,GAAe,QAAkC;AACxE,MAAI,CAAC,OAAQ,QAAO;AACpB,MAAI,OAAO,QAAS,QAAO,QAAQ,OAAO,WAAW,MAAM,CAAC;AAC5D,SAAO,I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}
|
package/dist/index.mjs
CHANGED
|
@@ -715,6 +715,16 @@ var shellFs = (sandbox, run) => new ShellFileSystem((command, options) => run(sa
|
|
|
715
715
|
var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
|
|
716
716
|
var provider = defineProvider({
|
|
717
717
|
name: "kosa8",
|
|
718
|
+
sizes: (config, profile, options) => {
|
|
719
|
+
if (options?.templateId !== void 0 || options?.snapshotId !== void 0) {
|
|
720
|
+
return { status: "unsupported", reason: "A kosa8 template or snapshot fixes CPU and memory; drop templateId/snapshotId to boot the standard size template." };
|
|
721
|
+
}
|
|
722
|
+
const templateId = config.sizeTemplates?.[profile.sizeClass];
|
|
723
|
+
if (typeof templateId !== "string" || !templateId.trim()) {
|
|
724
|
+
return { status: "unconfigured", reason: `kosa8 fixes CPU and memory per template; build one at ${profile.vcpus} vCPU / ${profile.memoryMiB} MiB and set sizeTemplates.${profile.sizeClass}.` };
|
|
725
|
+
}
|
|
726
|
+
return { status: "supported", nativeOptions: { templateId } };
|
|
727
|
+
},
|
|
718
728
|
methods: {
|
|
719
729
|
instances: {
|
|
720
730
|
create: async (config, options) => {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/transport.ts","../src/files.ts"],"sourcesContent":["/**\n * kosa8 Provider - Factory-based Implementation\n *\n * Sandboxes on kosa8 Cloud (https://kosa8.com). Each sandbox runs in its own microVM with its\n * own kernel. The cloud API is a small JSON surface, so this package talks to it with `fetch`\n * and has no SDK dependency.\n *\n * Commands go through the buffered exec endpoint: straight to the sandbox's host when the create\n * answer carries a direct-exec URL and token (see runDirect), otherwise through the API. File content\n * moves through kosa8's file API (`/v1/sandboxes/{id}/files`, see files.ts), with shell commands\n * over exec for small files and for hosts without it. `pause()`/`resume()` map to kosa8's sleep and\n * wake, and `provider.snapshot` to kosa8 snapshots: both keep the VM's memory (running processes)\n * as well as its disk.\n */\n\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\nimport { httpRequest, preconnect } from './transport';\nimport { readFileNative, writeFileNative, type ExecRunner } from './files';\n\nexport { WRITE_CHUNK_CHARS, writeFileViaExec } from './files';\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateSnapshotOptions,\n InstanceInfo,\n RunCommandOptions,\n SnapshotCapabilities,\n} from '@computesdk/provider';\n\nexport interface Kosa8Config {\n /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */\n apiKey?: string;\n /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */\n baseUrl?: string;\n /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */\n region?: string;\n}\n\n/** A sandbox as the kosa8 Cloud API returns it. */\nexport interface Kosa8SandboxData {\n id: string;\n state: string;\n template: string;\n cpus: number;\n mem_mb: number;\n region: string | null;\n created_at: number;\n started_at: number | null;\n sleep_after_s: number | null;\n delete_after: number | null;\n last_error: string | null;\n [key: string]: unknown;\n}\n\n/** A template as GET /v1/templates returns it. */\nexport interface Kosa8Template {\n key: string;\n cpus: number;\n mem_mb: number;\n image?: string;\n regions: string[];\n [key: string]: unknown;\n}\n\n/** The create answer's `direct` object: the host's exec endpoint for this sandbox and a token for it. */\nexport interface Kosa8Direct {\n exec_url: string;\n /** The host's raw file endpoint for this sandbox, when the token also covers files (`files.direct`). */\n files_url?: string;\n token: string;\n /** When the token stops working, ms since the epoch. */\n expires_at: number;\n}\n\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\n /** Present while commands can go straight to the sandbox's host (runDirect). */\n direct?: Kosa8Direct;\n /** A fresh direct token being fetched (refreshDirect). */\n refreshing?: Promise<void>;\n /** False once the sandbox's host answered that it has no file API: files then go over exec. */\n files?: boolean;\n /** False once the host refused file requests with the direct token: files then go through the API. */\n directFiles?: boolean;\n}\n\n/** A snapshot as the kosa8 Cloud API returns it. */\nexport interface Kosa8SnapshotData {\n id: string;\n name: string | null;\n state: string;\n source_sandbox_id: string;\n template: string;\n cpus: number;\n mem_mb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n created_at: number;\n [key: string]: unknown;\n}\n\n/** A snapshot as `provider.snapshot` returns it. */\nexport interface Kosa8Snapshot {\n id: string;\n provider: 'kosa8';\n createdAt: Date;\n metadata: {\n name: string | null;\n sourceInstanceId: string;\n state: string;\n template: string;\n cpus: number;\n memMb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n /** How long the host took to save it, when the API reports it. */\n createMs?: number | null;\n };\n}\n\ninterface Auth {\n apiKey: string;\n baseUrl: string;\n}\n\ninterface ExecResponse {\n exit: number | null;\n stdout: string;\n stderr: string;\n /** Set when the API kept only the first part of a stream (its output limit). */\n stdout_truncated?: boolean;\n stderr_truncated?: boolean;\n /** The stream's full length, kept or not. */\n stdout_bytes?: number;\n stderr_bytes?: number;\n}\n\n/**\n * A command's result. Beyond ComputeSDK's fields it says when the API returned only the first part\n * of the output (its limit on a buffered command): `truncated`, per stream, and each stream's full\n * length in bytes. These are absent when the API does not report them.\n */\nexport interface Kosa8CommandResult extends CommandResult {\n truncated?: boolean;\n stdoutTruncated?: boolean;\n stderrTruncated?: boolean;\n stdoutBytes?: number;\n stderrBytes?: number;\n}\n\n/** The API's shortest and longest lifetime for a sandbox (ttl_s). */\nconst MIN_TTL_S = 60;\nconst MAX_TTL_S = 90 * 86400;\n\n/** Exit code reported when `runCommand`'s timeout stops a command (as coreutils `timeout` does). */\nconst TIMEOUT_EXIT = 124;\n\n/** Names the marker file a timed command creates once it returns (see execArgv). */\nconst DONE_ENV = 'KOSA8_DONE';\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template (or an image) fixes the size. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'envs', 'volumes',\n] as const;\n\n/** A snapshot name the API accepts; another name is kept only in the snapshot's metadata. */\nconst SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\nfunction resolveConfig(config: Kosa8Config): Auth {\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const apiKey = config.apiKey || env?.KOSA8_API_KEY || '';\n if (!apiKey) {\n throw new Error(\n `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. ` +\n `Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`,\n );\n }\n const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || 'https://api.kosa8.com').replace(/\\/+$/, '');\n return { apiKey, baseUrl };\n}\n\nasync function request<T>(\n auth: Auth,\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n): Promise<T | null> {\n const res = await httpRequest(`${auth.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n if (res.status === 404) return null;\n const text = res.text;\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);\n }\n return (text ? JSON.parse(text) : null) as T;\n}\n\nconst sandboxPath = (id: string, rest = '') => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;\n\nfunction toSandbox(auth: Auth, data: Kosa8SandboxData, direct?: unknown): Kosa8Sandbox {\n const sandbox: Kosa8Sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\n if (isDirect(direct)) {\n sandbox.direct = direct;\n // The first command follows at once: its host's session opens now.\n preconnect(direct.exec_url);\n }\n return sandbox;\n}\n\nfunction isDirect(d: unknown): d is Kosa8Direct {\n const x = d as Kosa8Direct | null | undefined;\n return !!x && typeof x.exec_url === 'string' && /^https:\\/\\//.test(x.exec_url) && typeof x.token === 'string' &&\n typeof x.expires_at === 'number';\n}\n\n/** A direct token this close to expiry is not used; one closer than DIRECT_REFRESH_MS is renewed in the background. */\nconst DIRECT_MARGIN_MS = 15_000;\nconst DIRECT_REFRESH_MS = 60_000;\n\n/**\n * Statuses from the direct endpoint that mean the command did not run there: the token was refused\n * (401, 403), the host does not have the sandbox (404), it is asleep and only the API wakes it\n * (409), the host does not offer it (501), or Cloudflare could not reach the host (521, 522, 523,\n * 530). The command is then sent through the API. Any other failure is reported as is, since the\n * command may have run.\n */\nconst DIRECT_NOT_RUN = new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);\n\n/**\n * The direct token and files URL for file requests, or null when files go through the API: no\n * token, a host whose token does not cover files, one that refused it, or a token about to expire\n * (renewed in the background, as for commands).\n */\nexport function directFiles(sandbox: Kosa8Sandbox): { url: string; token: string } | null {\n const d = sandbox.direct;\n if (!d?.files_url || sandbox.directFiles === false || !/^https:\\/\\//.test(d.files_url)) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };\n}\n\n/** Renews the direct token in the background; a failure leaves the API path in use. */\nfunction refreshDirect(sandbox: Kosa8Sandbox): void {\n if (sandbox.refreshing) return;\n sandbox.refreshing = request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct'))\n .then((r) => {\n if (isDirect(r?.direct)) sandbox.direct = r.direct;\n })\n .catch(() => {})\n .finally(() => {\n sandbox.refreshing = undefined;\n });\n}\n\n/**\n * Runs a command on the sandbox's host directly (the create answer's `direct`), skipping the API's\n * hop. Returns null when the command was not run there, so the caller sends it through the API;\n * the sandbox then stops using the direct path until a fresh token arrives.\n */\nasync function runDirect(sandbox: Kosa8Sandbox, body: unknown, signal?: AbortSignal): Promise<ExecResponse | null> {\n const d = sandbox.direct;\n if (!d) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n if (left < DIRECT_MARGIN_MS) return null;\n const res = await httpRequest(d.exec_url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${d.token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal,\n });\n const text = res.text;\n if (DIRECT_NOT_RUN.has(res.status)) {\n if (sandbox.direct === d) sandbox.direct = undefined;\n return null;\n }\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string };\n if (parsed?.error) detail = parsed.error;\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);\n }\n return JSON.parse(text) as ExecResponse;\n}\n\n/** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */\nexport function createBody(config: Kosa8Config, options: CreateInstanceOptions = {}): Record<string, unknown> {\n for (const key of UNSUPPORTED_CREATE_OPTIONS) {\n if (options[key] !== undefined) {\n throw new Error(\n `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; ` +\n `pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n if (options.snapshotId !== undefined) {\n // A sandbox made from a snapshot takes its template, size, image and host from the snapshot.\n for (const key of ['templateId', 'image', 'region'] as const) {\n if (options[key] !== undefined) {\n throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);\n }\n }\n body.snapshot = options.snapshotId;\n } else if (options.image !== undefined) {\n // An OCI image boots a VM of its own (the API's default size for an image, 2 vCPU / 4 GiB),\n // so the configured default template does not apply; an explicit templateId is passed on.\n body.image = options.image;\n if (options.templateId) body.template = options.templateId;\n } else {\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n }\n if (options.snapshotId === undefined) {\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\n }\n if (options.sleepAfterSeconds !== undefined) body.sleep_after_s = options.sleepAfterSeconds;\n if (typeof options.timeout === 'number' && options.timeout > 0) {\n // kosa8 deletes the sandbox when its lifetime ends; the API's shortest lifetime is 60 s.\n body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1000)));\n }\n return body;\n}\n\n/** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */\nexport function execArgv(command: string, options?: RunCommandOptions): string[] {\n let cmd = command;\n if (options?.cwd) cmd = `cd \"${escapeShellArg(options.cwd)}\" && ${cmd}`;\n if (options?.background) {\n cmd = `nohup sh -c \"${escapeShellArg(cmd)}\" >/dev/null 2>&1 &`;\n } else if (options?.timeout && options.timeout > 0) {\n // Stop the command in the sandbox, not just the wait for it. GNU timeout signals the whole\n // process group; an image without `timeout` runs the command unbounded and the request's\n // own deadline (runCommand) still applies.\n //\n // Status 137 alone does not mean the deadline passed: the command may exit 137 itself or be\n // killed early. The command runs in a subshell and a marker file is created once it returns,\n // whatever its status. Only a 137 with no marker (the shell itself was killed) once the\n // deadline has passed (whole seconds: the elapsed count cannot fall short of a real deadline)\n // is reported as a timeout.\n const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const plain = `sh -c \"${escapeShellArg(cmd)}\"`;\n const marked = `sh -c \"${escapeShellArg(`(\\n${cmd}\\n); s=$?; : > \"$${DONE_ENV}\"; exit $s`)}\"`;\n cmd =\n `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then ` +\n `rm -f \"$${DONE_ENV}\"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; ` +\n `if [ $s -eq 137 ] && [ ! -e \"$${DONE_ENV}\" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; ` +\n `rm -f \"$${DONE_ENV}\"; exit $s; ` +\n `else ${plain}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/**\n * The exec API's limit on each argv entry. Measured in UTF-8 bytes here, which is never less than\n * the API's own count, so a command with multibyte characters cannot slip over it.\n */\nconst MAX_ARG_BYTES = 8192;\n\n/** The exec API's limit on the whole request body, in bytes. */\nexport const MAX_EXEC_BODY_BYTES = 64 * 1024;\n\n/** Environment variable that carries a script too long for one argv entry; callers may not set it. */\nexport const SCRIPT_ENV = 'KOSA8_SCRIPT';\n\n/**\n * The exec request body: a script too long for one argv entry travels in an environment variable.\n * Throws before any request is made when the serialized body would exceed the exec API's limit.\n */\nexport function execBody(command: string, options?: RunCommandOptions): { cmd: string[]; env: string[] } {\n const argv = execArgv(command, options);\n const env = execEnv(options?.env);\n const body = Buffer.byteLength(argv[2], 'utf8') <= MAX_ARG_BYTES\n ? { cmd: argv, env }\n : { cmd: ['sh', '-c', `eval \"$${SCRIPT_ENV}\"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };\n const size = Buffer.byteLength(JSON.stringify(body), 'utf8');\n if (size > MAX_EXEC_BODY_BYTES) {\n throw new Error(\n `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) ` +\n `for the command and its environment together. Write a long script to a file with ` +\n `sandbox.filesystem.writeFile() and run that file instead.`,\n );\n }\n return body;\n}\n\nfunction execEnv(env?: Record<string, string>): string[] {\n if (!env) return [];\n return Object.entries(env).map(([key, value]) => {\n if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n if (key === SCRIPT_ENV) {\n throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);\n }\n return `${key}=${value}`;\n });\n}\n\nfunction infoStatus(state: string): InstanceInfo['status'] {\n if (state === 'error') return 'error';\n // A sleeping sandbox is alive: its memory and disk are saved, and any call (a command, a file\n // read or write) wakes it in about a second, so it reports as running.\n if (state === 'running' || state === 'sleeping') return 'running';\n // creating, paused, stopped, deleted and expired (past its deadline): not running now, so a\n // readiness check keeps waiting and a liveness check sees it gone.\n return 'stopped';\n}\n\nasync function getData(sandbox: Kosa8Sandbox): Promise<Kosa8SandboxData | null> {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id));\n return data?.sandbox ?? null;\n}\n\n/** How often a sandbox that is still booting (an image's cold boot) is checked, and for how long. */\nconst BOOT_POLL_MS = 150;\nconst BOOT_TIMEOUT_MS = 5 * 60_000;\n\n/**\n * Waits for a sandbox the API answered with `creating` (202: an image booted cold) to run, so the\n * create resolves to a sandbox that takes commands. Its direct exec token is fetched once it runs.\n */\nasync function waitUntilRunning(sandbox: Kosa8Sandbox, signal?: AbortSignal): Promise<void> {\n const deadline = Date.now() + BOOT_TIMEOUT_MS;\n while (sandbox.data.state === 'creating') {\n if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1000} s`);\n signal?.throwIfAborted();\n await new Promise((r) => setTimeout(r, BOOT_POLL_MS));\n const current = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id), undefined, signal);\n if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);\n sandbox.data = current.sandbox;\n }\n if (sandbox.data.state !== 'running') {\n const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : '';\n throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);\n }\n if (!sandbox.direct) {\n const r = await request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct')).catch(() => null);\n if (isDirect(r?.direct)) {\n sandbox.direct = r.direct;\n preconnect(r.direct.exec_url);\n }\n }\n}\n\nfunction toSnapshot(s: Kosa8SnapshotData, createMs?: number | null): Kosa8Snapshot {\n return {\n id: s.id,\n provider: 'kosa8',\n createdAt: new Date(s.created_at),\n metadata: {\n name: s.name ?? null,\n sourceInstanceId: s.source_sandbox_id,\n state: s.state,\n template: s.template,\n cpus: s.cpus,\n memMb: s.mem_mb,\n image: s.image ?? null,\n bytes: s.bytes ?? 0,\n region: s.region ?? null,\n ...(createMs !== undefined ? { createMs } : {}),\n },\n };\n}\n\n/**\n * kosa8 snapshots save the whole VM, memory included, so a restore resumes running processes. The\n * source keeps running, and one snapshot restores into any number of sandboxes, each copy-on-write\n * on the snapshot's host. A snapshot is ready when `create` returns.\n */\nexport const SNAPSHOT_CAPABILITIES: SnapshotCapabilities = {\n scope: 'rootfs',\n memory: true,\n destroysSource: false,\n source: 'kept',\n fork: true,\n readiness: 'immediate',\n};\n\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nconst provider = defineProvider<Kosa8Sandbox, Kosa8Config>({\n name: 'kosa8',\n methods: {\n instances: {\n create: async (config: Kosa8Config, options?: CreateInstanceOptions) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData; direct?: unknown }>(\n auth,\n 'POST',\n '/v1/sandboxes',\n createBody(config, options),\n options?.signal,\n );\n if (!data?.sandbox) throw new Error('kosa8 API returned no sandbox on create');\n const sandbox = toSandbox(auth, data.sandbox, data.direct);\n if (sandbox.data.state !== 'running') {\n try {\n await waitUntilRunning(sandbox, options?.signal);\n } catch (err) {\n // A sandbox that never ran is not left behind, billed.\n await request(auth, 'DELETE', sandboxPath(sandbox.id)).catch(() => {});\n throw err;\n }\n }\n return { instance: sandbox, instanceId: sandbox.id };\n },\n\n getById: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData }>(auth, 'GET', sandboxPath(instanceId));\n return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;\n },\n\n list: async (config: Kosa8Config) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandboxes: Kosa8SandboxData[] }>(auth, 'GET', '/v1/sandboxes');\n return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));\n },\n\n destroy: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n // A sandbox that is already gone answers 404, which request() returns as null.\n await request(auth, 'DELETE', sandboxPath(instanceId));\n },\n\n runCommand: async (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions): Promise<Kosa8CommandResult> => {\n const start = Date.now();\n const body = execBody(command, options);\n // The command is stopped in the sandbox at the deadline; the request gets a grace period on top.\n const signal = options?.timeout && options.timeout > 0 && !options.background\n ? AbortSignal.timeout(options.timeout + 30_000)\n : undefined;\n const data = (await runDirect(sandbox, body, signal)) ??\n (await request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n const result: Kosa8CommandResult = {\n stdout: data.stdout ?? '',\n stderr: data.stderr ?? '',\n exitCode: Number.isInteger(data.exit) ? (data.exit as number) : -1,\n durationMs: Date.now() - start,\n };\n if (typeof data.stdout_truncated === 'boolean' || typeof data.stderr_truncated === 'boolean') {\n result.stdoutTruncated = data.stdout_truncated === true;\n result.stderrTruncated = data.stderr_truncated === true;\n result.truncated = result.stdoutTruncated || result.stderrTruncated;\n }\n if (typeof data.stdout_bytes === 'number') result.stdoutBytes = data.stdout_bytes;\n if (typeof data.stderr_bytes === 'number') result.stderrBytes = data.stderr_bytes;\n return result;\n },\n\n getInfo: async (sandbox: Kosa8Sandbox): Promise<InstanceInfo> => {\n const current = (await getData(sandbox)) ?? { ...sandbox.data, state: 'deleted' };\n sandbox.data = current;\n return {\n id: sandbox.id,\n provider: 'kosa8',\n status: infoStatus(current.state),\n createdAt: new Date(current.created_at),\n timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,\n metadata: {\n state: current.state,\n template: current.template,\n cpus: current.cpus,\n memMb: current.mem_mb,\n region: current.region,\n sleepAfterSeconds: current.sleep_after_s,\n deleteAfter: current.delete_after,\n lastError: current.last_error,\n },\n };\n },\n\n getUrl: async (): Promise<string> => {\n throw notAvailable('port URLs');\n },\n\n // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.\n pause: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/sleep'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n resume: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/wake'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n pauseCapabilities: { memory: true },\n\n // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.\n lifetime: {},\n\n // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.\n extendLifetime: async (sandbox: Kosa8Sandbox, ms: number): Promise<void> => {\n const current = await getData(sandbox);\n if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = current;\n if (current.delete_after == null) return;\n const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1000);\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'PATCH', sandboxPath(sandbox.id), {\n delete_after: Math.floor(deleteAfter),\n });\n // A 404 here means the sandbox was deleted between the read and the update.\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n if (data.sandbox) sandbox.data = data.sandbox;\n },\n\n getInstance: (sandbox: Kosa8Sandbox): Kosa8Sandbox => sandbox,\n\n // File content straight to the sandbox's host with the direct token, else through the API's\n // file stream, else (an older host) exec (files.ts); the rest are single shell commands.\n filesystem: {\n readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),\n writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),\n mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),\n readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),\n exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),\n remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path),\n },\n },\n\n snapshot: {\n capabilities: SNAPSHOT_CAPABILITIES,\n\n // POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.\n create: async (config: Kosa8Config, instanceId: string, options?: CreateSnapshotOptions): Promise<Kosa8Snapshot> => {\n const auth = resolveConfig(config);\n const name = typeof options?.name === 'string' && SNAPSHOT_NAME.test(options.name) ? options.name : undefined;\n const data = await request<{ snapshot: Kosa8SnapshotData; ms?: number | null }>(\n auth,\n 'POST',\n sandboxPath(instanceId, '/snapshots'),\n name ? { name } : {},\n );\n if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);\n return toSnapshot(data.snapshot, typeof data.ms === 'number' ? data.ms : null);\n },\n\n list: async (config: Kosa8Config): Promise<Kosa8Snapshot[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ snapshots: Kosa8SnapshotData[] }>(auth, 'GET', '/v1/snapshots');\n return (data?.snapshots ?? []).map((s) => toSnapshot(s));\n },\n\n // A snapshot that is already gone answers 404, which request() returns as null.\n delete: async (config: Kosa8Config, snapshotId: string): Promise<void> => {\n const auth = resolveConfig(config);\n await request(auth, 'DELETE', `/v1/snapshots/${encodeURIComponent(snapshotId)}`);\n },\n },\n\n template: {\n create: async () => {\n throw notAvailable('creating templates (templates are offered by the hosts)');\n },\n list: async (config: Kosa8Config): Promise<Kosa8Template[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ templates: Kosa8Template[] }>(auth, 'GET', '/v1/templates');\n return data?.templates ?? [];\n },\n delete: async () => {\n throw notAvailable('deleting templates (templates are offered by the hosts)');\n },\n },\n },\n});\n\n/**\n * The kosa8 provider. Configuring it opens the HTTP/2 session to the API (transport.ts), so the\n * first create does not pay the connection's handshake.\n */\nexport const kosa8: typeof provider = (config) => {\n try {\n preconnect(resolveConfig(config).baseUrl);\n } catch {\n // No key yet: the first call reports it.\n }\n return provider(config);\n};\n\nexport default kosa8;\n","/**\n * HTTP for the kosa8 provider: one HTTP/2 session per origin, shared by every request, instead of\n * a TLS connection per request.\n *\n * With `fetch`, 100 sandboxes created at once open 100 connections, each paying its own TCP and\n * TLS handshake before the request is sent. On kosa8 Cloud that was ~260 ms of each create in a\n * 100-at-once burst from Virginia (2026-11-13), against ~40 ms for a request on a connection that\n * was already open. Over one HTTP/2 session the handshake is paid once, and `preconnect` pays it\n * before the first request (when the provider is configured).\n *\n * `fetch` stays the fallback: where `node:http2` is not available, for an origin whose session\n * could not be opened, and whenever the global `fetch` has been replaced (tests, proxies,\n * instrumentation), which is then honoured for every request.\n */\n\ntype Http2 = typeof import('node:http2');\ntype Session = import('node:http2').ClientHttp2Session;\n\nexport interface HttpResponse {\n status: number;\n ok: boolean;\n /** The body as UTF-8 text; empty when the request asked for `binary`. */\n text: string;\n /** The body's bytes, present when the request asked for `binary`. */\n bytes?: Uint8Array;\n /** Response headers, names in lower case. */\n headers: Record<string, string>;\n}\n\nexport interface HttpInit {\n method: string;\n headers: Record<string, string>;\n body?: string | Uint8Array;\n signal?: AbortSignal;\n /** Return the body as bytes (`bytes`) rather than text, for file content. */\n binary?: boolean;\n}\n\n/** The global fetch as it was when this module loaded; a different one later was put there on purpose. */\nconst nativeFetch: typeof fetch | undefined = typeof fetch === 'function' ? fetch : undefined;\n\nlet http2Load: Promise<Http2 | null> | undefined;\nfunction loadHttp2(): Promise<Http2 | null> {\n http2Load ??= import('node:http2').then(\n (m) => ((m as unknown as { default?: Http2 }).default ?? m) as Http2,\n () => null,\n );\n return http2Load;\n}\n\ninterface Origin {\n session?: Promise<Session | null>;\n /** Set once a session could not be opened: `fetch` for this origin from then on. */\n failed?: boolean;\n}\n\nconst origins = new Map<string, Origin>();\n\n/**\n * Requests in progress on each session. A session's socket is referenced only while this is above\n * zero, so an idle session never keeps the process alive. Counted per session, not per origin: a\n * session the origin has stopped using (GOAWAY) is still released by the requests that were on it.\n */\nconst inFlight = new WeakMap<Session, number>();\n/** Sessions that received GOAWAY: closed once their last request finishes. */\nconst retired = new WeakSet<Session>();\n\nfunction hold(s: Session): void {\n inFlight.set(s, (inFlight.get(s) ?? 0) + 1);\n s.ref();\n}\n\nfunction release(s: Session): void {\n const n = (inFlight.get(s) ?? 1) - 1;\n inFlight.set(s, n);\n if (n > 0 || s.destroyed) return;\n if (retired.has(s)) s.close();\n else s.unref();\n}\n\nfunction abortError(signal: AbortSignal): unknown {\n return signal.reason ?? new Error('The operation was aborted');\n}\n\n/** p, or the signal's abort, whichever comes first; p itself is left to settle for its other waiters. */\nfunction untilAborted<T>(p: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(abortError(signal));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** Each stream's and the whole session's receive window. */\nconst WINDOW_BYTES = 16 * 1024 * 1024;\nconst SESSION_WINDOW_BYTES = 64 * 1024 * 1024;\n\n/** How long opening a session may take before the origin falls back to `fetch`. */\nconst CONNECT_TIMEOUT_MS = 10_000;\n\n/**\n * KOSA8_HTTP_TRANSPORT: unset (auto), `fetch` (never HTTP/2), or `http2` (HTTP/2 even when the\n * global fetch was replaced, and plaintext h2c to a loopback `http:` URL, for tests).\n */\nfunction mode(): 'auto' | 'fetch' | 'http2' {\n const m = typeof process !== 'undefined' ? process.env?.KOSA8_HTTP_TRANSPORT : undefined;\n return m === 'fetch' || m === 'http2' ? m : 'auto';\n}\n\nfunction originOf(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return u.origin;\n const loopback = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';\n return u.protocol === 'http:' && loopback && mode() === 'http2' ? u.origin : null;\n } catch {\n return null;\n }\n}\n\nfunction useHttp2(): boolean {\n if (typeof process === 'undefined' || !process.versions?.node) return false;\n const m = mode();\n if (m === 'fetch') return false;\n return m === 'http2' || (typeof fetch === 'function' && fetch === nativeFetch);\n}\n\nfunction session(origin: string): Promise<Session | null> {\n let o = origins.get(origin);\n if (!o) {\n o = {};\n origins.set(origin, o);\n }\n if (o.failed) return Promise.resolve(null);\n if (o.session) return o.session;\n const entry = o;\n const opening: Promise<Session | null> = loadHttp2().then((http2) => {\n if (!http2) {\n entry.failed = true;\n return null;\n }\n return new Promise<Session | null>((resolve) => {\n let settled = false;\n // Large flow-control windows, so a big file moves at the link's speed rather than 64 KiB\n // per round trip (HTTP/2's default window).\n const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n entry.failed = true;\n s.destroy();\n resolve(null);\n }, CONNECT_TIMEOUT_MS);\n timer.unref?.();\n const forget = () => {\n if (entry.session === opening) entry.session = undefined;\n };\n s.once('connect', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n s.setLocalWindowSize(SESSION_WINDOW_BYTES);\n } catch {\n // An older Node: the default window.\n }\n // Unreferenced until a request holds it (hold), so a preconnect alone never keeps the\n // process alive.\n if (!inFlight.get(s)) s.unref();\n resolve(s);\n });\n s.on('error', () => {\n forget();\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n entry.failed = true;\n resolve(null);\n }\n });\n s.once('goaway', () => {\n // No new streams on it: later requests open a new session, and this one is closed once\n // the requests already on it finish.\n forget();\n retired.add(s);\n if (!inFlight.get(s)) s.close();\n });\n s.once('close', forget);\n });\n });\n entry.session = opening;\n return opening;\n}\n\n/** Opens the session to url's origin now, so the first request does not pay the handshake. */\nexport function preconnect(url: string): void {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return;\n void session(origin);\n}\n\nasync function viaFetch(url: string, init: HttpInit): Promise<HttpResponse> {\n const res = await fetch(url, {\n method: init.method,\n headers: init.headers,\n // A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).\n body: init.body as BodyInit | undefined,\n signal: init.signal,\n });\n const headers: Record<string, string> = {};\n res.headers?.forEach?.((v, k) => (headers[k.toLowerCase()] = v));\n if (init.binary) {\n return { status: res.status, ok: res.ok, text: '', bytes: new Uint8Array(await res.arrayBuffer()), headers };\n }\n return { status: res.status, ok: res.ok, text: await res.text(), headers };\n}\n\n/** One request: over the origin's HTTP/2 session when there is one, else `fetch`. */\nexport async function httpRequest(url: string, init: HttpInit): Promise<HttpResponse> {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return viaFetch(url, init);\n // Waiting for the session honours this request's abort; the opening itself goes on for the\n // other requests sharing it.\n const s = await untilAborted(session(origin), init.signal);\n if (!s || s.closed || s.destroyed) return viaFetch(url, init);\n hold(s);\n try {\n return await viaSession(s, url, init);\n } catch (e) {\n // The server took no part in the request (refused stream, or the session was going away\n // or gone when it was sent): sent once more, over fetch. Anything else may have been\n // processed and is reported, never repeated.\n if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);\n throw e;\n } finally {\n release(s);\n }\n}\n\nfunction notProcessed(e: unknown): boolean {\n const x = e as { code?: string; rstCode?: number } | null;\n return (\n !!x &&\n (x.code === 'ERR_HTTP2_GOAWAY_SESSION' ||\n x.code === 'ERR_HTTP2_INVALID_SESSION' ||\n x.rstCode === 7) /* REFUSED_STREAM */\n );\n}\n\nfunction viaSession(s: Session, url: string, init: HttpInit): Promise<HttpResponse> {\n const u = new URL(url);\n return new Promise<HttpResponse>((resolve, reject) => {\n const headers: Record<string, string> = {\n ':method': init.method,\n ':path': u.pathname + u.search,\n };\n for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;\n let req: import('node:http2').ClientHttp2Stream;\n try {\n req = s.request(headers);\n } catch (e) {\n reject(e);\n return;\n }\n let done = false;\n const finish = (f: () => void) => {\n if (done) return;\n done = true;\n init.signal?.removeEventListener('abort', onAbort);\n f();\n };\n const aborted = () => (init.signal ? abortError(init.signal) : new Error('The operation was aborted'));\n const onAbort = () => {\n finish(() => reject(aborted()));\n req.close(0x8); // NGHTTP2_CANCEL\n };\n if (init.signal) {\n if (init.signal.aborted) {\n onAbort();\n return;\n }\n init.signal.addEventListener('abort', onAbort, { once: true });\n }\n const chunks: Buffer[] = [];\n let status = 0;\n const got: Record<string, string> = {};\n req.on('response', (h) => {\n status = Number(h[':status'] ?? 0);\n for (const [k, v] of Object.entries(h)) if (!k.startsWith(':') && v !== undefined) got[k] = String(v);\n });\n req.on('data', (c: Buffer) => chunks.push(c));\n // Settled on 'close', the last event. Node emits 'end' even when the connection drops part way\n // through the body (the session is already destroyed by then), so only a stream that ended\n // while its session was alive, and closed without a reset (rstCode 0, NO_ERROR), is an answer.\n // Anything else (no response, an interrupted body) is an error, never a truncated answer and\n // never left pending. finish ignores this after 'error'.\n let ended = false;\n req.on('end', () => {\n ended = !s.destroyed;\n });\n req.on('close', () => {\n if (status !== 0 && ended && !req.rstCode) {\n const body = Buffer.concat(chunks);\n finish(() =>\n resolve({\n status,\n ok: status >= 200 && status < 300,\n text: init.binary ? '' : body.toString('utf8'),\n ...(init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {}),\n headers: got,\n }),\n );\n return;\n }\n const why = status === 0 ? 'without a response' : 'before the response completed';\n finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));\n });\n req.on('error', (e) =>\n finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode }))),\n );\n req.end(init.body);\n });\n}\n\n/** Closes every session (for tests and orderly shutdown). */\nexport function closeSessions(): void {\n for (const o of origins.values()) {\n void o.session?.then((s) => s?.close());\n }\n origins.clear();\n}\n","/**\n * File content for the kosa8 provider.\n *\n * kosa8's file stream takes and returns a file's raw bytes at any absolute path:\n * `PUT`/`GET …/files?path=`, with `offset=` on a PUT (the rest of the file kept) and `Range` on a\n * GET. It is reached two ways, tried in this order:\n *\n * 1. Straight on the sandbox's host, at the direct token's `files_url`, when the token covers files.\n * This skips the API's Worker and Cloudflare's 100 MB request limit.\n * 2. Through the API, `/v1/sandboxes/{id}/files`.\n *\n * A file of at most one part (64 MiB) is one request. A larger one is sent in parts to a\n * temporary name beside it — the first part creates it, the rest are written at their offsets in\n * parallel — and renamed over its path once every part landed, so a failed part leaves the file\n * it replaces intact. It is read the same way, with ranges.\n *\n * An older host has the base64 file API instead: /workspace only, 8 MiB at most, no offsets. Its\n * refusals (400 outside /workspace, 413, 501) send the file over exec instead, in base64 chunks.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { escapeShellArg } from '@computesdk/provider';\nimport { httpRequest, type HttpResponse } from './transport';\n\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\nimport type { Kosa8Sandbox } from './index';\n\nexport type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/** Where file requests go: the host's own files URL with the direct token, or the API with the key. */\nexport interface FileTarget {\n url: string;\n token: string;\n}\n\n/**\n * Bytes per request (under the API's 100 MB request body limit), and parts moved at once: reads\n * four, writes two (four 64 MiB uploads at once on one connection sometimes made the host's HTTP/2\n * server end it with ENHANCE_YOUR_CALM, and two are about as fast). A mutable object so tests can\n * use small parts.\n */\nexport const fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };\n/**\n * Times a request that failed in transit, or with a server error, is sent again. Cloudflare's\n * 52x (host unreachable) are not retried: from the files URL they send the request to the API.\n */\nconst FILE_RETRIES = 2;\nconst RETRY_STATUS = new Set([500, 502, 503, 504]);\n\n/**\n * Statuses from the host's files URL that mean the request was not served there: the token was\n * refused (401), the sandbox is asleep and only the API wakes it (409), the host does not offer it\n * (501), or Cloudflare could not reach the host. The request then goes through the API. 403 and 404\n * are not here: from the files URL they mean permission denied and no such file.\n */\nconst DIRECT_REFUSED = new Set([401, 409, 501, 521, 522, 523, 530]);\n\n/**\n * Base64 characters per write exec (the fallback for older hosts). The exec API caps each argv\n * entry at 8192 characters, so content travels in an environment variable, which counts only toward\n * the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 48 * 1024;\n/** A file this small is read inline by one exec (fallback); its base64 stays under the exec output limit. */\nexport const INLINE_READ_BYTES = 1024 * 1024;\n\nconst NOT_FOUND_EXIT = 44;\nconst MIB = 1024 * 1024;\n\nconst q = (s: string) => `\"${escapeShellArg(s)}\"`;\nconst notFound = (path: string) => new Error(`ENOENT: no such file or directory, open '${path}'`);\n\nconst apiTarget = (sandbox: Kosa8Sandbox): FileTarget => ({\n url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,\n token: sandbox.apiKey,\n});\n\nfunction errorDetail(res: HttpResponse): string {\n const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString('utf8') : '');\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n return text.slice(0, 500);\n}\n\n/** The error for a refused file request, with Node's codes for the common ones. */\nfunction fileError(res: HttpResponse, op: 'open' | 'write', path: string): Error {\n const detail = errorDetail(res);\n if (res.status === 404) return notFound(path);\n if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ''}`);\n}\n\n/**\n * A refusal from the older base64 file API (or a host without any): a path outside /workspace,\n * a file over its 8 MiB, or offsets and streams it does not have. Exec reaches those.\n */\nfunction olderFileApi(res: HttpResponse): boolean {\n return res.status === 413 || res.status === 501 || (res.status === 400 && /workspace/i.test(errorDetail(res)));\n}\n\nasync function send(\n t: FileTarget,\n method: 'GET' | 'PUT',\n path: string,\n { body, offset, range }: { body?: Uint8Array; offset?: number; range?: [number, number] } = {},\n): Promise<HttpResponse> {\n const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ''}`;\n const headers: Record<string, string> = { Authorization: `Bearer ${t.token}` };\n if (body) headers['Content-Type'] = 'application/octet-stream';\n if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;\n // Every request here is idempotent (a whole file, a part at its offset, or a read), so one that\n // failed in transit or with a server error is sent again.\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await httpRequest(url, { method, headers, body, binary: true });\n if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;\n } catch (err) {\n if (attempt >= FILE_RETRIES) throw err;\n }\n await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));\n }\n}\n\n/**\n * Runs task over items, at most `limit` at once. After a task fails no more are started, and the\n * first failure is returned (or thrown) once the ones in progress have finished.\n */\nasync function inParallel<T, R>(items: T[], limit: number, task: (item: T) => Promise<R | null>): Promise<R | null> {\n let next = 0;\n let failed: R | null = null;\n let thrown: { err: unknown } | undefined;\n const worker = async () => {\n while (!failed && !thrown && next < items.length) {\n try {\n const r = await task(items[next++]);\n if (r) failed ??= r;\n } catch (err) {\n thrown ??= { err };\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n if (thrown) throw thrown.err;\n return failed;\n}\n\n/** Writes bytes at path through t: null when written, else the refusal. */\nasync function writeTo(t: FileTarget, path: string, bytes: Uint8Array): Promise<HttpResponse | null> {\n // The first part replaces the file (creating its directories); the rest are written at their offsets.\n const first = await send(t, 'PUT', path, { body: bytes.subarray(0, fileParts.bytes) });\n if (!first.ok) return first;\n const offsets: number[] = [];\n for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);\n return inParallel(offsets, fileParts.writeConcurrency, async (at) => {\n const res = await send(t, 'PUT', path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });\n return res.ok ? null : res;\n });\n}\n\n/** Reads path through t: its bytes, or the refusal. */\nasync function readFrom(t: FileTarget, path: string): Promise<Uint8Array | HttpResponse> {\n const first = await send(t, 'GET', path, { range: [0, fileParts.bytes - 1] });\n // 416: the first byte is past the end, so the file is empty.\n if (first.status === 416) return new Uint8Array();\n // 200: the whole file (a server that ignores Range).\n if (first.status === 200) return first.bytes ?? new Uint8Array();\n if (first.status !== 206) return first;\n const head = first.bytes ?? new Uint8Array();\n const total = Number(/\\/(\\d+)\\s*$/.exec(first.headers['content-range'] ?? '')?.[1] ?? head.length);\n if (total <= head.length) return head;\n const starts: number[] = [];\n for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);\n const parts = new Map<number, Uint8Array>();\n const failed = await inParallel(starts, fileParts.concurrency, async (at) => {\n const res = await send(t, 'GET', path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });\n if (res.status !== 206 && res.status !== 200) return res;\n parts.set(at, res.bytes ?? new Uint8Array());\n return null;\n });\n if (failed) return failed;\n const all = Buffer.concat([head, ...starts.map((at) => parts.get(at)!)]);\n if (all.length !== total) {\n throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);\n }\n return all;\n}\n\n// --- write -------------------------------------------------------------------\n\n/**\n * Writes a file: straight to the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function writeFileNative(\n sandbox: Kosa8Sandbox,\n path: string,\n content: string,\n run: ExecRunner,\n direct: FileTarget | null = null,\n): Promise<void> {\n const bytes = Buffer.from(content, 'utf8');\n const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${randomBytes(6).toString('hex')}` : null;\n const dest = staged ?? path;\n const commit = async () => {\n // `[ -d ]` first: `mv` onto an existing directory would move the staged file inside it.\n if (staged) {\n await mustSucceed(\n run,\n sandbox,\n `if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,\n 'write',\n path,\n );\n }\n };\n try {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const res = await writeTo(direct, dest, bytes).catch(() => undefined);\n if (res === null) {\n await commit();\n return;\n }\n if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, 'write', path);\n if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const res = await writeTo(apiTarget(sandbox), dest, bytes);\n if (!res) {\n await commit();\n return;\n }\n if (!olderFileApi(res)) throw fileError(res, 'write', path);\n if (res.status === 501) sandbox.files = false;\n }\n return writeFileViaExec(sandbox, path, bytes, run);\n } finally {\n if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {});\n }\n}\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, what: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n if ((result as { stdoutTruncated?: boolean }).stdoutTruncated) {\n throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);\n }\n return result.stdout;\n}\n\n/**\n * Writes a file through exec (older hosts): base64 chunks into a temporary file beside it, then an\n * atomic rename. One chunk is a single command.\n */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void> {\n const target = q(path);\n const tmp = q(`${path}.computesdk-${randomBytes(6).toString('hex')}`);\n const encoded = Buffer.from(content).toString('base64');\n const mkParent = `d=$(dirname ${target}) && mkdir -p \"$d\"`;\n if (encoded.length <= WRITE_CHUNK_CHARS) {\n const cmd = `${mkParent} && printf '%s' \"$KOSA8_CHUNK\" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;\n await mustSucceed(run, sandbox, cmd, 'write', path, { KOSA8_CHUNK: encoded });\n return;\n }\n try {\n await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, 'write', path);\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, 'write', path, {\n KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS),\n });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, 'write', path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\n// --- read --------------------------------------------------------------------\n\nconst fromBase64 = (s: string) => Buffer.from(s.replace(/\\s+/g, ''), 'base64');\n\n/**\n * Reads a file: straight from the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function readFileNative(sandbox: Kosa8Sandbox, path: string, run: ExecRunner, direct: FileTarget | null = null): Promise<string> {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const got = await readFrom(direct, path).catch(() => undefined);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, 'open', path);\n if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const got = await readFrom(apiTarget(sandbox), path);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (!olderFileApi(got)) throw fileError(got, 'open', path);\n if (got.status === 501) sandbox.files = false;\n }\n return readFileViaExec(sandbox, path, run);\n}\n\n/** Reads a file through exec (older hosts): inline when small, else 1 MiB per command. */\nasync function readFileViaExec(sandbox: Kosa8Sandbox, path: string, run: ExecRunner): Promise<string> {\n const p = q(path);\n const out = await mustSucceed(\n run,\n sandbox,\n `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo \"$s\"; if [ \"$s\" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,\n 'open',\n path,\n );\n const nl = out.indexOf('\\n');\n const size = Number(out.slice(0, nl < 0 ? undefined : nl).trim());\n if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);\n if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? '' : out.slice(nl + 1)).toString('utf8');\n const chunks: Buffer[] = new Array(Math.ceil(size / INLINE_READ_BYTES));\n let next = 0;\n const worker = async () => {\n while (next < chunks.length) {\n const i = next++;\n chunks[i] = fromBase64(\n await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, 'open', path),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));\n const all = Buffer.concat(chunks);\n if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);\n return all.toString('utf8');\n}\n"],"mappings":";AAeA,SAAS,gBAAgB,kBAAAA,iBAAgB,uBAAuB;;;ACwBhE,IAAM,cAAwC,OAAO,UAAU,aAAa,QAAQ;AAEpF,IAAI;AACJ,SAAS,YAAmC;AAC1C,4BAAc,OAAO,OAAY,EAAE;AAAA,IACjC,CAAC,MAAQ,EAAqC,WAAW;AAAA,IACzD,MAAM;AAAA,EACR;AACA,SA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yDAAyD;AAAA,MAC9E;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAMM,IAAM,QAAyB,CAAC,WAAW;AAChD,MAAI;AACF,eAAW,cAAc,MAAM,EAAE,OAAO;AAAA,EAC1C,QAAQ;AAAA,EAER;AACA,SAAO,SAAS,MAAM;AACxB;AAEA,IAAO,gBAAQ;","names":["escapeShellArg","escapeShellArg"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/transport.ts","../src/files.ts"],"sourcesContent":["/**\n * kosa8 Provider - Factory-based Implementation\n *\n * Sandboxes on kosa8 Cloud (https://kosa8.com). Each sandbox runs in its own microVM with its\n * own kernel. The cloud API is a small JSON surface, so this package talks to it with `fetch`\n * and has no SDK dependency.\n *\n * Commands go through the buffered exec endpoint: straight to the sandbox's host when the create\n * answer carries a direct-exec URL and token (see runDirect), otherwise through the API. File content\n * moves through kosa8's file API (`/v1/sandboxes/{id}/files`, see files.ts), with shell commands\n * over exec for small files and for hosts without it. `pause()`/`resume()` map to kosa8's sleep and\n * wake, and `provider.snapshot` to kosa8 snapshots: both keep the VM's memory (running processes)\n * as well as its disk.\n */\n\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\nimport { httpRequest, preconnect } from './transport';\nimport { readFileNative, writeFileNative, type ExecRunner } from './files';\n\nexport { WRITE_CHUNK_CHARS, writeFileViaExec } from './files';\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateSnapshotOptions,\n InstanceInfo,\n InstanceSizeClass,\n RunCommandOptions,\n SnapshotCapabilities,\n} from '@computesdk/provider';\n\nexport interface Kosa8Config {\n /** Template to boot per standard `sizeClass`. The template fixes CPU and memory, so build one per size. */\n sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;\n /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */\n apiKey?: string;\n /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */\n baseUrl?: string;\n /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */\n region?: string;\n}\n\n/** A sandbox as the kosa8 Cloud API returns it. */\nexport interface Kosa8SandboxData {\n id: string;\n state: string;\n template: string;\n cpus: number;\n mem_mb: number;\n region: string | null;\n created_at: number;\n started_at: number | null;\n sleep_after_s: number | null;\n delete_after: number | null;\n last_error: string | null;\n [key: string]: unknown;\n}\n\n/** A template as GET /v1/templates returns it. */\nexport interface Kosa8Template {\n key: string;\n cpus: number;\n mem_mb: number;\n image?: string;\n regions: string[];\n [key: string]: unknown;\n}\n\n/** The create answer's `direct` object: the host's exec endpoint for this sandbox and a token for it. */\nexport interface Kosa8Direct {\n exec_url: string;\n /** The host's raw file endpoint for this sandbox, when the token also covers files (`files.direct`). */\n files_url?: string;\n token: string;\n /** When the token stops working, ms since the epoch. */\n expires_at: number;\n}\n\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\n /** Present while commands can go straight to the sandbox's host (runDirect). */\n direct?: Kosa8Direct;\n /** A fresh direct token being fetched (refreshDirect). */\n refreshing?: Promise<void>;\n /** False once the sandbox's host answered that it has no file API: files then go over exec. */\n files?: boolean;\n /** False once the host refused file requests with the direct token: files then go through the API. */\n directFiles?: boolean;\n}\n\n/** A snapshot as the kosa8 Cloud API returns it. */\nexport interface Kosa8SnapshotData {\n id: string;\n name: string | null;\n state: string;\n source_sandbox_id: string;\n template: string;\n cpus: number;\n mem_mb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n created_at: number;\n [key: string]: unknown;\n}\n\n/** A snapshot as `provider.snapshot` returns it. */\nexport interface Kosa8Snapshot {\n id: string;\n provider: 'kosa8';\n createdAt: Date;\n metadata: {\n name: string | null;\n sourceInstanceId: string;\n state: string;\n template: string;\n cpus: number;\n memMb: number;\n image: string | null;\n bytes: number;\n region: string | null;\n /** How long the host took to save it, when the API reports it. */\n createMs?: number | null;\n };\n}\n\ninterface Auth {\n apiKey: string;\n baseUrl: string;\n}\n\ninterface ExecResponse {\n exit: number | null;\n stdout: string;\n stderr: string;\n /** Set when the API kept only the first part of a stream (its output limit). */\n stdout_truncated?: boolean;\n stderr_truncated?: boolean;\n /** The stream's full length, kept or not. */\n stdout_bytes?: number;\n stderr_bytes?: number;\n}\n\n/**\n * A command's result. Beyond ComputeSDK's fields it says when the API returned only the first part\n * of the output (its limit on a buffered command): `truncated`, per stream, and each stream's full\n * length in bytes. These are absent when the API does not report them.\n */\nexport interface Kosa8CommandResult extends CommandResult {\n truncated?: boolean;\n stdoutTruncated?: boolean;\n stderrTruncated?: boolean;\n stdoutBytes?: number;\n stderrBytes?: number;\n}\n\n/** The API's shortest and longest lifetime for a sandbox (ttl_s). */\nconst MIN_TTL_S = 60;\nconst MAX_TTL_S = 90 * 86400;\n\n/** Exit code reported when `runCommand`'s timeout stops a command (as coreutils `timeout` does). */\nconst TIMEOUT_EXIT = 124;\n\n/** Names the marker file a timed command creates once it returns (see execArgv). */\nconst DONE_ENV = 'KOSA8_DONE';\n\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template (or an image) fixes the size. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'envs', 'volumes',\n] as const;\n\n/** A snapshot name the API accepts; another name is kept only in the snapshot's metadata. */\nconst SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\nfunction resolveConfig(config: Kosa8Config): Auth {\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const apiKey = config.apiKey || env?.KOSA8_API_KEY || '';\n if (!apiKey) {\n throw new Error(\n `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. ` +\n `Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`,\n );\n }\n const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || 'https://api.kosa8.com').replace(/\\/+$/, '');\n return { apiKey, baseUrl };\n}\n\nasync function request<T>(\n auth: Auth,\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n): Promise<T | null> {\n const res = await httpRequest(`${auth.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n if (res.status === 404) return null;\n const text = res.text;\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);\n }\n return (text ? JSON.parse(text) : null) as T;\n}\n\nconst sandboxPath = (id: string, rest = '') => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;\n\nfunction toSandbox(auth: Auth, data: Kosa8SandboxData, direct?: unknown): Kosa8Sandbox {\n const sandbox: Kosa8Sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\n if (isDirect(direct)) {\n sandbox.direct = direct;\n // The first command follows at once: its host's session opens now.\n preconnect(direct.exec_url);\n }\n return sandbox;\n}\n\nfunction isDirect(d: unknown): d is Kosa8Direct {\n const x = d as Kosa8Direct | null | undefined;\n return !!x && typeof x.exec_url === 'string' && /^https:\\/\\//.test(x.exec_url) && typeof x.token === 'string' &&\n typeof x.expires_at === 'number';\n}\n\n/** A direct token this close to expiry is not used; one closer than DIRECT_REFRESH_MS is renewed in the background. */\nconst DIRECT_MARGIN_MS = 15_000;\nconst DIRECT_REFRESH_MS = 60_000;\n\n/**\n * Statuses from the direct endpoint that mean the command did not run there: the token was refused\n * (401, 403), the host does not have the sandbox (404), it is asleep and only the API wakes it\n * (409), the host does not offer it (501), or Cloudflare could not reach the host (521, 522, 523,\n * 530). The command is then sent through the API. Any other failure is reported as is, since the\n * command may have run.\n */\nconst DIRECT_NOT_RUN = new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);\n\n/**\n * The direct token and files URL for file requests, or null when files go through the API: no\n * token, a host whose token does not cover files, one that refused it, or a token about to expire\n * (renewed in the background, as for commands).\n */\nexport function directFiles(sandbox: Kosa8Sandbox): { url: string; token: string } | null {\n const d = sandbox.direct;\n if (!d?.files_url || sandbox.directFiles === false || !/^https:\\/\\//.test(d.files_url)) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };\n}\n\n/** Renews the direct token in the background; a failure leaves the API path in use. */\nfunction refreshDirect(sandbox: Kosa8Sandbox): void {\n if (sandbox.refreshing) return;\n sandbox.refreshing = request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct'))\n .then((r) => {\n if (isDirect(r?.direct)) sandbox.direct = r.direct;\n })\n .catch(() => {})\n .finally(() => {\n sandbox.refreshing = undefined;\n });\n}\n\n/**\n * Runs a command on the sandbox's host directly (the create answer's `direct`), skipping the API's\n * hop. Returns null when the command was not run there, so the caller sends it through the API;\n * the sandbox then stops using the direct path until a fresh token arrives.\n */\nasync function runDirect(sandbox: Kosa8Sandbox, body: unknown, signal?: AbortSignal): Promise<ExecResponse | null> {\n const d = sandbox.direct;\n if (!d) return null;\n const left = d.expires_at - Date.now();\n if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);\n if (left < DIRECT_MARGIN_MS) return null;\n const res = await httpRequest(d.exec_url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${d.token}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal,\n });\n const text = res.text;\n if (DIRECT_NOT_RUN.has(res.status)) {\n if (sandbox.direct === d) sandbox.direct = undefined;\n return null;\n }\n if (!res.ok) {\n let detail = text;\n try {\n const parsed = JSON.parse(text) as { error?: string };\n if (parsed?.error) detail = parsed.error;\n } catch {\n // Not JSON: keep the raw text.\n }\n throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);\n }\n return JSON.parse(text) as ExecResponse;\n}\n\n/** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */\nexport function createBody(config: Kosa8Config, options: CreateInstanceOptions = {}): Record<string, unknown> {\n for (const key of UNSUPPORTED_CREATE_OPTIONS) {\n if (options[key] !== undefined) {\n throw new Error(\n `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; ` +\n `pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n if (options.snapshotId !== undefined) {\n // A sandbox made from a snapshot takes its template, size, image and host from the snapshot.\n for (const key of ['templateId', 'image', 'region'] as const) {\n if (options[key] !== undefined) {\n throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);\n }\n }\n body.snapshot = options.snapshotId;\n } else if (options.image !== undefined) {\n // An OCI image boots a VM of its own (the API's default size for an image, 2 vCPU / 4 GiB),\n // so the configured default template does not apply; an explicit templateId is passed on.\n body.image = options.image;\n if (options.templateId) body.template = options.templateId;\n } else {\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n }\n if (options.snapshotId === undefined) {\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\n }\n if (options.sleepAfterSeconds !== undefined) body.sleep_after_s = options.sleepAfterSeconds;\n if (typeof options.timeout === 'number' && options.timeout > 0) {\n // kosa8 deletes the sandbox when its lifetime ends; the API's shortest lifetime is 60 s.\n body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1000)));\n }\n return body;\n}\n\n/** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */\nexport function execArgv(command: string, options?: RunCommandOptions): string[] {\n let cmd = command;\n if (options?.cwd) cmd = `cd \"${escapeShellArg(options.cwd)}\" && ${cmd}`;\n if (options?.background) {\n cmd = `nohup sh -c \"${escapeShellArg(cmd)}\" >/dev/null 2>&1 &`;\n } else if (options?.timeout && options.timeout > 0) {\n // Stop the command in the sandbox, not just the wait for it. GNU timeout signals the whole\n // process group; an image without `timeout` runs the command unbounded and the request's\n // own deadline (runCommand) still applies.\n //\n // Status 137 alone does not mean the deadline passed: the command may exit 137 itself or be\n // killed early. The command runs in a subshell and a marker file is created once it returns,\n // whatever its status. Only a 137 with no marker (the shell itself was killed) once the\n // deadline has passed (whole seconds: the elapsed count cannot fall short of a real deadline)\n // is reported as a timeout.\n const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const plain = `sh -c \"${escapeShellArg(cmd)}\"`;\n const marked = `sh -c \"${escapeShellArg(`(\\n${cmd}\\n); s=$?; : > \"$${DONE_ENV}\"; exit $s`)}\"`;\n cmd =\n `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then ` +\n `rm -f \"$${DONE_ENV}\"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; ` +\n `if [ $s -eq 137 ] && [ ! -e \"$${DONE_ENV}\" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; ` +\n `rm -f \"$${DONE_ENV}\"; exit $s; ` +\n `else ${plain}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/**\n * The exec API's limit on each argv entry. Measured in UTF-8 bytes here, which is never less than\n * the API's own count, so a command with multibyte characters cannot slip over it.\n */\nconst MAX_ARG_BYTES = 8192;\n\n/** The exec API's limit on the whole request body, in bytes. */\nexport const MAX_EXEC_BODY_BYTES = 64 * 1024;\n\n/** Environment variable that carries a script too long for one argv entry; callers may not set it. */\nexport const SCRIPT_ENV = 'KOSA8_SCRIPT';\n\n/**\n * The exec request body: a script too long for one argv entry travels in an environment variable.\n * Throws before any request is made when the serialized body would exceed the exec API's limit.\n */\nexport function execBody(command: string, options?: RunCommandOptions): { cmd: string[]; env: string[] } {\n const argv = execArgv(command, options);\n const env = execEnv(options?.env);\n const body = Buffer.byteLength(argv[2], 'utf8') <= MAX_ARG_BYTES\n ? { cmd: argv, env }\n : { cmd: ['sh', '-c', `eval \"$${SCRIPT_ENV}\"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };\n const size = Buffer.byteLength(JSON.stringify(body), 'utf8');\n if (size > MAX_EXEC_BODY_BYTES) {\n throw new Error(\n `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) ` +\n `for the command and its environment together. Write a long script to a file with ` +\n `sandbox.filesystem.writeFile() and run that file instead.`,\n );\n }\n return body;\n}\n\nfunction execEnv(env?: Record<string, string>): string[] {\n if (!env) return [];\n return Object.entries(env).map(([key, value]) => {\n if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);\n if (key === SCRIPT_ENV) {\n throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);\n }\n return `${key}=${value}`;\n });\n}\n\nfunction infoStatus(state: string): InstanceInfo['status'] {\n if (state === 'error') return 'error';\n // A sleeping sandbox is alive: its memory and disk are saved, and any call (a command, a file\n // read or write) wakes it in about a second, so it reports as running.\n if (state === 'running' || state === 'sleeping') return 'running';\n // creating, paused, stopped, deleted and expired (past its deadline): not running now, so a\n // readiness check keeps waiting and a liveness check sees it gone.\n return 'stopped';\n}\n\nasync function getData(sandbox: Kosa8Sandbox): Promise<Kosa8SandboxData | null> {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id));\n return data?.sandbox ?? null;\n}\n\n/** How often a sandbox that is still booting (an image's cold boot) is checked, and for how long. */\nconst BOOT_POLL_MS = 150;\nconst BOOT_TIMEOUT_MS = 5 * 60_000;\n\n/**\n * Waits for a sandbox the API answered with `creating` (202: an image booted cold) to run, so the\n * create resolves to a sandbox that takes commands. Its direct exec token is fetched once it runs.\n */\nasync function waitUntilRunning(sandbox: Kosa8Sandbox, signal?: AbortSignal): Promise<void> {\n const deadline = Date.now() + BOOT_TIMEOUT_MS;\n while (sandbox.data.state === 'creating') {\n if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1000} s`);\n signal?.throwIfAborted();\n await new Promise((r) => setTimeout(r, BOOT_POLL_MS));\n const current = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'GET', sandboxPath(sandbox.id), undefined, signal);\n if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);\n sandbox.data = current.sandbox;\n }\n if (sandbox.data.state !== 'running') {\n const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : '';\n throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);\n }\n if (!sandbox.direct) {\n const r = await request<{ direct?: unknown }>(sandbox, 'POST', sandboxPath(sandbox.id, '/direct')).catch(() => null);\n if (isDirect(r?.direct)) {\n sandbox.direct = r.direct;\n preconnect(r.direct.exec_url);\n }\n }\n}\n\nfunction toSnapshot(s: Kosa8SnapshotData, createMs?: number | null): Kosa8Snapshot {\n return {\n id: s.id,\n provider: 'kosa8',\n createdAt: new Date(s.created_at),\n metadata: {\n name: s.name ?? null,\n sourceInstanceId: s.source_sandbox_id,\n state: s.state,\n template: s.template,\n cpus: s.cpus,\n memMb: s.mem_mb,\n image: s.image ?? null,\n bytes: s.bytes ?? 0,\n region: s.region ?? null,\n ...(createMs !== undefined ? { createMs } : {}),\n },\n };\n}\n\n/**\n * kosa8 snapshots save the whole VM, memory included, so a restore resumes running processes. The\n * source keeps running, and one snapshot restores into any number of sandboxes, each copy-on-write\n * on the snapshot's host. A snapshot is ready when `create` returns.\n */\nexport const SNAPSHOT_CAPABILITIES: SnapshotCapabilities = {\n scope: 'rootfs',\n memory: true,\n destroysSource: false,\n source: 'kept',\n fork: true,\n readiness: 'immediate',\n};\n\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nconst provider = defineProvider<Kosa8Sandbox, Kosa8Config>({\n name: 'kosa8',\n sizes: (config, profile, options) => {\n if (options?.templateId !== undefined || options?.snapshotId !== undefined) {\n return { status: 'unsupported', reason: 'A kosa8 template or snapshot fixes CPU and memory; drop templateId/snapshotId to boot the standard size template.' };\n }\n const templateId = config.sizeTemplates?.[profile.sizeClass];\n if (typeof templateId !== 'string' || !templateId.trim()) {\n return { status: 'unconfigured', reason: `kosa8 fixes CPU and memory per template; build one at ${profile.vcpus} vCPU / ${profile.memoryMiB} MiB and set sizeTemplates.${profile.sizeClass}.` };\n }\n return { status: 'supported', nativeOptions: { templateId } };\n },\n methods: {\n instances: {\n create: async (config: Kosa8Config, options?: CreateInstanceOptions) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData; direct?: unknown }>(\n auth,\n 'POST',\n '/v1/sandboxes',\n createBody(config, options),\n options?.signal,\n );\n if (!data?.sandbox) throw new Error('kosa8 API returned no sandbox on create');\n const sandbox = toSandbox(auth, data.sandbox, data.direct);\n if (sandbox.data.state !== 'running') {\n try {\n await waitUntilRunning(sandbox, options?.signal);\n } catch (err) {\n // A sandbox that never ran is not left behind, billed.\n await request(auth, 'DELETE', sandboxPath(sandbox.id)).catch(() => {});\n throw err;\n }\n }\n return { instance: sandbox, instanceId: sandbox.id };\n },\n\n getById: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandbox: Kosa8SandboxData }>(auth, 'GET', sandboxPath(instanceId));\n return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;\n },\n\n list: async (config: Kosa8Config) => {\n const auth = resolveConfig(config);\n const data = await request<{ sandboxes: Kosa8SandboxData[] }>(auth, 'GET', '/v1/sandboxes');\n return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));\n },\n\n destroy: async (config: Kosa8Config, instanceId: string) => {\n const auth = resolveConfig(config);\n // A sandbox that is already gone answers 404, which request() returns as null.\n await request(auth, 'DELETE', sandboxPath(instanceId));\n },\n\n runCommand: async (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions): Promise<Kosa8CommandResult> => {\n const start = Date.now();\n const body = execBody(command, options);\n // The command is stopped in the sandbox at the deadline; the request gets a grace period on top.\n const signal = options?.timeout && options.timeout > 0 && !options.background\n ? AbortSignal.timeout(options.timeout + 30_000)\n : undefined;\n const data = (await runDirect(sandbox, body, signal)) ??\n (await request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n const result: Kosa8CommandResult = {\n stdout: data.stdout ?? '',\n stderr: data.stderr ?? '',\n exitCode: Number.isInteger(data.exit) ? (data.exit as number) : -1,\n durationMs: Date.now() - start,\n };\n if (typeof data.stdout_truncated === 'boolean' || typeof data.stderr_truncated === 'boolean') {\n result.stdoutTruncated = data.stdout_truncated === true;\n result.stderrTruncated = data.stderr_truncated === true;\n result.truncated = result.stdoutTruncated || result.stderrTruncated;\n }\n if (typeof data.stdout_bytes === 'number') result.stdoutBytes = data.stdout_bytes;\n if (typeof data.stderr_bytes === 'number') result.stderrBytes = data.stderr_bytes;\n return result;\n },\n\n getInfo: async (sandbox: Kosa8Sandbox): Promise<InstanceInfo> => {\n const current = (await getData(sandbox)) ?? { ...sandbox.data, state: 'deleted' };\n sandbox.data = current;\n return {\n id: sandbox.id,\n provider: 'kosa8',\n status: infoStatus(current.state),\n createdAt: new Date(current.created_at),\n timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,\n metadata: {\n state: current.state,\n template: current.template,\n cpus: current.cpus,\n memMb: current.mem_mb,\n region: current.region,\n sleepAfterSeconds: current.sleep_after_s,\n deleteAfter: current.delete_after,\n lastError: current.last_error,\n },\n };\n },\n\n getUrl: async (): Promise<string> => {\n throw notAvailable('port URLs');\n },\n\n // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.\n pause: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/sleep'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n resume: async (sandbox: Kosa8Sandbox): Promise<void> => {\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'POST', sandboxPath(sandbox.id, '/wake'));\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = data.sandbox;\n },\n\n pauseCapabilities: { memory: true },\n\n // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.\n lifetime: {},\n\n // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.\n extendLifetime: async (sandbox: Kosa8Sandbox, ms: number): Promise<void> => {\n const current = await getData(sandbox);\n if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n sandbox.data = current;\n if (current.delete_after == null) return;\n const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1000);\n const data = await request<{ sandbox: Kosa8SandboxData }>(sandbox, 'PATCH', sandboxPath(sandbox.id), {\n delete_after: Math.floor(deleteAfter),\n });\n // A 404 here means the sandbox was deleted between the read and the update.\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n if (data.sandbox) sandbox.data = data.sandbox;\n },\n\n getInstance: (sandbox: Kosa8Sandbox): Kosa8Sandbox => sandbox,\n\n // File content straight to the sandbox's host with the direct token, else through the API's\n // file stream, else (an older host) exec (files.ts); the rest are single shell commands.\n filesystem: {\n readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),\n writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),\n mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),\n readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),\n exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),\n remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path),\n },\n },\n\n snapshot: {\n capabilities: SNAPSHOT_CAPABILITIES,\n\n // POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.\n create: async (config: Kosa8Config, instanceId: string, options?: CreateSnapshotOptions): Promise<Kosa8Snapshot> => {\n const auth = resolveConfig(config);\n const name = typeof options?.name === 'string' && SNAPSHOT_NAME.test(options.name) ? options.name : undefined;\n const data = await request<{ snapshot: Kosa8SnapshotData; ms?: number | null }>(\n auth,\n 'POST',\n sandboxPath(instanceId, '/snapshots'),\n name ? { name } : {},\n );\n if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);\n return toSnapshot(data.snapshot, typeof data.ms === 'number' ? data.ms : null);\n },\n\n list: async (config: Kosa8Config): Promise<Kosa8Snapshot[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ snapshots: Kosa8SnapshotData[] }>(auth, 'GET', '/v1/snapshots');\n return (data?.snapshots ?? []).map((s) => toSnapshot(s));\n },\n\n // A snapshot that is already gone answers 404, which request() returns as null.\n delete: async (config: Kosa8Config, snapshotId: string): Promise<void> => {\n const auth = resolveConfig(config);\n await request(auth, 'DELETE', `/v1/snapshots/${encodeURIComponent(snapshotId)}`);\n },\n },\n\n template: {\n create: async () => {\n throw notAvailable('creating templates (templates are offered by the hosts)');\n },\n list: async (config: Kosa8Config): Promise<Kosa8Template[]> => {\n const auth = resolveConfig(config);\n const data = await request<{ templates: Kosa8Template[] }>(auth, 'GET', '/v1/templates');\n return data?.templates ?? [];\n },\n delete: async () => {\n throw notAvailable('deleting templates (templates are offered by the hosts)');\n },\n },\n },\n});\n\n/**\n * The kosa8 provider. Configuring it opens the HTTP/2 session to the API (transport.ts), so the\n * first create does not pay the connection's handshake.\n */\nexport const kosa8: typeof provider = (config) => {\n try {\n preconnect(resolveConfig(config).baseUrl);\n } catch {\n // No key yet: the first call reports it.\n }\n return provider(config);\n};\n\nexport default kosa8;\n","/**\n * HTTP for the kosa8 provider: one HTTP/2 session per origin, shared by every request, instead of\n * a TLS connection per request.\n *\n * With `fetch`, 100 sandboxes created at once open 100 connections, each paying its own TCP and\n * TLS handshake before the request is sent. On kosa8 Cloud that was ~260 ms of each create in a\n * 100-at-once burst from Virginia (2026-11-13), against ~40 ms for a request on a connection that\n * was already open. Over one HTTP/2 session the handshake is paid once, and `preconnect` pays it\n * before the first request (when the provider is configured).\n *\n * `fetch` stays the fallback: where `node:http2` is not available, for an origin whose session\n * could not be opened, and whenever the global `fetch` has been replaced (tests, proxies,\n * instrumentation), which is then honoured for every request.\n */\n\ntype Http2 = typeof import('node:http2');\ntype Session = import('node:http2').ClientHttp2Session;\n\nexport interface HttpResponse {\n status: number;\n ok: boolean;\n /** The body as UTF-8 text; empty when the request asked for `binary`. */\n text: string;\n /** The body's bytes, present when the request asked for `binary`. */\n bytes?: Uint8Array;\n /** Response headers, names in lower case. */\n headers: Record<string, string>;\n}\n\nexport interface HttpInit {\n method: string;\n headers: Record<string, string>;\n body?: string | Uint8Array;\n signal?: AbortSignal;\n /** Return the body as bytes (`bytes`) rather than text, for file content. */\n binary?: boolean;\n}\n\n/** The global fetch as it was when this module loaded; a different one later was put there on purpose. */\nconst nativeFetch: typeof fetch | undefined = typeof fetch === 'function' ? fetch : undefined;\n\nlet http2Load: Promise<Http2 | null> | undefined;\nfunction loadHttp2(): Promise<Http2 | null> {\n http2Load ??= import('node:http2').then(\n (m) => ((m as unknown as { default?: Http2 }).default ?? m) as Http2,\n () => null,\n );\n return http2Load;\n}\n\ninterface Origin {\n session?: Promise<Session | null>;\n /** Set once a session could not be opened: `fetch` for this origin from then on. */\n failed?: boolean;\n}\n\nconst origins = new Map<string, Origin>();\n\n/**\n * Requests in progress on each session. A session's socket is referenced only while this is above\n * zero, so an idle session never keeps the process alive. Counted per session, not per origin: a\n * session the origin has stopped using (GOAWAY) is still released by the requests that were on it.\n */\nconst inFlight = new WeakMap<Session, number>();\n/** Sessions that received GOAWAY: closed once their last request finishes. */\nconst retired = new WeakSet<Session>();\n\nfunction hold(s: Session): void {\n inFlight.set(s, (inFlight.get(s) ?? 0) + 1);\n s.ref();\n}\n\nfunction release(s: Session): void {\n const n = (inFlight.get(s) ?? 1) - 1;\n inFlight.set(s, n);\n if (n > 0 || s.destroyed) return;\n if (retired.has(s)) s.close();\n else s.unref();\n}\n\nfunction abortError(signal: AbortSignal): unknown {\n return signal.reason ?? new Error('The operation was aborted');\n}\n\n/** p, or the signal's abort, whichever comes first; p itself is left to settle for its other waiters. */\nfunction untilAborted<T>(p: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) return p;\n if (signal.aborted) return Promise.reject(abortError(signal));\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener('abort', onAbort, { once: true });\n p.then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n}\n\n/** Each stream's and the whole session's receive window. */\nconst WINDOW_BYTES = 16 * 1024 * 1024;\nconst SESSION_WINDOW_BYTES = 64 * 1024 * 1024;\n\n/** How long opening a session may take before the origin falls back to `fetch`. */\nconst CONNECT_TIMEOUT_MS = 10_000;\n\n/**\n * KOSA8_HTTP_TRANSPORT: unset (auto), `fetch` (never HTTP/2), or `http2` (HTTP/2 even when the\n * global fetch was replaced, and plaintext h2c to a loopback `http:` URL, for tests).\n */\nfunction mode(): 'auto' | 'fetch' | 'http2' {\n const m = typeof process !== 'undefined' ? process.env?.KOSA8_HTTP_TRANSPORT : undefined;\n return m === 'fetch' || m === 'http2' ? m : 'auto';\n}\n\nfunction originOf(url: string): string | null {\n try {\n const u = new URL(url);\n if (u.protocol === 'https:') return u.origin;\n const loopback = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';\n return u.protocol === 'http:' && loopback && mode() === 'http2' ? u.origin : null;\n } catch {\n return null;\n }\n}\n\nfunction useHttp2(): boolean {\n if (typeof process === 'undefined' || !process.versions?.node) return false;\n const m = mode();\n if (m === 'fetch') return false;\n return m === 'http2' || (typeof fetch === 'function' && fetch === nativeFetch);\n}\n\nfunction session(origin: string): Promise<Session | null> {\n let o = origins.get(origin);\n if (!o) {\n o = {};\n origins.set(origin, o);\n }\n if (o.failed) return Promise.resolve(null);\n if (o.session) return o.session;\n const entry = o;\n const opening: Promise<Session | null> = loadHttp2().then((http2) => {\n if (!http2) {\n entry.failed = true;\n return null;\n }\n return new Promise<Session | null>((resolve) => {\n let settled = false;\n // Large flow-control windows, so a big file moves at the link's speed rather than 64 KiB\n // per round trip (HTTP/2's default window).\n const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n entry.failed = true;\n s.destroy();\n resolve(null);\n }, CONNECT_TIMEOUT_MS);\n timer.unref?.();\n const forget = () => {\n if (entry.session === opening) entry.session = undefined;\n };\n s.once('connect', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n s.setLocalWindowSize(SESSION_WINDOW_BYTES);\n } catch {\n // An older Node: the default window.\n }\n // Unreferenced until a request holds it (hold), so a preconnect alone never keeps the\n // process alive.\n if (!inFlight.get(s)) s.unref();\n resolve(s);\n });\n s.on('error', () => {\n forget();\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n entry.failed = true;\n resolve(null);\n }\n });\n s.once('goaway', () => {\n // No new streams on it: later requests open a new session, and this one is closed once\n // the requests already on it finish.\n forget();\n retired.add(s);\n if (!inFlight.get(s)) s.close();\n });\n s.once('close', forget);\n });\n });\n entry.session = opening;\n return opening;\n}\n\n/** Opens the session to url's origin now, so the first request does not pay the handshake. */\nexport function preconnect(url: string): void {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return;\n void session(origin);\n}\n\nasync function viaFetch(url: string, init: HttpInit): Promise<HttpResponse> {\n const res = await fetch(url, {\n method: init.method,\n headers: init.headers,\n // A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).\n body: init.body as BodyInit | undefined,\n signal: init.signal,\n });\n const headers: Record<string, string> = {};\n res.headers?.forEach?.((v, k) => (headers[k.toLowerCase()] = v));\n if (init.binary) {\n return { status: res.status, ok: res.ok, text: '', bytes: new Uint8Array(await res.arrayBuffer()), headers };\n }\n return { status: res.status, ok: res.ok, text: await res.text(), headers };\n}\n\n/** One request: over the origin's HTTP/2 session when there is one, else `fetch`. */\nexport async function httpRequest(url: string, init: HttpInit): Promise<HttpResponse> {\n const origin = originOf(url);\n if (!origin || !useHttp2()) return viaFetch(url, init);\n // Waiting for the session honours this request's abort; the opening itself goes on for the\n // other requests sharing it.\n const s = await untilAborted(session(origin), init.signal);\n if (!s || s.closed || s.destroyed) return viaFetch(url, init);\n hold(s);\n try {\n return await viaSession(s, url, init);\n } catch (e) {\n // The server took no part in the request (refused stream, or the session was going away\n // or gone when it was sent): sent once more, over fetch. Anything else may have been\n // processed and is reported, never repeated.\n if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);\n throw e;\n } finally {\n release(s);\n }\n}\n\nfunction notProcessed(e: unknown): boolean {\n const x = e as { code?: string; rstCode?: number } | null;\n return (\n !!x &&\n (x.code === 'ERR_HTTP2_GOAWAY_SESSION' ||\n x.code === 'ERR_HTTP2_INVALID_SESSION' ||\n x.rstCode === 7) /* REFUSED_STREAM */\n );\n}\n\nfunction viaSession(s: Session, url: string, init: HttpInit): Promise<HttpResponse> {\n const u = new URL(url);\n return new Promise<HttpResponse>((resolve, reject) => {\n const headers: Record<string, string> = {\n ':method': init.method,\n ':path': u.pathname + u.search,\n };\n for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;\n let req: import('node:http2').ClientHttp2Stream;\n try {\n req = s.request(headers);\n } catch (e) {\n reject(e);\n return;\n }\n let done = false;\n const finish = (f: () => void) => {\n if (done) return;\n done = true;\n init.signal?.removeEventListener('abort', onAbort);\n f();\n };\n const aborted = () => (init.signal ? abortError(init.signal) : new Error('The operation was aborted'));\n const onAbort = () => {\n finish(() => reject(aborted()));\n req.close(0x8); // NGHTTP2_CANCEL\n };\n if (init.signal) {\n if (init.signal.aborted) {\n onAbort();\n return;\n }\n init.signal.addEventListener('abort', onAbort, { once: true });\n }\n const chunks: Buffer[] = [];\n let status = 0;\n const got: Record<string, string> = {};\n req.on('response', (h) => {\n status = Number(h[':status'] ?? 0);\n for (const [k, v] of Object.entries(h)) if (!k.startsWith(':') && v !== undefined) got[k] = String(v);\n });\n req.on('data', (c: Buffer) => chunks.push(c));\n // Settled on 'close', the last event. Node emits 'end' even when the connection drops part way\n // through the body (the session is already destroyed by then), so only a stream that ended\n // while its session was alive, and closed without a reset (rstCode 0, NO_ERROR), is an answer.\n // Anything else (no response, an interrupted body) is an error, never a truncated answer and\n // never left pending. finish ignores this after 'error'.\n let ended = false;\n req.on('end', () => {\n ended = !s.destroyed;\n });\n req.on('close', () => {\n if (status !== 0 && ended && !req.rstCode) {\n const body = Buffer.concat(chunks);\n finish(() =>\n resolve({\n status,\n ok: status >= 200 && status < 300,\n text: init.binary ? '' : body.toString('utf8'),\n ...(init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {}),\n headers: got,\n }),\n );\n return;\n }\n const why = status === 0 ? 'without a response' : 'before the response completed';\n finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));\n });\n req.on('error', (e) =>\n finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode }))),\n );\n req.end(init.body);\n });\n}\n\n/** Closes every session (for tests and orderly shutdown). */\nexport function closeSessions(): void {\n for (const o of origins.values()) {\n void o.session?.then((s) => s?.close());\n }\n origins.clear();\n}\n","/**\n * File content for the kosa8 provider.\n *\n * kosa8's file stream takes and returns a file's raw bytes at any absolute path:\n * `PUT`/`GET …/files?path=`, with `offset=` on a PUT (the rest of the file kept) and `Range` on a\n * GET. It is reached two ways, tried in this order:\n *\n * 1. Straight on the sandbox's host, at the direct token's `files_url`, when the token covers files.\n * This skips the API's Worker and Cloudflare's 100 MB request limit.\n * 2. Through the API, `/v1/sandboxes/{id}/files`.\n *\n * A file of at most one part (64 MiB) is one request. A larger one is sent in parts to a\n * temporary name beside it — the first part creates it, the rest are written at their offsets in\n * parallel — and renamed over its path once every part landed, so a failed part leaves the file\n * it replaces intact. It is read the same way, with ranges.\n *\n * An older host has the base64 file API instead: /workspace only, 8 MiB at most, no offsets. Its\n * refusals (400 outside /workspace, 413, 501) send the file over exec instead, in base64 chunks.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { escapeShellArg } from '@computesdk/provider';\nimport { httpRequest, type HttpResponse } from './transport';\n\nimport type { CommandResult, RunCommandOptions } from '@computesdk/provider';\nimport type { Kosa8Sandbox } from './index';\n\nexport type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/** Where file requests go: the host's own files URL with the direct token, or the API with the key. */\nexport interface FileTarget {\n url: string;\n token: string;\n}\n\n/**\n * Bytes per request (under the API's 100 MB request body limit), and parts moved at once: reads\n * four, writes two (four 64 MiB uploads at once on one connection sometimes made the host's HTTP/2\n * server end it with ENHANCE_YOUR_CALM, and two are about as fast). A mutable object so tests can\n * use small parts.\n */\nexport const fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };\n/**\n * Times a request that failed in transit, or with a server error, is sent again. Cloudflare's\n * 52x (host unreachable) are not retried: from the files URL they send the request to the API.\n */\nconst FILE_RETRIES = 2;\nconst RETRY_STATUS = new Set([500, 502, 503, 504]);\n\n/**\n * Statuses from the host's files URL that mean the request was not served there: the token was\n * refused (401), the sandbox is asleep and only the API wakes it (409), the host does not offer it\n * (501), or Cloudflare could not reach the host. The request then goes through the API. 403 and 404\n * are not here: from the files URL they mean permission denied and no such file.\n */\nconst DIRECT_REFUSED = new Set([401, 409, 501, 521, 522, 523, 530]);\n\n/**\n * Base64 characters per write exec (the fallback for older hosts). The exec API caps each argv\n * entry at 8192 characters, so content travels in an environment variable, which counts only toward\n * the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 48 * 1024;\n/** A file this small is read inline by one exec (fallback); its base64 stays under the exec output limit. */\nexport const INLINE_READ_BYTES = 1024 * 1024;\n\nconst NOT_FOUND_EXIT = 44;\nconst MIB = 1024 * 1024;\n\nconst q = (s: string) => `\"${escapeShellArg(s)}\"`;\nconst notFound = (path: string) => new Error(`ENOENT: no such file or directory, open '${path}'`);\n\nconst apiTarget = (sandbox: Kosa8Sandbox): FileTarget => ({\n url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,\n token: sandbox.apiKey,\n});\n\nfunction errorDetail(res: HttpResponse): string {\n const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString('utf8') : '');\n try {\n const parsed = JSON.parse(text) as { error?: string; message?: string };\n if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(': ');\n } catch {\n // Not JSON: keep the raw text.\n }\n return text.slice(0, 500);\n}\n\n/** The error for a refused file request, with Node's codes for the common ones. */\nfunction fileError(res: HttpResponse, op: 'open' | 'write', path: string): Error {\n const detail = errorDetail(res);\n if (res.status === 404) return notFound(path);\n if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ''}`);\n return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ''}`);\n}\n\n/**\n * A refusal from the older base64 file API (or a host without any): a path outside /workspace,\n * a file over its 8 MiB, or offsets and streams it does not have. Exec reaches those.\n */\nfunction olderFileApi(res: HttpResponse): boolean {\n return res.status === 413 || res.status === 501 || (res.status === 400 && /workspace/i.test(errorDetail(res)));\n}\n\nasync function send(\n t: FileTarget,\n method: 'GET' | 'PUT',\n path: string,\n { body, offset, range }: { body?: Uint8Array; offset?: number; range?: [number, number] } = {},\n): Promise<HttpResponse> {\n const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ''}`;\n const headers: Record<string, string> = { Authorization: `Bearer ${t.token}` };\n if (body) headers['Content-Type'] = 'application/octet-stream';\n if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;\n // Every request here is idempotent (a whole file, a part at its offset, or a read), so one that\n // failed in transit or with a server error is sent again.\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await httpRequest(url, { method, headers, body, binary: true });\n if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;\n } catch (err) {\n if (attempt >= FILE_RETRIES) throw err;\n }\n await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));\n }\n}\n\n/**\n * Runs task over items, at most `limit` at once. After a task fails no more are started, and the\n * first failure is returned (or thrown) once the ones in progress have finished.\n */\nasync function inParallel<T, R>(items: T[], limit: number, task: (item: T) => Promise<R | null>): Promise<R | null> {\n let next = 0;\n let failed: R | null = null;\n let thrown: { err: unknown } | undefined;\n const worker = async () => {\n while (!failed && !thrown && next < items.length) {\n try {\n const r = await task(items[next++]);\n if (r) failed ??= r;\n } catch (err) {\n thrown ??= { err };\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n if (thrown) throw thrown.err;\n return failed;\n}\n\n/** Writes bytes at path through t: null when written, else the refusal. */\nasync function writeTo(t: FileTarget, path: string, bytes: Uint8Array): Promise<HttpResponse | null> {\n // The first part replaces the file (creating its directories); the rest are written at their offsets.\n const first = await send(t, 'PUT', path, { body: bytes.subarray(0, fileParts.bytes) });\n if (!first.ok) return first;\n const offsets: number[] = [];\n for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);\n return inParallel(offsets, fileParts.writeConcurrency, async (at) => {\n const res = await send(t, 'PUT', path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });\n return res.ok ? null : res;\n });\n}\n\n/** Reads path through t: its bytes, or the refusal. */\nasync function readFrom(t: FileTarget, path: string): Promise<Uint8Array | HttpResponse> {\n const first = await send(t, 'GET', path, { range: [0, fileParts.bytes - 1] });\n // 416: the first byte is past the end, so the file is empty.\n if (first.status === 416) return new Uint8Array();\n // 200: the whole file (a server that ignores Range).\n if (first.status === 200) return first.bytes ?? new Uint8Array();\n if (first.status !== 206) return first;\n const head = first.bytes ?? new Uint8Array();\n const total = Number(/\\/(\\d+)\\s*$/.exec(first.headers['content-range'] ?? '')?.[1] ?? head.length);\n if (total <= head.length) return head;\n const starts: number[] = [];\n for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);\n const parts = new Map<number, Uint8Array>();\n const failed = await inParallel(starts, fileParts.concurrency, async (at) => {\n const res = await send(t, 'GET', path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });\n if (res.status !== 206 && res.status !== 200) return res;\n parts.set(at, res.bytes ?? new Uint8Array());\n return null;\n });\n if (failed) return failed;\n const all = Buffer.concat([head, ...starts.map((at) => parts.get(at)!)]);\n if (all.length !== total) {\n throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);\n }\n return all;\n}\n\n// --- write -------------------------------------------------------------------\n\n/**\n * Writes a file: straight to the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function writeFileNative(\n sandbox: Kosa8Sandbox,\n path: string,\n content: string,\n run: ExecRunner,\n direct: FileTarget | null = null,\n): Promise<void> {\n const bytes = Buffer.from(content, 'utf8');\n const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${randomBytes(6).toString('hex')}` : null;\n const dest = staged ?? path;\n const commit = async () => {\n // `[ -d ]` first: `mv` onto an existing directory would move the staged file inside it.\n if (staged) {\n await mustSucceed(\n run,\n sandbox,\n `if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,\n 'write',\n path,\n );\n }\n };\n try {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const res = await writeTo(direct, dest, bytes).catch(() => undefined);\n if (res === null) {\n await commit();\n return;\n }\n if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, 'write', path);\n if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const res = await writeTo(apiTarget(sandbox), dest, bytes);\n if (!res) {\n await commit();\n return;\n }\n if (!olderFileApi(res)) throw fileError(res, 'write', path);\n if (res.status === 501) sandbox.files = false;\n }\n return writeFileViaExec(sandbox, path, bytes, run);\n } finally {\n if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {});\n }\n}\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, what: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n if ((result as { stdoutTruncated?: boolean }).stdoutTruncated) {\n throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);\n }\n return result.stdout;\n}\n\n/**\n * Writes a file through exec (older hosts): base64 chunks into a temporary file beside it, then an\n * atomic rename. One chunk is a single command.\n */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string | Uint8Array, run: ExecRunner): Promise<void> {\n const target = q(path);\n const tmp = q(`${path}.computesdk-${randomBytes(6).toString('hex')}`);\n const encoded = Buffer.from(content).toString('base64');\n const mkParent = `d=$(dirname ${target}) && mkdir -p \"$d\"`;\n if (encoded.length <= WRITE_CHUNK_CHARS) {\n const cmd = `${mkParent} && printf '%s' \"$KOSA8_CHUNK\" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;\n await mustSucceed(run, sandbox, cmd, 'write', path, { KOSA8_CHUNK: encoded });\n return;\n }\n try {\n await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, 'write', path);\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, 'write', path, {\n KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS),\n });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, 'write', path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\n// --- read --------------------------------------------------------------------\n\nconst fromBase64 = (s: string) => Buffer.from(s.replace(/\\s+/g, ''), 'base64');\n\n/**\n * Reads a file: straight from the host when the direct token covers files, else through the API's\n * file stream, else (an older host) over exec.\n */\nexport async function readFileNative(sandbox: Kosa8Sandbox, path: string, run: ExecRunner, direct: FileTarget | null = null): Promise<string> {\n if (direct) {\n // A connection to the host that failed in transit (after retries) leaves the API to try.\n const got = await readFrom(direct, path).catch(() => undefined);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, 'open', path);\n if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;\n }\n if (sandbox.files !== false) {\n const got = await readFrom(apiTarget(sandbox), path);\n if (got instanceof Uint8Array) return Buffer.from(got).toString('utf8');\n if (!olderFileApi(got)) throw fileError(got, 'open', path);\n if (got.status === 501) sandbox.files = false;\n }\n return readFileViaExec(sandbox, path, run);\n}\n\n/** Reads a file through exec (older hosts): inline when small, else 1 MiB per command. */\nasync function readFileViaExec(sandbox: Kosa8Sandbox, path: string, run: ExecRunner): Promise<string> {\n const p = q(path);\n const out = await mustSucceed(\n run,\n sandbox,\n `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo \"$s\"; if [ \"$s\" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,\n 'open',\n path,\n );\n const nl = out.indexOf('\\n');\n const size = Number(out.slice(0, nl < 0 ? undefined : nl).trim());\n if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);\n if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? '' : out.slice(nl + 1)).toString('utf8');\n const chunks: Buffer[] = new Array(Math.ceil(size / INLINE_READ_BYTES));\n let next = 0;\n const worker = async () => {\n while (next < chunks.length) {\n const i = next++;\n chunks[i] = fromBase64(\n await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, 'open', path),\n );\n }\n };\n await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));\n const all = Buffer.concat(chunks);\n if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);\n return all.toString('utf8');\n}\n"],"mappings":";AAeA,SAAS,gBAAgB,kBAAAA,iBAAgB,uBAAuB;;;ACwBhE,IAAM,cAAwC,OAAO,UAAU,aAAa,QAAQ;AAEpF,IAAI;AACJ,SAAS,YAAmC;AAC1C,4BAAc,OAAO,OAAY,EAAE;AAAA,IACjC,CAAC,MAAQ,EAAqC,WAAW;AAAA,IACzD,MAAM;AAAA,EACR;AACA,SAAO;AACT;AAQA,IAAM,UAAU,oBAAI,IAAoB;AAOxC,IAAM,WAAW,oBAAI,QA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