@fungi.computer/computer 0.17.0 → 0.18.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.
@@ -48,6 +48,26 @@ async function existingServices() {
48
48
  }
49
49
 
50
50
  /** s6-svc exits 111 when no supervisor listens, which is true of a service that never started. */
51
+ /**
52
+ * What went wrong, for the Hub to say in words. s6 reports its failures only as
53
+ * text, so this is the one place that reads it; callers get the kind.
54
+ */
55
+ function failureOf(error) {
56
+ const text = `${error?.stderr ?? ""}\n${error?.message ?? String(error)}`;
57
+ const lines = text
58
+ .split("\n")
59
+ .map((line) => line.trim())
60
+ .filter((line) => line !== "");
61
+ const kind = /timed out|ETIMEDOUT/u.test(text)
62
+ ? "timeout"
63
+ : /unable to control|supervisor not listening/u.test(text)
64
+ ? "refused"
65
+ : /No such file|ENOENT/u.test(text)
66
+ ? "missing"
67
+ : "other";
68
+ return { failure: kind, detail: (lines.at(-1) ?? "").slice(0, 300) };
69
+ }
70
+
51
71
  async function stopSupervisor(name) {
52
72
  try {
53
73
  await control(name, "-dx");
@@ -164,5 +184,7 @@ try {
164
184
  }
165
185
  } catch (error) {
166
186
  console.error("fungi-services:", error);
187
+ // The last line: the kind of failure, then the last line the command wrote.
188
+ console.error(JSON.stringify(failureOf(error)));
167
189
  process.exit(1);
168
190
  }
@@ -3,6 +3,7 @@ export { checkComputerGrant, type ComputerAdmission } from "./admission.js";
3
3
  export { createFleetBacking } from "./backing.js";
4
4
  export { computerActionSchema, computerProvenanceSchema, computerGrantSchema, computerStateSchema, computerFactSchema, computerBackendViewSchema, localBackendAttachSchema, localBackendDetachSchema, localBackendDetachRequestSchema, ComputerBackingError, type ComputerAction, type ComputerProvenance, type ComputerGrant, type ComputerRuntimeState, type ComputerFact, type ComputerBackendView, type ComputerBackendsProjection, type ComputerBackingChange, type LocalBackendAttachInput, type LocalBackendDetachInput, } from "./wire.js";
5
5
  export { ComputerRuntimeUsage } from "./runtime-usage.js";
6
+ export { ComputerStartDisconnectedError } from "./lifecycle.js";
6
7
  export { computerKeepAwake } from "./keep-awake.js";
7
8
  export { computerUsageIntervalSchema, type ComputerUsageInterval, } from "./wire.js";
8
9
  export { createFleetInventory } from "./inventory.js";
@@ -3,6 +3,7 @@ export { checkComputerGrant } from "./admission.js";
3
3
  export { createFleetBacking } from "./backing.js";
4
4
  export { computerActionSchema, computerProvenanceSchema, computerGrantSchema, computerStateSchema, computerFactSchema, computerBackendViewSchema, localBackendAttachSchema, localBackendDetachSchema, localBackendDetachRequestSchema, ComputerBackingError, } from "./wire.js";
5
5
  export { ComputerRuntimeUsage } from "./runtime-usage.js";
6
+ export { ComputerStartDisconnectedError } from "./lifecycle.js";
6
7
  export { computerKeepAwake } from "./keep-awake.js";
7
8
  export { computerUsageIntervalSchema, } from "./wire.js";
8
9
  export { createFleetInventory } from "./inventory.js";
@@ -3,6 +3,14 @@ import type { ComputerDO as NativeComputerDO, OnBoxVmContainerHost } from "../in
3
3
  import { type ContainerRuntimeStart, type HostedBacking, type AttachedBackend, type AttachedBackendView } from "../computer-backends.js";
4
4
  import { ComputerRuntimeUsage } from "./runtime-usage.js";
5
5
  import type { ComputerGrant } from "./wire.js";
6
+ /**
7
+ * The hosted runtime was admitted and its workspace pushed, then it was not
8
+ * running. The name survives a Durable Object RPC, so a caller that only sees
9
+ * the error cross it can still say what happened.
10
+ */
11
+ export declare class ComputerStartDisconnectedError extends Error {
12
+ constructor();
13
+ }
6
14
  /** Runtime observations consumed by the host; never host callbacks. */
7
15
  export type FleetLifecycleFact = Readonly<{
8
16
  kind: "reservation.release" | "reservation.monitor";
@@ -5,6 +5,17 @@ import { z } from "zod";
5
5
  import { ComputerRuntimeUsage } from "./runtime-usage.js";
6
6
  import { checkComputerGrant } from "./admission.js";
7
7
  import { computerKeepAwake } from "./keep-awake.js";
8
+ /**
9
+ * The hosted runtime was admitted and its workspace pushed, then it was not
10
+ * running. The name survives a Durable Object RPC, so a caller that only sees
11
+ * the error cross it can still say what happened.
12
+ */
13
+ export class ComputerStartDisconnectedError extends Error {
14
+ constructor() {
15
+ super("Hosted Computer disconnected while starting");
16
+ this.name = "ComputerStartDisconnectedError";
17
+ }
18
+ }
8
19
  const vmRecycleAfterMs = 23 * 60 * 60 * 1_000;
9
20
  const vmRecycleQuietMs = 30_000;
10
21
  const runtimeWatchSchema = z.lazy(() => z.coerce.number().int().min(1_000).max(3_600_000).catch(60_000));
@@ -72,7 +83,7 @@ export class FleetLifecycle {
72
83
  await this.ports.backend.workspace().push(hosted.id);
73
84
  });
74
85
  if (!(await this.ports.backend.containerRunning(hosted.backing)))
75
- throw new Error("Hosted Computer disconnected while starting");
86
+ throw new ComputerStartDisconnectedError();
76
87
  return { state: "running" };
77
88
  }
