@computesdk/kosa8 1.0.4 → 1.0.6

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.mjs CHANGED
@@ -1,6 +1,468 @@
1
1
  // src/index.ts
2
+ import { defineProvider, escapeShellArg as escapeShellArg2, ShellFileSystem } from "@computesdk/provider";
3
+
4
+ // src/transport.ts
5
+ var nativeFetch = typeof fetch === "function" ? fetch : void 0;
6
+ var http2Load;
7
+ function loadHttp2() {
8
+ http2Load ?? (http2Load = import("http2").then(
9
+ (m) => m.default ?? m,
10
+ () => null
11
+ ));
12
+ return http2Load;
13
+ }
14
+ var origins = /* @__PURE__ */ new Map();
15
+ var inFlight = /* @__PURE__ */ new WeakMap();
16
+ var retired = /* @__PURE__ */ new WeakSet();
17
+ function hold(s) {
18
+ inFlight.set(s, (inFlight.get(s) ?? 0) + 1);
19
+ s.ref();
20
+ }
21
+ function release(s) {
22
+ const n = (inFlight.get(s) ?? 1) - 1;
23
+ inFlight.set(s, n);
24
+ if (n > 0 || s.destroyed) return;
25
+ if (retired.has(s)) s.close();
26
+ else s.unref();
27
+ }
28
+ function abortError(signal) {
29
+ return signal.reason ?? new Error("The operation was aborted");
30
+ }
31
+ function untilAborted(p, signal) {
32
+ if (!signal) return p;
33
+ if (signal.aborted) return Promise.reject(abortError(signal));
34
+ return new Promise((resolve, reject) => {
35
+ const onAbort = () => reject(abortError(signal));
36
+ signal.addEventListener("abort", onAbort, { once: true });
37
+ p.then(
38
+ (v) => {
39
+ signal.removeEventListener("abort", onAbort);
40
+ resolve(v);
41
+ },
42
+ (e) => {
43
+ signal.removeEventListener("abort", onAbort);
44
+ reject(e);
45
+ }
46
+ );
47
+ });
48
+ }
49
+ var WINDOW_BYTES = 16 * 1024 * 1024;
50
+ var SESSION_WINDOW_BYTES = 64 * 1024 * 1024;
51
+ var CONNECT_TIMEOUT_MS = 1e4;
52
+ function mode() {
53
+ const m = typeof process !== "undefined" ? process.env?.KOSA8_HTTP_TRANSPORT : void 0;
54
+ return m === "fetch" || m === "http2" ? m : "auto";
55
+ }
56
+ function originOf(url) {
57
+ try {
58
+ const u = new URL(url);
59
+ if (u.protocol === "https:") return u.origin;
60
+ const loopback = u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "[::1]";
61
+ return u.protocol === "http:" && loopback && mode() === "http2" ? u.origin : null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ function useHttp2() {
67
+ if (typeof process === "undefined" || !process.versions?.node) return false;
68
+ const m = mode();
69
+ if (m === "fetch") return false;
70
+ return m === "http2" || typeof fetch === "function" && fetch === nativeFetch;
71
+ }
72
+ function session(origin) {
73
+ let o = origins.get(origin);
74
+ if (!o) {
75
+ o = {};
76
+ origins.set(origin, o);
77
+ }
78
+ if (o.failed) return Promise.resolve(null);
79
+ if (o.session) return o.session;
80
+ const entry = o;
81
+ const opening = loadHttp2().then((http2) => {
82
+ if (!http2) {
83
+ entry.failed = true;
84
+ return null;
85
+ }
86
+ return new Promise((resolve) => {
87
+ let settled = false;
88
+ const s = http2.connect(origin, { settings: { initialWindowSize: WINDOW_BYTES } });
89
+ const timer = setTimeout(() => {
90
+ if (settled) return;
91
+ settled = true;
92
+ entry.failed = true;
93
+ s.destroy();
94
+ resolve(null);
95
+ }, CONNECT_TIMEOUT_MS);
96
+ timer.unref?.();
97
+ const forget = () => {
98
+ if (entry.session === opening) entry.session = void 0;
99
+ };
100
+ s.once("connect", () => {
101
+ if (settled) return;
102
+ settled = true;
103
+ clearTimeout(timer);
104
+ try {
105
+ s.setLocalWindowSize(SESSION_WINDOW_BYTES);
106
+ } catch {
107
+ }
108
+ if (!inFlight.get(s)) s.unref();
109
+ resolve(s);
110
+ });
111
+ s.on("error", () => {
112
+ forget();
113
+ if (!settled) {
114
+ settled = true;
115
+ clearTimeout(timer);
116
+ entry.failed = true;
117
+ resolve(null);
118
+ }
119
+ });
120
+ s.once("goaway", () => {
121
+ forget();
122
+ retired.add(s);
123
+ if (!inFlight.get(s)) s.close();
124
+ });
125
+ s.once("close", forget);
126
+ });
127
+ });
128
+ entry.session = opening;
129
+ return opening;
130
+ }
131
+ function preconnect(url) {
132
+ const origin = originOf(url);
133
+ if (!origin || !useHttp2()) return;
134
+ void session(origin);
135
+ }
136
+ async function viaFetch(url, init) {
137
+ const res = await fetch(url, {
138
+ method: init.method,
139
+ headers: init.headers,
140
+ // A Uint8Array body is sent as its bytes (BodyInit types leave out views over a SharedArrayBuffer).
141
+ body: init.body,
142
+ signal: init.signal
143
+ });
144
+ const headers = {};
145
+ res.headers?.forEach?.((v, k) => headers[k.toLowerCase()] = v);
146
+ if (init.binary) {
147
+ return { status: res.status, ok: res.ok, text: "", bytes: new Uint8Array(await res.arrayBuffer()), headers };
148
+ }
149
+ return { status: res.status, ok: res.ok, text: await res.text(), headers };
150
+ }
151
+ async function httpRequest(url, init) {
152
+ const origin = originOf(url);
153
+ if (!origin || !useHttp2()) return viaFetch(url, init);
154
+ const s = await untilAborted(session(origin), init.signal);
155
+ if (!s || s.closed || s.destroyed) return viaFetch(url, init);
156
+ hold(s);
157
+ try {
158
+ return await viaSession(s, url, init);
159
+ } catch (e) {
160
+ if (notProcessed(e) && !init.signal?.aborted) return await viaFetch(url, init);
161
+ throw e;
162
+ } finally {
163
+ release(s);
164
+ }
165
+ }
166
+ function notProcessed(e) {
167
+ const x = e;
168
+ return !!x && (x.code === "ERR_HTTP2_GOAWAY_SESSION" || x.code === "ERR_HTTP2_INVALID_SESSION" || x.rstCode === 7);
169
+ }
170
+ function viaSession(s, url, init) {
171
+ const u = new URL(url);
172
+ return new Promise((resolve, reject) => {
173
+ const headers = {
174
+ ":method": init.method,
175
+ ":path": u.pathname + u.search
176
+ };
177
+ for (const [k, v] of Object.entries(init.headers)) headers[k.toLowerCase()] = v;
178
+ let req;
179
+ try {
180
+ req = s.request(headers);
181
+ } catch (e) {
182
+ reject(e);
183
+ return;
184
+ }
185
+ let done = false;
186
+ const finish = (f) => {
187
+ if (done) return;
188
+ done = true;
189
+ init.signal?.removeEventListener("abort", onAbort);
190
+ f();
191
+ };
192
+ const aborted = () => init.signal ? abortError(init.signal) : new Error("The operation was aborted");
193
+ const onAbort = () => {
194
+ finish(() => reject(aborted()));
195
+ req.close(8);
196
+ };
197
+ if (init.signal) {
198
+ if (init.signal.aborted) {
199
+ onAbort();
200
+ return;
201
+ }
202
+ init.signal.addEventListener("abort", onAbort, { once: true });
203
+ }
204
+ const chunks = [];
205
+ let status = 0;
206
+ const got = {};
207
+ req.on("response", (h) => {
208
+ status = Number(h[":status"] ?? 0);
209
+ for (const [k, v] of Object.entries(h)) if (!k.startsWith(":") && v !== void 0) got[k] = String(v);
210
+ });
211
+ req.on("data", (c) => chunks.push(c));
212
+ let ended = false;
213
+ req.on("end", () => {
214
+ ended = !s.destroyed;
215
+ });
216
+ req.on("close", () => {
217
+ if (status !== 0 && ended && !req.rstCode) {
218
+ const body = Buffer.concat(chunks);
219
+ finish(
220
+ () => resolve({
221
+ status,
222
+ ok: status >= 200 && status < 300,
223
+ text: init.binary ? "" : body.toString("utf8"),
224
+ ...init.binary ? { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) } : {},
225
+ headers: got
226
+ })
227
+ );
228
+ return;
229
+ }
230
+ const why = status === 0 ? "without a response" : "before the response completed";
231
+ finish(() => reject(new Error(`kosa8: the HTTP/2 stream closed ${why}`)));
232
+ });
233
+ req.on(
234
+ "error",
235
+ (e) => finish(() => reject(init.signal?.aborted ? aborted() : Object.assign(e, { rstCode: req.rstCode })))
236
+ );
237
+ req.end(init.body);
238
+ });
239
+ }
240
+
241
+ // src/files.ts
2
242
  import { randomBytes } from "crypto";
3
- import { defineProvider, escapeShellArg, ShellFileSystem } from "@computesdk/provider";
243
+ import { escapeShellArg } from "@computesdk/provider";
244
+ var fileParts = { bytes: 64 * 1024 * 1024, concurrency: 4, writeConcurrency: 2 };
245
+ var FILE_RETRIES = 2;
246
+ var RETRY_STATUS = /* @__PURE__ */ new Set([500, 502, 503, 504]);
247
+ var DIRECT_REFUSED = /* @__PURE__ */ new Set([401, 409, 501, 521, 522, 523, 530]);
248
+ var WRITE_CHUNK_CHARS = 48 * 1024;
249
+ var INLINE_READ_BYTES = 1024 * 1024;
250
+ var NOT_FOUND_EXIT = 44;
251
+ var MIB = 1024 * 1024;
252
+ var q = (s) => `"${escapeShellArg(s)}"`;
253
+ var notFound = (path) => new Error(`ENOENT: no such file or directory, open '${path}'`);
254
+ var apiTarget = (sandbox) => ({
255
+ url: `${sandbox.baseUrl}/v1/sandboxes/${encodeURIComponent(sandbox.id)}/files`,
256
+ token: sandbox.apiKey
257
+ });
258
+ function errorDetail(res) {
259
+ const text = res.text || (res.bytes ? Buffer.from(res.bytes).toString("utf8") : "");
260
+ try {
261
+ const parsed = JSON.parse(text);
262
+ if (parsed && (parsed.error || parsed.message)) return [parsed.error, parsed.message].filter(Boolean).join(": ");
263
+ } catch {
264
+ }
265
+ return text.slice(0, 500);
266
+ }
267
+ function fileError(res, op, path) {
268
+ const detail = errorDetail(res);
269
+ if (res.status === 404) return notFound(path);
270
+ if (res.status === 403) return new Error(`EACCES: permission denied, ${op} '${path}'${detail ? `: ${detail}` : ""}`);
271
+ if (res.status === 507) return new Error(`ENOSPC: no space left on device, ${op} '${path}'${detail ? `: ${detail}` : ""}`);
272
+ return new Error(`kosa8 file ${op} '${path}' failed (${res.status})${detail ? `: ${detail}` : ""}`);
273
+ }
274
+ function olderFileApi(res) {
275
+ return res.status === 413 || res.status === 501 || res.status === 400 && /workspace/i.test(errorDetail(res));
276
+ }
277
+ async function send(t, method, path, { body, offset, range } = {}) {
278
+ const url = `${t.url}?path=${encodeURIComponent(path)}${offset ? `&offset=${offset}` : ""}`;
279
+ const headers = { Authorization: `Bearer ${t.token}` };
280
+ if (body) headers["Content-Type"] = "application/octet-stream";
281
+ if (range) headers.Range = `bytes=${range[0]}-${range[1]}`;
282
+ for (let attempt = 0; ; attempt++) {
283
+ try {
284
+ const res = await httpRequest(url, { method, headers, body, binary: true });
285
+ if (!RETRY_STATUS.has(res.status) || attempt >= FILE_RETRIES) return res;
286
+ } catch (err) {
287
+ if (attempt >= FILE_RETRIES) throw err;
288
+ }
289
+ await new Promise((r) => setTimeout(r, 250 * (attempt + 1)));
290
+ }
291
+ }
292
+ async function inParallel(items, limit, task) {
293
+ let next = 0;
294
+ let failed = null;
295
+ let thrown;
296
+ const worker = async () => {
297
+ while (!failed && !thrown && next < items.length) {
298
+ try {
299
+ const r = await task(items[next++]);
300
+ if (r) failed ?? (failed = r);
301
+ } catch (err) {
302
+ thrown ?? (thrown = { err });
303
+ }
304
+ }
305
+ };
306
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
307
+ if (thrown) throw thrown.err;
308
+ return failed;
309
+ }
310
+ async function writeTo(t, path, bytes) {
311
+ const first = await send(t, "PUT", path, { body: bytes.subarray(0, fileParts.bytes) });
312
+ if (!first.ok) return first;
313
+ const offsets = [];
314
+ for (let at = fileParts.bytes; at < bytes.length; at += fileParts.bytes) offsets.push(at);
315
+ return inParallel(offsets, fileParts.writeConcurrency, async (at) => {
316
+ const res = await send(t, "PUT", path, { body: bytes.subarray(at, at + fileParts.bytes), offset: at });
317
+ return res.ok ? null : res;
318
+ });
319
+ }
320
+ async function readFrom(t, path) {
321
+ const first = await send(t, "GET", path, { range: [0, fileParts.bytes - 1] });
322
+ if (first.status === 416) return new Uint8Array();
323
+ if (first.status === 200) return first.bytes ?? new Uint8Array();
324
+ if (first.status !== 206) return first;
325
+ const head = first.bytes ?? new Uint8Array();
326
+ const total = Number(/\/(\d+)\s*$/.exec(first.headers["content-range"] ?? "")?.[1] ?? head.length);
327
+ if (total <= head.length) return head;
328
+ const starts = [];
329
+ for (let at = head.length; at < total; at += fileParts.bytes) starts.push(at);
330
+ const parts = /* @__PURE__ */ new Map();
331
+ const failed = await inParallel(starts, fileParts.concurrency, async (at) => {
332
+ const res = await send(t, "GET", path, { range: [at, Math.min(total, at + fileParts.bytes) - 1] });
333
+ if (res.status !== 206 && res.status !== 200) return res;
334
+ parts.set(at, res.bytes ?? new Uint8Array());
335
+ return null;
336
+ });
337
+ if (failed) return failed;
338
+ const all = Buffer.concat([head, ...starts.map((at) => parts.get(at))]);
339
+ if (all.length !== total) {
340
+ throw new Error(`open '${path}' failed: read ${all.length} of ${total} bytes (the file changed while it was read?)`);
341
+ }
342
+ return all;
343
+ }
344
+ async function writeFileNative(sandbox, path, content, run, direct = null) {
345
+ const bytes = Buffer.from(content, "utf8");
346
+ const staged = bytes.length > fileParts.bytes ? `${path}.computesdk-${randomBytes(6).toString("hex")}` : null;
347
+ const dest = staged ?? path;
348
+ const commit = async () => {
349
+ if (staged) {
350
+ await mustSucceed(
351
+ run,
352
+ sandbox,
353
+ `if [ -d ${q(path)} ]; then echo 'target is a directory' >&2; exit 1; fi; mv -f ${q(staged)} ${q(path)}`,
354
+ "write",
355
+ path
356
+ );
357
+ }
358
+ };
359
+ try {
360
+ if (direct) {
361
+ const res = await writeTo(direct, dest, bytes).catch(() => void 0);
362
+ if (res === null) {
363
+ await commit();
364
+ return;
365
+ }
366
+ if (res && !DIRECT_REFUSED.has(res.status)) throw fileError(res, "write", path);
367
+ if (res && (res.status === 401 || res.status === 501)) sandbox.directFiles = false;
368
+ }
369
+ if (sandbox.files !== false) {
370
+ const res = await writeTo(apiTarget(sandbox), dest, bytes);
371
+ if (!res) {
372
+ await commit();
373
+ return;
374
+ }
375
+ if (!olderFileApi(res)) throw fileError(res, "write", path);
376
+ if (res.status === 501) sandbox.files = false;
377
+ }
378
+ return writeFileViaExec(sandbox, path, bytes, run);
379
+ } finally {
380
+ if (staged) await run(sandbox, `rm -f ${q(staged)}`).catch(() => {
381
+ });
382
+ }
383
+ }
384
+ async function mustSucceed(run, sandbox, command, what, path, env) {
385
+ const result = await run(sandbox, command, env ? { env } : void 0);
386
+ if (result.exitCode === NOT_FOUND_EXIT) throw notFound(path);
387
+ if (result.exitCode !== 0) {
388
+ const detail = (result.stderr || result.stdout).trim();
389
+ throw new Error(`${what} '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`);
390
+ }
391
+ if (result.stdoutTruncated) {
392
+ throw new Error(`${what} '${path}' failed: the command's output was cut off at the exec API's limit`);
393
+ }
394
+ return result.stdout;
395
+ }
396
+ async function writeFileViaExec(sandbox, path, content, run) {
397
+ const target = q(path);
398
+ const tmp = q(`${path}.computesdk-${randomBytes(6).toString("hex")}`);
399
+ const encoded = Buffer.from(content).toString("base64");
400
+ const mkParent = `d=$(dirname ${target}) && mkdir -p "$d"`;
401
+ if (encoded.length <= WRITE_CHUNK_CHARS) {
402
+ const cmd = `${mkParent} && printf '%s' "$KOSA8_CHUNK" | base64 -d > ${tmp} && mv -f ${tmp} ${target} || { s=$?; rm -f ${tmp}; exit $s; }`;
403
+ await mustSucceed(run, sandbox, cmd, "write", path, { KOSA8_CHUNK: encoded });
404
+ return;
405
+ }
406
+ try {
407
+ await mustSucceed(run, sandbox, `${mkParent} && : > ${tmp}`, "write", path);
408
+ for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) {
409
+ await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, "write", path, {
410
+ KOSA8_CHUNK: encoded.slice(i, i + WRITE_CHUNK_CHARS)
411
+ });
412
+ }
413
+ await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, "write", path);
414
+ } catch (err) {
415
+ await run(sandbox, `rm -f ${tmp}`).catch(() => {
416
+ });
417
+ throw err;
418
+ }
419
+ }
420
+ var fromBase64 = (s) => Buffer.from(s.replace(/\s+/g, ""), "base64");
421
+ async function readFileNative(sandbox, path, run, direct = null) {
422
+ if (direct) {
423
+ const got = await readFrom(direct, path).catch(() => void 0);
424
+ if (got instanceof Uint8Array) return Buffer.from(got).toString("utf8");
425
+ if (got && !DIRECT_REFUSED.has(got.status)) throw fileError(got, "open", path);
426
+ if (got && (got.status === 401 || got.status === 501)) sandbox.directFiles = false;
427
+ }
428
+ if (sandbox.files !== false) {
429
+ const got = await readFrom(apiTarget(sandbox), path);
430
+ if (got instanceof Uint8Array) return Buffer.from(got).toString("utf8");
431
+ if (!olderFileApi(got)) throw fileError(got, "open", path);
432
+ if (got.status === 501) sandbox.files = false;
433
+ }
434
+ return readFileViaExec(sandbox, path, run);
435
+ }
436
+ async function readFileViaExec(sandbox, path, run) {
437
+ const p = q(path);
438
+ const out = await mustSucceed(
439
+ run,
440
+ sandbox,
441
+ `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; s=$(wc -c < ${p} | tr -d ' ') || exit $?; echo "$s"; if [ "$s" -le ${INLINE_READ_BYTES} ]; then base64 < ${p}; fi`,
442
+ "open",
443
+ path
444
+ );
445
+ const nl = out.indexOf("\n");
446
+ const size = Number(out.slice(0, nl < 0 ? void 0 : nl).trim());
447
+ if (!Number.isInteger(size) || size < 0) throw new Error(`open '${path}' failed: unexpected answer from the sandbox`);
448
+ if (size <= INLINE_READ_BYTES) return fromBase64(nl < 0 ? "" : out.slice(nl + 1)).toString("utf8");
449
+ const chunks = new Array(Math.ceil(size / INLINE_READ_BYTES));
450
+ let next = 0;
451
+ const worker = async () => {
452
+ while (next < chunks.length) {
453
+ const i = next++;
454
+ chunks[i] = fromBase64(
455
+ await mustSucceed(run, sandbox, `[ -f ${p} ] || exit ${NOT_FOUND_EXIT}; dd if=${p} bs=${MIB} skip=${i} count=1 2>/dev/null | base64`, "open", path)
456
+ );
457
+ }
458
+ };
459
+ await Promise.all(Array.from({ length: Math.min(fileParts.concurrency, chunks.length) }, worker));
460
+ const all = Buffer.concat(chunks);
461
+ if (all.length !== size) throw new Error(`open '${path}' failed: read ${all.length} of ${size} bytes (the file changed while it was read?)`);
462
+ return all.toString("utf8");
463
+ }
464
+
465
+ // src/index.ts
4
466
  var MIN_TTL_S = 60;
