@catamorphic/work-server 0.1.0-alpha.43 → 0.1.0-alpha.44

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 (66) hide show
  1. package/README.md +4 -1
  2. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  3. package/dist/chunk-ynxz0am9.js.map +11 -0
  4. package/dist/cluster.d.ts +19 -1
  5. package/dist/cluster.d.ts.map +1 -1
  6. package/dist/index.d.ts +2 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +784 -197
  9. package/dist/index.js.map +18 -16
  10. package/dist/machines/contract.d.ts +138 -14
  11. package/dist/machines/contract.d.ts.map +1 -1
  12. package/dist/machines/sequencer.d.ts +33 -6
  13. package/dist/machines/sequencer.d.ts.map +1 -1
  14. package/dist/machines/simulation.d.ts +64 -0
  15. package/dist/machines/simulation.d.ts.map +1 -1
  16. package/dist/machines/work-machines.d.ts +20 -2
  17. package/dist/machines/work-machines.d.ts.map +1 -1
  18. package/dist/server.d.ts +11 -1
  19. package/dist/server.d.ts.map +1 -1
  20. package/dist/testing.d.ts +1 -1
  21. package/dist/testing.d.ts.map +1 -1
  22. package/dist/testing.js +208 -17
  23. package/dist/testing.js.map +4 -4
  24. package/dist/workers/cache-archive-routes.d.ts +24 -0
  25. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  26. package/dist/workers/harness-sign-ins.d.ts +32 -1
  27. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  28. package/dist/workers/machine-store.d.ts +37 -0
  29. package/dist/workers/machine-store.d.ts.map +1 -1
  30. package/dist/workers/member-machine-routes.d.ts +3 -0
  31. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  32. package/dist/workers/member-machines.d.ts +52 -5
  33. package/dist/workers/member-machines.d.ts.map +1 -1
  34. package/dist/workers/placement.d.ts +10 -0
  35. package/dist/workers/placement.d.ts.map +1 -1
  36. package/dist/workers/sign-in-store.d.ts +67 -0
  37. package/dist/workers/sign-in-store.d.ts.map +1 -0
  38. package/dist/workers/sign-ins.d.ts +4 -6
  39. package/dist/workers/sign-ins.d.ts.map +1 -1
  40. package/dist/workers/worker-protocol.d.ts +9 -1
  41. package/dist/workers/worker-protocol.d.ts.map +1 -1
  42. package/dist/workers/worker-registry.d.ts +20 -6
  43. package/dist/workers/worker-registry.d.ts.map +1 -1
  44. package/dist/workers/worker-runtime.d.ts.map +1 -1
  45. package/package.json +18 -19
  46. package/src/cluster.ts +62 -7
  47. package/src/index.ts +7 -0
  48. package/src/machines/contract-kit.ts +1 -1
  49. package/src/machines/contract.ts +191 -19
  50. package/src/machines/sequencer.ts +106 -11
  51. package/src/machines/simulation.ts +370 -20
  52. package/src/machines/work-machines.ts +33 -3
  53. package/src/server.ts +106 -9
  54. package/src/testing.ts +1 -0
  55. package/src/workers/cache-archive-routes.ts +125 -0
  56. package/src/workers/harness-sign-ins.ts +207 -22
  57. package/src/workers/machine-store.ts +337 -56
  58. package/src/workers/member-machine-routes.ts +58 -3
  59. package/src/workers/member-machines.ts +168 -14
  60. package/src/workers/placement.ts +7 -0
  61. package/src/workers/sign-in-store.ts +241 -0
  62. package/src/workers/sign-ins.ts +9 -33
  63. package/src/workers/worker-protocol.ts +9 -1
  64. package/src/workers/worker-registry.ts +47 -6
  65. package/src/workers/worker-runtime.ts +5 -1
  66. package/dist/chunk-kcck20aw.js.map +0 -11
package/src/server.ts CHANGED
@@ -4,12 +4,14 @@ import path from "node:path";
4
4
  import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
5
5
  import type { AgentCapabilityOptions } from "@catamorphic/core";
