@computesdk/kosa8 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +11 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -61,9 +61,9 @@ interface Kosa8Config {
|
|
|
61
61
|
apiKey?: string;
|
|
62
62
|
/** API base URL - defaults to KOSA8_API_URL, then https://api.kosa8.com */
|
|
63
63
|
baseUrl?: string;
|
|
64
|
-
/** Default template for new sandboxes
|
|
64
|
+
/** Default template for new sandboxes - defaults to KOSA8_TEMPLATE, then the organization's default (`base`, no Node) */
|
|
65
65
|
template?: string;
|
|
66
|
-
/** Default region for new sandboxes, e.g. `eu-hel1`
|
|
66
|
+
/** Default region for new sandboxes, e.g. `eu-hel1` - defaults to KOSA8_REGION, then any region */
|
|
67
67
|
region?: string;
|
|
68
68
|
}
|
|
69
69
|
```
|
|
@@ -99,3 +99,13 @@ interface Kosa8Config {
|
|
|
99
99
|
|
|
100
100
|
- [kosa8](https://kosa8.com)
|
|
101
101
|
- [Cloud dashboard](https://app.kosa8.com)
|
|
102
|
+
|
|
103
|
+
## Logos
|
|
104
|
+
|
|
105
|
+
SVG logos for results pages and docs are in [`assets/`](./assets):
|
|
106
|
+
|
|
107
|
+
| File | Use |
|
|
108
|
+
|---|---|
|
|
109
|
+
| `kosa8-logo-light.svg` | Mark and wordmark, for light backgrounds |
|
|
110
|
+
| `kosa8-logo-dark.svg` | Mark and wordmark, for dark backgrounds |
|
|
111
|
+
| `kosa8-mark.svg` | Square mark alone (icons, tables) |
|
package/dist/index.d.mts
CHANGED
|
@@ -7,9 +7,9 @@ interface Kosa8Config {
|
|
|
7
7
|
apiKey?: string;
|
|
8
8
|
/** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
|
|
9
9
|
baseUrl?: string;
|
|
10
|
-
/** Default template for new sandboxes
|
|
10
|
+
/** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */
|
|
11
11
|
template?: string;
|
|
12
|
-
/** Default region for new sandboxes, e.g. `eu-hel1`
|
|
12
|
+
/** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */
|
|
13
13
|
region?: string;
|
|
14
14
|
}
|
|
15
15
|
/** A sandbox as the kosa8 Cloud API returns it. */
|
package/dist/index.d.ts
CHANGED
|
@@ -7,9 +7,9 @@ interface Kosa8Config {
|
|
|
7
7
|
apiKey?: string;
|
|
8
8
|
/** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
|
|
9
9
|
baseUrl?: string;
|
|
10
|
-
/** Default template for new sandboxes
|
|
10
|
+
/** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */
|
|
11
11
|
template?: string;
|
|
12
|
-
/** Default region for new sandboxes, e.g. `eu-hel1`
|
|
12
|
+
/** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */
|
|
13
13
|
region?: string;
|
|
14
14
|
}
|
|
15
15
|
/** A sandbox as the kosa8 Cloud API returns it. */
|
package/dist/index.js
CHANGED
|
@@ -36,6 +36,7 @@ var import_provider = require("@computesdk/provider");
|
|
|
36
36
|
var MIN_TTL_S = 60;
|
|
37
37
|
var MAX_TTL_S = 90 * 86400;
|
|
38
38
|
var TIMEOUT_EXIT = 124;
|
|
39
|
+
var DONE_ENV = "KOSA8_DONE";
|
|
39
40
|
var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
40
41
|
var UNSUPPORTED_CREATE_OPTIONS = [
|
|
41
42
|
"cpu",
|
|
@@ -100,9 +101,10 @@ function createBody(config, options = {}) {
|
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
103
|
const body = {};
|
|
103
|
-
const
|
|
104
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
105
|
+
const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
|
|
104
106
|
if (template) body.template = template;
|
|
105
|
-
const region = typeof options.region === "string" ? options.region : config.region;
|
|
107
|
+
const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
|
|
106
108
|
if (region) body.region = region;
|
|
107
109
|
if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
|
|
108
110
|
if (typeof options.timeout === "number" && options.timeout > 0) {
|
|
@@ -117,18 +119,21 @@ function execArgv(command, options) {
|
|
|
117
119
|
cmd = `nohup sh -c "${(0, import_provider.escapeShellArg)(cmd)}" >/dev/null 2>&1 &`;
|
|
118
120
|
} else if (options?.timeout && options.timeout > 0) {
|
|
119
121
|
const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
+
const plain = `sh -c "${(0, import_provider.escapeShellArg)(cmd)}"`;
|
|
123
|
+
const marked = `sh -c "${(0, import_provider.escapeShellArg)(`(
|
|
124
|
+
${cmd}
|
|
125
|
+
); s=$?; : > "$${DONE_ENV}"; exit $s`)}"`;
|
|
126
|
+
cmd = `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then rm -f "$${DONE_ENV}"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; if [ $s -eq 137 ] && [ ! -e "$${DONE_ENV}" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; rm -f "$${DONE_ENV}"; exit $s; else ${plain}; fi`;
|
|
122
127
|
}
|
|
123
128
|
return ["sh", "-c", cmd];
|
|
124
129
|
}
|
|
125
|
-
var
|
|
130
|
+
var MAX_ARG_BYTES = 8192;
|
|
126
131
|
var MAX_EXEC_BODY_BYTES = 64 * 1024;
|
|
127
132
|
var SCRIPT_ENV = "KOSA8_SCRIPT";
|
|
128
133
|
function execBody(command, options) {
|
|
129
134
|
const argv = execArgv(command, options);
|
|
130
135
|
const env = execEnv(options?.env);
|
|
131
|
-
const body = argv[2]
|
|
136
|
+
const body = Buffer.byteLength(argv[2], "utf8") <= MAX_ARG_BYTES ? { cmd: argv, env } : { cmd: ["sh", "-c", `eval "$${SCRIPT_ENV}"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };
|
|
132
137
|
const size = Buffer.byteLength(JSON.stringify(body), "utf8");
|
|
133
138
|
if (size > MAX_EXEC_BODY_BYTES) {
|
|
134
139
|
throw new Error(
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.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. File operations run as shell commands over\n * that exec (ComputeSDK's shell filesystem; no native file API is used here), and `pause()`/`resume()` map\n * to kosa8's sleep and wake, which snapshot the VM's memory and disk and restore it.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\n\nimport type { CommandResult, CreateInstanceOptions, InstanceInfo, RunCommandOptions } 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 (the org's default, `base`, when unset) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` (any region when unset) */\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\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\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}\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\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template fixes the size and image. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'image', 'snapshotId', 'envs', 'volumes',\n] as const;\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 fetch(`${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 = await 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): Kosa8Sandbox {\n return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\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()).`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const template = options.templateId ?? config.template;\n if (template) body.template = template;\n const region = typeof options.region === 'string' ? options.region : config.region;\n if (region) body.region = region;\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 const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const inner = `sh -c \"${escapeShellArg(cmd)}\"`;\n cmd = `if command -v timeout >/dev/null 2>&1; then timeout -s KILL ${seconds} ${inner}; s=$?; [ $s -eq 137 ] && exit ${TIMEOUT_EXIT}; exit $s; else ${inner}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/** The exec API's limit on each argv entry. */\nconst MAX_ARG_CHARS = 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 = argv[2].length <= MAX_ARG_CHARS\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 if (state === 'running') return 'running';\n // creating, sleeping, paused, stopped and deleted: not running now, so a readiness check keeps waiting.\n // A sleeping sandbox wakes on its next command.\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\ntype ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/**\n * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small\n * for the shell filesystem's inline chunks, so file content travels in an environment variable,\n * which counts only toward the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 32 * 1024;\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n}\n\n/** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void> {\n const target = `\"${escapeShellArg(path)}\"`;\n const tmp = `\"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString('hex')}`)}\"`;\n const encoded = Buffer.from(content, 'utf8').toString('base64');\n const chunks: string[] = [];\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));\n try {\n await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p \"$d\" && : > ${tmp}`, path);\n for (const chunk of chunks) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nexport const kosa8 = 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 }>(\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 return { instance: toSandbox(auth, data.sandbox), instanceId: data.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<CommandResult> => {\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 request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal);\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n return {\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 },\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 // Shell commands over exec. kosa8's own file API needs a host capability that is not on\n // every host yet, so it is not used here.\n filesystem: {\n readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),\n writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),\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 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\nexport default kosa8;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,SAAS,IAAI;AAAA,QACrE,WAAW,CAAC,SAAS,MAAM,SAAS,QAAQ,iBAAiB,SAAS,MAAM,SAAS,GAAG;AAAA,QACxF,OAAO,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,MAAM,IAAI;AAAA,QAC/D,SAAS,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,QAAQ,IAAI;AAAA,QACnE,QAAQ,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,OAAO,IAAI;AAAA,QACjE,QAAQ,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,OAAO,IAAI;AAAA,MACnE;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;AAED,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.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. File operations run as shell commands over\n * that exec (ComputeSDK's shell filesystem; no native file API is used here), and `pause()`/`resume()` map\n * to kosa8's sleep and wake, which snapshot the VM's memory and disk and restore it.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\n\nimport type { CommandResult, CreateInstanceOptions, InstanceInfo, RunCommandOptions } 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\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\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}\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 fixes the size and image. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'image', 'snapshotId', 'envs', 'volumes',\n] as const;\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 fetch(`${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 = await 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): Kosa8Sandbox {\n return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\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()).`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\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 if (state === 'running') return 'running';\n // creating, sleeping, paused, stopped and deleted: not running now, so a readiness check keeps waiting.\n // A sleeping sandbox wakes on its next command.\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\ntype ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/**\n * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small\n * for the shell filesystem's inline chunks, so file content travels in an environment variable,\n * which counts only toward the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 32 * 1024;\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n}\n\n/** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void> {\n const target = `\"${escapeShellArg(path)}\"`;\n const tmp = `\"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString('hex')}`)}\"`;\n const encoded = Buffer.from(content, 'utf8').toString('base64');\n const chunks: string[] = [];\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));\n try {\n await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p \"$d\" && : > ${tmp}`, path);\n for (const chunk of chunks) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nexport const kosa8 = 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 }>(\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 return { instance: toSandbox(auth, data.sandbox), instanceId: data.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<CommandResult> => {\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 request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal);\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n return {\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 },\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 // Shell commands over exec. kosa8's own file API needs a host capability that is not on\n // every host yet, so it is not used here.\n filesystem: {\n readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),\n writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),\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 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\nexport default kosa8;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,yBAA4B;AAC5B,sBAAgE;AA4DhE,IAAM,YAAY;AAClB,IAAM,YAAY,KAAK;AAGvB,IAAM,eAAe;AAGrB,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= 124;
|
|
7
|
+
var DONE_ENV = "KOSA8_DONE";
|
|
7
8
|
var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
8
9
|
var UNSUPPORTED_CREATE_OPTIONS = [
|
|
9
10
|
"cpu",
|
|
@@ -68,9 +69,10 @@ function createBody(config, options = {}) {
|
|
|
68
69
|
}
|
|
69
70
|
}
|
|
70
71
|
const body = {};
|
|
71
|
-
const
|
|
72
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
73
|
+
const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
|
|
72
74
|
if (template) body.template = template;
|
|
73
|
-
const region = typeof options.region === "string" ? options.region : config.region;
|
|
75
|
+
const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
|
|
74
76
|
if (region) body.region = region;
|
|
75
77
|
if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
|
|
76
78
|
if (typeof options.timeout === "number" && options.timeout > 0) {
|
|
@@ -85,18 +87,21 @@ function execArgv(command, options) {
|
|
|
85
87
|
cmd = `nohup sh -c "${escapeShellArg(cmd)}" >/dev/null 2>&1 &`;
|
|
86
88
|
} else if (options?.timeout && options.timeout > 0) {
|
|
87
89
|
const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
+
const plain = `sh -c "${escapeShellArg(cmd)}"`;
|
|
91
|
+
const marked = `sh -c "${escapeShellArg(`(
|
|
92
|
+
${cmd}
|
|
93
|
+
); s=$?; : > "$${DONE_ENV}"; exit $s`)}"`;
|
|
94
|
+
cmd = `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then rm -f "$${DONE_ENV}"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; if [ $s -eq 137 ] && [ ! -e "$${DONE_ENV}" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; rm -f "$${DONE_ENV}"; exit $s; else ${plain}; fi`;
|
|
90
95
|
}
|
|
91
96
|
return ["sh", "-c", cmd];
|
|
92
97
|
}
|
|
93
|
-
var
|
|
98
|
+
var MAX_ARG_BYTES = 8192;
|
|
94
99
|
var MAX_EXEC_BODY_BYTES = 64 * 1024;
|
|
95
100
|
var SCRIPT_ENV = "KOSA8_SCRIPT";
|
|
96
101
|
function execBody(command, options) {
|
|
97
102
|
const argv = execArgv(command, options);
|
|
98
103
|
const env = execEnv(options?.env);
|
|
99
|
-
const body = argv[2]
|
|
104
|
+
const body = Buffer.byteLength(argv[2], "utf8") <= MAX_ARG_BYTES ? { cmd: argv, env } : { cmd: ["sh", "-c", `eval "$${SCRIPT_ENV}"`], env: [...env, `${SCRIPT_ENV}=${argv[2]}`] };
|
|
100
105
|
const size = Buffer.byteLength(JSON.stringify(body), "utf8");
|
|
101
106
|
if (size > MAX_EXEC_BODY_BYTES) {
|
|
102
107
|
throw new Error(
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.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. File operations run as shell commands over\n * that exec (ComputeSDK's shell filesystem; no native file API is used here), and `pause()`/`resume()` map\n * to kosa8's sleep and wake, which snapshot the VM's memory and disk and restore it.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\n\nimport type { CommandResult, CreateInstanceOptions, InstanceInfo, RunCommandOptions } 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 (the org's default, `base`, when unset) */\n template?: string;\n /** Default region for new sandboxes, e.g. `eu-hel1` (any region when unset) */\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\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\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}\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\nconst ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Create options that kosa8 cannot honour: a template fixes the size and image. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'image', 'snapshotId', 'envs', 'volumes',\n] as const;\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 fetch(`${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 = await 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): Kosa8Sandbox {\n return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\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()).`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const template = options.templateId ?? config.template;\n if (template) body.template = template;\n const region = typeof options.region === 'string' ? options.region : config.region;\n if (region) body.region = region;\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 const seconds = Math.max(1, Math.ceil(options.timeout / 1000));\n const inner = `sh -c \"${escapeShellArg(cmd)}\"`;\n cmd = `if command -v timeout >/dev/null 2>&1; then timeout -s KILL ${seconds} ${inner}; s=$?; [ $s -eq 137 ] && exit ${TIMEOUT_EXIT}; exit $s; else ${inner}; fi`;\n }\n return ['sh', '-c', cmd];\n}\n\n/** The exec API's limit on each argv entry. */\nconst MAX_ARG_CHARS = 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 = argv[2].length <= MAX_ARG_CHARS\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 if (state === 'running') return 'running';\n // creating, sleeping, paused, stopped and deleted: not running now, so a readiness check keeps waiting.\n // A sleeping sandbox wakes on its next command.\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\ntype ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/**\n * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small\n * for the shell filesystem's inline chunks, so file content travels in an environment variable,\n * which counts only toward the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 32 * 1024;\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n}\n\n/** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void> {\n const target = `\"${escapeShellArg(path)}\"`;\n const tmp = `\"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString('hex')}`)}\"`;\n const encoded = Buffer.from(content, 'utf8').toString('base64');\n const chunks: string[] = [];\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));\n try {\n await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p \"$d\" && : > ${tmp}`, path);\n for (const chunk of chunks) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nexport const kosa8 = 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 }>(\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 return { instance: toSandbox(auth, data.sandbox), instanceId: data.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<CommandResult> => {\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 request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal);\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n return {\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 },\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 // Shell commands over exec. kosa8's own file API needs a host capability that is not on\n // every host yet, so it is not used here.\n filesystem: {\n readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),\n writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),\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 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\nexport default kosa8;\n"],"mappings":";AAYA,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,gBAAgB,uBAAuB;AA4DhE,IAAM,YAAY;AAClB,IAAM,YAAY,KAAK;AAGvB,IAAM,eAAe;AAErB,IAAM,WAAW;AAGjB,IAAM,6BAA6B;AAAA,EACjC;AAAA,EAAO;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAY;AAAA,EAAU;AAAA,EAAa;AAAA,EAAU;AAAA,EAAY;AAAA,EAAU;AAAA,EAC3F;AAAA,EAAS;AAAA,EAAc;AAAA,EAAQ;AACjC;AAEA,SAAS,cAAc,QAA2B;AAChD,QAAM,MAAM,OAAO,YAAY,cAAc,QAAQ,MAAM;AAC3D,QAAM,SAAS,OAAO,UAAU,KAAK,iBAAiB;AACtD,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,QAAM,WAAW,OAAO,WAAW,KAAK,iBAAiB,yBAAyB,QAAQ,QAAQ,EAAE;AACpG,SAAO,EAAE,QAAQ,QAAQ;AAC3B;AAEA,eAAe,QACb,MACA,QACA,MACA,MACA,QACmB;AACnB,QAAM,MAAM,MAAM,MAAM,GAAG,KAAK,OAAO,GAAG,IAAI,IAAI;AAAA,IAChD;AAAA,IACA,SAAS;AAAA,MACP,eAAe,UAAU,KAAK,MAAM;AAAA,MACpC,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,gBAAgB,mBAAmB;AAAA,IACrE;AAAA,IACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAAA,IAC1D;AAAA,EACF,CAAC;AACD,MAAI,IAAI,WAAW,IAAK,QAAO;AAC/B,QAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,MAAI,CAAC,IAAI,IAAI;AACX,QAAI,SAAS;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AAQ,EAAE,YAAY;AAClE,YAAI,KAAK,QAAS,SAAQ,OAAO,KAAK;AAAA,MACxC;AAAA,MAEA,aAAa,CAAC,YAAwC;AAAA;AAAA;AAAA,MAItD,YAAY;AAAA,QACV,UAAU,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,SAAS,IAAI;AAAA,QACrE,WAAW,CAAC,SAAS,MAAM,SAAS,QAAQ,iBAAiB,SAAS,MAAM,SAAS,GAAG;AAAA,QACxF,OAAO,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,MAAM,IAAI;AAAA,QAC/D,SAAS,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,QAAQ,IAAI;AAAA,QACnE,QAAQ,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,OAAO,IAAI;AAAA,QACjE,QAAQ,CAAC,SAAS,MAAM,QAAQ,QAAQ,SAAS,GAAG,EAAE,OAAO,IAAI;AAAA,MACnE;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;AAED,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.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. File operations run as shell commands over\n * that exec (ComputeSDK's shell filesystem; no native file API is used here), and `pause()`/`resume()` map\n * to kosa8's sleep and wake, which snapshot the VM's memory and disk and restore it.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport { defineProvider, escapeShellArg, ShellFileSystem } from '@computesdk/provider';\n\nimport type { CommandResult, CreateInstanceOptions, InstanceInfo, RunCommandOptions } 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\nexport interface Kosa8Sandbox {\n id: string;\n data: Kosa8SandboxData;\n apiKey: string;\n baseUrl: string;\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}\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 fixes the size and image. */\nconst UNSUPPORTED_CREATE_OPTIONS = [\n 'cpu', 'cpus', 'vcpus', 'cpuLimit', 'memory', 'memoryMiB', 'memMiB', 'memoryMb', 'diskMb', 'diskMiB',\n 'image', 'snapshotId', 'envs', 'volumes',\n] as const;\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 fetch(`${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 = await 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): Kosa8Sandbox {\n return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };\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()).`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n const env = typeof process !== 'undefined' ? process.env : undefined;\n const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || undefined);\n if (template) body.template = template;\n const region = typeof options.region === 'string' ? options.region : (config.region ?? (env?.KOSA8_REGION || undefined));\n if (region) body.region = region;\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 if (state === 'running') return 'running';\n // creating, sleeping, paused, stopped and deleted: not running now, so a readiness check keeps waiting.\n // A sleeping sandbox wakes on its next command.\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\ntype ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;\n\n/**\n * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small\n * for the shell filesystem's inline chunks, so file content travels in an environment variable,\n * which counts only toward the 64 KiB request body.\n */\nexport const WRITE_CHUNK_CHARS = 32 * 1024;\n\nconst shellFs = (sandbox: Kosa8Sandbox, run: ExecRunner) =>\n new ShellFileSystem((command, options) => run(sandbox, command, options));\n\nasync function mustSucceed(run: ExecRunner, sandbox: Kosa8Sandbox, command: string, path: string, env?: Record<string, string>) {\n const result = await run(sandbox, command, env ? { env } : undefined);\n if (result.exitCode !== 0) {\n const detail = (result.stderr || result.stdout).trim();\n throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ''}`);\n }\n}\n\n/** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */\nexport async function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void> {\n const target = `\"${escapeShellArg(path)}\"`;\n const tmp = `\"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString('hex')}`)}\"`;\n const encoded = Buffer.from(content, 'utf8').toString('base64');\n const chunks: string[] = [];\n for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));\n try {\n await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p \"$d\" && : > ${tmp}`, path);\n for (const chunk of chunks) {\n await mustSucceed(run, sandbox, `printf '%s' \"$KOSA8_CHUNK\" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });\n }\n await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);\n } catch (err) {\n await run(sandbox, `rm -f ${tmp}`).catch(() => {});\n throw err;\n }\n}\n\nconst notAvailable = (what: string) =>\n new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);\n\nexport const kosa8 = 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 }>(\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 return { instance: toSandbox(auth, data.sandbox), instanceId: data.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<CommandResult> => {\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 request<ExecResponse>(sandbox, 'POST', sandboxPath(sandbox.id, '/exec'), body, signal);\n if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);\n return {\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 },\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 // Shell commands over exec. kosa8's own file API needs a host capability that is not on\n // every host yet, so it is not used here.\n filesystem: {\n readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),\n writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),\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 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\nexport default kosa8;\n"],"mappings":";AAYA,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,gBAAgB,u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