@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
@@ -5,13 +5,18 @@ import {
5
5
  type AdministratorAccess,
6
6
  administratorCaller,
7
7
  } from "../identity/administrator-routes.js";
8
- import type { InstallTarget } from "../workers/install-script.js";
9
- import type { MachineClass } from "../workers/machine-classes.js";
10
- import type { MachineReconciler } from "../workers/machine-rules.js";
8
+ import type { WorkMachines } from "../machines/work-machines.js";
11
9
  import { WorkerPlacementSchema } from "../workers/placement.js";
12
- import type { WorkWorkerRegistry } from "../workers/worker-registry.js";
10
+ import {
11
+ isWorkerNode,
12
+ WORKER_NODE_PREFIX,
13
+ type WorkWorkerRegistry,
14
+ } from "../workers/worker-registry.js";
13
15
  import { verifyWorkOperatorSecret } from "./operator-access.js";
14
16
 
17
+ /** A placement's fields as written: each is optional in a request. */
18
+ const PlacementInput = WorkerPlacementSchema.partial();
19
+
15
20
  const MachineParams = z.object({ nodeId: z.string().min(1) });
16
21
  const MachineUpdate = z.strictObject({ enabled: z.boolean() });
17
22
 
@@ -23,12 +28,10 @@ export interface MachineManagement {
23
28
  publicBase: string;
24
29
  tenantId: string;
25
30
  authorityId: string;
26
- /** Machine classes (ADR 0205), to check pooled enrollments. */
27
- classes: Readonly<Record<string, MachineClass>>;
28
- /** What machines install, for the printed install command. */
29
- install: { target: InstallTarget } | { unavailable: string };
30
- /** Machine rules, when classes or a provisioner are configured. */
31
- machines?: MachineReconciler;
31
+ /** The sequencer, when the host passed a machines hook (ADR 0349). */
32
+ machines?: WorkMachines;
33
+ /** The account a verified email names, for `for: [{ email }]`. */
34
+ userIdForEmail(email: string): Promise<string | undefined>;
32
35
  }
33
36
 
34
37
  type Handler = (
@@ -74,9 +77,9 @@ export function registerMachineSetup(
74
77
  }
75
78
 
76
79
  /**
77
- * Organization administrators manage workers and machine rules through the
78
- * public API as the operator does on the loopback listener (ADR 0205), with
79
- * the same handlers.
80
+ * Organization administrators manage machines through the public API as
81
+ * the operator does on the loopback listener (ADR 0205), with the same
82
+ * handlers.
80
83
  */
81
84
  export function registerMachineAdministration(
82
85
  args: MachineManagement & AdministratorAccess & { app: FastifyInstance },
@@ -102,27 +105,41 @@ export function registerMachineAdministration(
102
105
  });
103
106
  }
104
107
 
