@kvbox/server 0.6.6 → 0.6.7

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.
@@ -1354,7 +1354,13 @@ var StartRunRequest = z4.object({
1354
1354
  id: z4.string().regex(BOX_RUN_ID_RE),
1355
1355
  command: z4.string().min(1).max(8192),
1356
1356
  /** The command and everything it started are killed after this long. */
1357
- timeoutSec: z4.number().int().min(1).max(86400)
1357
+ timeoutSec: z4.number().int().min(1).max(86400),
1358
+ /**
1359
+ * The caller will read the output back (`exec`, #188): the box's kvbox-agent must know `runOutput`
1360
+ * (base v0.16.0+), which the host checks before the command starts, so an older box is `box-outdated`
1361
+ * without having run anything.
1362
+ */
1363
+ output: z4.boolean().optional()
1358
1364
  });
1359
1365
  var StartRunAnswerSchema = z4.object({
1360
1366
  id: z4.string(),
@@ -1376,6 +1382,38 @@ var BoxRunSchema = z4.object({
1376
1382
  durationMs: z4.number().int().nonnegative().optional()
1377
1383
  });
1378
1384
  var RunRefusalSchema = z4.object({ error: z4.string(), code: z4.string().optional() });
1385
+ var RUN_OUTPUT_MAX_BYTES = 1 << 20;
1386
+ var RUN_STREAMS = ["stdout", "stderr"];
1387
+ var RunOutputSchema = z4.object({
1388
+ id: z4.string(),
1389
+ stream: z4.enum(RUN_STREAMS),
1390
+ offset: z4.number().int().nonnegative(),
1391
+ size: z4.number().int().nonnegative(),
1392
+ data: z4.string()
1393
+ });
1394
+ var ExecRequest = z4.object({
1395
+ command: z4.string().min(1).max(8192),
1396
+ /** The command and everything it started are killed after this long (default DEFAULT_EXEC_TIMEOUT_SEC). */
1397
+ timeoutSec: z4.number().int().min(1).max(86400).optional()
1398
+ });
1399
+ var ExecStartSchema = z4.object({
1400
+ id: z4.string(),
1401
+ /** The box was asleep and this request woke it. */
1402
+ woke: z4.boolean()
1403
+ });
1404
+ var ExecSchema = z4.object({
1405
+ id: z4.string(),
1406
+ state: z4.enum(BOX_RUN_STATES),
1407
+ /** With `exited`; 128 + the signal for a command a signal ended. */
1408
+ exitCode: z4.number().int().optional(),
1409
+ /** With `exited` and `timeout`: how long the command itself ran. */
1410
+ durationMs: z4.number().int().nonnegative().optional(),
1411
+ stdout: z4.string().optional(),
1412
+ stderr: z4.string().optional(),
1413
+ stdoutBytes: z4.number().int().nonnegative().optional(),
1414
+ stderrBytes: z4.number().int().nonnegative().optional(),
1415
+ truncated: z4.boolean().optional()
1416
+ });
1379
1417
  var EnvVarSchema = z4.object({
1380
1418
  name: z4.string(),
1381
1419
  value: z4.string().optional(),
@@ -1734,7 +1772,7 @@ var VolumeEventsResponseSchema = z4.object({
1734
1772
  events: z4.array(VolumeEventRowSchema),
1735
1773
  next: z4.number().int()
1736
1774
  });
1737
- var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit"];
1775
+ var API_ERROR_CODES = ["account-inactive", "org-inactive", "out-of-credit", "box-outdated"];
1738
1776
  var ApiErrorCodeSchema = z4.enum(API_ERROR_CODES);
1739
1777
  var ApiErrorSchema = z4.object({
1740
1778
  error: z4.string(),
@@ -2107,6 +2145,12 @@ async function runStatus(udsPath, id, timeoutMs) {
2107
2145
  ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
2108
2146
  };
2109
2147
  }
2148
+ async function runOutput(udsPath, id, stream, offset, limit, timeoutMs = 15e3) {
2149
+ const reply = await agentCall(udsPath, { op: "runOutput", id, stream, offset, limit }, timeoutMs);
2150
+ const { size: size2, data } = reply;
2151
+ if (typeof size2 !== "number" || !Number.isInteger(size2) || size2 < 0 || typeof data !== "string") throw new KvboxError("kvbox-agent sent run output this server does not understand");
2152
+ return { size: size2, offset, data };
2153
+ }
2110
2154
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
2111
2155
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
2112
2156
  var isNoAgent = (err) => /vsock connect refused|vsock connection closed before the guest accepted|did not accept the vsock connection|kvbox-agent unreachable: connect (ENOENT|ECONNREFUSED)/.test(err.message ?? "");
@@ -5673,13 +5717,23 @@ async function socketOf(ref, p) {
5673
5717
  if (status !== "running") throw new KvboxError(`${stateMessage(ref, status)}; only a running box runs a command`);
5674
5718
  return p.machine(meta.owner, meta.name).vsock;
5675
5719
  }
5676
- var outdated = (ref, err) => {
5677
- if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before commands (it needs base v0.15.0 or later)`);
5720
+ var OUTPUT_BASE = "v0.16.0";
5721
+ var outdated = (ref, err, needs = "v0.15.0") => {
5722
+ if (isUnknownOp(err)) throw new BoxOutdatedError(`box ${shown(ref)} runs on an image from before ${needs === OUTPUT_BASE ? "reading a command's output" : "commands"} (it needs base ${needs} or later)`);
5678
5723
  if (isNoAgent(err)) throw new KvboxError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message})`);
5679
5724
  throw err;
5680
5725
  };
5726
+ var AgentNotAnsweringError = class extends KvboxError {
5727
+ };
5728
+ var unanswered = (ref, err, needs) => {
5729
+ if (isNoAgent(err) || /kvbox-agent did not answer within/.test(err.message ?? "")) {
5730
+ throw new AgentNotAnsweringError(`box ${shown(ref)}: its kvbox-agent is not answering (${err.message}); ask again`);
5731
+ }
5732
+ return outdated(ref, err, needs);
5733
+ };
5681
5734
  async function startBoxRun(ref, req, p = paths()) {
5682
5735
  const vsock = await socketOf(ref, p);
5736
+ if (req.output) await runOutput(vsock, req.id, "stdout", 0, 0).catch((err) => outdated(ref, err, OUTPUT_BASE));
5683
5737
  const had = going.get(keyOf(ref))?.has(req.id) ?? false;
5684
5738
  note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
5685
5739
  return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
@@ -5687,9 +5741,14 @@ async function startBoxRun(ref, req, p = paths()) {
5687
5741
  return outdated(ref, err);
5688
5742
  });
5689
5743
  }
5744
+ async function boxRunOutput(ref, id, stream, offset, limit, p = paths()) {
5745
+ const vsock = await socketOf(ref, p);
5746
+ const out = await runOutput(vsock, id, stream, offset, limit).catch((err) => unanswered(ref, err, OUTPUT_BASE));
5747
+ return { id, stream, ...out };
5748
+ }
5690
5749
  async function boxRunStatus(ref, id, p = paths()) {
5691
5750
  const vsock = await socketOf(ref, p);
5692
- const run2 = await runStatus(vsock, id).catch((err) => outdated(ref, err));
5751
+ const run2 = await runStatus(vsock, id).catch((err) => unanswered(ref, err));
5693
5752
  note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
5694
5753
  return { id, ...run2 };
5695
5754
  }
@@ -6166,7 +6225,7 @@ function versionOf(srcFileUrl, injected) {
6166
6225
  }
6167
6226
 
6168
6227
  // src/version.ts
6169
- var VERSION = versionOf(import.meta.url, true ? "0.6.6" : void 0);
6228
+ var VERSION = versionOf(import.meta.url, true ? "0.6.7" : void 0);
6170
6229
 
6171
6230
  // src/caller.ts
6172
6231
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6764,12 +6823,19 @@ function machineRoutes() {
6764
6823
 
6765
6824
  // src/routes/runs.ts
6766
6825
  import { Hono as Hono7 } from "hono";
6826
+ import { z as z8 } from "zod";
6767
6827
  var refusal = (c, err) => {
6768
6828
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
6769
6829
  if (err instanceof BoxOutdatedError) return c.json({ error: err.message, code: "box-outdated" }, 409);
6830
+ if (err instanceof AgentNotAnsweringError) return c.json({ error: err.message, code: "unreachable" }, 503);
6770
6831
  if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
6771
6832
  throw err;
6772
6833
  };
6834
+ var OutputQuery = z8.object({
6835
+ stream: z8.enum(RUN_STREAMS).default("stdout"),
6836
+ offset: z8.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),
6837
+ limit: z8.coerce.number().int().min(0).max(RUN_OUTPUT_MAX_BYTES).default(RUN_OUTPUT_MAX_BYTES)
6838
+ });
6773
6839
  function runRoutes(wake = wakeBox) {
6774
6840
  const r = new Hono7();
6775
6841
  r.post("/:name/runs", async (c) => {
@@ -6784,12 +6850,25 @@ function runRoutes(wake = wakeBox) {
6784
6850
  });
6785
6851
  r.get("/:name/runs/:id", async (c) => {
6786
6852
  try {
6787
- const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
6853
+ const { ref } = await runningBox(c.req.param("name"), c.get("owner"), wants(c.req.header(WAKE_HEADER)) ? wake : void 0);
6788
6854
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
6789
6855
  } catch (err) {
6790
6856
  return refusal(c, err);
6791
6857
  }
6792
6858
  });
6859
+ r.get("/:name/runs/:id/output", async (c) => {
6860
+ const id = c.req.param("id");
6861
+ const query = OutputQuery.safeParse(c.req.query());
6862
+ if (!BOX_RUN_ID_RE.test(id)) throw new KvboxError(`run ${id}: not a run id`);
6863
+ if (!query.success) throw new KvboxError(`stream must be ${RUN_STREAMS.join(" or ")}, offset a whole number, limit at most ${RUN_OUTPUT_MAX_BYTES}`);
6864
+ const { stream, offset, limit } = query.data;
6865
+ try {
6866
+ const { ref } = await runningBox(c.req.param("name"), c.get("owner"));
6867
+ return c.json(RunOutputSchema.parse(await boxRunOutput(ref, id, stream, offset, limit)));
6868
+ } catch (err) {
6869
+ return refusal(c, err);
6870
+ }
6871
+ });
6793
6872
  return r;
6794
6873
  }
6795
6874
 
@@ -7254,7 +7333,7 @@ import { Command as Command11 } from "commander";
7254
7333
 
7255
7334
  // src/core/realm.ts
7256
7335
  import { lstat as lstat2, readFile as readFile14, readdir as readdir7, readlink, rename as rename7, rm as rm9, symlink as symlink2, writeFile as writeFile11 } from "node:fs/promises";
7257
- import { z as z8 } from "zod";
7336
+ import { z as z9 } from "zod";
7258
7337
  var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7259
7338
  async function ownersIn(root, from, suffix = "") {
7260
7339
  const entries = await readdir7(root).catch((err) => {
@@ -7318,7 +7397,7 @@ async function plan(from, to, p) {
7318
7397
  for (const oldOwner of await ownersIn(p.volumes, from)) {
7319
7398
  await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7320
7399
  for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7321
- const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z8.string().optional() }), `volume ${oldOwner}/${name}`);
7400
+ const meta = await read(p.volume(oldOwner, name).meta, VolumeMetaSchema.extend({ id: z9.string().optional() }), `volume ${oldOwner}/${name}`);
7322
7401
  out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7323
7402
  }
7324
7403
  }