@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
package/src/server.ts CHANGED
@@ -6,10 +6,14 @@ import type { AgentCapabilityOptions } from "@catamorphic/core";
6
6
  import {
7
7
  type ConnectionActionGuard,
8
8
  type ConnectionProvider,
9
+ FULL_TOKEN_SCOPE,
10
+ hasTokenScope,
9
11
  type Identity,
10
12
  type ModelRequestRewrite,
11
13
  startEventDispatcher,
14
+ tokenScopesOf,
12
15
  WorkerNodesService,
16
+ withTokenScopes,
13
17
  } from "@catamorphic/core";
14
18
  import {
15
19
  createDatabase,
@@ -24,10 +28,6 @@ import {
24
28
  instrumentHttpServer,
25
29
  serveSpaDist,
26
30
  } from "@catamorphic/fastify-plugin";
27
- import {
28
- type HetznerCloudClientOptions,
29
- HetznerCloudMachines,
30
- } from "@catamorphic/hetzner";
31
31
  import { gatewayHostOf, MACHINE_CAPABILITIES } from "@catamorphic/sandbox";
32
32
  import {
33
33
  aiToolCall,
@@ -44,6 +44,8 @@ import {
44
44
  FsBundleStore,
45
45
  type GithubConnectionOptions,
46
46
  githubCodeHost,
47
+ MACHINE_TRIGGER_KINDS,
48
+ machineProjectEvent,
47
49
  ObjectRemoteBackend,
48
50
  PostgresObjectStore,
49
51
  ProjectManager,
@@ -95,6 +97,12 @@ import { registerAdministratorRoutes } from "./identity/administrator-routes.js"
95
97
  import { WorkAdministrators } from "./identity/administrators.js";
96
98
  import type { DirectoryProvider } from "./identity/directory.js";
97
99
  import { GoogleWorkspaceDirectory } from "./identity/google-directory.js";
100
+ import type {
101
+ MachineEvent,
102
+ MachinesHook,
103
+ PersonFacts,
104
+ } from "./machines/contract.js";
105
+ import { WorkMachines, workMachineWorld } from "./machines/work-machines.js";
98
106
  import { registerConnectionSetup } from "./setup/connections.js";
99
107
  import { registerGithubAppSetup } from "./setup/github-app.js";
100
108
  import {
@@ -118,19 +126,8 @@ import {
118
126
  import { registerShareRoutes } from "./shares/share-routes.js";
119
127
  import { shareTools } from "./shares/share-tools.js";
120
128
  import { WorkSharesService } from "./shares/shares-service.js";
121
- import { CodexSignIns } from "./workers/codex-sign-ins.js";
122
- import {
123
- installTarget,
124
- registerInstallScriptRoute,
125
- } from "./workers/install-script.js";
126
- import {
127
- MachinesConfigSchema,
128
- machineClassesProblem,
129
- } from "./workers/machine-classes.js";
130
- import {
131
- type MachineProvisioner,
132
- MachineReconciler,
133
- } from "./workers/machine-rules.js";
129
+ import { startDiskCare } from "./workers/disk-care.js";
130
+ import { HarnessSignIns } from "./workers/harness-sign-ins.js";
134
131
  import { registerMemberMachineRoutes } from "./workers/member-machine-routes.js";
135
132
  import { MemberMachines } from "./workers/member-machines.js";
136
133
  import { signInCapabilities } from "./workers/sign-ins.js";
@@ -169,6 +166,13 @@ export interface WorkServerHooks {
169
166
  * connects.
170
167
  */
171
168
  github?: GithubConnectionOptions;
169
+ /**
170
+ * Host code run when a project is created and deleted (ADRs 0046, 0331):
171
+ * provision what the project needs (a schema, a bucket) and return its
172
+ * credentials as project secrets, then clean it up on delete. Work
173
+ * retries a cleanup until it reports done.
174
+ */
175
+ projectHooks?: CreateCatamorphicConfig["projectHooks"];
172
176
  /** Replace or extend the files seeded into new projects (ADR 0049). */
173
177
  projectSeeds?: (
174
178
  defaults: Readonly<Record<string, string>>,
@@ -199,16 +203,14 @@ export interface WorkServerHooks {
199
203
  */
200
204
  directories?: readonly DirectoryProvider[];
201
205
  /**
202
- * Creates and destroys worker machines on a platform Work does not ship,
203
- * for `custom` machine classes (ADRs 0167, 0205). With no classes
204
- * configured, every class a rule names is custom.
205
- */
206
- machineProvisioner?: MachineProvisioner;
207
- /**
208
- * Hetzner Cloud API options for `hetzner-cloud` classes: another
209
- * endpoint, or a `fetch` for tests. The token is `config.hetznerToken`.
206
+ * The host's machines (ADR 0349): `plan` decides which machines should
207
+ * exist from the facts Work gives it, and `create`, `destroy`, `stop`,
208
+ * `start` and `describe` are the calls that touch the host's cloud.
209
+ * Work sequences them and keeps them safe; it integrates with no cloud
210
+ * and no directory itself. Recipes for common clouds and policies are
211
+ * registry packs. With no hook, machines are enrolled by hand.
210
212
  */
211
- hetzner?: Omit<HetznerCloudClientOptions, "token">;
213
+ machines?: MachinesHook;
212
214
  /** Mount additional host routes on the public application. */
213
215
  routes?: (args: {
214
216
  app: FastifyInstance;
@@ -305,16 +307,6 @@ async function createWorkServerInner(
305
307
  "Postgres deployments require the same WORK_SECRET on every instance",
306
308
  );
307
309
  }
308
- // Machine classes (ADR 0205) need what their platforms need.
309
- const machineClasses = config.machines
310
- ? MachinesConfigSchema.parse(config.machines).classes
311
- : {};
312
- const machinesProblem = machineClassesProblem({
313
- classes: machineClasses,
314
- hetznerToken: Boolean(config.hetznerToken),
315
- provisioner: Boolean(hooks.machineProvisioner),
316
- });
317
- if (machinesProblem) throw new Error(machinesProblem);
318
310
  // Every replica must answer the same loopback operator credential; one
319
311
  // generated into a replica's disposable data directory would not.
320
312
  if (config.databaseUrl && !config.operatorSecret) {
@@ -422,6 +414,26 @@ async function createWorkServerInner(
422
414
  log,
423
415
  });
424
416
  disposers.push(async () => stopVolumePruning());
417
+ // This machine measures its disk and removes what Work left (ADR 0336).
418
+ // Run as local processes, its work shares one disk with the server's
419
+ // database and its people's files, where holding chats back frees
420
+ // nothing: it keeps only the critical floor unless the operator sets one.
421
+ // Sandboxes many workspaces share keep the full floor, as workers do.
422
+ const diskCare = startDiskCare({
423
+ provider: sandboxProvider,
424
+ defaultFloor:
425
+ resolvedExecution.backend === "local-process" ? "critical" : "workspaces",
426
+ ...(execution.diskFloorMb !== undefined
427
+ ? { floorMb: execution.diskFloorMb }
428
+ : {}),
429
+ ...(execution.diskCriticalMb !== undefined
430
+ ? { criticalMb: execution.diskCriticalMb }
431
+ : {}),
432
+ graceMs: execution.imageRetentionMs,
433
+ log,
434
+ });
435
+ disposers.push(async () => diskCare.stop());
436
+ await diskCare.measure();
425
437
  if (!ownDb) throw new Error("Database was not initialized");
426
438
  await migrateToLatest({ db: ownDb });
427
439
  const objectStore = config.databaseUrl
@@ -494,15 +506,15 @@ async function createWorkServerInner(
494
506
  );
495
507
  }
496
508
  }
497
- // Who owns a piece of work, for worker access (ADR 0167): their email and
498
- // directory groups. Sign-in is set up below; placement runs only later.
499
- let placementOwner: (
500
- userId: string,
501
- ) => Promise<{ userId: string; groups: string[] } | undefined> = async () =>
502
- undefined;
503
509
  // A worker that connects may take chats waiting for a machine (ADR
504
510
  // 0258): this process's agent sweep hears it once the core is up.
505
511
  let workerConnected = () => {};
512
+ // Work retired from a machine that is gone (ADR 0348) is admitted again
513
+ // by the same sweep.
514
+ let workRetired = () => {};
515
+ // Something happened to a machine (ADR 0349): delivered once the core
516
+ // is up, to the projects it is for and to the host's own listener.
517
+ let machineEvent: (event: MachineEvent) => Promise<void> = async () => {};
506
518
  // Enrolled remote workers (ADR 0164). Each worker owns its node lease
507
519
  // (ADR 0192), so any replica serves its calls and runs its agents.
508
520
  const workers = new WorkWorkerRegistry({
@@ -510,7 +522,11 @@ async function createWorkServerInner(
510
522
  nodes: new WorkerNodesService(ownDb),
511
523
  tenantId: SERVER_TENANT_ID,
512
524
  authorityId: hostId,
525
+ // Every replica derives the same enrollment codes (ADR 0349).
526
+ enrollmentSecret: authSecret,
513
527
  connected: () => workerConnected(),
528
+ retired: () => workRetired(),
529
+ event: (event) => machineEvent(event),
514
530
  log,
515
531
  });
516
532
  // A single person's server whose operator accepted personal credentials
@@ -536,11 +552,9 @@ async function createWorkServerInner(
536
552
  backend: execution.backend,
537
553
  signIns: () => signInCapabilities(execution.signInRoot),
538
554
  ownSignIns: singleServerSignIns,
555
+ disk: () => diskCare.latest(),
539
556
  sandboxProvider,
540
- placement: {
541
- workers: () => workers.placements(),
542
- owner: (userId) => placementOwner(userId),
543
- },
557
+ placement: { workers: () => workers.placements() },
544
558
  });
545
559
  disposers.push(() => machine.stop());
546
560
  let maintaining: Promise<void> | undefined;
@@ -578,9 +592,17 @@ async function createWorkServerInner(
578
592
  );
579
593
  const catamorphic = createCatamorphic({
580
594
  hostId,
595
+ // The chat as the web client opens it, for whoever is handed its state.
596
+ ...(isLoopbackBase(publicBase)
597
+ ? {}
598
+ : {
599
+ sessionUrl: (chat: { projectId: string; sessionId: string }) =>
600
+ `${publicBase}/?project=${encodeURIComponent(chat.projectId)}&session=${encodeURIComponent(chat.sessionId)}`,
601
+ }),
581
602
  ...(hooks.capabilityProviders
582
603
  ? { capabilityProviders: hooks.capabilityProviders }
583
604
  : {}),
605
+ ...(hooks.projectHooks ? { projectHooks: hooks.projectHooks } : {}),
584
606
  agentCapabilities: workAgentCapabilities({
585
607
  core: () => catamorphic.core,
586
608
  auth: () => workAuth,
@@ -607,6 +629,13 @@ async function createWorkServerInner(
607
629
  memberIdForEmail: ({ email }) =>
608
630
  verifiedUserIdForEmail({ auth: workAuth, email }),
609
631
  workerNode: machine.lease,
632
+ // A cache copy nobody mounted is evicted when its volume would be
633
+ // pruned (ADR 0334).
634
+ caches: {
635
+ retentionDays: Math.round(
636
+ execution.volumeRetentionMs / (24 * 60 * 60 * 1000),
637
+ ),
638
+ },
610
639
  clientExecution: true,
611
640
  database: databaseConfig,
612
641
  storage: objectStore
@@ -652,6 +681,12 @@ async function createWorkServerInner(
652
681
  connectionMcpUrl: () => `${publicBase}/api/connection-mcp`,
653
682
  // Sandboxes with restricted egress still reach the gateway (ADR 0176).
654
683
  gatewayHosts: config.publicBases.map((base) => gatewayHostOf(base)),
684
+ // A host that makes machines for waiting work lets a new chat wait for
685
+ // its machine instead of failing at once (ADR 0349); a project's own
686
+ // `waitMinutes` still bounds its Environment.
687
+ ...(hooks.machines
688
+ ? { placementWaitMinutes: config.machineWaitMinutes ?? 30 }
689
+ : {}),
655
690
  gatewayUrl: () => `${publicBase}/api/gateway`,
656
691
  ...(agents.registry ? { codingAgent: agents.registry } : {}),
657
692
  appBundleStore:
@@ -666,6 +701,8 @@ async function createWorkServerInner(
666
701
  webhook,
667
702
  ...SESSION_TRIGGER_KINDS,
668
703
  ...DIRECTORY_TRIGGER_KINDS,
704
+ // What happens to machines, for projects' own workflows (ADR 0349).
705
+ ...MACHINE_TRIGGER_KINDS,
669
706
  ],
670
707
  // Workflows bound to `ai.tool-call` are tools on the project MCP, for
671
708
  // project agents and members' own MCP clients alike.
@@ -741,6 +778,7 @@ async function createWorkServerInner(
741
778
  disposers.push(() => worker.stop());
742
779
  const core = catamorphic.core;
743
780
  workerConnected = () => core.wakeups.notify("agent");
781
+ workRetired = () => core.wakeups.notify("agent");
744
782
  // Any replica recovers the work of replicas that are gone for good: runs
745
783
  // move to a live machine, chats are admitted again on their next turn.
746
784
  {
@@ -853,68 +891,106 @@ async function createWorkServerInner(
853
891
  tenantId: SERVER_TENANT_ID,
854
892
  publicBase,
855
893
  });
856
- placementOwner = async (userId) => {
857
- const [user, account] = await Promise.all([
858
- workAuth.findUserById({ userId }),
894
+ // A machine event reaches the projects the machine is for, as a project
895
+ // event their workflows may trigger on, and the host's own listener.
896
+ // Work itself depends on neither (ADR 0349).
897
+ machineEvent = async (event) => {
898
+ const projects = new Set(
899
+ (event.machine.for ?? []).flatMap((principal) =>
900
+ "project" in principal ? [principal.project] : [],
901
+ ),
902
+ );
903
+ const record = machineProjectEvent({
904
+ kind: event.kind,
905
+ at: event.at,
906
+ machine: {
907
+ ...event.machine,
908
+ for: event.machine.for ? [...event.machine.for] : null,
909
+ ...(event.disk ? { disk: event.disk } : {}),
910
+ },
911
+ });
912
+ const failures: unknown[] = [];
913
+ for (const projectId of projects)
914
+ await core.projectEvents
915
+ .append({ projectId, ...record })
916
+ .catch((error: unknown) => failures.push(error));
917
+ await Promise.resolve(hooks.machines?.onEvent?.(event)).catch(
918
+ (error: unknown) => failures.push(error),
919
+ );
920
+ if (failures.length > 0) throw failures[0];
921
+ };
922
+ /** The server's accounts with their project roles, for the plan. */
923
+ const people = async (): Promise<PersonFacts[]> => {
924
+ const [users, accounts, memberships] = await Promise.all([
925
+ workAuth.listUsers(),
859
926
  core.db
860
927
  .selectFrom("work_accounts")
861
- .select("directory_groups")
862
- .where("user_id", "=", userId)
863
- .executeTakeFirst(),
928
+ .select(["user_id", "disabled_at", "administrator"])
929
+ .execute(),
930
+ core.db
931
+ .selectFrom("memberships")
932
+ .select(["external_user_id", "project_id", "roles"])
933
+ .execute(),
864
934
  ]);
865
- const groups = Array.isArray(account?.directory_groups)
866
- ? account.directory_groups.filter(
867
- (group): group is string => typeof group === "string",
868
- )
869
- : [];
870
- return {
871
- userId: user?.email?.toLowerCase() ?? userId,
872
- groups: groups.map((group) => group.toLowerCase()),
873
- };
935
+ const accountOf = new Map(accounts.map((row) => [row.user_id, row]));
936
+ const rolesOf = new Map<string, Record<string, string[]>>();
937
+ for (const row of memberships) {
938
+ const roles = rolesOf.get(row.external_user_id) ?? {};
939
+ roles[row.project_id] = Array.isArray(row.roles)
940
+ ? row.roles.filter((role): role is string => typeof role === "string")
941
+ : [];
942
+ rolesOf.set(row.external_user_id, roles);
943
+ }
944
+ return users
945
+ .map((user) => ({
946
+ id: user.id,
947
+ email: user.emailVerified ? user.email.toLowerCase() : null,
948
+ name: user.name || null,
949
+ active: !accountOf.get(user.id)?.disabled_at,
950
+ administrator: Boolean(accountOf.get(user.id)?.administrator),
951
+ roles: rolesOf.get(user.id) ?? {},
952
+ }))
953
+ .sort((left, right) => left.id.localeCompare(right.id));
874
954
  };
875
- // Every machine installs the same way (ADR 0205): the script this
876
- // server serves, with its public origin and worker image baked in.
877
- const install = installTarget({
878
- publicBase,
879
- ...(config.workerImage ? { workerImage: config.workerImage } : {}),
880
- });
881
- const machineReconciler =
882
- Object.keys(machineClasses).length > 0 || hooks.machineProvisioner
883
- ? new MachineReconciler({
955
+ const workMachines = hooks.machines
956
+ ? new WorkMachines({
957
+ db: core.db,
958
+ tenantId: SERVER_TENANT_ID,
959
+ hook: hooks.machines,
960
+ workers,
961
+ world: workMachineWorld({
884
962
  db: core.db,
885
963
  tenantId: SERVER_TENANT_ID,
886
964
  workers,
887
- classes: machineClasses,
888
- ...(hooks.machineProvisioner
889
- ? { provisioner: hooks.machineProvisioner }
890
- : {}),
891
- ...(config.hetznerToken
892
- ? {
893
- hetzner: new HetznerCloudMachines({
894
- client: { ...hooks.hetzner, token: config.hetznerToken },
895
- }),
896
- }
897
- : {}),
898
- install,
899
965
  controlPlaneUrl: publicBase,
900
- emailOf: async (userId) =>
901
- (await workAuth.findUserById({ userId }))?.email?.toLowerCase(),
902
- log,
903
- })
904
- : undefined;
905
- const reconcileMachines = () => machineReconciler?.reconcileSoon();
906
- if (machineReconciler) {
907
- const machineTimer = setInterval(reconcileMachines, 60_000);
966
+ people,
967
+ event: async (event) => {
968
+ await machineEvent(event).catch((error: unknown) =>
969
+ log(
970
+ `Recording ${event.kind} for machine ${event.machine.name} failed: ${
971
+ error instanceof Error ? error.message : String(error)
972
+ }`,
973
+ ),
974
+ );
975
+ },
976
+ }),
977
+ log,
978
+ })
979
+ : undefined;
980
+ const planMachines = () => workMachines?.passSoon();
981
+ if (workMachines) {
982
+ // A pass every minute, and at once when what a plan reads changed:
983
+ // waiting work, what machines hold, a machine connecting or going
984
+ // unseen, accounts and roles. That is one cheap look every few seconds.
985
+ const machineTimer = setInterval(planMachines, 60_000);
908
986
  machineTimer.unref();
909
- // Machines on demand (ADR 0258): demand is looked at every few seconds
910
- // with one statement, and a pass runs when it changed.
911
987
  let checking: Promise<void> | undefined;
912
- const demandTimer = setInterval(() => {
913
- checking ??= machineReconciler
914
- .checkDemand()
988
+ const checkTimer = setInterval(() => {
989
+ checking ??= workMachines
990
+ .check()
915
991
  .catch((error: unknown) =>
916
992
  log(
917
- `Machine demand check failed: ${
993
+ `Machine check failed: ${
918
994
  error instanceof Error ? error.message : String(error)
919
995
  }`,
920
996
  ),
@@ -923,12 +999,13 @@ async function createWorkServerInner(
923
999
  checking = undefined;
924
1000
  });
925
1001
  }, 10_000);
926
- demandTimer.unref();
1002
+ checkTimer.unref();
1003
+ planMachines();
927
1004
  disposers.push(async () => {
928
1005
  clearInterval(machineTimer);
929
- clearInterval(demandTimer);
1006
+ clearInterval(checkTimer);
930
1007
  await checking;
931
- await machineReconciler.settle();
1008
+ await workMachines.settle();
932
1009
  });
933
1010
  }
934
1011
  const accountLifecycle = new AccountLifecycle({
@@ -939,19 +1016,14 @@ async function createWorkServerInner(
939
1016
  directory: workAuthConfig.directory,
940
1017
  tenantId: SERVER_TENANT_ID,
941
1018
  projectEvents: core.projectEvents,
942
- // Groups that decide roles or whose work a worker takes (ADR 0167).
943
- mappedGroups: async () => [
944
- ...new Set([
945
- ...(await admission.mappedDirectoryGroups()),
946
- ...(await workers.accessGroups()),
947
- ...((await machineReconciler?.groups()) ?? []),
948
- ]),
949
- ],
1019
+ // Groups that decide roles. Machines know no groups: a host that
1020
+ // wants a group's members to have machines expands it in its plan.
1021
+ mappedGroups: () => admission.mappedDirectoryGroups(),
950
1022
  reconcileRoles: (args) => admission.reconcileDirectoryRoles(args),
951
1023
  onDisabled: async ({ userId }) => {
952
1024
  await stopMemberWork({ core, identity: rootIdentity, userId, log });
953
- // A disabled member's dedicated machine goes on the next pass.
954
- reconcileMachines();
1025
+ // The plan hears the account is disabled on its next pass.
1026
+ planMachines();
955
1027
  },
956
1028
  // Guests view shares in the browser; they never hold API tokens.
957
1029
  refuseTokens: async (userId) =>
@@ -1096,17 +1168,34 @@ async function createWorkServerInner(
1096
1168
  if (!authenticated) return null;
1097
1169
  if (!(await accountLifecycle.isActive(authenticated.userId))) return null;
1098
1170
  if (await shares.isGuest(authenticated.userId)) return null;
1099
- return administrators.withPermissions(
1100
- await core.memberships.identityForUser({
1101
- tenantId: SERVER_TENANT_ID,
1102
- externalUserId: authenticated.userId,
1103
- }),
1171
+ // A grant that names none of Work's scopes holds nothing here: its
1172
+ // client signs in again and is asked what it may do.
1173
+ if (tokenScopesOf(authenticated.scopes).length === 0) return null;
1174
+ // A client holds what its person consented to: the member's roles,
1175
+ // narrowed by the grant's scopes (ADR 0347). Only `work:full`, which
1176
+ // Work's own apps ask for, is the person themself.
1177
+ return withTokenScopes(
1178
+ await administrators.withPermissions(
1179
+ await core.memberships.identityForUser({
1180
+ tenantId: SERVER_TENANT_ID,
1181
+ externalUserId: authenticated.userId,
1182
+ }),
1183
+ ),
1184
+ authenticated.scopes,
1104
1185
  );
1105
1186
  };
1106
1187
  const app = createApp({
1107
1188
  core,
1108
1189
  identity: identityFromBearer((token) => memberIdentity(`Bearer ${token}`)),
1109
1190
  features: { publications: "members" },
1191
+ mcp: {
1192
+ // Every replica signs with the deployment's secret, under a label of
1193
+ // its own: a state one replica handed out, another accepts.
1194
+ stateSecret: createHash("sha256")
1195
+ .update(`mcp-request-state:${authSecret}`)
1196
+ .digest("hex"),
1197
+ resourceMetadataUrl: `${publicBase}/.well-known/oauth-protected-resource`,
1198
+ },
1110
1199
  projectMcp: {
1111
1200
  serverInfo: { name: "work", title: "Work" },
1112
1201
  instructions:
@@ -1158,27 +1247,28 @@ async function createWorkServerInner(
1158
1247
  : (authorization ?? ""),
1159
1248
  );
1160
1249
  const resourceMetadata = `${publicBase}/.well-known/oauth-protected-resource`;
1250
+ // The scopes a client should ask for (RFC 6750): reading, and
1251
+ // running chats. Approving is never asked for on its behalf.
1161
1252
  reply.header(
1162
1253
  "www-authenticate",
1163
- `Bearer resource_metadata="${resourceMetadata}"${
1254
+ `Bearer resource_metadata="${resourceMetadata}", scope="${MCP_CHALLENGE_SCOPES.join(" ")}"${
1164
1255
  hasBearer ? ', error="invalid_token"' : ""
1165
1256
  }`,
1166
1257
  );
1167
1258
  done(null, payload);
1168
1259
  });
1169
1260
  registerWorkerRoutes(app, workers);
1170
- registerInstallScriptRoute(app, install);
1171
- // Workers and machine rules: the operator on the loopback listener, and
1172
- // organization administrators through the API (ADR 0205).
1261
+ // Machines: the operator on the loopback listener, and organization
1262
+ // administrators through the API (ADR 0205).
1173
1263
  const machineManagement = {
1174
1264
  nodes: machine.nodes,
1175
1265
  workers,
1176
1266
  tenantId: SERVER_TENANT_ID,
1177
1267
  authorityId: hostId,
1178
1268
  publicBase,
1179
- classes: machineClasses,
1180
- install,
1181
- ...(machineReconciler ? { machines: machineReconciler } : {}),
1269
+ userIdForEmail: async (email: string) =>
1270
+ (await verifiedUserIdForEmail({ auth: workAuth, email })) ?? undefined,
1271
+ ...(workMachines ? { machines: workMachines } : {}),
1182
1272
  };
1183
1273
  registerWorkAuthRoutes(app, {
1184
1274
  auth: workAuth,
@@ -1189,37 +1279,26 @@ async function createWorkServerInner(
1189
1279
  trustedProxies: config.trustedProxies ?? [],
1190
1280
  log,
1191
1281
  });
1282
+ const memberCaller = async (request: FastifyRequest) => {
1283
+ const header = request.headers.authorization;
1284
+ const authorization = Array.isArray(header) ? header[0] : header;
1285
+ return authorization ? memberIdentity(authorization) : null;
1286
+ };
1192
1287
  registerShareRoutes(app, {
1193
1288
  core,
1194
1289
  auth: workAuth,
1195
1290
  shares,
1196
1291
  publicBase,
1197
1292
  isActive: (userId) => accountLifecycle.isActive(userId),
1198
- caller: async (request) => {
1199
- const header = request.headers.authorization;
1200
- const authorization = Array.isArray(header) ? header[0] : header;
1201
- if (!authorization) return null;
1202
- const authenticated = await workAuth.resolveAccessToken({
1203
- authorization,
1204
- });
1205
- if (
1206
- !authenticated ||
1207
- !(await accountLifecycle.isActive(authenticated.userId)) ||
1208
- (await shares.isGuest(authenticated.userId))
1209
- )
1210
- return null;
1211
- return core.memberships.identityForUser({
1212
- tenantId: SERVER_TENANT_ID,
1213
- externalUserId: authenticated.userId,
1214
- });
1215
- },
1293
+ caller: memberCaller,
1216
1294
  });
1217
1295
  const administratorAccess = {
1218
1296
  administrators,
1219
1297
  caller: async (request: FastifyRequest) => {
1220
- const header = request.headers.authorization;
1221
- const authorization = Array.isArray(header) ? header[0] : header;
1222
- return authorization ? memberIdentity(authorization) : null;
1298
+ const identity = await memberCaller(request);
1299
+ return identity && hasTokenScope(identity, FULL_TOKEN_SCOPE)
1300
+ ? identity
1301
+ : null;
1223
1302
  },
1224
1303
  };
1225
1304
  registerAdministratorRoutes(app, administratorAccess);
@@ -1228,12 +1307,12 @@ async function createWorkServerInner(
1228
1307
  ...administratorAccess,
1229
1308
  ...machineManagement,
1230
1309
  });
1231
- // Members sign in to Codex on machines of their own from the app (ADR
1232
- // 0213). A single server whose operator accepted personal credentials
1233
- // is one of them for the first member to sign in there; a replica's own
1234
- // machine never is.
1310
+ // Members sign in to Claude Code and Codex on machines of their own from
1311
+ // the app (ADRs 0213, 0342). A single server whose operator accepted
1312
+ // personal credentials is one of them for the first member to sign in
1313
+ // there; a replica's own machine never is.
1235
1314
  const ownSignIns = singleServerSignIns
1236
- ? new CodexSignIns({
1315
+ ? new HarnessSignIns({
1237
1316
  signInRoot: execution.signInRoot,
1238
1317
  dataDir: data,
1239
1318
  env: { ...process.env, PATH: config.execution.path },
@@ -1247,12 +1326,12 @@ async function createWorkServerInner(
1247
1326
  machines: new MemberMachines({
1248
1327
  nodes: () =>
1249
1328
  memberNodes.list({ tenantId: SERVER_TENANT_ID, authorityId: hostId }),
1250
- placements: () => workers.placements(),
1251
- owner: (userId) => placementOwner(userId),
1329
+ machines: async () =>
1330
+ (await workers.machines.records()).map((record) => record.facts),
1252
1331
  ...(ownSignIns
1253
1332
  ? { ownMachine: { nodeId: machine.lease.id, signIns: ownSignIns } }
1254
1333
  : {}),
1255
- worker: (args) => workers.codexSignIn(args),
1334
+ worker: (args) => workers.harnessSignIn(args),
1256
1335
  }),
1257
1336
  });
1258
1337
  registerWorkAdmissionRoutes(app, {
@@ -1517,6 +1596,12 @@ ${workMark({ size: 72 })}
1517
1596
  </div>
1518
1597
  `;
1519
1598
 
1599
+ /**
1600
+ * The scopes an MCP client is told to ask for when it has no token (ADR
1601
+ * 0347): the least that runs a chat. More is granted by stepping up.
1602
+ */
1603
+ const MCP_CHALLENGE_SCOPES = ["work:read", "sessions:run"] as const;
1604
+
1520
1605
  function isLoopbackBase(base: string): boolean {
1521
1606
  const { hostname } = new URL(base);
1522
1607
  return (