@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,522 @@
1
+ import { z } from "zod";
2
+
3
+ /*
4
+ * The machines hook (ADR 0349): the one object a host passes as
5
+ * `hooks.machines`. The host's code decides which machines should exist
6
+ * (`plan`) and makes the calls that touch its cloud (`create`, `destroy`,
7
+ * `stop`, `start`, `describe`). Work sequences those calls (it records its
8
+ * intent before each, repeats it until done, and never makes one machine
9
+ * twice across replicas), enforces safety (nothing holding live work is
10
+ * stopped or destroyed unless it is lost) and owns liveness, enrollment and
11
+ * capacity. Everything here is plain data, so a plan can be tested without
12
+ * a server.
13
+ */
14
+
15
+ /**
16
+ * Who may place work on a machine: one user (their account id), one
17
+ * project's own work (project chats and automations), or one chat of a
18
+ * project by its chat key.
19
+ */
20
+ export type MachinePrincipal =
21
+ | { user: string }
22
+ | { project: string }
23
+ | { project: string; key: string };
24
+
25
+ export const MachinePrincipalSchema: z.ZodType<
26
+ MachinePrincipal,
27
+ MachinePrincipal
28
+ > = z.union([
29
+ z.strictObject({ user: z.string().min(1).max(255) }),
30
+ z.strictObject({
31
+ project: z.uuid(),
32
+ key: z.string().min(1).max(255),
33
+ }),
34
+ z.strictObject({ project: z.uuid() }),
35
+ ]);
36
+
37
+ /** Labels the Work server sets on every node itself (ADR 0167). */
38
+ export const RESERVED_LABELS = ["node", "plane"] as const;
39
+
40
+ export const MachineLabelsSchema = z
41
+ .record(
42
+ z
43
+ .string()
44
+ .regex(
45
+ /^[a-z0-9][a-z0-9._-]{0,62}$/,
46
+ "Label names are lowercase letters, digits, dots, dashes",
47
+ ),
48
+ z.string().min(1).max(128),
49
+ )
50
+ .refine(
51
+ (labels) => RESERVED_LABELS.every((key) => !(key in labels)),
52
+ `The server sets ${RESERVED_LABELS.join(" and ")} itself`,
53
+ );
54
+
55
+ /** A machine's name: it becomes a worker name, a host name and a cloud tag. */
56
+ export const MachineNameSchema = z
57
+ .string()
58
+ .regex(
59
+ /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/,
60
+ "Use lowercase letters, digits, and dashes between them, at most 63 characters",
61
+ );
62
+
63
+ /** Minutes a machine that was serving may go unseen before it is lost. */
64
+ export const DEFAULT_LOST_AFTER_MINUTES = 5;
65
+
66
+ /** One machine the host wants to exist. */
67
+ export interface DesiredMachine {
68
+ /** Stable name chosen by the host; Work matches machines by it. */
69
+ name: string;
70
+ /**
71
+ * Who may place work here: users, projects, chat keys. Omitted: anyone
72
+ * whose role and Environment allow it. An empty list: nobody (a spare).
73
+ */
74
+ for?: readonly MachinePrincipal[];
75
+ /** Labels an Environment's `pool` selects on. */
76
+ labels?: Readonly<Record<string, string>>;
77
+ /** Default "running". "stopped" keeps the disk. */
78
+ state?: "running" | "stopped";
79
+ /**
80
+ * Opaque to Work; handed to the hook's verbs. Not applied to an existing
81
+ * machine: a new shape is a new name.
82
+ */
83
+ options?: Readonly<Record<string, unknown>>;
84
+ /** The people it serves trust each other, so process isolation is enough. */
85
+ trusted?: boolean;
86
+ /** Minutes unreachable before Work calls it lost; the server's default is 5. */
87
+ lostAfterMinutes?: number;
88
+ /** Shown beside the machine, so a person can see why it exists or was stopped. */
89
+ reason?: string;
90
+ }
91
+
92
+ export const DesiredMachineSchema = z.strictObject({
93
+ name: MachineNameSchema,
94
+ for: z.array(MachinePrincipalSchema).max(500).optional(),
95
+ labels: MachineLabelsSchema.optional(),
96
+ state: z.enum(["running", "stopped"]).optional(),
97
+ options: z.record(z.string(), z.json()).optional(),
98
+ trusted: z.boolean().optional(),
99
+ lostAfterMinutes: z
100
+ .number()
101
+ .int()
102
+ .min(2)
103
+ .max(24 * 60)
104
+ .optional(),
105
+ reason: z.string().max(500).optional(),
106
+ });
107
+
108
+ /** What a plan may return: at most this many machines, each name once. */
109
+ export const MAX_PLANNED_MACHINES = 1_000;
110
+
111
+ export const MachinePlanSchema = z
112
+ .array(DesiredMachineSchema)
113
+ .max(MAX_PLANNED_MACHINES)
114
+ .superRefine((machines, context) => {
115
+ const seen = new Set<string>();
116
+ for (const [index, machine] of machines.entries()) {
117
+ if (seen.has(machine.name))
118
+ context.addIssue({
119
+ code: "custom",
120
+ message: `The plan names '${machine.name}' twice; each machine has one entry`,
121
+ path: [index, "name"],
122
+ });
123
+ seen.add(machine.name);
124
+ }
125
+ });
126
+
127
+ /**
128
+ * Where a machine stands:
129
+ *
130
+ * - `starting`: Work is making it (its create may not have answered yet),
131
+ * or it has not connected for the first time.
132
+ * - `serving`: connected and taking work.
133
+ * - `draining`: the plan no longer names it; it takes no new work and is
134
+ * destroyed once it holds none.
135
+ * - `stopping`, `stopped`, `resuming`: its disk is kept; it offers no
136
+ * capacity until it serves again.
137
+ * - `unreachable`: it was serving and has not called since its lease lapsed.
138
+ * - `lost`: unreachable for its limit; its work is retired.
139
+ * - `disabled`: an operator disabled it; its work waits and it is never lost.
140
+ * - `destroying`: Work is asking the hook to destroy it.
141
+ */
142
+ export type MachineState =
143
+ | "starting"
144
+ | "serving"
145
+ | "draining"
146
+ | "stopping"
147
+ | "stopped"
148
+ | "resuming"
149
+ | "unreachable"
150
+ | "lost"
151
+ | "disabled"
152
+ | "destroying";
153
+
154
+ /** One machine Work knows, as the plan reads it. */
155
+ export interface MachineFacts {
156
+ name: string;
157
+ /** The platform's id from `create`; null until it answered, or for a machine enrolled by hand. */
158
+ ref: string | null;
159
+ /** Made through this hook. False: an operator enrolled it by hand, and Work never creates, stops or destroys it. */
160
+ managed: boolean;
161
+ state: MachineState;
162
+ /** Since when it is in `state` (ISO 8601). */
163
+ since: string;
164
+ labels: Readonly<Record<string, string>>;
165
+ /** Who may place work here; null for anyone. */
166
+ for: readonly MachinePrincipal[] | null;
167
+ trusted: boolean;
168
+ /** The options it was created with. */
169
+ options: Readonly<Record<string, unknown>>;
170
+ reason: string | null;
171
+ /** Live workspaces on it, and whose they are. */
172
+ holding: { workspaces: number; for: readonly MachinePrincipal[] };
173
+ /** Since when it has held no workspace while serving; null while it holds one or is not serving. */
174
+ idleSince: string | null;
175
+ /** When its worker last called; null before its first call. */
176
+ lastSeenAt: string | null;
177
+ /** What it offers, from its worker's own report; null before it first connected. */
178
+ capacity: {
179
+ workspaces: number;
180
+ cpuMillis?: number;
181
+ memoryMb?: number;
182
+ } | null;
183
+ /** What its workspaces reserve now. */
184
+ usage: {
185
+ workspaces: number;
186
+ cpuMillis: number;
187
+ memoryMb: number;
188
+ storageMb: number;
189
+ } | null;
190
+ /** Its latest disk report; `low` once it is under its floor and takes no new work. */
191
+ disk: {
192
+ totalBytes: number;
193
+ freeBytes: number;
194
+ floorBytes: number;
195
+ low: boolean;
196
+ } | null;
197
+ /** How it isolates agents; null before it first connected. */
198
+ isolation: "process" | "sandbox" | null;
199
+ /** Users signed in to a harness on it. */
200
+ signedIn: readonly string[];
201
+ /** Why Work cannot do what the plan asks yet (it holds live work, the hook has no `stop`). */
202
+ notice: string | null;
203
+ /** The latest failure of a verb for it, cleared when that verb next succeeds. */
204
+ lastError: { verb: MachineVerb; message: string; at: string } | null;
205
+ }
206
+
207
+ export type MachineVerb = "create" | "destroy" | "stop" | "start" | "describe";
208
+
209
+ /** Work that has no machine yet. */
210
+ export interface WaitingWork {
211
+ /** The chat's or run's id. */
212
+ id: string;
213
+ /** A chat, a workflow run, or a cache fill. */
214
+ kind: "chat" | "run" | "fill";
215
+ project: string;
216
+ /** The member whose work it is; null for the project's own. */
217
+ user: string | null;
218
+ /** The chat key of a project's own chat, if it has one. */
219
+ key: string | null;
220
+ environment: string;
221
+ /** The Environment's pool: labels a machine must carry. */
222
+ pool: Readonly<Record<string, string>>;
223
+ requirements: {
224
+ resources: {
225
+ cpuMillis?: number;
226
+ memoryMb?: number;
227
+ storageMb?: number;
228
+ gpu?: boolean;
229
+ };
230
+ capabilities: readonly string[];
231
+ isolation?: "none" | "process" | "sandbox";
232
+ };
233
+ /** No machine open to it had room (`capacity`), or none was online (`unavailable`). */
234
+ reason: "capacity" | "unavailable";
235
+ /** ISO 8601. */
236
+ waitingSince: string;
237
+ }
238
+
239
+ /** One account of the server, so "everyone with role X" needs no directory. */
240
+ export interface PersonFacts {
241
+ /** The account id: what `{ user }` names. */
242
+ id: string;
243
+ email: string | null;
244
+ name: string | null;
245
+ /** False once the account is disabled. */
246
+ active: boolean;
247
+ administrator: boolean;
248
+ /** Role names by project id. */
249
+ roles: Readonly<Record<string, readonly string[]>>;
250
+ }
251
+
252
+ /** What `plan` is given. */
253
+ export interface MachinePlanFacts {
254
+ /** ISO 8601, by the server's database clock. */
255
+ now: string;
256
+ /** Work that has no machine yet. */
257
+ work: readonly WaitingWork[];
258
+ /** Every machine Work knows, managed by this hook or enrolled by hand. */
259
+ machines: readonly MachineFacts[];
260
+ /** The server's accounts with their project roles. */
261
+ people: readonly PersonFacts[];
262
+ }
263
+
264
+ /** The machine a verb acts on. */
265
+ export interface MachineTarget {
266
+ name: string;
267
+ /** The ref `create` answered; null when it never did. */
268
+ ref: string | null;
269
+ /**
270
+ * The idempotency key its `create` was given, which finds a machine whose
271
+ * create answer was lost. Null for none.
272
+ */
273
+ idempotencyKey: string | null;
274
+ /** The options it was created with. */
275
+ options: Readonly<Record<string, unknown>>;
276
+ labels: Readonly<Record<string, string>>;
277
+ }
278
+
279
+ export interface MachineCreateRequest {
280
+ name: string;
281
+ options: Readonly<Record<string, unknown>>;
282
+ labels: Readonly<Record<string, string>>;
283
+ /**
284
+ * What the new machine starts its worker with: `WORK_CONTROL_PLANE_URL`
285
+ * and `WORK_WORKER_ENROLLMENT`. The code is a secret: never log it.
286
+ */
287
+ enrollment: {
288
+ controlPlaneUrl: string;
289
+ code: string;
290
+ /** The platform's idempotency token for this create: 64 hex characters. */
291
+ idempotencyKey: string;
292
+ };
293
+ }
294
+
295
+ /**
296
+ * `ref`: the machine exists (or already did, for this key). `pending`: not
297
+ * yet; Work asks again with the same request. `refused`: the platform made
298
+ * nothing and would refuse again; Work withdraws the code, shows the
299
+ * reason, and asks again later with a new enrollment.
300
+ */
301
+ export type MachineCreateResult =
302
+ | { ref: string }
303
+ | { pending: true }
304
+ | { refused: string };
305
+
306
+ export const MachineCreateResultSchema: z.ZodType<
307
+ MachineCreateResult,
308
+ MachineCreateResult
309
+ > = z.union([
310
+ z.strictObject({ ref: z.string().min(1).max(500) }),
311
+ z.strictObject({ pending: z.literal(true) }),
312
+ z.strictObject({ refused: z.string().min(1).max(2_000) }),
313
+ ]);
314
+
315
+ const DoneSchema = z.strictObject({ done: z.boolean() });
316
+ export const MachineDestroyResultSchema = DoneSchema;
317
+ export const MachineStopResultSchema = DoneSchema;
318
+ export const MachineStartResultSchema = z.union([
319
+ DoneSchema,
320
+ z.strictObject({ gone: z.literal(true) }),
321
+ ]);
322
+ export const MachineDescribeResultSchema = z.strictObject({
323
+ state: z.enum(["running", "stopped", "gone", "unknown"]),
324
+ });
325
+
326
+ export const MACHINE_EVENT_KINDS = [
327
+ "machine.created",
328
+ "machine.connected",
329
+ "machine.lost",
330
+ "machine.stopped",
331
+ "machine.started",
332
+ "machine.released",
333
+ "machine.destroyed",
334
+ "machine.disk-low",
335
+ ] as const;
336
+ export type MachineEventKind = (typeof MACHINE_EVENT_KINDS)[number];
337
+
338
+ /** Something that happened to a machine. Nothing Work needs depends on it. */
339
+ export interface MachineEvent {
340
+ kind: MachineEventKind;
341
+ /** ISO 8601. */
342
+ at: string;
343
+ machine: {
344
+ name: string;
345
+ ref: string | null;
346
+ managed: boolean;
347
+ labels: Readonly<Record<string, string>>;
348
+ for: readonly MachinePrincipal[] | null;
349
+ options: Readonly<Record<string, unknown>>;
350
+ reason: string | null;
351
+ };
352
+ /** `machine.disk-low` only: the report that began the episode. */
353
+ disk?: {
354
+ path: string;
355
+ totalBytes: number;
356
+ freeBytes: number;
357
+ floorBytes: number;
358
+ measuredAt: string;
359
+ };
360
+ }
361
+
362
+ /**
363
+ * The host's machines: `plan` decides, the verbs act. One provisioner per
364
+ * hook; a host with two clouds dispatches inside its own verbs (by an
365
+ * option or a label).
366
+ */
367
+ export interface MachinesHook {
368
+ /**
369
+ * Decide: given the facts, the set of machines that should exist. It
370
+ * changes nothing in Work; it may read the host's own config or
371
+ * directory. Return the same names for the same facts: Work works out
372
+ * the difference. A plan that throws, takes too long or returns
373
+ * something invalid changes nothing, and its error is shown.
374
+ */
375
+ plan(args: MachinePlanFacts): Promise<readonly DesiredMachine[]>;
376
+ /**
377
+ * Make one machine that starts the Work worker with `enrollment`. Work
378
+ * recorded its intent first and repeats this call with the same
379
+ * `idempotencyKey` until it answers `ref`: hand the key to the platform
380
+ * as its idempotency token, so a repeat returns the same machine.
381
+ */
382
+ create(args: MachineCreateRequest): Promise<MachineCreateResult>;
383
+ /**
384
+ * Remove the machine: the one `ref` names, and any made with
385
+ * `idempotencyKey` or carrying `name` whose create answer was lost.
386
+ * `requestedAt` is when Work first asked. Answer `done: false` while it is
387
+ * still going, or while a machine just created may not be listed yet;
388
+ * Work asks again.
389
+ */
390
+ destroy(args: MachineTarget & { requestedAt: string }): Promise<{
391
+ done: boolean;
392
+ }>;
393
+ /**
394
+ * Stop the machine and keep its disk. `requestedAt` is stable for this
395
+ * stop request. Without a stop verb, no machine is stopped.
396
+ */
397
+ stop?(
398
+ args: MachineTarget & { requestedAt: string },
399
+ ): Promise<{ done: boolean }>;
400
+ /**
401
+ * Start a stopped machine; its worker connects again by itself. `gone`
402
+ * when it no longer exists: Work treats it as lost and makes it again.
403
+ * `requestedAt` is stable for this start request.
404
+ */
405
+ start?(
406
+ args: MachineTarget & { requestedAt: string },
407
+ ): Promise<{ done: boolean } | { gone: true }>;
408
+ /** Lets Work confirm a loss at once instead of waiting out the limit. */
409
+ describe?(args: MachineTarget): Promise<{
410
+ state: "running" | "stopped" | "gone" | "unknown";
411
+ }>;
412
+ /**
413
+ * Hear every machine event, to route it wherever the host likes. Work
414
+ * also records each for the projects named in the machine's `for`.
415
+ */
416
+ onEvent?(event: MachineEvent): Promise<void> | void;
417
+ }
418
+
419
+ /** Whether two principals name the same thing. */
420
+ export function samePrincipal(
421
+ left: MachinePrincipal,
422
+ right: MachinePrincipal,
423
+ ): boolean {
424
+ if ("user" in left) return "user" in right && left.user === right.user;
425
+ if ("user" in right) return false;
426
+ const leftKey = "key" in left ? left.key : undefined;
427
+ const rightKey = "key" in right ? right.key : undefined;
428
+ return left.project === right.project && leftKey === rightKey;
429
+ }
430
+
431
+ /**
432
+ * Whether `principal` could already place work on a machine for `list`: it
433
+ * is named there, or it is one chat key of a project the list names.
434
+ */
435
+ function covered(
436
+ list: readonly MachinePrincipal[],
437
+ principal: MachinePrincipal,
438
+ ): boolean {
439
+ return list.some(
440
+ (entry) =>
441
+ samePrincipal(entry, principal) ||
442
+ ("project" in entry &&
443
+ !("key" in entry) &&
444
+ "project" in principal &&
445
+ entry.project === principal.project),
446
+ );
447
+ }
448
+
449
+ /**
450
+ * Whether changing whom a machine is for lets someone new reach what the
451
+ * previous owners left on it (sandboxes, volumes, sign-ins), so it must be
452
+ * reset first. Narrowing never does; opening a machine to anyone, or to a
453
+ * principal that could not use it before, does.
454
+ */
455
+ export function principalsChangeNeedsReset(args: {
456
+ from: readonly MachinePrincipal[] | null;
457
+ to: readonly MachinePrincipal[] | null;
458
+ }): boolean {
459
+ if (args.from === null) return false;
460
+ if (args.to === null) return true;
461
+ const from = args.from;
462
+ return args.to.some((principal) => !covered(from, principal));
463
+ }
464
+
465
+ /** Principals in a stable order with duplicates removed, to compare and store. */
466
+ export function normalizePrincipals(
467
+ principals: readonly MachinePrincipal[],
468
+ ): MachinePrincipal[] {
469
+ const key = (principal: MachinePrincipal) =>
470
+ "user" in principal
471
+ ? `user\0${principal.user}`
472
+ : `project\0${principal.project}\0${"key" in principal ? principal.key : ""}`;
473
+ const byKey = new Map(
474
+ principals.map((principal) => [key(principal), principal]),
475
+ );
476
+ return [...byKey.entries()]
477
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
478
+ .map(([, principal]) => principal);
479
+ }
480
+
481
+ /** Whether two principal lists (or "anyone") are the same. */
482
+ export function samePrincipals(
483
+ left: readonly MachinePrincipal[] | null,
484
+ right: readonly MachinePrincipal[] | null,
485
+ ): boolean {
486
+ if (left === null || right === null) return left === right;
487
+ return (
488
+ JSON.stringify(normalizePrincipals(left)) ===
489
+ JSON.stringify(normalizePrincipals(right))
490
+ );
491
+ }
492
+
493
+ /**
494
+ * One principal and nobody else: no one else's work lands on the machine,
495
+ * so process isolation is enough and it may hold that owner's sign-ins.
496
+ */
497
+ export function servesOneOwner(
498
+ principals: readonly MachinePrincipal[] | null,
499
+ ): boolean {
500
+ return principals !== null && normalizePrincipals(principals).length === 1;
501
+ }
502
+
503
+ /** A machine taking no one's work: any isolation is enough. */
504
+ export function servesNobody(
505
+ principals: readonly MachinePrincipal[] | null,
506
+ ): boolean {
507
+ return principals !== null && principals.length === 0;
508
+ }
509
+
510
+ /** Whether a machine for `principals` takes this waiting work. */
511
+ export function principalsTake(args: {
512
+ for: readonly MachinePrincipal[] | null;
513
+ work: Pick<WaitingWork, "project" | "user" | "key">;
514
+ }): boolean {
515
+ if (args.for === null) return true;
516
+ const { work } = args;
517
+ return args.for.some((principal) => {
518
+ if ("user" in principal) return work.user === principal.user;
519
+ if (work.user !== null || principal.project !== work.project) return false;
520
+ return !("key" in principal) || principal.key === work.key;
521
+ });
522
+ }