@fungi.computer/computer 0.6.3 → 0.8.0

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.
package/README.md CHANGED
@@ -1,93 +1,21 @@
1
- # Computer runtime
1
+ # Computer (`@fungi.computer/computer`)
2
2
 
3
- This private runtime hosts one logical Fungi Computer: a SQLite-backed workspace
4
- of files, admitted operations, and optional execution backends. The Hub composes
5
- it with Team authorization, capacity and billing. The runtime is not an
6
- independently installed npm VM service and does not own Team roles.
3
+ A Fungi Computer is a durable workspace for Agents: files in SQLite inside a
4
+ Durable Object, with a Linux container or an in-Worker shell behind it to run
5
+ commands, processes and ports. Oyster's standalone host runs one; the Fungi Hub
6
+ composes it with Team authorization, capacity and billing.
7
7
 
8
- ## Fleet contracts
8
+ ## Install
9
9
 
10
- Node tooling and browser consumers can import the grant/fact schemas and types
11
- from `@fungi.computer/computer/fleet/wire`, and backing descriptions from
12
- `@fungi.computer/computer/backing`. These entries do not load Worker runtime
13
- declarations. The `./fleet` lifecycle and main Computer entry require the host
14
- runtime's Cloudflare Workers types.
15
-
16
- The packed stranger check exercises these Node-safe entries and the egress
17
- helpers after a cold install of the runtime closure. The fork's companion check
18
- parses the published shell-module groups used by the Computer image with Acorn
19
- and checks their declarations. Neither check starts a Computer, executes a
20
- Worker shell, or qualifies the Worker/Workspace/Git SDK in a Node type
21
- environment.
22
-
23
- `@fungi.computer/computer/fleet` owns the host-neutral grant check, backing
24
- records and fact contracts. A host authenticates its caller and supplies a
25
- `ComputerGrant`: one Computer, explicit actions, an expiry, optional host-owned
26
- egress data, plus opaque actor/invocation provenance. `checkComputerGrant`
27
- returns `admitted` or `Refused`; grants impose no paid-usage budget. A caller's
28
- per-command timeout remains a command parameter enforced by the operation
29
- executor. Hub credit enforcement remains on its existing funded/unfunded
30
- admission and `creditChanged` → credit-publication restate/stop path.
31
-
32
- `createFleetBacking` accepts the maintained SQLite owner. Creation records a
33
- plain backing decision once. Explicit fleet-default and Computer overrides
34
- remain possible; local attachment keeps replay identity, actor ownership and
35
- detach cancellation. Mutations return complete backend projections rather than
36
- calling a host or delivering messages. The composing host can include the call
37
- and durable outbox staging in its SQLite transaction. Its deployment chooses the
38
- offered backing kinds; the fleet never rereads deployment configuration.
39
-
40
- `ComputerFact` describes process exit, file writes, egress, lifecycle and
41
- runtime interval observations with provenance. CPU time is nullable when
42
- unmeasured. The host reads these records and owns settlement and delivery.
43
- Host-specific egress data is decoded by its host; the fleet contract carries
44
- JSON data without importing the host's policy.
45
-
46
- The fleet also owns inventory/replay receipts, running-slot storage, runtime
47
- intervals, and native lifecycle activity/recycling. Inventory admission stays at
48
- the host: an existing create receipt is checked before funding a new create.
49
- Slot capacity is explicit infrastructure input; grants carry no usage cap.
50
- `FleetLifecycle.run` checks a host-issued start grant before native execution.
51
- The host consumes returned reservation/diagnostic facts and
52
- `ComputerRuntimeUsage.pendingFacts` interval facts; it owns credit changes,
53
- usage delivery, logging, and Team Git. Acknowledgment retains the existing
54
- runtime checkpoint identity and occurs only after delivery. Transport activity,
55
- idle sleep, and VM recycle sequencing retain the existing runtime behavior. The
56
- Hub records creation backing facts for its declared known Computers at
57
- initialization; the fleet never derives missing records on reads.
58
-
59
- The Hub projects each current resource decision into a grant for the requested
60
- Files or execution permission. It carries the stored decision's expiry and
61
- actor/attachment identity. Native acceptance still rechecks the current Hub
62
- decision before fleet admission; a grant is never cached across that check. The
63
- Hub projects interval facts into its existing usage Post payload without
64
- changing billing or credit-stop behavior.
65
-
66
- The repository architecture test rejects upward imports from this runtime into
67
- Apps, Billing, Broker or Team/plan modules, including type and dynamic imports.
68
-
69
- ## Source setup
70
-
71
- Use a configured repository checkout with the pinned Node and pnpm tools. Run
72
- from the repository root:
10
+ Install it beside Oyster, whose example `wrangler.jsonc` builds the Computer's
11
+ container from this package's `Dockerfile`:
73
12
 
