@computesdk/createos-sandbox 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.js +25 -10
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +25 -10
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.d.mts
CHANGED
|
@@ -32,12 +32,18 @@ interface CreateosCreateOptions extends CreateSandboxOptions {
|
|
|
32
32
|
cpus?: number;
|
|
33
33
|
/** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */
|
|
34
34
|
ephemeralDiskMb?: number;
|
|
35
|
-
/** Enable public ingress. Defaults to
|
|
35
|
+
/** Enable public ingress. Defaults to false. */
|
|
36
36
|
ingressEnabled?: boolean;
|
|
37
37
|
/** SSH public keys to inject at boot. */
|
|
38
38
|
sshPubkeys?: string[];
|
|
39
39
|
/** Egress allow-list. */
|
|
40
40
|
egress?: string[];
|
|
41
|
+
/** Env vars set at sandbox creation. */
|
|
42
|
+
envs?: Record<string, string>;
|
|
43
|
+
/** Explicit sandbox name (control mints one if omitted). */
|
|
44
|
+
name?: string;
|
|
45
|
+
/** Snapshot id (paused sandbox) to fork from — bypasses cold create. */
|
|
46
|
+
snapshotId?: string;
|
|
41
47
|
}
|
|
42
48
|
/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.
|
|
43
49
|
* Returns undefined when neither is given (caller applies the default). */
|
package/dist/index.d.ts
CHANGED
|
@@ -32,12 +32,18 @@ interface CreateosCreateOptions extends CreateSandboxOptions {
|
|
|
32
32
|
cpus?: number;
|
|
33
33
|
/** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */
|
|
34
34
|
ephemeralDiskMb?: number;
|
|
35
|
-
/** Enable public ingress. Defaults to
|
|
35
|
+
/** Enable public ingress. Defaults to false. */
|
|
36
36
|
ingressEnabled?: boolean;
|
|
37
37
|
/** SSH public keys to inject at boot. */
|
|
38
38
|
sshPubkeys?: string[];
|
|
39
39
|
/** Egress allow-list. */
|
|
40
40
|
egress?: string[];
|
|
41
|
+
/** Env vars set at sandbox creation. */
|
|
42
|
+
envs?: Record<string, string>;
|
|
43
|
+
/** Explicit sandbox name (control mints one if omitted). */
|
|
44
|
+
name?: string;
|
|
45
|
+
/** Snapshot id (paused sandbox) to fork from — bypasses cold create. */
|
|
46
|
+
snapshotId?: string;
|
|
41
47
|
}
|
|
42
48
|
/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.
|
|
43
49
|
* Returns undefined when neither is given (caller applies the default). */
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ var provider = require('@computesdk/provider');
|
|
|
6
6
|
// src/index.ts
|
|
7
7
|
var PROVIDER_NAME = "createos-sandbox";
|
|
8
8
|
var sandboxConfig = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
var clientCache = /* @__PURE__ */ new Map();
|
|
9
10
|
function shellQuote(arg) {
|
|
10
11
|
return `'${arg.replace(/'/g, "'\\''")}'`;
|
|
11
12
|
}
|
|
@@ -23,7 +24,13 @@ function resolveClient(config) {
|
|
|
23
24
|
);
|
|
24
25
|
}
|
|
25
26
|
const baseUrl = config.baseUrl?.trim() || env("CREATEOS_SANDBOX_BASE_URL")?.trim() || DEFAULT_BASE_URL;
|
|
26
|
-
|
|
27
|
+
const cacheKey = `${apiKey}\0${baseUrl}`;
|
|
28
|
+
let client = clientCache.get(cacheKey);
|
|
29
|
+
if (!client) {
|
|
30
|
+
client = new sandbox.CreateosSandboxClient({ apiKey, baseUrl });
|
|
31
|
+
clientCache.set(cacheKey, client);
|
|
32
|
+
}
|
|
33
|
+
return client;
|
|
27
34
|
}
|
|
28
35
|
function isNotFound(e) {
|
|
29
36
|
return e instanceof sandbox.CreateosSandboxNotFoundError;
|
|
@@ -44,14 +51,20 @@ function defaultShape(shapes) {
|
|
|
44
51
|
const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);
|
|
45
52
|
return (fit ?? sorted[0])?.id;
|
|
46
53
|
}
|
|
54
|
+
var shapesCache = /* @__PURE__ */ new WeakMap();
|
|
55
|
+
var SHAPES_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
56
|
+
var FALLBACK_SHAPE = "s-1vcpu-1gb";
|
|
47
57
|
async function resolveShape(client, opts, config) {
|
|
48
58
|
const explicit = opts.shape ?? config.shape;
|
|
49
59
|
if (explicit) return explicit;
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
60
|
+
if (opts.memoryMb == null && opts.cpus == null) return FALLBACK_SHAPE;
|
|
61
|
+
const now = Date.now();
|
|
62
|
+
let entry = shapesCache.get(client);
|
|
63
|
+
if (!entry || entry.expires < now) {
|
|
64
|
+
entry = { shapes: await client.listShapes(), expires: now + SHAPES_CACHE_TTL_MS };
|
|
65
|
+
shapesCache.set(client, entry);
|
|
54
66
|
}
|
|
67
|
+
const picked = pickShape(entry.shapes, opts.memoryMb, opts.cpus) ?? defaultShape(entry.shapes) ?? FALLBACK_SHAPE;
|
|
55
68
|
return picked;
|
|
56
69
|
}
|
|
57
70
|
function mapStatus(status) {
|
|
@@ -68,7 +81,7 @@ function strArray(v) {
|
|
|
68
81
|
}
|
|
69
82
|
function toForkRequest(opts) {
|
|
70
83
|
const req = {
|
|
71
|
-
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) :
|
|
84
|
+
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) : false
|
|
72
85
|
};
|
|
73
86
|
const ssh = strArray(opts.sshPubkeys);
|
|
74
87
|
if (ssh) req.ssh_pubkeys = ssh;
|
|
@@ -81,7 +94,7 @@ function toForkRequest(opts) {
|
|
|
81
94
|
function toCreateRequest(opts, shape, rootfs) {
|
|
82
95
|
const req = {
|
|
83
96
|
shape,
|
|
84
|
-
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) :
|
|
97
|
+
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) : false
|
|
85
98
|
};
|
|
86
99
|
if (rootfs) req.rootfs = rootfs;
|
|
87
100
|
if (opts.name) req.name = String(opts.name);
|
|
@@ -146,7 +159,7 @@ var createosSandbox = provider.defineProvider({
|
|
|
146
159
|
return { sandbox: forked, sandboxId: forked.id };
|
|
147
160
|
}
|
|
148
161
|
const shape = await resolveShape(client, opts, config);
|
|
149
|
-
const rootfs = opts.image ?? opts.runtime ?? config.rootfs;
|
|
162
|
+
const rootfs = opts.image ?? opts.runtime ?? config.rootfs ?? "devbox:1";
|
|
150
163
|
const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));
|
|
151
164
|
sandboxConfig.set(sandbox, config);
|
|
152
165
|
return { sandbox, sandboxId: sandbox.id };
|
|
@@ -173,8 +186,10 @@ var createosSandbox = provider.defineProvider({
|
|
|
173
186
|
destroy: async (config, sandboxId) => {
|
|
174
187
|
const client = resolveClient(config);
|
|
175
188
|
try {
|
|
176
|
-
|
|
177
|
-
|
|
189
|
+
await client.http.request(
|
|
190
|
+
"DELETE",
|
|
191
|
+
`/v1/sandboxes/${encodeURIComponent(sandboxId)}`
|
|
192
|
+
);
|
|
178
193
|
} catch (e) {
|
|
179
194
|
if (isNotFound(e)) return;
|
|
180
195
|
throw e;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["CreateosSandboxClient","CreateosSandboxNotFoundError","defineProvider"],"mappings":";;;;;;AAiDA,IAAM,aAAA,GAAgB,kBAAA;AAOtB,IAAM,aAAA,uBAAoB,OAAA,EAAiC;AAO3D,SAAS,WAAW,GAAA,EAAqB;AACvC,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;AAaA,IAAM,qBAAA,GAAwB,IAAA;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U,aAAA;AAAA,UACV,SAAA,EAAW,IAAI,IAAA,CAAK,CAAA,CAAE,KAAK,SAAA,IAAa,CAAA,CAAE,KAAK,UAAU;AAAA,SAC3D,CAAE,CAAA;AAAA,MACN,CAAA;AAAA,MACA,MAAA,EAAQ,OAAO,MAAA,EAAwB,UAAA,KAAuB;AAC5D,QAAA,MAAM,MAAA,GAAS,cAAc,MAAM,CAAA;AACnC,QAAA,IAAI;AACF,UAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,UAAA,CAAW,UAAU,CAAA;AAClD,UAAA,MAAM,QAAQ,OAAA,EAAQ;AAAA,QACxB,SAAS,CAAA,EAAG;AACV,UAAA,IAAI,UAAA,CAAW,CAAC,CAAA,EAAG;AACnB,UAAA,MAAM,CAAA;AAAA,QACR;AAAA,MACF;AAAA;AACF;AAEJ,CAAC","file":"index.js","sourcesContent":["/**\n * CreateOS Sandbox Provider for ComputeSDK\n *\n * VM sandboxes backed by the NodeOps createos-sandbox control plane.\n * Thin adapter over the official `@nodeops-createos/sandbox` npm package — the same\n * SDK used across the CreateOS tooling.\n *\n * Design notes:\n * - `TSandbox` is the native `@nodeops-createos/sandbox` `Sandbox` handle, so\n * `getInstance()` hands callers the full stateful API (pause / resume / fork /\n * disks / networks / bandwidth) that ComputeSDK's core surface does not model.\n * The resolving config is associated with each handle via a `WeakMap`\n * side-channel (`sandboxConfig`), so `getInfo` can honour `config` (e.g.\n * `timeout`) and its error policy without wrapping or mutating the handle.\n * - createos-sandbox sizes VMs from a fixed *shape* catalog rather than free-form\n * cpu/mem, so create() maps ComputeSDK's `cpus`/`memoryMb` onto the nearest\n * shape and honours an explicit provider-specific `shape` override.\n * - The control plane drops per-exec env server-side (env is sandbox-level,\n * set at create time), so per-command `env`/`cwd` are synthesised by\n * wrapping the command in an inline `sh -c` script.\n * - Snapshot semantics differ from running-snapshot providers (e2b/tensorlake):\n * `snapshot.create` *pauses* the sandbox (the source VM stops), and the\n * paused sandbox id IS the snapshot id. `create({ snapshotId })` forks that\n * paused bundle into a fresh sandbox.\n *\n * Error policy: provider operations fail loudly when the provider boundary is\n * broken. Only a genuine 404 (`CreateosSandboxNotFoundError`) is mapped to the\n * idempotent \"absent\" outcome (`getById` → null, `destroy`/`delete` → no-op).\n * Auth, network, validation, and server errors propagate.\n */\n\nimport { CreateosSandboxClient, CreateosSandboxNotFoundError, Sandbox } from \"@nodeops-createos/sandbox\";\nimport type {\n CreateSandboxRequest,\n ForkSandboxRequest,\n SandboxStatus,\n Shape,\n} from \"@nodeops-createos/sandbox\";\nimport { defineProvider } from \"@computesdk/provider\";\nimport type {\n CommandResult,\n CreateSandboxOptions,\n CreateSnapshotOptions,\n FileEntry,\n ListSnapshotsOptions,\n RunCommandOptions,\n SandboxInfo,\n} from \"@computesdk/provider\";\n\nconst PROVIDER_NAME = \"createos-sandbox\";\n\n/** Per-sandbox config side-channel: associates the resolving config with each\n * native handle without mutating it or wrapping `TSandbox` — so `getInstance()`\n * still returns the bare native handle (the escape hatch other providers honour),\n * while `getInfo` can still reach `config` (e.g. `timeout`). Keyed weakly, so an\n * entry is collected with its sandbox. */\nconst sandboxConfig = new WeakMap<Sandbox, CreateosConfig>();\n\n/** Quote a value into one complete, self-contained shell token. Unlike the\n * framework's `escapeShellArg` (which only neutralises metacharacters *inside*\n * surrounding double quotes), this wraps in single quotes so the token is safe\n * to splice unquoted — spaces, `;`, `&`, `|`, globs and the rest cannot split\n * the command or inject syntax. Embedded single quotes are closed/escaped/reopened. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** The framework-supplied command runner handed to filesystem callbacks. */\ntype CommandRunner = (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\n/** Memory floor (MiB) for the default shape when a create() pins no size. The\n * control plane names no default shape and `CreateSandboxRequest` requires\n * one, so the default is a client policy — the smallest *live* catalog shape\n * with at least this much RAM. Override per-create with `shape`/`config.shape`. */\nconst DEFAULT_SHAPE_MIN_MIB = 1024;\n\n/** POSIX environment variable name. Keys are spliced into a shell `export`, so\n * anything outside this grammar is rejected rather than emitted (injection). */\nconst ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport interface CreateosConfig {\n /** createos-sandbox API key. Falls back to the CREATEOS_SANDBOX_API_KEY env var. */\n apiKey?: string;\n /** Control-plane base URL. Falls back to the CREATEOS_SANDBOX_BASE_URL env\n * var, then the production control plane. */\n baseUrl?: string;\n /** Default shape when create options pin neither `shape` nor cpus/memoryMb. */\n shape?: string;\n /** Default rootfs catalog name or template id. Empty = host default. */\n rootfs?: string;\n /** Reported `getInfo().timeout` in ms. Informational only. */\n timeout?: number;\n}\n\n/** ComputeSDK create options plus the createos-specific fields this provider\n * reads off the (otherwise open) options bag. Declaring them turns the cast-\n * heavy decode into a typed contract and makes unsupported fields obvious. */\nexport interface CreateosCreateOptions extends CreateSandboxOptions {\n /** Explicit shape id. Overrides cpus/memoryMb selection and skips the catalog fetch. */\n shape?: string;\n /** Rootfs catalog name or template id (alias of `runtime`). */\n image?: string;\n /** Rootfs catalog name or template id (alias of `image`). */\n runtime?: string;\n /** Requested RAM; mapped onto the smallest fitting shape. */\n memoryMb?: number;\n /** Requested vCPUs; mapped onto the smallest fitting shape. */\n cpus?: number;\n /** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */\n ephemeralDiskMb?: number;\n /** Enable public ingress. Defaults to true. */\n ingressEnabled?: boolean;\n /** SSH public keys to inject at boot. */\n sshPubkeys?: string[];\n /** Egress allow-list. */\n egress?: string[];\n}\n\n/** Production control-plane base URL, used when neither `config.baseUrl` nor\n * the CREATEOS_SANDBOX_BASE_URL env var is set. */\nconst DEFAULT_BASE_URL = \"https://api.sb.createos.sh\";\n\nfunction env(key: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[key] : undefined;\n}\n\nfunction resolveClient(config: CreateosConfig): CreateosSandboxClient {\n const apiKey = config.apiKey ?? env(\"CREATEOS_SANDBOX_API_KEY\");\n if (!apiKey) {\n throw new Error(\n \"Missing CreateOS API key. Provide 'apiKey' in config or set the \" +\n \"CREATEOS_SANDBOX_API_KEY environment variable.\",\n );\n }\n // Precedence: explicit config > env var > production default. A blank value\n // is treated as unset so the next source applies.\n const baseUrl =\n config.baseUrl?.trim() || env(\"CREATEOS_SANDBOX_BASE_URL\")?.trim() || DEFAULT_BASE_URL;\n return new CreateosSandboxClient({ apiKey, baseUrl });\n}\n\n/** True only for a genuine \"resource does not exist\" (404). Everything else —\n * auth, network, validation, server, rate-limit — is a broken boundary. */\nfunction isNotFound(e: unknown): boolean {\n return e instanceof CreateosSandboxNotFoundError;\n}\n\n/** Sort a catalog by ascending RAM then vCPU. Selection relies on this order;\n * the control plane gives no ordering guarantee for `listShapes()`. */\nfunction sortShapes(shapes: Shape[]): Shape[] {\n return shapes.toSorted((a, b) => a.mem_mib - b.mem_mib || a.vcpu - b.vcpu);\n}\n\n/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.\n * Returns undefined when neither is given (caller applies the default). */\nexport function pickShape(shapes: Shape[], memoryMb?: number, cpus?: number): string | undefined {\n if (memoryMb == null && cpus == null) return undefined;\n const sorted = sortShapes(shapes);\n const fit = sorted.find(\n (s) => (memoryMb == null || s.mem_mib >= memoryMb) && (cpus == null || s.vcpu >= cpus),\n );\n return (fit ?? sorted[sorted.length - 1])?.id;\n}\n\n/** Default shape when create() pins neither `shape` nor cpus/memoryMb: the\n * smallest live shape meeting the RAM floor, else the smallest available. */\nexport function defaultShape(shapes: Shape[]): string | undefined {\n const sorted = sortShapes(shapes);\n const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);\n return (fit ?? sorted[0])?.id;\n}\n\n/** Resolve the shape for a create() call. Fetches the live catalog only when\n * no explicit `shape` is pinned, so the explicit path never depends on\n * `/v1/shapes` being reachable. */\nasync function resolveShape(\n client: CreateosSandboxClient,\n opts: CreateosCreateOptions,\n config: CreateosConfig,\n): Promise<string> {\n const explicit = opts.shape ?? config.shape;\n if (explicit) return explicit;\n const shapes = await client.listShapes();\n const picked = pickShape(shapes, opts.memoryMb, opts.cpus) ?? defaultShape(shapes);\n if (!picked) {\n throw new Error(\"CreateOS control plane returned an empty shape catalog.\");\n }\n return picked;\n}\n\n/** Map an createos-sandbox lifecycle state onto ComputeSDK's running|stopped|error. */\nexport function mapStatus(status: SandboxStatus): SandboxInfo[\"status\"] {\n if (status === \"running\") return \"running\";\n if (status === \"error\" || status === \"failed\") return \"error\";\n return \"stopped\";\n}\n\n/** A non-empty env record from `envs` (preferred) or the legacy `env` alias. */\nfunction envsOf(opts: CreateosCreateOptions): Record<string, string> | undefined {\n const envs = opts.envs ?? (opts as { env?: Record<string, string> }).env;\n return envs && Object.keys(envs).length > 0 ? envs : undefined;\n}\n\n/** A string[] when the value is an array, else undefined. */\nfunction strArray(v: unknown): string[] | undefined {\n return Array.isArray(v) ? (v as string[]) : undefined;\n}\n\n/** Pure map: ComputeSDK create options → createos-sandbox fork request body. */\nexport function toForkRequest(opts: CreateosCreateOptions): ForkSandboxRequest {\n const req: ForkSandboxRequest = {\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : true,\n };\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n return req;\n}\n\n/** Pure map: ComputeSDK create options (+ resolved shape/rootfs) → create request. */\nexport function toCreateRequest(\n opts: CreateosCreateOptions,\n shape: string,\n rootfs?: string,\n): CreateSandboxRequest {\n const req: CreateSandboxRequest = {\n shape,\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : true,\n };\n if (rootfs) req.rootfs = rootfs;\n if (opts.name) req.name = String(opts.name);\n // Pass the requested overlay-disk size straight through; the control plane\n // validates it (0 / omitted = shape default). No client-side menu.\n if (typeof opts.ephemeralDiskMb === \"number\" && opts.ephemeralDiskMb > 0) {\n req.disk_mib = opts.ephemeralDiskMb;\n }\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n return req;\n}\n\n/** Wrap a command so per-call cwd/env/background work despite the server dropping\n * exec env. Env *keys* are validated before being spliced into `export` —\n * values are shell-quoted, but a malformed key would otherwise be raw shell. */\nexport function buildScript(command: string, options?: RunCommandOptions): string {\n let script = command;\n if (options?.cwd) script = `cd ${shellQuote(options.cwd)} && ${script}`;\n if (options?.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([k, v]) => {\n if (!ENV_KEY_RE.test(k)) {\n throw new Error(\n `Invalid environment variable name ${JSON.stringify(k)}: ` +\n `must match ${ENV_KEY_RE.source}.`,\n );\n }\n return `export ${k}=${shellQuote(String(v))}`;\n })\n .join(\"; \");\n script = `${exports}; ${script}`;\n }\n if (options?.background) {\n script = `nohup sh -c ${shellQuote(script)} > /dev/null 2>&1 &`;\n }\n return script;\n}\n\n/** Parse `ls -lA --time-style=+%s` output into ComputeSDK FileEntry rows. */\nexport function parseLsOutput(stdout: string): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split(\"\\n\")) {\n if (!line || line.startsWith(\"total \")) continue;\n const m = line.match(/^(\\S+)\\s+\\d+\\s+\\S+\\s+\\S+\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/);\n if (!m) continue;\n const name = m[4]!.replace(/ -> .*$/, \"\"); // strip symlink target\n entries.push({\n name,\n type: m[1]!.startsWith(\"d\") ? \"directory\" : \"file\",\n size: Number(m[2]),\n modified: new Date(Number(m[3]) * 1000),\n });\n }\n return entries;\n}\n\nexport const createosSandbox = defineProvider<Sandbox, CreateosConfig>({\n name: PROVIDER_NAME,\n methods: {\n sandbox: {\n create: async (config: CreateosConfig, options?: CreateSandboxOptions) => {\n const client = resolveClient(config);\n const opts = (options ?? {}) as CreateosCreateOptions;\n\n // A snapshot id is a paused sandbox: fork it into a fresh sandbox.\n if (opts.snapshotId) {\n const source = await client.getSandbox(opts.snapshotId);\n const forked = await source.fork(toForkRequest(opts));\n // Surface lifecycle failures: a fork that never reaches \"running\"\n // (or hits a terminal state) must not be reported as success.\n await forked.waitUntilRunning();\n sandboxConfig.set(forked, config);\n return { sandbox: forked, sandboxId: forked.id };\n }\n\n const shape = await resolveShape(client, opts, config);\n const rootfs = opts.image ?? opts.runtime ?? config.rootfs;\n const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n },\n\n getById: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n } catch (e) {\n if (isNotFound(e)) return null;\n throw e;\n }\n },\n\n list: async (config: CreateosConfig) => {\n const client = resolveClient(config);\n // No catch: a failed list is a broken boundary, not an empty account.\n const sandboxes = await client.listSandboxes({ limit: 100 });\n return sandboxes.map((sandbox) => {\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n });\n },\n\n destroy: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone; destroy is idempotent\n throw e;\n }\n },\n\n runCommand: async (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n ): Promise<CommandResult> => {\n // `sh -c` (not `bash -lc`): POSIX-portable so bare rootfses without\n // bash still run. buildScript only emits POSIX constructs. Transport /\n // auth errors propagate; a command that ran reports its own exit code.\n const { result, exec_ms } = await sandbox.runCommand(\"sh\", [\n \"-c\",\n buildScript(command, options),\n ]);\n const stderr = result.error ? `${result.stderr}${result.error}` : result.stderr;\n return {\n stdout: result.stdout,\n stderr,\n exitCode: result.exit_code,\n durationMs: exec_ms,\n };\n },\n\n getInfo: async (sandbox: Sandbox): Promise<SandboxInfo> => {\n // Refresh failures propagate (no swallow): a getInfo that cannot reach\n // the control plane must surface that rather than return stale data.\n await sandbox.refresh();\n const v = sandbox.data;\n return {\n id: v.id,\n provider: PROVIDER_NAME,\n status: mapStatus(v.status),\n createdAt: new Date(v.created_at),\n timeout: sandboxConfig.get(sandbox)?.timeout ?? 0,\n metadata: {\n createosStatus: v.status,\n shape: v.shape,\n rootfs: v.rootfs,\n region: v.region,\n ip: v.ip,\n ingressEnabled: v.ingress_enabled,\n },\n };\n },\n\n getUrl: async (sandbox: Sandbox, options: { port: number; protocol?: string }) => {\n const scheme = options.protocol === \"http\" ? \"http\" : \"https\";\n return sandbox.previewUrl(options.port, { scheme });\n },\n\n // Escape hatch: the bare native @nodeops-createos/sandbox handle\n // (pause/resume/fork/disks/...).\n getInstance: (sandbox: Sandbox): Sandbox => sandbox,\n\n filesystem: {\n readFile: async (sandbox: Sandbox, path: string): Promise<string> => {\n const buf = await sandbox.files.download(path);\n return new TextDecoder().decode(buf);\n },\n writeFile: async (sandbox: Sandbox, path: string, content: string): Promise<void> => {\n await sandbox.files.upload(path, content);\n },\n mkdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `mkdir -p ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`mkdir ${path} failed: ${r.stderr}`);\n },\n readdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const r = await runCommand(sandbox, `ls -lA --time-style=+%s ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`readdir ${path} failed: ${r.stderr}`);\n return parseLsOutput(r.stdout);\n },\n exists: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const r = await runCommand(sandbox, `test -e ${shellQuote(path)}`);\n return r.exitCode === 0;\n },\n remove: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `rm -rf ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`remove ${path} failed: ${r.stderr}`);\n },\n },\n },\n\n snapshot: {\n create: async (\n config: CreateosConfig,\n sandboxId: string,\n options?: CreateSnapshotOptions,\n ) => {\n const client = resolveClient(config);\n const sandbox = await client.getSandbox(sandboxId);\n // createos-sandbox has no decoupled snapshot object: pausing IS the snapshot,\n // and the paused sandbox id is the snapshot id. This stops the source VM.\n await sandbox.pause();\n // The success claim is \"it paused\" — surface a pause that timed out or\n // entered a terminal state rather than returning a phantom snapshot.\n await sandbox.waitUntilPaused();\n return {\n id: sandboxId,\n provider: PROVIDER_NAME,\n createdAt: new Date(),\n metadata: { name: options?.name, ...options?.metadata },\n };\n },\n list: async (config: CreateosConfig, _options?: ListSnapshotsOptions) => {\n const client = resolveClient(config);\n // The typed status filter excludes \"paused\", so list all and filter.\n const all = await client.listSandboxes({ limit: 500 });\n return all\n .filter((s) => s.status === \"paused\")\n .map((s) => ({\n id: s.id,\n provider: PROVIDER_NAME,\n createdAt: new Date(s.data.paused_at ?? s.data.created_at),\n }));\n },\n delete: async (config: CreateosConfig, snapshotId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(snapshotId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone\n throw e;\n }\n },\n },\n },\n});\n\nexport type { Sandbox as CreateosSandbox } from \"@nodeops-createos/sandbox\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["CreateosSandboxClient","CreateosSandboxNotFoundError","defineProvider"],"mappings":";;;;;;AAiDA,IAAM,aAAA,GAAgB,kBAAA;AAOtB,IAAM,aAAA,uBAAoB,OAAA,EAAiC;AAG3D,IAAM,WAAA,uBAAkB,GAAA,EAAmC;AAO3D,SAAS,WAAW,GAAA,EAAqB;AACvC,EAAA,OAAO,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UAAU,CAAA;AAClD,UAAA,MAAM,QAAQ,OAAA,EAAQ;AAAA,QACxB,SAAS,CAAA,EAAG;AACV,UAAA,IAAI,UAAA,CAAW,CAAC,CAAA,EAAG;AACnB,UAAA,MAAM,CAAA;AAAA,QACR;AAAA,MACF;AAAA;AACF;AAEJ,CAAC","file":"index.js","sourcesContent":["/**\n * CreateOS Sandbox Provider for ComputeSDK\n *\n * VM sandboxes backed by the NodeOps createos-sandbox control plane.\n * Thin adapter over the official `@nodeops-createos/sandbox` npm package — the same\n * SDK used across the CreateOS tooling.\n *\n * Design notes:\n * - `TSandbox` is the native `@nodeops-createos/sandbox` `Sandbox` handle, so\n * `getInstance()` hands callers the full stateful API (pause / resume / fork /\n * disks / networks / bandwidth) that ComputeSDK's core surface does not model.\n * The resolving config is associated with each handle via a `WeakMap`\n * side-channel (`sandboxConfig`), so `getInfo` can honour `config` (e.g.\n * `timeout`) and its error policy without wrapping or mutating the handle.\n * - createos-sandbox sizes VMs from a fixed *shape* catalog rather than free-form\n * cpu/mem, so create() maps ComputeSDK's `cpus`/`memoryMb` onto the nearest\n * shape and honours an explicit provider-specific `shape` override.\n * - The control plane drops per-exec env server-side (env is sandbox-level,\n * set at create time), so per-command `env`/`cwd` are synthesised by\n * wrapping the command in an inline `sh -c` script.\n * - Snapshot semantics differ from running-snapshot providers (e2b/tensorlake):\n * `snapshot.create` *pauses* the sandbox (the source VM stops), and the\n * paused sandbox id IS the snapshot id. `create({ snapshotId })` forks that\n * paused bundle into a fresh sandbox.\n *\n * Error policy: provider operations fail loudly when the provider boundary is\n * broken. Only a genuine 404 (`CreateosSandboxNotFoundError`) is mapped to the\n * idempotent \"absent\" outcome (`getById` → null, `destroy`/`delete` → no-op).\n * Auth, network, validation, and server errors propagate.\n */\n\nimport { CreateosSandboxClient, CreateosSandboxNotFoundError, Sandbox } from \"@nodeops-createos/sandbox\";\nimport type {\n CreateSandboxRequest,\n ForkSandboxRequest,\n SandboxStatus,\n Shape,\n} from \"@nodeops-createos/sandbox\";\nimport { defineProvider } from \"@computesdk/provider\";\nimport type {\n CommandResult,\n CreateSandboxOptions,\n CreateSnapshotOptions,\n FileEntry,\n ListSnapshotsOptions,\n RunCommandOptions,\n SandboxInfo,\n} from \"@computesdk/provider\";\n\nconst PROVIDER_NAME = \"createos-sandbox\";\n\n/** Per-sandbox config side-channel: associates the resolving config with each\n * native handle without mutating it or wrapping `TSandbox` — so `getInstance()`\n * still returns the bare native handle (the escape hatch other providers honour),\n * while `getInfo` can still reach `config` (e.g. `timeout`). Keyed weakly, so an\n * entry is collected with its sandbox. */\nconst sandboxConfig = new WeakMap<Sandbox, CreateosConfig>();\n\n/** Reuse clients for the same apiKey+baseUrl pair. */\nconst clientCache = new Map<string, CreateosSandboxClient>();\n\n/** Quote a value into one complete, self-contained shell token. Unlike the\n * framework's `escapeShellArg` (which only neutralises metacharacters *inside*\n * surrounding double quotes), this wraps in single quotes so the token is safe\n * to splice unquoted — spaces, `;`, `&`, `|`, globs and the rest cannot split\n * the command or inject syntax. Embedded single quotes are closed/escaped/reopened. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** The framework-supplied command runner handed to filesystem callbacks. */\ntype CommandRunner = (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\n/** Memory floor (MiB) for the default shape when a create() pins no size. The\n * control plane names no default shape and `CreateSandboxRequest` requires\n * one, so the default is a client policy — the smallest *live* catalog shape\n * with at least this much RAM. Override per-create with `shape`/`config.shape`. */\nconst DEFAULT_SHAPE_MIN_MIB = 1024;\n\n/** POSIX environment variable name. Keys are spliced into a shell `export`, so\n * anything outside this grammar is rejected rather than emitted (injection). */\nconst ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport interface CreateosConfig {\n /** createos-sandbox API key. Falls back to the CREATEOS_SANDBOX_API_KEY env var. */\n apiKey?: string;\n /** Control-plane base URL. Falls back to the CREATEOS_SANDBOX_BASE_URL env\n * var, then the production control plane. */\n baseUrl?: string;\n /** Default shape when create options pin neither `shape` nor cpus/memoryMb. */\n shape?: string;\n /** Default rootfs catalog name or template id. Empty = host default. */\n rootfs?: string;\n /** Reported `getInfo().timeout` in ms. Informational only. */\n timeout?: number;\n}\n\n/** ComputeSDK create options plus the createos-specific fields this provider\n * reads off the (otherwise open) options bag. Declaring them turns the cast-\n * heavy decode into a typed contract and makes unsupported fields obvious. */\nexport interface CreateosCreateOptions extends CreateSandboxOptions {\n /** Explicit shape id. Overrides cpus/memoryMb selection and skips the catalog fetch. */\n shape?: string;\n /** Rootfs catalog name or template id (alias of `runtime`). */\n image?: string;\n /** Rootfs catalog name or template id (alias of `image`). */\n runtime?: string;\n /** Requested RAM; mapped onto the smallest fitting shape. */\n memoryMb?: number;\n /** Requested vCPUs; mapped onto the smallest fitting shape. */\n cpus?: number;\n /** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */\n ephemeralDiskMb?: number;\n /** Enable public ingress. Defaults to false. */\n ingressEnabled?: boolean;\n /** SSH public keys to inject at boot. */\n sshPubkeys?: string[];\n /** Egress allow-list. */\n egress?: string[];\n /** Env vars set at sandbox creation. */\n envs?: Record<string, string>;\n /** Explicit sandbox name (control mints one if omitted). */\n name?: string;\n /** Snapshot id (paused sandbox) to fork from — bypasses cold create. */\n snapshotId?: string;\n}\n\n/** Production control-plane base URL, used when neither `config.baseUrl` nor\n * the CREATEOS_SANDBOX_BASE_URL env var is set. */\nconst DEFAULT_BASE_URL = \"https://api.sb.createos.sh\";\n\nfunction env(key: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[key] : undefined;\n}\n\nfunction resolveClient(config: CreateosConfig): CreateosSandboxClient {\n const apiKey = config.apiKey ?? env(\"CREATEOS_SANDBOX_API_KEY\");\n if (!apiKey) {\n throw new Error(\n \"Missing CreateOS API key. Provide 'apiKey' in config or set the \" +\n \"CREATEOS_SANDBOX_API_KEY environment variable.\",\n );\n }\n // Precedence: explicit config > env var > production default. A blank value\n // is treated as unset so the next source applies.\n const baseUrl =\n config.baseUrl?.trim() || env(\"CREATEOS_SANDBOX_BASE_URL\")?.trim() || DEFAULT_BASE_URL;\n const cacheKey = `${apiKey}\\0${baseUrl}`;\n let client = clientCache.get(cacheKey);\n if (!client) {\n client = new CreateosSandboxClient({ apiKey, baseUrl });\n clientCache.set(cacheKey, client);\n }\n return client;\n}\n\n/** True only for a genuine \"resource does not exist\" (404). Everything else —\n * auth, network, validation, server, rate-limit — is a broken boundary. */\nfunction isNotFound(e: unknown): boolean {\n return e instanceof CreateosSandboxNotFoundError;\n}\n\n/** Sort a catalog by ascending RAM then vCPU. Selection relies on this order;\n * the control plane gives no ordering guarantee for `listShapes()`. */\nfunction sortShapes(shapes: Shape[]): Shape[] {\n return shapes.toSorted((a, b) => a.mem_mib - b.mem_mib || a.vcpu - b.vcpu);\n}\n\n/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.\n * Returns undefined when neither is given (caller applies the default). */\nexport function pickShape(shapes: Shape[], memoryMb?: number, cpus?: number): string | undefined {\n if (memoryMb == null && cpus == null) return undefined;\n const sorted = sortShapes(shapes);\n const fit = sorted.find(\n (s) => (memoryMb == null || s.mem_mib >= memoryMb) && (cpus == null || s.vcpu >= cpus),\n );\n return (fit ?? sorted[sorted.length - 1])?.id;\n}\n\n/** Default shape when create() pins neither `shape` nor cpus/memoryMb: the\n * smallest live shape meeting the RAM floor, else the smallest available. */\nexport function defaultShape(shapes: Shape[]): string | undefined {\n const sorted = sortShapes(shapes);\n const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);\n return (fit ?? sorted[0])?.id;\n}\n\n/** Cache shapes per client with a 5-minute TTL. */\nconst shapesCache = new WeakMap<CreateosSandboxClient, { shapes: Shape[]; expires: number }>();\nconst SHAPES_CACHE_TTL_MS = 5 * 60 * 1_000;\nconst FALLBACK_SHAPE = \"s-1vcpu-1gb\";\n\n/** Resolve the shape for a create() call. Fetches the live catalog only when\n * no explicit `shape` is pinned, so the explicit path never depends on\n * `/v1/shapes` being reachable. */\nasync function resolveShape(\n client: CreateosSandboxClient,\n opts: CreateosCreateOptions,\n config: CreateosConfig,\n): Promise<string> {\n const explicit = opts.shape ?? config.shape;\n if (explicit) return explicit;\n if (opts.memoryMb == null && opts.cpus == null) return FALLBACK_SHAPE;\n const now = Date.now();\n let entry = shapesCache.get(client);\n if (!entry || entry.expires < now) {\n entry = { shapes: await client.listShapes(), expires: now + SHAPES_CACHE_TTL_MS };\n shapesCache.set(client, entry);\n }\n const picked = pickShape(entry.shapes, opts.memoryMb, opts.cpus) ?? defaultShape(entry.shapes) ?? FALLBACK_SHAPE;\n return picked;\n}\n\n/** Map an createos-sandbox lifecycle state onto ComputeSDK's running|stopped|error. */\nexport function mapStatus(status: SandboxStatus): SandboxInfo[\"status\"] {\n if (status === \"running\") return \"running\";\n if (status === \"error\" || status === \"failed\") return \"error\";\n return \"stopped\";\n}\n\n/** A non-empty env record from `envs` (preferred) or the legacy `env` alias. */\nfunction envsOf(opts: CreateosCreateOptions): Record<string, string> | undefined {\n const envs = opts.envs ?? (opts as { env?: Record<string, string> }).env;\n return envs && Object.keys(envs).length > 0 ? envs : undefined;\n}\n\n/** A string[] when the value is an array, else undefined. */\nfunction strArray(v: unknown): string[] | undefined {\n return Array.isArray(v) ? (v as string[]) : undefined;\n}\n\n/** Pure map: ComputeSDK create options → createos-sandbox fork request body. */\nexport function toForkRequest(opts: CreateosCreateOptions): ForkSandboxRequest {\n const req: ForkSandboxRequest = {\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : false,\n };\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n return req;\n}\n\n/** Pure map: ComputeSDK create options (+ resolved shape/rootfs) → create request. */\nexport function toCreateRequest(\n opts: CreateosCreateOptions,\n shape: string,\n rootfs?: string,\n): CreateSandboxRequest {\n const req: CreateSandboxRequest = {\n shape,\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : false,\n };\n if (rootfs) req.rootfs = rootfs;\n if (opts.name) req.name = String(opts.name);\n // Pass the requested overlay-disk size straight through; the control plane\n // validates it (0 / omitted = shape default). No client-side menu.\n if (typeof opts.ephemeralDiskMb === \"number\" && opts.ephemeralDiskMb > 0) {\n req.disk_mib = opts.ephemeralDiskMb;\n }\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n return req;\n}\n\n/** Wrap a command so per-call cwd/env/background work despite the server dropping\n * exec env. Env *keys* are validated before being spliced into `export` —\n * values are shell-quoted, but a malformed key would otherwise be raw shell. */\nexport function buildScript(command: string, options?: RunCommandOptions): string {\n let script = command;\n if (options?.cwd) script = `cd ${shellQuote(options.cwd)} && ${script}`;\n if (options?.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([k, v]) => {\n if (!ENV_KEY_RE.test(k)) {\n throw new Error(\n `Invalid environment variable name ${JSON.stringify(k)}: ` +\n `must match ${ENV_KEY_RE.source}.`,\n );\n }\n return `export ${k}=${shellQuote(String(v))}`;\n })\n .join(\"; \");\n script = `${exports}; ${script}`;\n }\n if (options?.background) {\n script = `nohup sh -c ${shellQuote(script)} > /dev/null 2>&1 &`;\n }\n return script;\n}\n\n/** Parse `ls -lA --time-style=+%s` output into ComputeSDK FileEntry rows. */\nexport function parseLsOutput(stdout: string): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split(\"\\n\")) {\n if (!line || line.startsWith(\"total \")) continue;\n const m = line.match(/^(\\S+)\\s+\\d+\\s+\\S+\\s+\\S+\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/);\n if (!m) continue;\n const name = m[4]!.replace(/ -> .*$/, \"\"); // strip symlink target\n entries.push({\n name,\n type: m[1]!.startsWith(\"d\") ? \"directory\" : \"file\",\n size: Number(m[2]),\n modified: new Date(Number(m[3]) * 1000),\n });\n }\n return entries;\n}\n\nexport const createosSandbox = defineProvider<Sandbox, CreateosConfig>({\n name: PROVIDER_NAME,\n methods: {\n sandbox: {\n create: async (config: CreateosConfig, options?: CreateSandboxOptions) => {\n const client = resolveClient(config);\n const opts = (options ?? {}) as CreateosCreateOptions;\n\n // A snapshot id is a paused sandbox: fork it into a fresh sandbox.\n if (opts.snapshotId) {\n const source = await client.getSandbox(opts.snapshotId);\n const forked = await source.fork(toForkRequest(opts));\n // Surface lifecycle failures: a fork that never reaches \"running\"\n // (or hits a terminal state) must not be reported as success.\n await forked.waitUntilRunning();\n sandboxConfig.set(forked, config);\n return { sandbox: forked, sandboxId: forked.id };\n }\n\n const shape = await resolveShape(client, opts, config);\n const rootfs = opts.image ?? opts.runtime ?? config.rootfs ?? \"devbox:1\";\n const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n },\n\n getById: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n } catch (e) {\n if (isNotFound(e)) return null;\n throw e;\n }\n },\n\n list: async (config: CreateosConfig) => {\n const client = resolveClient(config);\n // No catch: a failed list is a broken boundary, not an empty account.\n const sandboxes = await client.listSandboxes({ limit: 100 });\n return sandboxes.map((sandbox) => {\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n });\n },\n\n destroy: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n await client.http.request(\n \"DELETE\",\n `/v1/sandboxes/${encodeURIComponent(sandboxId)}`,\n );\n } catch (e) {\n if (isNotFound(e)) return; // already gone; destroy is idempotent\n throw e;\n }\n },\n\n runCommand: async (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n ): Promise<CommandResult> => {\n // `sh -c` (not `bash -lc`): POSIX-portable so bare rootfses without\n // bash still run. buildScript only emits POSIX constructs. Transport /\n // auth errors propagate; a command that ran reports its own exit code.\n const { result, exec_ms } = await sandbox.runCommand(\"sh\", [\n \"-c\",\n buildScript(command, options),\n ]);\n const stderr = result.error ? `${result.stderr}${result.error}` : result.stderr;\n return {\n stdout: result.stdout,\n stderr,\n exitCode: result.exit_code,\n durationMs: exec_ms,\n };\n },\n\n getInfo: async (sandbox: Sandbox): Promise<SandboxInfo> => {\n // Refresh failures propagate (no swallow): a getInfo that cannot reach\n // the control plane must surface that rather than return stale data.\n await sandbox.refresh();\n const v = sandbox.data;\n return {\n id: v.id,\n provider: PROVIDER_NAME,\n status: mapStatus(v.status),\n createdAt: new Date(v.created_at),\n timeout: sandboxConfig.get(sandbox)?.timeout ?? 0,\n metadata: {\n createosStatus: v.status,\n shape: v.shape,\n rootfs: v.rootfs,\n region: v.region,\n ip: v.ip,\n ingressEnabled: v.ingress_enabled,\n },\n };\n },\n\n getUrl: async (sandbox: Sandbox, options: { port: number; protocol?: string }) => {\n const scheme = options.protocol === \"http\" ? \"http\" : \"https\";\n return sandbox.previewUrl(options.port, { scheme });\n },\n\n // Escape hatch: the bare native @nodeops-createos/sandbox handle\n // (pause/resume/fork/disks/...).\n getInstance: (sandbox: Sandbox): Sandbox => sandbox,\n\n filesystem: {\n readFile: async (sandbox: Sandbox, path: string): Promise<string> => {\n const buf = await sandbox.files.download(path);\n return new TextDecoder().decode(buf);\n },\n writeFile: async (sandbox: Sandbox, path: string, content: string): Promise<void> => {\n await sandbox.files.upload(path, content);\n },\n mkdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `mkdir -p ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`mkdir ${path} failed: ${r.stderr}`);\n },\n readdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const r = await runCommand(sandbox, `ls -lA --time-style=+%s ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`readdir ${path} failed: ${r.stderr}`);\n return parseLsOutput(r.stdout);\n },\n exists: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const r = await runCommand(sandbox, `test -e ${shellQuote(path)}`);\n return r.exitCode === 0;\n },\n remove: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `rm -rf ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`remove ${path} failed: ${r.stderr}`);\n },\n },\n },\n\n snapshot: {\n create: async (\n config: CreateosConfig,\n sandboxId: string,\n options?: CreateSnapshotOptions,\n ) => {\n const client = resolveClient(config);\n const sandbox = await client.getSandbox(sandboxId);\n // createos-sandbox has no decoupled snapshot object: pausing IS the snapshot,\n // and the paused sandbox id is the snapshot id. This stops the source VM.\n await sandbox.pause();\n // The success claim is \"it paused\" — surface a pause that timed out or\n // entered a terminal state rather than returning a phantom snapshot.\n await sandbox.waitUntilPaused();\n return {\n id: sandboxId,\n provider: PROVIDER_NAME,\n createdAt: new Date(),\n metadata: { name: options?.name, ...options?.metadata },\n };\n },\n list: async (config: CreateosConfig, _options?: ListSnapshotsOptions) => {\n const client = resolveClient(config);\n // The typed status filter excludes \"paused\", so list all and filter.\n const all = await client.listSandboxes({ limit: 500 });\n return all\n .filter((s) => s.status === \"paused\")\n .map((s) => ({\n id: s.id,\n provider: PROVIDER_NAME,\n createdAt: new Date(s.data.paused_at ?? s.data.created_at),\n }));\n },\n delete: async (config: CreateosConfig, snapshotId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(snapshotId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone\n throw e;\n }\n },\n },\n },\n});\n\nexport type { Sandbox as CreateosSandbox } from \"@nodeops-createos/sandbox\";\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { defineProvider } from '@computesdk/provider';
|
|
|
4
4
|
// src/index.ts
|
|
5
5
|
var PROVIDER_NAME = "createos-sandbox";
|
|
6
6
|
var sandboxConfig = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
var clientCache = /* @__PURE__ */ new Map();
|
|
7
8
|
function shellQuote(arg) {
|
|
8
9
|
return `'${arg.replace(/'/g, "'\\''")}'`;
|
|
9
10
|
}
|
|
@@ -21,7 +22,13 @@ function resolveClient(config) {
|
|
|
21
22
|
);
|
|
22
23
|
}
|
|
23
24
|
const baseUrl = config.baseUrl?.trim() || env("CREATEOS_SANDBOX_BASE_URL")?.trim() || DEFAULT_BASE_URL;
|
|
24
|
-
|
|
25
|
+
const cacheKey = `${apiKey}\0${baseUrl}`;
|
|
26
|
+
let client = clientCache.get(cacheKey);
|
|
27
|
+
if (!client) {
|
|
28
|
+
client = new CreateosSandboxClient({ apiKey, baseUrl });
|
|
29
|
+
clientCache.set(cacheKey, client);
|
|
30
|
+
}
|
|
31
|
+
return client;
|
|
25
32
|
}
|
|
26
33
|
function isNotFound(e) {
|
|
27
34
|
return e instanceof CreateosSandboxNotFoundError;
|
|
@@ -42,14 +49,20 @@ function defaultShape(shapes) {
|
|
|
42
49
|
const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);
|
|
43
50
|
return (fit ?? sorted[0])?.id;
|
|
44
51
|
}
|
|
52
|
+
var shapesCache = /* @__PURE__ */ new WeakMap();
|
|
53
|
+
var SHAPES_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
54
|
+
var FALLBACK_SHAPE = "s-1vcpu-1gb";
|
|
45
55
|
async function resolveShape(client, opts, config) {
|
|
46
56
|
const explicit = opts.shape ?? config.shape;
|
|
47
57
|
if (explicit) return explicit;
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
58
|
+
if (opts.memoryMb == null && opts.cpus == null) return FALLBACK_SHAPE;
|
|
59
|
+
const now = Date.now();
|
|
60
|
+
let entry = shapesCache.get(client);
|
|
61
|
+
if (!entry || entry.expires < now) {
|
|
62
|
+
entry = { shapes: await client.listShapes(), expires: now + SHAPES_CACHE_TTL_MS };
|
|
63
|
+
shapesCache.set(client, entry);
|
|
52
64
|
}
|
|
65
|
+
const picked = pickShape(entry.shapes, opts.memoryMb, opts.cpus) ?? defaultShape(entry.shapes) ?? FALLBACK_SHAPE;
|
|
53
66
|
return picked;
|
|
54
67
|
}
|
|
55
68
|
function mapStatus(status) {
|
|
@@ -66,7 +79,7 @@ function strArray(v) {
|
|
|
66
79
|
}
|
|
67
80
|
function toForkRequest(opts) {
|
|
68
81
|
const req = {
|
|
69
|
-
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) :
|
|
82
|
+
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) : false
|
|
70
83
|
};
|
|
71
84
|
const ssh = strArray(opts.sshPubkeys);
|
|
72
85
|
if (ssh) req.ssh_pubkeys = ssh;
|
|
@@ -79,7 +92,7 @@ function toForkRequest(opts) {
|
|
|
79
92
|
function toCreateRequest(opts, shape, rootfs) {
|
|
80
93
|
const req = {
|
|
81
94
|
shape,
|
|
82
|
-
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) :
|
|
95
|
+
ingress_enabled: opts.ingressEnabled !== void 0 ? Boolean(opts.ingressEnabled) : false
|
|
83
96
|
};
|
|
84
97
|
if (rootfs) req.rootfs = rootfs;
|
|
85
98
|
if (opts.name) req.name = String(opts.name);
|
|
@@ -144,7 +157,7 @@ var createosSandbox = defineProvider({
|
|
|
144
157
|
return { sandbox: forked, sandboxId: forked.id };
|
|
145
158
|
}
|
|
146
159
|
const shape = await resolveShape(client, opts, config);
|
|
147
|
-
const rootfs = opts.image ?? opts.runtime ?? config.rootfs;
|
|
160
|
+
const rootfs = opts.image ?? opts.runtime ?? config.rootfs ?? "devbox:1";
|
|
148
161
|
const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));
|
|
149
162
|
sandboxConfig.set(sandbox, config);
|
|
150
163
|
return { sandbox, sandboxId: sandbox.id };
|
|
@@ -171,8 +184,10 @@ var createosSandbox = defineProvider({
|
|
|
171
184
|
destroy: async (config, sandboxId) => {
|
|
172
185
|
const client = resolveClient(config);
|
|
173
186
|
try {
|
|
174
|
-
|
|
175
|
-
|
|
187
|
+
await client.http.request(
|
|
188
|
+
"DELETE",
|
|
189
|
+
`/v1/sandboxes/${encodeURIComponent(sandboxId)}`
|
|
190
|
+
);
|
|
176
191
|
} catch (e) {
|
|
177
192
|
if (isNotFound(e)) return;
|
|
178
193
|
throw e;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;AAiDA,IAAM,aAAA,GAAgB,kBAAA;AAOtB,IAAM,aAAA,uBAAoB,OAAA,EAAiC;AAO3D,SAAS,WAAW,GAAA,EAAqB;AACvC,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;AAaA,IAAM,qBAAA,GAAwB,IAAA;AAI9B,IAAM,UAAA,GAAa,0BAAA;AA0CnB,IAAM,gBAAA,GAAmB,4BAAA;AAEzB,SAAS,IAAI,GAAA,EAAiC;AAC5C,EAAA,OAAO,OAAO,OAAA,KAAY,WAAA,GAAc,OAAA,CAAQ,GAAA,GAAM,GAAG,CAAA,GAAI,MAAA;AAC/D;AAEA,SAAS,cAAc,MAAA,EAA+C;AACpE,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,GAAA,CAAI,0BAA0B,CAAA;AAC9D,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AA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AAG;AACV,UAAA,IAAI,UAAA,CAAW,CAAC,CAAA,EAAG;AACnB,UAAA,MAAM,CAAA;AAAA,QACR;AAAA,MACF;AAAA;AACF;AAEJ,CAAC","file":"index.mjs","sourcesContent":["/**\n * CreateOS Sandbox Provider for ComputeSDK\n *\n * VM sandboxes backed by the NodeOps createos-sandbox control plane.\n * Thin adapter over the official `@nodeops-createos/sandbox` npm package — the same\n * SDK used across the CreateOS tooling.\n *\n * Design notes:\n * - `TSandbox` is the native `@nodeops-createos/sandbox` `Sandbox` handle, so\n * `getInstance()` hands callers the full stateful API (pause / resume / fork /\n * disks / networks / bandwidth) that ComputeSDK's core surface does not model.\n * The resolving config is associated with each handle via a `WeakMap`\n * side-channel (`sandboxConfig`), so `getInfo` can honour `config` (e.g.\n * `timeout`) and its error policy without wrapping or mutating the handle.\n * - createos-sandbox sizes VMs from a fixed *shape* catalog rather than free-form\n * cpu/mem, so create() maps ComputeSDK's `cpus`/`memoryMb` onto the nearest\n * shape and honours an explicit provider-specific `shape` override.\n * - The control plane drops per-exec env server-side (env is sandbox-level,\n * set at create time), so per-command `env`/`cwd` are synthesised by\n * wrapping the command in an inline `sh -c` script.\n * - Snapshot semantics differ from running-snapshot providers (e2b/tensorlake):\n * `snapshot.create` *pauses* the sandbox (the source VM stops), and the\n * paused sandbox id IS the snapshot id. `create({ snapshotId })` forks that\n * paused bundle into a fresh sandbox.\n *\n * Error policy: provider operations fail loudly when the provider boundary is\n * broken. Only a genuine 404 (`CreateosSandboxNotFoundError`) is mapped to the\n * idempotent \"absent\" outcome (`getById` → null, `destroy`/`delete` → no-op).\n * Auth, network, validation, and server errors propagate.\n */\n\nimport { CreateosSandboxClient, CreateosSandboxNotFoundError, Sandbox } from \"@nodeops-createos/sandbox\";\nimport type {\n CreateSandboxRequest,\n ForkSandboxRequest,\n SandboxStatus,\n Shape,\n} from \"@nodeops-createos/sandbox\";\nimport { defineProvider } from \"@computesdk/provider\";\nimport type {\n CommandResult,\n CreateSandboxOptions,\n CreateSnapshotOptions,\n FileEntry,\n ListSnapshotsOptions,\n RunCommandOptions,\n SandboxInfo,\n} from \"@computesdk/provider\";\n\nconst PROVIDER_NAME = \"createos-sandbox\";\n\n/** Per-sandbox config side-channel: associates the resolving config with each\n * native handle without mutating it or wrapping `TSandbox` — so `getInstance()`\n * still returns the bare native handle (the escape hatch other providers honour),\n * while `getInfo` can still reach `config` (e.g. `timeout`). Keyed weakly, so an\n * entry is collected with its sandbox. */\nconst sandboxConfig = new WeakMap<Sandbox, CreateosConfig>();\n\n/** Quote a value into one complete, self-contained shell token. Unlike the\n * framework's `escapeShellArg` (which only neutralises metacharacters *inside*\n * surrounding double quotes), this wraps in single quotes so the token is safe\n * to splice unquoted — spaces, `;`, `&`, `|`, globs and the rest cannot split\n * the command or inject syntax. Embedded single quotes are closed/escaped/reopened. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** The framework-supplied command runner handed to filesystem callbacks. */\ntype CommandRunner = (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\n/** Memory floor (MiB) for the default shape when a create() pins no size. The\n * control plane names no default shape and `CreateSandboxRequest` requires\n * one, so the default is a client policy — the smallest *live* catalog shape\n * with at least this much RAM. Override per-create with `shape`/`config.shape`. */\nconst DEFAULT_SHAPE_MIN_MIB = 1024;\n\n/** POSIX environment variable name. Keys are spliced into a shell `export`, so\n * anything outside this grammar is rejected rather than emitted (injection). */\nconst ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport interface CreateosConfig {\n /** createos-sandbox API key. Falls back to the CREATEOS_SANDBOX_API_KEY env var. */\n apiKey?: string;\n /** Control-plane base URL. Falls back to the CREATEOS_SANDBOX_BASE_URL env\n * var, then the production control plane. */\n baseUrl?: string;\n /** Default shape when create options pin neither `shape` nor cpus/memoryMb. */\n shape?: string;\n /** Default rootfs catalog name or template id. Empty = host default. */\n rootfs?: string;\n /** Reported `getInfo().timeout` in ms. Informational only. */\n timeout?: number;\n}\n\n/** ComputeSDK create options plus the createos-specific fields this provider\n * reads off the (otherwise open) options bag. Declaring them turns the cast-\n * heavy decode into a typed contract and makes unsupported fields obvious. */\nexport interface CreateosCreateOptions extends CreateSandboxOptions {\n /** Explicit shape id. Overrides cpus/memoryMb selection and skips the catalog fetch. */\n shape?: string;\n /** Rootfs catalog name or template id (alias of `runtime`). */\n image?: string;\n /** Rootfs catalog name or template id (alias of `image`). */\n runtime?: string;\n /** Requested RAM; mapped onto the smallest fitting shape. */\n memoryMb?: number;\n /** Requested vCPUs; mapped onto the smallest fitting shape. */\n cpus?: number;\n /** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */\n ephemeralDiskMb?: number;\n /** Enable public ingress. Defaults to true. */\n ingressEnabled?: boolean;\n /** SSH public keys to inject at boot. */\n sshPubkeys?: string[];\n /** Egress allow-list. */\n egress?: string[];\n}\n\n/** Production control-plane base URL, used when neither `config.baseUrl` nor\n * the CREATEOS_SANDBOX_BASE_URL env var is set. */\nconst DEFAULT_BASE_URL = \"https://api.sb.createos.sh\";\n\nfunction env(key: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[key] : undefined;\n}\n\nfunction resolveClient(config: CreateosConfig): CreateosSandboxClient {\n const apiKey = config.apiKey ?? env(\"CREATEOS_SANDBOX_API_KEY\");\n if (!apiKey) {\n throw new Error(\n \"Missing CreateOS API key. Provide 'apiKey' in config or set the \" +\n \"CREATEOS_SANDBOX_API_KEY environment variable.\",\n );\n }\n // Precedence: explicit config > env var > production default. A blank value\n // is treated as unset so the next source applies.\n const baseUrl =\n config.baseUrl?.trim() || env(\"CREATEOS_SANDBOX_BASE_URL\")?.trim() || DEFAULT_BASE_URL;\n return new CreateosSandboxClient({ apiKey, baseUrl });\n}\n\n/** True only for a genuine \"resource does not exist\" (404). Everything else —\n * auth, network, validation, server, rate-limit — is a broken boundary. */\nfunction isNotFound(e: unknown): boolean {\n return e instanceof CreateosSandboxNotFoundError;\n}\n\n/** Sort a catalog by ascending RAM then vCPU. Selection relies on this order;\n * the control plane gives no ordering guarantee for `listShapes()`. */\nfunction sortShapes(shapes: Shape[]): Shape[] {\n return shapes.toSorted((a, b) => a.mem_mib - b.mem_mib || a.vcpu - b.vcpu);\n}\n\n/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.\n * Returns undefined when neither is given (caller applies the default). */\nexport function pickShape(shapes: Shape[], memoryMb?: number, cpus?: number): string | undefined {\n if (memoryMb == null && cpus == null) return undefined;\n const sorted = sortShapes(shapes);\n const fit = sorted.find(\n (s) => (memoryMb == null || s.mem_mib >= memoryMb) && (cpus == null || s.vcpu >= cpus),\n );\n return (fit ?? sorted[sorted.length - 1])?.id;\n}\n\n/** Default shape when create() pins neither `shape` nor cpus/memoryMb: the\n * smallest live shape meeting the RAM floor, else the smallest available. */\nexport function defaultShape(shapes: Shape[]): string | undefined {\n const sorted = sortShapes(shapes);\n const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);\n return (fit ?? sorted[0])?.id;\n}\n\n/** Resolve the shape for a create() call. Fetches the live catalog only when\n * no explicit `shape` is pinned, so the explicit path never depends on\n * `/v1/shapes` being reachable. */\nasync function resolveShape(\n client: CreateosSandboxClient,\n opts: CreateosCreateOptions,\n config: CreateosConfig,\n): Promise<string> {\n const explicit = opts.shape ?? config.shape;\n if (explicit) return explicit;\n const shapes = await client.listShapes();\n const picked = pickShape(shapes, opts.memoryMb, opts.cpus) ?? defaultShape(shapes);\n if (!picked) {\n throw new Error(\"CreateOS control plane returned an empty shape catalog.\");\n }\n return picked;\n}\n\n/** Map an createos-sandbox lifecycle state onto ComputeSDK's running|stopped|error. */\nexport function mapStatus(status: SandboxStatus): SandboxInfo[\"status\"] {\n if (status === \"running\") return \"running\";\n if (status === \"error\" || status === \"failed\") return \"error\";\n return \"stopped\";\n}\n\n/** A non-empty env record from `envs` (preferred) or the legacy `env` alias. */\nfunction envsOf(opts: CreateosCreateOptions): Record<string, string> | undefined {\n const envs = opts.envs ?? (opts as { env?: Record<string, string> }).env;\n return envs && Object.keys(envs).length > 0 ? envs : undefined;\n}\n\n/** A string[] when the value is an array, else undefined. */\nfunction strArray(v: unknown): string[] | undefined {\n return Array.isArray(v) ? (v as string[]) : undefined;\n}\n\n/** Pure map: ComputeSDK create options → createos-sandbox fork request body. */\nexport function toForkRequest(opts: CreateosCreateOptions): ForkSandboxRequest {\n const req: ForkSandboxRequest = {\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : true,\n };\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n return req;\n}\n\n/** Pure map: ComputeSDK create options (+ resolved shape/rootfs) → create request. */\nexport function toCreateRequest(\n opts: CreateosCreateOptions,\n shape: string,\n rootfs?: string,\n): CreateSandboxRequest {\n const req: CreateSandboxRequest = {\n shape,\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : true,\n };\n if (rootfs) req.rootfs = rootfs;\n if (opts.name) req.name = String(opts.name);\n // Pass the requested overlay-disk size straight through; the control plane\n // validates it (0 / omitted = shape default). No client-side menu.\n if (typeof opts.ephemeralDiskMb === \"number\" && opts.ephemeralDiskMb > 0) {\n req.disk_mib = opts.ephemeralDiskMb;\n }\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n return req;\n}\n\n/** Wrap a command so per-call cwd/env/background work despite the server dropping\n * exec env. Env *keys* are validated before being spliced into `export` —\n * values are shell-quoted, but a malformed key would otherwise be raw shell. */\nexport function buildScript(command: string, options?: RunCommandOptions): string {\n let script = command;\n if (options?.cwd) script = `cd ${shellQuote(options.cwd)} && ${script}`;\n if (options?.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([k, v]) => {\n if (!ENV_KEY_RE.test(k)) {\n throw new Error(\n `Invalid environment variable name ${JSON.stringify(k)}: ` +\n `must match ${ENV_KEY_RE.source}.`,\n );\n }\n return `export ${k}=${shellQuote(String(v))}`;\n })\n .join(\"; \");\n script = `${exports}; ${script}`;\n }\n if (options?.background) {\n script = `nohup sh -c ${shellQuote(script)} > /dev/null 2>&1 &`;\n }\n return script;\n}\n\n/** Parse `ls -lA --time-style=+%s` output into ComputeSDK FileEntry rows. */\nexport function parseLsOutput(stdout: string): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split(\"\\n\")) {\n if (!line || line.startsWith(\"total \")) continue;\n const m = line.match(/^(\\S+)\\s+\\d+\\s+\\S+\\s+\\S+\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/);\n if (!m) continue;\n const name = m[4]!.replace(/ -> .*$/, \"\"); // strip symlink target\n entries.push({\n name,\n type: m[1]!.startsWith(\"d\") ? \"directory\" : \"file\",\n size: Number(m[2]),\n modified: new Date(Number(m[3]) * 1000),\n });\n }\n return entries;\n}\n\nexport const createosSandbox = defineProvider<Sandbox, CreateosConfig>({\n name: PROVIDER_NAME,\n methods: {\n sandbox: {\n create: async (config: CreateosConfig, options?: CreateSandboxOptions) => {\n const client = resolveClient(config);\n const opts = (options ?? {}) as CreateosCreateOptions;\n\n // A snapshot id is a paused sandbox: fork it into a fresh sandbox.\n if (opts.snapshotId) {\n const source = await client.getSandbox(opts.snapshotId);\n const forked = await source.fork(toForkRequest(opts));\n // Surface lifecycle failures: a fork that never reaches \"running\"\n // (or hits a terminal state) must not be reported as success.\n await forked.waitUntilRunning();\n sandboxConfig.set(forked, config);\n return { sandbox: forked, sandboxId: forked.id };\n }\n\n const shape = await resolveShape(client, opts, config);\n const rootfs = opts.image ?? opts.runtime ?? config.rootfs;\n const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n },\n\n getById: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n } catch (e) {\n if (isNotFound(e)) return null;\n throw e;\n }\n },\n\n list: async (config: CreateosConfig) => {\n const client = resolveClient(config);\n // No catch: a failed list is a broken boundary, not an empty account.\n const sandboxes = await client.listSandboxes({ limit: 100 });\n return sandboxes.map((sandbox) => {\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n });\n },\n\n destroy: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone; destroy is idempotent\n throw e;\n }\n },\n\n runCommand: async (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n ): Promise<CommandResult> => {\n // `sh -c` (not `bash -lc`): POSIX-portable so bare rootfses without\n // bash still run. buildScript only emits POSIX constructs. Transport /\n // auth errors propagate; a command that ran reports its own exit code.\n const { result, exec_ms } = await sandbox.runCommand(\"sh\", [\n \"-c\",\n buildScript(command, options),\n ]);\n const stderr = result.error ? `${result.stderr}${result.error}` : result.stderr;\n return {\n stdout: result.stdout,\n stderr,\n exitCode: result.exit_code,\n durationMs: exec_ms,\n };\n },\n\n getInfo: async (sandbox: Sandbox): Promise<SandboxInfo> => {\n // Refresh failures propagate (no swallow): a getInfo that cannot reach\n // the control plane must surface that rather than return stale data.\n await sandbox.refresh();\n const v = sandbox.data;\n return {\n id: v.id,\n provider: PROVIDER_NAME,\n status: mapStatus(v.status),\n createdAt: new Date(v.created_at),\n timeout: sandboxConfig.get(sandbox)?.timeout ?? 0,\n metadata: {\n createosStatus: v.status,\n shape: v.shape,\n rootfs: v.rootfs,\n region: v.region,\n ip: v.ip,\n ingressEnabled: v.ingress_enabled,\n },\n };\n },\n\n getUrl: async (sandbox: Sandbox, options: { port: number; protocol?: string }) => {\n const scheme = options.protocol === \"http\" ? \"http\" : \"https\";\n return sandbox.previewUrl(options.port, { scheme });\n },\n\n // Escape hatch: the bare native @nodeops-createos/sandbox handle\n // (pause/resume/fork/disks/...).\n getInstance: (sandbox: Sandbox): Sandbox => sandbox,\n\n filesystem: {\n readFile: async (sandbox: Sandbox, path: string): Promise<string> => {\n const buf = await sandbox.files.download(path);\n return new TextDecoder().decode(buf);\n },\n writeFile: async (sandbox: Sandbox, path: string, content: string): Promise<void> => {\n await sandbox.files.upload(path, content);\n },\n mkdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `mkdir -p ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`mkdir ${path} failed: ${r.stderr}`);\n },\n readdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const r = await runCommand(sandbox, `ls -lA --time-style=+%s ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`readdir ${path} failed: ${r.stderr}`);\n return parseLsOutput(r.stdout);\n },\n exists: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const r = await runCommand(sandbox, `test -e ${shellQuote(path)}`);\n return r.exitCode === 0;\n },\n remove: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `rm -rf ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`remove ${path} failed: ${r.stderr}`);\n },\n },\n },\n\n snapshot: {\n create: async (\n config: CreateosConfig,\n sandboxId: string,\n options?: CreateSnapshotOptions,\n ) => {\n const client = resolveClient(config);\n const sandbox = await client.getSandbox(sandboxId);\n // createos-sandbox has no decoupled snapshot object: pausing IS the snapshot,\n // and the paused sandbox id is the snapshot id. This stops the source VM.\n await sandbox.pause();\n // The success claim is \"it paused\" — surface a pause that timed out or\n // entered a terminal state rather than returning a phantom snapshot.\n await sandbox.waitUntilPaused();\n return {\n id: sandboxId,\n provider: PROVIDER_NAME,\n createdAt: new Date(),\n metadata: { name: options?.name, ...options?.metadata },\n };\n },\n list: async (config: CreateosConfig, _options?: ListSnapshotsOptions) => {\n const client = resolveClient(config);\n // The typed status filter excludes \"paused\", so list all and filter.\n const all = await client.listSandboxes({ limit: 500 });\n return all\n .filter((s) => s.status === \"paused\")\n .map((s) => ({\n id: s.id,\n provider: PROVIDER_NAME,\n createdAt: new Date(s.data.paused_at ?? s.data.created_at),\n }));\n },\n delete: async (config: CreateosConfig, snapshotId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(snapshotId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone\n throw e;\n }\n },\n },\n },\n});\n\nexport type { Sandbox as CreateosSandbox } from \"@nodeops-createos/sandbox\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;AAiDA,IAAM,aAAA,GAAgB,kBAAA;AAOtB,IAAM,aAAA,uBAAoB,OAAA,EAAiC;AAG3D,IAAM,WAAA,uBAAkB,GAAA,EAAmC;AAO3D,SAAS,WAAW,GAAA,EAAqB;AACvC,EAAA,OAAO,CAAA,CAAA,EAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAC,CAAA,CAAA,CAAA;AACvC;AAaA,IAAM,qBAAA,GAAwB,IAAA;AAI9B,IAAM,UAAA,GAAa,0BAAA;AAgDnB,IAAM,gBAAA,GAAmB,4BAAA;AAEzB,SAAS,IAAI,GAAA,EAAiC;AAC5C,EAAA,OAAO,OAAO,OAAA,KAAY,WAAA,GAAc,OAAA,CAAQ,GAAA,GAAM,GAAG,CAAA,GAAI,MAAA;AAC/D;AAEA,SAAS,cAAc,MAAA,EAA+C;AACpE,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,GAAA,CAAI,0BAA0B,CAAA;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,UAAU,EAAE,IAAA,EAAM,SAAS,IAAA,EAAM,GAAG,SAAS,QAAA;AAAS,SACxD;AAAA,MACF,CAAA;AAAA,MACA,IAAA,EAAM,OAAO,MAAA,EAAwB,QAAA,KAAoC;AACvE,QAAA,MAAM,MAAA,GAAS,cAAc,MAAM,CAAA;AAEnC,QAAA,MAAM,MAAM,MAAM,MAAA,CAAO,cAAc,EAAE,KAAA,EAAO,KAAK,CAAA;AACrD,QAAA,OAAO,GAAA,CACJ,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,QAAQ,CAAA,CACnC,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,UACX,IAAI,CAAA,CAAE,EAAA;AAAA,UACN,QAAA,EAAU,aAAA;AAAA,UACV,SAAA,EAAW,IAAI,IAAA,CAAK,CAAA,CAAE,KAAK,SAAA,IAAa,CAAA,CAAE,KAAK,UAAU;AAAA,SAC3D,CAAE,CAAA;AAAA,MACN,CAAA;AAAA,MACA,MAAA,EAAQ,OAAO,MAAA,EAAwB,UAAA,KAAuB;AAC5D,QAAA,MAAM,MAAA,GAAS,cAAc,MAAM,CAAA;AACnC,QAAA,IAAI;AACF,UAAA,MAAM,OAAA,GAAU,MAAM,MAAA,CAAO,UAAA,CAAW,UAAU,CAAA;AAClD,UAAA,MAAM,QAAQ,OAAA,EAAQ;AAAA,QACxB,SAAS,CAAA,EAAG;AACV,UAAA,IAAI,UAAA,CAAW,CAAC,CAAA,EAAG;AACnB,UAAA,MAAM,CAAA;AAAA,QACR;AAAA,MACF;AAAA;AACF;AAEJ,CAAC","file":"index.mjs","sourcesContent":["/**\n * CreateOS Sandbox Provider for ComputeSDK\n *\n * VM sandboxes backed by the NodeOps createos-sandbox control plane.\n * Thin adapter over the official `@nodeops-createos/sandbox` npm package — the same\n * SDK used across the CreateOS tooling.\n *\n * Design notes:\n * - `TSandbox` is the native `@nodeops-createos/sandbox` `Sandbox` handle, so\n * `getInstance()` hands callers the full stateful API (pause / resume / fork /\n * disks / networks / bandwidth) that ComputeSDK's core surface does not model.\n * The resolving config is associated with each handle via a `WeakMap`\n * side-channel (`sandboxConfig`), so `getInfo` can honour `config` (e.g.\n * `timeout`) and its error policy without wrapping or mutating the handle.\n * - createos-sandbox sizes VMs from a fixed *shape* catalog rather than free-form\n * cpu/mem, so create() maps ComputeSDK's `cpus`/`memoryMb` onto the nearest\n * shape and honours an explicit provider-specific `shape` override.\n * - The control plane drops per-exec env server-side (env is sandbox-level,\n * set at create time), so per-command `env`/`cwd` are synthesised by\n * wrapping the command in an inline `sh -c` script.\n * - Snapshot semantics differ from running-snapshot providers (e2b/tensorlake):\n * `snapshot.create` *pauses* the sandbox (the source VM stops), and the\n * paused sandbox id IS the snapshot id. `create({ snapshotId })` forks that\n * paused bundle into a fresh sandbox.\n *\n * Error policy: provider operations fail loudly when the provider boundary is\n * broken. Only a genuine 404 (`CreateosSandboxNotFoundError`) is mapped to the\n * idempotent \"absent\" outcome (`getById` → null, `destroy`/`delete` → no-op).\n * Auth, network, validation, and server errors propagate.\n */\n\nimport { CreateosSandboxClient, CreateosSandboxNotFoundError, Sandbox } from \"@nodeops-createos/sandbox\";\nimport type {\n CreateSandboxRequest,\n ForkSandboxRequest,\n SandboxStatus,\n Shape,\n} from \"@nodeops-createos/sandbox\";\nimport { defineProvider } from \"@computesdk/provider\";\nimport type {\n CommandResult,\n CreateSandboxOptions,\n CreateSnapshotOptions,\n FileEntry,\n ListSnapshotsOptions,\n RunCommandOptions,\n SandboxInfo,\n} from \"@computesdk/provider\";\n\nconst PROVIDER_NAME = \"createos-sandbox\";\n\n/** Per-sandbox config side-channel: associates the resolving config with each\n * native handle without mutating it or wrapping `TSandbox` — so `getInstance()`\n * still returns the bare native handle (the escape hatch other providers honour),\n * while `getInfo` can still reach `config` (e.g. `timeout`). Keyed weakly, so an\n * entry is collected with its sandbox. */\nconst sandboxConfig = new WeakMap<Sandbox, CreateosConfig>();\n\n/** Reuse clients for the same apiKey+baseUrl pair. */\nconst clientCache = new Map<string, CreateosSandboxClient>();\n\n/** Quote a value into one complete, self-contained shell token. Unlike the\n * framework's `escapeShellArg` (which only neutralises metacharacters *inside*\n * surrounding double quotes), this wraps in single quotes so the token is safe\n * to splice unquoted — spaces, `;`, `&`, `|`, globs and the rest cannot split\n * the command or inject syntax. Embedded single quotes are closed/escaped/reopened. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n/** The framework-supplied command runner handed to filesystem callbacks. */\ntype CommandRunner = (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\n/** Memory floor (MiB) for the default shape when a create() pins no size. The\n * control plane names no default shape and `CreateSandboxRequest` requires\n * one, so the default is a client policy — the smallest *live* catalog shape\n * with at least this much RAM. Override per-create with `shape`/`config.shape`. */\nconst DEFAULT_SHAPE_MIN_MIB = 1024;\n\n/** POSIX environment variable name. Keys are spliced into a shell `export`, so\n * anything outside this grammar is rejected rather than emitted (injection). */\nconst ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport interface CreateosConfig {\n /** createos-sandbox API key. Falls back to the CREATEOS_SANDBOX_API_KEY env var. */\n apiKey?: string;\n /** Control-plane base URL. Falls back to the CREATEOS_SANDBOX_BASE_URL env\n * var, then the production control plane. */\n baseUrl?: string;\n /** Default shape when create options pin neither `shape` nor cpus/memoryMb. */\n shape?: string;\n /** Default rootfs catalog name or template id. Empty = host default. */\n rootfs?: string;\n /** Reported `getInfo().timeout` in ms. Informational only. */\n timeout?: number;\n}\n\n/** ComputeSDK create options plus the createos-specific fields this provider\n * reads off the (otherwise open) options bag. Declaring them turns the cast-\n * heavy decode into a typed contract and makes unsupported fields obvious. */\nexport interface CreateosCreateOptions extends CreateSandboxOptions {\n /** Explicit shape id. Overrides cpus/memoryMb selection and skips the catalog fetch. */\n shape?: string;\n /** Rootfs catalog name or template id (alias of `runtime`). */\n image?: string;\n /** Rootfs catalog name or template id (alias of `image`). */\n runtime?: string;\n /** Requested RAM; mapped onto the smallest fitting shape. */\n memoryMb?: number;\n /** Requested vCPUs; mapped onto the smallest fitting shape. */\n cpus?: number;\n /** Overlay disk size (MiB). 0 / omitted = the shape's default disk. */\n ephemeralDiskMb?: number;\n /** Enable public ingress. Defaults to false. */\n ingressEnabled?: boolean;\n /** SSH public keys to inject at boot. */\n sshPubkeys?: string[];\n /** Egress allow-list. */\n egress?: string[];\n /** Env vars set at sandbox creation. */\n envs?: Record<string, string>;\n /** Explicit sandbox name (control mints one if omitted). */\n name?: string;\n /** Snapshot id (paused sandbox) to fork from — bypasses cold create. */\n snapshotId?: string;\n}\n\n/** Production control-plane base URL, used when neither `config.baseUrl` nor\n * the CREATEOS_SANDBOX_BASE_URL env var is set. */\nconst DEFAULT_BASE_URL = \"https://api.sb.createos.sh\";\n\nfunction env(key: string): string | undefined {\n return typeof process !== \"undefined\" ? process.env?.[key] : undefined;\n}\n\nfunction resolveClient(config: CreateosConfig): CreateosSandboxClient {\n const apiKey = config.apiKey ?? env(\"CREATEOS_SANDBOX_API_KEY\");\n if (!apiKey) {\n throw new Error(\n \"Missing CreateOS API key. Provide 'apiKey' in config or set the \" +\n \"CREATEOS_SANDBOX_API_KEY environment variable.\",\n );\n }\n // Precedence: explicit config > env var > production default. A blank value\n // is treated as unset so the next source applies.\n const baseUrl =\n config.baseUrl?.trim() || env(\"CREATEOS_SANDBOX_BASE_URL\")?.trim() || DEFAULT_BASE_URL;\n const cacheKey = `${apiKey}\\0${baseUrl}`;\n let client = clientCache.get(cacheKey);\n if (!client) {\n client = new CreateosSandboxClient({ apiKey, baseUrl });\n clientCache.set(cacheKey, client);\n }\n return client;\n}\n\n/** True only for a genuine \"resource does not exist\" (404). Everything else —\n * auth, network, validation, server, rate-limit — is a broken boundary. */\nfunction isNotFound(e: unknown): boolean {\n return e instanceof CreateosSandboxNotFoundError;\n}\n\n/** Sort a catalog by ascending RAM then vCPU. Selection relies on this order;\n * the control plane gives no ordering guarantee for `listShapes()`. */\nfunction sortShapes(shapes: Shape[]): Shape[] {\n return shapes.toSorted((a, b) => a.mem_mib - b.mem_mib || a.vcpu - b.vcpu);\n}\n\n/** Pick the smallest live catalog shape that satisfies the requested cpu/mem.\n * Returns undefined when neither is given (caller applies the default). */\nexport function pickShape(shapes: Shape[], memoryMb?: number, cpus?: number): string | undefined {\n if (memoryMb == null && cpus == null) return undefined;\n const sorted = sortShapes(shapes);\n const fit = sorted.find(\n (s) => (memoryMb == null || s.mem_mib >= memoryMb) && (cpus == null || s.vcpu >= cpus),\n );\n return (fit ?? sorted[sorted.length - 1])?.id;\n}\n\n/** Default shape when create() pins neither `shape` nor cpus/memoryMb: the\n * smallest live shape meeting the RAM floor, else the smallest available. */\nexport function defaultShape(shapes: Shape[]): string | undefined {\n const sorted = sortShapes(shapes);\n const fit = sorted.find((s) => s.mem_mib >= DEFAULT_SHAPE_MIN_MIB);\n return (fit ?? sorted[0])?.id;\n}\n\n/** Cache shapes per client with a 5-minute TTL. */\nconst shapesCache = new WeakMap<CreateosSandboxClient, { shapes: Shape[]; expires: number }>();\nconst SHAPES_CACHE_TTL_MS = 5 * 60 * 1_000;\nconst FALLBACK_SHAPE = \"s-1vcpu-1gb\";\n\n/** Resolve the shape for a create() call. Fetches the live catalog only when\n * no explicit `shape` is pinned, so the explicit path never depends on\n * `/v1/shapes` being reachable. */\nasync function resolveShape(\n client: CreateosSandboxClient,\n opts: CreateosCreateOptions,\n config: CreateosConfig,\n): Promise<string> {\n const explicit = opts.shape ?? config.shape;\n if (explicit) return explicit;\n if (opts.memoryMb == null && opts.cpus == null) return FALLBACK_SHAPE;\n const now = Date.now();\n let entry = shapesCache.get(client);\n if (!entry || entry.expires < now) {\n entry = { shapes: await client.listShapes(), expires: now + SHAPES_CACHE_TTL_MS };\n shapesCache.set(client, entry);\n }\n const picked = pickShape(entry.shapes, opts.memoryMb, opts.cpus) ?? defaultShape(entry.shapes) ?? FALLBACK_SHAPE;\n return picked;\n}\n\n/** Map an createos-sandbox lifecycle state onto ComputeSDK's running|stopped|error. */\nexport function mapStatus(status: SandboxStatus): SandboxInfo[\"status\"] {\n if (status === \"running\") return \"running\";\n if (status === \"error\" || status === \"failed\") return \"error\";\n return \"stopped\";\n}\n\n/** A non-empty env record from `envs` (preferred) or the legacy `env` alias. */\nfunction envsOf(opts: CreateosCreateOptions): Record<string, string> | undefined {\n const envs = opts.envs ?? (opts as { env?: Record<string, string> }).env;\n return envs && Object.keys(envs).length > 0 ? envs : undefined;\n}\n\n/** A string[] when the value is an array, else undefined. */\nfunction strArray(v: unknown): string[] | undefined {\n return Array.isArray(v) ? (v as string[]) : undefined;\n}\n\n/** Pure map: ComputeSDK create options → createos-sandbox fork request body. */\nexport function toForkRequest(opts: CreateosCreateOptions): ForkSandboxRequest {\n const req: ForkSandboxRequest = {\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : false,\n };\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n return req;\n}\n\n/** Pure map: ComputeSDK create options (+ resolved shape/rootfs) → create request. */\nexport function toCreateRequest(\n opts: CreateosCreateOptions,\n shape: string,\n rootfs?: string,\n): CreateSandboxRequest {\n const req: CreateSandboxRequest = {\n shape,\n ingress_enabled: opts.ingressEnabled !== undefined ? Boolean(opts.ingressEnabled) : false,\n };\n if (rootfs) req.rootfs = rootfs;\n if (opts.name) req.name = String(opts.name);\n // Pass the requested overlay-disk size straight through; the control plane\n // validates it (0 / omitted = shape default). No client-side menu.\n if (typeof opts.ephemeralDiskMb === \"number\" && opts.ephemeralDiskMb > 0) {\n req.disk_mib = opts.ephemeralDiskMb;\n }\n const envs = envsOf(opts);\n if (envs) req.envs = envs;\n const ssh = strArray(opts.sshPubkeys);\n if (ssh) req.ssh_pubkeys = ssh;\n const egress = strArray(opts.egress);\n if (egress) req.egress = egress;\n return req;\n}\n\n/** Wrap a command so per-call cwd/env/background work despite the server dropping\n * exec env. Env *keys* are validated before being spliced into `export` —\n * values are shell-quoted, but a malformed key would otherwise be raw shell. */\nexport function buildScript(command: string, options?: RunCommandOptions): string {\n let script = command;\n if (options?.cwd) script = `cd ${shellQuote(options.cwd)} && ${script}`;\n if (options?.env && Object.keys(options.env).length > 0) {\n const exports = Object.entries(options.env)\n .map(([k, v]) => {\n if (!ENV_KEY_RE.test(k)) {\n throw new Error(\n `Invalid environment variable name ${JSON.stringify(k)}: ` +\n `must match ${ENV_KEY_RE.source}.`,\n );\n }\n return `export ${k}=${shellQuote(String(v))}`;\n })\n .join(\"; \");\n script = `${exports}; ${script}`;\n }\n if (options?.background) {\n script = `nohup sh -c ${shellQuote(script)} > /dev/null 2>&1 &`;\n }\n return script;\n}\n\n/** Parse `ls -lA --time-style=+%s` output into ComputeSDK FileEntry rows. */\nexport function parseLsOutput(stdout: string): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split(\"\\n\")) {\n if (!line || line.startsWith(\"total \")) continue;\n const m = line.match(/^(\\S+)\\s+\\d+\\s+\\S+\\s+\\S+\\s+(\\d+)\\s+(\\d+)\\s+(.+)$/);\n if (!m) continue;\n const name = m[4]!.replace(/ -> .*$/, \"\"); // strip symlink target\n entries.push({\n name,\n type: m[1]!.startsWith(\"d\") ? \"directory\" : \"file\",\n size: Number(m[2]),\n modified: new Date(Number(m[3]) * 1000),\n });\n }\n return entries;\n}\n\nexport const createosSandbox = defineProvider<Sandbox, CreateosConfig>({\n name: PROVIDER_NAME,\n methods: {\n sandbox: {\n create: async (config: CreateosConfig, options?: CreateSandboxOptions) => {\n const client = resolveClient(config);\n const opts = (options ?? {}) as CreateosCreateOptions;\n\n // A snapshot id is a paused sandbox: fork it into a fresh sandbox.\n if (opts.snapshotId) {\n const source = await client.getSandbox(opts.snapshotId);\n const forked = await source.fork(toForkRequest(opts));\n // Surface lifecycle failures: a fork that never reaches \"running\"\n // (or hits a terminal state) must not be reported as success.\n await forked.waitUntilRunning();\n sandboxConfig.set(forked, config);\n return { sandbox: forked, sandboxId: forked.id };\n }\n\n const shape = await resolveShape(client, opts, config);\n const rootfs = opts.image ?? opts.runtime ?? config.rootfs ?? \"devbox:1\";\n const sandbox = await client.createSandbox(toCreateRequest(opts, shape, rootfs));\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n },\n\n getById: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(sandboxId);\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n } catch (e) {\n if (isNotFound(e)) return null;\n throw e;\n }\n },\n\n list: async (config: CreateosConfig) => {\n const client = resolveClient(config);\n // No catch: a failed list is a broken boundary, not an empty account.\n const sandboxes = await client.listSandboxes({ limit: 100 });\n return sandboxes.map((sandbox) => {\n sandboxConfig.set(sandbox, config);\n return { sandbox, sandboxId: sandbox.id };\n });\n },\n\n destroy: async (config: CreateosConfig, sandboxId: string) => {\n const client = resolveClient(config);\n try {\n await client.http.request(\n \"DELETE\",\n `/v1/sandboxes/${encodeURIComponent(sandboxId)}`,\n );\n } catch (e) {\n if (isNotFound(e)) return; // already gone; destroy is idempotent\n throw e;\n }\n },\n\n runCommand: async (\n sandbox: Sandbox,\n command: string,\n options?: RunCommandOptions,\n ): Promise<CommandResult> => {\n // `sh -c` (not `bash -lc`): POSIX-portable so bare rootfses without\n // bash still run. buildScript only emits POSIX constructs. Transport /\n // auth errors propagate; a command that ran reports its own exit code.\n const { result, exec_ms } = await sandbox.runCommand(\"sh\", [\n \"-c\",\n buildScript(command, options),\n ]);\n const stderr = result.error ? `${result.stderr}${result.error}` : result.stderr;\n return {\n stdout: result.stdout,\n stderr,\n exitCode: result.exit_code,\n durationMs: exec_ms,\n };\n },\n\n getInfo: async (sandbox: Sandbox): Promise<SandboxInfo> => {\n // Refresh failures propagate (no swallow): a getInfo that cannot reach\n // the control plane must surface that rather than return stale data.\n await sandbox.refresh();\n const v = sandbox.data;\n return {\n id: v.id,\n provider: PROVIDER_NAME,\n status: mapStatus(v.status),\n createdAt: new Date(v.created_at),\n timeout: sandboxConfig.get(sandbox)?.timeout ?? 0,\n metadata: {\n createosStatus: v.status,\n shape: v.shape,\n rootfs: v.rootfs,\n region: v.region,\n ip: v.ip,\n ingressEnabled: v.ingress_enabled,\n },\n };\n },\n\n getUrl: async (sandbox: Sandbox, options: { port: number; protocol?: string }) => {\n const scheme = options.protocol === \"http\" ? \"http\" : \"https\";\n return sandbox.previewUrl(options.port, { scheme });\n },\n\n // Escape hatch: the bare native @nodeops-createos/sandbox handle\n // (pause/resume/fork/disks/...).\n getInstance: (sandbox: Sandbox): Sandbox => sandbox,\n\n filesystem: {\n readFile: async (sandbox: Sandbox, path: string): Promise<string> => {\n const buf = await sandbox.files.download(path);\n return new TextDecoder().decode(buf);\n },\n writeFile: async (sandbox: Sandbox, path: string, content: string): Promise<void> => {\n await sandbox.files.upload(path, content);\n },\n mkdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `mkdir -p ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`mkdir ${path} failed: ${r.stderr}`);\n },\n readdir: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const r = await runCommand(sandbox, `ls -lA --time-style=+%s ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`readdir ${path} failed: ${r.stderr}`);\n return parseLsOutput(r.stdout);\n },\n exists: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const r = await runCommand(sandbox, `test -e ${shellQuote(path)}`);\n return r.exitCode === 0;\n },\n remove: async (sandbox: Sandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const r = await runCommand(sandbox, `rm -rf ${shellQuote(path)}`);\n if (r.exitCode !== 0) throw new Error(`remove ${path} failed: ${r.stderr}`);\n },\n },\n },\n\n snapshot: {\n create: async (\n config: CreateosConfig,\n sandboxId: string,\n options?: CreateSnapshotOptions,\n ) => {\n const client = resolveClient(config);\n const sandbox = await client.getSandbox(sandboxId);\n // createos-sandbox has no decoupled snapshot object: pausing IS the snapshot,\n // and the paused sandbox id is the snapshot id. This stops the source VM.\n await sandbox.pause();\n // The success claim is \"it paused\" — surface a pause that timed out or\n // entered a terminal state rather than returning a phantom snapshot.\n await sandbox.waitUntilPaused();\n return {\n id: sandboxId,\n provider: PROVIDER_NAME,\n createdAt: new Date(),\n metadata: { name: options?.name, ...options?.metadata },\n };\n },\n list: async (config: CreateosConfig, _options?: ListSnapshotsOptions) => {\n const client = resolveClient(config);\n // The typed status filter excludes \"paused\", so list all and filter.\n const all = await client.listSandboxes({ limit: 500 });\n return all\n .filter((s) => s.status === \"paused\")\n .map((s) => ({\n id: s.id,\n provider: PROVIDER_NAME,\n createdAt: new Date(s.data.paused_at ?? s.data.created_at),\n }));\n },\n delete: async (config: CreateosConfig, snapshotId: string) => {\n const client = resolveClient(config);\n try {\n const sandbox = await client.getSandbox(snapshotId);\n await sandbox.destroy();\n } catch (e) {\n if (isNotFound(e)) return; // already gone\n throw e;\n }\n },\n },\n },\n});\n\nexport type { Sandbox as CreateosSandbox } from \"@nodeops-createos/sandbox\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@computesdk/createos-sandbox",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "CreateOS provider for ComputeSDK — NodeOps VM sandboxes with pause/resume/fork snapshots",
|
|
5
5
|
"author": "NodeOps Inc.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -21,8 +21,8 @@
|
|
|
21
21
|
"dist"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@nodeops-createos/sandbox": "^0.
|
|
25
|
-
"@computesdk/provider": "2.1.
|
|
24
|
+
"@nodeops-createos/sandbox": "^0.7.1",
|
|
25
|
+
"@computesdk/provider": "2.1.4"
|
|
26
26
|
},
|
|
27
27
|
"keywords": [
|
|
28
28
|
"code-execution",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"typescript": "^5.0.0",
|
|
53
53
|
"vitest": "^1.0.0",
|
|
54
54
|
"@computesdk/test-utils": "2.0.0",
|
|
55
|
-
"computesdk": "4.1.
|
|
55
|
+
"computesdk": "4.1.4"
|
|
56
56
|
},
|
|
57
57
|
"scripts": {
|
|
58
58
|
"build": "tsup",
|