@fungi.computer/computer 0.18.17 → 0.19.1

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.
@@ -1,5 +1,17 @@
1
- /** The one idle window: a Computer sleeps this long after its last activity. */
1
+ /**
2
+ * The one idle window: a Computer with no operation in flight, no open
3
+ * terminal, no command Fungi started that is still running and no traffic the
4
+ * host sees to its VM is stopped this long after its last activity, freeing its
5
+ * host slot. Its files are saved first and it starts again on its next use.
6
+ * An Agent that is only thinking, with no command running, does not hold it.
7
+ */
2
8
  export declare const computerContainerSleepAfterMs: number;
9
+ /**
10
+ * The platform's own inactivity kill, a backstop well above the idle window: it
11
+ * saves nothing and cannot see what the Hub counts, so the Hub's save-then-stop
12
+ * must always come first.
13
+ */
14
+ export declare const computerPlatformBackstopMs: number;
3
15
  /** A kept-awake container's platform backstop: the 24 hour runtime ceiling. */
4
16
  export declare const computerKeepAwakeTimeoutMs: number;
5
17
  export declare function hostedComputerContainersPaused(hostedComputers: string | undefined): boolean;
@@ -1,6 +1,18 @@
1
1
  import { z } from "zod";
2
- /** The one idle window: a Computer sleeps this long after its last activity. */
3
- export const computerContainerSleepAfterMs = 60 * 60 * 1_000;
2
+ /**
3
+ * The one idle window: a Computer with no operation in flight, no open
4
+ * terminal, no command Fungi started that is still running and no traffic the
5
+ * host sees to its VM is stopped this long after its last activity, freeing its
6
+ * host slot. Its files are saved first and it starts again on its next use.
7
+ * An Agent that is only thinking, with no command running, does not hold it.
8
+ */
9
+ export const computerContainerSleepAfterMs = 10 * 60 * 1_000;
10
+ /**
11
+ * The platform's own inactivity kill, a backstop well above the idle window: it
12
+ * saves nothing and cannot see what the Hub counts, so the Hub's save-then-stop
13
+ * must always come first.
14
+ */
15
+ export const computerPlatformBackstopMs = 60 * 60 * 1_000;
4
16
  /** A kept-awake container's platform backstop: the 24 hour runtime ceiling. */
5
17
  export const computerKeepAwakeTimeoutMs = 24 * 60 * 60 * 1_000;
6
18
  const hostedComputersSchema = z
@@ -24,5 +36,5 @@ export function assertComputerContainersEnabled(hostedComputers) {
24
36
  export async function configureComputerContainer(container, keepAwake) {
25
37
  if (container === undefined)
26
38
  throw new Error("Computer Durable Object is not container-enabled");
27
- await container.setInactivityTimeout(keepAwake ? computerKeepAwakeTimeoutMs : computerContainerSleepAfterMs);
39
+ await container.setInactivityTimeout(keepAwake ? computerKeepAwakeTimeoutMs : computerPlatformBackstopMs);
28
40
  }
@@ -49,6 +49,8 @@ export type FleetLifecyclePorts = Readonly<{
49
49
  containerRunning: (backing: HostedBacking) => Promise<boolean>;
50
50
  /** The Computer's process record learns that this backend went to sleep. */
51
51
  endedByIdleSleep: (backendId: string) => void;
52
+ /** Whether a command started since `since` is still running on this backend. */
53
+ hasRunningProcesses: (backendId: string, since: number) => boolean;
52
54
  vmQueuePosition: (hostId: string) => Promise<number | null>;
53
55
  }>;
54
56
  }>;