74
13
  ```sh
75
- pnpm turbo:run run build --filter=@fungi.computer/computer
76
- pnpm --filter @fungi.computer/computer typecheck
77
- pnpm --filter @fungi.computer/computer lint
78
- pnpm turbo:run run test --filter=@fungi.computer/computer
14
+ npm install @fungi.computer/oyster @fungi.computer/computer
79
15
  ```
80
16
 
81
- The build emits the runtime and copies its daemon/build assets. The test graph
82
- assembles and builds the local container image before starting native Worker
83
- checks. Docker owns its layer cache; the image build has a separate bounded
84
- proof lifetime, so cold compilation does not consume the Worker response
85
- deadline. Before invoking a native test file directly, run
86
- `pnpm turbo:run run build:container --filter=@fungi.computer/computer`.
87
-
88
- The test suite uses disposable Workers and proof containers, so container proofs
89
- require a working local Docker/Workers environment. These commands do not deploy
90
- a Hub, publish an App or replace a production Computer image.
17
+ The [Oyster README](https://github.com/fungi-computer/oyster) deploys both. The
18
+ runtime itself does not own Team roles or billing.
91
19
 
92
20
  ## Files and operation results
93
21
 
@@ -212,6 +140,67 @@ Computer control endpoints to the browser.
212
140
  the host's admitted egress composition; a native container binding and the
213
141
  on-box host adapter are separate configuration paths.
214
142
 
143
+ ## Fleet contracts
144
+
145
+ Node tooling and browser consumers can import the grant/fact schemas and types
146
+ from `@fungi.computer/computer/fleet/wire`, and backing descriptions from
147
+ `@fungi.computer/computer/backing`. These entries do not load Worker runtime
148
+ declarations. The `./fleet` lifecycle and main Computer entry require the host
149
+ runtime's Cloudflare Workers types.
150
+
151
+ The packed stranger check exercises these Node-safe entries and the egress
152
+ helpers after a cold install of the runtime closure. The fork's companion check
153
+ parses the published shell-module groups used by the Computer image with Acorn
154
+ and checks their declarations. Neither check starts a Computer, executes a
155
+ Worker shell, or qualifies the Worker/Workspace/Git SDK in a Node type
156
+ environment.
157
+
158
+ `@fungi.computer/computer/fleet` owns the host-neutral grant check, backing
159
+ records and fact contracts. A host authenticates its caller and supplies a
160
+ `ComputerGrant`: one Computer, explicit actions, an expiry, optional host-owned
161
+ egress data, plus opaque actor/invocation provenance. `checkComputerGrant`
162
+ returns `admitted` or `Refused`; grants impose no paid-usage budget. A caller's
163
+ per-command timeout remains a command parameter enforced by the operation
164
+ executor. Hub credit enforcement remains on its existing funded/unfunded
165
+ admission and `creditChanged` → credit-publication restate/stop path.
166
+
167
+ `createFleetBacking` accepts the maintained SQLite owner. Creation records a
168
+ plain backing decision once. Explicit fleet-default and Computer overrides
169
+ remain possible; local attachment keeps replay identity, actor ownership and
170
+ detach cancellation. Mutations return complete backend projections rather than
171
+ calling a host or delivering messages. The composing host can include the call
172
+ and durable outbox staging in its SQLite transaction. Its deployment chooses the
173
+ offered backing kinds; the fleet never rereads deployment configuration.
174
+
175
+ `ComputerFact` describes process exit, file writes, egress, lifecycle and
176
+ runtime interval observations with provenance. CPU time is nullable when
177
+ unmeasured. The host reads these records and owns settlement and delivery.
178
+ Host-specific egress data is decoded by its host; the fleet contract carries
179
+ JSON data without importing the host's policy.
180
+
181
+ The fleet also owns inventory/replay receipts, running-slot storage, runtime
182
+ intervals, and native lifecycle activity/recycling. Inventory admission stays at
183
+ the host: an existing create receipt is checked before funding a new create.
184
+ Slot capacity is explicit infrastructure input; grants carry no usage cap.
185
+ `FleetLifecycle.run` checks a host-issued start grant before native execution.
186
+ The host consumes returned reservation/diagnostic facts and
187
+ `ComputerRuntimeUsage.pendingFacts` interval facts; it owns credit changes,
188
+ usage delivery, logging, and Team Git. Acknowledgment retains the existing
189
+ runtime checkpoint identity and occurs only after delivery. Transport activity,
190
+ idle sleep, and VM recycle sequencing retain the existing runtime behavior. The
191
+ Hub records creation backing facts for its declared known Computers at
192
+ initialization; the fleet never derives missing records on reads.
193
+
194
+ The Hub projects each current resource decision into a grant for the requested
195
+ Files or execution permission. It carries the stored decision's expiry and
196
+ actor/attachment identity. Native acceptance still rechecks the current Hub
197
+ decision before fleet admission; a grant is never cached across that check. The
198
+ Hub projects interval facts into its existing usage Post payload without
199
+ changing billing or credit-stop behavior.
200
+
201
+ The repository architecture test rejects upward imports from this runtime into
202
+ Apps, Billing, Broker or Team/plan modules, including type and dynamic imports.
203
+
215
204
  ## Image and build inputs
216
205
 
217
206
  The [Dockerfile](Dockerfile) builds the Linux environment with pinned Node,
@@ -261,3 +250,28 @@ service-relative routing. The host supplies its selector decoder, hostname
261
250
  policy and live admission callback. Admission runs at the exposed-port listing
262
251
  and forwarding acceptance points; a ticket is never a grant. Hub retains its
263
252
  local App projection and signed-ticket hostname configuration.
253
+
254
+ ## Contribute
255
+
256
+ Use a configured repository checkout with the pinned Node and pnpm tools. Run
257
+ from the repository root:
258
+
259
+ ```sh
260
+ pnpm turbo:run run build --filter=@fungi.computer/computer
261
+ pnpm --filter @fungi.computer/computer typecheck
262
+ pnpm --filter @fungi.computer/computer lint
263
+ pnpm turbo:run run test --filter=@fungi.computer/computer
264
+ ```
265
+
266
+ The build emits the runtime and copies its daemon/build assets. The test graph
267
+ assembles and builds the local container image before starting native Worker
268
+ checks. Docker owns its layer cache; the image build has a separate bounded
269
+ proof lifetime, so cold compilation does not consume the Worker response
270
+ deadline. Before invoking a native test file directly, run
271
+ `pnpm turbo:run run build:container --filter=@fungi.computer/computer`.
272
+
273
+ The test suite uses disposable Workers and proof containers, so container proofs
274
+ require a working local Docker/Workers environment. These commands do not deploy
275
+ a Hub, publish an App or replace a production Computer image.
276
+
277
+ MIT. See [`LICENSE`](LICENSE).
@@ -114,10 +114,12 @@ export async function ensureNativePatchArtifact({
114
114
  }
115
115
  if (await published()) return restore("hit");
116
116
  // Compilation runs in an asynchronous child, so the maintained lock heartbeat stays live.
117
+ // Wait as long as the holder heartbeats: a contended box can compile for
118
+ // longer than any fixed retry budget, and a dead holder's lock goes stale.
117
119
  const release = await lockfile.lock(key, {
118
120
  stale: 120_000,
119
121
  update: 20_000,
120
- retries: { retries: 600, factor: 1.5, minTimeout: 50, maxTimeout: 1_000 },
122
+ retries: { forever: true, factor: 1.5, minTimeout: 50, maxTimeout: 1_000 },
121
123
  });
122
124
  let staging;
123
125
  try {
@@ -10,6 +10,8 @@ export declare function createFleetInventory(options: Readonly<{
10
10
  replay: (actor: FleetActor, request: ComputerCreateRequest) => FleetComputer | null;
11
11
  create: (actor: FleetActor, request: ComputerCreateRequest) => FleetComputer;
12
12
  read: (computerId: string) => FleetComputer | null;
13
+ creator: (computerId: string) => FleetActor | null;
14
+ retire: (computerId: string) => "retired" | "already_retired" | null;
13
15
  list: (input: ComputerPage) => {
14
16
  readonly computers: Readonly<{
15
17
  computerId: string;
@@ -120,8 +120,9 @@ export function createFleetInventory(options) {
120
120
  const stored = rowSchema.safeParse(sql
121
121
  .exec(`${selectRow} WHERE computer_id=?`, receipt.data.computer_id)
122
122
  .toArray()[0]);
123
+ if (stored.success && stored.data.active === 0)
124
+ throw new ComputerInventoryError("request_conflict");
123
125
  if (!stored.success ||
124
- stored.data.active === 0 ||
125
126
  stored.data.name !== receipt.data.name ||
126
127
  stored.data.actor_kind !== receipt.data.actor_kind ||
127
128
  stored.data.actor_id !== receipt.data.actor_id)
@@ -148,5 +149,49 @@ export function createFleetInventory(options) {
148
149
  throw new ComputerInventoryError("partial_init");
149
150
  return created;
150
151
  });
151
- return { ensure, replay, create, read, list, ids, count };
152
+ /** Who created an active Computer; authorization belongs to the host. */
153
+ const creator = (computerId) => {
154
+ const raw = sql
155
+ .exec(`${selectRow} WHERE computer_id=?`, computerId)
156
+ .toArray()[0];
157
+ if (raw === undefined)
158
+ return null;
159
+ const row = rowSchema.safeParse(raw);
160
+ if (!row.success)
161
+ throw new ComputerInventoryError("partial_init");
162
+ return row.data.active === 0
163
+ ? null
164
+ : { kind: row.data.actor_kind, id: row.data.actor_id };
165
+ };
166
+ /**
167
+ * Retire a Computer: it leaves the inventory, its name becomes free, and a
168
+ * replayed create refuses. The row stays as the retirement record so a
169
+ * retried teardown still knows the Computer was this Team's.
170
+ */
171
+ const retire = (computerId) => options.transactionSync(() => {
172
+ const raw = sql
173
+ .exec(`${selectRow} WHERE computer_id=?`, computerId)
174
+ .toArray()[0];
175
+ if (raw === undefined)
176
+ return null;
177
+ const row = rowSchema.safeParse(raw);
178
+ if (!row.success)
179
+ throw new ComputerInventoryError("partial_init");
180
+ if (row.data.active === 0)
181
+ return "already_retired";
182
+ // The Computer ID is unique, so it frees the name without a collision.
183
+ sql.exec("UPDATE hub_team_computers SET active=0,name=computer_id,updated_at=? WHERE computer_id=?", Date.now(), computerId);
184
+ return "retired";
185
+ });
186
+ return {
187
+ ensure,
188
+ replay,
189
+ create,
190
+ read,
191
+ creator,
192
+ retire,
193
+ list,
194
+ ids,
195
+ count,
196
+ };
152
197
  }
@@ -22,6 +22,7 @@ export declare const computerActionSchema: z.ZodEnum<{
22
22
  processStart: "processStart";
23
23
  processList: "processList";
24
24
  processKill: "processKill";
25
+ processLogs: "processLogs";
25
26
  exposePort: "exposePort";
26
27
  unexposePort: "unexposePort";
27
28
  listPorts: "listPorts";
@@ -57,6 +58,7 @@ export declare const computerGrantSchema: z.ZodObject<{
57
58
  processStart: "processStart";
58
59
  processList: "processList";
59
60
  processKill: "processKill";
61
+ processLogs: "processLogs";
60
62
  exposePort: "exposePort";
61
63
  unexposePort: "unexposePort";
62
64
  listPorts: "listPorts";
@@ -10,6 +10,7 @@ export const computerActionSchema = z.enum([
10
10
  "processStart",
11
11
  "processList",
12
12
  "processKill",
13
+ "processLogs",
13
14
  "exposePort",
14
15
  "unexposePort",
15
16
  "listPorts",
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ import { type IWorkspaceContainerAPI } from "@fungi.computer/cloudflare-computer
6
6
  import { DurableObject } from "cloudflare:workers";
7
7
  import type { FilesPort } from "@fungi.computer/knapsack";
8
8
  import { z } from "zod";
9
- import { type ComputerExecutionBudget, type ComputerExecutionHostHooks, type ComputerExecRequest, type ComputerOperationResult, type ComputerFileReadInput, type ComputerFileByteReadInput, type ComputerFileReplacement, type ComputerFileReplacementResult, type ComputerValue, writeInputSchema, writeOutputSchema, type ComputerProcess } from "@fungi.computer/computer-contract";
9
+ import { type ComputerExecutionBudget, type ComputerExecutionHostHooks, type ComputerExecRequest, type ComputerOperationResult, type ComputerFileReadInput, type ComputerFileByteReadInput, type ComputerFileReplacement, type ComputerFileReplacementResult, type ComputerValue, writeInputSchema, writeOutputSchema, processLogsOutputSchema, type ComputerProcess } from "@fungi.computer/computer-contract";
10
10
  import { createWorkspaceFilesPort } from "./files.js";
11
11
  import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement } from "./on-box-vm.js";
12
12
  import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
@@ -275,6 +275,9 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
275
275
  protected listProcessesAfterAcceptance(accept: () => void): Promise<{
276
276
  processes: ComputerProcess[];
277
277
  }>;
278
+ /** The retained last output lines of one process, with its record. */
279
+ processLogs(input: ComputerValue): z.output<typeof processLogsOutputSchema>;
280
+ protected processLogsAfterAcceptance(input: ComputerValue, accept: () => void): z.output<typeof processLogsOutputSchema>;
278
281
  /** Send SIGTERM to one running process; its exit is recorded when observed. */
279
282
  killProcess(input: ComputerValue): Promise<{
280
283
  process: ComputerProcess;
package/dist/index.js CHANGED
@@ -67,13 +67,13 @@ import { z } from "zod";
67
67
  import { SystemTrustContainerBackend } from "./container-system-trust.js";
68
68
  import { computerTransportBackend } from "./transport-backend.js";
69
69
  import { PullPendingTracker } from "./pull-pending.js";
70
- import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
70
+ import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
71
71
  import { createWorkspaceFilesPort, readBoundedWorkspaceText, listWorkspaceFiles, } from "./files.js";
72
72
  import { computerExecutionResult } from "./execution-result.js";
73
73
  import { ComputerOperationRecord } from "./operation-record.js";
74
74
  import { createComputerExecutionLifecycle } from "./execution-lifecycle.js";
75
75
  import { applyWorkspacePatch } from "./files-patch.js";
76
- import { ComputerProcessInventory, drainProcessExit, failedObservation, observeProcess, } from "./process-inventory.js";
76
+ import { ComputerProcessInventory, drainProcessExit, ProcessLogTail, failedObservation, observeProcess, } from "./process-inventory.js";
77
77
  import { assertComputerContainersEnabled, ComputerContainersPausedError, configureComputerContainer, hostedComputerContainersPaused, } from "./container-policy.js";
78
78
  import { OnBoxVmContainerHost, onBoxVmPlacement, } from "./on-box-vm.js";
79
79
  import { computerKeepAwake } from "./fleet/keep-awake.js";
@@ -1276,6 +1276,24 @@ export class ComputerDO extends ContainerComputer {
1276
1276
  await this.#renewExecution(row.id);
1277
1277
  return process;
1278
1278
  }
1279
+ /** The retained last output lines of one process, with its record. */
1280
+ processLogs(input) {
1281
+ return this.processLogsAfterAcceptance(input, () => undefined);
1282
+ }
1283
+ processLogsAfterAcceptance(input, accept) {
1284
+ const { id, lines } = processLogsInputSchema.parse(input);
1285
+ accept();
1286
+ const row = this.#processes.get(id);
1287
+ const log = this.#processes.logOf(id);
1288
+ if (row === undefined || log === undefined)
1289
+ throw new ComputerProcessNotFoundError(id);
1290
+ const wanted = lines ?? maximumProcessLogLines;
1291
+ return processLogsOutputSchema.parse({
1292
+ process: this.#processReceipt(row),
1293
+ lines: log.lines.slice(-wanted),
1294
+ truncated: log.truncated || log.lines.length > wanted,
1295
+ });
1296
+ }
1279
1297
  /** Send SIGTERM to one running process; its exit is recorded when observed. */
1280
1298
  async killProcess(input) {
1281
1299
  return await this.killProcessAfterAcceptance(input, () => undefined);
@@ -1406,7 +1424,18 @@ export class ComputerDO extends ContainerComputer {
1406
1424
  */
1407
1425
  async #watchProcess(id, run) {
1408
1426
  try {
1409
- const settled = await drainProcessExit(run);
1427
+ const tail = new ProcessLogTail();
1428
+ let lastSaved = 0;
1429
+ const settled = await drainProcessExit(run, (text) => {
1430
+ tail.push(text);
1431
+ // Output is saved at most once a second while the process runs.
1432
+ const now = Date.now();
1433
+ if (now - lastSaved >= 1_000) {
1434
+ lastSaved = now;
1435
+ this.#processes.setLog(id, tail.snapshot());
1436
+ }
1437
+ });
1438
+ this.#processes.setLog(id, tail.snapshot());
1410
1439
  if (settled !== undefined) {
1411
1440
  this.#settle(id, {
1412
1441
  state: "exited",
@@ -3,6 +3,23 @@ import { z } from "zod";
3
3
  import { processStartInputSchema, type ComputerProcess, type ComputerProcessId, type ComputerProcessSync } from "@fungi.computer/computer-contract";
4
4
  /** The durable SQLite surface owned by processes and their port exposures. */
5
5
  export type ComputerProcessStorage = Pick<DurableObjectStorage, "sql" | "transactionSync">;
6
+ /** The retained last output lines of one process. */
7
+ export type ProcessLogSnapshot = Readonly<{
8
+ lines: readonly string[];
9
+ truncated: boolean;
10
+ }>;
11
+ /**
12
+ * Keeps the last lines a process wrote, bounded by line count, line length
13
+ * and total size. A partial last line is held until its newline arrives or
14
+ * the snapshot is read.
15
+ */
16
+ export declare class ProcessLogTail {
17
+ #private;
18
+ /** Add a chunk of stdout or stderr text. */
19
+ push(chunk: string): void;
20
+ /** The retained lines, including any unfinished last line. */
21
+ snapshot(): ProcessLogSnapshot;
22
+ }
6
23
  /** Computer-owned replay identities; computerd owns execution and exit observations. */
7
24
  export declare class ComputerProcessInventory {
8
25
  #private;
@@ -15,6 +32,10 @@ export declare class ComputerProcessInventory {
15
32
  created: boolean;
16
33
  }>;
17
34
  exited(id: ComputerProcessId, exitCode: number | null, sync?: ComputerProcessSync): ComputerProcess;
35
+ /** Replace the retained output tail of one process, if its record is still kept. */
36
+ setLog(id: ComputerProcessId, tail: ProcessLogSnapshot): void;
37
+ /** The retained output tail of one process, or undefined when no record is kept. */
38
+ logOf(id: ComputerProcessId): ProcessLogSnapshot | undefined;
18
39
  /** Retain a failed dispatch receipt: retrying that key cannot create new work. */
19
40
  release(id: ComputerProcessId): void;
20
41
  /**
@@ -75,7 +96,7 @@ export declare function observeProcess(runtime: ProcessRuntime, id: string): Pro
75
96
  * Workspace. `undefined` if the stream broke or was replaced before any
76
97
  * exit was observed -- there is nothing to record.
77
98
  */
78
- export declare function drainProcessExit(run: WorkspaceRuntimeExecHandle<"utf8">): Promise<Readonly<{
99
+ export declare function drainProcessExit(run: WorkspaceRuntimeExecHandle<"utf8">, onOutput?: (text: string) => void): Promise<Readonly<{
79
100
  exitCode: number;
80
101
  sync: ComputerProcessSync;
81
102
  settleLater?: Promise<ComputerProcessSync>;
@@ -51,7 +51,7 @@ 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 { z } from "zod";
54
- import { computerProcessSchema, processStartInputSchema, mintComputerProcessId, ComputerProcessLimitError, ComputerPortReservedError, ComputerPortConflictError, ComputerPortLimitError, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, maximumRunningProcesses, } from "@fungi.computer/computer-contract";
54
+ import { computerProcessSchema, processStartInputSchema, mintComputerProcessId, ComputerProcessLimitError, ComputerPortReservedError, ComputerPortConflictError, ComputerPortLimitError, isComputerReservedPort, maximumExposedPorts, maximumProcessLogLineCharacters, maximumProcessLogLines, maximumProcessRecords, maximumRunningProcesses, } from "@fungi.computer/computer-contract";
55
55
  import { ComputerOperationConflictError } from "./operation-record.js";
56
56
  function toProcess(row) {
57
57
  return computerProcessSchema.parse({
@@ -75,7 +75,52 @@ function toProcess(row) {
75
75
  * storage (confirmed in workerd; node:sqlite does not enforce the same
76
76
  * sandbox, so a unit test against it alone would hide this).
77
77
  */
78
- const processSchemaVersion = 2;
78
+ const processSchemaVersion = 3;
79
+ /** At most this many bytes of output text are retained per process. */
80
+ const maximumLogBytes = 64 * 1024;
81
+ /**
82
+ * Keeps the last lines a process wrote, bounded by line count, line length
83
+ * and total size. A partial last line is held until its newline arrives or
84
+ * the snapshot is read.
85
+ */
86
+ export class ProcessLogTail {
87
+ #lines = [];
88
+ #partial = "";
89
+ #truncated = false;
90
+ /** Add a chunk of stdout or stderr text. */
91
+ push(chunk) {
92
+ const parts = (this.#partial + chunk).split("\n");
93
+ this.#partial = parts.pop() ?? "";
94
+ for (const part of parts)
95
+ this.#lines.push(clipLine(part));
96
+ this.#partial = clipLine(this.#partial);
97
+ this.#trim();
98
+ }
99
+ /** The retained lines, including any unfinished last line. */
100
+ snapshot() {
101
+ const lines = this.#partial === "" ? this.#lines : [...this.#lines, this.#partial];
102
+ return {
103
+ lines: lines.slice(-maximumProcessLogLines),
104
+ truncated: this.#truncated,
105
+ };
106
+ }
107
+ #trim() {
108
+ let bytes = 0;
109
+ for (const line of this.#lines)
110
+ bytes += line.length + 1;
111
+ while (this.#lines.length > maximumProcessLogLines ||
112
+ (bytes > maximumLogBytes && this.#lines.length > 1)) {
113
+ const dropped = this.#lines.shift();
114
+ bytes -= (dropped?.length ?? 0) + 1;
115
+ this.#truncated = true;
116
+ }
117
+ }
118
+ }
119
+ function clipLine(line) {
120
+ return line.length > maximumProcessLogLineCharacters
121
+ ? line.slice(0, maximumProcessLogLineCharacters)
122
+ : line;
123
+ }
79
124
  /** Computer-owned replay identities; computerd owns execution and exit observations. */
80
125
  export class ComputerProcessInventory {
81
126
  #storage;
@@ -94,7 +139,7 @@ export class ComputerProcessInventory {
94
139
  storage.sql.exec("DELETE FROM computer_schema_meta WHERE id = 0");
95
140
  storage.sql.exec("INSERT INTO computer_schema_meta (id, version) VALUES (0, ?)", processSchemaVersion);
96
141
  }
97
- storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_processes (id TEXT PRIMARY KEY, request_scope TEXT NOT NULL, request_id TEXT NOT NULL, input_hash TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT, port INTEGER, state TEXT NOT NULL CHECK (state IN ('running','exited')), exit_code INTEGER, sync TEXT NOT NULL DEFAULT 'unknown' CHECK (sync IN ('synced','pending','unknown')), started_at INTEGER NOT NULL, ended_at INTEGER, CHECK ((state = 'running') = (ended_at IS NULL)), UNIQUE(request_scope, request_id)) STRICT");
142
+ storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_processes (id TEXT PRIMARY KEY, request_scope TEXT NOT NULL, request_id TEXT NOT NULL, input_hash TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT, port INTEGER, state TEXT NOT NULL CHECK (state IN ('running','exited')), exit_code INTEGER, sync TEXT NOT NULL DEFAULT 'unknown' CHECK (sync IN ('synced','pending','unknown')), started_at INTEGER NOT NULL, ended_at INTEGER, log_tail TEXT NOT NULL DEFAULT '', log_truncated INTEGER NOT NULL DEFAULT 0, CHECK ((state = 'running') = (ended_at IS NULL)), UNIQUE(request_scope, request_id)) STRICT");
98
143
  storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_exposed_ports (port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535), process_id TEXT) STRICT");
99
144
  });
100
145
  }
@@ -163,6 +208,22 @@ export class ComputerProcessInventory {
163
208
  return this.#require(id);
164
209
  });
165
210
  }
211
+ /** Replace the retained output tail of one process, if its record is still kept. */
212
+ setLog(id, tail) {
213
+ this.#storage.sql.exec("UPDATE computer_processes SET log_tail = ?, log_truncated = ? WHERE id = ?", tail.lines.join("\n"), tail.truncated ? 1 : 0, id);
214
+ }
215
+ /** The retained output tail of one process, or undefined when no record is kept. */
216
+ logOf(id) {
217
+ const row = this.#storage.sql
218
+ .exec("SELECT * FROM computer_processes WHERE id = ?", id)
219
+ .toArray()[0];
220
+ if (row === undefined)
221
+ return undefined;
222
+ return {
223
+ lines: row.log_tail === "" ? [] : row.log_tail.split("\n"),
224
+ truncated: row.log_truncated === 1,
225
+ };
226
+ }
166
227
  /** Retain a failed dispatch receipt: retrying that key cannot create new work. */
167
228
  release(id) {
168
229
  const row = this.get(id);
@@ -392,7 +453,7 @@ export async function observeProcess(runtime, id) {
392
453
  * Workspace. `undefined` if the stream broke or was replaced before any
393
454
  * exit was observed -- there is nothing to record.
394
455
  */
395
- export async function drainProcessExit(run) {
456
+ export async function drainProcessExit(run, onOutput) {
396
457
  const reader = run.getReader();
397
458
  const dispose = () => {
398
459
  reader.releaseLock();
@@ -406,6 +467,8 @@ export async function drainProcessExit(run) {
406
467
  const next = await reader.read();
407
468
  if (next.done)
408
469
  break;
470
+ if (next.value.name === "stdout" || next.value.name === "stderr")
471
+ onOutput?.(next.value.value);
409
472
  if (next.value.name === "exit") {
410
473
  exitCode = next.value.code;
411
474
  const drained = await drainPastExit(reader);
@@ -19898,6 +19898,10 @@ var gillResponseSchema = Union2([
19898
19898
  title: rowLabelSchemaV1,
19899
19899
  state: Literal2("empty"),
19900
19900
  rows: Tuple([]),
19901
+ /** One line naming the first action, in the App's own words. */
19902
+ emptyText: optional2(String4.pipe(check(isMinLength(1)), check(isMaxLength(120)))),
19903
+ /** The host supplies the button; the App only says it belongs. */
19904
+ action: optional2(Struct({ kind: Literal2("open") })),
19901
19905
  next: optional2(String4.pipe(check(isMaxLength(1024))))
19902
19906
  }),
19903
19907
  Struct({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.6.3",
3
+ "version": "0.8.0",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",
@@ -59,11 +59,11 @@
59
59
  "@fungi.computer/cairn": "0.1.0",
60
60
  "@fungi.computer/capnweb": "0.12.0-fungi.0",
61
61
  "@fungi.computer/cloudflare-computer": "0.2.1-fungi.2",
62
- "@fungi.computer/cordyceps": "0.4.0",
63
- "@fungi.computer/knapsack": "0.4.7",
64
- "@fungi.computer/seam": "0.2.4",
65
- "@fungi.computer/watchdog": "0.1.2",
66
- "@fungi.computer/computer-contract": "0.0.12",
62
+ "@fungi.computer/cordyceps": "0.4.1",
63
+ "@fungi.computer/knapsack": "0.4.9",
64
+ "@fungi.computer/seam": "0.2.5",
65
+ "@fungi.computer/watchdog": "0.1.3",
66
+ "@fungi.computer/computer-contract": "0.1.0",
67
67
  "effect": "4.0.2",
68
68
  "just-bash": "3.4.2",
69
69
  "zod": "4.4.3"