5
467
  var MAX_TTL_S = 90 * 86400;
6
468
  var TIMEOUT_EXIT = 124;
@@ -17,11 +479,10 @@ var UNSUPPORTED_CREATE_OPTIONS = [
17
479
  "memoryMb",
18
480
  "diskMb",
19
481
  "diskMiB",
20
- "image",
21
- "snapshotId",
22
482
  "envs",
23
483
  "volumes"
24
484
  ];
485
+ var SNAPSHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
25
486
  function resolveConfig(config) {
26
487
  const env = typeof process !== "undefined" ? process.env : void 0;
27
488
  const apiKey = config.apiKey || env?.KOSA8_API_KEY || "";
@@ -34,7 +495,7 @@ function resolveConfig(config) {
34
495
  return { apiKey, baseUrl };
35
496
  }
36
497
  async function request(auth, method, path, body, signal) {
37
- const res = await fetch(`${auth.baseUrl}${path}`, {
498
+ const res = await httpRequest(`${auth.baseUrl}${path}`, {
38
499
  method,
39
500
  headers: {
40
501
  Authorization: `Bearer ${auth.apiKey}`,
@@ -44,7 +505,7 @@ async function request(auth, method, path, body, signal) {
44
505
  signal
45
506
  });
46
507
  if (res.status === 404) return null;
47
- const text = await res.text();
508
+ const text = res.text;
48
509
  if (!res.ok) {
49
510
  let detail = text;
50
511
  try {
@@ -57,23 +518,93 @@ async function request(auth, method, path, body, signal) {
57
518
  return text ? JSON.parse(text) : null;
58
519
  }
59
520
  var sandboxPath = (id, rest = "") => `/v1/sandboxes/${encodeURIComponent(id)}${rest}`;
60
- function toSandbox(auth, data) {
61
- return { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };
521
+ function toSandbox(auth, data, direct) {
522
+ const sandbox = { id: data.id, data, apiKey: auth.apiKey, baseUrl: auth.baseUrl };
523
+ if (isDirect(direct)) {
524
+ sandbox.direct = direct;
525
+ preconnect(direct.exec_url);
526
+ }
527
+ return sandbox;
528
+ }
529
+ function isDirect(d) {
530
+ const x = d;
531
+ return !!x && typeof x.exec_url === "string" && /^https:\/\//.test(x.exec_url) && typeof x.token === "string" && typeof x.expires_at === "number";
532
+ }
533
+ var DIRECT_MARGIN_MS = 15e3;
534
+ var DIRECT_REFRESH_MS = 6e4;
535
+ var DIRECT_NOT_RUN = /* @__PURE__ */ new Set([401, 403, 404, 409, 501, 521, 522, 523, 530]);
536
+ function directFiles(sandbox) {
537
+ const d = sandbox.direct;
538
+ if (!d?.files_url || sandbox.directFiles === false || !/^https:\/\//.test(d.files_url)) return null;
539
+ const left = d.expires_at - Date.now();
540
+ if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);
541
+ return left < DIRECT_MARGIN_MS ? null : { url: d.files_url, token: d.token };
542
+ }
543
+ function refreshDirect(sandbox) {
544
+ if (sandbox.refreshing) return;
545
+ sandbox.refreshing = request(sandbox, "POST", sandboxPath(sandbox.id, "/direct")).then((r) => {
546
+ if (isDirect(r?.direct)) sandbox.direct = r.direct;
547
+ }).catch(() => {
548
+ }).finally(() => {
549
+ sandbox.refreshing = void 0;
550
+ });
551
+ }
552
+ async function runDirect(sandbox, body, signal) {
553
+ const d = sandbox.direct;
554
+ if (!d) return null;
555
+ const left = d.expires_at - Date.now();
556
+ if (left < DIRECT_REFRESH_MS) refreshDirect(sandbox);
557
+ if (left < DIRECT_MARGIN_MS) return null;
558
+ const res = await httpRequest(d.exec_url, {
559
+ method: "POST",
560
+ headers: { Authorization: `Bearer ${d.token}`, "Content-Type": "application/json" },
561
+ body: JSON.stringify(body),
562
+ signal
563
+ });
564
+ const text = res.text;
565
+ if (DIRECT_NOT_RUN.has(res.status)) {
566
+ if (sandbox.direct === d) sandbox.direct = void 0;
567
+ return null;
568
+ }
569
+ if (!res.ok) {
570
+ let detail = text;
571
+ try {
572
+ const parsed = JSON.parse(text);
573
+ if (parsed?.error) detail = parsed.error;
574
+ } catch {
575
+ }
576
+ throw new Error(`kosa8 host error (${res.status}) on exec in ${sandbox.id}: ${detail}`);
577
+ }
578
+ return JSON.parse(text);
62
579
  }
63
580
  function createBody(config, options = {}) {
64
581
  for (const key of UNSUPPORTED_CREATE_OPTIONS) {
65
582
  if (options[key] !== void 0) {
66
583
  throw new Error(
67
- `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()).`
584
+ `kosa8 does not support the '${key}' create option. A sandbox's size and image come from its template; pick one with 'templateId' (list them with provider.template.list()), or boot an OCI image with 'image'.`
68
585
  );
69
586
  }
70
587
  }
71
588
  const body = {};
72
589
  const env = typeof process !== "undefined" ? process.env : void 0;
73
- const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
74
- if (template) body.template = template;
75
- const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
76
- if (region) body.region = region;
590
+ if (options.snapshotId !== void 0) {
591
+ for (const key of ["templateId", "image", "region"]) {
592
+ if (options[key] !== void 0) {
593
+ throw new Error(`kosa8 restores a snapshot with its own template, image and region; leave out '${key}' with 'snapshotId'.`);
594
+ }
595
+ }
596
+ body.snapshot = options.snapshotId;
597
+ } else if (options.image !== void 0) {
598
+ body.image = options.image;
599
+ if (options.templateId) body.template = options.templateId;
600
+ } else {
601
+ const template = options.templateId ?? config.template ?? (env?.KOSA8_TEMPLATE || void 0);
602
+ if (template) body.template = template;
603
+ }
604
+ if (options.snapshotId === void 0) {
605
+ const region = typeof options.region === "string" ? options.region : config.region ?? (env?.KOSA8_REGION || void 0);
606
+ if (region) body.region = region;
607
+ }
77
608
  if (options.sleepAfterSeconds !== void 0) body.sleep_after_s = options.sleepAfterSeconds;
78
609
  if (typeof options.timeout === "number" && options.timeout > 0) {
79
610
  body.ttl_s = Math.min(MAX_TTL_S, Math.max(MIN_TTL_S, Math.ceil(options.timeout / 1e3)));
@@ -82,13 +613,13 @@ function createBody(config, options = {}) {
82
613
  }
83
614
  function execArgv(command, options) {
84
615
  let cmd = command;
85
- if (options?.cwd) cmd = `cd "${escapeShellArg(options.cwd)}" && ${cmd}`;
616
+ if (options?.cwd) cmd = `cd "${escapeShellArg2(options.cwd)}" && ${cmd}`;
86
617
  if (options?.background) {
87
- cmd = `nohup sh -c "${escapeShellArg(cmd)}" >/dev/null 2>&1 &`;
618
+ cmd = `nohup sh -c "${escapeShellArg2(cmd)}" >/dev/null 2>&1 &`;
88
619
  } else if (options?.timeout && options.timeout > 0) {
89
620
  const seconds = Math.max(1, Math.ceil(options.timeout / 1e3));
90
- const plain = `sh -c "${escapeShellArg(cmd)}"`;
91
- const marked = `sh -c "${escapeShellArg(`(
621
+ const plain = `sh -c "${escapeShellArg2(cmd)}"`;
622
+ const marked = `sh -c "${escapeShellArg2(`(
92
623
  ${cmd}
93
624
  ); s=$?; : > "$${DONE_ENV}"; exit $s`)}"`;
94
625
  cmd = `if command -v timeout >/dev/null 2>&1 && ${DONE_ENV}=$(mktemp 2>/dev/null); then rm -f "$${DONE_ENV}"; export ${DONE_ENV}; t0=$(date +%s); timeout -s KILL ${seconds} ${marked}; s=$?; if [ $s -eq 137 ] && [ ! -e "$${DONE_ENV}" ] && [ $(( $(date +%s) - t0 )) -ge ${seconds} ]; then s=${TIMEOUT_EXIT}; fi; rm -f "$${DONE_ENV}"; exit $s; else ${plain}; fi`;
@@ -122,42 +653,67 @@ function execEnv(env) {
122
653
  }
123
654
  function infoStatus(state) {
124
655
  if (state === "error") return "error";
125
- if (state === "running") return "running";
656
+ if (state === "running" || state === "sleeping") return "running";
126
657
  return "stopped";
127
658
  }
128
659
  async function getData(sandbox) {
129
660
  const data = await request(sandbox, "GET", sandboxPath(sandbox.id));
130
661
  return data?.sandbox ?? null;
131
662
  }
132
- var WRITE_CHUNK_CHARS = 32 * 1024;
133
- var shellFs = (sandbox, run) => new ShellFileSystem((command, options) => run(sandbox, command, options));
134
- async function mustSucceed(run, sandbox, command, path, env) {
135
- const result = await run(sandbox, command, env ? { env } : void 0);
136
- if (result.exitCode !== 0) {
137
- const detail = (result.stderr || result.stdout).trim();
138
- throw new Error(`write '${path}' failed (exit ${result.exitCode})${detail ? `: ${detail}` : ""}`);
663
+ var BOOT_POLL_MS = 150;
664
+ var BOOT_TIMEOUT_MS = 5 * 6e4;
665
+ async function waitUntilRunning(sandbox, signal) {
666
+ const deadline = Date.now() + BOOT_TIMEOUT_MS;
667
+ while (sandbox.data.state === "creating") {
668
+ if (Date.now() > deadline) throw new Error(`kosa8 sandbox ${sandbox.id} did not start within ${BOOT_TIMEOUT_MS / 1e3} s`);
669
+ signal?.throwIfAborted();
670
+ await new Promise((r) => setTimeout(r, BOOT_POLL_MS));
671
+ const current = await request(sandbox, "GET", sandboxPath(sandbox.id), void 0, signal);
672
+ if (!current?.sandbox) throw new Error(`kosa8 sandbox ${sandbox.id} was deleted while it started`);
673
+ sandbox.data = current.sandbox;
139
674
  }
140
- }
141
- async function writeFileViaExec(sandbox, path, content, run) {
142
- const target = `"${escapeShellArg(path)}"`;
143
- const tmp = `"${escapeShellArg(`${path}.computesdk-${randomBytes(6).toString("hex")}`)}"`;
144
- const encoded = Buffer.from(content, "utf8").toString("base64");
145
- const chunks = [];
146
- for (let i = 0; i < encoded.length; i += WRITE_CHUNK_CHARS) chunks.push(encoded.slice(i, i + WRITE_CHUNK_CHARS));
147
- try {
148
- await mustSucceed(run, sandbox, `d=$(dirname ${target}) && mkdir -p "$d" && : > ${tmp}`, path);
149
- for (const chunk of chunks) {
150
- await mustSucceed(run, sandbox, `printf '%s' "$KOSA8_CHUNK" | base64 -d >> ${tmp}`, path, { KOSA8_CHUNK: chunk });
675
+ if (sandbox.data.state !== "running") {
676
+ const why = sandbox.data.last_error ? `: ${sandbox.data.last_error}` : "";
677
+ throw new Error(`kosa8 sandbox ${sandbox.id} is ${sandbox.data.state}, not running${why}`);
678
+ }
679
+ if (!sandbox.direct) {
680
+ const r = await request(sandbox, "POST", sandboxPath(sandbox.id, "/direct")).catch(() => null);
681
+ if (isDirect(r?.direct)) {
682
+ sandbox.direct = r.direct;
683
+ preconnect(r.direct.exec_url);
151
684
  }
152
- await mustSucceed(run, sandbox, `mv -f ${tmp} ${target}`, path);
153
- } catch (err) {
154
- await run(sandbox, `rm -f ${tmp}`).catch(() => {
155
- });
156
- throw err;
157
685
  }
158
686
  }
687
+ function toSnapshot(s, createMs) {
688
+ return {
689
+ id: s.id,
690
+ provider: "kosa8",
691
+ createdAt: new Date(s.created_at),
692
+ metadata: {
693
+ name: s.name ?? null,
694
+ sourceInstanceId: s.source_sandbox_id,
695
+ state: s.state,
696
+ template: s.template,
697
+ cpus: s.cpus,
698
+ memMb: s.mem_mb,
699
+ image: s.image ?? null,
700
+ bytes: s.bytes ?? 0,
701
+ region: s.region ?? null,
702
+ ...createMs !== void 0 ? { createMs } : {}
703
+ }
704
+ };
705
+ }
706
+ var SNAPSHOT_CAPABILITIES = {
707
+ scope: "rootfs",
708
+ memory: true,
709
+ destroysSource: false,
710
+ source: "kept",
711
+ fork: true,
712
+ readiness: "immediate"
713
+ };
714
+ var shellFs = (sandbox, run) => new ShellFileSystem((command, options) => run(sandbox, command, options));
159
715
  var notAvailable = (what) => new Error(`kosa8 does not support ${what} through ComputeSDK yet.`);
160
- var kosa8 = defineProvider({
716
+ var provider = defineProvider({
161
717
  name: "kosa8",
162
718
  methods: {
163
719
  instances: {
@@ -171,7 +727,17 @@ var kosa8 = defineProvider({
171
727
  options?.signal
172
728
  );
173
729
  if (!data?.sandbox) throw new Error("kosa8 API returned no sandbox on create");
174
- return { instance: toSandbox(auth, data.sandbox), instanceId: data.sandbox.id };
730
+ const sandbox = toSandbox(auth, data.sandbox, data.direct);
731
+ if (sandbox.data.state !== "running") {
732
+ try {
733
+ await waitUntilRunning(sandbox, options?.signal);
734
+ } catch (err) {
735
+ await request(auth, "DELETE", sandboxPath(sandbox.id)).catch(() => {
736
+ });
737
+ throw err;
738
+ }
739
+ }
740
+ return { instance: sandbox, instanceId: sandbox.id };
175
741
  },
176
742
  getById: async (config, instanceId) => {
177
743
  const auth = resolveConfig(config);
@@ -191,14 +757,22 @@ var kosa8 = defineProvider({
191
757
  const start = Date.now();
192
758
  const body = execBody(command, options);
193
759
  const signal = options?.timeout && options.timeout > 0 && !options.background ? AbortSignal.timeout(options.timeout + 3e4) : void 0;
194
- const data = await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
760
+ const data = await runDirect(sandbox, body, signal) ?? await request(sandbox, "POST", sandboxPath(sandbox.id, "/exec"), body, signal);
195
761
  if (!data) throw new Error(`kosa8 sandbox ${sandbox.id} not found`);
196
- return {
762
+ const result = {
197
763
  stdout: data.stdout ?? "",
198
764
  stderr: data.stderr ?? "",
199
765
  exitCode: Number.isInteger(data.exit) ? data.exit : -1,
200
766
  durationMs: Date.now() - start
201
767
  };
768
+ if (typeof data.stdout_truncated === "boolean" || typeof data.stderr_truncated === "boolean") {
769
+ result.stdoutTruncated = data.stdout_truncated === true;
770
+ result.stderrTruncated = data.stderr_truncated === true;
771
+ result.truncated = result.stdoutTruncated || result.stderrTruncated;
772
+ }
773
+ if (typeof data.stdout_bytes === "number") result.stdoutBytes = data.stdout_bytes;
774
+ if (typeof data.stderr_bytes === "number") result.stderrBytes = data.stderr_bytes;
775
+ return result;
202
776
  },
203
777
  getInfo: async (sandbox) => {
204
778
  const current = await getData(sandbox) ?? { ...sandbox.data, state: "deleted" };
@@ -252,17 +826,43 @@ var kosa8 = defineProvider({
252
826
  if (data.sandbox) sandbox.data = data.sandbox;
253
827
  },
254
828
  getInstance: (sandbox) => sandbox,
255
- // Shell commands over exec. kosa8's own file API needs a host capability that is not on
256
- // every host yet, so it is not used here.
829
+ // File content straight to the sandbox's host with the direct token, else through the API's
830
+ // file stream, else (an older host) exec (files.ts); the rest are single shell commands.
257
831
  filesystem: {
258
- readFile: (sandbox, path, run) => shellFs(sandbox, run).readFile(path),
259
- writeFile: (sandbox, path, content, run) => writeFileViaExec(sandbox, path, content, run),
832
+ readFile: (sandbox, path, run) => readFileNative(sandbox, path, run, directFiles(sandbox)),
833
+ writeFile: (sandbox, path, content, run) => writeFileNative(sandbox, path, content, run, directFiles(sandbox)),
260
834
  mkdir: (sandbox, path, run) => shellFs(sandbox, run).mkdir(path),
261
835
  readdir: (sandbox, path, run) => shellFs(sandbox, run).readdir(path),
262
836
  exists: (sandbox, path, run) => shellFs(sandbox, run).exists(path),
263
837
  remove: (sandbox, path, run) => shellFs(sandbox, run).remove(path)
264
838
  }
265
839
  },
840
+ snapshot: {
841
+ capabilities: SNAPSHOT_CAPABILITIES,
842
+ // POST /v1/sandboxes/{id}/snapshots: the VM saved as it is now, memory and disk; it keeps running.
843
+ create: async (config, instanceId, options) => {
844
+ const auth = resolveConfig(config);
845
+ const name = typeof options?.name === "string" && SNAPSHOT_NAME.test(options.name) ? options.name : void 0;
846
+ const data = await request(
847
+ auth,
848
+ "POST",
849
+ sandboxPath(instanceId, "/snapshots"),
850
+ name ? { name } : {}
851
+ );
852
+ if (!data?.snapshot) throw new Error(`kosa8 sandbox ${instanceId} not found`);
853
+ return toSnapshot(data.snapshot, typeof data.ms === "number" ? data.ms : null);
854
+ },
855
+ list: async (config) => {
856
+ const auth = resolveConfig(config);
857
+ const data = await request(auth, "GET", "/v1/snapshots");
858
+ return (data?.snapshots ?? []).map((s) => toSnapshot(s));
859
+ },
860
+ // A snapshot that is already gone answers 404, which request() returns as null.
861
+ delete: async (config, snapshotId) => {
862
+ const auth = resolveConfig(config);
863
+ await request(auth, "DELETE", `/v1/snapshots/${encodeURIComponent(snapshotId)}`);
864
+ }
865
+ },
266
866
  template: {
267
867
  create: async () => {
268
868
  throw notAvailable("creating templates (templates are offered by the hosts)");
@@ -278,13 +878,22 @@ var kosa8 = defineProvider({
278
878
  }
279
879
  }
280
880
  });
881
+ var kosa8 = (config) => {
882
+ try {
883
+ preconnect(resolveConfig(config).baseUrl);
884
+ } catch {
885
+ }
886
+ return provider(config);
887
+ };
281
888
  var index_default = kosa8;
282
889
  export {
283
890
  MAX_EXEC_BODY_BYTES,
284
891
  SCRIPT_ENV,
892
+ SNAPSHOT_CAPABILITIES,
285
893
  WRITE_CHUNK_CHARS,
286
894
  createBody,
287
895
  index_default as default,
896
+ directFiles,
288
897
  execArgv,
289
898
  execBody,
290
899
  kosa8,