@catamorphic/work-server 0.1.0-alpha.38 → 0.1.0-alpha.41

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 +44 -34
  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
@@ -1,360 +0,0 @@
1
- import { type ChildProcess, spawn } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
- import fs from "node:fs";
4
- import path from "node:path";
5
- import { z } from "zod";
6
- import {
7
- assertMachineFree,
8
- MachineHeldError,
9
- placeSignIn,
10
- signInCommand,
11
- signOutOnMachine,
12
- stageSignIn,
13
- } from "./sign-ins.js";
14
-
15
- /*
16
- * A member signs in to Codex on one of their machines from the Work app
17
- * (ADR 0213): this machine runs Codex's own device-code login
18
- * (`codex login --device-auth`) into a home of its own for them, the app
19
- * shows the link and the one-time code it printed, and the member approves
20
- * in their own browser. The token is issued to Codex on this machine and
21
- * never leaves it; the one-time code is useless without that approval.
22
- * Attempts are this process's working state: a machine that restarts
23
- * forgets them, and the member starts again.
24
- */
25
-
26
- /** What a member does with Codex on a machine. */
27
- export type CodexSignInRequest =
28
- | { action: "begin"; member: string }
29
- | { action: "status"; member: string; attempt: string }
30
- | { action: "cancel"; member: string; attempt: string }
31
- | { action: "signOut"; member: string };
32
-
33
- export const CodexSignInStartedSchema = z.strictObject({
34
- attempt: z.string().uuid(),
35
- verificationUrl: z.string().url(),
36
- userCode: z.string().min(1).max(32),
37
- expiresAt: z.string().datetime(),
38
- });
39
- export type CodexSignInStarted = z.infer<typeof CodexSignInStartedSchema>;
40
-
41
- export const CodexSignInStatusSchema = z.strictObject({
42
- state: z.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
43
- message: z.string().max(400).optional(),
44
- });
45
- export type CodexSignInStatus = z.infer<typeof CodexSignInStatusSchema>;
46
- export type CodexSignInState = CodexSignInStatus["state"];
47
-
48
- export const CodexSignedOutSchema = z.strictObject({ signedOut: z.boolean() });
49
-
50
- /** A login this machine would not start, and why, for the member to read. */
51
- export const CodexSignInRefusedSchema = z.strictObject({
52
- refused: z.string().min(1).max(400),
53
- });
54
-
55
- /** How long Codex takes at most to print its link and code. */
56
- const CODE_TIMEOUT_MS = 30_000;
57
- /** Codex's own codes last 15 minutes unless it says otherwise. */
58
- const DEFAULT_CODE_MINUTES = 15;
59
- /** Finished attempts are remembered this long for a late status read. */
60
- const FINISHED_TTL_MS = 60 * 60_000;
61
-
62
- interface Attempt {
63
- member: string;
64
- child: ChildProcess;
65
- staging: string;
66
- expiresAt: number;
67
- state: CodexSignInState;
68
- message?: string;
69
- finishedAt?: number;
70
- deadline: NodeJS.Timeout;
71
- }
72
-
73
- /** Codex's output without its colors. */
74
- export function plainOutput(text: string): string {
75
- // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escapes
76
- return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
77
- }
78
-
79
- /**
80
- * The link, one-time code and lifetime `codex login --device-auth` printed,
81
- * once it printed both.
82
- */
83
- export function parseDeviceCode(
84
- output: string,
85
- ): { verificationUrl: string; userCode: string; minutes: number } | undefined {
86
- const text = plainOutput(output);
87
- const verificationUrl = /https:\/\/\S+/.exec(text)?.[0];
88
- const userCode = text
89
- .split("\n")
90
- .map((line) => line.trim())
91
- .find((line) => /^[A-Z0-9]{3,8}-[A-Z0-9]{3,8}$/.test(line));
92
- if (!verificationUrl || !userCode) return undefined;
93
- const minutes = Number(/expires in (\d+) minutes?/i.exec(text)?.[1]);
94
- return {
95
- verificationUrl,
96
- userCode,
97
- minutes:
98
- Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_CODE_MINUTES,
99
- };
100
- }
101
-
102
- /** The last thing Codex said, for a member to read: one short line. */
103
- function lastWords(output: string): string | undefined {
104
- const lines = plainOutput(output)
105
- .split("\n")
106
- .map((line) => line.trim())
107
- .filter(Boolean);
108
- const last = lines.at(-1);
109
- return last ? last.slice(0, 300) : undefined;
110
- }
111
-
112
- export class CodexSignInRefusedError extends Error {
113
- constructor(message: string) {
114
- super(message);
115
- this.name = "CodexSignInRefusedError";
116
- }
117
- }
118
-
119
- export class CodexSignIns {
120
- /**
121
- * Replica memory (a): the logins this machine's own process runs, each a
122
- * child process here; a machine that restarts forgets them and the
123
- * member starts again.
124
- */
125
- private readonly attempts = new Map<string, Attempt>();
126
-
127
- constructor(
128
- private readonly options: {
129
- /** The machine's sign-in root (`<data>/sign-ins`). */
130
- signInRoot: string;
131
- /** The machine's data directory, for signing out. */
132
- dataDir: string;
133
- env?: NodeJS.ProcessEnv;
134
- now?: () => number;
135
- /**
136
- * A member's sign-in was placed or removed: the machine tells
137
- * placement now rather than at its next scan.
138
- */
139
- onChange?: () => void;
140
- },
141
- ) {}
142
-
143
- /** One request from the control plane (or this server's own routes). */
144
- async handle(
145
- request: CodexSignInRequest,
146
- ): Promise<
147
- | CodexSignInStarted
148
- | { refused: string }
149
- | CodexSignInStatus
150
- | { signedOut: boolean }
151
- > {
152
- switch (request.action) {
153
- case "begin":
154
- // A refusal is an answer the member reads, not a machine failure.
155
- return this.begin(request).catch((error: unknown) => {
156
- if (error instanceof CodexSignInRefusedError)
157
- return { refused: error.message.slice(0, 400) };
158
- throw error;
159
- });
160
- case "status":
161
- return this.status(request);
162
- case "cancel":
163
- return this.cancel(request);
164
- case "signOut": {
165
- const signedOut = signOutOnMachine({
166
- dataDir: this.options.dataDir,
167
- harness: "codex",
168
- member: request.member,
169
- });
170
- if (signedOut) this.options.onChange?.();
171
- return { signedOut };
172
- }
173
- }
174
- }
175
-
176
- /**
177
- * Start Codex's device-code login for a member. Resolves once Codex
178
- * printed its link and code; one login runs per member, so a new one
179
- * replaces theirs.
180
- */
181
- async begin(input: { member: string }): Promise<CodexSignInStarted> {
182
- this.prune();
183
- try {
184
- assertMachineFree({
185
- root: this.options.signInRoot,
186
- member: input.member,
187
- });
188
- } catch (error) {
189
- if (error instanceof MachineHeldError)
190
- throw new CodexSignInRefusedError(error.message);
191
- throw error;
192
- }
193
- for (const [id, attempt] of this.attempts)
194
- if (attempt.member === input.member && attempt.state === "waiting")
195
- this.finish(id, "cancelled", "A newer sign-in replaced this one");
196
- const staging = stageSignIn({
197
- root: this.options.signInRoot,
198
- harness: "codex",
199
- member: input.member,
200
- });
201
- const login = signInCommand({
202
- home: staging,
203
- args: ["--device-auth"],
204
- env: this.options.env,
205
- });
206
- const child = spawn(login.command, login.args, {
207
- env: {
208
- ...(this.options.env ?? process.env),
209
- ...login.env,
210
- NO_COLOR: "1",
211
- },
212
- stdio: ["ignore", "pipe", "pipe"],
213
- });
214
- const id = randomUUID();
215
- let output = "";
216
- return new Promise<CodexSignInStarted>((resolve, reject) => {
217
- let settled = false;
218
- const fail = (message: string) => {
219
- if (settled) return;
220
- settled = true;
221
- clearTimeout(timer);
222
- child.kill("SIGTERM");
223
- fs.rmSync(staging, { recursive: true, force: true });
224
- reject(new CodexSignInRefusedError(message));
225
- };
226
- const timer = setTimeout(
227
- () =>
228
- fail(
229
- `Codex did not print a sign-in code within ${CODE_TIMEOUT_MS / 1000} seconds${lastWords(output) ? `: ${lastWords(output)}` : ""}`,
230
- ),
231
- CODE_TIMEOUT_MS,
232
- );
233
- const read = (chunk: Buffer) => {
234
- output += chunk.toString("utf8");
235
- if (output.length > 64_000) output = output.slice(-64_000);
236
- const code = parseDeviceCode(output);
237
- if (!code || settled) return;
238
- settled = true;
239
- clearTimeout(timer);
240
- const now = this.now();
241
- const expiresAt = now + code.minutes * 60_000;
242
- this.attempts.set(id, {
243
- member: input.member,
244
- child,
245
- staging,
246
- expiresAt,
247
- state: "waiting",
248
- // Codex gives up on its own; this only makes sure.
249
- deadline: setTimeout(
250
- () => this.finish(id, "expired", "The code expired"),
251
- code.minutes * 60_000 + 60_000,
252
- ),
253
- });
254
- resolve({
255
- attempt: id,
256
- verificationUrl: code.verificationUrl,
257
- userCode: code.userCode,
258
- expiresAt: new Date(expiresAt).toISOString(),
259
- });
260
- };
261
- child.stdout?.on("data", read);
262
- child.stderr?.on("data", read);
263
- child.once("error", (error) =>
264
- fail(`Could not run Codex on this machine: ${error.message}`),
265
- );
266
- child.once("exit", (code) => {
267
- if (!settled) {
268
- fail(
269
- lastWords(output) ??
270
- `Codex stopped before printing a sign-in code (exit ${code ?? "signal"})`,
271
- );
272
- return;
273
- }
274
- const attempt = this.attempts.get(id);
275
- if (attempt?.state !== "waiting") return;
276
- if (code === 0 && fs.existsSync(path.join(staging, "auth.json"))) {
277
- try {
278
- // Someone else may have signed in here meanwhile.
279
- assertMachineFree({
280
- root: this.options.signInRoot,
281
- member: input.member,
282
- });
283
- placeSignIn({
284
- root: this.options.signInRoot,
285
- harness: "codex",
286
- member: input.member,
287
- staging,
288
- });
289
- } catch (error) {
290
- // Held by someone else, or the machine was reset meanwhile.
291
- this.finish(
292
- id,
293
- "failed",
294
- error instanceof Error ? error.message : String(error),
295
- );
296
- return;
297
- }
298
- this.finish(id, "signed-in");
299
- this.options.onChange?.();
300
- return;
301
- }
302
- this.finish(
303
- id,
304
- this.now() >= attempt.expiresAt ? "expired" : "failed",
305
- lastWords(output) ?? "Codex did not complete the sign-in",
306
- );
307
- });
308
- });
309
- }
310
-
311
- status(input: { member: string; attempt: string }): CodexSignInStatus {
312
- const attempt = this.attempts.get(input.attempt);
313
- if (!attempt || attempt.member !== input.member)
314
- return {
315
- state: "failed",
316
- message:
317
- "This machine no longer knows this sign-in; it may have restarted. Start again",
318
- };
319
- return {
320
- state: attempt.state,
321
- ...(attempt.message ? { message: attempt.message } : {}),
322
- };
323
- }
324
-
325
- cancel(input: { member: string; attempt: string }): CodexSignInStatus {
326
- const attempt = this.attempts.get(input.attempt);
327
- if (attempt?.member === input.member && attempt.state === "waiting")
328
- this.finish(input.attempt, "cancelled");
329
- return this.status(input);
330
- }
331
-
332
- /** End every login this machine runs, when it stops. */
333
- stop(): void {
334
- for (const [id, attempt] of this.attempts)
335
- if (attempt.state === "waiting") this.finish(id, "cancelled");
336
- }
337
-
338
- private finish(id: string, state: CodexSignInState, message?: string): void {
339
- const attempt = this.attempts.get(id);
340
- if (attempt?.state !== "waiting") return;
341
- attempt.state = state;
342
- if (message) attempt.message = message;
343
- attempt.finishedAt = this.now();
344
- clearTimeout(attempt.deadline);
345
- if (attempt.child.exitCode === null) attempt.child.kill("SIGTERM");
346
- if (state !== "signed-in")
347
- fs.rmSync(attempt.staging, { recursive: true, force: true });
348
- }
349
-
350
- private prune(): void {
351
- const now = this.now();
352
- for (const [id, attempt] of this.attempts)
353
- if (attempt.finishedAt && now - attempt.finishedAt > FINISHED_TTL_MS)
354
- this.attempts.delete(id);
355
- }
356
-
357
- private now(): number {
358
- return this.options.now?.() ?? Date.now();
359
- }
360
- }