78
89
  finally {
package/dist/index.js CHANGED
@@ -51,7 +51,8 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
51
51
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
52
  });
53
53
  import { boundExecStream } from "./exec-output.js";
54
- import { portPreviewFailure, portPreviewReply } from "./port-failure.js";
54
+ import { portPreviewFailure } from "./port-failure.js";
55
+ import { forwardPreviewWaitingForPort } from "./preview-wait.js";
55
56
  export { createLocalBackendReplayStore } from "./local-backend-replay.js";
56
57
  import { computerInternetAccess } from "./internet-access.js";
57
58
  import { createComputerVaultReferences, isVaultExecutionContext, vaultExecutionHooks, } from "./vault-references.js";
@@ -1015,10 +1016,19 @@ export class ComputerDO extends ContainerComputer {
1015
1016
  const hosted = this.hostedRoute();
1016
1017
  if (hosted === undefined)
1017
1018
  throw new ComputerBackendUnavailableError("no_backend");
1018
- const response = await this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1019
- .port(port)
1020
- .fetch(new Request(forwarded, { headers })));
1021
- return await portPreviewReply(response, request, port);
1019
+ // A declared, enabled service on this port is still starting after a wake
1020
+ // while the port is closed: wait for it, up to 20 s.
1021
+ const service = this.services
1022
+ .list()
1023
+ .find(({ enabled, port: owned }) => enabled && owned === port);
1024
+ return await forwardPreviewWaitingForPort({
1025
+ service: service === undefined ? undefined : { name: service.name, port },
1026
+ port,
1027
+ request,
1028
+ attempt: () => this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
1029
+ .port(port)
1030
+ .fetch(new Request(forwarded, { headers }))),
1031
+ });
1022
1032
  }
