@fungi.computer/computer 0.9.0 → 0.11.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.
@@ -1,7 +1,23 @@
1
- /** The Computer ceiling shared by the platform image and on-box host. */
2
- export const computerResourceBounds = Object.freeze({
1
+ /**
2
+ * What each Computer size gives an on-box VM. The names match
3
+ * `computerSizeSchema` in `src/computer-backends.ts`, which a test pins.
4
+ */
5
+ export const computerSizes = Object.freeze({
6
+ small: Object.freeze({ vcpus: 2, memoryMib: 4_096 }),
7
+ default: Object.freeze({ vcpus: 4, memoryMib: 8_192 }),
8
+ large: Object.freeze({ vcpus: 8, memoryMib: 16_384 }),
9
+ });
10
+
11
+ /** A Cloudflare `standard-4` instance: the platform container's one size. */
12
+ export const platformContainerResources = Object.freeze({
3
13
  vcpus: 4,
4
14
  memoryMib: 12_288,
15
+ });
16
+
17
+ /** The ceiling shared by the platform image and on-box host: the largest size. */
18
+ export const computerResourceBounds = Object.freeze({
19
+ vcpus: computerSizes.large.vcpus,
20
+ memoryMib: computerSizes.large.memoryMib,
5
21
  diskGib: 20,
6
22
  pidsMax: 256,
7
23
  maxRuntimeMs: 24 * 60 * 60 * 1_000,
@@ -28,6 +44,14 @@ export function computerRuntimeExpired(startedAt, now, maximumRuntimeMs) {
28
44
  return now - startedAt >= maximumRuntimeMs;
29
45
  }
30
46
 
47
+ /** The VM resources one size selects, refusing a name that is not a size. */
48
+ export function computerSizeResources(size) {
49
+ if (!Object.hasOwn(computerSizes, size))
50
+ throw new Error(`Computer size ${String(size)} is not offered`);
51
+ const { vcpus, memoryMib } = computerSizes[size];
52
+ return { vcpus, memMib: memoryMib };
53
+ }
54
+
31
55
  /** The host may provision a smaller VM, never a larger Computer. */
32
56
  export function boundedVmResources({ vcpus, memMib, diskGib, pidsMax }) {
33
57
  return {
@@ -1,4 +1,17 @@
1
1
  import * as z from "zod";
2
+ /**
3
+ * A Computer's size, chosen at creation. It selects the on-box VM's vCPUs and
4
+ * memory and the retail price. Platform containers have one fixed instance
5
+ * type and ignore it. The resources behind each name live in
6
+ * `container/resource-bounds.mjs`, which the VM host also reads.
7
+ */
8
+ export declare const computerSizeSchema: z.ZodEnum<{
9
+ default: "default";
10
+ small: "small";
11
+ large: "large";
12
+ }>;
13
+ export type ComputerSize = z.infer<typeof computerSizeSchema>;
14
+ export declare const defaultComputerSize: ComputerSize;
2
15
  /** A backend the platform runs: a Cloudflare container or an on-box VM. */
3
16
  export declare const hostedBackingSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4
17
  kind: z.ZodLiteral<"platform-container">;
@@ -89,5 +102,6 @@ export declare function routeComputerBackend(backends: readonly AttachedBackend[
89
102
  export type ContainerRuntimeStart = Readonly<{
90
103
  runtimeId: string;
91
104
  backing: HostedBacking;
105
+ size: ComputerSize;
92
106
  startedAt: number;
93
107
  }>;
@@ -10,6 +10,14 @@ import * as z from "zod";
10
10
  */
11
11
  const hostIdSchema = z.lazy(() => z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/));
12
12
  const labelSchema = z.lazy(() => z.string().trim().min(1).max(256));
13
+ /**
14
+ * A Computer's size, chosen at creation. It selects the on-box VM's vCPUs and
15
+ * memory and the retail price. Platform containers have one fixed instance
16
+ * type and ignore it. The resources behind each name live in
17
+ * `container/resource-bounds.mjs`, which the VM host also reads.
18
+ */
19
+ export const computerSizeSchema = z.enum(["small", "default", "large"]);
20
+ export const defaultComputerSize = "default";
13
21
  /** A backend the platform runs: a Cloudflare container or an on-box VM. */
14
22
  export const hostedBackingSchema = z.discriminatedUnion("kind", [
15
23
  z.strictObject({ kind: z.literal("platform-container") }),
@@ -12,6 +12,7 @@ export declare function createFleetComputers(owner: WatchdogSqliteOwner, capacit
12
12
  readonly computers: Readonly<{
13
13
  computerId: string;
14
14
  name: string;
15
+ size: import("../computer-backends.js").ComputerSize;
15
16
  createdAt: number;
16
17
  updatedAt: number;
17
18
  }>[];
@@ -24,6 +25,7 @@ export declare function createFleetComputers(owner: WatchdogSqliteOwner, capacit
24
25
  computer: Readonly<{
25
26
  computerId: string;
26
27
  name: string;
28
+ size: import("../computer-backends.js").ComputerSize;
27
29
  createdAt: number;
28
30
  updatedAt: number;
29
31
  }>;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { type ComputerSize } from "../computer-backends.js";
2
3
  /** Opaque host identity; the fleet does not interpret the actor kind. */
3
4
  export type FleetActor = Readonly<{
4
5
  kind: string;
@@ -8,16 +9,23 @@ export type FleetActor = Readonly<{
8
9
  export type FleetComputer = Readonly<{
9
10
  computerId: string;
10
11
  name: string;
12
+ size: ComputerSize;
11
13
  createdAt: number;
12
14
  updatedAt: number;
13
15
  }>;
14
16
  /** A durable create receipt binds the complete request to its actor. */
15
17
  export declare const computerCreateRequestSchema: z.ZodObject<{
16
18
  name: z.ZodOptional<z.ZodString>;
19
+ size: z.ZodOptional<z.ZodEnum<{
20
+ default: "default";
21
+ small: "small";
22
+ large: "large";
23
+ }>>;
17
24
  requestId: z.ZodString;
18
25
  }, z.core.$strict>;
19
26
  export type ComputerCreateRequest = Readonly<{
20
27
  name?: string | undefined;
28
+ size?: ComputerSize | undefined;
21
29
  requestId: string;
22
30
  }>;
23
31
  /** Inventory pages retain stable ordering and a bounded response. */
@@ -1,7 +1,10 @@
1
1
  import { z } from "zod";
2
+ import { computerSizeSchema } from "../computer-backends.js";
2
3
  /** A durable create receipt binds the complete request to its actor. */
3
4
  export const computerCreateRequestSchema = z.strictObject({
4
5
  name: z.string().min(1).max(256).optional(),
6
+ /** Omitted means `default`. */
7
+ size: computerSizeSchema.optional(),
5
8
  requestId: z.string().min(1).max(256),
6
9
  });
7
10
  /** Inventory pages retain stable ordering and a bounded response. */
@@ -16,6 +16,7 @@ export declare function createFleetInventory(options: Readonly<{
16
16
  readonly computers: Readonly<{
17
17
  computerId: string;
18
18
  name: string;
19
+ size: import("../computer-backends.js").ComputerSize;
19
20
  createdAt: number;
20
21
  updatedAt: number;
21
22
  }>[];
@@ -1,6 +1,7 @@
1
1
  import { words } from "@fungi.computer/cairn";
2
2
  import { defineIdFamily } from "@fungi.computer/cairn/id";
3
3
  import { z } from "zod";
4
+ import { computerSizeSchema, defaultComputerSize, } from "../computer-backends.js";
4
5
  import { ComputerInventoryError, computerPageSchema, } from "./inventory-wire.js";
5
6
  const computerIds = defineIdFamily({
6
7
  family: "computer",
@@ -10,6 +11,7 @@ const computerIds = defineIdFamily({
10
11
  const rowSchema = z.lazy(() => z.strictObject({
11
12
  computer_id: z.string().min(1),
12
13
  name: z.string().min(1).max(256),
14
+ size: computerSizeSchema,
13
15
  actor_kind: z.string().min(1),
14
16
  actor_id: z.string().min(1).max(256),
15
17
  active: z.number().int().min(0).max(1),
@@ -24,7 +26,7 @@ const receiptSchema = z.lazy(() => z.strictObject({
24
26
  name: z.string().min(1).max(256),
25
27
  computer_id: z.string().min(1),
26
28
  }));
27
- const selectRow = "SELECT computer_id,name,actor_kind,actor_id,active,created_at,updated_at FROM hub_team_computers";
29
+ const selectRow = "SELECT computer_id,name,size,actor_kind,actor_id,active,created_at,updated_at FROM hub_team_computers";
28
30
  function actorColumns(actor) {
29
31
  return { actorId: actor.id, actorKind: actor.kind };
30
32
  }
@@ -35,7 +37,7 @@ function sameActor(actorKind, actorId, actor) {
35
37
  export function createFleetInventory(options) {
36
38
  const { sql } = options;
37
39
  const ensure = () => {
38
- sql.exec("CREATE TABLE IF NOT EXISTS hub_team_computers (computer_id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0,1)), created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL) STRICT");
40
+ sql.exec("CREATE TABLE IF NOT EXISTS hub_team_computers (computer_id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, size TEXT NOT NULL CHECK (size IN ('small','default','large')), actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0,1)), created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL) STRICT");
39
41
  sql.exec("CREATE TABLE IF NOT EXISTS hub_team_computer_create_receipts (request_id TEXT PRIMARY KEY, actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, requested_name TEXT, name TEXT NOT NULL, computer_id TEXT NOT NULL REFERENCES hub_team_computers(computer_id)) STRICT");
40
42
  };
41
43
  const decode = (row) => {
@@ -45,6 +47,7 @@ export function createFleetInventory(options) {
45
47
  return {
46
48
  computerId: id.value,
47
49
  name: row.name,
50
+ size: row.size,
48
51
  createdAt: row.created_at,
49
52
  updatedAt: row.updated_at,
50
53
  };
@@ -122,6 +125,9 @@ export function createFleetInventory(options) {
122
125
  .toArray()[0]);
123
126
  if (stored.success && stored.data.active === 0)
124
127
  throw new ComputerInventoryError("request_conflict");
128
+ if (stored.success &&
129
+ stored.data.size !== (request.size ?? defaultComputerSize))
130
+ throw new ComputerInventoryError("request_conflict");
125
131
  if (!stored.success ||
126
132
  stored.data.name !== receipt.data.name ||
127
133
  stored.data.actor_kind !== receipt.data.actor_kind ||
@@ -142,7 +148,7 @@ export function createFleetInventory(options) {
142
148
  const computerId = computerIds.computer.generate();
143
149
  const now = Date.now();
144
150
  const columns = actorColumns(actor);
145
- sql.exec("INSERT INTO hub_team_computers (computer_id,name,actor_kind,actor_id,active,created_at,updated_at) VALUES (?,?,?,?,?,?,?)", computerId, name, columns.actorKind, columns.actorId, 1, now, now);
151
+ sql.exec("INSERT INTO hub_team_computers (computer_id,name,size,actor_kind,actor_id,active,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?)", computerId, name, request.size ?? defaultComputerSize, columns.actorKind, columns.actorId, 1, now, now);
146
152
  sql.exec("INSERT INTO hub_team_computer_create_receipts (request_id,actor_kind,actor_id,requested_name,name,computer_id) VALUES (?,?,?,?,?,?)", request.requestId, columns.actorKind, columns.actorId, request.name ?? null, name, computerId);
147
153
  const created = read(computerId);
148
154
  if (created === null)
@@ -272,6 +272,7 @@ export class FleetLifecycle {
272
272
  this.containerRuntimeStarted({
273
273
  runtimeId: current.runtimeId,
274
274
  backing,
275
+ size: row.size,
275
276
  startedAt: Date.now(),
276
277
  });
277
278
  }
@@ -314,7 +315,7 @@ export class FleetLifecycle {
314
315
  .state();
315
316
  if (!current.running || current.runtimeId !== row.runtimeId)
316
317
  continue;
317
- this.usage.requestRecycle(row.runtimeId, backing, Date.now());
318
+ this.usage.requestRecycle(row.runtimeId, backing, row.size, Date.now());
318
319
  await this.armRuntimeWatch(Date.now() + vmRecycleQuietMs);
319
320
  const started = await this.ports.backend
320
321
  .hostedContainerHost(backing)
@@ -1,5 +1,5 @@
1
1
  import type { WatchdogSqliteOwner } from "@fungi.computer/watchdog";
2
- import { type ContainerRuntimeStart, type HostedBacking } from "../computer-backends.js";
2
+ import { type ComputerSize, type ContainerRuntimeStart, type HostedBacking } from "../computer-backends.js";
3
3
  import type { ComputerFact, ComputerProvenance, ComputerUsageInterval } from "./wire.js";
4
4
  /**
5
5
  * Computer-local interval ledger; the host owns usage settlement.
@@ -26,6 +26,7 @@ export declare class ComputerRuntimeUsage {
26
26
  recycleCandidates(before: number): {
27
27
  runtimeId: string;
28
28
  backing: HostedBacking;
29
+ size: ComputerSize;
29
30
  }[];
30
31
  private ensureRecycle;
31
32
  pendingRecycles(): {
@@ -33,9 +34,10 @@ export declare class ComputerRuntimeUsage {
33
34
  backing: Extract<HostedBacking, {
34
35
  kind: "on-box-vm";
35
36
  }>;
37
+ size: ComputerSize;
36
38
  requestedAt: number;
37
39
  }[];
38
- requestRecycle(runtimeId: string, backing: HostedBacking, requestedAt: number): void;
40
+ requestRecycle(runtimeId: string, backing: HostedBacking, size: ComputerSize, requestedAt: number): void;
39
41
  finishRecycle(runtimeId: string): void;
40
42
  oldestVmStart(): number | null;
41
43
  /**
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { hostedBackingSchema, } from "../computer-backends.js";
2
+ import { computerSizeSchema, hostedBackingSchema, } from "../computer-backends.js";
3
3
  /**
4
4
  * Computer-local interval ledger; the host owns usage settlement.
5
5
  *
@@ -15,12 +15,12 @@ export class ComputerRuntimeUsage {
15
15
  this.checkpointMs = checkpointMs;
16
16
  }
17
17
  ensure() {
18
- this.sql.exec("CREATE TABLE IF NOT EXISTS hub_computer_runtime_usage (runtime_id TEXT PRIMARY KEY, backing TEXT NOT NULL, started_at INTEGER NOT NULL, observed_at INTEGER NOT NULL, ended INTEGER NOT NULL CHECK (ended IN (0,1)), delivered_at INTEGER NOT NULL DEFAULT -1) STRICT");
18
+ this.sql.exec("CREATE TABLE IF NOT EXISTS hub_computer_runtime_usage (runtime_id TEXT PRIMARY KEY, backing TEXT NOT NULL, size TEXT NOT NULL CHECK (size IN ('small','default','large')), started_at INTEGER NOT NULL, observed_at INTEGER NOT NULL, ended INTEGER NOT NULL CHECK (ended IN (0,1)), delivered_at INTEGER NOT NULL DEFAULT -1) STRICT");
19
19
  this.sql.exec("CREATE TABLE IF NOT EXISTS hub_computer_runtime_activity (runtime_id TEXT PRIMARY KEY, last_activity_at INTEGER NOT NULL) STRICT");
20
20
  }
21
21
  started(start) {
22
22
  this.ensure();
23
- this.sql.exec("INSERT OR IGNORE INTO hub_computer_runtime_usage (runtime_id, backing, started_at, observed_at, ended) VALUES (?,?,?,?,0)", start.runtimeId, JSON.stringify(start.backing), start.startedAt, start.startedAt);
23
+ this.sql.exec("INSERT OR IGNORE INTO hub_computer_runtime_usage (runtime_id, backing, size, started_at, observed_at, ended) VALUES (?,?,?,?,?,0)", start.runtimeId, JSON.stringify(start.backing), start.size, start.startedAt, start.startedAt);
24
24
  this.sql.exec("INSERT OR IGNORE INTO hub_computer_runtime_activity (runtime_id, last_activity_at) VALUES (?,?)", start.runtimeId, start.startedAt);
25
25
  }
26
26
  touchActivity(backing, at) {
@@ -62,20 +62,21 @@ export class ComputerRuntimeUsage {
62
62
  }
63
63
  recycleCandidates(before) {
64
64
  return this.sql
65
- .exec("SELECT runtime_id,backing FROM hub_computer_runtime_usage WHERE ended=0 AND started_at<=?", before)
65
+ .exec("SELECT runtime_id,backing,size FROM hub_computer_runtime_usage WHERE ended=0 AND started_at<=?", before)
66
66
  .toArray()
67
67
  .map((row) => ({
68
68
  runtimeId: z.string().parse(row.runtime_id),
69
69
  backing: hostedBackingSchema.parse(JSON.parse(z.string().parse(row.backing))),
70
+ size: computerSizeSchema.parse(row.size),
70
71
  }));
71
72
  }
72
73
  ensureRecycle() {
73
- this.sql.exec("CREATE TABLE IF NOT EXISTS hub_computer_vm_recycle (runtime_id TEXT PRIMARY KEY, backing TEXT NOT NULL, requested_at INTEGER NOT NULL) STRICT");
74
+ this.sql.exec("CREATE TABLE IF NOT EXISTS hub_computer_vm_recycle (runtime_id TEXT PRIMARY KEY, backing TEXT NOT NULL, size TEXT NOT NULL CHECK (size IN ('small','default','large')), requested_at INTEGER NOT NULL) STRICT");
74
75
  }
75
76
  pendingRecycles() {
76
77
  this.ensureRecycle();
77
78
  return this.sql
78
- .exec("SELECT runtime_id,backing,requested_at FROM hub_computer_vm_recycle")
79
+ .exec("SELECT runtime_id,backing,size,requested_at FROM hub_computer_vm_recycle")
79
80
  .toArray()
80
81
  .map((row) => {
81
82
  const backing = hostedBackingSchema.parse(JSON.parse(z.string().parse(row.backing)));
@@ -84,13 +85,14 @@ export class ComputerRuntimeUsage {
84
85
  return {
85
86
  runtimeId: z.string().parse(row.runtime_id),
86
87
  backing,
88
+ size: computerSizeSchema.parse(row.size),
87
89
  requestedAt: z.number().parse(row.requested_at),
88
90
  };
89
91
  });
90
92
  }
91
- requestRecycle(runtimeId, backing, requestedAt) {
93
+ requestRecycle(runtimeId, backing, size, requestedAt) {
92
94
  this.ensureRecycle();
93
- this.sql.exec("INSERT INTO hub_computer_vm_recycle (runtime_id,backing,requested_at) VALUES (?,?,?)", runtimeId, JSON.stringify(backing), requestedAt);
95
+ this.sql.exec("INSERT INTO hub_computer_vm_recycle (runtime_id,backing,size,requested_at) VALUES (?,?,?,?)", runtimeId, JSON.stringify(backing), size, requestedAt);
94
96
  }
95
97
  finishRecycle(runtimeId) {
96
98
  this.sql.exec("DELETE FROM hub_computer_vm_recycle WHERE runtime_id=?", runtimeId);
@@ -116,11 +118,12 @@ export class ComputerRuntimeUsage {
116
118
  }
117
119
  pending() {
118
120
  return this.sql
119
- .exec("SELECT runtime_id, backing, started_at, observed_at, ended FROM hub_computer_runtime_usage WHERE observed_at > delivered_at OR ended = 1 LIMIT 64")
121
+ .exec("SELECT runtime_id, backing, size, started_at, observed_at, ended FROM hub_computer_runtime_usage WHERE observed_at > delivered_at OR ended = 1 LIMIT 64")
120
122
  .toArray()
121
123
  .map((row) => ({
122
124
  runtimeId: z.string().parse(row.runtime_id),
123
125
  backing: hostedBackingSchema.parse(JSON.parse(z.string().parse(row.backing))),
126
+ size: computerSizeSchema.parse(row.size),
124
127
  startedAt: z.number().parse(row.started_at),
125
128
  observedAt: z.number().parse(row.observed_at),
126
129
  ended: row.ended === 1,
@@ -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";
@@ -165,6 +167,11 @@ export declare const computerUsageIntervalSchema: z.ZodObject<{
165
167
  kind: z.ZodLiteral<"on-box-vm">;
166
168
  hostId: z.ZodLazy<z.ZodString>;
167
169
  }, z.core.$strict>], "kind">;
170
+ size: z.ZodEnum<{
171
+ default: "default";
172
+ small: "small";
173
+ large: "large";
174
+ }>;
168
175
  startedAt: z.ZodNumber;
169
176
  observedAt: z.ZodNumber;
170
177
  ended: z.ZodBoolean;
@@ -178,6 +185,7 @@ export type ComputerUsageInterval = Readonly<{
178
185
  kind: "on-box-vm";
179
186
  hostId: string;
180
187
  }>;
188
+ size: "small" | "default" | "large";
181
189
  startedAt: number;
182
190
  observedAt: number;
183
191
  ended: boolean;
@@ -240,6 +248,11 @@ export declare const computerFactSchema: z.ZodLazy<z.ZodDiscriminatedUnion<[z.Zo
240
248
  kind: z.ZodLiteral<"on-box-vm">;
241
249
  hostId: z.ZodLazy<z.ZodString>;
242
250
  }, z.core.$strict>], "kind">;
251
+ size: z.ZodEnum<{
252
+ default: "default";
253
+ small: "small";
254
+ large: "large";
255
+ }>;
243
256
  startedAt: z.ZodNumber;
244
257
  observedAt: z.ZodNumber;
245
258
  ended: z.ZodBoolean;
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { computerOperationSchema, computerValueSchema, pathSchema, } from "@fungi.computer/computer-contract";
3
- import { attachedBackendId, hostedBackingSchema, localBackendSchema, } from "../computer-backends.js";
3
+ import { attachedBackendId, computerSizeSchema, hostedBackingSchema, localBackendSchema, } from "../computer-backends.js";
4
4
  /** Operations the host may admit on one Computer. */
5
5
  export const computerActionSchema = z.enum([
6
6
  ...computerOperationSchema.options,
@@ -98,6 +98,7 @@ const factIdentity = {
98
98
  export const computerUsageIntervalSchema = z.strictObject({
99
99
  runtimeId: z.string().min(1).max(128),
100
100
  backing: hostedBackingSchema,
101
+ size: computerSizeSchema,
101
102
  startedAt: z.number().int().nonnegative(),
102
103
  /** The last observed instant; final once `ended` is true. */
103
104
  observedAt: z.number().int().nonnegative(),
@@ -1,4 +1,20 @@
1
1
  import { z } from "zod";
2
+ /**
3
+ * What one running VM of each size counts against a host's capacity, in
4
+ * half-default-VM units: the configured memory in 4 GiB steps (4, 8 and 16
5
+ * GiB). Configured memory bounds what a busy guest can pin, where the measured
6
+ * resident size of an idle VM (about 0.43 GiB) bounds nothing. A host's
7
+ * `maxActive` and `reservedHeadroom` still count default-size VMs, so a host
8
+ * admits the same number of default VMs as before, twice as many small ones and
9
+ * half as many large ones.
10
+ */
11
+ export declare const computerSizeUnits: {
12
+ readonly small: 1;
13
+ readonly default: 2;
14
+ readonly large: 4;
15
+ };
16
+ /** Units one default-size VM holds: the factor between `maxActive` and units. */
17
+ export declare const unitsPerDefaultVm: 2;
2
18
  /** One VM host's active capacity, including slots held back as headroom. */
3
19
  export declare const hostCapacitySchema: z.ZodObject<{
4
20
  maxActive: z.ZodNumber;
@@ -1,4 +1,20 @@
1
1
  import { z } from "zod";
2
+ /**
3
+ * What one running VM of each size counts against a host's capacity, in
4
+ * half-default-VM units: the configured memory in 4 GiB steps (4, 8 and 16
5
+ * GiB). Configured memory bounds what a busy guest can pin, where the measured
6
+ * resident size of an idle VM (about 0.43 GiB) bounds nothing. A host's
7
+ * `maxActive` and `reservedHeadroom` still count default-size VMs, so a host
8
+ * admits the same number of default VMs as before, twice as many small ones and
9
+ * half as many large ones.
10
+ */
11
+ export const computerSizeUnits = {
12
+ small: 1,
13
+ default: 2,
14
+ large: 4,
15
+ };
16
+ /** Units one default-size VM holds: the factor between `maxActive` and units. */
17
+ export const unitsPerDefaultVm = computerSizeUnits.default;
2
18
  /** One VM host's active capacity, including slots held back as headroom. */
3
19
  export const hostCapacitySchema = z
4
20
  .strictObject({
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import { z } from "zod";
9
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
- import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
12
+ import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ComputerSize, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
13
13
  import { LocalBackendConnections } from "./local-backend.js";
14
14
  /** Files needs only the native Workspace lease and its atomic replacement door. */
15
15
  export type ComputerFilesRpc = Readonly<{
@@ -103,6 +103,8 @@ declare class ContainerComputer extends ContainerComputerBase {
103
103
  * overrides this with the list its Team projected down.
104
104
  */
105
105
  protected attachedBackends(): readonly AttachedBackend[];
106
+ /** This Computer's size, which the owner knows; the default until it says. */
107
+ protected computerSize(): ComputerSize;
106
108
  /** A runtime of a hosted backend started; owners meter it. */
107
109
  protected containerRuntimeStarted(start: ContainerRuntimeStart): void;
108
110
  /** The single routing decision over this Computer's attached backends. */
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";
@@ -78,7 +78,7 @@ import { ComputerProcessInventory, drainProcessExit, ProcessLogTail, failedObser
78
78
  import { assertComputerContainersEnabled, ComputerContainersPausedError, configureComputerContainer, hostedComputerContainersPaused, } from "./container-policy.js";
79
79
  import { OnBoxVmContainerHost, onBoxVmPlacement, } from "./on-box-vm.js";
80
80
  import { computerKeepAwake } from "./fleet/keep-awake.js";
81
- import { attachedBackendId, describeAttachedBackend, routeComputerBackend, } from "./computer-backends.js";
81
+ import { attachedBackendId, defaultComputerSize, describeAttachedBackend, routeComputerBackend, } from "./computer-backends.js";
82
82
  import { MeteredContainerHost } from "./metered-container-host.js";
83
83
  import { LocalBackendConnections, LocalWorkspaceBackend, localBackendDialPath, ownerLocalBackendDialPath, verifyLocalBackendDial, } from "./local-backend.js";
84
84
  const computerBinding = "COMPUTER";
@@ -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);
@@ -322,6 +369,10 @@ class ContainerComputer extends ContainerComputerBase {
322
369
  this.localConnections.park(backendId, server);
323
370
  return new Response(null, { status: 101, webSocket: client });
324
371
  }
372
+ /** This Computer's size, which the owner knows; the default until it says. */
373
+ computerSize() {
374
+ return defaultComputerSize;
375
+ }
325
376
  /** A runtime of a hosted backend started; owners meter it. */
326
377
  containerRuntimeStarted(start) {
327
378
  void start;
@@ -362,7 +413,7 @@ class ContainerComputer extends ContainerComputerBase {
362
413
  const host = backing.kind === "platform-container"
363
414
  ? this.getWorkspaceContainer()
364
415
  : this.onBoxVmHost(backing.hostId);
365
- return new MeteredContainerHost(host, backing, (start) => {
416
+ return new MeteredContainerHost(host, backing, () => this.computerSize(), (start) => {
366
417
  this.containerRuntimeStarted(start);
367
418
  });
368
419
  }
@@ -381,7 +432,7 @@ class ContainerComputer extends ContainerComputerBase {
381
432
  }
382
433
  /** Let the consuming owner admit boots while preserving the runtime host seam. */
383
434
  createOnBoxVmHost(placement) {
384
- return new OnBoxVmContainerHost(placement, this.bindings, this.state.id.toString());
435
+ return new OnBoxVmContainerHost(placement, this.bindings, this.state.id.toString(), () => this.computerSize());
385
436
  }
386
437
  /** Whether a hosted backend's runtime is running now. */
387
438
  async containerRunning(backing) {
@@ -1046,6 +1097,12 @@ export class ComputerDO extends ContainerComputer {
1046
1097
  await this.#syncRunningHosted("push");
1047
1098
  return result;
1048
1099
  }
1100
+ case "move": {
1101
+ await this.#syncRunningHosted("pull");
1102
+ const result = this.state.storage.transactionSync(() => move(workspace, input));
1103
+ await this.#syncRunningHosted("push");
1104
+ return result;
1105
+ }
1049
1106
  default:
1050
1107
  throw new Error(`Computer capability is unavailable: ${selected}`);
1051
1108
  }
@@ -1,5 +1,5 @@
1
1
  import type { IWorkspaceContainerAPI, WorkspaceRef } from "@fungi.computer/cloudflare-computer/backends/container";
2
- import type { ContainerRuntimeStart, HostedBacking } from "./computer-backends.js";
2
+ import type { ComputerSize, ContainerRuntimeStart, HostedBacking } from "./computer-backends.js";
3
3
  /**
4
4
  * A container host that reports each runtime it starts. Every other call
5
5
  * passes through unchanged, so the container backend cannot tell it apart
@@ -7,7 +7,7 @@ import type { ContainerRuntimeStart, HostedBacking } from "./computer-backends.j
7
7
  */
8
8
  export declare class MeteredContainerHost implements IWorkspaceContainerAPI {
9
9
  #private;
10
- constructor(host: IWorkspaceContainerAPI, backing: HostedBacking, started: (start: ContainerRuntimeStart) => void);
10
+ constructor(host: IWorkspaceContainerAPI, backing: HostedBacking, size: () => ComputerSize, started: (start: ContainerRuntimeStart) => void);
11
11
  start(env: Record<string, string>, enableInternet: boolean): Promise<{
12
12
  runtimeId: string;
13
13
  }>;
@@ -6,10 +6,12 @@
6
6
  export class MeteredContainerHost {
7
7
  #host;
8
8
  #backing;
9
+ #size;
9
10
  #started;
10
- constructor(host, backing, started) {
11
+ constructor(host, backing, size, started) {
11
12
  this.#host = host;
12
13
  this.#backing = backing;
14
+ this.#size = size;
13
15
  this.#started = started;
14
16
  }
15
17
  async #report(boot) {
@@ -17,6 +19,7 @@ export class MeteredContainerHost {
17
19
  this.#started({
18
20
  runtimeId: runtime.runtimeId,
19
21
  backing: this.#backing,
22
+ size: this.#size(),
20
23
  startedAt: Date.now(),
21
24
  });
22
25
  return runtime;
@@ -1,5 +1,6 @@
1
1
  import type { IWorkspaceContainerAPI, WorkspaceRef } from "@fungi.computer/cloudflare-computer/backends/container";
2
2
  import { z } from "zod";
3
+ import { type ComputerSize } from "./computer-backends.js";
3
4
  /**
4
5
  * The on-box VM backing of a Computer's container.
5
6
  *
@@ -58,6 +59,11 @@ declare const vmInventorySchema: z.ZodArray<z.ZodObject<{
58
59
  id: z.ZodString;
59
60
  name: z.ZodString;
60
61
  lastActive: z.ZodNumber;
62
+ size: z.ZodEnum<{
63
+ default: "default";
64
+ small: "small";
65
+ large: "large";
66
+ }>;
61
67
  }, z.core.$strict>>;
62
68
  export type OnBoxVmInventory = z.infer<typeof vmInventorySchema>;
63
69
  export type OnBoxVmOperation = "status" | "start" | "restart" | "destroy" | "intercept" | "inventory";
@@ -74,7 +80,11 @@ export declare class OnBoxVmTimeoutError extends OnBoxVmTimeoutError_base<{
74
80
  /** One Durable Object's view of its microVM through the host service. */
75
81
  export declare class OnBoxVmContainerHost implements IWorkspaceContainerAPI {
76
82
  #private;
77
- constructor(placement: OnBoxVmPlacement, env: OnBoxVmEnv, vmId: string);
83
+ /**
84
+ * `size` names the Computer's size at each boot; a host built only to read
85
+ * or stop VMs omits it and cannot boot one.
86
+ */
87
+ constructor(placement: OnBoxVmPlacement, env: OnBoxVmEnv, vmId: string, size?: () => ComputerSize);
78
88
  /** Signed host-wide inventory; includes VMs outside this Hub's directory. */
79
89
  inventory(): Promise<OnBoxVmInventory>;
80
90
  start(env: Record<string, string>, enableInternet: boolean): Promise<{
package/dist/on-box-vm.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { computerSizeSchema } from "./computer-backends.js";
2
3
  import * as Data from "effect/Data";
3
4
  import { SeamReplayPartitions, importSeamSigner, importSeamVerifiers, seamBodyDigest, seamHeader, signSeamRequest, unsignedPayload, verifySeamRequest, } from "@fungi.computer/seam";
4
5
  function accessHeaders(env) {
@@ -86,6 +87,7 @@ const vmInventorySchema = z.array(vmStateSchema.extend({
86
87
  id: z.string().regex(/^[0-9a-f]{64}$/),
87
88
  name: z.string(),
88
89
  lastActive: z.number().int().nonnegative(),
90
+ size: computerSizeSchema,
89
91
  }));
90
92
  const vmStartSchema = z.lazy(() => z.strictObject({
91
93
  runtimeId: z.string().min(1).max(128),
@@ -124,7 +126,13 @@ export class OnBoxVmContainerHost {
124
126
  #placement;
125
127
  #env;
126
128
  #vmId;
127
- constructor(placement, env, vmId) {
129
+ #size;
130
+ /**
131
+ * `size` names the Computer's size at each boot; a host built only to read
132
+ * or stop VMs omits it and cannot boot one.
133
+ */
134
+ constructor(placement, env, vmId, size) {
135
+ this.#size = size;
128
136
  this.#placement = placement;
129
137
  this.#env = env;
130
138
  this.#vmId = z
@@ -161,10 +169,13 @@ export class OnBoxVmContainerHost {
161
169
  }
162
170
  }
163
171
  async #boot(operation, env, enableInternet) {
172
+ if (this.#size === undefined)
173
+ throw new Error("This on-box VM host was built without a Computer size");
164
174
  const started = await this.#call(operation, vmStartSchema, {
165
175
  env,
166
176
  enableInternet,
167
177
  sleepAfterMs: vmHostSleepBackstopMs,
178
+ size: this.#size(),
168
179
  });
169
180
  return { runtimeId: started.runtimeId };
170
181
  }
@@ -19604,6 +19604,16 @@ var appBackendBindingKinds = {
19604
19604
  requires: ["computer.writeFile"],
19605
19605
  effect: "write"
19606
19606
  },
19607
+ mkdir: {
19608
+ cap: "app.computer.write",
19609
+ requires: ["computer.writeFile"],
19610
+ effect: "write"
19611
+ },
19612
+ move: {
19613
+ cap: "app.computer.write",
19614
+ requires: ["computer.writeFile"],
19615
+ effect: "write"
19616
+ },
19607
19617
  preview: {
19608
19618
  cap: "app.computer.exec",
19609
19619
  requires: ["computer.execute"],
@@ -19677,6 +19687,7 @@ var appCapabilityIds = [
19677
19687
  "agent.manage",
19678
19688
  "agent.rename",
19679
19689
  "agent.avatar",
19690
+ "agent.instructions",
19680
19691
  "agent.toolPolicy",
19681
19692
  "agent.read",
19682
19693
  "agent.send",
@@ -22488,6 +22499,19 @@ import { join as join6 } from "node:path";
22488
22499
  // src/build.ts
22489
22500
  init_snapshot_program_scripts();
22490
22501
 
22502
+ // src/build/build-memory.ts
22503
+ import { totalmem } from "node:os";
22504
+ var mebibyte = 1024 * 1024;
22505
+ var preferredHeapMib = 4096;
22506
+ function machineMemoryMib() {
22507
+ const constrained = process.constrainedMemory();
22508
+ const bytes = constrained > 0 && constrained < totalmem() ? constrained : totalmem();
22509
+ return Math.floor(bytes / mebibyte);
22510
+ }
22511
+ function buildHeapMib(memoryMib) {
22512
+ return Math.min(preferredHeapMib, Math.floor(memoryMib * 2 / 3));
22513
+ }
22514
+
22491
22515
  // src/build/process-group.ts
22492
22516
  import { setTimeout as delay2 } from "node:timers/promises";
22493
22517
  var CleanupError = class extends Error {
@@ -35736,13 +35760,12 @@ function runHtmlCommand(args2, cwd, env, command = "pnpm", onOutput) {
35736
35760
  function snapshotPrograms() {
35737
35761
  return Promise.resolve().then(() => (init_snapshot_program_scripts(), snapshot_program_scripts_exports));
35738
35762
  }
35739
- var snapshotBuildHeapMegabytes = 4096;
35740
35763
  function snapshotBuildEnvironment(sourceSnapshotPath) {
35741
35764
  const env = {
35742
35765
  PATH: process.env.PATH ?? "/usr/bin:/bin",
35743
35766
  HOME: join5(sourceSnapshotPath, ".publisher-home"),
35744
35767
  NODE_ENV: "production",
35745
- NODE_OPTIONS: `--max-old-space-size=${String(snapshotBuildHeapMegabytes)}`,
35768
+ NODE_OPTIONS: `--max-old-space-size=${String(buildHeapMib(machineMemoryMib()))}`,
35746
35769
  NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS,
35747
35770
  SSL_CERT_FILE: process.env.SSL_CERT_FILE,
35748
35771
  npm_config_userconfig: "/dev/null",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/computer",
3
- "version": "0.9.0",
3
+ "version": "0.11.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.11",
64
64
  "@fungi.computer/seam": "0.2.5",
65
65
  "@fungi.computer/watchdog": "0.1.3",
66
- "@fungi.computer/computer-contract": "0.2.0",
66
+ "@fungi.computer/computer-contract": "0.3.1",
67
67
  "effect": "4.0.2",
68
68
  "just-bash": "3.4.2",
69
69
  "zod": "4.4.3"