@kvbox/server 0.5.32 → 0.5.35

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.
@@ -546,6 +546,8 @@ var MachineSchema = z3.object({
546
546
  ownerKind: z3.enum(["user", "org"]).optional(),
547
547
  /** Seconds without network traffic before the host hibernates the box (#47). Absent: never. */
548
548
  autoHibernateSec: z3.number().int().positive().optional(),
549
+ /** A script inside the box that says it is idle (#102, exit 0): auto-hibernate asks it instead of watching the traffic. */
550
+ idleCheck: z3.string().optional(),
549
551
  /** Volumes attached to the box (#52), in drive order; each is mounted at `mountPath` while the box runs. Absent: none. */
550
552
  volumes: z3.array(z3.object({ name: z3.string(), sizeGib: z3.number().int(), mountPath: z3.string() })).optional(),
551
553
  /** Boxes that may reach this one, each on one port (#98). Absent: none. */
@@ -663,11 +665,18 @@ var RescaleMachineRequest = z3.object({
663
665
  size: SizeSchema.optional(),
664
666
  vcpu: z3.number().int().min(1).max(64).optional(),
665
667
  memMib: z3.number().int().min(256).optional(),
666
- diskGib: z3.number().int().min(1).optional()
668
+ diskGib: z3.number().int().min(1).optional(),
669
+ /** Skip the capacity guard when a running box grows (#37). */
670
+ force: z3.boolean().optional()
671
+ });
672
+ var StartMachineRequest = z3.object({
673
+ force: z3.boolean().optional()
667
674
  });
668
675
  var SetMachineRequest = z3.object({
669
676
  /** Seconds without network traffic before the box is hibernated (#47); 0: never. */
670
- autoHibernateSec: z3.number().int().min(0).optional()
677
+ autoHibernateSec: z3.number().int().min(0).optional(),
678
+ /** The box's idle check (#102): an absolute path to a script inside the box, exit 0 = idle; "": none, back to network traffic. */
679
+ idleCheck: z3.union([z3.literal(""), z3.string().max(255).regex(/^\/[^\0\n]*$/, "an absolute path inside the box")]).optional()
671
680
  });
672
681
  var SnapshotSchema = z3.object({
673
682
  name: z3.string(),
@@ -1436,6 +1445,12 @@ var MachineMetaSchema = z4.object({
1436
1445
  ports: z4.array(z4.object({ guestPort: z4.number().int(), hostPort: z4.number().int(), proto: z4.enum(["tcp", "udp"]) })).optional(),
1437
1446
  /** Seconds without traffic on the box's tap before the server hibernates it (#47, core/idle.ts). Absent: never. */
1438
1447
  autoHibernateSec: z4.number().int().positive().optional(),
1448
+ /**
1449
+ * A script inside the box auto-hibernate asks instead of watching the tap (#102, core/idle.ts): run by
1450
+ * kvbox-agent, exit 0 = idle. A new box gets its image's `idle` (image.json); `kvbox vm set --idle-check`
1451
+ * changes it. The one place the host looks. Absent: the traffic rule.
1452
+ */
1453
+ idleCheck: z4.string().optional(),
1439
1454
  /**
1440
1455
  * Names of the owner's volumes attached to the box (#52), in the order they were attached, which is
1441
1456
  * their drive order (/dev/vdc, /dev/vdd, …). This list is the one truth about what is attached: a
@@ -1713,6 +1728,16 @@ import { closeSync as closeSync2, existsSync as existsSync6, openSync as openSyn
1713
1728
  import { link as link2, mkdir as mkdir6, readFile as readFile6, rm as rm3, truncate as truncate2, writeFile as writeFile5 } from "node:fs/promises";
1714
1729
  import { setTimeout as sleep } from "node:timers/promises";
1715
1730
 
1731
+ // ../shared/src/duration.ts
1732
+ var UNIT_SEC = { m: 60, h: 3600, d: 86400 };
1733
+ function parseDuration(text) {
1734
+ const t = text.trim().toLowerCase();
1735
+ if (!/^(\d+[mhd])+$/.test(t)) return void 0;
1736
+ let sec = 0;
1737
+ for (const [, n, unit] of t.matchAll(/(\d+)([mhd])/g)) sec += Number(n) * UNIT_SEC[unit];
1738
+ return sec;
1739
+ }
1740
+
1716
1741
  // src/core/agent.ts
1717
1742
  import { connect } from "node:net";
1718
1743
  var AGENT_PORT = 52;
@@ -1777,6 +1802,9 @@ async function dropVolumes(udsPath, timeoutMs) {
1777
1802
  function setEnv(udsPath, vars, timeoutMs) {
1778
1803
  return agentCall(udsPath, { op: "env", vars: vars.map((v) => [v.name, v.value]) }, timeoutMs);
1779
1804
  }
1805
+ async function idle(udsPath, script, timeoutMs = 15e3) {
1806
+ return (await agentCall(udsPath, { op: "idle", path: script }, timeoutMs))["idle"] === true;
1807
+ }
1780
1808
  var isUnknownOp = (err) => /unknown op/.test(err.message ?? "");
1781
1809
  var isGuestBooting = (err) => /did not accept the vsock connection/.test(err.message ?? "");
1782
1810
  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 ?? "");
@@ -2036,8 +2064,16 @@ async function assertOverlayCapable(file, image, version) {
2036
2064
  if (!ok) throw new KvboxError(`${imageLabel(image)} ${version} is not a kvbox image (no /sbin/overlay-init); rerun install-server.sh`);
2037
2065
  }
2038
2066
  var ImageManifestSchema = z6.object({
2039
- /** false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection). */
2040
- autoHibernate: z6.boolean().optional(),
2067
+ /**
2068
+ * false: a new box of this image does not auto-hibernate unless asked (nothing wakes it on a TCP connection).
2069
+ * A duration (`"10m"`, #102): a new box's idle time unless the caller gave one, instead of the host's default.
2070
+ */
2071
+ autoHibernate: z6.union([z6.boolean(), z6.string().refine((s) => parseDuration(s) !== void 0, "a duration like 10m, 4h or 1d")]).optional(),
2072
+ /**
2073
+ * A script inside the box that says whether it is idle (#102), exit 0 = idle: a new box's `idleCheck`
2074
+ * (meta.json), which auto-hibernate asks through kvbox-agent instead of watching the traffic.
2075
+ */
2076
+ idle: z6.string().optional(),
2041
2077
  /** Variables the box gets unless the caller or its owner set them; a value may name an earlier one, or a generated one, as `${NAME}`. */
2042
2078
  env: z6.record(z6.string(), z6.string()).optional(),
2043
2079
  /** Variables the host fills with a random password when the caller gave none. */
@@ -2350,7 +2386,7 @@ async function runningReservations(p = paths()) {
2350
2386
  for (const ref of await listMachineRefs(p)) {
2351
2387
  try {
2352
2388
  const meta = await readMachineMeta(ref, p);
2353
- if (vmAlive(meta)) out.push({ name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });
2389
+ if (vmAlive(meta)) out.push({ owner: meta.owner, name: meta.name, vcpu: meta.vcpu, memMib: meta.memMib });
2354
2390
  } catch {
2355
2391
  }
2356
2392
  }
@@ -2374,30 +2410,41 @@ function gb(mib) {
2374
2410
  const g = mib / 1024;
2375
2411
  return `${Number.isInteger(g) ? g : g.toFixed(1)} GB`;
2376
2412
  }
2377
- function describeRunning(running) {
2413
+ function describeRunning(running, viewer) {
2378
2414
  if (running.length === 0) return "no box is running";
2379
- const list = running.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`).join(", ");
2415
+ const own = viewer === void 0 ? running : running.filter((r) => r.owner === viewer);
2416
+ const others = running.length - own.length;
2417
+ const named = own.map((r) => `${r.name} ${r.vcpu} vCPU/${gb(r.memMib)}`);
2418
+ if (others > 0) named.push(`${others} ${others === 1 ? "box" : "boxes"} of other users`);
2419
+ const list = named.join(", ");
2380
2420
  const vcpu = running.reduce((n, r) => n + r.vcpu, 0);
2381
2421
  const mem = running.reduce((n, r) => n + r.memMib, 0);
2382
2422
  return `${running.length} running ${running.length === 1 ? "box reserves" : "boxes reserve"} ${vcpu} vCPU and ${gb(mem)} (${list})`;
2383
2423
  }
2384
- function roomFor(host, running, want) {
2424
+ var HINTS = {
2425
+ new: "stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway",
2426
+ start: "stop or remove a box (kvbox stop, kvbox rm), or pass --force to start it anyway",
2427
+ rescale: "stop or remove a box (kvbox stop, kvbox rm), ask for less, or pass --force to rescale it anyway"
2428
+ };
2429
+ function roomFor(host, running, want, opts = {}) {
2430
+ const { viewer, by = "new" } = opts;
2385
2431
  const reservedMem = running.reduce((n, r) => n + r.memMib, 0);
2386
2432
  const reservedVcpu = running.reduce((n, r) => n + r.vcpu, 0);
2387
2433
  const memLimit = host.memMib - MEM_HEADROOM_MIB;
2388
2434
  const vcpuLimit = host.cores * VCPU_OVERSUBSCRIPTION;
2389
- const hint = "stop or remove a box (kvbox stop, kvbox rm), pick a smaller --size, or pass --force to start it anyway";
2435
+ const hint = HINTS[by];
2390
2436
  if (reservedMem + want.memMib > memLimit) {
2391
- return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running)}; this host has ${gb(host.memMib)} and keeps ${gb(MEM_HEADROOM_MIB)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` + hint;
2437
+ return `not enough memory for a ${gb(want.memMib)} box: ${describeRunning(running, viewer)}; this host has ${gb(host.memMib)} and keeps ${gb(MEM_HEADROOM_MIB)} for itself, so boxes may reserve ${gb(memLimit)} in total. ` + hint;
2392
2438
  }
2393
2439
  if (reservedVcpu + want.vcpu > vcpuLimit) {
2394
- return `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running)}; this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` + hint;
2440
+ return `too many vCPUs for a ${want.vcpu} vCPU box: ${describeRunning(running, viewer)}; this host has ${host.cores} cores and allows ${vcpuLimit} vCPUs in total (${VCPU_OVERSUBSCRIPTION}x). ` + hint;
2395
2441
  }
2396
2442
  return void 0;
2397
2443
  }
2398
- async function assertRoomFor(vcpu, memMib, force, p = paths()) {
2444
+ async function assertRoomFor(vcpu, memMib, force, box, by, p = paths()) {
2399
2445
  if (force) return;
2400
- const reason = roomFor(hostResources(), await runningReservations(p), { vcpu, memMib });
2446
+ const running = (await runningReservations(p)).filter((r) => box.name === void 0 || !(r.owner === box.owner && r.name === box.name));
2447
+ const reason = roomFor(hostResources(), running, { vcpu, memMib }, { viewer: box.owner, by });
2401
2448
  if (reason !== void 0) throw new KvboxError(reason);
2402
2449
  }
2403
2450
 
@@ -2905,14 +2952,17 @@ function toMachine(meta, p = paths()) {
2905
2952
  ...meta.sshPort === void 0 ? {} : { sshPort: meta.sshPort },
2906
2953
  ...meta.ports?.length ? { ports: meta.ports.map((f) => ({ ...f })) } : {},
2907
2954
  ...meta.autoHibernateSec ? { autoHibernateSec: meta.autoHibernateSec } : {},
2955
+ ...meta.idleCheck !== void 0 ? { idleCheck: meta.idleCheck } : {},
2908
2956
  ...meta.volumes?.length ? { volumes: volumeSummaries(meta, p) } : {},
2909
2957
  ...meta.links?.some((l) => !l.stale) ? { links: meta.links.filter((l) => !l.stale).map((l) => ({ from: linkFrom(l, meta.owner), port: l.port })) } : {}
2910
2958
  };
2911
2959
  }
2912
2960
  var linkFrom = (l, owner) => l.owner === owner ? l.name : `${l.owner.split("@")[0]}/${l.name}`;
2913
2961
  function autoHibernateFor(req, cfg, manifest = {}) {
2914
- if (req.autoHibernateSec === void 0 && manifest.autoHibernate === false) return void 0;
2915
- return (req.autoHibernateSec ?? cfg.autoHibernateSec) || void 0;
2962
+ if (req.autoHibernateSec !== void 0) return req.autoHibernateSec || void 0;
2963
+ if (manifest.autoHibernate === false) return void 0;
2964
+ if (typeof manifest.autoHibernate === "string") return parseDuration(manifest.autoHibernate) || void 0;
2965
+ return cfg.autoHibernateSec || void 0;
2916
2966
  }
2917
2967
  async function readAllMeta(p) {
2918
2968
  const metas = [];
@@ -3087,7 +3137,7 @@ async function createMachine(req, owner, p = paths()) {
3087
3137
  if (!isSizeName(sizeName)) throw new KvboxError(`unknown size "${sizeName}"; use one of ${Object.keys(SIZES).join(", ")}`);
3088
3138
  const size = SIZES[sizeName];
3089
3139
  assertAssets(cfg);
3090
- await assertRoomFor(size.vcpu, size.memMib, req.force ?? false, p);
3140
+ await assertRoomFor(size.vcpu, size.memMib, req.force ?? false, { owner }, "new", p);
3091
3141
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
3092
3142
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
3093
3143
  const existing = await readAllMeta(p);
@@ -3109,7 +3159,7 @@ async function createMachine(req, owner, p = paths()) {
3109
3159
  await createOverlay(m.overlay, size.diskGib);
3110
3160
  if (vars.length > 0) await writeBoxEnv({ owner, name }, vars, p);
3111
3161
  },
3112
- { source: "base", autoHibernateSec, url: maskedUrl(manifest, vars) },
3162
+ { source: "base", autoHibernateSec, idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
3113
3163
  cfg,
3114
3164
  p
3115
3165
  );
@@ -3179,7 +3229,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
3179
3229
  if (req.image !== void 0 && imageKey(req.image) !== snap.image) {
3180
3230
  throw new KvboxError(`--base cannot be combined with --from: a restored box has the snapshot's image (${shown(from)}: ${imageLabel(snap.image)})`);
3181
3231
  }
3182
- await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, p);
3232
+ await assertRoomFor(snap.vcpu, snap.memMib, req.force ?? false, { owner }, "new", p);
3183
3233
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
3184
3234
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
3185
3235
  const existing = await readAllMeta(p);
@@ -3199,7 +3249,7 @@ async function restoreFrom(from, owner, req, cfg, p) {
3199
3249
  await placeholderDrives(m.dir, snap.volumes ?? []);
3200
3250
  return { vmstate: s.vmstate, mem: s.mem, label: shown(from), volumes: snap.volumes };
3201
3251
  },
3202
- { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), url: maskedUrl(manifest, vars) },
3252
+ { source: `snapshot:${refKey(from)}`, autoHibernateSec: autoHibernateFor(req, cfg, manifest), idleCheck: manifest.idle, url: maskedUrl(manifest, vars) },
3203
3253
  cfg,
3204
3254
  p
3205
3255
  );
@@ -3269,7 +3319,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3269
3319
  }
3270
3320
  assertAssets(cfg);
3271
3321
  imageFileFor(src, p);
3272
- await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, p);
3322
+ await assertRoomFor(shape.vcpu, shape.memMib, req.force ?? false, { owner }, "new", p);
3273
3323
  const sshKeys = isCloudBox(owner) && req.sshKeys !== void 0 && req.sshKeys.length > 0 ? req.sshKeys : void 0;
3274
3324
  authorizedKeysB64(await readHostPubkey(p), sshKeys ?? []);
3275
3325
  const existing = await readAllMeta(p);
@@ -3278,7 +3328,7 @@ var forkMachine = locked(async function forkMachine2(ref, owner, req, p = paths(
3278
3328
  const ip = nextFreeIp(cfg.subnet, [...existing.map((m) => m.ip), cfg.gateway]);
3279
3329
  const box = { id, name, owner, ip, mac: macFor(ip), ...shape, base: src.base, image: src.image, sshKeys };
3280
3330
  const srcEnv = p.machine(src.owner, src.name).env;
3281
- const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, url: src.url };
3331
+ const origin = { source: `fork:${refKey(src)}`, autoHibernateSec: (req.autoHibernateSec ?? src.autoHibernateSec) || void 0, idleCheck: src.idleCheck, url: src.url };
3282
3332
  if (!warm) {
3283
3333
  return bootInto(
3284
3334
  box,
@@ -3441,7 +3491,7 @@ var stopMachine = locked(async function stopMachine2(ref, p = paths()) {
3441
3491
  recordState(stopped, "stopped", "stop", p);
3442
3492
  return toMachine(stopped, p);
3443
3493
  });
3444
- var startMachine = locked(async function startMachine2(ref, p = paths()) {
3494
+ var startMachine = locked(async function startMachine2(ref, p = paths(), force = false) {
3445
3495
  const meta = await readMeta(ref, p);
3446
3496
  const cfg = await loadConfig(p);
3447
3497
  if (vmAlive(meta)) throw new KvboxError(`box ${shown(ref)} is already ${meta.paused ? "up, in standby (kvbox resume " + shown(ref) + ")" : "running"}`);
@@ -3449,6 +3499,7 @@ var startMachine = locked(async function startMachine2(ref, p = paths()) {
3449
3499
  throw new KvboxError(`${stateMessage(ref, "hibernated")}: kvbox wake ${shown(ref)} continues where it left off; to boot fresh instead, kvbox stop ${shown(ref)} first (discards its memory)`);
3450
3500
  }
3451
3501
  assertAssets(cfg);
3502
+ await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
3452
3503
  const keysB64 = authorizedKeysB64(await readHostPubkey(p), meta.sshKeys ?? []);
3453
3504
  await ensureHostNetwork(cfg);
3454
3505
  const tap = await createTap(meta, cfg);
@@ -3579,7 +3630,7 @@ var hibernateMachine = locked(async function hibernateMachine2(ref, p = paths(),
3579
3630
  recordState(hibernated, "hibernated", by, p);
3580
3631
  return toMachine(hibernated, p);
3581
3632
  });
3582
- var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3633
+ var wakeMachine = locked(async function wakeMachine2(ref, p = paths(), force = false) {
3583
3634
  const meta = await readMeta(ref, p);
3584
3635
  const cfg = await loadConfig(p);
3585
3636
  const status = statusOf(meta, p);
@@ -3589,6 +3640,7 @@ var wakeMachine = locked(async function wakeMachine2(ref, p = paths()) {
3589
3640
  if (!existsSync6(imageFile(meta.image, meta.base, p))) {
3590
3641
  throw new KvboxError(`box ${shown(ref)} stacks on ${imageLabel(meta.image)} ${meta.base}, which is gone from ${p.assets}`);
3591
3642
  }
3643
+ await assertRoomFor(meta.vcpu, meta.memMib, force, meta, "start", p);
3592
3644
  const m = p.machine(ref.owner, ref.name);
3593
3645
  await ensureHostNetwork(cfg);
3594
3646
  const tap = await createTap(meta, cfg, { detached: true });
@@ -3629,7 +3681,7 @@ async function applyAtNextBoot(meta, changes, by, cfg, p, whileStopped) {
3629
3681
  await writeMachineMeta(updated, p);
3630
3682
  if (whileStopped) await whileStopped();
3631
3683
  recordState(updated, "stopped", by, p);
3632
- return wasRunning ? startMachine(meta, p) : toMachine(updated, p);
3684
+ return wasRunning ? startMachine(meta, p, true) : toMachine(updated, p);
3633
3685
  }
3634
3686
  function assertNotHibernated(meta, p) {
3635
3687
  if (isHibernated(meta, p)) {
@@ -3666,6 +3718,9 @@ var rescaleMachine = locked(async function rescaleMachine2(ref, req, p = paths()
3666
3718
  if (target.memMib !== meta.memMib) changes.memMib = target.memMib;
3667
3719
  const growTo = target.diskGib > currentDiskGib ? target.diskGib : void 0;
3668
3720
  if (Object.keys(changes).length === 0 && growTo === void 0) return toMachine(meta, p);
3721
+ if (vmAlive(meta) && (target.vcpu > meta.vcpu || target.memMib > meta.memMib)) {
3722
+ await assertRoomFor(target.vcpu, target.memMib, req.force ?? false, meta, "rescale", p);
3723
+ }
3669
3724
  return applyAtNextBoot(meta, changes, "rescale", cfg, p, growTo === void 0 ? void 0 : () => growDisk(disk, growTo));
3670
3725
  });
3671
3726
  var attachVolume = locked(async function attachVolume2(ref, volume, p = paths()) {
@@ -3696,6 +3751,7 @@ var setMachine = locked(async function setMachine2(ref, req, p = paths()) {
3696
3751
  const meta = await readMeta(ref, p);
3697
3752
  const next = { ...meta };
3698
3753
  if (req.autoHibernateSec !== void 0) next.autoHibernateSec = req.autoHibernateSec || void 0;
3754
+ if (req.idleCheck !== void 0) next.idleCheck = req.idleCheck || void 0;
3699
3755
  await writeMachineMeta(next, p);
3700
3756
  return toMachine(next, p);
3701
3757
  });
@@ -3910,7 +3966,7 @@ async function bootRecovered(settled, p = paths()) {
3910
3966
  for (let ref = queue.shift(); ref !== void 0 && !recoveryStopping; ref = queue.shift()) {
3911
3967
  try {
3912
3968
  if (!cutByReboot(await readMeta(ref, p))) continue;
3913
- await startMachine(ref, p);
3969
+ await startMachine(ref, p, true);
3914
3970
  booted.push(refKey(ref));
3915
3971
  } catch (err) {
3916
3972
  failed.push({ box: refKey(ref), error: err.message });
@@ -4023,6 +4079,10 @@ async function tapTraffic(id) {
4023
4079
  return null;
4024
4080
  }
4025
4081
  }
4082
+ async function boxIdle(box, p) {
4083
+ if (box.idleCheck === void 0) return null;
4084
+ return idle(p.machine(box.owner, box.name).vsock, box.idleCheck);
4085
+ }
4026
4086
  async function hibernateIfRunning(box, p) {
4027
4087
  const ref = { owner: box.owner, name: box.name };
4028
4088
  return withBoxLock(ref, async () => {
@@ -4036,41 +4096,55 @@ function startIdleWatch(opts = {}) {
4036
4096
  const p = opts.p ?? paths();
4037
4097
  const list = opts.list ?? (() => listMachines(null, p));
4038
4098
  const traffic = opts.traffic ?? tapTraffic;
4099
+ const guestIdle = opts.guestIdle ?? ((box) => boxIdle(box, p));
4039
4100
  const hibernate = opts.hibernate ?? ((box) => hibernateIfRunning(box, p));
4040
4101
  const busy = opts.busy ?? ((box) => boxBusy(box));
4041
4102
  const now = opts.now ?? Date.now;
4042
4103
  const log = opts.log ?? ((line) => console.log(line));
4043
4104
  const seen = /* @__PURE__ */ new Map();
4105
+ const checkErrors = /* @__PURE__ */ new Map();
4044
4106
  let timer;
4045
4107
  let stopped = false;
4046
4108
  const inflight = /* @__PURE__ */ new Set();
4047
4109
  const hibernateOne = async (box, quiet, bytes, t) => {
4048
4110
  inflight.add(box.id);
4111
+ const byImage = bytes < 0;
4049
4112
  try {
4050
- if (await hibernate(box)) log(`box ${box.owner}/${box.name}: no network traffic for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4113
+ if (await hibernate(box)) log(`box ${box.owner}/${box.name}: ${byImage ? "idle by its own check" : "no network traffic"} for ${quiet} min; hibernated it (kvbox connect wakes it)`);
4051
4114
  seen.delete(box.id);
4052
4115
  } catch (err) {
4053
- log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min without traffic: ${err.message}`);
4116
+ log(`warning: box ${box.owner}/${box.name}: could not hibernate it after ${quiet} min ${byImage ? "idle" : "without traffic"}: ${err.message}`);
4054
4117
  seen.set(box.id, { bytes, since: t });
4055
4118
  } finally {
4056
4119
  inflight.delete(box.id);
4057
4120
  }
4058
4121
  };
4122
+ const askIdle = (box) => guestIdle(box).then(
4123
+ (v) => (checkErrors.delete(box.id), v),
4124
+ (err) => {
4125
+ if (checkErrors.get(box.id) !== err.message) log(`warning: box ${box.owner}/${box.name}: its idle check ${box.idleCheck ?? ""} failed, so it counts as busy and does not hibernate: ${err.message}`);
4126
+ checkErrors.set(box.id, err.message);
4127
+ return false;
4128
+ }
4129
+ );
4059
4130
  const check = async () => {
4060
4131
  const started = [];
4061
4132
  const watched = /* @__PURE__ */ new Set();
4133
+ const due = [];
4062
4134
  for (const box of await list()) {
4063
4135
  if (!box.autoHibernateSec || box.status !== "running" || box.links?.length) continue;
4064
- if (inflight.has(box.id)) {
4065
- watched.add(box.id);
4066
- continue;
4067
- }
4068
- const bytes = await traffic(box.id);
4136
+ if (inflight.has(box.id)) watched.add(box.id);
4137
+ else due.push(box);
4138
+ }
4139
+ const verdicts = await Promise.all(due.map(askIdle));
4140
+ for (const [i, box] of due.entries()) {
4141
+ const verdict = verdicts[i] ?? null;
4142
+ const bytes = verdict === null ? await traffic(box.id) : -1;
4069
4143
  if (bytes === null) continue;
4070
4144
  watched.add(box.id);
4071
4145
  const t = now();
4072
4146
  const last = seen.get(box.id);
4073
- if (!last || last.bytes !== bytes || busy(box)) {
4147
+ if (!last || last.bytes !== bytes || verdict === false || busy(box)) {
4074
4148
  seen.set(box.id, { bytes, since: t });
4075
4149
  continue;
4076
4150
  }
@@ -4079,6 +4153,7 @@ function startIdleWatch(opts = {}) {
4079
4153
  started.push(hibernateOne(box, Math.round((t - last.since) / 6e4), bytes, t));
4080
4154
  }
4081
4155
  for (const id of seen.keys()) if (!watched.has(id)) seen.delete(id);
4156
+ for (const id of checkErrors.keys()) if (!watched.has(id)) checkErrors.delete(id);
4082
4157
  return started;
4083
4158
  };
4084
4159
  const round2 = async () => {
@@ -4180,7 +4255,7 @@ function versionOf(srcFileUrl, injected) {
4180
4255
  }
4181
4256
 
4182
4257
  // src/version.ts
4183
- var VERSION = versionOf(import.meta.url, true ? "0.5.32" : void 0);
4258
+ var VERSION = versionOf(import.meta.url, true ? "0.5.35" : void 0);
4184
4259
 
4185
4260
  // src/caller.ts
4186
4261
  import { createHash as createHash2, timingSafeEqual } from "node:crypto";
@@ -4569,11 +4644,17 @@ function machineRoutes() {
4569
4644
  return c.json(await forkMachine(parseRef(c.req.param("name"), caller), into, body), 201);
4570
4645
  });
4571
4646
  r.post("/:name/stop", async (c) => c.json(await stopMachine(parseRef(c.req.param("name"), c.get("owner")))));
4572
- r.post("/:name/start", async (c) => c.json(await startMachine(parseRef(c.req.param("name"), c.get("owner")))));
4647
+ r.post("/:name/start", async (c) => {
4648
+ const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
4649
+ return c.json(await startMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
4650
+ });
4573
4651
  r.post("/:name/pause", async (c) => c.json(await pauseMachine(parseRef(c.req.param("name"), c.get("owner")))));
4574
4652
  r.post("/:name/resume", async (c) => c.json(await resumeMachine(parseRef(c.req.param("name"), c.get("owner")))));
4575
4653
  r.post("/:name/hibernate", async (c) => c.json(await hibernateMachine(parseRef(c.req.param("name"), c.get("owner")))));
4576
- r.post("/:name/wake", async (c) => c.json(await wakeMachine(parseRef(c.req.param("name"), c.get("owner")))));
4654
+ r.post("/:name/wake", async (c) => {
4655
+ const body = StartMachineRequest.parse(await c.req.json().catch(() => ({})));
4656
+ return c.json(await wakeMachine(parseRef(c.req.param("name"), c.get("owner")), void 0, body.force ?? false));
4657
+ });
4577
4658
  r.post("/:name/update", async (c) => c.json(await updateMachine(parseRef(c.req.param("name"), c.get("owner")))));
4578
4659
  r.post("/:name/rescale", async (c) => {
4579
4660
  const body = RescaleMachineRequest.parse(await c.req.json().catch(() => ({})));