@fungi.computer/computer 0.8.8 → 0.10.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.
@@ -39,6 +39,8 @@ export type FleetLifecyclePorts = Readonly<{
39
39
  id: string;
40
40
  };
41
41
  containerRunning: (backing: HostedBacking) => Promise<boolean>;
42
+ /** The Computer's process record learns that this backend went to sleep. */
43
+ endedByIdleSleep: (backendId: string) => void;
42
44
  vmQueuePosition: (hostId: string) => Promise<number | null>;
43
45
  }>;
44
46
  }>;
@@ -358,6 +358,8 @@ export class FleetLifecycle {
358
358
  this.diagnostic("computer_idle_stop_failed", "idle_stop", cause);
359
359
  return { running: true, at: this.billedThrough(runtimeId, now) };
360
360
  }
361
+ // The sleep ended every command still running on this backend; say so.
362
+ this.ports.backend.endedByIdleSleep(attachedBackendId(backing));
361
363
  return { running: false, at: this.billedThrough(runtimeId, now) };
362
364
  }
363
365
  return { running, at: this.billedThrough(runtimeId, exitedAt) };
@@ -17,6 +17,7 @@ export declare const computerActionSchema: z.ZodEnum<{
17
17
  "files.grep": "files.grep";
18
18
  "files.edit": "files.edit";
19
19
  "files.patch": "files.patch";
20
+ "files.move": "files.move";
20
21
  terminal: "terminal";
21
22
  stop: "stop";
22
23
  processStart: "processStart";
@@ -53,6 +54,7 @@ export declare const computerGrantSchema: z.ZodObject<{
53
54
  "files.grep": "files.grep";
54
55
  "files.edit": "files.edit";
55
56
  "files.patch": "files.patch";
57
+ "files.move": "files.move";
56
58
  terminal: "terminal";
57
59
  stop: "stop";
58
60
  processStart: "processStart";
package/dist/index.d.ts CHANGED
@@ -156,6 +156,8 @@ declare class ContainerComputer extends ContainerComputerBase {
156
156
  export declare class ComputerDO extends ContainerComputer implements ComputerFilesRpc {
157
157
  #private;
158
158
  constructor(ctx: DurableObjectState, env: ComputerEnv);
159
+ /** The fleet slept this backend after it sat idle; its running commands ended with it. */
160
+ protected endedByIdleSleep(backendId: string): void;
159
161
  /** Host-admitted settings write; egress reads the current durable value. */
160
162
  internetAccess(enabled?: boolean): boolean;
161
163
  /**
package/dist/index.js CHANGED
@@ -68,7 +68,7 @@ import { z } from "zod";
68
68
  import { SystemTrustContainerBackend } from "./container-system-trust.js";
69
69
  import { computerTransportBackend } from "./transport-backend.js";
70
70
  import { PullPendingTracker } from "./pull-pending.js";
71
- 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
+ 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, moveInputSchema, moveOutputSchema, ComputerFileMoveError, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
72
72
  import { createWorkspaceFilesPort, readBoundedWorkspaceText, listWorkspaceFiles, } from "./files.js";
73
73
  import { computerExecutionResult } from "./execution-result.js";
74
74
  import { ComputerOperationRecord } from "./operation-record.js";
@@ -125,6 +125,53 @@ async function mkdir(workspace, input) {
125
125
  await workspace.fs.mkdir(path, { recursive });
126
126
  return mkdirOutputSchema.parse({ path });
127
127
  }
128
+ const isMissing = z.lazy(() => z.object({ code: z.literal("ENOENT") }));
129
+ const isInvalid = z.lazy(() => z.object({ code: z.literal("EINVAL") }));
130
+ /**
131
+ * Rename through the Workspace provider's native `rename`, which moves the
132
+ * inode under its new name, so a directory keeps its whole subtree and nothing
133
+ * is copied. The provider overwrites an existing destination, so refuse that
134
+ * first. Call inside one storage transaction: a refusal after
135
+ * `createParents` has made folders rolls them back.
136
+ */
137
+ function move(workspace, input) {
138
+ const { from, to, createParents } = moveInputSchema.parse(input);
139
+ const provider = new SQLiteWorkspaceProvider(workspace.fs.db);
140
+ const lstat = (path) => {
141
+ try {
142
+ return provider.lstatSync(path);
143
+ }
144
+ catch (cause) {
145
+ if (isMissing.safeParse(cause).success)
146
+ return null;
147
+ throw cause;
148
+ }
149
+ };
150
+ const source = lstat(from);
151
+ if (source === null)
152
+ throw new ComputerFileMoveError("missing", `no such path: ${from}`);
153
+ if (source.isDirectory() && (to === from || to.startsWith(`${from}/`)))
154
+ throw new ComputerFileMoveError("invalid", `a directory cannot move into itself: ${from}`);
155
+ if (lstat(to) !== null)
156
+ throw new ComputerFileMoveError("exists", `already exists: ${to}`);
157
+ const parent = to.slice(0, Math.max(to.lastIndexOf("/"), 1));
158
+ if (createParents)
159
+ provider.mkdirSync(parent, { recursive: true });
160
+ try {
161
+ provider.renameSync(from, to);
162
+ }
163
+ catch (cause) {
164
+ // The provider's own checks still decide what the text above cannot: a
165
+ // missing parent, and a destination that resolves inside the source
166
+ // through a symlink.
167
+ if (isMissing.safeParse(cause).success)
168
+ throw new ComputerFileMoveError("missing", `parent directory missing: ${to}`);
169
+ if (isInvalid.safeParse(cause).success)
170
+ throw new ComputerFileMoveError("invalid", `cannot move ${from} to ${to}`);
171
+ throw cause;
172
+ }
173
+ return moveOutputSchema.parse({ from, to });
174
+ }
128
175
  async function write(workspace, input) {
129
176
  const { path, content } = writeInputSchema.parse(input);
130
177
  await workspace.fs.writeFile(path, content);
@@ -518,6 +565,10 @@ export class ComputerDO extends ContainerComputer {
518
565
  // Reconstruction revokes unfinished exec authority before the first RPC.
519
566
  void this.#executions;
520
567
  }
568
+ /** The fleet slept this backend after it sat idle; its running commands ended with it. */
569
+ endedByIdleSleep(backendId) {
570
+ this.#processes.endedByIdleSleep(backendId);
571
+ }
521
572
  /** Host-admitted settings write; egress reads the current durable value. */
522
573
  internetAccess(enabled) {
523
574
  return computerInternetAccess(this.state.storage.sql, enabled);
@@ -1042,6 +1093,12 @@ export class ComputerDO extends ContainerComputer {
1042
1093
  await this.#syncRunningHosted("push");
1043
1094
  return result;
1044
1095
  }
1096
+ case "move": {
1097
+ await this.#syncRunningHosted("pull");
1098
+ const result = this.state.storage.transactionSync(() => move(workspace, input));
1099
+ await this.#syncRunningHosted("push");
1100
+ return result;
1101
+ }
1045
1102
  default:
1046
1103
  throw new Error(`Computer capability is unavailable: ${selected}`);
1047
1104
  }
@@ -1,10 +1,18 @@
1
1
  import type { SeamReplayStore } from "@fungi.computer/seam";
2
2
  import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
3
- /** Private receiver-local storage ceiling, not a Team or attachment quota. */
3
+ /**
4
+ * Private receiver-local storage ceiling for ONE backend's live dial history,
5
+ * not a Team or attachment quota. Each attached backend has its own share, so a
6
+ * backend that reaches it is refused alone; a Computer's total is bounded by
7
+ * its attached-backend limit times this.
8
+ */
4
9
  export declare const maximumLocalDialReplayRecords = 4096;
5
10
  /**
6
- * One Computer's local-dial receiver history, in its existing owner database.
7
- * Reconstruct with the same owner, never a process-generation namespace.
8
- * Native SQLite owns atomicity and commit; there is no in-memory fallback.
11
+ * One backend's share of a Computer's local-dial receiver history, in its
12
+ * existing owner database. A nonce is a replay whichever backend first used
13
+ * it, but only `backendId`'s own live records count toward its capacity.
14
+ * Reconstruct with the same owner and backend, never a process-generation
15
+ * namespace. Native SQLite owns atomicity and commit; there is no in-memory
16
+ * fallback.
9
17
  */
10
- export declare function createLocalBackendReplayStore(owner: WatchdogSqliteOwner): SeamReplayStore;
18
+ export declare function createLocalBackendReplayStore(owner: WatchdogSqliteOwner, backendId: string): SeamReplayStore;
@@ -1,22 +1,44 @@
1
1
  import { z } from "zod";
2
- /** Private receiver-local storage ceiling, not a Team or attachment quota. */
2
+ /**
3
+ * Private receiver-local storage ceiling for ONE backend's live dial history,
4
+ * not a Team or attachment quota. Each attached backend has its own share, so a
5
+ * backend that reaches it is refused alone; a Computer's total is bounded by
6
+ * its attached-backend limit times this.
7
+ */
3
8
  export const maximumLocalDialReplayRecords = 4096;
4
9
  const countSchema = z.number().int().nonnegative();
10
+ const definitionSchema = z.object({ sql: z.string() });
5
11
  /**
6
- * One Computer's local-dial receiver history, in its existing owner database.
7
- * Reconstruct with the same owner, never a process-generation namespace.
8
- * Native SQLite owns atomicity and commit; there is no in-memory fallback.
12
+ * One backend's share of a Computer's local-dial receiver history, in its
13
+ * existing owner database. A nonce is a replay whichever backend first used
14
+ * it, but only `backendId`'s own live records count toward its capacity.
15
+ * Reconstruct with the same owner and backend, never a process-generation
16
+ * namespace. Native SQLite owns atomicity and commit; there is no in-memory
17
+ * fallback.
9
18
  */
10
- export function createLocalBackendReplayStore(owner) {
19
+ export function createLocalBackendReplayStore(owner, backendId) {
11
20
  return {
12
21
  admit({ nonce, now, expiresAt }) {
13
22
  try {
14
23
  return owner.transactionSync(() => {
24
+ // Pre-release data is disposable: a table without `backend_id` is
25
+ // dropped and recreated in the current shape. Its nonces are dials
26
+ // that expire within Seam's 120 s window (two 60 s skews), the
27
+ // bounded span in which one of them could be replayed.
28
+ const existing = definitionSchema
29
+ .optional()
30
+ .parse(owner.sql
31
+ .exec("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'computer_local_dial_replay'")
32
+ .toArray()[0]);
33
+ if (existing !== undefined && !existing.sql.includes("backend_id"))
34
+ owner.sql.exec("DROP TABLE computer_local_dial_replay");
15
35
  owner.sql
16
36
  .exec(`CREATE TABLE IF NOT EXISTS computer_local_dial_replay (
17
37
  nonce TEXT PRIMARY KEY,
38
+ backend_id TEXT NOT NULL,
18
39
  expires_at INTEGER NOT NULL
19
40
  ) STRICT`);
41
+ owner.sql.exec("CREATE INDEX IF NOT EXISTS computer_local_dial_replay_backend ON computer_local_dial_replay (backend_id)");
20
42
  // Seam's last fresh instant is inclusive. Do not renew duplicate
21
43
  // deadlines, assume expiry order, or discard any still-live record.
22
44
  owner.sql.exec("DELETE FROM computer_local_dial_replay WHERE expires_at < ?", now);
@@ -25,11 +47,11 @@ export function createLocalBackendReplayStore(owner) {
25
47
  .toArray().length > 0)
26
48
  return "replayed";
27
49
  const count = countSchema.parse(owner.sql
28
- .exec("SELECT COUNT(*) AS count FROM computer_local_dial_replay")
50
+ .exec("SELECT COUNT(*) AS count FROM computer_local_dial_replay WHERE backend_id = ?", backendId)
29
51
  .toArray()[0]?.count);
30
52
  if (count >= maximumLocalDialReplayRecords)
31
53
  return "at-capacity";
32
- owner.sql.exec("INSERT INTO computer_local_dial_replay (nonce, expires_at) VALUES (?, ?)", nonce, expiresAt);
54
+ owner.sql.exec("INSERT INTO computer_local_dial_replay (nonce, backend_id, expires_at) VALUES (?, ?, ?)", nonce, backendId, expiresAt);
33
55
  return "admitted";
34
56
  });
35
57
  }
@@ -128,7 +128,7 @@ export function localBackendAudience(computerName, backendId) {
128
128
  */
129
129
  export async function verifyLocalBackendDial(request, computerName, backend, owner) {
130
130
  try {
131
- await verifySeamRequest(await importSeamVerifiers({ [backend.deviceId]: backend.publicKey }), localBackendAudience(computerName, attachedBackendId(backend)), request.method, request.url, request.headers.get(seamHeader), null, createLocalBackendReplayStore(owner));
131
+ await verifySeamRequest(await importSeamVerifiers({ [backend.deviceId]: backend.publicKey }), localBackendAudience(computerName, attachedBackendId(backend)), request.method, request.url, request.headers.get(seamHeader), null, createLocalBackendReplayStore(owner, attachedBackendId(backend)));
132
132
  return true;
133
133
  }
134
134
  catch (cause) {
@@ -34,6 +34,13 @@ export declare class ComputerProcessInventory {
34
34
  /** The backend selected at admission, retained across reconnects and restarts. */
35
35
  backend(id: string): string | undefined;
36
36
  exited(id: ComputerProcessId, exitCode: number | null, sync?: ComputerProcessSync): ComputerProcess;
37
+ /**
38
+ * The Computer slept after sitting idle, so every command still running on
39
+ * that backend stopped with it. Record them as ended by idle sleep, in one
40
+ * transaction, instead of leaving a later liveness probe to report an
41
+ * unexplained exit.
42
+ */
43
+ endedByIdleSleep(backend: string): void;
37
44
  /** Replace the retained output tail of one process, if its record is still kept. */
38
45
  setLog(id: ComputerProcessId, tail: ProcessLogSnapshot): void;
39
46
  /** The retained output tail of one process, or undefined when no record is kept. */
@@ -64,6 +64,7 @@ function toProcess(row) {
64
64
  sync: row.sync,
65
65
  startedAt: row.started_at,
66
66
  endedAt: row.ended_at,
67
+ endedReason: row.ended_reason,
67
68
  });
68
69
  }
69
70
  /**
@@ -75,7 +76,7 @@ function toProcess(row) {
75
76
  * storage (confirmed in workerd; node:sqlite does not enforce the same
76
77
  * sandbox, so a unit test against it alone would hide this).
77
78
  */
78
- const processSchemaVersion = 4;
79
+ const processSchemaVersion = 5;
79
80
  /** At most this many bytes of output text are retained per process. */
80
81
  const maximumLogBytes = 64 * 1024;
81
82
  /**
@@ -139,7 +140,7 @@ export class ComputerProcessInventory {
139
140
  storage.sql.exec("DELETE FROM computer_schema_meta WHERE id = 0");
140
141
  storage.sql.exec("INSERT INTO computer_schema_meta (id, version) VALUES (0, ?)", processSchemaVersion);
141
142
  }
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, backend 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");
143
+ 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, backend 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, ended_reason TEXT CHECK (ended_reason IN ('idle-sleep')), 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");
143
144
  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");
144
145
  });
145
146
  }
@@ -214,6 +215,22 @@ export class ComputerProcessInventory {
214
215
  return this.#require(id);
215
216
  });
216
217
  }
218
+ /**
219
+ * The Computer slept after sitting idle, so every command still running on
220
+ * that backend stopped with it. Record them as ended by idle sleep, in one
221
+ * transaction, instead of leaving a later liveness probe to report an
222
+ * unexplained exit.
223
+ */
224
+ endedByIdleSleep(backend) {
225
+ this.#storage.transactionSync(() => {
226
+ const ids = this.#storage.sql
227
+ .exec("SELECT id FROM computer_processes WHERE backend = ? AND state = 'running'", backend)
228
+ .toArray();
229
+ this.#storage.sql.exec("UPDATE computer_processes SET state = 'exited', exit_code = NULL, sync = 'unknown', ended_at = ?, ended_reason = 'idle-sleep' WHERE backend = ? AND state = 'running'", this.#now(), backend);
230
+ for (const { id } of ids)
231
+ this.#storage.sql.exec("DELETE FROM computer_exposed_ports WHERE process_id = ?", id);
232
+ });
233
+ }
217
234
  /** Replace the retained output tail of one process, if its record is still kept. */
218
235
  setLog(id, tail) {
219
236
  this.#storage.sql.exec("UPDATE computer_processes SET log_tail = ?, log_truncated = ? WHERE id = ?", tail.lines.join("\n"), tail.truncated ? 1 : 0, id);
@@ -19604,6 +19604,11 @@ var appBackendBindingKinds = {
19604
19604
  requires: ["computer.writeFile"],
19605
19605
  effect: "write"
19606
19606
  },
19607
+ move: {
19608
+ cap: "app.computer.write",
19609
+ requires: ["computer.writeFile"],
19610
+ effect: "write"
19611
+ },
19607
19612
  preview: {
19608
19613
  cap: "app.computer.exec",
19609
19614
  requires: ["computer.execute"],
@@ -19677,6 +19682,7 @@ var appCapabilityIds = [
19677
19682
  "agent.manage",
19678
19683
  "agent.rename",
19679
19684
  "agent.avatar",
19685
+ "agent.instructions",
19680
19686
  "agent.toolPolicy",
19681
19687
  "agent.read",
19682
19688
  "agent.send",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.8.8",
3
+ "version": "0.10.0",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Cloudflare Computer host for one durable Fungi Computer",
6
6
  "type": "module",
@@ -60,10 +60,10 @@
60
60
  "@fungi.computer/capnweb": "0.12.0-fungi.0",
61
61
  "@fungi.computer/cloudflare-computer": "0.2.1-fungi.2",
62
62
  "@fungi.computer/cordyceps": "0.4.2",
63
- "@fungi.computer/knapsack": "0.4.9",
63
+ "@fungi.computer/knapsack": "0.4.10",
64
64
  "@fungi.computer/seam": "0.2.5",
65
65
  "@fungi.computer/watchdog": "0.1.3",
66
- "@fungi.computer/computer-contract": "0.1.0",
66
+ "@fungi.computer/computer-contract": "0.3.0",
67
67
  "effect": "4.0.2",
68
68
  "just-bash": "3.4.2",
69
69
  "zod": "4.4.3"