6
6
  import {
7
+ type CacheStore,
7
8
  type ConnectionActionGuard,
8
9
  type ConnectionProvider,
9
10
  FULL_TOKEN_SCOPE,
10
11
  hasTokenScope,
11
12
  type Identity,
12
13
  type ModelRequestRewrite,
14
+ projectPrincipalIdentity,
13
15
  startEventDispatcher,
14
16
  tokenScopesOf,
15
17
  WorkerNodesService,
@@ -32,6 +34,7 @@ import { gatewayHostOf, MACHINE_CAPABILITIES } from "@catamorphic/sandbox";
32
34
  import {
33
35
  aiToolCall,
34
36
  aiToolKind,
37
+ assertNativeGit,
35
38
  builtinModelConnectionProviders,
36
39
  type Catamorphic,
37
40
  type CreateCatamorphicConfig,
@@ -45,6 +48,7 @@ import {
45
48
  type GithubConnectionOptions,
46
49
  githubCodeHost,
47
50
  MACHINE_TRIGGER_KINDS,
51
+ machineEventProjects,
48
52
  machineProjectEvent,
49
53
  ObjectRemoteBackend,
50
54
  PostgresObjectStore,
@@ -127,13 +131,20 @@ import {
127
131
  import { registerShareRoutes } from "./shares/share-routes.js";
128
132
  import { shareTools } from "./shares/share-tools.js";
129
133
  import { WorkSharesService } from "./shares/shares-service.js";
134
+ import {
135
+ cacheArchiveUrl,
136
+ registerCacheArchiveRoutes,
137
+ } from "./workers/cache-archive-routes.js";
130
138
  import { RUNNING_TIME_FILE, startDiskCare } from "./workers/disk-care.js";
131
139
  import { HarnessSignIns } from "./workers/harness-sign-ins.js";
132
140
  import { registerMemberMachineRoutes } from "./workers/member-machine-routes.js";
133
141
  import { MemberMachines } from "./workers/member-machines.js";
134
142
  import { signInCapabilities } from "./workers/sign-ins.js";
135
143
  import { startVolumePruning } from "./workers/volume-pruning.js";
136
- import { WorkWorkerRegistry } from "./workers/worker-registry.js";
144
+ import {
145
+ WORKER_NODE_PREFIX,
146
+ WorkWorkerRegistry,
147
+ } from "./workers/worker-registry.js";
137
148
  import { registerWorkerRoutes } from "./workers/worker-routes.js";
138
149
 
139
150
  /**
@@ -212,6 +223,16 @@ export interface WorkServerHooks {
212
223
  * registry packs. With no hook, machines are enrolled by hand.
213
224
  */
214
225
  machines?: MachinesHook;
226
+ /**
227
+ * The host's cache store (ADR 0360): where every machine's copy of an
228
+ * Environment cache can come from. After a trusted fill publishes a cache
229
+ * on one machine Work saves it there, and a machine that lacks the cache
230
+ * restores it from there before it fills from nothing. Two verbs, `save`
231
+ * and `restore`, over streams; the registry ships one for a shared
232
+ * directory. Archives pass through this server on their way, a cache's
233
+ * size at a time. With no store, every machine fills its own.
234
+ */
235
+ cacheStore?: CacheStore;
215
236
  /** Mount additional host routes on the public application. */
216
237
  routes?: (args: {
217
238
  app: FastifyInstance;
@@ -281,6 +302,11 @@ async function createWorkServerInner(
281
302
  const log = options.log ?? (() => {});
282
303
  const data = config.dataDir;
283
304
  const publicBase = config.publicBases[0] ?? "http://127.0.0.1:4700";
305
+ // Every project is kept with the Git program (ADR 0356): a server
306
+ // without one, or with one too old, says so now instead of failing its
307
+ // first project.
308
+ const git = await assertNativeGit();
309
+ log(`Git ${git.version}`);
284
310
  // Config is data, validated by the schemas the image's files use; only
285
311
  // the image's environment layer reads files for it (ADR 0183).
286
312
  const workAuthConfig = parseWorkAuthConfig(config.auth ?? {});
@@ -514,6 +540,9 @@ async function createWorkServerInner(
514
540
  // Work retired from a machine that is gone (ADR 0348) is admitted again
515
541
  // by the same sweep.
516
542
  let workRetired = () => {};
543
+ // A machine gave a workspace's room back: queued runs that found no room
544
+ // are tried at once, by this process's queue.
545
+ let roomFreed = () => {};
517
546
  // Something happened to a machine (ADR 0349): delivered once the core
518
547
  // is up, to the projects it is for and to the host's own listener.
519
548
  let machineEvent: (event: MachineEvent) => Promise<void> = async () => {};
@@ -528,6 +557,7 @@ async function createWorkServerInner(
528
557
  enrollmentSecret: authSecret,
529
558
  connected: () => workerConnected(),
530
559
  retired: () => workRetired(),
560
+ roomFreed: () => roomFreed(),
531
561
  event: (event) => machineEvent(event),
532
562
  log,
533
563
  });
@@ -557,6 +587,7 @@ async function createWorkServerInner(
557
587
  disk: () => diskCare.latest(),
558
588
  sandboxProvider,
559
589
  placement: { workers: () => workers.placements() },
590
+ roomFreed: () => roomFreed(),
560
591
  });
561
592
  disposers.push(() => machine.stop());
562
593
  let maintaining: Promise<void> | undefined;
@@ -637,6 +668,33 @@ async function createWorkServerInner(
637
668
  retentionDays: Math.round(
638
669
  execution.volumeRetentionMs / (24 * 60 * 60 * 1000),
639
670
  ),
671
+ // A fill or a preparation names only a machine that takes its
672
+ // project's work (ADR 0360).
673
+ machineAdmits: ({ projectId, machine }) =>
674
+ workers.machines.admitsProjectWork({ nodeId: machine, projectId }),
675
+ // Machines stream archives to and from this server (ADR 0360).
676
+ ...(hooks.cacheStore
677
+ ? {
678
+ store: hooks.cacheStore,
679
+ transferUrl: ({ transferId }) =>
680
+ cacheArchiveUrl({ base: publicBase, transferId }),
681
+ }
682
+ : {}),
683
+ },
684
+ // A spare is handed to the first chat key placed on it, under its
685
+ // machine's lock (ADR 0360).
686
+ allocationPlaced: async ({
687
+ transaction,
688
+ workerNodeId,
689
+ projectId,
690
+ policy,
691
+ }) => {
692
+ await workers.machines.claimSpare({
693
+ transaction,
694
+ nodeId: workerNodeId,
695
+ projectId,
696
+ chatKey: policy.chatKey,
697
+ });
640
698
  },
641
699
  clientExecution: true,
642
700
  database: databaseConfig,
@@ -647,6 +705,9 @@ async function createWorkServerInner(
647
705
  new ObjectRemoteBackend({
648
706
  store: objectStore,
649
707
  keyPrefix: "origins/",
708
+ // Large histories are stored as packs; this replica reads
709
+ // them here, beside the copies that borrow from them.
710
+ cachePath: path.join(data, "projects", ".origins"),
650
711
  }),
651
712
  ),
652
713
  }
@@ -783,6 +844,7 @@ async function createWorkServerInner(
783
844
  const core = catamorphic.core;
784
845
  workerConnected = () => core.wakeups.notify("agent");
785
846
  workRetired = () => core.wakeups.notify("agent");
847
+ roomFreed = () => core.wakeups.notify("capacity");
786
848
  // Any replica recovers the work of replicas that are gone for good: runs
787
849
  // move to a live machine, chats are admitted again on their next turn.
788
850
  {
@@ -895,15 +957,11 @@ async function createWorkServerInner(
895
957
  tenantId: SERVER_TENANT_ID,
896
958
  publicBase,
897
959
  });
898
- // A machine event reaches the projects the machine is for, as a project
899
- // event their workflows may trigger on, and the host's own listener.
900
- // Work itself depends on neither (ADR 0349).
960
+ // A machine event reaches the project the machine names and the projects
961
+ // it is for, as a project event their workflows may trigger on, and the
962
+ // host's own listener. Work itself depends on neither (ADRs 0349, 0364).
901
963
  machineEvent = async (event) => {
902
- const projects = new Set(
903
- (event.machine.for ?? []).flatMap((principal) =>
904
- "project" in principal ? [principal.project] : [],
905
- ),
906
- );
964
+ const projects = machineEventProjects(event.machine);
907
965
  const record = machineProjectEvent({
908
966
  kind: event.kind,
909
967
  at: event.at,
@@ -956,6 +1014,7 @@ async function createWorkServerInner(
956
1014
  }))
957
1015
  .sort((left, right) => left.id.localeCompare(right.id));
958
1016
  };
1017
+ const machineSessions = core.agentSessions;
959
1018
  const workMachines = hooks.machines
960
1019
  ? new WorkMachines({
961
1020
  db: core.db,
@@ -968,6 +1027,39 @@ async function createWorkServerInner(
968
1027
  workers,
969
1028
  controlPlaneUrl: publicBase,
970
1029
  people,
1030
+ // A machine stops with its quiet workspaces kept (ADR 0361).
1031
+ ...(machineSessions
1032
+ ? {
1033
+ stopQuietWorkspaces: (args: { workerNodeId: string }) =>
1034
+ machineSessions.stopQuietWorkspaces(args),
1035
+ }
1036
+ : {}),
1037
+ prepare: async ({ name, project, environment, commit }) => {
1038
+ const preparation = await core.machinePreparations.request({
1039
+ identity: projectPrincipalIdentity({
1040
+ tenantId: SERVER_TENANT_ID,
1041
+ projectId: project,
1042
+ environment,
1043
+ }),
1044
+ projectId: project,
1045
+ environment,
1046
+ machine: `${WORKER_NODE_PREFIX}${name}`,
1047
+ ...(commit !== undefined ? { commit } : {}),
1048
+ });
1049
+ return {
1050
+ project,
1051
+ environment,
1052
+ status:
1053
+ preparation.status === "succeeded"
1054
+ ? "prepared"
1055
+ : preparation.status === "failed"
1056
+ ? "failed"
1057
+ : "preparing",
1058
+ commit: preparation.commit,
1059
+ error: preparation.error,
1060
+ since: preparation.finishedAt ?? preparation.createdAt,
1061
+ };
1062
+ },
971
1063
  event: async (event) => {
972
1064
  await machineEvent(event).catch((error: unknown) =>
973
1065
  log(
@@ -1252,6 +1344,7 @@ async function createWorkServerInner(
1252
1344
  done(null, payload);
1253
1345
  });
1254
1346
  registerWorkerRoutes(app, workers);
1347
+ if (core.cacheArchives) registerCacheArchiveRoutes(app, core.cacheArchives);
1255
1348
  // Machines: the operator on the loopback listener, and organization
1256
1349
  // administrators through the API (ADR 0205).
1257
1350
  const machineManagement = {
@@ -1311,6 +1404,8 @@ async function createWorkServerInner(
1311
1404
  dataDir: data,
1312
1405
  env: { ...process.env, PATH: config.execution.path },
1313
1406
  onChange: () => machine.refreshSignIns(),
1407
+ // Where its sandboxes run images, a login runs in one (ADR 0363).
1408
+ provider: sandboxProvider,
1314
1409
  })
1315
1410
  : undefined;
1316
1411
  if (ownSignIns) disposers.push(async () => ownSignIns.stop());
@@ -1326,6 +1421,8 @@ async function createWorkServerInner(
1326
1421
  ? { ownMachine: { nodeId: machine.lease.id, signIns: ownSignIns } }
1327
1422
  : {}),
1328
1423
  worker: (args) => workers.harnessSignIn(args),
1424
+ environments: core.executionEnvironments,
1425
+ signIns: workers.machines.signIns,
1329
1426
  }),
1330
1427
  });
1331
1428
  registerWorkAdmissionRoutes(app, {
package/src/testing.ts CHANGED
@@ -17,6 +17,7 @@ export {
17
17
  export {
18
18
  quietSummary,
19
19
  type SimulatedCall,
20
+ type SimulatedStart,
20
21
  SimulatedWork,
21
22
  type SimulatedWorkOptions,
22
23
  } from "./machines/simulation.js";
@@ -0,0 +1,125 @@
1
+ import { Readable } from "node:stream";
2
+ import {
3
+ type CacheArchivesService,
4
+ CacheArchiveTooLargeError,
5
+ CacheTransferRefusedError,
6
+ } from "@catamorphic/core";
7
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
8
+
9
+ /** Where a machine streams one cache archive to or from (ADR 0360). */
10
+ export const CACHE_ARCHIVE_ROUTE = "/api/cache-archives";
11
+
12
+ /** The URL of one transfer on a control plane at `base`. */
13
+ export function cacheArchiveUrl(args: {
14
+ base: string;
15
+ transferId: string;
16
+ }): string {
17
+ return `${args.base.replace(/\/+$/, "")}${CACHE_ARCHIVE_ROUTE}/${args.transferId}`;
18
+ }
19
+
20
+ /**
21
+ * Answer a machine whose upload is not taken, then drop its connection:
22
+ * what it still sends is not read to its end. Until the answer is out the
23
+ * rest is read and dropped, so the machine hears it instead of a reset.
24
+ */
25
+ function refuseUpload(args: {
26
+ reply: FastifyReply;
27
+ body: Readable;
28
+ status: number;
29
+ error: string;
30
+ }) {
31
+ const { reply, body } = args;
32
+ body.resume();
33
+ reply.raw.once("finish", () => body.destroy());
34
+ return reply
35
+ .header("connection", "close")
36
+ .status(args.status)
37
+ .send({ error: args.error });
38
+ }
39
+
40
+ function bearerOf(request: FastifyRequest): string {
41
+ const header = request.headers.authorization;
42
+ const value = Array.isArray(header) ? header[0] : header;
43
+ return value?.startsWith("Bearer ") ? value.slice("Bearer ".length) : "";
44
+ }
45
+
46
+ /**
47
+ * The streams of a host's cache store (ADR 0360). A machine PUTs the
48
+ * archive of a cache generation a trusted fill wrote, and GETs one to
49
+ * restore, each with the one-time token Work handed it for that transfer.
50
+ * The bytes pass through this process into or out of the host's store one
51
+ * chunk at a time: nothing is buffered, each side waits for the other, and
52
+ * no transaction or lock is held while they move. A token opens one stream,
53
+ * and a stream carries no more than Work set for it: a save its cache's
54
+ * limit with an allowance for the archive's format (answered 413 past it,
55
+ * and the store keeps nothing), a restore the size Work recorded (cut off
56
+ * past it). Any replica serves any transfer; what passed is recorded for
57
+ * the fill's replica to read.
58
+ */
59
+ export function registerCacheArchiveRoutes(
60
+ app: FastifyInstance,
61
+ archives: CacheArchivesService,
62
+ ): void {
63
+ void app.register(async (scope) => {
64
+ // The archive is handed on as it arrives, never parsed or collected.
65
+ scope.addContentTypeParser("application/x-tar", (_request, payload, done) =>
66
+ done(null, payload),
67
+ );
68
+ scope.put<{ Params: { id: string } }>(
69
+ `${CACHE_ARCHIVE_ROUTE}/:id`,
70
+ async (request, reply) => {
71
+ const body = request.body;
72
+ if (!(body instanceof Readable))
73
+ return reply
74
+ .status(415)
75
+ .send({ error: "Send the archive as application/x-tar" });
76
+ try {
77
+ return await archives.receive({
78
+ transferId: request.params.id,
79
+ token: bearerOf(request),
80
+ body,
81
+ });
82
+ } catch (error) {
83
+ if (error instanceof CacheTransferRefusedError)
84
+ return refuseUpload({
85
+ reply,
86
+ body,
87
+ status: 404,
88
+ error: error.message,
89
+ });
90
+ if (error instanceof CacheArchiveTooLargeError)
91
+ return refuseUpload({
92
+ reply,
93
+ body,
94
+ status: 413,
95
+ error: error.message,
96
+ });
97
+ body.destroy();
98
+ throw error;
99
+ }
100
+ },
101
+ );
102
+ scope.get<{ Params: { id: string } }>(
103
+ `${CACHE_ARCHIVE_ROUTE}/:id`,
104
+ async (request, reply) => {
105
+ try {
106
+ const archive = await archives.send({
107
+ transferId: request.params.id,
108
+ token: bearerOf(request),
109
+ });
110
+ if (!archive)
111
+ return reply
112
+ .status(404)
113
+ .send({ error: "The store has no archive of this cache" });
114
+ return reply
115
+ .header("content-type", "application/x-tar")
116
+ .send(Readable.from(archive));
117
+ } catch (error) {
118
+ if (error instanceof CacheTransferRefusedError)
119
+ return reply.status(404).send({ error: error.message });
120
+ throw error;
121
+ }
122
+ },
123
+ );
124
+ });
125
+ }