1023
1033
  catch (cause) {
1024
1034
  console.error("Computer runtime operation failed", cause);
@@ -6,13 +6,21 @@ declare const hostRefusalSchema: Schema.Literals<readonly ["not_running", "not_l
6
6
  * the Computer answers on that port. `unreachable`: Fungi could not reach the
7
7
  * Computer. `expired`: the preview link's five-minute ticket ran out.
8
8
  */
9
- export type PortPreviewFailure = Schema.Schema.Type<typeof hostRefusalSchema> | "unreachable" | "expired";
9
+ export type PortPreviewFailure = Schema.Schema.Type<typeof hostRefusalSchema> | "unreachable" | "expired" | "service_timeout";
10
+ /**
11
+ * The VM host's typed refusal, or null when the reply is the guest's own.
12
+ * vmd pipes an upgrade's bytes raw, so on an upgrade request the header could
13
+ * be the guest's and is never read.
14
+ */
15
+ export declare function portPreviewRefusal(response: Response, request: Request): PortPreviewFailure | null;
16
+ /** How long a preview waits for a declared service to open its port. */
17
+ export declare const declaredPortWaitSeconds = 20;
10
18
  /**
11
19
  * The one answer a failed preview gives: a styled page in plain words for a
12
20
  * browser document, or `{ error: reason }` for a script's request. Raw
13
21
  * upstream text never reaches the viewer.
14
22
  */
15
- export declare function portPreviewFailure(reason: PortPreviewFailure, request: Request, port?: number): Promise<Response>;
23
+ export declare function portPreviewFailure(reason: PortPreviewFailure, request: Request, port?: number, service?: string): Promise<Response>;
16
24
  /**
17
25
  * What a preview answers for a forwarded port reply: the VM host's own
18
26
  * refusal in plain words, or the guest's reply as it is, minus cookies.
@@ -17,12 +17,14 @@ const hostRefusalSchema = Schema.Literals([
17
17
  * vmd pipes an upgrade's bytes raw, so on an upgrade request the header could
18
18
  * be the guest's and is never read.
19
19
  */
20
- function hostPortRefusal(response, request) {
20
+ export function portPreviewRefusal(response, request) {
21
21
  if (request.headers.has("upgrade"))
22
22
  return null;
23
23
  const named = Schema.decodeUnknownOption(hostRefusalSchema)(response.headers.get(portFailureHeader));
24
24
  return Option.isSome(named) ? named.value : null;
25
25
  }
26
+ /** How long a preview waits for a declared service to open its port. */
27
+ export const declaredPortWaitSeconds = 20;
26
28
  const copy = {
27
29
  not_running: () => ({
28
30
  title: "This Computer is asleep",
@@ -42,12 +44,23 @@ const copy = {
42
44
  title: "This preview link has expired",
43
45
  detail: "Open the preview again from Fungi to get a fresh link.",
44
46
  }),
47
+ service_timeout: (port, service) => ({
48
+ title: service === undefined || port === undefined
49
+ ? "The service didn't open its port in time"
50
+ : serviceTimeoutMessage(service, port),
51
+ detail: "Check its output under Services on this Computer's card, then reload this page.",
52
+ }),
45
53
  };
54
+ /** The one sentence for a declared service that never opened its port. */
55
+ function serviceTimeoutMessage(service, port) {
56
+ return `${service} didn't open port ${String(port)} within ${String(declaredPortWaitSeconds)} s`;
57
+ }
46
58
  const statuses = {
47
59
  not_running: 503,
48
60
  not_listening: 502,
49
61
  unreachable: 502,
50
62
  expired: 403,
63
+ service_timeout: 504,
51
64
  };
52
65
  // The preview origin is isolated and loads no Fungi asset, so the page's
53
66
  // styling travels inline and follows the viewer's light or dark scheme.
@@ -67,12 +80,19 @@ a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
67
80
  * browser document, or `{ error: reason }` for a script's request. Raw
68
81
  * upstream text never reaches the viewer.
69
82
  */
70
- export async function portPreviewFailure(reason, request, port) {
83
+ export async function portPreviewFailure(reason, request, port, service) {
71
84
  const headers = { "Cache-Control": "no-store" };
72
85
  const status = statuses[reason];
73
86
  if (request.headers.get("sec-fetch-dest") !== "document")
74
- return Response.json({ error: reason }, { status, headers });
75
- const { title, detail } = copy[reason](port);
87
+ return Response.json(reason === "service_timeout"
88
+ ? {
89
+ error: reason,
90
+ message: service === undefined || port === undefined
91
+ ? "The service didn't open its port in time"
92
+ : serviceTimeoutMessage(service, port),
93
+ }
94
+ : { error: reason }, { status, headers });
95
+ const { title, detail } = copy[reason](port, service);
76
96
  const page = await html `<!doctype html>
77
97
  <html lang="en">
78
98
  <meta charset="utf-8" />
@@ -95,7 +115,7 @@ export async function portPreviewFailure(reason, request, port) {
95
115
  * refusal in plain words, or the guest's reply as it is, minus cookies.
96
116
  */
97
117
  export async function portPreviewReply(response, request, port) {
98
- const refused = hostPortRefusal(response, request);
118
+ const refused = portPreviewRefusal(response, request);
99
119
  if (refused !== null) {
100
120
  await response.body?.cancel();
101
121
  return await portPreviewFailure(refused, request, port);
@@ -0,0 +1,24 @@
1
+ /** How long a preview waits for a declared service to open its port. */
2
+ export declare const declaredPortWaitMs: number;
3
+ /** A declared, enabled service that owns the previewed port. */
4
+ export type PreviewedService = Readonly<{
5
+ name: string;
6
+ port: number;
7
+ }>;
8
+ /**
9
+ * Forward one preview request. When an enabled declared service owns the port,
10
+ * a closed port is the service still starting after a wake, so keep trying for
11
+ * up to 20 s and then say which service never opened which port. A port no
12
+ * service declares is answered at once, as is any request that cannot be
13
+ * replayed (a body, or an upgrade): the host's refusal means it never reached
14
+ * the guest, but a streamed body is already spent.
15
+ */
16
+ export declare function forwardPreviewWaitingForPort(options: {
17
+ service: PreviewedService | undefined;
18
+ request: Request;
19
+ port: number;
20
+ /** One try against the guest; throws when the Computer cannot be reached. */
21
+ attempt: () => Promise<Response>;
22
+ now?: () => number;
23
+ delay?: (ms: number) => Promise<void>;
24
+ }): Promise<Response>;
@@ -0,0 +1,47 @@
1
+ import { declaredPortWaitSeconds, portPreviewFailure, portPreviewReply, portPreviewRefusal, } from "./port-failure.js";
2
+ /** How long a preview waits for a declared service to open its port. */
3
+ export const declaredPortWaitMs = declaredPortWaitSeconds * 1_000;
4
+ const pollMs = 500;
5
+ /**
6
+ * Forward one preview request. When an enabled declared service owns the port,
7
+ * a closed port is the service still starting after a wake, so keep trying for
8
+ * up to 20 s and then say which service never opened which port. A port no
9
+ * service declares is answered at once, as is any request that cannot be
10
+ * replayed (a body, or an upgrade): the host's refusal means it never reached
11
+ * the guest, but a streamed body is already spent.
12
+ */
13
+ export async function forwardPreviewWaitingForPort(options) {
14
+ const { service, request, attempt } = options;
15
+ const now = options.now ?? (() => Date.now());
16
+ const delay = options.delay ??
17
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
18
+ const { port } = options;
19
+ const replayable = service !== undefined &&
20
+ request.body === null &&
21
+ !request.headers.has("upgrade");
22
+ const reply = (response) => portPreviewReply(response, request, port);
23
+ if (!replayable) {
24
+ const response = await attempt();
25
+ return await reply(response);
26
+ }
27
+ const deadline = now() + declaredPortWaitMs;
28
+ let last;
29
+ for (;;) {
30
+ last = await tryOnce(attempt);
31
+ if (last.ok) {
32
+ if (portPreviewRefusal(last.response, request) !== "not_listening")
33
+ return await reply(last.response);
34
+ await last.response.body?.cancel();
35
+ }
36
+ // A failed try is the Computer unreachable this time: it may be mid-start.
37
+ if (now() >= deadline || request.signal.aborted)
38
+ break;
39
+ await delay(Math.min(pollMs, Math.max(1, deadline - now())));
40
+ }
41
+ if (!last.ok)
42
+ throw last.cause;
43
+ return await portPreviewFailure("service_timeout", request, port, service.name);
44
+ }
45
+ function tryOnce(attempt) {
46
+ return attempt().then((response) => ({ ok: true, response }), (cause) => ({ ok: false, cause }));
47
+ }
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import type { ComputerServiceInventory, ComputerServicesApply } from "./services.js";
2
3
  /** The command result `applyDeclaredServices` needs from the Computer's exec path. */
3
4
  export type ServicesCommandResult = Readonly<{
@@ -6,12 +7,30 @@ export type ServicesCommandResult = Readonly<{
6
7
  stdout: string;
7
8
  stderr: string;
8
9
  }>;
10
+ /** How a `fungi-services` command failed: its kind, and the last line it wrote. */
11
+ declare const servicesFailureSchema: z.ZodObject<{
12
+ failure: z.ZodEnum<{
13
+ refused: "refused";
14
+ missing: "missing";
15
+ timeout: "timeout";
16
+ other: "other";
17
+ }>;
18
+ detail: z.ZodString;
19
+ }, z.core.$strict>;
20
+ export type ComputerServicesFailure = z.output<typeof servicesFailureSchema>;
21
+ /**
22
+ * The failure `fungi-services` reported on stderr. A command that wrote none
23
+ * (a crash, a stopped runtime) is `other`, with the last line it wrote.
24
+ */
25
+ export declare function servicesFailureOf(result: ServicesCommandResult): ComputerServicesFailure;
9
26
  /** `fungi-services apply` did not finish; the Computer's services may be stopped. */
10
27
  export declare class ComputerServicesApplyError extends Error {
28
+ readonly result: ServicesCommandResult;
11
29
  constructor(result: ServicesCommandResult);
12
30
  }
13
31
  /** A read or control command of `fungi-services` did not finish. */
14
32
  export declare class ComputerServicesCommandError extends Error {
33
+ readonly result: ServicesCommandResult;
15
34
  constructor(operation: string, result: ServicesCommandResult);
16
35
  }
17
36
  /**
@@ -32,3 +51,4 @@ export declare function applyDeclaredServices(options: {
32
51
  run: (command: string) => Promise<ServicesCommandResult>;
33
52
  whenEmpty?: "run" | "skip";
34
53
  }): Promise<"applied" | "none">;
54
+ export {};
@@ -1,15 +1,38 @@
1
+ import { z } from "zod";
2
+ /** How a `fungi-services` command failed: its kind, and the last line it wrote. */
3
+ const servicesFailureSchema = z.strictObject({
4
+ failure: z.enum(["refused", "missing", "timeout", "other"]),
5
+ detail: z.string(),
6
+ });
7
+ /**
8
+ * The failure `fungi-services` reported on stderr. A command that wrote none
9
+ * (a crash, a stopped runtime) is `other`, with the last line it wrote.
10
+ */
11
+ export function servicesFailureOf(result) {
12
+ const last = result.stderr.trim().split("\n").at(-1) ?? "";
13
+ try {
14
+ return servicesFailureSchema.parse(JSON.parse(last));
15
+ }
16
+ catch {
17
+ return { failure: "other", detail: last };
18
+ }
19
+ }
1
20
  /** `fungi-services apply` did not finish; the Computer's services may be stopped. */
2
21
  export class ComputerServicesApplyError extends Error {
22
+ result;
3
23
  constructor(result) {
4
24
  super(`Computer services could not be applied (${result.status}, exit ${String(result.exitCode)}): ${result.stderr.slice(0, 500)}`);
5
25
  this.name = "ComputerServicesApplyError";
26
+ this.result = result;
6
27
  }
7
28
  }
8
29
  /** A read or control command of `fungi-services` did not finish. */
9
30
  export class ComputerServicesCommandError extends Error {
31
+ result;
10
32
  constructor(operation, result) {
11
33
  super(`Computer services ${operation} failed (${result.status}, exit ${String(result.exitCode)}): ${result.stderr.slice(0, 500)}`);
12
34
  this.name = "ComputerServicesCommandError";
35
+ this.result = result;
13
36
  }
14
37
  }
15
38
  /**
@@ -20840,6 +20840,7 @@ var appCapabilityIds = [
20840
20840
  "agent.avatar",
20841
20841
  "agent.instructions",
20842
20842
  "agent.toolPolicy",
20843
+ "agent.extensions",
20843
20844
  "agent.stop",
20844
20845
  "agent.read",
20845
20846
  "agent.send",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.17.0",
3
+ "version": "0.18.1",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",
@@ -54,6 +54,10 @@
54
54
  "./services": {
55
55
  "types": "./dist/services.d.ts",
56
56
  "import": "./dist/services.js"
57
+ },
58
+ "./services-apply": {
59
+ "types": "./dist/services-apply.d.ts",
60
+ "import": "./dist/services-apply.js"
57
61
  }
58
62
  },
59
63
  "files": [
@@ -68,10 +72,10 @@
68
72
  "@fungi.computer/capnweb": "0.12.0-fungi.0",
69
73
  "@fungi.computer/cloudflare-computer": "0.2.1-fungi.3",
70
74
  "@fungi.computer/cordyceps": "0.4.3",
71
- "@fungi.computer/knapsack": "0.4.24",
75
+ "@fungi.computer/knapsack": "0.4.25",
72
76
  "@fungi.computer/seam": "0.2.7",
73
77
  "@fungi.computer/watchdog": "0.1.5",
74
- "@fungi.computer/computer-contract": "0.6.0",
78
+ "@fungi.computer/computer-contract": "0.6.1",
75
79
  "effect": "4.0.2",
76
80
  "just-bash": "3.4.2",
77
81
  "zod": "4.4.3",