@computesdk/kosa8 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 computesdk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # @computesdk/kosa8
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [kosa8](https://kosa8.com) provider for ComputeSDK - cloud sandboxes where each sandbox runs in its own microVM with its own kernel, billed per second, with sleep and wake.
4
+
5
+ ## Installation & Setup
6
+
7
+ ```bash
8
+ npm install @computesdk/kosa8
9
+ ```
10
+
11
+ Create an API key in the kosa8 Cloud dashboard at [app.kosa8.com](https://app.kosa8.com), then add it to a `.env` file:
12
+
13
+ ```bash
14
+ KOSA8_API_KEY=your_kosa8_api_key
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```typescript
20
+ import { compute } from 'computesdk';
21
+ import { kosa8 } from '@computesdk/kosa8';
22
+
23
+ compute.setConfig({
24
+ provider: kosa8({ apiKey: process.env.KOSA8_API_KEY }),
25
+ });
26
+
27
+ const sandbox = await compute.instances.create();
28
+
29
+ const result = await sandbox.runCommand('uname -r && echo "Hello from kosa8!"');
30
+ console.log(result.stdout);
31
+
32
+ await sandbox.destroy();
33
+ ```
34
+
35
+ Or call the provider factory directly:
36
+
37
+ ```typescript
38
+ import { kosa8 } from '@computesdk/kosa8';
39
+
40
+ const sdk = kosa8({ apiKey: process.env.KOSA8_API_KEY });
41
+
42
+ // See which templates your organization can start
43
+ console.log(await sdk.template.list());
44
+
45
+ const sandbox = await sdk.sandbox.create({ templateId: 'base', timeout: 30 * 60 * 1000 });
46
+ await sandbox.filesystem.writeFile('/tmp/hello.sh', 'echo $((6 * 7))');
47
+ console.log((await sandbox.runCommand('sh /tmp/hello.sh')).stdout); // "42\n"
48
+
49
+ // Sleep: the VM's memory and disk are snapshotted and its RAM freed. Wake restores it.
50
+ await sandbox.pause();
51
+ await sandbox.resume();
52
+
53
+ await sandbox.destroy();
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ ```typescript
59
+ interface Kosa8Config {
60
+ /** kosa8 Cloud API key - if not provided, will use KOSA8_API_KEY env var */
61
+ apiKey?: string;
62
+ /** API base URL - defaults to KOSA8_API_URL, then https://api.kosa8.com */
63
+ baseUrl?: string;
64
+ /** Default template for new sandboxes - defaults to KOSA8_TEMPLATE, then the organization's default (`base`, no Node) */
65
+ template?: string;
66
+ /** Default region for new sandboxes, e.g. `eu-hel1` - defaults to KOSA8_REGION, then any region */
67
+ region?: string;
68
+ }
69
+ ```
70
+
71
+ ## Create Options
72
+
73
+ | Option | Maps to | Notes |
74
+ |---|---|---|
75
+ | `templateId` | `template` | A template key from `template.list()`. The template sets the sandbox's vCPUs, memory and image. |
76
+ | `region` | `region` | A region id such as `eu-hel1`. |
77
+ | `timeout` (ms) | `ttl_s` | The sandbox is deleted when its lifetime ends. Rounded up to whole seconds; the API's minimum is 60 s and maximum 90 days. Without it, a sandbox lives until destroyed. |
78
+ | `sleepAfterSeconds` | `sleep_after_s` | Idle seconds before the sandbox sleeps; `0` never sleeps. |
79
+
80
+ `cpu`, `memory`, disk sizes, `image`, `snapshotId`, `envs` and `volumes` are rejected with an error rather than ignored: a sandbox's size and image come from its template. Pass environment variables per command with `runCommand(cmd, { env })`.
81
+
82
+ ## Features
83
+
84
+ - **Command execution** with `cwd`, `env`, `timeout` and background commands
85
+ - **Filesystem**: read, write, list, mkdir, exists and remove, run as shell commands over exec
86
+ - **Pause and resume**: `pause()` puts the sandbox to sleep (memory and disk are snapshotted, its RAM is freed) and `resume()` wakes it. A command sent to a sleeping sandbox also wakes it.
87
+ - **Lifetime**: `extendLifetime(ms)` moves the delete time of a sandbox created with `timeout`
88
+ - **Templates**: `template.list()` returns the templates your organization can start, with their size and regions
89
+
90
+ ## Limitations
91
+
92
+ - `getUrl()` (port URLs) is not supported yet and throws.
93
+ - Output is returned when the command finishes; there is no live streaming.
94
+ - `runCommand`'s `timeout` stops the command inside the sandbox with `timeout -s KILL` and reports exit code 124. On an image without the `timeout` utility, the command runs to completion.
95
+ - Templates are offered by kosa8's hosts, so `template.create()` and `template.delete()` throw. Snapshots and forking are not exposed through this provider.
96
+ - Sandboxes created without `timeout` live until destroyed, so always call `destroy()` when you are done.
97
+
98
+ ## Links
99
+
100
+ - [kosa8](https://kosa8.com)
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) |
@@ -0,0 +1,74 @@
1
+ import * as computesdk from 'computesdk';
2
+ import * as _computesdk_provider from '@computesdk/provider';
3
+ import { CreateInstanceOptions, RunCommandOptions, CommandResult } from '@computesdk/provider';
4
+
5
+ interface Kosa8Config {
6
+ /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */
7
+ apiKey?: string;
8
+ /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
9
+ baseUrl?: string;
10
+ /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */
11
+ template?: string;
12
+ /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */
13
+ region?: string;
14
+ }
15
+ /** A sandbox as the kosa8 Cloud API returns it. */
16
+ interface Kosa8SandboxData {
17
+ id: string;
18
+ state: string;
19
+ template: string;
20
+ cpus: number;
21
+ mem_mb: number;
22
+ region: string | null;
23
+ created_at: number;
24
+ started_at: number | null;
25
+ sleep_after_s: number | null;
26
+ delete_after: number | null;
27
+ last_error: string | null;
28
+ [key: string]: unknown;
29
+ }
30
+ /** A template as GET /v1/templates returns it. */
31
+ interface Kosa8Template {
32
+ key: string;
33
+ cpus: number;
34
+ mem_mb: number;
35
+ image?: string;
36
+ regions: string[];
37
+ [key: string]: unknown;
38
+ }
39
+ interface Kosa8Sandbox {
40
+ id: string;
41
+ data: Kosa8SandboxData;
42
+ apiKey: string;
43
+ baseUrl: string;
44
+ }
45
+ /** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */
46
+ declare function createBody(config: Kosa8Config, options?: CreateInstanceOptions): Record<string, unknown>;
47
+ /** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */
48
+ declare function execArgv(command: string, options?: RunCommandOptions): string[];
49
+ /** The exec API's limit on the whole request body, in bytes. */
50
+ declare const MAX_EXEC_BODY_BYTES: number;
51
+ /** Environment variable that carries a script too long for one argv entry; callers may not set it. */
52
+ declare const SCRIPT_ENV = "KOSA8_SCRIPT";
53
+ /**
54
+ * The exec request body: a script too long for one argv entry travels in an environment variable.
55
+ * Throws before any request is made when the serialized body would exceed the exec API's limit.
56
+ */
57
+ declare function execBody(command: string, options?: RunCommandOptions): {
58
+ cmd: string[];
59
+ env: string[];
60
+ };
61
+ type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;
62
+ /**
63
+ * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small
64
+ * for the shell filesystem's inline chunks, so file content travels in an environment variable,
65
+ * which counts only toward the 64 KiB request body.
66
+ */
67
+ declare const WRITE_CHUNK_CHARS: number;
68
+ /** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */
69
+ declare function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void>;
70
+ declare const kosa8: (config: Kosa8Config & _computesdk_provider.ProcessRuntimeOptions) => _computesdk_provider.Provider<Kosa8Sandbox, any, any, computesdk.Volume> & {
71
+ readonly sizes: computesdk.InstanceSizeManager;
72
+ };
73
+
74
+ export { type Kosa8Config, type Kosa8Sandbox, type Kosa8SandboxData, type Kosa8Template, MAX_EXEC_BODY_BYTES, SCRIPT_ENV, WRITE_CHUNK_CHARS, createBody, kosa8 as default, execArgv, execBody, kosa8, writeFileViaExec };
@@ -0,0 +1,74 @@
1
+ import * as computesdk from 'computesdk';
2
+ import * as _computesdk_provider from '@computesdk/provider';
3
+ import { CreateInstanceOptions, RunCommandOptions, CommandResult } from '@computesdk/provider';
4
+
5
+ interface Kosa8Config {
6
+ /** kosa8 Cloud API key - if not provided, will fallback to KOSA8_API_KEY environment variable */
7
+ apiKey?: string;
8
+ /** API base URL - if not provided, will fallback to KOSA8_API_URL, then https://api.kosa8.com */
9
+ baseUrl?: string;
10
+ /** Default template for new sandboxes - falls back to KOSA8_TEMPLATE, then the org's default (`base`) */
11
+ template?: string;
12
+ /** Default region for new sandboxes, e.g. `eu-hel1` - falls back to KOSA8_REGION, then any region */
13
+ region?: string;
14
+ }
15
+ /** A sandbox as the kosa8 Cloud API returns it. */
16
+ interface Kosa8SandboxData {
17
+ id: string;
18
+ state: string;
19
+ template: string;
20
+ cpus: number;
21
+ mem_mb: number;
22
+ region: string | null;
23
+ created_at: number;
24
+ started_at: number | null;
25
+ sleep_after_s: number | null;
26
+ delete_after: number | null;
27
+ last_error: string | null;
28
+ [key: string]: unknown;
29
+ }
30
+ /** A template as GET /v1/templates returns it. */
31
+ interface Kosa8Template {
32
+ key: string;
33
+ cpus: number;
34
+ mem_mb: number;
35
+ image?: string;
36
+ regions: string[];
37
+ [key: string]: unknown;
38
+ }
39
+ interface Kosa8Sandbox {
40
+ id: string;
41
+ data: Kosa8SandboxData;
42
+ apiKey: string;
43
+ baseUrl: string;
44
+ }
45
+ /** Maps ComputeSDK's create options onto the body of POST /v1/sandboxes. */
46
+ declare function createBody(config: Kosa8Config, options?: CreateInstanceOptions): Record<string, unknown>;
47
+ /** Builds the argv for POST /v1/sandboxes/{id}/exec from a shell command string. */
48
+ declare function execArgv(command: string, options?: RunCommandOptions): string[];
49
+ /** The exec API's limit on the whole request body, in bytes. */
50
+ declare const MAX_EXEC_BODY_BYTES: number;
51
+ /** Environment variable that carries a script too long for one argv entry; callers may not set it. */
52
+ declare const SCRIPT_ENV = "KOSA8_SCRIPT";
53
+ /**
54
+ * The exec request body: a script too long for one argv entry travels in an environment variable.
55
+ * Throws before any request is made when the serialized body would exceed the exec API's limit.
56
+ */
57
+ declare function execBody(command: string, options?: RunCommandOptions): {
58
+ cmd: string[];
59
+ env: string[];
60
+ };
61
+ type ExecRunner = (sandbox: Kosa8Sandbox, command: string, options?: RunCommandOptions) => Promise<CommandResult>;
62
+ /**
63
+ * Base64 characters per write. The exec API caps each argv entry at 8192 characters, too small
64
+ * for the shell filesystem's inline chunks, so file content travels in an environment variable,
65
+ * which counts only toward the 64 KiB request body.
66
+ */
67
+ declare const WRITE_CHUNK_CHARS: number;
68
+ /** Writes a file through exec: base64 chunks into a temporary file beside it, then an atomic rename. */
69
+ declare function writeFileViaExec(sandbox: Kosa8Sandbox, path: string, content: string, run: ExecRunner): Promise<void>;
70
+ declare const kosa8: (config: Kosa8Config & _computesdk_provider.ProcessRuntimeOptions) => _computesdk_provider.Provider<Kosa8Sandbox, any, any, computesdk.Volume> & {
71
+ readonly sizes: computesdk.InstanceSizeManager;
72
+ };
73
+
74
+ export { type Kosa8Config, type Kosa8Sandbox, type Kosa8SandboxData, type Kosa8Template, MAX_EXEC_BODY_BYTES, SCRIPT_ENV, WRITE_CHUNK_CHARS, createBody, kosa8 as default, execArgv, execBody, kosa8, writeFileViaExec };
package/dist/index.js ADDED
@@ -0,0 +1,325 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MAX_EXEC_BODY_BYTES: () => MAX_EXEC_BODY_BYTES,
24
+ SCRIPT_ENV: () => SCRIPT_ENV,
25
+ WRITE_CHUNK_CHARS: () => WRITE_CHUNK_CHARS,
26
+ createBody: () => createBody,
27
+ default: () => index_default,
28
+ execArgv: () => execArgv,
29
+ execBody: () => execBody,
30
+ kosa8: () => kosa8,
31
+ writeFileViaExec: () => writeFileViaExec
32
+ });
33
+ module.exports = __toCommonJS(index_exports);
34
+ var import_node_crypto = require("crypto");
35
+ var import_provider = require("@computesdk/provider");
36
+ var MIN_TTL_S = 60;
37
+ var MAX_TTL_S = 90 * 86400;
38
+ var TIMEOUT_EXIT = 124;
39
+ var DONE_ENV = "KOSA8_DONE";
40
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
41
+ var UNSUPPORTED_CREATE_OPTIONS = [
42
+ "cpu",
43
+ "cpus",
44
+ "vcpus",
45
+ "cpuLimit",
46
+ "memory",
47
+ "memoryMiB",
48
+ "memMiB",
49
+ "memoryMb",
50
+ "diskMb",
51
+ "diskMiB",
52
+ "image",
53
+ "snapshotId",
54
+ "envs",
55
+ "volumes"
56
+ ];
57
+ function resolveConfig(config) {
58
+ const env = typeof process !== "undefined" ? process.env : void 0;
59
+ const apiKey = config.apiKey || env?.KOSA8_API_KEY || "";
60
+ if (!apiKey) {
61
+ throw new Error(
62
+ `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`
63
+ );
64
+ }
65
+ const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || "https://api.kosa8.com").replace(/\/+$/, "");
66
+ return { apiKey, baseUrl };
67
+ }
68
+ async function request(auth, method, path, body, signal) {
69
+ const res = await fetch(`${auth.baseUrl}${path}`, {
70
+ method,
71
+ headers: {
72
+ Authorization: `Bearer ${auth.apiKey}`,
73
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
74
+ },
75
+ body: body === void 0 ? void 0 : JSON.stringify(body),
76
+ signal
77
+ });
78
+ if (res.status === 404) return null;
79
+ const text = await res.text();
80
+ if (!res.ok) {
81
+ let detail = text;
82
+ try {
83
+ const parsed = JSON.parse(text);
84
+ if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(": ");
85
+ } catch {
86
+ }
87
+ throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);
88
+ }
89
+ return text ? JSON.parse(text) : null;
90
+ }
91
+ var sandboxPath = (id, rest = "") => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;
92
+ function toSandbox(auth, data) {
93
+ return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };
94
+ }
95
+ function createBody(config, options = {}) {
96
+ for (const key of UNSUPPORTED_CREATE_OPTIONS) {
97
+ if (options[key] !== void 0) {
98
+ throw new Error(
99
+ `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()).`
100
+ );
101
+ }
102
+ }
103
+ const body = {};
104
+ const env = typeof process !== "undefined" ? process.env : void 0;
105
+ const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
106
+ if (template) body.template = template;
107
+ const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
108
+ if (region) body.region = region;
109
+ if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
110
+ if (typeof options.timeout === "number" && options.timeout > 0) {
111
+ body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1e3)));
112
+ }
113
+ return body;
114
+ }
115
+ function execArgv(command, options) {
116
+ let cmd = command;
117
+ if (options?.cwd) cmd = `cd "${(0, import_provider.escapeShellArg)(options.cwd)}" && ${cmd}`;
118
+ if (options?.background) {
119
+ cmd = `nohup sh -c "${(0, import_provider.escapeShellArg)(cmd)}" >/dev/null 2>&1 &`;
120
+ } else if (options?.timeout && options.timeout > 0) {
121
+ const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
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`;
127
+ }
128
+ return ["sh", "-c", cmd];
129
+ }
130
+ var MAX_ARG_BYTES = 8192;
131
+ var MAX_EXEC_BODY_BYTES = 64 * 1024;
132
+ var SCRIPT_ENV = "KOSA8_SCRIPT";
133
+ function execBody(command, options) {
134
+ const argv = execArgv(command, options);
135
+ const env = execEnv(options?.env);
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]}`] };
137
+ const size = Buffer.byteLength(JSON.stringify(body), "utf8");
138
+ if (size > MAX_EXEC_BODY_BYTES) {
139
+ throw new Error(
140
+ `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) for the command and its environment together. Write a long script to a file with sandbox.filesystem.writeFile() and run that file instead.`
141
+ );
142
+ }
143
+ return body;
144
+ }
145
+ function execEnv(env) {
146
+ if (!env) return [];
147
+ return Object.entries(env).map(([key, value]) => {
148
+ if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);
149
+ if (key === SCRIPT_ENV) {
150
+ throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);
151
+ }
152
+ return `${key}=${value}`;
153
+ });
154
+ }
155
+ function infoStatus(state) {
156
+ if (state === "error") return "error";
157
+ if (state === "running") return "running";
158
+ return "stopped";
159
+ }
160
+ async function getData(sandbox) {
161
+ const data = await request(sandbox, "GET", sandboxPath(sandbox.id));
162
+ return data?.sandbox ?? null;
163
+ }
164
+ var WRITE_CHUNK_CHARS = 32 * 1024;
165
+ var shellFs = (sandbox, run) => new import_provider.ShellFileSystem((command, options) => run(sandbox, command, options));
166
+ async function mustSucceed(run, sandbox, command, path, env) {
167
+ const result = await run(sandbox, command, env ? { env } : void 0);
168
+ if (result.exitCode !== 0) {
169
+ const detail = (result.stderr || result.stdout).trim();
170
+ throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`);
171
+ }
172
+ }
173
+ async function writeFileViaExec(sandbox, path, content, run) {
174
+ const target = `"${(0, import_provider.escapeShellArg)(path)}"`;
175
+ const tmp = `"${(0, import_provider.escapeShellArg)(`${path}.computesdk-${(0, import_node_crypto.randomBytes)(6).toString("hex")}`)}"`;
176
+ const encoded = Buffer.from(content, "utf8").toString("base64");
177
+ const chunks = [];
178
+ for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));
179
+ try {
180
+ await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p "$d" && : > ${tmp}`, path);
181
+ for (const chunk of chunks) {
182
+ await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });
183
+ }
184
+ await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);
185
+ } catch (err) {
186
+ await run(sandbox, `rm -f ${tmp}`).catch(() => {
187
+ });
188
+ throw err;
189
+ }
190
+ }
191
+ var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
192
+ var kosa8 = (0, import_provider.defineProvider)({
193
+ name: "kosa8",
194
+ methods: {
195
+ instances: {
196
+ create: async (config, options) => {
197
+ const auth = resolveConfig(config);
198
+ const data = await request(
199
+ auth,
200
+ "POST",
201
+ "/v1/sandboxes",
202
+ createBody(config, options),
203
+ options?.signal
204
+ );
205
+ if (!data?.sandbox) throw new Error("kosa8 API returned no sandbox on create");
206
+ return { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id };
207
+ },
208
+ getById: async (config, instanceId) => {
209
+ const auth = resolveConfig(config);
210
+ const data = await request(auth, "GET", sandboxPath(instanceId));
211
+ return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;
212
+ },
213
+ list: async (config) => {
214
+ const auth = resolveConfig(config);
215
+ const data = await request(auth, "GET", "/v1/sandboxes");
216
+ return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));
217
+ },
218
+ destroy: async (config, instanceId) => {
219
+ const auth = resolveConfig(config);
220
+ await request(auth, "DELETE", sandboxPath(instanceId));
221
+ },
222
+ runCommand: async (sandbox, command, options) => {
223
+ const start = Date.now();
224
+ const body = execBody(command, options);
225
+ const signal = options?.timeout && options.timeout > 0 && !options.background ? AbortSignal.timeout(options.timeout + 3e4) : void 0;
226
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
227
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
228
+ return {
229
+ stdout: data.stdout ?? "",
230
+ stderr: data.stderr ?? "",
231
+ exitCode: Number.isInteger(data.exit) ? data.exit : -1,
232
+ durationMs: Date.now() - start
233
+ };
234
+ },
235
+ getInfo: async (sandbox) => {
236
+ const current = await getData(sandbox) ?? { ...sandbox.data, state: "deleted" };
237
+ sandbox.data = current;
238
+ return {
239
+ id: sandbox.id,
240
+ provider: "kosa8",
241
+ status: infoStatus(current.state),
242
+ createdAt: new Date(current.created_at),
243
+ timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,
244
+ metadata: {
245
+ state: current.state,
246
+ template: current.template,
247
+ cpus: current.cpus,
248
+ memMb: current.mem_mb,
249
+ region: current.region,
250
+ sleepAfterSeconds: current.sleep_after_s,
251
+ deleteAfter: current.delete_after,
252
+ lastError: current.last_error
253
+ }
254
+ };
255
+ },
256
+ getUrl: async () => {
257
+ throw notAvailable("port URLs");
258
+ },
259
+ // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.
260
+ pause: async (sandbox) => {
261
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/sleep"));
262
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
263
+ sandbox.data = data.sandbox;
264
+ },
265
+ resume: async (sandbox) => {
266
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/wake"));
267
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
268
+ sandbox.data = data.sandbox;
269
+ },
270
+ pauseCapabilities: { memory: true },
271
+ // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.
272
+ lifetime: {},
273
+ // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.
274
+ extendLifetime: async (sandbox, ms) => {
275
+ const current = await getData(sandbox);
276
+ if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
277
+ sandbox.data = current;
278
+ if (current.delete_after == null) return;
279
+ const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1e3);
280
+ const data = await request(sandbox, "PATCH", sandboxPath(sandbox.id), {
281
+ delete_after: Math.floor(deleteAfter)
282
+ });
283
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
284
+ if (data.sandbox) sandbox.data = data.sandbox;
285
+ },
286
+ getInstance: (sandbox) => sandbox,
287
+ // Shell commands over exec. kosa8's own file API needs a host capability that is not on
288
+ // every host yet, so it is not used here.
289
+ filesystem: {
290
+ readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),
291
+ writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),
292
+ mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),
293
+ readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),
294
+ exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),
295
+ remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path)
296
+ }
297
+ },
298
+ template: {
299
+ create: async () => {
300
+ throw notAvailable("creating templates (templates are offered by the hosts)");
301
+ },
302
+ list: async (config) => {
303
+ const auth = resolveConfig(config);
304
+ const data = await request(auth, "GET", "/v1/templates");
305
+ return data?.templates ?? [];
306
+ },
307
+ delete: async () => {
308
+ throw notAvailable("deleting templates (templates are offered by the hosts)");
309
+ }
310
+ }
311
+ }
312
+ });
313
+ var index_default = kosa8;
314
+ // Annotate the CommonJS export names for ESM import in node:
315
+ 0 && (module.exports = {
316
+ MAX_EXEC_BODY_BYTES,
317
+ SCRIPT_ENV,
318
+ WRITE_CHUNK_CHARS,
319
+ createBody,
320
+ execArgv,
321
+ execBody,
322
+ kosa8,
323
+ writeFileViaExec
324
+ });
325
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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 - 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,IAAM,WAAW;AAEjB,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,UAA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AG;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":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,293 @@
1
+ // src/index.ts
2
+ import { randomBytes } from "crypto";
3
+ import { defineProvider, escapeShellArg, ShellFileSystem } from "@computesdk/provider";
4
+ var MIN_TTL_S = 60;
5
+ var MAX_TTL_S = 90 * 86400;
6
+ var TIMEOUT_EXIT = 124;
7
+ var DONE_ENV = "KOSA8_DONE";
8
+ var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
9
+ var UNSUPPORTED_CREATE_OPTIONS = [
10
+ "cpu",
11
+ "cpus",
12
+ "vcpus",
13
+ "cpuLimit",
14
+ "memory",
15
+ "memoryMiB",
16
+ "memMiB",
17
+ "memoryMb",
18
+ "diskMb",
19
+ "diskMiB",
20
+ "image",
21
+ "snapshotId",
22
+ "envs",
23
+ "volumes"
24
+ ];
25
+ function resolveConfig(config) {
26
+ const env = typeof process !== "undefined" ? process.env : void 0;
27
+ const apiKey = config.apiKey || env?.KOSA8_API_KEY || "";
28
+ if (!apiKey) {
29
+ throw new Error(
30
+ `Missing kosa8 API key. Provide 'apiKey' in config or set the KOSA8_API_KEY environment variable. Create a key in the kosa8 Cloud dashboard at https://app.kosa8.com`
31
+ );
32
+ }
33
+ const baseUrl = (config.baseUrl || env?.KOSA8_API_URL || "https://api.kosa8.com").replace(/\/+$/, "");
34
+ return { apiKey, baseUrl };
35
+ }
36
+ async function request(auth, method, path, body, signal) {
37
+ const res = await fetch(`${auth.baseUrl}${path}`, {
38
+ method,
39
+ headers: {
40
+ Authorization: `Bearer ${auth.apiKey}`,
41
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
42
+ },
43
+ body: body === void 0 ? void 0 : JSON.stringify(body),
44
+ signal
45
+ });
46
+ if (res.status === 404) return null;
47
+ const text = await res.text();
48
+ if (!res.ok) {
49
+ let detail = text;
50
+ try {
51
+ const parsed = JSON.parse(text);
52
+ if (parsed && (parsed.error || parsed.message)) detail = [parsed.error, parsed.message].filter(Boolean).join(": ");
53
+ } catch {
54
+ }
55
+ throw new Error(`kosa8 API error (${res.status}) on ${method} ${path}: ${detail}`);
56
+ }
57
+ return text ? JSON.parse(text) : null;
58
+ }
59
+ var sandboxPath = (id, rest = "") => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;
60
+ function toSandbox(auth, data) {
61
+ return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };
62
+ }
63
+ function createBody(config, options = {}) {
64
+ for (const key of UNSUPPORTED_CREATE_OPTIONS) {
65
+ if (options[key] !== void 0) {
66
+ throw new Error(
67
+ `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()).`
68
+ );
69
+ }
70
+ }
71
+ const body = {};
72
+ const env = typeof process !== "undefined" ? process.env : void 0;
73
+ const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
74
+ if (template) body.template = template;
75
+ const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
76
+ if (region) body.region = region;
77
+ if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
78
+ if (typeof options.timeout === "number" && options.timeout > 0) {
79
+ body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1e3)));
80
+ }
81
+ return body;
82
+ }
83
+ function execArgv(command, options) {
84
+ let cmd = command;
85
+ if (options?.cwd) cmd = `cd "${escapeShellArg(options.cwd)}" && ${cmd}`;
86
+ if (options?.background) {
87
+ cmd = `nohup sh -c "${escapeShellArg(cmd)}" >/dev/null 2>&1 &`;
88
+ } else if (options?.timeout && options.timeout > 0) {
89
+ const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
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`;
95
+ }
96
+ return ["sh", "-c", cmd];
97
+ }
98
+ var MAX_ARG_BYTES = 8192;
99
+ var MAX_EXEC_BODY_BYTES = 64 * 1024;
100
+ var SCRIPT_ENV = "KOSA8_SCRIPT";
101
+ function execBody(command, options) {
102
+ const argv = execArgv(command, options);
103
+ const env = execEnv(options?.env);
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]}`] };
105
+ const size = Buffer.byteLength(JSON.stringify(body), "utf8");
106
+ if (size > MAX_EXEC_BODY_BYTES) {
107
+ throw new Error(
108
+ `kosa8 exec request is ${size} bytes, over the exec API's limit of ${MAX_EXEC_BODY_BYTES} bytes (64 KiB) for the command and its environment together. Write a long script to a file with sandbox.filesystem.writeFile() and run that file instead.`
109
+ );
110
+ }
111
+ return body;
112
+ }
113
+ function execEnv(env) {
114
+ if (!env) return [];
115
+ return Object.entries(env).map(([key, value]) => {
116
+ if (!ENV_NAME.test(key)) throw new Error(`Invalid environment variable name: ${key}`);
117
+ if (key === SCRIPT_ENV) {
118
+ throw new Error(`The environment variable name ${SCRIPT_ENV} is reserved by the kosa8 provider; use another name.`);
119
+ }
120
+ return `${key}=${value}`;
121
+ });
122
+ }
123
+ function infoStatus(state) {
124
+ if (state === "error") return "error";
125
+ if (state === "running") return "running";
126
+ return "stopped";
127
+ }
128
+ async function getData(sandbox) {
129
+ const data = await request(sandbox, "GET", sandboxPath(sandbox.id));
130
+ return data?.sandbox ?? null;
131
+ }
132
+ var WRITE_CHUNK_CHARS = 32 * 1024;
133
+ var shellFs = (sandbox, run) => new ShellFileSystem((command, options) => run(sandbox, command, options));
134
+ async function mustSucceed(run, sandbox, command, path, env) {
135
+ const result = await run(sandbox, command, env ? { env } : void 0);
136
+ if (result.exitCode !== 0) {
137
+ const detail = (result.stderr || result.stdout).trim();
138
+ throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`);
139
+ }
140
+ }
141
+ async function writeFileViaExec(sandbox, path, content, run) {
142
+ const target = `"${escapeShellArg(path)}"`;
143
+ const tmp = `"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString("hex")}`)}"`;
144
+ const encoded = Buffer.from(content, "utf8").toString("base64");
145
+ const chunks = [];
146
+ for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));
147
+ try {
148
+ await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p "$d" && : > ${tmp}`, path);
149
+ for (const chunk of chunks) {
150
+ await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });
151
+ }
152
+ await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);
153
+ } catch (err) {
154
+ await run(sandbox, `rm -f ${tmp}`).catch(() => {
155
+ });
156
+ throw err;
157
+ }
158
+ }
159
+ var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
160
+ var kosa8 = defineProvider({
161
+ name: "kosa8",
162
+ methods: {
163
+ instances: {
164
+ create: async (config, options) => {
165
+ const auth = resolveConfig(config);
166
+ const data = await request(
167
+ auth,
168
+ "POST",
169
+ "/v1/sandboxes",
170
+ createBody(config, options),
171
+ options?.signal
172
+ );
173
+ if (!data?.sandbox) throw new Error("kosa8 API returned no sandbox on create");
174
+ return { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id };
175
+ },
176
+ getById: async (config, instanceId) => {
177
+ const auth = resolveConfig(config);
178
+ const data = await request(auth, "GET", sandboxPath(instanceId));
179
+ return data?.sandbox ? { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id } : null;
180
+ },
181
+ list: async (config) => {
182
+ const auth = resolveConfig(config);
183
+ const data = await request(auth, "GET", "/v1/sandboxes");
184
+ return (data?.sandboxes ?? []).map((row) => ({ instance: toSandbox(auth, row), instanceId: row.id }));
185
+ },
186
+ destroy: async (config, instanceId) => {
187
+ const auth = resolveConfig(config);
188
+ await request(auth, "DELETE", sandboxPath(instanceId));
189
+ },
190
+ runCommand: async (sandbox, command, options) => {
191
+ const start = Date.now();
192
+ const body = execBody(command, options);
193
+ const signal = options?.timeout && options.timeout > 0 && !options.background ? AbortSignal.timeout(options.timeout + 3e4) : void 0;
194
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
195
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
196
+ return {
197
+ stdout: data.stdout ?? "",
198
+ stderr: data.stderr ?? "",
199
+ exitCode: Number.isInteger(data.exit) ? data.exit : -1,
200
+ durationMs: Date.now() - start
201
+ };
202
+ },
203
+ getInfo: async (sandbox) => {
204
+ const current = await getData(sandbox) ?? { ...sandbox.data, state: "deleted" };
205
+ sandbox.data = current;
206
+ return {
207
+ id: sandbox.id,
208
+ provider: "kosa8",
209
+ status: infoStatus(current.state),
210
+ createdAt: new Date(current.created_at),
211
+ timeout: current.delete_after ? Math.max(0, current.delete_after - Date.now()) : 0,
212
+ metadata: {
213
+ state: current.state,
214
+ template: current.template,
215
+ cpus: current.cpus,
216
+ memMb: current.mem_mb,
217
+ region: current.region,
218
+ sleepAfterSeconds: current.sleep_after_s,
219
+ deleteAfter: current.delete_after,
220
+ lastError: current.last_error
221
+ }
222
+ };
223
+ },
224
+ getUrl: async () => {
225
+ throw notAvailable("port URLs");
226
+ },
227
+ // Sleep snapshots the VM (memory and disk) and frees its RAM; wake restores it.
228
+ pause: async (sandbox) => {
229
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/sleep"));
230
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
231
+ sandbox.data = data.sandbox;
232
+ },
233
+ resume: async (sandbox) => {
234
+ const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/wake"));
235
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
236
+ sandbox.data = data.sandbox;
237
+ },
238
+ pauseCapabilities: { memory: true },
239
+ // No default lifetime: a sandbox lives until it is destroyed, unless created with `timeout`.
240
+ lifetime: {},
241
+ // Moves the sandbox's delete time later by `ms`. A sandbox with no delete time has no limit to extend.
242
+ extendLifetime: async (sandbox, ms) => {
243
+ const current = await getData(sandbox);
244
+ if (!current) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
245
+ sandbox.data = current;
246
+ if (current.delete_after == null) return;
247
+ const deleteAfter = Math.min(Math.max(current.delete_after, Date.now()) + ms, Date.now() + MAX_TTL_S * 1e3);
248
+ const data = await request(sandbox, "PATCH", sandboxPath(sandbox.id), {
249
+ delete_after: Math.floor(deleteAfter)
250
+ });
251
+ if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
252
+ if (data.sandbox) sandbox.data = data.sandbox;
253
+ },
254
+ getInstance: (sandbox) => sandbox,
255
+ // Shell commands over exec. kosa8's own file API needs a host capability that is not on
256
+ // every host yet, so it is not used here.
257
+ filesystem: {
258
+ readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),
259
+ writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),
260
+ mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),
261
+ readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),
262
+ exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),
263
+ remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path)
264
+ }
265
+ },
266
+ template: {
267
+ create: async () => {
268
+ throw notAvailable("creating templates (templates are offered by the hosts)");
269
+ },
270
+ list: async (config) => {
271
+ const auth = resolveConfig(config);
272
+ const data = await request(auth, "GET", "/v1/templates");
273
+ return data?.templates ?? [];
274
+ },
275
+ delete: async () => {
276
+ throw notAvailable("deleting templates (templates are offered by the hosts)");
277
+ }
278
+ }
279
+ }
280
+ });
281
+ var index_default = kosa8;
282
+ export {
283
+ MAX_EXEC_BODY_BYTES,
284
+ SCRIPT_ENV,
285
+ WRITE_CHUNK_CHARS,
286
+ createBody,
287
+ index_default as default,
288
+ execArgv,
289
+ execBody,
290
+ kosa8,
291
+ writeFileViaExec
292
+ };
293
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +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 - 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,uBAAuB;AA4DhE,IAAM,YAAY;AAClB,IAAM,YAAY,KAAK;AAGvB,IAAM,eAAe;AAGrB,IAAM,WAAW;AAEjB,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;AACb,QAAI;AACF,YAAM,SAAS,KAAK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AQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@computesdk/kosa8",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.2",
4
+ "description": "kosa8 provider for ComputeSDK - sandboxes that each run in their own microVM with its own kernel, with sleep and wake",
5
+ "author": "kosa8",
6
+ "license": "MIT",
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.mjs",
14
+ "require": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "keywords": [
21
+ "computesdk",
22
+ "provider",
23
+ "sandbox",
24
+ "code-execution",
25
+ "cloud",
26
+ "compute",
27
+ "microvm",
28
+ "kosa8"
29
+ ],
30
+ "dependencies": {
31
+ "@computesdk/provider": "2.1.23",
32
+ "computesdk": "4.1.17"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^20.0.0",
36
+ "@vitest/coverage-v8": "^1.0.0",
37
+ "eslint": "^8.37.0",
38
+ "rimraf": "^5.0.0",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.0.0",
41
+ "vitest": "^1.0.0",
42
+ "@computesdk/test-utils": "2.0.6"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/computesdk/computesdk.git",
47
+ "directory": "packages/kosa8"
48
+ },
49
+ "homepage": "https://kosa8.com",
50
+ "bugs": {
51
+ "url": "https://github.com/computesdk/computesdk/issues"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "clean": "rimraf dist",
56
+ "dev": "tsup --watch",
57
+ "test": "vitest run",
58
+ "test:watch": "vitest watch",
59
+ "test:coverage": "vitest run --coverage",
60
+ "typecheck": "tsc --noEmit",
61
+ "lint": "eslint"
62
+ }
6
63
  }