@kvbox/server 0.6.5 → 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(),
@@ -1368,9 +1374,46 @@ var BoxRunSchema = z4.object({
1368
1374
  id: z4.string(),
1369
1375
  state: z4.enum(BOX_RUN_STATES),
1370
1376
  /** With `exited`; 128 + the signal for a command a signal ended. */
1371
- exitCode: z4.number().int().optional()
1377
+ exitCode: z4.number().int().optional(),
1378
+ /**
1379
+ * With `exited` and `timeout`: how long the command itself ran, by the box's own clock (base v0.15.1
1380
+ * and later). The asker learns of the end seconds late, so its own count is too long.
1381
+ */
1382
+ durationMs: z4.number().int().nonnegative().optional()
1372
1383
  });
1373
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
+ });
1374
1417
  var EnvVarSchema = z4.object({
1375
1418
  name: z4.string(),
1376
1419
  value: z4.string().optional(),
@@ -1729,7 +1772,7 @@ var VolumeEventsResponseSchema = z4.object({
1729
1772
  events: z4.array(VolumeEventRowSchema),
1730
1773
  next: z4.number().int()
1731
1774
  });
1732
- 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"];
1733
1776
  var ApiErrorCodeSchema = z4.enum(API_ERROR_CODES);
1734
1777
  var ApiErrorSchema = z4.object({
1735
1778
  error: z4.string(),
@@ -2095,7 +2138,18 @@ async function runStatus(udsPath, id, timeoutMs) {
2095
2138
  const reply = await agentCall(udsPath, { op: "runStatus", id }, timeoutMs);
2096
2139
  const state = reply["state"];
2097
2140
  if (state !== "running" && state !== "exited" && state !== "timeout" && state !== "unknown") throw new KvboxError("kvbox-agent sent a run state this server does not know");
2098
- return { state, ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {} };
2141
+ const durationMs = reply["durationMs"];
2142
+ return {
2143
+ state,
2144
+ ...typeof reply["exitCode"] === "number" ? { exitCode: reply["exitCode"] } : {},
2145
+ ...typeof durationMs === "number" && Number.isInteger(durationMs) && durationMs >= 0 ? { durationMs } : {}
2146
+ };
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 };
2099
2153
  }
2100
2154
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
2101
2155
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
@@ -5663,13 +5717,23 @@ async function socketOf(ref, p) {
5663
5717
  if (status !== "running") throw new KvboxError(`${stateMessage(ref, status)}; only a running box runs a command`);
5664
5718
  return p.machine(meta.owner, meta.name).vsock;
5665
5719
  }
5666
- var outdated = (ref, err) => {
5667
- 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)`);
5668
5723
  if (isNoAgent(err)) throw new KvboxError(`box ${shown(ref)} did not take the request: its kvbox-agent is not answering (${err.message})`);
5669
5724
  throw err;
5670
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
+ };
5671
5734
  async function startBoxRun(ref, req, p = paths()) {
5672
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));
5673
5737
  const had = going.get(keyOf(ref))?.has(req.id) ?? false;
5674
5738
  note(ref, req.id, Date.now() + req.timeoutSec * 1e3 + 6e4);
5675
5739
  return startRun(vsock, req.id, req.command, req.timeoutSec).catch((err) => {
@@ -5677,9 +5741,14 @@ async function startBoxRun(ref, req, p = paths()) {
5677
5741
  return outdated(ref, err);
5678
5742
  });
5679
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
+ }
5680
5749
  async function boxRunStatus(ref, id, p = paths()) {
5681
5750
  const vsock = await socketOf(ref, p);
5682
- const run2 = await runStatus(vsock, id).catch((err) => outdated(ref, err));
5751
+ const run2 = await runStatus(vsock, id).catch((err) => unanswered(ref, err));
5683
5752
  note(ref, id, run2.state === "running" ? Date.now() + SEEN_RUNNING_MS : null);
5684
5753
  return { id, ...run2 };
5685
5754
  }
@@ -6156,7 +6225,7 @@ function versionOf(srcFileUrl, injected) {
6156
6225
  }
6157
6226
 
6158
6227
  // src/version.ts
6159
- var VERSION = versionOf(import.meta.url, true ? "0.6.5" : void 0);
6228
+ var VERSION = versionOf(import.meta.url, true ? "0.6.7" : void 0);
6160
6229
 
6161
6230
  // src/caller.ts
6162
6231
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
@@ -6754,12 +6823,19 @@ function machineRoutes() {
6754
6823
 
6755
6824
  // src/routes/runs.ts
6756
6825
  import { Hono as Hono7 } from "hono";
6826
+ import { z as z8 } from "zod";
6757
6827
  var refusal = (c, err) => {
6758
6828
  if (err instanceof ProxyFailure) return c.json({ error: err.message, code: err.code }, err.status);
6759
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);
6760
6831
  if (err instanceof NotFoundError) return c.json({ error: err.message, code: "not-found" }, 404);
6761
6832
  throw err;
6762
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
+ });
6763
6839
  function runRoutes(wake = wakeBox) {
6764
6840
  const r = new Hono7();
6765
6841
  r.post("/:name/runs", async (c) => {
@@ -6774,12 +6850,25 @@ function runRoutes(wake = wakeBox) {
6774
6850
  });
6775
6851
  r.get("/:name/runs/:id", async (c) => {
6776
6852
  try {
6777
- 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);
6778
6854
  return c.json(BoxRunSchema.parse(await boxRunStatus(ref, c.req.param("id"))));
6779
6855
  } catch (err) {
6780
6856
  return refusal(c, err);
6781
6857
  }
6782
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
+ });
6783
6872
  return r;
6784
6873
  }
6785
6874
 
@@ -7244,7 +7333,7 @@ import { Command as Command11 } from "commander";
7244
7333
 
7245
7334
  // src/core/realm.ts
7246
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";
7247
- import { z as z8 } from "zod";
7336
+ import { z as z9 } from "zod";
7248
7337
  var esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7249
7338
  async function ownersIn(root, from, suffix = "") {
7250
7339
  const entries = await readdir7(root).catch((err) => {
@@ -7308,7 +7397,7 @@ async function plan(from, to, p) {
7308
7397
  for (const oldOwner of await ownersIn(p.volumes, from)) {
7309
7398
  await clash(p.ownerVolumes(owner(oldOwner)), `volumes of ${owner(oldOwner)}`);
7310
7399
  for (const name of await namesIn2(p.ownerVolumes(oldOwner))) {
7311
- 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}`);
7312
7401
  out.volumes.push({ oldOwner, name, meta: { ...meta, owner: owner(meta.owner) } });
7313
7402
  }
7314
7403
  }