@catamorphic/work-server 0.1.0-alpha.39 → 0.1.0-alpha.42

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.
Files changed (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
package/src/cluster.ts CHANGED
@@ -2,7 +2,9 @@ import { createECDH, createHash } from "node:crypto";
2
2
  import {
3
3
  capacityFits,
4
4
  cleanupWorkerAllocations,
5
+ diskFits,
5
6
  EnvironmentCapacityError,
7
+ floorFor,
6
8
  WORKER_NODE_LEASE_MS,
7
9
  type WorkerCapacity,
8
10
  WorkerNodeLeaseHeldError,
@@ -12,13 +14,18 @@ import type { DB } from "@catamorphic/db";
12
14
  import type {
13
15
  EnvironmentBinding,
14
16
  EnvironmentProvider,
17
+ MachineDisk,
15
18
  SandboxProvider,
16
19
  } from "@catamorphic/sandbox";
17
20
  import {
18
21
  accessTier,
22
+ describeDisk,
23
+ diskBudgetMb,
19
24
  environmentSatisfies,
25
+ MACHINE_CAPABILITIES,
20
26
  placementOrder,
21
27
  poolMatches,
28
+ servesOnlyThisOwner,
22
29
  } from "@catamorphic/sandbox";
23
30
  import { type Kysely, sql } from "kysely";
24
31
  import {
@@ -68,18 +75,21 @@ export async function registerWorkMachine(args: {
68
75
  */
69
76
  ownSignIns?: boolean;
70
77
  /**
71
- * Whose work each worker takes, and who owns a piece of work: an email
72
- * and directory groups matched against worker access (ADR 0167).
78
+ * This machine's latest disk measurement (ADR 0336), sent with each
79
+ * heartbeat; admission keeps its floor and reserves `storageMb` here.
80
+ */
81
+ disk?: () => MachineDisk | undefined;
82
+ /**
83
+ * Whom each worker's machine is for (ADRs 0167, 0349): users, projects'
84
+ * own work, single chat keys, or anyone.
73
85
  */
74
86
  placement?: {
75
87
  workers(): Promise<Map<string, ScheduledPlacement>>;
76
- owner(
77
- userId: string,
78
- ): Promise<{ userId: string; groups: readonly string[] } | undefined>;
79
88
  };
80
89
  }) {
81
90
  const nodes = new WorkerNodesService(args.db);
82
91
  let signIns = args.signIns?.() ?? [];
92
+ const firstDisk = args.disk?.();
83
93
  const describe = (): EnvironmentBinding => ({
84
94
  id: args.nodeId,
85
95
  label: args.label,
@@ -93,11 +103,14 @@ export async function registerWorkMachine(args: {
93
103
  "network.egress",
94
104
  ...(args.sandboxProvider.capabilities ?? []),
95
105
  ...(args.capabilities ?? []),
106
+ ...(firstDisk ? [MACHINE_CAPABILITIES.disk] : []),
96
107
  ...signIns,
97
108
  ],
98
109
  resources: {
99
110
  cpuMillis: args.capacity?.cpuMillis,
100
111
  memoryMb: args.capacity?.memoryMb,
112
+ // The most a workspace may reserve here (ADR 0336).
113
+ ...(firstDisk ? { storageMb: diskBudgetMb(firstDisk) } : {}),
101
114
  },
102
115
  resourceLimits: args.sandboxProvider.resourceLimits,
103
116
  labels: { ...args.labels, node: args.nodeId, plane: "control" },
@@ -133,11 +146,13 @@ export async function registerWorkMachine(args: {
133
146
  tenantId,
134
147
  projectId,
135
148
  ownerUserId,
149
+ chatKey,
136
150
  pool,
137
151
  strict,
138
152
  workerNodeId,
139
153
  allocationBindingId,
140
154
  requirements,
155
+ fill,
141
156
  }) => {
142
157
  const candidates = await nodes.list({
143
158
  tenantId,
@@ -146,12 +161,7 @@ export async function registerWorkMachine(args: {
146
161
  const workerPlacements =
147
162
  (await args.placement?.workers()) ??
148
163
  new Map<string, ScheduledPlacement>();
149
- const owner = ownerUserId
150
- ? ((await args.placement?.owner(ownerUserId)) ?? {
151
- userId: ownerUserId,
152
- groups: [],
153
- })
154
- : undefined;
164
+ const owner = ownerUserId ? { userId: ownerUserId } : undefined;
155
165
  // Labels are live: the server's own plus the operator's current ones.
156
166
  const described = candidates.map((node) => {
157
167
  const worker = isWorkerNode(node.id);
@@ -169,16 +179,17 @@ export async function registerWorkMachine(args: {
169
179
  },
170
180
  };
171
181
  });
172
- // A released machine takes no new work, and keeps serving an
173
- // Allocation it already holds (ADR 0205): a lookup naming it as both
174
- // the Allocation's binding and its machine.
182
+ // A machine that is not accepting (dropped by the plan, stopping,
183
+ // being reset) takes no new work, and keeps serving an Allocation it
184
+ // already holds (ADRs 0205, 0349): a lookup naming it as both the
185
+ // Allocation's binding and its machine.
175
186
  const holdsAllocation = (nodeId: string) =>
176
187
  allocationBindingId === nodeId && workerNodeId === nodeId;
177
188
  const eligible = described.filter(
178
189
  ({ node, policy, worker, labels }) =>
179
190
  node.available &&
180
191
  (!worker ||
181
- (policy && (!policy.released || holdsAllocation(node.id)))) &&
192
+ (policy && (policy.accepting || holdsAllocation(node.id)))) &&
182
193
  (!allocationBindingId || allocationBindingId === node.id) &&
183
194
  (!workerNodeId || workerNodeId === node.id) &&
184
195
  poolMatches(labels, pool) &&
@@ -188,49 +199,87 @@ export async function registerWorkMachine(args: {
188
199
  // the operator marked those people as trusting each other.
189
200
  (!policy ||
190
201
  policy.trusted ||
191
- servesOneOwner(policy.access) ||
202
+ servesOneOwner(policy.for) ||
192
203
  node.descriptor.isolation !== "process"),
193
204
  );
205
+ const tierOf = (policy: ScheduledPlacement | undefined) =>
206
+ accessTier({
207
+ access: policy ? nodeAccess(policy.for) : { everyone: true },
208
+ owner,
209
+ ...(projectId ? { projectId } : {}),
210
+ ...(chatKey ? { chatKey } : {}),
211
+ });
194
212
  const ordered = placementOrder(
195
213
  eligible,
196
- ({ policy }) =>
197
- accessTier({
198
- access: policy ? nodeAccess(policy.access) : { everyone: true },
199
- owner,
200
- ...(projectId ? { projectId } : {}),
201
- }),
214
+ // Admission decided whom an Allocation's machine is for: it
215
+ // resolves for that Allocation whatever the machine is for now.
216
+ ({ node, policy }) =>
217
+ tierOf(policy) ?? (holdsAllocation(node.id) ? 2 : undefined),
202
218
  { strict },
203
219
  );
220
+ // The rule admission applies (ADR 0336): a workflow run down to the
221
+ // critical floor, everything with the storage it reserves, and a cache
222
+ // fill with its cache's size above the full floor.
223
+ const storageMb =
224
+ (requirements?.resources?.storageMb ?? 0) + (fill?.storageMb ?? 0);
225
+ const workload =
226
+ requirements?.workload && !fill
227
+ ? { workload: requirements.workload }
228
+ : {};
229
+ const roomy = ({ node }: (typeof ordered)[number]) =>
230
+ diskFits({
231
+ usage: node.usage,
232
+ resources: storageMb > 0 ? { storageMb } : {},
233
+ ...workload,
234
+ ...(node.disk && node.diskFresh ? { disk: node.disk } : {}),
235
+ });
204
236
  const chosen = ordered.find(
205
- ({ node }) =>
237
+ (entry) =>
206
238
  allocationBindingId ||
207
- !node.capacity ||
208
- capacityFits({
209
- capacity: node.capacity,
210
- usage: node.usage,
211
- resources: { ...node.defaults, ...requirements?.resources },
212
- }),
239
+ (roomy(entry) &&
240
+ (!entry.node.capacity ||
241
+ capacityFits({
242
+ capacity: entry.node.capacity,
243
+ usage: entry.node.usage,
244
+ resources: {
245
+ ...entry.node.defaults,
246
+ ...requirements?.resources,
247
+ },
248
+ }))),
213
249
  );
214
250
  if (!chosen) {
215
251
  const full = ordered[0];
216
- if (full) throw new EnvironmentCapacityError(full.node.id);
252
+ // Short of disk is a wait like any other (ADR 0336), said as such.
253
+ const disk = full && !roomy(full) ? full.node.disk : undefined;
254
+ if (full)
255
+ throw new EnvironmentCapacityError(
256
+ full.node.id,
257
+ disk
258
+ ? {
259
+ disk,
260
+ floorBytes: floorFor({ disk, ...workload }),
261
+ ...(storageMb > 0 ? { storageMb } : {}),
262
+ }
263
+ : undefined,
264
+ );
217
265
  return undefined;
218
266
  }
219
267
  const selected = {
220
268
  ...chosen.node,
221
- descriptor: { ...chosen.node.descriptor, labels: chosen.labels },
269
+ descriptor: {
270
+ ...chosen.node.descriptor,
271
+ labels: chosen.labels,
272
+ ...(chosen.policy?.admissionRevision
273
+ ? { admissionRevision: chosen.policy.admissionRevision }
274
+ : {}),
275
+ },
222
276
  };
223
- // A worker whose access names only this owner (a member, or for a
224
- // project's own work that project) takes no one else's work, so it
225
- // may hold their personal credentials (ADR 0184) and secrets (ADR
226
- // 0206).
277
+ // A worker that is for this owner alone (a member, or for a
278
+ // project's own work that project or that one chat key) takes no one
279
+ // else's work, so it may hold their personal credentials (ADR 0184)
280
+ // and secrets (ADR 0206).
227
281
  const servesOnlyOwner = Boolean(
228
- chosen.policy &&
229
- accessTier({
230
- access: nodeAccess(chosen.policy.access),
231
- owner,
232
- ...(projectId ? { projectId } : {}),
233
- }) === 0,
282
+ chosen.policy && servesOnlyThisOwner(tierOf(chosen.policy)),
234
283
  );
235
284
  // A member's sign-in only on a machine that holds no one else's
236
285
  // (ADR 0213), or a single person's server that accepted them.
@@ -254,7 +303,9 @@ export async function registerWorkMachine(args: {
254
303
  sandboxProvider: nodes.remoteProvider({
255
304
  nodeId: selected.id,
256
305
  offer: selected.remote,
257
- label: "The worker",
306
+ // Named, so a turn it cuts short says which machine.
307
+ label: `Worker ${selected.descriptor.label}`,
308
+ capabilities: selected.descriptor.capabilities,
258
309
  }),
259
310
  }
260
311
  : {}),
@@ -296,11 +347,28 @@ export async function registerWorkMachine(args: {
296
347
  isLost = true;
297
348
  markLost();
298
349
  };
350
+ // The disk is reported under the lease it holds (ADR 0336); an episode
351
+ // under the floor is logged once, where any replica could hear it.
352
+ const reportDisk = async () => {
353
+ const disk = args.disk?.();
354
+ if (!disk) return;
355
+ const episode = await nodes.reportDisk({ lease, disk });
356
+ if (episode.state === "started")
357
+ console.warn(
358
+ `[catamorphic] ${args.label} is short of disk: ${describeDisk(disk)}`,
359
+ );
360
+ };
299
361
  const beat = async (): Promise<void> => {
300
362
  const sentAt = performance.now();
301
363
  if (await renew()) {
302
364
  renewedFrom = sentAt;
303
365
  ready = true;
366
+ await reportDisk().catch((error: unknown) =>
367
+ console.warn(
368
+ "[catamorphic] Could not report this machine's disk",
369
+ error,
370
+ ),
371
+ );
304
372
  return;
305
373
  }
306
374
  ready = false;
@@ -322,6 +390,11 @@ export async function registerWorkMachine(args: {
322
390
  if (!(error instanceof WorkerNodeLeaseHeldError)) throw error;
323
391
  }
324
392
  };
393
+ // Admission knows this machine's disk from its first moment.
394
+ if (ready)
395
+ await reportDisk().catch((error: unknown) =>
396
+ console.warn("[catamorphic] Could not report this machine's disk", error),
397
+ );
325
398
  const timer = setInterval(() => {
326
399
  if (isLost) return;
327
400
  // Whatever the database says, a disposable node whose lease could have
package/src/config.ts CHANGED
@@ -12,11 +12,6 @@ import {
12
12
  type GatewayConfig,
13
13
  gatewayConfigFromFile,
14
14
  } from "./gateway/gateway-config.js";
15
- import {
16
- type MachinesConfig,
17
- machineClassesProblem,
18
- machinesConfigFromFile,
19
- } from "./workers/machine-classes.js";
20
15
  import { NodeLabelsSchema } from "./workers/placement.js";
21
16
 
22
17
  export type WorkAgentEffort = "low" | "medium" | "high";
@@ -119,21 +114,12 @@ export interface WorkServerConfig {
119
114
  */
120
115
  webhookMaxBodyBytes?: number;
121
116
  /**
122
- * Machine classes machine rules name (ADR 0205): Hetzner Cloud servers,
123
- * pools of enrolled machines, or the `machineProvisioner` hook's. The
124
- * image reads them from the JSON file `WORK_MACHINES_CONFIG`.
125
- */
126
- machines?: MachinesConfig;
127
- /**
128
- * Hetzner Cloud API token for `hetzner-cloud` classes, from
129
- * `WORK_HETZNER_TOKEN`; never part of the machines file.
130
- */
131
- hetznerToken?: string;
132
- /**
133
- * The deployment's own worker image (ADRs 0205, 0294), explicitly
134
- * supplied here or through `WORK_WORKER_IMAGE`.
117
+ * Minutes work waits for a machine in an Environment that names no
118
+ * `waitMinutes` of its own, on a server with a machines hook (ADR 0349),
119
+ * from `WORK_MACHINE_WAIT_MINUTES` (default 30): a new chat waits for
120
+ * the machine the plan starts for it instead of failing at once.
135
121
  */
136
- workerImage?: string;
122
+ machineWaitMinutes?: number;
137
123
  }
138
124
 
139
125
  export function workServerConfigFromEnv(
@@ -208,30 +194,18 @@ export function workServerConfigFromEnv(
208
194
  };
209
195
  }
210
196
 
211
- /** Machine classes, the Hetzner token, and the worker image (ADR 0205). */
197
+ /** How long waiting work waits for its machine by default (ADR 0349). */
212
198
  function machineSettingsFromEnv(
213
199
  env: Record<string, string | undefined>,
214
- ): Pick<WorkServerConfig, "machines" | "hetznerToken" | "workerImage"> {
215
- const machines = env.WORK_MACHINES_CONFIG
216
- ? machinesConfigFromFile(env.WORK_MACHINES_CONFIG)
217
- : undefined;
218
- const hetznerToken = env.WORK_HETZNER_TOKEN?.trim() || undefined;
219
- if (machines) {
220
- // Custom classes need the hook, which only a custom server has; the
221
- // server checks that when it starts.
222
- const problem = machineClassesProblem({
223
- classes: machines.classes,
224
- hetznerToken: Boolean(hetznerToken),
225
- provisioner: true,
226
- });
227
- if (problem) throw new Error(problem);
228
- }
229
- const workerImage = env.WORK_WORKER_IMAGE?.trim();
230
- return {
231
- ...(machines ? { machines } : {}),
232
- ...(hetznerToken ? { hetznerToken } : {}),
233
- ...(workerImage ? { workerImage } : {}),
234
- };
200
+ ): Pick<WorkServerConfig, "machineWaitMinutes"> {
201
+ const raw = env.WORK_MACHINE_WAIT_MINUTES?.trim();
202
+ if (!raw) return {};
203
+ const minutes = Number(raw);
204
+ if (!Number.isSafeInteger(minutes) || minutes < 1 || minutes > 24 * 60)
205
+ throw new Error(
206
+ "WORK_MACHINE_WAIT_MINUTES must be a whole number of minutes from 1 to 1440",
207
+ );
208
+ return { machineWaitMinutes: minutes };
235
209
  }
236
210
 
237
211
  function proxyEntries(value: string): string[] {
@@ -101,6 +101,25 @@ export interface WorkExecutionSettings {
101
101
  * `WORK_VOLUME_RETENTION_DAYS`, default 30).
102
102
  */
103
103
  volumeRetentionDays: number;
104
+ /**
105
+ * What the machine keeps free on each filesystem it writes to, in MiB
106
+ * (ADR 0336, `WORK_DISK_FLOOR_MB`): admission never goes below it. 0
107
+ * keeps none; absent, 10% of the filesystem and at most 10 GiB.
108
+ */
109
+ diskFloorMb?: number;
110
+ /**
111
+ * The lower floor workflow runs start down to, in MiB (ADR 0336,
112
+ * `WORK_DISK_CRITICAL_MB`): so the workflows that free or replace
113
+ * machines still run when chats stop. 0 keeps none; absent, 1% of the
114
+ * filesystem and at most 1 GiB.
115
+ */
116
+ diskCriticalMb?: number;
117
+ /**
118
+ * Hours an image Work built or pulled, and the Docker data inside
119
+ * sandboxes, may go unused before the machine removes it (ADR 0336,
120
+ * `WORK_IMAGE_RETENTION_HOURS`, default 24).
121
+ */
122
+ imageRetentionHours: number;
104
123
  }
105
124
 
106
125
  /** The settings once the backend is known: what a machine runs with. */
@@ -123,6 +142,12 @@ export function executionSettingsFromEnv(
123
142
  throw new Error(`${name} must be a positive integer`);
124
143
  return value;
125
144
  };
145
+ const nonNegative = (name: string): number => {
146
+ const value = Number(env[name]);
147
+ if (!Number.isSafeInteger(value) || value < 0)
148
+ throw new Error(`${name} must be a whole number of MiB, 0 or more`);
149
+ return value;
150
+ };
126
151
  const backend = env.WORK_SANDBOX ?? "auto";
127
152
  if (
128
153
  backend !== "auto" &&
@@ -178,6 +203,13 @@ export function executionSettingsFromEnv(
178
203
  workloads: workloadsFromEnv(env.WORK_CONTROL_PLANE_WORKLOADS),
179
204
  trustControlPlaneAgents: env.WORK_TRUST_CONTROL_PLANE_AGENTS === "1",
180
205
  volumeRetentionDays: positive("WORK_VOLUME_RETENTION_DAYS", 30),
206
+ imageRetentionHours: positive("WORK_IMAGE_RETENTION_HOURS", 24),
207
+ ...(env.WORK_DISK_FLOOR_MB !== undefined
208
+ ? { diskFloorMb: nonNegative("WORK_DISK_FLOOR_MB") }
209
+ : {}),
210
+ ...(env.WORK_DISK_CRITICAL_MB !== undefined
211
+ ? { diskCriticalMb: nonNegative("WORK_DISK_CRITICAL_MB") }
212
+ : {}),
181
213
  ...(env.WORK_SANDBOX_PIDS_LIMIT !== undefined
182
214
  ? { pidsLimit: positive("WORK_SANDBOX_PIDS_LIMIT", 4096) }
183
215
  : {}),
@@ -629,5 +661,13 @@ export function workExecution(args: {
629
661
  reason: settings.reason,
630
662
  },
631
663
  volumeRetentionMs: settings.volumeRetentionDays * 24 * 60 * 60 * 1000,
664
+ /** What the machine keeps free on its disk (ADR 0336). */
665
+ ...(settings.diskFloorMb !== undefined
666
+ ? { diskFloorMb: settings.diskFloorMb }
667
+ : {}),
668
+ ...(settings.diskCriticalMb !== undefined
669
+ ? { diskCriticalMb: settings.diskCriticalMb }
670
+ : {}),
671
+ imageRetentionMs: settings.imageRetentionHours * 60 * 60 * 1000,
632
672
  };
633
673
  }
package/src/fake-agent.ts CHANGED
@@ -32,6 +32,7 @@ interface FakeSandbox {
32
32
  * - `write-file <name> <text>` (answers `Wrote <name>`), `read-file <name>`
33
33
  * - `run <shell>`: `exit=<code>` then the output (` ;; ` chains steps)
34
34
  * - `mcp <alias> <tool> <json>`: one tool of the chat's connection server
35
+ * - `tool <name> <json>`: one of Work's own tools, as `submit_result`
35
36
  * - `background-start`, `background-list`, `background-stop <id>`
36
37
  * - `ask <question>`: asks the person and answers with their answer
37
38
  *
@@ -64,6 +65,7 @@ const COMMANDS = [
64
65
  "read-file",
65
66
  "run",
66
67
  "mcp",
68
+ "tool",
67
69
  "ask",
68
70
  "background-start",
69
71
  "background-list",
@@ -202,7 +204,7 @@ async function answer(input: {
202
204
  if (signal.aborted) resolve(undefined);
203
205
  signal.addEventListener("abort", () => resolve(undefined), { once: true });
204
206
  });
205
- if (command === "run" || command === "mcp") {
207
+ if (command === "run" || command === "mcp" || command === "tool") {
206
208
  // An interrupt ends the turn at once; the step's command is left to
207
209
  // finish on its own.
208
210
  const results: string[] = [];
@@ -210,9 +212,11 @@ async function answer(input: {
210
212
  const result = await Promise.race([
211
213
  step.startsWith("mcp ")
212
214
  ? callConnectionTool(input.attempt, step.slice("mcp ".length))
213
- : exec(step.slice("run ".length)).then(
214
- (done) => `exit=${done.exitCode}\n${done.result.trim()}`,
215
- ),
215
+ : step.startsWith("tool ")
216
+ ? callWorkTool(input.host, step.slice("tool ".length))
217
+ : exec(step.slice("run ".length)).then(
218
+ (done) => `exit=${done.exitCode}\n${done.result.trim()}`,
219
+ ),
216
220
  stopped,
217
221
  ]);
218
222
  if (result === undefined) return undefined;
@@ -301,6 +305,19 @@ const ToolAnswer = z.object({
301
305
  });
302
306
 
303
307
  /** `<alias> <tool> <json>`: one `tools/call` on the alias's MCP server. */
308
+ /** One of the host tools Work serves the attempt (`submit_result`, ...). */
309
+ async function callWorkTool(host: AttemptHost, step: string): Promise<string> {
310
+ const [name = "", ...rest] = step.split(" ");
311
+ const result = await host.callTool({
312
+ name,
313
+ input: JSON.parse(rest.join(" ") || "{}"),
314
+ });
315
+ const text = result.content
316
+ .map((block) => (block.type === "text" ? block.text : ""))
317
+ .join("\n");
318
+ return `${result.isError ? "error: " : ""}${text}`;
319
+ }
320
+
304
321
  async function callConnectionTool(
305
322
  attempt: AttemptStart,
306
323
  step: string,
package/src/index.ts CHANGED
@@ -14,6 +14,12 @@ export {
14
14
  type ModelRequest,
15
15
  type ModelRequestRewrite,
16
16
  } from "@catamorphic/core";
17
+ export {
18
+ SIGN_IN_HARNESSES,
19
+ SIGN_IN_SPECS,
20
+ type SignInHarness,
21
+ signInHarness,
22
+ } from "@catamorphic/sandbox";
17
23
  export {
18
24
  defineCapability,
19
25
  defineGitConnectionProvider,
@@ -57,6 +63,26 @@ export {
57
63
  type GoogleServiceAccountKey,
58
64
  GoogleWorkspaceDirectory,
59
65
  } from "./identity/google-directory.js";
66
+ export {
67
+ DEFAULT_LOST_AFTER_MINUTES,
68
+ type DesiredMachine,
69
+ DesiredMachineSchema,
70
+ MACHINE_EVENT_KINDS,
71
+ type MachineCreateRequest,
72
+ type MachineCreateResult,
73
+ type MachineEvent,
74
+ type MachineEventKind,
75
+ type MachineFacts,
76
+ type MachinePlanFacts,
77
+ type MachinePrincipal,
78
+ type MachineState,
79
+ type MachinesHook,
80
+ type MachineTarget,
81
+ type MachineVerb,
82
+ type PersonFacts,
83
+ type WaitingWork,
84
+ } from "./machines/contract.js";
85
+ export type { MachinePassSummary } from "./machines/sequencer.js";
60
86
  export {
61
87
  lanAddresses,
62
88
  type MdnsResponder,
@@ -69,18 +95,6 @@ export {
69
95
  type WorkServerHooks,
70
96
  type WorkServerOptions,
71
97
  } from "./server.js";
72
- export {
73
- type MachineClass,
74
- MachineClassSchema,
75
- type MachinesConfig,
76
- MachinesConfigSchema,
77
- } from "./workers/machine-classes.js";
78
- export {
79
- type MachineProvisioner,
80
- MachineProvisioningRefusedError,
81
- type MachineRule,
82
- type ReconcileSummary,
83
- } from "./workers/machine-rules.js";
84
98
  export {
85
99
  listMachineSignIns,
86
100
  MachineHeldError,