@catamorphic/work-server 0.1.0-alpha.39 → 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 +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
@@ -1,404 +0,0 @@
1
- import { createHash, randomBytes, randomUUID } from "node:crypto";
2
- import fs from "node:fs";
3
- import { createRequire } from "node:module";
4
- import path from "node:path";
5
- import type { AgentTurnUsage, Item, Turn } from "@catamorphic/agent-protocol";
6
- import {
7
- type AgentSessionsService,
8
- type Identity,
9
- parseRegistryCatalog,
10
- } from "@catamorphic/core";
11
- import pg from "pg";
12
- import { workServerConfigFromEnv } from "./config.js";
13
- import {
14
- executionSettingsFromEnv,
15
- type WorkExecutionSettings,
16
- } from "./execution-config.js";
17
- import {
18
- type DirectoryAccountStatus,
19
- type DirectoryProvider,
20
- DirectoryUnavailableError,
21
- } from "./identity/directory.js";
22
- import type { WorkServerOptions } from "./server.js";
23
-
24
- /**
25
- * A directory (ADR 0161) governing Better Auth's local "credential"
26
- * accounts, whose account id is the user id, so every lifecycle path runs
27
- * through the real OAuth server and token gate. Accounts it does not know
28
- * are active in no group; it answers only about the groups it is asked.
29
- */
30
- export class FakeDirectory implements DirectoryProvider {
31
- readonly providerId = "credential";
32
- readonly requiredGroups: string[] = [];
33
- /** Replica memory (single process): a test's directory, never a host's. */
34
- readonly accounts = new Map<string, DirectoryAccountStatus>();
35
- unavailable = false;
36
- calls = 0;
37
-
38
- async check(args: {
39
- accountId: string;
40
- groups: readonly string[];
41
- }): Promise<DirectoryAccountStatus> {
42
- this.calls += 1;
43
- if (this.unavailable) throw new DirectoryUnavailableError("offline");
44
- const status = this.accounts.get(args.accountId) ?? {
45
- active: true,
46
- groups: [],
47
- };
48
- return status.active
49
- ? {
50
- active: true,
51
- groups: status.groups.filter((group) => args.groups.includes(group)),
52
- }
53
- : status;
54
- }
55
- }
56
-
57
- /** Test servers boot from the same env parser as the image. */
58
- export function testServerOptions(args: {
59
- dataDir: string;
60
- publicBases?: string[];
61
- env: Record<string, string | undefined>;
62
- }): WorkServerOptions {
63
- return {
64
- config: {
65
- ...workServerConfigFromEnv({
66
- WORK_DATA_DIR: args.dataDir,
67
- // Tests run trusted subprocesses unless they choose a backend.
68
- WORK_SANDBOX: "local-process",
69
- ...args.env,
70
- }),
71
- dataDir: args.dataDir,
72
- ...(args.publicBases ? { publicBases: args.publicBases } : {}),
73
- },
74
- };
75
- }
76
-
77
- /**
78
- * A test worker's execution settings, from the same parser as the image.
79
- * Like {@link testServerOptions}, trusted subprocesses unless the test
80
- * chooses a backend: `auto` would pick containers on a runner with Docker.
81
- */
82
- export function testExecutionSettings(
83
- env: Record<string, string | undefined>,
84
- ): WorkExecutionSettings {
85
- return executionSettingsFromEnv({ WORK_SANDBOX: "local-process", ...env });
86
- }
87
-
88
- /**
89
- * A database of its own on the server at `DATABASE_URL`: a deployment's
90
- * replicas share one origin and secrets, which other suites do not.
91
- */
92
- export async function createTestDatabase(prefix: string): Promise<{
93
- url: string;
94
- drop(): Promise<void>;
95
- }> {
96
- const admin = new pg.Client({ connectionString: process.env.DATABASE_URL });
97
- const database = `${prefix}_${randomBytes(4).toString("hex")}`;
98
- await admin.connect();
99
- await admin.query(`CREATE DATABASE ${database}`);
100
- const url = new URL(process.env.DATABASE_URL ?? "");
101
- url.pathname = `/${database}`;
102
- return {
103
- url: url.toString(),
104
- drop: async () => {
105
- try {
106
- await dropTestDatabase({ admin, database });
107
- } finally {
108
- await admin.end();
109
- }
110
- },
111
- };
112
- }
113
-
114
- interface InjectableApp {
115
- inject(options: {
116
- method: "GET" | "POST";
117
- url: string;
118
- headers?: Record<string, string>;
119
- payload?: unknown;
120
- }): Promise<{
121
- statusCode: number;
122
- headers: Record<string, string | string[] | number | undefined>;
123
- json(): Record<string, unknown>;
124
- }>;
125
- }
126
-
127
- /** Accept the signed authorization prompt before exchanging the code. */
128
- export async function acceptOAuthConsent(args: {
129
- app: InjectableApp;
130
- location: string;
131
- cookie: string;
132
- }): Promise<string> {
133
- const consent = new URL(args.location);
134
- if (consent.pathname !== "/oauth/consent") return args.location;
135
- const page = await args.app.inject({
136
- method: "GET",
137
- url: `${consent.pathname}${consent.search}`,
138
- headers: { cookie: args.cookie },
139
- });
140
- if (page.statusCode !== 200) {
141
- throw new Error(`consent page answered ${page.statusCode}, expected 200`);
142
- }
143
- const accepted = await args.app.inject({
144
- method: "POST",
145
- url: "/oauth/consent",
146
- headers: {
147
- cookie: args.cookie,
148
- "content-type": "application/x-www-form-urlencoded",
149
- },
150
- payload: new URLSearchParams({
151
- accept: "true",
152
- oauth_query: consent.search.slice(1),
153
- }).toString(),
154
- });
155
- if (accepted.statusCode !== 302) {
156
- throw new Error(`consent answered ${accepted.statusCode}, expected 302`);
157
- }
158
- return String(accepted.headers.location ?? "");
159
- }
160
-
161
- /**
162
- * The OAuth flow an MCP client runs, in process: local sign-in, dynamic
163
- * client registration, PKCE authorization, and the code exchange.
164
- */
165
- export async function oauthAccessToken(args: {
166
- app: InjectableApp;
167
- username: string;
168
- password: string;
169
- }): Promise<string> {
170
- const { app } = args;
171
- const resourceMetadata = await app.inject({
172
- method: "GET",
173
- url: "/.well-known/oauth-protected-resource",
174
- });
175
- const resource = resourceMetadata.json().resource;
176
- if (typeof resource !== "string")
177
- throw new Error("Missing Work resource metadata");
178
- const expectStatus = (step: string, actual: number, expected: number) => {
179
- if (actual !== expected)
180
- throw new Error(`${step} answered ${actual}, expected ${expected}`);
181
- };
182
- const login = await app.inject({
183
- method: "POST",
184
- url: "/api/auth/sign-in/username",
185
- payload: { username: args.username, password: args.password },
186
- });
187
- expectStatus("sign-in", login.statusCode, 200);
188
- const setCookie = login.headers["set-cookie"];
189
- const cookie = String(Array.isArray(setCookie) ? setCookie[0] : setCookie);
190
-
191
- const redirectUri = "http://127.0.0.1:49152/callback";
192
- const registered = await app.inject({
193
- method: "POST",
194
- url: "/api/auth/oauth2/register",
195
- payload: {
196
- redirect_uris: [redirectUri],
197
- token_endpoint_auth_method: "none",
198
- grant_types: ["authorization_code", "refresh_token"],
199
- response_types: ["code"],
200
- client_name: "Work server test",
201
- },
202
- });
203
- expectStatus("registration", registered.statusCode, 201);
204
- const clientId = String(registered.json().client_id);
205
- const verifier = randomBytes(32).toString("base64url");
206
- const challenge = createHash("sha256").update(verifier).digest("base64url");
207
- const authorize = new URLSearchParams({
208
- client_id: clientId,
209
- redirect_uri: redirectUri,
210
- response_type: "code",
211
- resource,
212
- scope: "openid profile email offline_access",
213
- state: "work-server-state",
214
- code_challenge: challenge,
215
- code_challenge_method: "S256",
216
- });
217
- const authorized = await app.inject({
218
- method: "GET",
219
- url: `/api/auth/oauth2/authorize?${authorize}`,
220
- headers: { cookie },
221
- });
222
- expectStatus("authorization", authorized.statusCode, 302);
223
- const callback = await acceptOAuthConsent({
224
- app,
225
- location: String(authorized.headers.location ?? ""),
226
- cookie,
227
- });
228
- const code = new URL(callback).searchParams.get("code") ?? "";
229
-
230
- const token = await app.inject({
231
- method: "POST",
232
- url: "/api/auth/oauth2/token",
233
- headers: { "content-type": "application/x-www-form-urlencoded" },
234
- payload: new URLSearchParams({
235
- grant_type: "authorization_code",
236
- client_id: clientId,
237
- redirect_uri: redirectUri,
238
- code,
239
- code_verifier: verifier,
240
- }).toString(),
241
- });
242
- expectStatus("token", token.statusCode, 200);
243
- return String(token.json().access_token);
244
- }
245
-
246
- /**
247
- * Drop a test's own database once the servers that used it have closed
248
- * their connections. Forcing it while a pool is still closing a client
249
- * terminates that client, which surfaces as an uncaught error; a
250
- * connection still open after 10 seconds is a leak, so the test fails.
251
- */
252
- export async function dropTestDatabase(args: {
253
- admin: {
254
- query(
255
- text: string,
256
- values?: unknown[],
257
- ): Promise<{ rows: Array<{ connections?: number }> }>;
258
- };
259
- database: string;
260
- }): Promise<void> {
261
- const deadline = Date.now() + 10_000;
262
- let open = 0;
263
- do {
264
- const { rows } = await args.admin.query(
265
- "SELECT count(*)::int AS connections FROM pg_stat_activity WHERE datname = $1",
266
- [args.database],
267
- );
268
- open = rows[0]?.connections ?? 0;
269
- if (open > 0) await new Promise((resolve) => setTimeout(resolve, 100));
270
- } while (open > 0 && Date.now() < deadline);
271
- await args.admin.query(`DROP DATABASE ${args.database} WITH (FORCE)`);
272
- if (open > 0) {
273
- throw new Error(
274
- `${open} connection(s) to ${args.database} were still open 10 seconds after the servers shut down`,
275
- );
276
- }
277
- }
278
-
279
- /**
280
- * A settled turn as tests read it: the agent's final reply (or the turn's
281
- * error, for one that failed), its usage, and the turn.
282
- */
283
- export function replyOf(result: { reply: Item | null; turn: Turn }): {
284
- content: string;
285
- usage: AgentTurnUsage | undefined;
286
- turn: Turn;
287
- } {
288
- const { reply, turn } = result;
289
- return {
290
- content:
291
- reply?.kind === "assistant_message"
292
- ? reply.text
293
- : (turn.error?.message ?? ""),
294
- usage: turn.outcome?.usage,
295
- turn,
296
- };
297
- }
298
-
299
- /** Send a message and wait for its turn: {@link replyOf} that turn. */
300
- export async function say(input: {
301
- sessions: AgentSessionsService;
302
- identity: Identity;
303
- projectId: string;
304
- sessionId: string;
305
- text: string;
306
- }): Promise<ReturnType<typeof replyOf>> {
307
- return replyOf(
308
- await input.sessions.sendMessage(
309
- input.identity,
310
- input.projectId,
311
- input.sessionId,
312
- input.text,
313
- ),
314
- );
315
- }
316
-
317
- /** Queue a message without waiting for it; resolves its turn's id. */
318
- export async function enqueue(input: {
319
- sessions: AgentSessionsService;
320
- identity: Identity;
321
- projectId: string;
322
- sessionId: string;
323
- text: string;
324
- }): Promise<string> {
325
- const receipt = await input.sessions.command(
326
- input.identity,
327
- input.projectId,
328
- input.sessionId,
329
- {
330
- type: "send",
331
- commandId: randomUUID(),
332
- text: input.text,
333
- dispatch: "queue",
334
- },
335
- );
336
- const turnId = receipt.result?.turnId;
337
- if (receipt.status !== "accepted" || typeof turnId !== "string")
338
- throw new Error(receipt.error?.message ?? "The message started no turn");
339
- return turnId;
340
- }
341
-
342
- /**
343
- * Every regular file under a directory, links not followed. A sandbox's
344
- * transient files (a lock, an index being rewritten) may go while it is
345
- * walked: what is gone by then is not listed. The directory itself must be
346
- * there, so a scan of it never passes for want of files.
347
- */
348
- export function filesUnder(directory: string): string[] {
349
- return walkFiles(directory, true);
350
- }
351
-
352
- function walkFiles(directory: string, root: boolean): string[] {
353
- let entries: fs.Dirent[];
354
- try {
355
- entries = fs.readdirSync(directory, { withFileTypes: true });
356
- } catch (error) {
357
- if (!root && isMissing(error)) return [];
358
- throw error;
359
- }
360
- return entries.flatMap((entry) => {
361
- const full = path.join(directory, entry.name);
362
- if (entry.isDirectory()) return walkFiles(full, false);
363
- return entry.isFile() ? [full] : [];
364
- });
365
- }
366
-
367
- /**
368
- * Files under a directory whose bytes contain the text, as a leak check
369
- * reads them: a file gone before it is read holds nothing.
370
- */
371
- export function filesHolding(directory: string, text: string): string[] {
372
- return filesUnder(directory).filter((file) => {
373
- try {
374
- return fs.readFileSync(file).includes(text);
375
- } catch (error) {
376
- if (isMissing(error)) return false;
377
- throw error;
378
- }
379
- });
380
- }
381
-
382
- function isMissing(error: unknown): boolean {
383
- return error instanceof Error && "code" in error && error.code === "ENOENT";
384
- }
385
-
386
- /**
387
- * A registry pack's files by their project targets, from the built catalog
388
- * an agent's `registry.read` returns (ADR 0262).
389
- */
390
- export function registryPack(name: string): Record<string, string> {
391
- const catalog = parseRegistryCatalog(
392
- fs.readFileSync(
393
- createRequire(import.meta.url).resolve(
394
- "@catamorphic/registry/catalog.json",
395
- ),
396
- "utf8",
397
- ),
398
- );
399
- const item = catalog.find((entry) => entry.name === name);
400
- if (!item) throw new Error(`No pack named ${name}`);
401
- return Object.fromEntries(
402
- item.files.map((file) => [file.target ?? file.path, file.content]),
403
- );
404
- }