@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
@@ -0,0 +1,1010 @@
1
+ import type { z } from "zod";
2
+ import {
3
+ DEFAULT_LOST_AFTER_MINUTES,
4
+ type DesiredMachine,
5
+ MachineCreateResultSchema,
6
+ MachineDescribeResultSchema,
7
+ MachineDestroyResultSchema,
8
+ type MachineEvent,
9
+ type MachineEventKind,
10
+ type MachineFacts,
11
+ MachinePlanSchema,
12
+ type MachinePrincipal,
13
+ MachineStartResultSchema,
14
+ type MachineState,
15
+ MachineStopResultSchema,
16
+ type MachinesHook,
17
+ type MachineTarget,
18
+ type MachineVerb,
19
+ normalizePrincipals,
20
+ type PersonFacts,
21
+ principalsChangeNeedsReset,
22
+ principalsTake,
23
+ samePrincipals,
24
+ servesNobody,
25
+ servesOneOwner,
26
+ type WaitingWork,
27
+ } from "./contract.js";
28
+
29
+ /*
30
+ * What Work does with a plan (ADR 0349). One pass reads the facts, asks the
31
+ * host's `plan` for the machines that should exist, and works out the
32
+ * difference: it records its intent before every call into host code,
33
+ * repeats each call until it is done, and never stops or destroys a
34
+ * machine that holds live work unless it is lost. Everything it knows and
35
+ * changes goes through a {@link MachineWorld}: the Work server's is
36
+ * Postgres; the contract kit's is a simulation with a clock a test moves.
37
+ */
38
+
39
+ /** Where Work stands with a machine; what it stores. */
40
+ export type MachinePhase =
41
+ | "starting"
42
+ | "running"
43
+ | "stopping"
44
+ | "stopped"
45
+ | "resuming"
46
+ | "destroying";
47
+
48
+ /**
49
+ * Minutes a resumed machine has to connect again, beyond its loss limit,
50
+ * before it is lost: a stopped machine boots before its worker calls.
51
+ */
52
+ export const RESUME_GRACE_MINUTES = 10;
53
+
54
+ /** A machine as the sequencer reads it: its facts and what Work keeps beside them. */
55
+ export interface MachineRecord {
56
+ facts: MachineFacts;
57
+ phase: MachinePhase;
58
+ phaseSince: string;
59
+ /** The key its create is asked with; null once refused, or for a machine enrolled by hand. */
60
+ idempotencyKey: string | null;
61
+ /** The plan no longer names it: it takes no new work. */
62
+ dropped: boolean;
63
+ /** Creates its platform refused in a row, and when the latest was (ISO 8601). */
64
+ refused: { count: number; at: string } | null;
65
+ /** Whom it is for once it is reset; it takes no new work until then. */
66
+ reset: { for: readonly MachinePrincipal[] | null } | null;
67
+ /** Resuming: its `start` answered done, and Work waits for its worker. */
68
+ startAsked: boolean;
69
+ /** When Work first asked to destroy it (ISO 8601). */
70
+ destroyRequestedAt: string | null;
71
+ /** The loss limit the plan gave it, if any. */
72
+ lostAfterMinutes: number | null;
73
+ /** An operator revoked its worker. */
74
+ revoked: boolean;
75
+ }
76
+
77
+ /** A desired machine with every default filled in. */
78
+ export interface PlannedMachine {
79
+ name: string;
80
+ for: readonly MachinePrincipal[] | null;
81
+ labels: Readonly<Record<string, string>>;
82
+ state: "running" | "stopped";
83
+ options: Readonly<Record<string, unknown>>;
84
+ trusted: boolean;
85
+ lostAfterMinutes: number | null;
86
+ reason: string | null;
87
+ }
88
+
89
+ /** What the sequencer reads and changes. Every change is one small step. */
90
+ export interface MachineWorld {
91
+ /** Where a new machine's worker reaches the server. */
92
+ controlPlaneUrl: string;
93
+ /** The clock every time here is read from (ISO 8601). */
94
+ now(): Promise<string>;
95
+ records(): Promise<MachineRecord[]>;
96
+ work(): Promise<WaitingWork[]>;
97
+ people(): Promise<PersonFacts[]>;
98
+ /**
99
+ * Record the intent to make a machine: its row and a new enrollment.
100
+ * False when the name is already known (another replica was first).
101
+ */
102
+ intend(args: { machine: PlannedMachine }): Promise<boolean>;
103
+ /**
104
+ * The enrollment its create is asked with, the same on every pass and
105
+ * replica until it is refused; null when it has none (refused).
106
+ */
107
+ enrollment(args: {
108
+ name: string;
109
+ }): Promise<{ code: string; idempotencyKey: string } | null>;
110
+ /** A new enrollment, and so a new idempotency key, after a refusal. */
111
+ reissue(args: { name: string }): Promise<void>;
112
+ created(args: { name: string; ref: string }): Promise<void>;
113
+ /** The platform made nothing: the code is withdrawn. */
114
+ refused(args: { name: string; reason: string }): Promise<void>;
115
+ /** Settings that never need a reset. */
116
+ configure(args: {
117
+ name: string;
118
+ labels: Readonly<Record<string, string>>;
119
+ trusted: boolean;
120
+ reason: string | null;
121
+ lostAfterMinutes: number | null;
122
+ }): Promise<void>;
123
+ /** Whom it is for from now on; also ends a reset that is no longer wanted. */
124
+ setFor(args: {
125
+ name: string;
126
+ for: readonly MachinePrincipal[] | null;
127
+ }): Promise<void>;
128
+ /** It takes no new work, and is for `for` once {@link reset} is done. */
129
+ beginReset(args: {
130
+ name: string;
131
+ for: readonly MachinePrincipal[] | null;
132
+ }): Promise<void>;
133
+ /**
134
+ * Reset it through its worker (sandboxes, volumes, members' sign-ins)
135
+ * and apply whom it is for. `busy` while it holds live workspaces,
136
+ * `offline` while it is not connected.
137
+ */
138
+ reset(args: { name: string }): Promise<"done" | "busy" | "offline">;
139
+ drop(args: { name: string }): Promise<void>;
140
+ undrop(args: { name: string }): Promise<void>;
141
+ /**
142
+ * Take it out of service for good, under its lock: only while it holds
143
+ * nothing (or its worker was revoked, or it never enrolled). True once
144
+ * it is `destroying`.
145
+ */
146
+ retire(args: { name: string }): Promise<boolean>;
147
+ /**
148
+ * It is lost: take it out of service and retire what it held, only
149
+ * while it is still unseen for `unseenForMs`. True once it is
150
+ * `destroying`; false when it called again meanwhile.
151
+ */
152
+ declareLost(args: { name: string; unseenForMs: number }): Promise<boolean>;
153
+ /**
154
+ * Take no new work and become `stopping`, under its lock: only while it
155
+ * holds nothing. False when it holds something.
156
+ */
157
+ beginStop(args: { name: string; at: string }): Promise<boolean>;
158
+ stopped(args: { name: string }): Promise<void>;
159
+ /** Become `resuming`: its worker may connect again. */
160
+ beginResume(args: { name: string; at: string }): Promise<boolean>;
161
+ /** Its `start` answered done. */
162
+ startAsked(args: { name: string }): Promise<void>;
163
+ /** Its platform confirmed it gone: Work knows it no more. */
164
+ forget(args: { name: string }): Promise<void>;
165
+ /** Why Work cannot do what the plan asks yet, or null. */
166
+ note(args: { name: string; notice: string | null }): Promise<void>;
167
+ failed(args: {
168
+ name: string;
169
+ verb: MachineVerb;
170
+ message: string;
171
+ }): Promise<void>;
172
+ succeeded(args: { name: string; verb: MachineVerb }): Promise<void>;
173
+ /** Something happened to a machine; delivery never fails a pass. */
174
+ event(args: MachineEvent): Promise<void>;
175
+ /** The plan answered (null) or failed with this error. */
176
+ planned(args: { error: string | null }): Promise<void>;
177
+ /** Which machine is being started or resumed for each piece of waiting work. */
178
+ waiting(args: {
179
+ machines: ReadonlyMap<
180
+ string,
181
+ { name: string; state: "starting" | "resuming" }
182
+ >;
183
+ }): Promise<void>;
184
+ }
185
+
186
+ /** What one pass changed. */
187
+ export interface MachinePassSummary {
188
+ /** Machines whose create answered a ref. */
189
+ created: string[];
190
+ /** Machines whose labels, principals or settings changed. */
191
+ updated: string[];
192
+ /** Machines reset before their principals changed. */
193
+ reset: string[];
194
+ /** Machines the plan dropped: they take no new work. */
195
+ released: string[];
196
+ /** Machines called lost: their work is retired. */
197
+ lost: string[];
198
+ stopped: string[];
199
+ /** Machines whose start answered done. */
200
+ resumed: string[];
201
+ /** Machines whose destruction is under way. */
202
+ destroying: string[];
203
+ destroyed: string[];
204
+ /** What went wrong, by machine and verb. */
205
+ failed: Array<{ name: string; verb?: MachineVerb; error: string }>;
206
+ /** The plan threw, timed out or answered something invalid: nothing changed. */
207
+ planError?: string;
208
+ /** Another replica was sequencing; its pass covers this one. */
209
+ busy?: true;
210
+ }
211
+
212
+ export function emptySummary(): MachinePassSummary {
213
+ return {
214
+ created: [],
215
+ updated: [],
216
+ reset: [],
217
+ released: [],
218
+ lost: [],
219
+ stopped: [],
220
+ resumed: [],
221
+ destroying: [],
222
+ destroyed: [],
223
+ failed: [],
224
+ };
225
+ }
226
+
227
+ /** The claim moved to another replica: this pass stops before changing more. */
228
+ export class MachinePassFencedError extends Error {
229
+ constructor() {
230
+ super("The machine sequencer's claim moved to another replica");
231
+ this.name = "MachinePassFencedError";
232
+ }
233
+ }
234
+
235
+ /** A machine's state, from what Work stores and its worker's lease. */
236
+ export function machineStateOf(args: {
237
+ phase: MachinePhase;
238
+ dropped: boolean;
239
+ disabled: boolean;
240
+ /** Its worker's lease is live. */
241
+ live: boolean;
242
+ /** Since its worker last called, in milliseconds. */
243
+ unseenForMs: number;
244
+ lostAfterMs: number;
245
+ /** Resuming: since its `start` answered done, in milliseconds; null before. */
246
+ startAskedForMs: number | null;
247
+ }): MachineState {
248
+ if (args.phase === "destroying") return "destroying";
249
+ if (args.phase === "stopping") return "stopping";
250
+ if (args.phase === "stopped") return "stopped";
251
+ if (args.phase === "starting") return "starting";
252
+ if (args.phase === "resuming")
253
+ return args.startAskedForMs !== null &&
254
+ args.startAskedForMs >= args.lostAfterMs + RESUME_GRACE_MINUTES * 60_000
255
+ ? "lost"
256
+ : "resuming";
257
+ if (args.disabled) return "disabled";
258
+ if (args.live) return args.dropped ? "draining" : "serving";
259
+ return args.unseenForMs >= args.lostAfterMs ? "lost" : "unreachable";
260
+ }
261
+
262
+ /** Milliseconds unseen that make a machine lost. */
263
+ export function lostAfterMsOf(args: {
264
+ lostAfterMinutes: number | null;
265
+ defaultMinutes?: number;
266
+ }): number {
267
+ return (
268
+ (args.lostAfterMinutes ??
269
+ args.defaultMinutes ??
270
+ DEFAULT_LOST_AFTER_MINUTES) * 60_000
271
+ );
272
+ }
273
+
274
+ /** Minutes before a refused create is asked again: 1, 2, 4 ... 30. */
275
+ export function refusalBackoffMs(count: number): number {
276
+ return Math.min(30, 2 ** Math.max(0, count - 1)) * 60_000;
277
+ }
278
+
279
+ /** A desired machine with its defaults. */
280
+ export function plannedMachine(desired: DesiredMachine): PlannedMachine {
281
+ return {
282
+ name: desired.name,
283
+ for: desired.for === undefined ? null : normalizePrincipals(desired.for),
284
+ labels: desired.labels ?? {},
285
+ state: desired.state ?? "running",
286
+ options: desired.options ?? {},
287
+ trusted: desired.trusted ?? false,
288
+ lostAfterMinutes: desired.lostAfterMinutes ?? null,
289
+ reason: desired.reason ?? null,
290
+ };
291
+ }
292
+
293
+ interface PassContext {
294
+ hook: MachinesHook;
295
+ world: MachineWorld;
296
+ fence: () => Promise<void>;
297
+ summary: MachinePassSummary;
298
+ verbTimeoutMs: number;
299
+ now: string;
300
+ defaultLostAfterMinutes: number | undefined;
301
+ }
302
+
303
+ /**
304
+ * One pass. `fence` throws {@link MachinePassFencedError} once another
305
+ * replica holds the claim; the pass then ends with what it did so far.
306
+ */
307
+ export async function runMachinePass(args: {
308
+ hook: MachinesHook;
309
+ world: MachineWorld;
310
+ fence?: () => Promise<void>;
311
+ /** How long `plan` may take (default 30 seconds). */
312
+ planTimeoutMs?: number;
313
+ /** How long one verb may take (default 2 minutes). */
314
+ verbTimeoutMs?: number;
315
+ /** The loss limit of a machine whose plan gives none. */
316
+ defaultLostAfterMinutes?: number;
317
+ log?: (line: string) => void;
318
+ }): Promise<MachinePassSummary> {
319
+ const { hook, world } = args;
320
+ const summary = emptySummary();
321
+ const [records, work, people, now] = await Promise.all([
322
+ world.records(),
323
+ world.work(),
324
+ world.people(),
325
+ world.now(),
326
+ ]);
327
+ const planned = await readPlan({
328
+ hook,
329
+ facts: { now, work, people, machines: records.map((entry) => entry.facts) },
330
+ timeoutMs: args.planTimeoutMs ?? 30_000,
331
+ });
332
+ if ("error" in planned) {
333
+ // Nothing changes: the machines Work has keep running as they are.
334
+ summary.planError = planned.error;
335
+ await world.planned({ error: planned.error });
336
+ args.log?.(
337
+ `Machines: the plan failed and nothing changed: ${planned.error}`,
338
+ );
339
+ return summary;
340
+ }
341
+ const context: PassContext = {
342
+ hook,
343
+ world,
344
+ fence: args.fence ?? (async () => {}),
345
+ summary,
346
+ verbTimeoutMs: args.verbTimeoutMs ?? 120_000,
347
+ now,
348
+ defaultLostAfterMinutes: args.defaultLostAfterMinutes,
349
+ };
350
+ const desired = new Map(
351
+ planned.machines.map((machine) => [machine.name, machine]),
352
+ );
353
+ /** Names free to make: never known, or gone in this pass. */
354
+ const free = new Set(desired.keys());
355
+ for (const record of records) {
356
+ const name = record.facts.name;
357
+ const wanted = desired.get(name);
358
+ const outcome = await guarded(context, name, () =>
359
+ record.facts.managed
360
+ ? stepManaged(context, record, wanted)
361
+ : stepEnrolledByHand(context, record, wanted),
362
+ );
363
+ if (outcome !== "gone") free.delete(name);
364
+ }
365
+ for (const name of free) {
366
+ const machine = desired.get(name);
367
+ if (!machine) continue;
368
+ await guarded(context, name, async () => {
369
+ await context.fence();
370
+ // Intent first: from here every pass and replica asks with one key.
371
+ if (!(await world.intend({ machine }))) return "kept";
372
+ await createStep(context, {
373
+ name,
374
+ options: machine.options,
375
+ labels: machine.labels,
376
+ for: machine.for,
377
+ reason: machine.reason,
378
+ refused: null,
379
+ failedBefore: false,
380
+ });
381
+ return "kept";
382
+ });
383
+ }
384
+ await annotateWaits({ world, work, fence: context.fence });
385
+ await world.planned({ error: null });
386
+ return summary;
387
+ }
388
+
389
+ /** Ask the plan, within its time, and check what it answered. */
390
+ async function readPlan(args: {
391
+ hook: MachinesHook;
392
+ facts: Parameters<MachinesHook["plan"]>[0];
393
+ timeoutMs: number;
394
+ }): Promise<{ machines: PlannedMachine[] } | { error: string }> {
395
+ let answered: unknown;
396
+ try {
397
+ answered = await withTimeout({
398
+ work: args.hook.plan(args.facts),
399
+ timeoutMs: args.timeoutMs,
400
+ message: `plan did not answer within ${Math.round(args.timeoutMs / 1000)} seconds`,
401
+ });
402
+ } catch (error) {
403
+ return { error: `plan threw: ${messageOf(error)}` };
404
+ }
405
+ const parsed = MachinePlanSchema.safeParse(answered);
406
+ if (!parsed.success) {
407
+ const issue = parsed.error.issues[0];
408
+ return {
409
+ error: `plan returned something invalid${
410
+ issue ? ` (${issue.path.join(".") || "result"}: ${issue.message})` : ""
411
+ }; return an array of { name, for?, labels?, state?, options?, trusted?, lostAfterMinutes?, reason? }`,
412
+ };
413
+ }
414
+ return { machines: parsed.data.map((machine) => plannedMachine(machine)) };
415
+ }
416
+
417
+ /** Run one machine's step; its failure is recorded and the pass goes on. */
418
+ async function guarded(
419
+ context: PassContext,
420
+ name: string,
421
+ run: () => Promise<"gone" | "kept">,
422
+ ): Promise<"gone" | "kept"> {
423
+ try {
424
+ return await run();
425
+ } catch (error) {
426
+ if (error instanceof MachinePassFencedError) throw error;
427
+ context.summary.failed.push({ name, error: messageOf(error) });
428
+ return "kept";
429
+ }
430
+ }
431
+
432
+ /** A machine this hook made: follow the plan, within what is safe. */
433
+ async function stepManaged(
434
+ context: PassContext,
435
+ record: MachineRecord,
436
+ wanted: PlannedMachine | undefined,
437
+ ): Promise<"gone" | "kept"> {
438
+ const { world, summary, hook } = context;
439
+ const { name } = record.facts;
440
+ const target = targetOf(record);
441
+ let phase = record.phase;
442
+ let phaseSince = record.phaseSince;
443
+ let notice: string | null = null;
444
+ const lost = async (unseenForMs: number): Promise<boolean> => {
445
+ await context.fence();
446
+ if (!(await world.declareLost({ name, unseenForMs }))) return false;
447
+ summary.lost.push(name);
448
+ await emit(context, "machine.lost", record);
449
+ return true;
450
+ };
451
+
452
+ if (phase !== "destroying") {
453
+ if (record.facts.state === "lost") {
454
+ // Its work is retired, so its chats continue from their last save.
455
+ // It called again meanwhile: it is kept as it is.
456
+ if (
457
+ !(await lost(
458
+ lostAfterMsOf({
459
+ lostAfterMinutes: record.lostAfterMinutes,
460
+ defaultMinutes: context.defaultLostAfterMinutes,
461
+ }),
462
+ ))
463
+ )
464
+ return "kept";
465
+ phase = "destroying";
466
+ } else if (record.facts.state === "unreachable" && hook.describe) {
467
+ const describe = hook.describe;
468
+ const described = await verb(context, {
469
+ record,
470
+ verb: "describe",
471
+ schema: MachineDescribeResultSchema,
472
+ expected: '{ state: "running" | "stopped" | "gone" | "unknown" }',
473
+ call: () => describe(target),
474
+ });
475
+ // The platform says it no longer exists: no need to wait out the limit.
476
+ if (described?.state === "gone" && (await lost(0))) phase = "destroying";
477
+ }
478
+ }
479
+ if (phase !== "destroying" && !wanted) {
480
+ if (!record.dropped) {
481
+ await context.fence();
482
+ await world.drop({ name });
483
+ summary.released.push(name);
484
+ await emit(context, "machine.released", record);
485
+ }
486
+ await context.fence();
487
+ if (await world.retire({ name })) phase = "destroying";
488
+ else
489
+ notice = `The plan no longer names it. It takes no new work and is destroyed once its ${workspaces(record)} given back.`;
490
+ }
491
+ if (phase === "destroying") return destroyStep(context, record);
492
+ if (!wanted) {
493
+ await setNotice(context, record, notice);
494
+ return "kept";
495
+ }
496
+
497
+ if (record.dropped) {
498
+ await context.fence();
499
+ await world.undrop({ name });
500
+ }
501
+ // Changing launch parameters while its create is uncertain can turn
502
+ // the same idempotency key into a different cloud request.
503
+ const settings =
504
+ record.facts.ref === null
505
+ ? { ...wanted, labels: record.facts.labels }
506
+ : wanted;
507
+ notice = (await applySettings(context, record, settings)) ?? notice;
508
+ if (
509
+ record.facts.ref === null &&
510
+ (phase === "starting" || phase === "running")
511
+ )
512
+ notice =
513
+ (await createStep(context, {
514
+ name,
515
+ options: record.facts.options,
516
+ labels: record.facts.labels,
517
+ for: record.facts.for,
518
+ reason: record.facts.reason,
519
+ refused: record.refused,
520
+ failedBefore: record.facts.lastError?.verb === "create",
521
+ })) ?? notice;
522
+
523
+ if (phase === "running" && wanted.state === "stopped") {
524
+ if (!hook.stop)
525
+ notice =
526
+ "The plan wants it stopped, but the machines hook has no stop: it keeps running.";
527
+ else if (record.facts.state === "serving") {
528
+ await context.fence();
529
+ if (await world.beginStop({ name, at: context.now })) {
530
+ phase = "stopping";
531
+ phaseSince = context.now;
532
+ } else
533
+ notice = `The plan wants it stopped. It stops once its ${workspaces(record)} given back.`;
534
+ }
535
+ }
536
+ if (phase === "stopping") {
537
+ const stop = hook.stop;
538
+ if (!stop)
539
+ notice =
540
+ "It is stopping, but the machines hook has no stop any more: add it back.";
541
+ else {
542
+ const answer = await verb(context, {
543
+ record,
544
+ verb: "stop",
545
+ schema: MachineStopResultSchema,
546
+ expected: "{ done: boolean }",
547
+ call: () => stop({ ...target, requestedAt: phaseSince }),
548
+ });
549
+ if (answer?.done) {
550
+ await context.fence();
551
+ await world.stopped({ name });
552
+ summary.stopped.push(name);
553
+ await emit(context, "machine.stopped", record);
554
+ phase = "stopped";
555
+ }
556
+ }
557
+ }
558
+ let startAsked = record.startAsked;
559
+ if (phase === "stopped" && wanted.state === "running") {
560
+ if (!hook.start)
561
+ notice =
562
+ "The plan wants it running, but the machines hook has no start: it stays stopped.";
563
+ else {
564
+ await context.fence();
565
+ if (await world.beginResume({ name, at: context.now })) {
566
+ phase = "resuming";
567
+ phaseSince = context.now;
568
+ startAsked = false;
569
+ }
570
+ }
571
+ }
572
+ if (phase === "resuming" && !startAsked) {
573
+ const start = hook.start;
574
+ if (!start)
575
+ notice =
576
+ "It is resuming, but the machines hook has no start any more: add it back.";
577
+ else {
578
+ const answer = await verb(context, {
579
+ record,
580
+ verb: "start",
581
+ schema: MachineStartResultSchema,
582
+ expected: "{ done: boolean } or { gone: true }",
583
+ call: () => start({ ...target, requestedAt: phaseSince }),
584
+ });
585
+ if (answer && "gone" in answer) {
586
+ // Nothing is left to resume: it is lost, and made again.
587
+ if (await lost(0)) return destroyStep(context, record);
588
+ } else if (answer?.done) {
589
+ await context.fence();
590
+ await world.startAsked({ name });
591
+ summary.resumed.push(name);
592
+ }
593
+ }
594
+ }
595
+ await setNotice(context, record, notice ?? isolationNotice(record, wanted));
596
+ return "kept";
597
+ }
598
+
599
+ /**
600
+ * A machine an operator enrolled by hand: the plan may say whom it is for,
601
+ * its labels and why, never create, stop or destroy it.
602
+ */
603
+ async function stepEnrolledByHand(
604
+ context: PassContext,
605
+ record: MachineRecord,
606
+ wanted: PlannedMachine | undefined,
607
+ ): Promise<"kept"> {
608
+ if (!wanted) return "kept";
609
+ let notice = await applySettings(context, record, wanted);
610
+ if (wanted.state === "stopped")
611
+ notice =
612
+ "An operator enrolled this machine by hand: the plan may change whom it is for, its labels and its reason, but Work never stops it.";
613
+ await setNotice(context, record, notice ?? isolationNotice(record, wanted));
614
+ return "kept";
615
+ }
616
+
617
+ /** Labels, trust, reason, loss limit and principals; resets where needed. */
618
+ async function applySettings(
619
+ context: PassContext,
620
+ record: MachineRecord,
621
+ wanted: PlannedMachine,
622
+ ): Promise<string | null> {
623
+ const { world, summary } = context;
624
+ const { facts } = record;
625
+ const { name } = facts;
626
+ let changed = false;
627
+ if (
628
+ canonical(facts.labels) !== canonical(wanted.labels) ||
629
+ facts.trusted !== wanted.trusted ||
630
+ facts.reason !== wanted.reason ||
631
+ record.lostAfterMinutes !== wanted.lostAfterMinutes
632
+ ) {
633
+ await context.fence();
634
+ await world.configure({
635
+ name,
636
+ labels: wanted.labels,
637
+ trusted: wanted.trusted,
638
+ reason: wanted.reason,
639
+ lostAfterMinutes: wanted.lostAfterMinutes,
640
+ });
641
+ changed = true;
642
+ }
643
+ let resetting = record.reset !== null;
644
+ const target = record.reset ? record.reset.for : facts.for;
645
+ if (!samePrincipals(target, wanted.for)) {
646
+ await context.fence();
647
+ // Nothing of anyone's is on a machine that never connected.
648
+ const needsReset =
649
+ record.phase !== "starting" &&
650
+ principalsChangeNeedsReset({ from: facts.for, to: wanted.for });
651
+ if (needsReset || resetting) {
652
+ await world.beginReset({ name, for: wanted.for });
653
+ resetting = true;
654
+ } else {
655
+ await world.setFor({ name, for: wanted.for });
656
+ resetting = false;
657
+ }
658
+ changed = true;
659
+ }
660
+ if (changed) summary.updated.push(name);
661
+ if (!resetting) return null;
662
+ await context.fence();
663
+ const outcome = await world.reset({ name });
664
+ if (outcome === "done") {
665
+ summary.reset.push(name);
666
+ return null;
667
+ }
668
+ return outcome === "busy"
669
+ ? `Whom it is for changes once it is reset. It takes no new work, and is reset once its ${workspaces(record)} given back.`
670
+ : "Whom it is for changes once it is reset. It takes no new work, and is reset once it is connected.";
671
+ }
672
+
673
+ /** Ask the hook to create a machine until it answers a ref. */
674
+ async function createStep(
675
+ context: PassContext,
676
+ machine: {
677
+ name: string;
678
+ options: Readonly<Record<string, unknown>>;
679
+ labels: Readonly<Record<string, string>>;
680
+ for: readonly MachinePrincipal[] | null;
681
+ reason: string | null;
682
+ refused: MachineRecord["refused"];
683
+ failedBefore: boolean;
684
+ },
685
+ ): Promise<string | null> {
686
+ const { world, hook, summary } = context;
687
+ const { name } = machine;
688
+ let enrollment = await world.enrollment({ name });
689
+ if (!enrollment) {
690
+ if (machine.refused) {
691
+ const waitMs =
692
+ refusalBackoffMs(machine.refused.count) -
693
+ (Date.parse(context.now) - Date.parse(machine.refused.at));
694
+ if (waitMs > 0)
695
+ return `Its platform refused to create it ${machine.refused.count} time(s) in a row. Work asks again in ${Math.ceil(waitMs / 60_000)} minute(s).`;
696
+ }
697
+ await context.fence();
698
+ await world.reissue({ name });
699
+ enrollment = await world.enrollment({ name });
700
+ if (!enrollment) return null;
701
+ }
702
+ const request = {
703
+ name,
704
+ options: machine.options,
705
+ labels: machine.labels,
706
+ enrollment: {
707
+ controlPlaneUrl: world.controlPlaneUrl,
708
+ code: enrollment.code,
709
+ idempotencyKey: enrollment.idempotencyKey,
710
+ },
711
+ };
712
+ const answer = await callHook(context, {
713
+ name,
714
+ verb: "create",
715
+ secret: enrollment.code,
716
+ failedBefore: machine.failedBefore,
717
+ schema: MachineCreateResultSchema,
718
+ expected: "{ ref } | { pending: true } | { refused: reason }",
719
+ call: () => hook.create(request),
720
+ });
721
+ if (!answer || "pending" in answer) return null;
722
+ await context.fence();
723
+ if ("refused" in answer) {
724
+ const reason = answer.refused.replaceAll(
725
+ enrollment.code,
726
+ "[enrollment code]",
727
+ );
728
+ await world.refused({ name, reason });
729
+ summary.failed.push({
730
+ name,
731
+ verb: "create",
732
+ error: `Its platform refused: ${reason}`,
733
+ });
734
+ return null;
735
+ }
736
+ await world.created({ name, ref: answer.ref });
737
+ summary.created.push(name);
738
+ await context.world.event({
739
+ kind: "machine.created",
740
+ at: context.now,
741
+ machine: {
742
+ name,
743
+ ref: answer.ref,
744
+ managed: true,
745
+ labels: machine.labels,
746
+ for: machine.for,
747
+ options: machine.options,
748
+ reason: machine.reason,
749
+ },
750
+ });
751
+ return null;
752
+ }
753
+
754
+ /** Ask the hook to destroy a machine until it is gone, then forget it. */
755
+ async function destroyStep(
756
+ context: PassContext,
757
+ record: MachineRecord,
758
+ ): Promise<"gone" | "kept"> {
759
+ const { world, summary, hook } = context;
760
+ const { name } = record.facts;
761
+ const answer = await verb(context, {
762
+ record,
763
+ verb: "destroy",
764
+ schema: MachineDestroyResultSchema,
765
+ expected: "{ done: boolean }",
766
+ call: () =>
767
+ hook.destroy({
768
+ ...targetOf(record),
769
+ requestedAt: record.destroyRequestedAt ?? context.now,
770
+ }),
771
+ });
772
+ if (!answer?.done) {
773
+ summary.destroying.push(name);
774
+ return "kept";
775
+ }
776
+ await context.fence();
777
+ await world.forget({ name });
778
+ summary.destroyed.push(name);
779
+ await emit(context, "machine.destroyed", record);
780
+ return "gone";
781
+ }
782
+
783
+ /** Call a verb for a known machine. */
784
+ function verb<T>(
785
+ context: PassContext,
786
+ args: {
787
+ record: MachineRecord;
788
+ verb: MachineVerb;
789
+ schema: z.ZodType<T>;
790
+ expected: string;
791
+ call: () => Promise<unknown>;
792
+ },
793
+ ): Promise<T | undefined> {
794
+ return callHook(context, {
795
+ name: args.record.facts.name,
796
+ verb: args.verb,
797
+ failedBefore: args.record.facts.lastError?.verb === args.verb,
798
+ schema: args.schema,
799
+ expected: args.expected,
800
+ call: args.call,
801
+ });
802
+ }
803
+
804
+ /**
805
+ * One call into host code: within its time, its answer checked. A failure
806
+ * is recorded for the machine and the call is made again on a later pass.
807
+ */
808
+ async function callHook<T>(
809
+ context: PassContext,
810
+ args: {
811
+ name: string;
812
+ verb: MachineVerb;
813
+ failedBefore: boolean;
814
+ secret?: string;
815
+ schema: z.ZodType<T>;
816
+ expected: string;
817
+ call: () => Promise<unknown>;
818
+ },
819
+ ): Promise<T | undefined> {
820
+ await context.fence();
821
+ let message: string;
822
+ try {
823
+ const raw = await withTimeout({
824
+ work: args.call(),
825
+ timeoutMs: context.verbTimeoutMs,
826
+ message: `${args.verb} did not answer within ${Math.round(context.verbTimeoutMs / 1000)} seconds`,
827
+ });
828
+ const parsed = args.schema.safeParse(raw);
829
+ if (parsed.success) {
830
+ if (args.failedBefore) {
831
+ await context.fence();
832
+ await context.world.succeeded({ name: args.name, verb: args.verb });
833
+ }
834
+ return parsed.data;
835
+ }
836
+ message = `${args.verb} returned ${preview(raw)}; return ${args.expected}`;
837
+ } catch (error) {
838
+ message = `${args.verb} threw: ${messageOf(error)}`;
839
+ }
840
+ if (args.secret)
841
+ message = message.replaceAll(args.secret, "[enrollment code]");
842
+ await context.fence();
843
+ context.summary.failed.push({
844
+ name: args.name,
845
+ verb: args.verb,
846
+ error: message,
847
+ });
848
+ await context.world.failed({ name: args.name, verb: args.verb, message });
849
+ return undefined;
850
+ }
851
+
852
+ /** Say which machine is being started or resumed for each piece of waiting work. */
853
+ async function annotateWaits(args: {
854
+ world: MachineWorld;
855
+ work: readonly WaitingWork[];
856
+ fence: () => Promise<void>;
857
+ }): Promise<void> {
858
+ const coming = (await args.world.records()).filter(
859
+ (record) =>
860
+ !record.dropped &&
861
+ (record.facts.state === "starting" || record.facts.state === "resuming"),
862
+ );
863
+ const machines = new Map<
864
+ string,
865
+ { name: string; state: "starting" | "resuming" }
866
+ >();
867
+ for (const work of args.work) {
868
+ const machine = coming.find((record) => machineTakes(record.facts, work));
869
+ if (machine)
870
+ machines.set(work.id, {
871
+ name: machine.facts.name,
872
+ state: machine.facts.state === "resuming" ? "resuming" : "starting",
873
+ });
874
+ }
875
+ await args.fence();
876
+ await args.world.waiting({ machines });
877
+ }
878
+
879
+ /**
880
+ * Whether a machine would take a piece of waiting work once it serves: its
881
+ * labels (and `plane: worker`) satisfy the work's pool, and it is for the
882
+ * work's owner.
883
+ */
884
+ export function machineTakes(
885
+ machine: Pick<MachineFacts, "labels" | "for">,
886
+ work: Pick<WaitingWork, "pool" | "project" | "user" | "key">,
887
+ ): boolean {
888
+ const labels: Record<string, string> = { ...machine.labels, plane: "worker" };
889
+ return (
890
+ Object.entries(work.pool).every(([key, value]) => labels[key] === value) &&
891
+ principalsTake({ for: machine.for, work })
892
+ );
893
+ }
894
+
895
+ function targetOf(record: MachineRecord): MachineTarget {
896
+ return {
897
+ name: record.facts.name,
898
+ ref: record.facts.ref,
899
+ idempotencyKey: record.idempotencyKey,
900
+ options: record.facts.options,
901
+ labels: record.facts.labels,
902
+ };
903
+ }
904
+
905
+ async function emit(
906
+ context: PassContext,
907
+ kind: MachineEventKind,
908
+ record: MachineRecord,
909
+ ): Promise<void> {
910
+ const { facts } = record;
911
+ await context.world.event({
912
+ kind,
913
+ at: context.now,
914
+ machine: {
915
+ name: facts.name,
916
+ ref: facts.ref,
917
+ managed: facts.managed,
918
+ labels: facts.labels,
919
+ for: facts.for,
920
+ options: facts.options,
921
+ reason: facts.reason,
922
+ },
923
+ });
924
+ }
925
+
926
+ async function setNotice(
927
+ context: PassContext,
928
+ record: MachineRecord,
929
+ notice: string | null,
930
+ ): Promise<void> {
931
+ if (notice === record.facts.notice) return;
932
+ await context.fence();
933
+ await context.world.note({ name: record.facts.name, notice });
934
+ }
935
+
936
+ /** A machine that would be refused work for how it isolates agents. */
937
+ function isolationNotice(
938
+ record: MachineRecord,
939
+ wanted: PlannedMachine,
940
+ ): string | null {
941
+ if (
942
+ record.facts.isolation !== "process" ||
943
+ wanted.trusted ||
944
+ servesOneOwner(wanted.for) ||
945
+ servesNobody(wanted.for)
946
+ )
947
+ return optionsNotice(record, wanted);
948
+ return "It runs agents as plain processes and serves more than one principal, so it takes no work. Give it sandboxes that isolate agents (microsandbox or gVisor), or mark it trusted if everyone it serves trusts each other.";
949
+ }
950
+
951
+ /** Options apply when a machine is created; say so when the plan changed them. */
952
+ function optionsNotice(
953
+ record: MachineRecord,
954
+ wanted: PlannedMachine,
955
+ ): string | null {
956
+ if (
957
+ !record.facts.managed ||
958
+ canonical(record.facts.options) === canonical(wanted.options)
959
+ )
960
+ return null;
961
+ return "The plan's options for this machine changed. Options apply only when a machine is created: give the new shape a new name.";
962
+ }
963
+
964
+ function workspaces(record: MachineRecord): string {
965
+ const count = record.facts.holding.workspaces;
966
+ return count === 1
967
+ ? "live workspace is"
968
+ : `${count > 0 ? `${count} ` : ""}live workspaces are`;
969
+ }
970
+
971
+ async function withTimeout<T>(args: {
972
+ work: Promise<T>;
973
+ timeoutMs: number;
974
+ message: string;
975
+ }): Promise<T> {
976
+ let timer: ReturnType<typeof setTimeout> | undefined;
977
+ const timeout = new Promise<never>((_resolve, reject) => {
978
+ timer = setTimeout(() => reject(new Error(args.message)), args.timeoutMs);
979
+ });
980
+ try {
981
+ return await Promise.race([args.work, timeout]);
982
+ } finally {
983
+ clearTimeout(timer);
984
+ }
985
+ }
986
+
987
+ function preview(value: unknown): string {
988
+ try {
989
+ return (JSON.stringify(value) ?? String(value)).slice(0, 200);
990
+ } catch {
991
+ return String(value);
992
+ }
993
+ }
994
+
995
+ function messageOf(error: unknown): string {
996
+ return error instanceof Error ? error.message : String(error);
997
+ }
998
+
999
+ /** JSON with sorted keys: stored jsonb reorders keys, so compare this way. */
1000
+ export function canonical(value: unknown): string {
1001
+ return JSON.stringify(value, (_key, entry: unknown) =>
1002
+ entry && typeof entry === "object" && !Array.isArray(entry)
1003
+ ? Object.fromEntries(
1004
+ Object.entries(entry).sort(([left], [right]) =>
1005
+ left.localeCompare(right),
1006
+ ),
1007
+ )
1008
+ : entry,
1009
+ );
1010
+ }