@@ -103,7 +105,9 @@ export declare class FleetLifecycle {
103
105
  /** Native execution remains the callback; policy has already become a grant. */
104
106
  run<T>(grant: ComputerGrant, backing: HostedBacking, run: () => Promise<T>): Promise<T>;
105
107
  /** Transport traffic advances activity; an idle open connection does not. */
106
- trackResponse(backing: HostedBacking, response: Response): Response;
108
+ trackResponse(backing: HostedBacking, response: Response, options?: Readonly<{
109
+ terminal?: boolean;
110
+ }>): Response;
107
111
  containerRuntimeStarted(start: ContainerRuntimeStart): void;
108
112
  armRuntimeWatch(due: number): Promise<void>;
109
113
  syncRecycledWorkspace(backing: HostedBacking): Promise<void>;
@@ -114,6 +118,11 @@ export declare class FleetLifecycle {
114
118
  private get awake();
115
119
  /** Metering never runs past the last activity of a Computer that is not awake. */
116
120
  private billedThrough;
121
+ /**
122
+ * Whether the host saw no traffic to this VM for the idle window: an SSH
123
+ * session or a served port keeps it up although the Hub saw nothing.
124
+ */
125
+ private quietOnHost;
117
126
  /** Whether an idle runtime has passed its sleep window. */
118
127
  private sleepDue;
119
128
  private observeRuntime;
@@ -39,6 +39,10 @@ export class FleetLifecycle {
39
39
  usage;
40
40
  #watchMs;
41
41
  #hostedOperations = 0;
42
+ /** Terminal sockets open right now: a person is attached, however quiet. */
43
+ #openSockets = 0;
44
+ /** Failed idle saves in a row, per runtime. */
45
+ #idleStopFailures = new Map();
42
46
  #startingHosted = 0;
43
47
  #lastHostedActivity = Date.now();
44
48
  #recycling;
@@ -186,7 +190,7 @@ export class FleetLifecycle {
186
190
  }
187
191
  }
188
192
  /** Transport traffic advances activity; an idle open connection does not. */
189
- trackResponse(backing, response) {
193
+ trackResponse(backing, response, options = {}) {
190
194
  const socket = response.webSocket ?? null;
191
195
  if (socket === null && response.body === null)
192
196
  return response;
@@ -203,7 +207,21 @@ export class FleetLifecycle {
203
207
  const pair = new WebSocketPair();
204
208
  const client = pair[0];
205
209
  const server = pair[1];
210
+ // Only a person's terminal is attached. A preview or App socket (a dev
211
+ // server's live reload in a forgotten tab) does not hold the Computer up.
212
+ let attached = options.terminal === true;
213
+ const detach = () => {
214
+ if (!attached)
215
+ return;
216
+ attached = false;
217
+ this.#openSockets--;
218
+ // The idle window starts when the person leaves.
219
+ const now = Date.now();
220
+ this.#lastHostedActivity = now;
221
+ this.usage.touchActivity(backing, now);
222
+ };
206
223
  const close = (event) => {
224
+ detach();
207
225
  const code = event.code === 1000 || (event.code >= 3000 && event.code <= 4999)
208
226
  ? event.code
209
227
  : 1000;
@@ -213,6 +231,7 @@ export class FleetLifecycle {
213
231
  server.close(code, event.reason);
214
232
  };
215
233
  const fail = () => {
234
+ detach();
216
235
  if (socket.readyState === WebSocket.OPEN)
217
236
  socket.close(1000, "Terminal transport failed");
218
237
  if (server.readyState === WebSocket.OPEN)
@@ -235,6 +254,8 @@ export class FleetLifecycle {
235
254
  server.binaryType = "arraybuffer";
236
255
  socket.accept();
237
256
  server.accept();
257
+ if (attached)
258
+ this.#openSockets++;
238
259
  return new Response(null, {
239
260
  status: 101,
240
261
  webSocket: client,
@@ -364,7 +385,9 @@ export class FleetLifecycle {
364
385
  /** Whether this Computer is metered without fresh activity: a dispatch is
365
386
  * in flight, or its owner opted into Keep awake. */
366
387
  get awake() {
367
- return (this.#hostedOperations > 0 || computerKeepAwake(this.ports.storage.sql));
388
+ return (this.#hostedOperations > 0 ||
389
+ this.#openSockets > 0 ||
390
+ computerKeepAwake(this.ports.storage.sql));
368
391
  }
369
392
  /** Metering never runs past the last activity of a Computer that is not awake. */
370
393
  billedThrough(runtimeId, at) {
@@ -372,6 +395,19 @@ export class FleetLifecycle {
372
395
  return at;
373
396
  return Math.min(at, this.usage.lastActivity(runtimeId, at) ?? at);
374
397
  }
398
+ /**
399
+ * Whether the host saw no traffic to this VM for the idle window: an SSH
400
+ * session or a served port keeps it up although the Hub saw nothing.
401
+ */
402
+ async quietOnHost(backing, now) {
403
+ if (backing.kind !== "on-box-vm")
404
+ return true;
405
+ const inventory = await this.ports.backend
406
+ .onBoxVmHost(backing.hostId)
407
+ .inventory();
408
+ const vm = inventory.find((entry) => entry.id === this.ports.backend.state.id.toString());
409
+ return (vm === undefined || now - vm.lastActive >= computerContainerSleepAfterMs);
410
+ }
375
411
  /** Whether an idle runtime has passed its sleep window. */
376
412
  sleepDue(runtimeId, now) {
377
413
  if (this.awake)
@@ -382,12 +418,33 @@ export class FleetLifecycle {
382
418
  async observeRuntime(runtimeId, backing, newest) {
383
419
  const now = Date.now();
384
420
  const { running, exitedAt } = await this.readRuntime(runtimeId, backing, newest, now);
385
- if (running && this.sleepDue(runtimeId, now)) {
421
+ // A command Fungi started that is still running is activity: the idle
422
+ // window starts when it ends. A row from before this runtime started is
423
+ // stale (its process died with the old VM) and is not trusted.
424
+ const runtimeStartedAt = this.usage.startedAt(runtimeId) ?? now;
425
+ if (running &&
426
+ this.ports.backend.hasRunningProcesses(attachedBackendId(backing), runtimeStartedAt))
427
+ this.usage.touchActivity(backing, now);
428
+ if (running &&
429
+ !this.hasPendingOperations &&
430
+ this.sleepDue(runtimeId, now) &&
431
+ (await this.quietOnHost(backing, now))) {
386
432
  try {
433
+ // Save the files before the runtime goes: a failed save keeps it up.
434
+ // A write made directly on the VM (SSH, a served port) between this
435
+ // save and the destroy is lost: an accepted, save-length window.
436
+ await this.ports.backend.syncRecycledWorkspace(backing);
387
437
  await this.destroyRuntime(backing, "Computer idle timeout");
438
+ this.#idleStopFailures.delete(runtimeId);
388
439
  }
389
440
  catch (cause) {
441
+ const failures = (this.#idleStopFailures.get(runtimeId) ?? 0) + 1;
442
+ this.#idleStopFailures.set(runtimeId, failures);
390
443
  this.diagnostic("computer_idle_stop_failed", "idle_stop", cause);
444
+ // A save that keeps failing leaves the Computer up until the host's
445
+ // 24 hour backstop ends it unsaved: say so before that.
446
+ if (failures >= 3)
447
+ this.diagnostic("computer_idle_stop_stuck", "idle_stop_stuck", cause);
391
448
  return { running: true, at: this.billedThrough(runtimeId, now) };
392
449
  }
393
450
  // The sleep ended every command still running on this backend; say so.
@@ -15,6 +15,8 @@ export declare class ComputerRuntimeUsage {
15
15
  ensure(): void;
16
16
  started(start: ContainerRuntimeStart): void;
17
17
  touchActivity(backing: HostedBacking, at: number): void;
18
+ /** When an open runtime started, or null when it is not open. */
19
+ startedAt(runtimeId: string): number | null;
18
20
  /** The last recorded activity of an open runtime; a missing record starts now. */
19
21
  lastActivity(runtimeId: string, now: number): number | null;
20
22
  hasOpen(backing: HostedBacking): boolean;
@@ -29,6 +29,16 @@ export class ComputerRuntimeUsage {
29
29
  this.sql.exec("UPDATE hub_computer_runtime_activity SET last_activity_at=MAX(last_activity_at, ?) WHERE runtime_id IN (SELECT runtime_id FROM hub_computer_runtime_usage WHERE backing=? AND ended=0)", at, encodedBacking);
30
30
  this.sql.exec("INSERT OR IGNORE INTO hub_computer_runtime_activity (runtime_id, last_activity_at) SELECT runtime_id, ? FROM hub_computer_runtime_usage WHERE backing=? AND ended=0", at, encodedBacking);
31
31
  }
32
+ /** When an open runtime started, or null when it is not open. */
33
+ startedAt(runtimeId) {
34
+ this.ensure();
35
+ const row = this.sql
36
+ .exec("SELECT started_at FROM hub_computer_runtime_usage WHERE runtime_id=? AND ended=0", runtimeId)
37
+ .toArray()[0];
38
+ return row === undefined
39
+ ? null
40
+ : z.number().int().nonnegative().parse(row.started_at);
41
+ }
32
42
  /** The last recorded activity of an open runtime; a missing record starts now. */
33
43
  lastActivity(runtimeId, now) {
34
44
  this.ensure();
package/dist/index.d.ts CHANGED
@@ -174,6 +174,8 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
174
174
  constructor(ctx: DurableObjectState, env: ComputerEnv);
175
175
  /** The fleet slept this backend after it sat idle; its running commands ended with it. */
176
176
  protected endedByIdleSleep(backendId: string): void;
177
+ /** A command still running on this backend keeps the Computer from idling out. */
178
+ protected hasRunningProcesses(backendId: string, since: number): boolean;
177
179
  /** Host-admitted settings write; egress reads the current durable value. */
178
180
  internetAccess(enabled?: boolean): boolean;
179
181
  /**
@@ -382,6 +384,8 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
382
384
  principal: string;
383
385
  }>;
384
386
  protected withHostedResponse(_backing: HostedBacking, run: () => Promise<Response>): Promise<Response>;
387
+ /** The terminal's upgrade: a person is attached for as long as it stays open. */
388
+ protected withTerminalResponse(backing: HostedBacking, run: () => Promise<Response>): Promise<Response>;
385
389
  /** Host-owned display labels only; never credentials or provider URLs. */
386
390
  protected terminalDisplayEnvironment(): Promise<Record<string, string>>;
387
391
  /** Atomically replace one bounded file only when its raw contents still match. */
package/dist/index.js CHANGED
@@ -620,6 +620,10 @@ export class ComputerDO extends ContainerComputer {
620
620
  endedByIdleSleep(backendId) {
621
621
  this.#processes.endedByIdleSleep(backendId);
622
622
  }
623
+ /** A command still running on this backend keeps the Computer from idling out. */
624
+ hasRunningProcesses(backendId, since) {
625
+ return this.#processes.hasRunning(backendId, since);
626
+ }
623
627
  /** Host-admitted settings write; egress reads the current durable value. */
624
628
  internetAccess(enabled) {
625
629
  return computerInternetAccess(this.state.storage.sql, enabled);
@@ -1929,7 +1933,8 @@ export class ComputerDO extends ContainerComputer {
1929
1933
  accept();
1930
1934
  try {
1931
1935
  const url = await target();
1932
- const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1936
+ // A person's terminal is attached; a preview or App socket is not.
1937
+ const response = await this.withTerminalResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1933
1938
  .port(computerTerminalPort)
1934
1939
  .fetch(new Request(url, request)));
1935
1940
  if (response.status === 101)
@@ -1944,6 +1949,10 @@ export class ComputerDO extends ContainerComputer {
1944
1949
  withHostedResponse(_backing, run) {
1945
1950
  return run();
1946
1951
  }
1952
+ /** The terminal's upgrade: a person is attached for as long as it stays open. */
1953
+ withTerminalResponse(backing, run) {
1954
+ return this.withHostedResponse(backing, run);
1955
+ }
1947
1956
  /** Host-owned display labels only; never credentials or provider URLs. */
1948
1957
  terminalDisplayEnvironment() {
1949
1958
  return Promise.resolve({
@@ -52,6 +52,12 @@ export declare class ComputerProcessInventory {
52
52
  /** The backend selected at admission, retained across reconnects and restarts. */
53
53
  backend(id: string): string | undefined;
54
54
  exited(id: ComputerProcessId, exitCode: number | null, sync?: ComputerProcessSync): ComputerProcess;
55
+ /**
56
+ * Whether a command is still running on this backend. A row that started
57
+ * before `since` (the current runtime's start) belongs to a runtime that has
58
+ * since gone, so its process is gone too and the stale row is not trusted.
59
+ */
60
+ hasRunning(backend: string, since: number): boolean;
55
61
  /**
56
62
  * The Computer slept after sitting idle, so every command still running on
57
63
  * that backend stopped with it. Record them as ended by idle sleep, in one
@@ -222,6 +222,16 @@ export class ComputerProcessInventory {
222
222
  return this.#require(id);
223
223
  });
224
224
  }
225
+ /**
226
+ * Whether a command is still running on this backend. A row that started
227
+ * before `since` (the current runtime's start) belongs to a runtime that has
228
+ * since gone, so its process is gone too and the stale row is not trusted.
229
+ */
230
+ hasRunning(backend, since) {
231
+ return (this.#storage.sql
232
+ .exec("SELECT 1 FROM computer_processes WHERE backend = ? AND state = 'running' AND started_at >= ? LIMIT 1", backend, since)
233
+ .toArray().length > 0);
234
+ }
225
235
  /**
226
236
  * The Computer slept after sitting idle, so every command still running on
227
237
  * that backend stopped with it. Record them as ended by idle sleep, in one
@@ -21895,6 +21895,34 @@ var siteHttpReplySchema = Struct({
21895
21895
  bodyBase64: String4
21896
21896
  });
21897
21897
 
21898
+ // ../puffball/dist/failure-facts.js
21899
+ var storageCategorySchema = object({
21900
+ message: string4().transform((text) => text.slice(0, 512)).pipe(union2([
21901
+ string4().regex(/timeout exceeded when trying to connect/iu).transform(() => "pool_timeout"),
21902
+ string4().regex(/too many clients|remaining connection slots/iu).transform(() => "too_many_connections"),
21903
+ string4().regex(/connection terminated|socket hang up|ECONNRESET/iu).transform(() => "connection_lost"),
21904
+ string4().regex(/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/iu).transform(() => "unreachable"),
21905
+ string4().regex(/too many API requests|too many subrequests/iu).transform(() => "request_limit"),
21906
+ string4().regex(/exceeded timeout|timed out|queued for too long|overloaded/iu).transform(() => "timeout"),
21907
+ string4().regex(/object to be reset|network connection lost|D1 DB reset/iu).transform(() => "reset"),
21908
+ string4().regex(/no such column/iu).transform(() => "missing_column"),
21909
+ string4().regex(/no such table/iu).transform(() => "missing_table"),
21910
+ string4().regex(/SQLITE_CONSTRAINT|constraint failed/iu).transform(() => "constraint"),
21911
+ string4().regex(/SQLITE_BUSY|database is locked/iu).transform(() => "busy"),
21912
+ string4().regex(/SQLITE_TOOBIG|row too large|response too large/iu).transform(() => "size_limit"),
21913
+ string4().regex(/CPU time limit/iu).transform(() => "cpu_limit"),
21914
+ string4().regex(/D1_ERROR|SQLITE_ERROR/iu).transform(() => "database_error")
21915
+ ]))
21916
+ }).transform(({ message }) => message);
21917
+ var withCodeSchema = object({
21918
+ code: union2([
21919
+ string4().regex(/^E[A-Z0-9_]{2,31}$/u),
21920
+ string4().regex(/^[0-9A-Z]{5}$/u)
21921
+ ])
21922
+ });
21923
+ var emptyMessageSchema = object({ message: literal("") });
21924
+ var frameLineSchema = string4().regex(/^\s+at\s/u);
21925
+
21898
21926
  // ../puffball/dist/internal/verified-artifact-snapshot.js
21899
21927
  var DEFAULT_ARTIFACT_SNAPSHOT_POLICY = Object.freeze({ maxBytes: 65536 });
21900
21928
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.18.17",
3
+ "version": "0.19.1",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",
@@ -72,10 +72,10 @@
72
72
  "@fungi.computer/capnweb": "0.12.0-fungi.0",
73
73
  "@fungi.computer/cloudflare-computer": "0.2.1-fungi.4",
74
74
  "@fungi.computer/cordyceps": "0.4.3",
75
- "@fungi.computer/knapsack": "0.4.39",
75
+ "@fungi.computer/knapsack": "0.4.40",
76
76
  "@fungi.computer/seam": "0.2.9",
77
77
  "@fungi.computer/watchdog": "0.1.7",
78
- "@fungi.computer/computer-contract": "0.6.16",
78
+ "@fungi.computer/computer-contract": "0.6.17",
79
79
  "effect": "4.0.2",
80
80
  "just-bash": "3.4.2",
81
81
  "zod": "4.4.3",