108
+ /**
109
+ * Whom a machine is for, as an operator writes it: principals, where a
110
+ * person may be named by the email they sign in with.
111
+ */
112
+ const PrincipalsInput = z
113
+ .array(
114
+ z.union([z.strictObject({ email: z.email().toLowerCase() }), z.unknown()]),
115
+ )
116
+ .max(500);
117
+
105
118
  function machineRoutes(args: MachineManagement): MachineRoute[] {
106
- // Machine rules: dedicated or shared machines per directory group.
107
- const withRules = async (
108
- reply: FastifyReply,
109
- run: (machines: MachineReconciler) => Promise<unknown>,
110
- ) => {
111
- if (!args.machines)
112
- return reply.status(409).send({
113
- error:
114
- "Machine rules need machine classes: set WORK_MACHINES_CONFIG, or extend the Work server with the machineProvisioner hook",
115
- });
116
- try {
117
- return await run(args.machines);
118
- } catch (error) {
119
- return reply
120
- .status(400)
121
- .send({ error: errorMessage(error, "Machine rules failed") });
119
+ /** `{ email }` entries become `{ user }`; an unknown email is refused. */
120
+ const principals = async (value: unknown): Promise<unknown> => {
121
+ const list = PrincipalsInput.parse(value);
122
+ const resolved: unknown[] = [];
123
+ for (const entry of list) {
124
+ const named = z
125
+ .strictObject({ email: z.email().toLowerCase() })
126
+ .safeParse(entry);
127
+ if (!named.success) {
128
+ resolved.push(entry);
129
+ continue;
130
+ }
131
+ const user = await args.userIdForEmail(named.data.email);
132
+ if (!user)
133
+ throw new Error(
134
+ `No account with the verified email ${named.data.email} has signed in to this server`,
135
+ );
136
+ resolved.push({ user });
122
137
  }
138
+ return resolved;
123
139
  };
124
140
  return [
125
- // Remote workers (ADR 0164): enroll with a one-time code, list, revoke.
141
+ // Machines enrolled by hand (ADRs 0164, 0349): enroll with a one-time
142
+ // code, list, revoke. The machines hook's own machines enroll themselves.
126
143
  {
127
144
  method: "POST",
128
145
  operator: "/_work/operator/workers",
@@ -133,44 +150,26 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
133
150
  name: z.string().min(1),
134
151
  ttlMinutes: z.number().int().positive().max(1440).optional(),
135
152
  labels: z.unknown().optional(),
136
- access: z.unknown().optional(),
153
+ for: z.unknown().optional(),
137
154
  trusted: z.boolean().optional(),
138
- /** A pooled machine rules assign (ADR 0205). */
139
- pool: z.boolean().optional(),
140
155
  })
141
156
  .safeParse(request.body);
142
157
  if (!body.success)
143
158
  return reply.status(400).send({ error: firstIssue(body.error) });
144
- const { labels, access, trusted, pool, ...rest } = body.data;
145
- if (pool && (access !== undefined || trusted !== undefined))
146
- return reply.status(400).send({
147
- error:
148
- "A pooled machine takes no work until a machine rule assigns it; leave out access and trusted",
149
- });
150
- const placement = WorkerPlacementSchema.safeParse({
151
- ...(labels === undefined ? {} : { labels }),
152
- ...(access === undefined ? {} : { access }),
153
- ...(trusted === undefined ? {} : { trusted }),
154
- });
155
- if (!placement.success)
156
- return reply.status(400).send({ error: firstIssue(placement.error) });
157
- if (pool) {
158
- const poolClass = placement.data.labels.class;
159
- const pools = Object.entries(args.classes)
160
- .filter(([, machineClass]) => machineClass.platform === "pool")
161
- .map(([name]) => name);
162
- if (!poolClass || !pools.includes(poolClass))
163
- return reply.status(400).send({
164
- error: `A pooled machine needs labels.class naming a pool class (${
165
- pools.join(", ") || "none configured in WORK_MACHINES_CONFIG"
166
- })`,
167
- });
168
- }
159
+ const { labels, trusted, ...rest } = body.data;
169
160
  try {
170
161
  const enrollment = await args.workers.createEnrollment({
171
- ...rest,
172
- placement: placement.data,
173
- ...(pool ? { pool } : {}),
162
+ name: rest.name,
163
+ ...(rest.ttlMinutes === undefined
164
+ ? {}
165
+ : { ttlMinutes: rest.ttlMinutes }),
166
+ placement: placementInput({
167
+ labels,
168
+ trusted,
169
+ ...(rest.for === undefined
170
+ ? {}
171
+ : { for: await principals(rest.for) }),
172
+ }),
174
173
  });
175
174
  return reply.status(201).send({
176
175
  ...enrollment,
@@ -179,11 +178,6 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
179
178
  // configuration, never to a chat or a repository.
180
179
  start:
181
180
  "WORK_CONTROL_PLANE_URL=<url> WORK_WORKER_ENROLLMENT=<code> bun apps/server/src/worker.ts",
182
- ...("target" in args.install
183
- ? {
184
- install: `curl -fsSL ${args.install.target.controlPlaneUrl}/api/workers/install.sh | sudo sh -s -- --code ${enrollment.code}`,
185
- }
186
- : {}),
187
181
  });
188
182
  } catch (error) {
189
183
  return reply
@@ -192,13 +186,21 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
192
186
  }
193
187
  },
194
188
  },
189
+ // Every machine Work knows, made by the machines hook or enrolled by
190
+ // hand, with what the latest plan said.
195
191
  {
196
192
  method: "GET",
197
193
  operator: "/_work/operator/workers",
198
194
  admin: "/api/work/machines/workers",
199
- handler: async () => ({ workers: await args.workers.list() }),
195
+ handler: async () => ({
196
+ workers: await args.workers.list(),
197
+ plan: {
198
+ configured: Boolean(args.machines),
199
+ ...(await args.workers.machines.plan()),
200
+ },
201
+ }),
200
202
  },
201
- // Whose work a worker takes and its labels (ADR 0167).
203
+ // Whom a machine enrolled by hand is for, and its labels (ADR 0349).
202
204
  {
203
205
  method: "PATCH",
204
206
  operator: "/_work/operator/workers/:name",
@@ -210,21 +212,25 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
210
212
  const body = z
211
213
  .strictObject({
212
214
  labels: z.unknown().optional(),
213
- access: z.unknown().optional(),
215
+ for: z.unknown().optional(),
214
216
  trusted: z.boolean().optional(),
215
217
  })
216
218
  .safeParse(request.body);
217
219
  if (!params.success || !body.success)
218
220
  return reply
219
221
  .status(400)
220
- .send({ error: "Provide labels, access, or trusted" });
222
+ .send({ error: "Provide labels, for, or trusted" });
221
223
  try {
222
224
  return {
223
225
  placement: await args.workers.setPlacement({
224
226
  name: params.data.name,
225
- placement: Object.fromEntries(
226
- Object.entries(body.data).filter(([, v]) => v !== undefined),
227
- ),
227
+ placement: placementInput({
228
+ labels: body.data.labels,
229
+ trusted: body.data.trusted,
230
+ ...(body.data.for === undefined
231
+ ? {}
232
+ : { for: await principals(body.data.for) }),
233
+ }),
228
234
  }),
229
235
  };
230
236
  } catch (error) {
@@ -261,55 +267,34 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
261
267
  .safeParse(request.params);
262
268
  if (!params.success)
263
269
  return reply.status(400).send({ error: "Provide a worker name" });
264
- return (await args.workers.revoke(params.data))
270
+ const revoked = await args.workers.revoke(params.data);
271
+ // The plan replaces a machine it still names.
272
+ if (revoked) args.machines?.passSoon();
273
+ return revoked
265
274
  ? { ok: true }
266
275
  : reply.status(404).send({ error: "Worker not found" });
267
276
  },
268
277
  },
269
- {
270
- method: "GET",
271
- operator: "/_work/operator/machine-rules",
272
- admin: "/api/work/machines/rules",
273
- handler: (_request, reply) =>
274
- withRules(reply, async (machines) => ({
275
- rules: await machines.rules(),
276
- status: await machines.status(),
277
- })),
278
- },
279
- {
280
- method: "PUT",
281
- operator: "/_work/operator/machine-rules/:name",
282
- admin: "/api/work/machines/rules/:name",
283
- // The rule is stored when this answers; a pass starts at once and
284
- // reports through the rule's status.
285
- handler: (request, reply) =>
286
- withRules(reply, async (machines) => {
287
- const { name } = z.object({ name: z.string() }).parse(request.params);
288
- const rule = await machines.setRule({ name, rule: request.body });
289
- machines.reconcileSoon();
290
- return { rule };
291
- }),
292
- },
293
- {
294
- method: "DELETE",
295
- operator: "/_work/operator/machine-rules/:name",
296
- admin: "/api/work/machines/rules/:name",
297
- handler: (request, reply) =>
298
- withRules(reply, async (machines) => {
299
- const { name } = z.object({ name: z.string() }).parse(request.params);
300
- if (!(await machines.deleteRule(name)))
301
- return reply.status(404).send({ error: "Rule not found" });
302
- machines.reconcileSoon();
303
- return { ok: true };
304
- }),
305
- },
306
- // A pass now, answered with what it did.
278
+ // Plan now (ADR 0349): ask the machines hook and act on its answer,
279
+ // answered with what the pass did.
307
280
  {
308
281
  method: "POST",
309
- operator: "/_work/operator/machine-rules/reconcile",
310
- admin: "/api/work/machines/rules/reconcile",
311
- handler: (_request, reply) =>
312
- withRules(reply, (machines) => machines.reconcile()),
282
+ operator: "/_work/operator/machines/plan",
283
+ admin: "/api/work/machines/plan",
284
+ handler: async (_request, reply) => {
285
+ if (!args.machines)
286
+ return reply.status(409).send({
287
+ error:
288
+ "This server makes no machines: pass a machines hook to createWorkServer (hooks.machines), or enroll machines by hand",
289
+ });
290
+ try {
291
+ return await args.machines.pass();
292
+ } catch (error) {
293
+ return reply
294
+ .status(500)
295
+ .send({ error: errorMessage(error, "The machine pass failed") });
296
+ }
297
+ },
313
298
  },
314
299
  {
315
300
  method: "GET",
@@ -376,11 +361,20 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
376
361
  return reply
377
362
  .status(400)
378
363
  .send({ error: "Provide a machine id and enabled state" });
379
- const changed = await args.nodes.setEnabled({
380
- ...args,
381
- nodeId: params.data.nodeId,
382
- enabled: body.data.enabled,
383
- });
364
+ // A worker's machine remembers that an operator disabled it, so
365
+ // it is never called lost and stays off when resumed (ADR 0349).
366
+ const { nodeId } = params.data;
367
+ const changed = isWorkerNode(nodeId)
368
+ ? await args.workers.setDisabled({
369
+ name: nodeId.slice(WORKER_NODE_PREFIX.length),
370
+ disabled: !body.data.enabled,
371
+ })
372
+ : await args.nodes.setEnabled({
373
+ ...args,
374
+ nodeId,
375
+ enabled: body.data.enabled,
376
+ });
377
+ if (changed) args.machines?.passSoon();
384
378
  if (!changed)
385
379
  return reply.status(404).send({ error: "Machine not found" });
386
380
  return { ok: true };
@@ -389,6 +383,19 @@ function machineRoutes(args: MachineManagement): MachineRoute[] {
389
383
  ];
390
384
  }
391
385
 
386
+ /** A placement as the registry parses it, with only what was given. */
387
+ function placementInput(input: {
388
+ labels?: unknown;
389
+ for?: unknown;
390
+ trusted?: boolean | undefined;
391
+ }): z.input<typeof PlacementInput> {
392
+ return PlacementInput.parse(
393
+ Object.fromEntries(
394
+ Object.entries(input).filter(([, value]) => value !== undefined),
395
+ ),
396
+ );
397
+ }
398
+
392
399
  function errorMessage(error: unknown, fallback: string): string {
393
400
  return error instanceof z.ZodError
394
401
  ? firstIssue(error)
@@ -1,6 +1,10 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { appGuestCsp, buildAppGuestDocument } from "@catamorphic/app";
3
- import type { CatamorphicCore, Identity } from "@catamorphic/core";
3
+ import {
4
+ type CatamorphicCore,
5
+ hasTokenScope,
6
+ type Identity,
7
+ } from "@catamorphic/core";
4
8
  import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
5
9
  import { micromark } from "micromark";
6
10
  import { z } from "zod";
@@ -49,6 +53,18 @@ export function registerShareRoutes(
49
53
  ) => {
50
54
  const identity = await options.caller(request);
51
55
  if (!identity) return reply.status(401).send({ error: "Unauthorized" });
56
+ const scope =
57
+ request.method === "GET" || !hasTokenScope(identity, "work:read")
58
+ ? "work:read"
59
+ : "program:publish";
60
+ if (!hasTokenScope(identity, scope))
61
+ return reply
62
+ .status(403)
63
+ .header(
64
+ "www-authenticate",
65
+ `Bearer error="insufficient_scope", scope="${scope}"`,
66
+ )
67
+ .send({ error: `This needs the ${scope} scope.` });
52
68
  const { projectId } = request.params as { projectId: string };
53
69
  try {
54
70
  return await run(identity, projectId);
package/src/testing.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Testing a machines hook (ADR 0349): `@catamorphic/work-server/testing`.
3
+ * The contract kit runs a hook against a simulated Work with a fake clock;
4
+ * `SimulatedWork` is that simulation, for a host's own scenarios.
5
+ */
6
+ export {
7
+ type ContractFacts,
8
+ checkMachineProvisioner,
9
+ checkMachinesHook,
10
+ type MachineProvisioner,
11
+ MachinesContractError,
12
+ MemoryCloud,
13
+ type MemoryCloudMachine,
14
+ machinesHook,
15
+ type PlatformProbe,
16
+ } from "./machines/contract-kit.js";
17
+ export {
18
+ quietSummary,
19
+ type SimulatedCall,
20
+ SimulatedWork,
21
+ type SimulatedWorkOptions,
22
+ } from "./machines/simulation.js";
@@ -0,0 +1,121 @@
1
+ import {
2
+ type DiskFloorDefault,
3
+ describeDisk,
4
+ diskLow,
5
+ type MachineDisk,
6
+ measureDisk,
7
+ type SandboxProvider,
8
+ } from "@catamorphic/sandbox";
9
+
10
+ /** How often a machine measures its disk (ADR 0336). */
11
+ export const DISK_MEASURE_INTERVAL_MS = 30_000;
12
+ /** How often it removes what Work left that nothing uses. */
13
+ export const DISK_CLEAN_INTERVAL_MS = 60 * 60_000;
14
+ /** How soon it cleans again while it is under its floor. */
15
+ export const DISK_LOW_CLEAN_INTERVAL_MS = 10 * 60_000;
16
+
17
+ export interface DiskCare {
18
+ /** The latest measurement, if any filesystem could be measured. */
19
+ latest(): MachineDisk | undefined;
20
+ /** Measure now; the first measurement is ready once this resolves. */
21
+ measure(): Promise<MachineDisk | undefined>;
22
+ stop(): void;
23
+ }
24
+
25
+ /**
26
+ * A machine's care of its disk (ADR 0336): it measures the filesystems its
27
+ * provider writes to every 30 seconds (not the rest of its data folder,
28
+ * such as a database, which Work's cleanup cannot free), keeping the one
29
+ * with the least room above its floor for the machine to report, and
30
+ * removes what its provider left that nothing used for `graceMs`: once at
31
+ * start, then hourly, and at once (at most every 10 minutes) while under
32
+ * its floor.
33
+ */
34
+ export function startDiskCare(args: {
35
+ provider: Pick<SandboxProvider, "disk">;
36
+ /** `WORK_DISK_FLOOR_MB`; the default floor when absent. */
37
+ floorMb?: number;
38
+ /** `WORK_DISK_CRITICAL_MB`; the default critical floor when absent. */
39
+ criticalMb?: number;
40
+ /** The floor kept when `floorMb` is absent (ADR 0336); `workspaces` when absent. */
41
+ defaultFloor?: DiskFloorDefault;
42
+ /** `WORK_IMAGE_RETENTION_HOURS`, in milliseconds. */
43
+ graceMs: number;
44
+ measureEveryMs?: number;
45
+ cleanEveryMs?: number;
46
+ lowCleanEveryMs?: number;
47
+ log?: (line: string) => void;
48
+ /** For tests: measure as {@link measureDisk} does. */
49
+ measureDisk?: typeof measureDisk;
50
+ }): DiskCare {
51
+ const measure = args.measureDisk ?? measureDisk;
52
+ let latest: MachineDisk | undefined;
53
+ let wasLow = false;
54
+ let stopped = false;
55
+ let lastClean = Number.NEGATIVE_INFINITY;
56
+ let cleaning: Promise<void> | undefined;
57
+ const clean = (): void => {
58
+ const run = args.provider.disk?.clean;
59
+ if (!run || cleaning || stopped) return;
60
+ lastClean = Date.now();
61
+ cleaning = run({ graceMs: args.graceMs })
62
+ .then((lines) => {
63
+ for (const line of lines) args.log?.(line);
64
+ })
65
+ .catch((error: unknown) =>
66
+ args.log?.(
67
+ `Removing what Work left on this machine failed: ${error instanceof Error ? error.message : String(error)}`,
68
+ ),
69
+ )
70
+ .finally(() => {
71
+ cleaning = undefined;
72
+ });
73
+ };
74
+ const once = async (): Promise<MachineDisk | undefined> => {
75
+ const paths = (await args.provider.disk?.paths().catch(() => [])) ?? [];
76
+ const measured = measure({
77
+ paths,
78
+ ...(args.floorMb !== undefined ? { floorMb: args.floorMb } : {}),
79
+ ...(args.criticalMb !== undefined ? { criticalMb: args.criticalMb } : {}),
80
+ ...(args.defaultFloor ? { defaultFloor: args.defaultFloor } : {}),
81
+ });
82
+ if (stopped) return latest;
83
+ latest = measured;
84
+ const low = measured ? diskLow(measured) : false;
85
+ if (measured && low !== wasLow)
86
+ args.log?.(
87
+ low
88
+ ? `This machine is short of disk (${describeDisk(measured)} at ${measured.path}); it takes no new workspaces until there is room`
89
+ : `This machine has room on its disk again (${describeDisk(measured)})`,
90
+ );
91
+ wasLow = low;
92
+ const due = low
93
+ ? (args.lowCleanEveryMs ?? DISK_LOW_CLEAN_INTERVAL_MS)
94
+ : (args.cleanEveryMs ?? DISK_CLEAN_INTERVAL_MS);
95
+ if (Date.now() - lastClean >= due) clean();
96
+ return measured;
97
+ };
98
+ let measuring: Promise<MachineDisk | undefined> | undefined;
99
+ const measureNow = (): Promise<MachineDisk | undefined> => {
100
+ measuring ??= once()
101
+ .catch(() => latest)
102
+ .finally(() => {
103
+ measuring = undefined;
104
+ });
105
+ return measuring;
106
+ };
107
+ void measureNow();
108
+ const timer = setInterval(
109
+ () => void measureNow(),
110
+ args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS,
111
+ );
112
+ timer.unref();
113
+ return {
114
+ latest: () => latest,
115
+ measure: measureNow,
116
+ stop: () => {
117
+ stopped = true;
118
+ clearInterval(timer);
119
+ },
120
+ };
121
+ }
@@ -17,6 +17,15 @@
17
17
  * the machine and no `ANTHROPIC_BASE_URL`) it calls no model: it runs the command of a
18
18
  * `run: <command>` line itself, and otherwise answers with a report of the
19
19
  * credentials it was given, so tests see what reached the CLI.
20
+ *
21
+ * `claude auth login` signs a member in as Claude Code 2.1.329 does with
22
+ * no terminal (ADR 0342): it prints "If the browser didn't open, visit:
23
+ * <link>" and "Paste code here if prompted > ", reads one line from its
24
+ * input, and on the expected code (`FAKE_CLAUDE_LOGIN_CODE`, else
25
+ * {@link LOGIN_CODE}) writes `.credentials.json` into `CLAUDE_CONFIG_DIR`
26
+ * holding `FAKE_CLAUDE_ACCESS_TOKEN`. A wrong code fails, repeating what it
27
+ * was given, as a careless CLI might. `claude auth status` prints whether
28
+ * that file is there; `claude auth logout` removes it.
20
29
  */
21
30
  import { execFileSync, spawnSync } from "node:child_process";
22
31
  import { createHash, randomUUID } from "node:crypto";
@@ -46,6 +55,92 @@ function flag(name: string): string | undefined {
46
55
  return undefined;
47
56
  }
48
57
 
58
+ /** The code the stand-in's sign-in page would give a member. */
59
+ const LOGIN_CODE = "TEST-CLAUDE-CODE#state";
60
+ /** The link `claude auth login` prints, shaped like the real one. */
61
+ const LOGIN_LINK =
62
+ "https://claude.com/cai/oauth/authorize?code=true&client_id=test-client&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&scope=user%3Ainference&code_challenge=test-challenge";
63
+
64
+ /** One line from the input, or undefined when it ended without one. */
65
+ function readLine(): Promise<string | undefined> {
66
+ return new Promise((resolve) => {
67
+ const reader = createInterface({ input: process.stdin });
68
+ reader.once("line", (line) => {
69
+ resolve(line);
70
+ reader.close();
71
+ });
72
+ reader.once("close", () => resolve(undefined));
73
+ });
74
+ }
75
+
76
+ const [command, action] = process.argv.slice(2);
77
+ if (command === "auth") {
78
+ const home =
79
+ process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude");
80
+ const credentials = path.join(home, ".credentials.json");
81
+ if (action === "status") {
82
+ const loggedIn = fs.existsSync(credentials);
83
+ console.log(
84
+ JSON.stringify({
85
+ loggedIn,
86
+ authMethod: loggedIn ? "claude.ai" : "none",
87
+ apiProvider: "firstParty",
88
+ }),
89
+ );
90
+ process.exit(loggedIn ? 0 : 1);
91
+ }
92
+ if (action === "logout") {
93
+ fs.rmSync(credentials, { force: true });
94
+ console.log("Successfully logged out from your Anthropic account.");
95
+ process.exit(0);
96
+ }
97
+ if (action !== "login") {
98
+ console.error(`This stand-in does not do auth ${action ?? ""}`);
99
+ process.exit(2);
100
+ }
101
+ // A login handed another credential is not the member's own sign-in.
102
+ for (const name of [
103
+ "ANTHROPIC_API_KEY",
104
+ "ANTHROPIC_AUTH_TOKEN",
105
+ "ANTHROPIC_BASE_URL",
106
+ "CLAUDE_CODE_OAUTH_TOKEN",
107
+ ])
108
+ if (process.env[name]) {
109
+ console.error(`Error: ${name} is set, so this is not a sign-in`);
110
+ process.exit(3);
111
+ }
112
+ process.stdout.write(
113
+ `Opening browser to sign in…\nIf the browser didn't open, visit: ${LOGIN_LINK}\nPaste code here if prompted > `,
114
+ );
115
+ const code = await readLine();
116
+ if (code === undefined) {
117
+ console.error("Error: no code was entered");
118
+ process.exit(1);
119
+ }
120
+ if (code !== (process.env.FAKE_CLAUDE_LOGIN_CODE ?? LOGIN_CODE)) {
121
+ console.error(`Error: invalid code ${code}`);
122
+ process.exit(1);
123
+ }
124
+ const accessToken =
125
+ process.env.FAKE_CLAUDE_ACCESS_TOKEN ?? "claude-access-test";
126
+ fs.mkdirSync(home, { recursive: true });
127
+ fs.writeFileSync(
128
+ credentials,
129
+ JSON.stringify({
130
+ claudeAiOauth: {
131
+ accessToken,
132
+ refreshToken: `refresh-${accessToken}`,
133
+ expiresAt: Date.now() + 8 * 60 * 60_000,
134
+ scopes: ["user:inference"],
135
+ subscriptionType: "max",
136
+ },
137
+ }),
138
+ { mode: 0o600 },
139
+ );
140
+ console.log("Login successful.");
141
+ process.exit(0);
142
+ }
143
+
49
144
  const sessionId = flag("--session-id") ?? flag("--resume") ?? randomUUID();
50
145
  const model = flag("--model") ?? "claude-test";
51
146
 
@@ -45,12 +45,19 @@ if (command === "login") {
45
45
  const outcome = path.dirname(path.dirname(home));
46
46
  for (;;) {
47
47
  const approve = path.join(outcome, "approve");
48
- if (fs.existsSync(approve)) {
48
+ // A test's write can be seen created but still empty: the approval
49
+ // counts once its token has landed, as a real login issues one.
50
+ const token = (() => {
51
+ try {
52
+ return fs.readFileSync(approve, "utf8").trim();
53
+ } catch {
54
+ return "";
55
+ }
56
+ })();
57
+ if (token) {
49
58
  fs.writeFileSync(
50
59
  path.join(home, "auth.json"),
51
- JSON.stringify({
52
- tokens: { access_token: fs.readFileSync(approve, "utf8").trim() },
53
- }),
60
+ JSON.stringify({ tokens: { access_token: token } }),
54
61
  { mode: 0o600 },
55
62
  );
56
63
  console.log("Successfully logged in");