@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/dist/index.js CHANGED
@@ -3,7 +3,11 @@ import {
3
3
  MachineLabelsSchema,
4
4
  DEFAULT_LOST_AFTER_MINUTES2,
5
5
  DesiredMachineSchema2,
6
+ SIGN_IN_WAIT_MINUTES,
6
7
  MACHINE_EVENT_KINDS2,
8
+ spareProject2,
9
+ handedOffKey2,
10
+ preparedFor2,
7
11
  principalsChangeNeedsReset,
8
12
  normalizePrincipals,
9
13
  servesOneOwner,
@@ -13,14 +17,14 @@ import {
13
17
  machineStateOf,
14
18
  lostAfterMsOf,
15
19
  runMachinePass
16
- } from "./chunk-kcck20aw.js";
20
+ } from "./chunk-ynxz0am9.js";
17
21
 
18
22
  // src/index.ts
19
23
  import {
20
24
  ConnectionActionRefusedError
21
25
  } from "@catamorphic/core";
22
26
  import {
23
- SIGN_IN_HARNESSES as SIGN_IN_HARNESSES3,
27
+ SIGN_IN_HARNESSES as SIGN_IN_HARNESSES5,
24
28
  SIGN_IN_SPECS as SIGN_IN_SPECS3,
25
29
  signInHarness as signInHarness3
26
30
  } from "@catamorphic/sandbox";
@@ -285,7 +289,6 @@ import {
285
289
  import { spawnSync } from "node:child_process";
286
290
  import { randomUUID } from "node:crypto";
287
291
  import fs2 from "node:fs";
288
- import { createRequire } from "node:module";
289
292
  import path from "node:path";
290
293
  import {
291
294
  MACHINE_CAPABILITIES,
@@ -335,32 +338,12 @@ function signInCapabilities(root) {
335
338
  ...listMachineSignIns(root).map((signIn) => signInCapability(signIn)).sort()
336
339
  ];
337
340
  }
338
- function onPath(command, env) {
339
- return (env.PATH ?? "").split(path.delimiter).some((directory) => {
340
- if (!directory)
341
- return false;
342
- try {
343
- fs2.accessSync(path.join(directory, command), fs2.constants.X_OK);
344
- return true;
345
- } catch {
346
- return false;
347
- }
348
- });
349
- }
350
- function harnessCommand(harness, env = process.env) {
351
- const { command } = SIGN_IN_SPECS[harness];
352
- if (harness === "codex" && !onPath(command, env))
353
- return {
354
- command: process.execPath,
355
- args: [
356
- createRequire(import.meta.url).resolve("@openai/codex/bin/codex.js")
357
- ]
358
- };
359
- return { command, args: [] };
341
+ function harnessCommand(harness) {
342
+ return { command: SIGN_IN_SPECS[harness].command, args: [] };
360
343
  }
361
344
  function signInCommand(input) {
362
345
  const spec = SIGN_IN_SPECS[input.harness];
363
- const cli = harnessCommand(input.harness, input.env);
346
+ const cli = harnessCommand(input.harness);
364
347
  return {
365
348
  command: cli.command,
366
349
  args: [...cli.args, ...spec.login, ...input.args ?? spec.defaultArgs],
@@ -648,7 +631,7 @@ function finish(args) {
648
631
  validateExecutionSettings(resolved);
649
632
  return resolved;
650
633
  }
651
- function onPath2(command, searchPath) {
634
+ function onPath(command, searchPath) {
652
635
  return searchPath.split(path2.delimiter).filter(Boolean).some((directory) => {
653
636
  try {
654
637
  fs3.accessSync(path2.join(directory, command), fs3.constants.X_OK);
@@ -664,8 +647,8 @@ function machineCapabilities(settings) {
664
647
  return [];
665
648
  return [
666
649
  ...settings.acceptPersonalCredentials ? [MACHINE_CAPABILITIES2.personalCredentials] : [],
667
- ...settings.backend === "local-process" && onPath2("claude", settings.path) ? [MACHINE_CAPABILITIES2.claudeCode] : [],
668
- ...settings.backend === "local-process" && onPath2("codex", settings.path) ? [MACHINE_CAPABILITIES2.codex] : []
650
+ ...settings.backend === "local-process" && onPath("claude", settings.path) ? [MACHINE_CAPABILITIES2.claudeCode] : [],
651
+ ...settings.backend === "local-process" && onPath("codex", settings.path) ? [MACHINE_CAPABILITIES2.codex] : []
669
652
  ];
670
653
  }
671
654
  function agentsReachMachine(settings) {
@@ -1412,11 +1395,12 @@ function startMdnsResponder(hostname, log = () => {}) {
1412
1395
  // src/server.ts
1413
1396
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
1414
1397
  import fs12 from "node:fs";
1415
- import path9 from "node:path";
1416
- import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
1398
+ import path10 from "node:path";
1399
+ import { ACTIVE_TURN_STATUSES as ACTIVE_TURN_STATUSES2 } from "@catamorphic/agent-protocol";
1417
1400
  import {
1418
1401
  FULL_TOKEN_SCOPE as FULL_TOKEN_SCOPE3,
1419
1402
  hasTokenScope as hasTokenScope2,
1403
+ projectPrincipalIdentity,
1420
1404
  startEventDispatcher,
1421
1405
  tokenScopesOf as tokenScopesOf2,
1422
1406
  WorkerNodesService as WorkerNodesService2,
@@ -1438,6 +1422,7 @@ import { gatewayHostOf, MACHINE_CAPABILITIES as MACHINE_CAPABILITIES6 } from "@c
1438
1422
  import {
1439
1423
  aiToolCall,
1440
1424
  aiToolKind,
1425
+ assertNativeGit,
1441
1426
  builtinModelConnectionProviders,
1442
1427
  connectionAuthorizationPage,
1443
1428
  createCatamorphic,
@@ -1448,6 +1433,7 @@ import {
1448
1433
  FsBundleStore,
1449
1434
  githubCodeHost,
1450
1435
  MACHINE_TRIGGER_KINDS,
1436
+ machineEventProjects,
1451
1437
  machineProjectEvent,
1452
1438
  ObjectRemoteBackend,
1453
1439
  PostgresObjectStore,
@@ -1462,7 +1448,7 @@ import { PROJECT_AGENTS_DIR } from "@catamorphic/workflow/project-layout";
1462
1448
  import { PGlite as PGlite2 } from "@electric-sql/pglite";
1463
1449
  import { pgcrypto } from "@electric-sql/pglite/contrib/pgcrypto";
1464
1450
  import Fastify from "fastify";
1465
- import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql8, WithSchemaPlugin } from "kysely";
1451
+ import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql9, WithSchemaPlugin } from "kysely";
1466
1452
  import { z as z25 } from "zod";
1467
1453
 
1468
1454
  // src/admission/admission-service.ts
@@ -2037,7 +2023,7 @@ function invalidInput(reply, issues) {
2037
2023
 
2038
2024
  // src/agent-capabilities.ts
2039
2025
  import { readFile } from "node:fs/promises";
2040
- import { createRequire as createRequire2 } from "node:module";
2026
+ import { createRequire } from "node:module";
2041
2027
  import {
2042
2028
  defineAgentCapability,
2043
2029
  defineRegistryCapability,
@@ -2049,7 +2035,7 @@ import { projectToolCapabilities } from "@catamorphic/fastify-plugin";
2049
2035
  import { z as z5 } from "zod";
2050
2036
  var SERVER_PROJECT_TOOLS = new Set(["set_session_metadata"]);
2051
2037
  var registry = defineRegistryCapability({
2052
- catalog: async () => parseRegistryCatalog(await readFile(createRequire2(import.meta.url).resolve("@catamorphic/registry/catalog.json"), "utf8"))
2038
+ catalog: async () => parseRegistryCatalog(await readFile(createRequire(import.meta.url).resolve("@catamorphic/registry/catalog.json"), "utf8"))
2053
2039
  });
2054
2040
  function workAgentCapabilities(args) {
2055
2041
  const directory = defineAgentCapability({
@@ -4060,7 +4046,7 @@ import {
4060
4046
  WorkerNodesService
4061
4047
  } from "@catamorphic/core";
4062
4048
  import {
4063
- accessTier,
4049
+ accessTier as accessTier2,
4064
4050
  describeDisk as describeDisk2,
4065
4051
  diskBudgetMb as diskBudgetMb2,
4066
4052
  environmentSatisfies,
@@ -4069,7 +4055,7 @@ import {
4069
4055
  poolMatches,
4070
4056
  servesOnlyThisOwner
4071
4057
  } from "@catamorphic/sandbox";
4072
- import { sql as sql5 } from "kysely";
4058
+ import { sql as sql6 } from "kysely";
4073
4059
 
4074
4060
  // src/workers/worker-registry.ts
4075
4061
  import {
@@ -4101,21 +4087,126 @@ import {
4101
4087
  MACHINE_CAPABILITIES as MACHINE_CAPABILITIES3,
4102
4088
  SANDBOX_CAPABILITIES
4103
4089
  } from "@catamorphic/sandbox";
4104
- import { sql as sql4 } from "kysely";
4090
+ import { sql as sql5 } from "kysely";
4105
4091
  import { z as z10 } from "zod";
4106
4092
 
4107
4093
  // src/workers/machine-store.ts
4108
4094
  import { createHash as createHash3, createHmac, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
4095
+ import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
4109
4096
  import {
4110
4097
  isProjectPrincipal,
4111
4098
  PLACEMENT_FREE_JOB_KINDS,
4112
- PLACEMENT_WAIT_FRESH_SECONDS
4099
+ PLACEMENT_WAIT_FRESH_SECONDS,
4100
+ WORKSPACE_IN_USE_SECONDS
4113
4101
  } from "@catamorphic/core";
4114
- import { parseSignInCapability } from "@catamorphic/sandbox";
4102
+ import { accessTier, parseSignInCapability } from "@catamorphic/sandbox";
4115
4103
  import {
4116
- sql as sql3
4104
+ sql as sql4
4117
4105
  } from "kysely";
4118
4106
  import { z as z9 } from "zod";
4107
+
4108
+ // src/workers/sign-in-store.ts
4109
+ import { SIGN_IN_HARNESSES as SIGN_IN_HARNESSES3 } from "@catamorphic/sandbox";
4110
+ import { sql as sql3 } from "kysely";
4111
+ class SignInStore {
4112
+ deps;
4113
+ constructor(deps) {
4114
+ this.deps = deps;
4115
+ }
4116
+ async wait(args) {
4117
+ const { db, tenantId } = this.deps;
4118
+ const expires = sql3`now() + make_interval(mins => ${SIGN_IN_WAIT_MINUTES})`;
4119
+ await db.deleteFrom("sign_in_waits").where("tenant_id", "=", tenantId).where("expires_at", "<=", sql3`now()`).execute();
4120
+ await db.insertInto("sign_in_waits").values({
4121
+ tenant_id: tenantId,
4122
+ machine: args.machine,
4123
+ member: args.member,
4124
+ harness: args.harness,
4125
+ project_id: args.project,
4126
+ environment_name: args.environment,
4127
+ expires_at: expires
4128
+ }).onConflict((conflict) => conflict.columns(["tenant_id", "machine", "member"]).doUpdateSet({
4129
+ harness: args.harness,
4130
+ project_id: args.project,
4131
+ environment_name: args.environment,
4132
+ expires_at: expires
4133
+ })).execute();
4134
+ }
4135
+ async began(args) {
4136
+ await this.deps.db.deleteFrom("sign_in_waits").where("tenant_id", "=", this.deps.tenantId).where("machine", "=", args.machine).where("member", "=", args.member).execute();
4137
+ }
4138
+ async waiting() {
4139
+ const rows = await this.deps.db.selectFrom("sign_in_waits").leftJoin("work_accounts", "work_accounts.user_id", "sign_in_waits.member").select([
4140
+ "sign_in_waits.id",
4141
+ "sign_in_waits.machine",
4142
+ "sign_in_waits.member",
4143
+ "sign_in_waits.project_id",
4144
+ "sign_in_waits.environment_name",
4145
+ "sign_in_waits.waiting_since",
4146
+ "work_accounts.disabled_at"
4147
+ ]).where("sign_in_waits.tenant_id", "=", this.deps.tenantId).where("sign_in_waits.expires_at", ">", sql3`now()`).orderBy("sign_in_waits.waiting_since").execute();
4148
+ return rows.filter((row) => row.disabled_at === null).map((row) => ({
4149
+ id: row.id,
4150
+ kind: "sign-in",
4151
+ project: row.project_id,
4152
+ user: row.member,
4153
+ key: null,
4154
+ environment: row.environment_name,
4155
+ pool: {},
4156
+ requirements: { resources: {}, capabilities: [] },
4157
+ reason: "unavailable",
4158
+ waitingSince: row.waiting_since.toISOString(),
4159
+ machine: row.machine
4160
+ }));
4161
+ }
4162
+ signature() {
4163
+ return this.deps.db.selectFrom("sign_in_waits").select(sql3`count(*)::text || '/' || coalesce(max(waiting_since)::text, '') || '/' || coalesce(max(expires_at)::text, '')`.as("sign_ins")).where("tenant_id", "=", this.deps.tenantId).where("expires_at", ">", sql3`now()`);
4164
+ }
4165
+ async begun(args) {
4166
+ const { db, tenantId } = this.deps;
4167
+ await db.deleteFrom("machine_sign_ins").where("tenant_id", "=", tenantId).where("signed_in_at", "is", null).where("begun_at", "<", sql3`now() - interval '1 day'`).execute();
4168
+ await db.insertInto("machine_sign_ins").values({
4169
+ attempt: args.attempt,
4170
+ tenant_id: tenantId,
4171
+ node_id: args.nodeId,
4172
+ member: args.member,
4173
+ harness: args.harness,
4174
+ project_id: args.made.project,
4175
+ environment_name: args.made.environment,
4176
+ image: args.made.image
4177
+ }).onConflict((conflict) => conflict.column("attempt").doNothing()).execute();
4178
+ }
4179
+ async signedIn(args) {
4180
+ await this.deps.db.transaction().execute(async (trx) => {
4181
+ const marked = await trx.updateTable("machine_sign_ins").set({ signed_in_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("attempt", "=", args.attempt).where("node_id", "=", args.nodeId).where("member", "=", args.member).where("harness", "=", args.harness).where("signed_in_at", "is", null).executeTakeFirst();
4182
+ if (!marked.numUpdatedRows)
4183
+ return;
4184
+ await trx.deleteFrom("machine_sign_ins").where("tenant_id", "=", this.deps.tenantId).where("node_id", "=", args.nodeId).where("member", "=", args.member).where("harness", "=", args.harness).where("attempt", "!=", args.attempt).where("signed_in_at", "is not", null).execute();
4185
+ });
4186
+ }
4187
+ async signedOut(args) {
4188
+ await this.deps.db.deleteFrom("machine_sign_ins").where("tenant_id", "=", this.deps.tenantId).where("node_id", "=", args.nodeId).where("member", "=", args.member).where("harness", "=", args.harness).execute();
4189
+ }
4190
+ async made(args) {
4191
+ const rows = await this.deps.db.selectFrom("machine_sign_ins").select(["node_id", "harness", "project_id", "environment_name", "image"]).where("tenant_id", "=", this.deps.tenantId).where("member", "=", args.member).where("signed_in_at", "is not", null).orderBy("signed_in_at").execute();
4192
+ const made = new Map;
4193
+ for (const row of rows) {
4194
+ const harness = SIGN_IN_HARNESSES3.find((name) => name === row.harness);
4195
+ if (!harness)
4196
+ continue;
4197
+ const entry = made.get(row.node_id) ?? {};
4198
+ entry[harness] = {
4199
+ project: row.project_id,
4200
+ environment: row.environment_name,
4201
+ image: row.image
4202
+ };
4203
+ made.set(row.node_id, entry);
4204
+ }
4205
+ return made;
4206
+ }
4207
+ }
4208
+
4209
+ // src/workers/machine-store.ts
4119
4210
  var WORKER_NODE_PREFIX = "worker.";
4120
4211
  var ENROLLMENT_MINUTES = 60;
4121
4212
  var PHASES = [
@@ -4134,7 +4225,8 @@ var VERBS = [
4134
4225
  "destroy",
4135
4226
  "stop",
4136
4227
  "start",
4137
- "describe"
4228
+ "describe",
4229
+ "onConnected"
4138
4230
  ];
4139
4231
  var OptionsSchema = z9.record(z9.string(), z9.unknown());
4140
4232
  var WaitPool = z9.record(z9.string(), z9.string());
@@ -4153,7 +4245,9 @@ class MachineStore {
4153
4245
  deps;
4154
4246
  constructor(deps) {
4155
4247
  this.deps = deps;
4248
+ this.signIns = new SignInStore(deps);
4156
4249
  }
4250
+ signIns;
4157
4251
  get defaultLostMinutes() {
4158
4252
  return this.deps.lostMinutes ?? DEFAULT_LOST_AFTER_MINUTES2;
4159
4253
  }
@@ -4183,6 +4277,8 @@ class MachineStore {
4183
4277
  idempotency_key: key,
4184
4278
  labels: JSON.stringify(machine.labels),
4185
4279
  serves: machine.for === null ? null : JSON.stringify(machine.for),
4280
+ spare: machine.spare,
4281
+ project_id: machine.project,
4186
4282
  trusted: machine.trusted,
4187
4283
  options: JSON.stringify(machine.options),
4188
4284
  lost_after_minutes: machine.lostAfterMinutes,
@@ -4202,7 +4298,7 @@ class MachineStore {
4202
4298
  if (!row?.enrollment_nonce || !row.idempotency_key)
4203
4299
  return null;
4204
4300
  await this.deps.db.updateTable("work_worker_enrollments").set({
4205
- expires_at: sql3`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4301
+ expires_at: sql4`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4206
4302
  }).where("tenant_id", "=", this.deps.tenantId).where("code_hash", "=", row.idempotency_key).where("used_at", "is", null).execute();
4207
4303
  return {
4208
4304
  code: this.code({ name: args.name, nonce: row.enrollment_nonce }),
@@ -4220,7 +4316,7 @@ class MachineStore {
4220
4316
  await trx.updateTable("work_machines").set({
4221
4317
  enrollment_nonce: nonce,
4222
4318
  idempotency_key: key,
4223
- updated_at: sql3`now()`
4319
+ updated_at: sql4`now()`
4224
4320
  }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4225
4321
  await this.insertEnrollment({ name: args.name, key, transaction: trx });
4226
4322
  });
@@ -4231,11 +4327,11 @@ class MachineStore {
4231
4327
  code_hash: args.key,
4232
4328
  tenant_id: this.deps.tenantId,
4233
4329
  name: args.name,
4234
- expires_at: sql3`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4330
+ expires_at: sql4`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4235
4331
  }).execute();
4236
4332
  }
4237
4333
  async lockName(args) {
4238
- await sql3`SELECT pg_advisory_xact_lock(hashtext(${`work-worker-name:${this.deps.tenantId}:${args.name}`}))`.execute(args.transaction);
4334
+ await sql4`SELECT pg_advisory_xact_lock(hashtext(${`work-worker-name:${this.deps.tenantId}:${args.name}`}))`.execute(args.transaction);
4239
4335
  }
4240
4336
  async created(args) {
4241
4337
  await this.update(args.name, {
@@ -4253,16 +4349,16 @@ class MachineStore {
4253
4349
  const failure = {
4254
4350
  last_error: `Its platform refused: ${args.reason}`.slice(0, 4000),
4255
4351
  last_error_verb: "create",
4256
- last_error_at: sql3`now()`,
4257
- updated_at: sql3`now()`
4352
+ last_error_at: sql4`now()`,
4353
+ updated_at: sql4`now()`
4258
4354
  };
4259
4355
  const withdrawn = row.idempotency_key ? await trx.deleteFrom("work_worker_enrollments").where("tenant_id", "=", this.deps.tenantId).where("code_hash", "=", row.idempotency_key).where("used_at", "is", null).returning("code_hash").executeTakeFirst() : undefined;
4260
4356
  await trx.updateTable("work_machines").set(withdrawn ? {
4261
4357
  ...failure,
4262
4358
  enrollment_nonce: null,
4263
4359
  idempotency_key: null,
4264
- refused_count: sql3`refused_count + 1`,
4265
- refused_at: sql3`now()`
4360
+ refused_count: sql4`refused_count + 1`,
4361
+ refused_at: sql4`now()`
4266
4362
  } : failure).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4267
4363
  });
4268
4364
  }
@@ -4271,9 +4367,45 @@ class MachineStore {
4271
4367
  labels: JSON.stringify(args.labels),
4272
4368
  trusted: args.trusted,
4273
4369
  reason: args.reason,
4274
- lost_after_minutes: args.lostAfterMinutes
4370
+ lost_after_minutes: args.lostAfterMinutes,
4371
+ ...args.spare !== undefined ? { spare: args.spare } : {},
4372
+ ...args.project !== undefined ? { project_id: args.project } : {}
4275
4373
  });
4276
4374
  }
4375
+ async claimSpare(args) {
4376
+ if (!args.chatKey || !args.nodeId.startsWith(WORKER_NODE_PREFIX))
4377
+ return false;
4378
+ const name = args.nodeId.slice(WORKER_NODE_PREFIX.length);
4379
+ const claimed = await args.transaction.updateTable("work_machines").set({
4380
+ serves: JSON.stringify([
4381
+ { project: args.projectId, key: args.chatKey }
4382
+ ]),
4383
+ spare: false,
4384
+ updated_at: sql4`now()`
4385
+ }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).where("spare", "=", true).where("serves", "=", sql4`${JSON.stringify([{ project: args.projectId }])}::jsonb`).returning("name").executeTakeFirst();
4386
+ if (!claimed)
4387
+ return false;
4388
+ await args.transaction.updateTable("worker_nodes").set({ admission_revision: randomUUID4() }).where("id", "=", args.nodeId).where("tenant_id", "=", this.deps.tenantId).where("admission_revision", "is not", null).execute();
4389
+ return true;
4390
+ }
4391
+ async admitsProjectWork(args) {
4392
+ if (!args.nodeId.startsWith(WORKER_NODE_PREFIX))
4393
+ return true;
4394
+ const row = await this.row({
4395
+ name: args.nodeId.slice(WORKER_NODE_PREFIX.length)
4396
+ });
4397
+ if (!row)
4398
+ return false;
4399
+ return accessTier({
4400
+ access: nodeAccess(storedPlacement(row).for),
4401
+ owner: undefined,
4402
+ projectId: args.projectId,
4403
+ fill: true
4404
+ }) !== undefined;
4405
+ }
4406
+ async heardConnected(args) {
4407
+ await this.update(args.name, { connect_pending: false });
4408
+ }
4277
4409
  async setFor(args) {
4278
4410
  await this.updatePlacement(args.name, {
4279
4411
  serves: principalsJson(args.for),
@@ -4289,14 +4421,14 @@ class MachineStore {
4289
4421
  }
4290
4422
  async finishReset(args) {
4291
4423
  await this.updatePlacement(args.name, {
4292
- serves: sql3`CASE WHEN reset_pending THEN reset_serves ELSE serves END`,
4424
+ serves: sql4`CASE WHEN reset_pending THEN reset_serves ELSE serves END`,
4293
4425
  reset_pending: false,
4294
4426
  reset_serves: null
4295
4427
  });
4296
4428
  }
4297
4429
  async setDropped(args) {
4298
4430
  await this.updatePlacement(args.name, {
4299
- dropped_at: args.dropped ? sql3`coalesce(dropped_at, now())` : null
4431
+ dropped_at: args.dropped ? sql4`coalesce(dropped_at, now())` : null
4300
4432
  });
4301
4433
  }
4302
4434
  async openPlacement({ name }) {
@@ -4305,24 +4437,28 @@ class MachineStore {
4305
4437
  async setPhase(args) {
4306
4438
  const moved = await (args.transaction ?? this.deps.db).updateTable("work_machines").set({
4307
4439
  phase: args.phase,
4308
- phase_since: args.at === undefined ? sql3`now()` : new Date(args.at),
4440
+ phase_since: args.at === undefined ? sql4`now()` : new Date(args.at),
4309
4441
  verb_done_at: null,
4310
- updated_at: sql3`now()`,
4442
+ updated_at: sql4`now()`,
4311
4443
  ...args.phase === "destroying" ? {
4312
- destroy_requested_at: sql3`coalesce(destroy_requested_at, now())`
4444
+ destroy_requested_at: sql4`coalesce(destroy_requested_at, now())`
4313
4445
  } : {},
4314
- ...args.lost ? { lost_at: sql3`coalesce(lost_at, now())` } : {},
4315
- ...args.phase === "running" ? { lost_at: null } : {}
4446
+ ...args.lost ? { lost_at: sql4`coalesce(lost_at, now())` } : {},
4447
+ ...args.phase === "running" ? {
4448
+ lost_at: null,
4449
+ connect_pending: sql4`CASE WHEN phase IN ('starting', 'resuming') THEN true ELSE connect_pending END`
4450
+ } : {}
4316
4451
  }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("phase", "!=", args.phase).$if(args.from !== undefined, (query) => query.where("phase", "in", [...args.from ?? []])).returning("name").executeTakeFirst();
4317
4452
  return Boolean(moved);
4318
4453
  }
4319
4454
  async startAsked(args) {
4320
- await this.deps.db.updateTable("work_machines").set({ verb_done_at: sql3`now()`, updated_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("phase", "=", "resuming").execute();
4455
+ await this.deps.db.updateTable("work_machines").set({ verb_done_at: sql4`now()`, updated_at: sql4`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("phase", "=", "resuming").execute();
4321
4456
  }
4322
4457
  async forget(args) {
4323
4458
  const db = args.transaction ?? this.deps.db;
4324
4459
  await db.deleteFrom("work_machines").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4325
4460
  await db.deleteFrom("work_worker_enrollments").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("used_at", "is", null).execute();
4461
+ await db.deleteFrom("machine_preparations").where("tenant_id", "=", this.deps.tenantId).where("worker_node_id", "=", `${WORKER_NODE_PREFIX}${args.name}`).execute();
4326
4462
  }
4327
4463
  async note(args) {
4328
4464
  await this.update(args.name, { notice: args.notice });
@@ -4331,14 +4467,14 @@ class MachineStore {
4331
4467
  await this.update(args.name, {
4332
4468
  last_error: args.message.slice(0, 4000),
4333
4469
  last_error_verb: args.verb,
4334
- last_error_at: sql3`now()`
4470
+ last_error_at: sql4`now()`
4335
4471
  });
4336
4472
  }
4337
4473
  async succeeded(args) {
4338
4474
  await this.deps.db.updateTable("work_machines").set({ last_error: null, last_error_verb: null, last_error_at: null }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).where("last_error_verb", "=", args.verb).execute();
4339
4475
  }
4340
4476
  async planned(args) {
4341
- const values = args.error ? { error: args.error.slice(0, 4000), error_at: sql3`now()` } : { planned_at: sql3`now()`, error: null, error_at: null };
4477
+ const values = args.error ? { error: args.error.slice(0, 4000), error_at: sql4`now()` } : { planned_at: sql4`now()`, error: null, error_at: null };
4342
4478
  await this.deps.db.insertInto("work_machine_plans").values({ tenant_id: this.deps.tenantId, ...values }).onConflict((conflict) => conflict.column("tenant_id").doUpdateSet(values)).execute();
4343
4479
  }
4344
4480
  async plan() {
@@ -4355,7 +4491,7 @@ class MachineStore {
4355
4491
  const node = await trx.selectFrom("worker_nodes").select(["id", "admission_revision"]).where("id", "=", nodeId).where("tenant_id", "=", tenantId).forUpdate().executeTakeFirst();
4356
4492
  if (options.onlyWhenUnopened && (!node || node.admission_revision))
4357
4493
  return;
4358
- const updated = await trx.updateTable("work_machines").set({ ...values, updated_at: sql3`now()` }).where("tenant_id", "=", tenantId).where("name", "=", name).returning(["reset_pending", "dropped_at", "phase"]).executeTakeFirst();
4494
+ const updated = await trx.updateTable("work_machines").set({ ...values, updated_at: sql4`now()` }).where("tenant_id", "=", tenantId).where("name", "=", name).returning(["reset_pending", "dropped_at", "phase"]).executeTakeFirst();
4359
4495
  if (node && updated)
4360
4496
  await trx.updateTable("worker_nodes").set({
4361
4497
  admission_revision: updated.reset_pending || updated.dropped_at || updated.phase !== "running" ? null : randomUUID4()
@@ -4363,7 +4499,7 @@ class MachineStore {
4363
4499
  });
4364
4500
  }
4365
4501
  async update(name, values) {
4366
- await this.deps.db.updateTable("work_machines").set({ ...values, updated_at: sql3`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).execute();
4502
+ await this.deps.db.updateTable("work_machines").set({ ...values, updated_at: sql4`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).execute();
4367
4503
  }
4368
4504
  async placementOf(args) {
4369
4505
  const row = await this.row(args);
@@ -4372,7 +4508,7 @@ class MachineStore {
4372
4508
  return storedPlacement(row);
4373
4509
  }
4374
4510
  async placements() {
4375
- const rows = await this.deps.db.selectFrom("work_machines as machine").innerJoin("worker_nodes as node", (join) => join.onRef("node.tenant_id", "=", "machine.tenant_id").on("node.id", "=", sql3`${WORKER_NODE_PREFIX} || machine.name`)).select([
4511
+ const rows = await this.deps.db.selectFrom("work_machines as machine").innerJoin("worker_nodes as node", (join) => join.onRef("node.tenant_id", "=", "machine.tenant_id").on("node.id", "=", sql4`${WORKER_NODE_PREFIX} || machine.name`)).select([
4376
4512
  "machine.name",
4377
4513
  "machine.labels",
4378
4514
  "machine.serves",
@@ -4380,12 +4516,19 @@ class MachineStore {
4380
4516
  "machine.phase",
4381
4517
  "machine.dropped_at",
4382
4518
  "machine.reset_pending",
4519
+ "machine.spare",
4383
4520
  "node.admission_revision"
4384
4521
  ]).where("machine.tenant_id", "=", this.deps.tenantId).execute();
4522
+ const prepared = await this.deps.db.selectFrom("machine_preparations").select(["worker_node_id", "project_id", "environment_name"]).where("tenant_id", "=", this.deps.tenantId).where("status", "=", "succeeded").execute();
4385
4523
  return new Map(rows.map((row) => [
4386
4524
  `${WORKER_NODE_PREFIX}${row.name}`,
4387
4525
  {
4388
4526
  ...storedPlacement(row),
4527
+ spare: row.spare,
4528
+ prepared: prepared.filter((entry) => entry.worker_node_id === `${WORKER_NODE_PREFIX}${row.name}`).map((entry) => ({
4529
+ project: entry.project_id,
4530
+ environment: entry.environment_name
4531
+ })),
4389
4532
  admissionRevision: row.admission_revision,
4390
4533
  accepting: row.phase === "running" && row.admission_revision !== null && row.dropped_at === null && !row.reset_pending
4391
4534
  }
@@ -4393,22 +4536,45 @@ class MachineStore {
4393
4536
  }
4394
4537
  async records() {
4395
4538
  const { db, tenantId } = this.deps;
4396
- const [rows, workers, nodes, holdings, loads, clock] = await Promise.all([
4539
+ const [rows, workers, nodes, holdings, loads, clock, preparations] = await Promise.all([
4397
4540
  db.selectFrom("work_machines").selectAll().where("tenant_id", "=", tenantId).orderBy("name").execute(),
4398
4541
  db.selectFrom("work_workers").select(["name", "enrolled_at", "last_seen_at", "revoked_at"]).where("tenant_id", "=", tenantId).execute(),
4399
4542
  this.deps.nodes.list({ tenantId, authorityId: this.deps.authorityId }),
4400
4543
  db.selectFrom("execution_allocations as allocation").leftJoin("agent_sessions as session", (join) => join.onRef("session.id", "=", "allocation.root_workload_id").on("allocation.workload_kind", "=", "agent")).select([
4401
4544
  "allocation.worker_node_id",
4402
4545
  "allocation.project_id",
4546
+ "allocation.status",
4547
+ "allocation.workload_kind",
4548
+ "allocation.created_at",
4549
+ "allocation.sandbox_creation_started",
4550
+ "allocation.sandbox_provider_id",
4403
4551
  "session.external_user_id",
4404
4552
  "session.chat_key"
4405
- ]).where("allocation.tenant_id", "=", tenantId).where("allocation.status", "=", "active").where("allocation.worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).execute(),
4553
+ ]).select((eb) => [
4554
+ eb.exists(eb.selectFrom("agent_turns").innerJoin("agent_sessions as sharer", "sharer.id", "agent_turns.session_id").select("agent_turns.id").whereRef("sharer.allocation_id", "=", "allocation.id").where("agent_turns.status", "in", [
4555
+ "queued",
4556
+ "held",
4557
+ ...ACTIVE_TURN_STATUSES
4558
+ ])).as("turning"),
4559
+ eb.selectFrom("agent_turns").innerJoin("agent_sessions as sharer", "sharer.id", "agent_turns.session_id").select((turn) => turn.fn.max("agent_turns.updated_at").as("at")).whereRef("sharer.allocation_id", "=", "allocation.id").as("last_turn_at"),
4560
+ eb.selectFrom("session_workspace_use").innerJoin("agent_sessions as user", "user.id", "session_workspace_use.session_id").select((use) => use.fn.max("session_workspace_use.used_at").as("at")).whereRef("user.allocation_id", "=", "allocation.id").as("last_used_at")
4561
+ ]).where("allocation.tenant_id", "=", tenantId).where("allocation.status", "in", ["active", "stopped"]).where("allocation.worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).execute(),
4406
4562
  db.selectFrom("execution_allocations").select([
4407
4563
  "worker_node_id",
4408
- sql3`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as("holding"),
4409
- sql3`max(capacity_released_at)`.as("last_released")
4564
+ sql4`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as("holding"),
4565
+ sql4`max(capacity_released_at)`.as("last_released")
4410
4566
  ]).where("tenant_id", "=", tenantId).where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).groupBy("worker_node_id").execute(),
4411
- sql3`SELECT now() AS now`.execute(db)
4567
+ sql4`SELECT now() AS now`.execute(db),
4568
+ db.selectFrom("machine_preparations").select([
4569
+ "worker_node_id",
4570
+ "project_id",
4571
+ "environment_name",
4572
+ "status",
4573
+ "commit_sha",
4574
+ "error",
4575
+ "queued_at",
4576
+ "finished_at"
4577
+ ]).where("tenant_id", "=", tenantId).orderBy("project_id").orderBy("environment_name").execute()
4412
4578
  ]);
4413
4579
  const now = clock.rows[0]?.now ?? new Date;
4414
4580
  const workerOf = new Map(workers.map((worker) => [worker.name, worker]));
@@ -4419,7 +4585,14 @@ class MachineStore {
4419
4585
  const worker = workerOf.get(row.name);
4420
4586
  const node = nodeOf.get(nodeId);
4421
4587
  const load = loadOf.get(nodeId);
4422
- const held = holdings.filter((entry) => entry.worker_node_id === nodeId);
4588
+ const kept = holdings.filter((entry) => entry.worker_node_id === nodeId);
4589
+ const held = kept.filter((entry) => entry.status === "active");
4590
+ const stopped = kept.length - held.length;
4591
+ const quiet = Number(load?.holding ?? 0) === kept.length && !preparations.some((entry) => entry.worker_node_id === nodeId && (entry.status === "queued" || entry.status === "running")) && held.every((entry) => entry.workload_kind === "agent" && !entry.turning && !usedWithin({
4592
+ at: dateOf(entry.last_used_at),
4593
+ now,
4594
+ seconds: WORKSPACE_IN_USE_SECONDS
4595
+ }) && !(entry.sandbox_creation_started && !entry.sandbox_provider_id));
4423
4596
  const phase = phaseOf(row.phase);
4424
4597
  const seen = worker?.last_seen_at ?? worker?.enrolled_at ?? row.phase_since;
4425
4598
  const lostAfterMs = lostAfterMsOf({
@@ -4445,17 +4618,33 @@ class MachineStore {
4445
4618
  since: sinceOf({ row, state, seen }).toISOString(),
4446
4619
  labels: placement.labels,
4447
4620
  for: placement.for,
4621
+ spare: row.spare,
4622
+ project: row.project_id,
4623
+ preparations: preparations.filter((entry) => entry.worker_node_id === nodeId).map((entry) => ({
4624
+ project: entry.project_id,
4625
+ environment: entry.environment_name,
4626
+ status: entry.status === "succeeded" ? "prepared" : entry.status === "failed" ? "failed" : "preparing",
4627
+ commit: entry.commit_sha,
4628
+ error: entry.error,
4629
+ since: (entry.finished_at ?? entry.queued_at).toISOString()
4630
+ })),
4448
4631
  trusted: placement.trusted,
4449
4632
  options: OptionsSchema.parse(row.options),
4450
4633
  reason: row.reason,
4451
4634
  holding: {
4452
4635
  workspaces: held.length,
4636
+ stopped,
4453
4637
  for: normalizePrincipals(held.map((entry) => entry.external_user_id && !isProjectPrincipal(entry.external_user_id) ? { user: entry.external_user_id } : entry.chat_key ? { project: entry.project_id, key: entry.chat_key } : { project: entry.project_id }))
4454
4638
  },
4455
- idleSince: (state === "serving" || state === "draining") && Number(load?.holding ?? 0) === 0 ? latest([
4639
+ quietSince: (state === "serving" || state === "draining") && quiet ? latest([
4456
4640
  row.phase_since,
4457
4641
  load?.last_released ?? null,
4458
- worker?.enrolled_at ?? null
4642
+ worker?.enrolled_at ?? null,
4643
+ ...held.flatMap((entry) => [
4644
+ entry.created_at,
4645
+ dateOf(entry.last_turn_at),
4646
+ dateOf(entry.last_used_at)
4647
+ ])
4459
4648
  ]).toISOString() : null,
4460
4649
  lastSeenAt: worker?.last_seen_at?.toISOString() ?? null,
4461
4650
  capacity: everConnected && node?.capacity ? node.capacity : null,
@@ -4481,12 +4670,13 @@ class MachineStore {
4481
4670
  startAsked: row.verb_done_at !== null,
4482
4671
  destroyRequestedAt: row.destroy_requested_at?.toISOString() ?? null,
4483
4672
  lostAfterMinutes: row.lost_after_minutes,
4484
- revoked: Boolean(worker?.revoked_at)
4673
+ revoked: Boolean(worker?.revoked_at),
4674
+ connectedPending: row.connect_pending
4485
4675
  };
4486
4676
  });
4487
4677
  }
4488
4678
  async now() {
4489
- const clock = await sql3`SELECT now() AS now`.execute(this.deps.db);
4679
+ const clock = await sql4`SELECT now() AS now`.execute(this.deps.db);
4490
4680
  return (clock.rows[0]?.now ?? new Date).toISOString();
4491
4681
  }
4492
4682
  async work() {
@@ -4501,8 +4691,9 @@ class MachineStore {
4501
4691
  "placement_waits.requirements",
4502
4692
  "placement_waits.reason",
4503
4693
  "placement_waits.waiting_since",
4694
+ "placement_waits.worker_node_id",
4504
4695
  "work_accounts.disabled_at",
4505
- sql3`EXISTS (SELECT 1 FROM environment_cache_fills WHERE id = placement_waits.root_workload_id)`.as("fill")
4696
+ sql4`EXISTS (SELECT 1 FROM environment_cache_fills WHERE id = placement_waits.root_workload_id)`.as("fill")
4506
4697
  ]).where("placement_waits.tenant_id", "=", this.deps.tenantId).where("placement_waits.last_tried_at", ">", waitFresh()).where(queuedPlacementWait(this.deps.db)).orderBy("placement_waits.waiting_since").execute();
4507
4698
  const work = [];
4508
4699
  for (const row of rows) {
@@ -4522,26 +4713,31 @@ class MachineStore {
4522
4713
  pool: pool.data,
4523
4714
  requirements: requirements.data,
4524
4715
  reason: row.reason === "unavailable" ? "unavailable" : "capacity",
4716
+ machine: row.worker_node_id?.startsWith(WORKER_NODE_PREFIX) ? row.worker_node_id.slice(WORKER_NODE_PREFIX.length) : null,
4525
4717
  waitingSince: row.waiting_since.toISOString()
4526
4718
  });
4527
4719
  }
4528
- return work;
4720
+ return [...work, ...await this.signIns.waiting()];
4529
4721
  }
4530
4722
  async signature() {
4531
4723
  const row = await this.deps.db.selectNoFrom((eb) => [
4532
- eb.selectFrom("placement_waits").select(sql3`count(*)::text || '/' || coalesce(max(waiting_since)::text, '')`.as("waits")).where("tenant_id", "=", this.deps.tenantId).where("last_tried_at", ">", waitFresh()).where(queuedPlacementWait(this.deps.db)).as("waits"),
4533
- eb.selectFrom("execution_allocations").select(sql3`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as("work")).where("tenant_id", "=", this.deps.tenantId).where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).as("work"),
4534
- eb.selectFrom("work_machines").select(sql3`coalesce(string_agg(name || ':' || phase || ':' || (dropped_at IS NOT NULL)::text || ':' || (disabled_at IS NOT NULL)::text, ',' ORDER BY name), '')`.as("machines")).where("tenant_id", "=", this.deps.tenantId).as("machines"),
4535
- eb.selectFrom("work_accounts").select(sql3`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as("accounts")).as("accounts"),
4536
- eb.selectFrom("memberships").select(sql3`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as("roles")).as("roles")
4724
+ eb.selectFrom("placement_waits").select(sql4`count(*)::text || '/' || coalesce(max(waiting_since)::text, '')`.as("waits")).where("tenant_id", "=", this.deps.tenantId).where("last_tried_at", ">", waitFresh()).where(queuedPlacementWait(this.deps.db)).as("waits"),
4725
+ eb.selectFrom("execution_allocations").select(sql4`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || count(*) FILTER (WHERE status = 'stopped')::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as("work")).where("tenant_id", "=", this.deps.tenantId).where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).as("work"),
4726
+ eb.selectFrom("work_machines").select(sql4`coalesce(string_agg(name || ':' || phase || ':' || (dropped_at IS NOT NULL)::text || ':' || (disabled_at IS NOT NULL)::text || ':' || spare::text || ':' || connect_pending::text, ',' ORDER BY name), '')`.as("machines")).where("tenant_id", "=", this.deps.tenantId).as("machines"),
4727
+ eb.selectFrom("machine_preparations").select(sql4`coalesce(string_agg(id::text || ':' || status, ',' ORDER BY id), '')`.as("preparations")).where("tenant_id", "=", this.deps.tenantId).as("preparations"),
4728
+ eb.selectFrom("work_accounts").select(sql4`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as("accounts")).as("accounts"),
4729
+ eb.selectFrom("memberships").select(sql4`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as("roles")).as("roles"),
4730
+ this.signIns.signature().as("signIns")
4537
4731
  ]).executeTakeFirst();
4538
4732
  const reach = [...await this.reach()].map(([name, entry]) => `${name}:${entry.state}`).join(",");
4539
4733
  return [
4540
4734
  row?.waits ?? "",
4541
4735
  row?.work ?? "",
4542
4736
  row?.machines ?? "",
4737
+ row?.preparations ?? "",
4543
4738
  row?.accounts ?? "",
4544
4739
  row?.roles ?? "",
4740
+ row?.signIns ?? "",
4545
4741
  reach
4546
4742
  ].join("|");
4547
4743
  }
@@ -4555,9 +4751,9 @@ class MachineStore {
4555
4751
  "machine.disabled_at",
4556
4752
  "machine.lost_at",
4557
4753
  "machine.lost_after_minutes",
4558
- sql3`coalesce(node.enabled AND node.lease_expires_at > now() AND worker.revoked_at IS NULL, false)`.as("live"),
4559
- sql3`(extract(epoch from (now() - coalesce(worker.last_seen_at, worker.enrolled_at, machine.phase_since))) * 1000)::float8`.as("unseen_for_ms"),
4560
- sql3`(extract(epoch from (now() - machine.verb_done_at)) * 1000)::float8`.as("start_asked_for_ms")
4754
+ sql4`coalesce(node.enabled AND node.lease_expires_at > now() AND worker.revoked_at IS NULL, false)`.as("live"),
4755
+ sql4`(extract(epoch from (now() - coalesce(worker.last_seen_at, worker.enrolled_at, machine.phase_since))) * 1000)::float8`.as("unseen_for_ms"),
4756
+ sql4`(extract(epoch from (now() - machine.verb_done_at)) * 1000)::float8`.as("start_asked_for_ms")
4561
4757
  ]).where("machine.tenant_id", "=", this.deps.tenantId).execute();
4562
4758
  return new Map(rows.map((row) => [
4563
4759
  row.name,
@@ -4587,6 +4783,12 @@ function hash(value) {
4587
4783
  function principalsJson(principals) {
4588
4784
  return principals === null ? null : JSON.stringify(normalizePrincipals(principals));
4589
4785
  }
4786
+ function dateOf(value) {
4787
+ return value === null ? null : new Date(value);
4788
+ }
4789
+ function usedWithin(args) {
4790
+ return args.at !== null && args.now.getTime() - args.at.getTime() < args.seconds * 1000;
4791
+ }
4590
4792
  function latest(dates) {
4591
4793
  return dates.reduce((best, date) => date && date > best ? date : best, new Date(0));
4592
4794
  }
@@ -4624,13 +4826,14 @@ function signedInOf(node) {
4624
4826
  return [...members].sort();
4625
4827
  }
4626
4828
  function waitFresh() {
4627
- return sql3`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
4829
+ return sql4`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
4628
4830
  }
4629
4831
  function queuedPlacementWait(db) {
4630
- const turns = db.selectFrom("agent_turns").select("id").where("session_id", "=", sql3`placement_waits.root_workload_id`).where("status", "=", "queued");
4631
- const jobs = db.selectFrom("workflow_runs as root").innerJoin("workflow_runs as run", "run.allocation_id", "root.allocation_id").innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id").select("job.id").where("root.id", "=", sql3`placement_waits.root_workload_id`).where("root.status", "in", ["pending", "running", "waiting"]).where("run.status", "in", ["pending", "running", "waiting"]).where("job.status", "=", "pending").where("job.kind", "not in", [...PLACEMENT_FREE_JOB_KINDS]).where("job.available_at", "<=", sql3`now()`);
4632
- const fills = db.selectFrom("environment_cache_fills").select("id").where("id", "=", sql3`placement_waits.root_workload_id`).where("status", "=", "queued");
4633
- return sql3`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
4832
+ const turns = db.selectFrom("agent_turns").select("id").where("session_id", "=", sql4`placement_waits.root_workload_id`).where("status", "=", "queued");
4833
+ const jobs = db.selectFrom("workflow_runs as root").innerJoin("workflow_runs as run", "run.allocation_id", "root.allocation_id").innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id").select("job.id").where("root.id", "=", sql4`placement_waits.root_workload_id`).where("root.status", "in", ["pending", "running", "waiting"]).where("run.status", "in", ["pending", "running", "waiting"]).where("job.status", "=", "pending").where("job.kind", "not in", [...PLACEMENT_FREE_JOB_KINDS]).where("job.available_at", "<=", sql4`now()`);
4834
+ const fills = db.selectFrom("environment_cache_fills").select("id").where("id", "=", sql4`placement_waits.root_workload_id`).where("status", "=", "queued");
4835
+ return sql4`(placement_waits.worker_node_id IS NOT NULL OR
4836
+ (placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
4634
4837
  (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})) OR
4635
4838
  EXISTS (${fills}))`;
4636
4839
  }
@@ -4811,6 +5014,7 @@ class WorkWorkerRegistry {
4811
5014
  managed: row.managed,
4812
5015
  labels: placement.labels,
4813
5016
  for: placement.for,
5017
+ project: row.project_id,
4814
5018
  options: z10.record(z10.string(), z10.unknown()).parse(row.options),
4815
5019
  reason: row.reason
4816
5020
  },
@@ -4841,13 +5045,13 @@ class WorkWorkerRegistry {
4841
5045
  throw await this.ended(args);
4842
5046
  }
4843
5047
  async seen(nodeId) {
4844
- await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql4`now()` }).where("node_id", "=", nodeId).where((eb) => eb.or([
5048
+ await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql5`now()` }).where("node_id", "=", nodeId).where((eb) => eb.or([
4845
5049
  eb("last_seen_at", "is", null),
4846
- eb("last_seen_at", "<", sql4`now() - interval '5 seconds'`)
5050
+ eb("last_seen_at", "<", sql5`now() - interval '5 seconds'`)
4847
5051
  ])).execute();
4848
5052
  }
4849
5053
  async serving(args) {
4850
- await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql4`now()` }).where("node_id", "=", args.nodeId).where("last_seen_at", "is", null).execute();
5054
+ await this.deps.db.updateTable("work_workers").set({ last_seen_at: sql5`now()` }).where("node_id", "=", args.nodeId).where("last_seen_at", "is", null).execute();
4851
5055
  const { name } = args;
4852
5056
  if (await this.machines.setPhase({
4853
5057
  name,
@@ -4917,7 +5121,7 @@ class WorkWorkerRegistry {
4917
5121
  const machine = await trx.selectFrom("work_machines").select(["phase", "disabled_at", "dropped_at"]).where("tenant_id", "=", this.deps.tenantId).where("name", "=", enrollment.name).forUpdate().executeTakeFirst();
4918
5122
  if (machine?.phase !== "starting" || machine.dropped_at)
4919
5123
  throw invalid();
4920
- const consumed = await trx.updateTable("work_worker_enrollments").set({ used_at: sql4`now()` }).where("code_hash", "=", codeHash).where("tenant_id", "=", this.deps.tenantId).where("used_at", "is", null).where("expires_at", ">", sql4`now()`).returning("code_hash").executeTakeFirst();
5124
+ const consumed = await trx.updateTable("work_worker_enrollments").set({ used_at: sql5`now()` }).where("code_hash", "=", codeHash).where("tenant_id", "=", this.deps.tenantId).where("used_at", "is", null).where("expires_at", ">", sql5`now()`).returning("code_hash").executeTakeFirst();
4921
5125
  if (!consumed)
4922
5126
  throw invalid();
4923
5127
  const nodeId = `${WORKER_NODE_PREFIX}${enrollment.name}`;
@@ -4932,7 +5136,7 @@ class WorkWorkerRegistry {
4932
5136
  await trx.updateTable("worker_nodes").set({
4933
5137
  enabled: machine.disabled_at === null,
4934
5138
  admission_revision: null,
4935
- lease_expires_at: sql4`now()`,
5139
+ lease_expires_at: sql5`now()`,
4936
5140
  disk: null,
4937
5141
  disk_low_at: null,
4938
5142
  disk_low_recorded_at: null
@@ -4961,7 +5165,7 @@ class WorkWorkerRegistry {
4961
5165
  return;
4962
5166
  const nodeId = match[1];
4963
5167
  const presented = hash2(match[2]);
4964
- const row = await this.deps.db.selectFrom("work_workers").select(["name", "credential_hash", "pending_credential_hash"]).select(sql4`rotation_requested_at IS NOT NULL OR credential_issued_at < now() - make_interval(days => ${WORKER_CREDENTIAL_MAX_AGE_DAYS})`.as("rotate")).where("node_id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).where("revoked_at", "is", null).executeTakeFirst();
5168
+ const row = await this.deps.db.selectFrom("work_workers").select(["name", "credential_hash", "pending_credential_hash"]).select(sql5`rotation_requested_at IS NOT NULL OR credential_issued_at < now() - make_interval(days => ${WORKER_CREDENTIAL_MAX_AGE_DAYS})`.as("rotate")).where("node_id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).where("revoked_at", "is", null).executeTakeFirst();
4965
5169
  if (!row)
4966
5170
  return;
4967
5171
  if (sameHash(row.credential_hash, presented))
@@ -4986,13 +5190,13 @@ class WorkWorkerRegistry {
4986
5190
  return;
4987
5191
  const promoted = await trx.updateTable("work_workers").set({
4988
5192
  credential_hash: args.credentialHash,
4989
- credential_issued_at: sql4`COALESCE(pending_issued_at, now())`,
5193
+ credential_issued_at: sql5`COALESCE(pending_issued_at, now())`,
4990
5194
  pending_credential_hash: null,
4991
5195
  pending_public_key: null,
4992
5196
  pending_issued_at: null,
4993
5197
  pending_rotation: null,
4994
- rotation_requested_at: sql4`CASE WHEN rotation_requested_at <= pending_issued_at THEN NULL ELSE rotation_requested_at END`
4995
- }).where("node_id", "=", args.nodeId).returning(sql4`rotation_requested_at IS NOT NULL`.as("rotate")).executeTakeFirstOrThrow();
5198
+ rotation_requested_at: sql5`CASE WHEN rotation_requested_at <= pending_issued_at THEN NULL ELSE rotation_requested_at END`
5199
+ }).where("node_id", "=", args.nodeId).returning(sql5`rotation_requested_at IS NOT NULL`.as("rotate")).executeTakeFirstOrThrow();
4996
5200
  await registerExecutorKey({
4997
5201
  db: trx,
4998
5202
  executor: nodeExecutor(args.nodeId),
@@ -5016,14 +5220,14 @@ class WorkWorkerRegistry {
5016
5220
  await trx.updateTable("work_workers").set({
5017
5221
  pending_credential_hash: hash2(secret),
5018
5222
  pending_public_key: publicKey,
5019
- pending_issued_at: sql4`now()`,
5223
+ pending_issued_at: sql5`now()`,
5020
5224
  pending_rotation: args.rotation
5021
5225
  }).where("node_id", "=", args.nodeId).execute();
5022
5226
  });
5023
5227
  return { credential: `${args.nodeId}:${secret}` };
5024
5228
  }
5025
5229
  async requestRotation(args) {
5026
- const row = await this.deps.db.updateTable("work_workers").set({ rotation_requested_at: sql4`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", WorkerName.parse(args.name)).where("revoked_at", "is", null).returning("node_id").executeTakeFirst();
5230
+ const row = await this.deps.db.updateTable("work_workers").set({ rotation_requested_at: sql5`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", WorkerName.parse(args.name)).where("revoked_at", "is", null).returning("node_id").executeTakeFirst();
5027
5231
  return Boolean(row);
5028
5232
  }
5029
5233
  async connect(args) {
@@ -5135,8 +5339,8 @@ class WorkWorkerRegistry {
5135
5339
  async setDisabled(args) {
5136
5340
  const name = WorkerName.parse(args.name);
5137
5341
  const row = await this.deps.db.updateTable("work_machines").set({
5138
- disabled_at: args.disabled ? sql4`coalesce(disabled_at, now())` : null,
5139
- updated_at: sql4`now()`
5342
+ disabled_at: args.disabled ? sql5`coalesce(disabled_at, now())` : null,
5343
+ updated_at: sql5`now()`
5140
5344
  }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).returning("phase").executeTakeFirst();
5141
5345
  if (!row)
5142
5346
  return false;
@@ -5159,7 +5363,7 @@ class WorkWorkerRegistry {
5159
5363
  }
5160
5364
  cleaning;
5161
5365
  async forgetNeverEnrolled() {
5162
- await this.deps.db.deleteFrom("work_machines").where("tenant_id", "=", this.deps.tenantId).where("managed", "=", false).where("phase", "=", "starting").where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_workers").select("work_workers.node_id").whereRef("work_workers.tenant_id", "=", "work_machines.tenant_id").whereRef("work_workers.name", "=", "work_machines.name").where("work_workers.revoked_at", "is", null)))).where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_worker_enrollments").select("work_worker_enrollments.code_hash").whereRef("work_worker_enrollments.tenant_id", "=", "work_machines.tenant_id").whereRef("work_worker_enrollments.name", "=", "work_machines.name").where("work_worker_enrollments.used_at", "is", null).where("work_worker_enrollments.expires_at", ">", sql4`now()`)))).execute();
5366
+ await this.deps.db.deleteFrom("work_machines").where("tenant_id", "=", this.deps.tenantId).where("managed", "=", false).where("phase", "=", "starting").where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_workers").select("work_workers.node_id").whereRef("work_workers.tenant_id", "=", "work_machines.tenant_id").whereRef("work_workers.name", "=", "work_machines.name").where("work_workers.revoked_at", "is", null)))).where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_worker_enrollments").select("work_worker_enrollments.code_hash").whereRef("work_worker_enrollments.tenant_id", "=", "work_machines.tenant_id").whereRef("work_worker_enrollments.name", "=", "work_machines.name").where("work_worker_enrollments.used_at", "is", null).where("work_worker_enrollments.expires_at", ">", sql5`now()`)))).execute();
5163
5367
  }
5164
5368
  async retireGone() {
5165
5369
  const revoked = await this.deps.db.selectFrom("work_workers").select(["node_id", "name"]).where("tenant_id", "=", this.deps.tenantId).where("revoked_at", "is not", null).where(({ exists, selectFrom }) => exists(selectFrom("execution_allocations").select("execution_allocations.id").whereRef("execution_allocations.worker_node_id", "=", "work_workers.node_id").where("execution_allocations.capacity_released_at", "is", null))).execute();
@@ -5175,7 +5379,7 @@ class WorkWorkerRegistry {
5175
5379
  await this.retire({ nodeId: machine.nodeId, name, reason: "lost" });
5176
5380
  if (machine.managed || machine.lostNoted)
5177
5381
  continue;
5178
- const noted = await this.deps.db.updateTable("work_machines").set({ lost_at: sql4`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).where("lost_at", "is", null).returning("name").executeTakeFirst();
5382
+ const noted = await this.deps.db.updateTable("work_machines").set({ lost_at: sql5`now()` }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).where("lost_at", "is", null).returning("name").executeTakeFirst();
5179
5383
  if (noted)
5180
5384
  await this.emit({ kind: "machine.lost", name });
5181
5385
  }
@@ -5218,7 +5422,8 @@ class WorkWorkerRegistry {
5218
5422
  nodeId: node.id,
5219
5423
  offer: node.remote,
5220
5424
  label: "The worker"
5221
- })
5425
+ }),
5426
+ ...this.deps.roomFreed ? { roomFreed: this.deps.roomFreed } : {}
5222
5427
  }).catch((error) => this.deps.log?.(`Workspace cleanup on ${node.id} deferred: ${error instanceof Error ? error.message : String(error)}`));
5223
5428
  }
5224
5429
  }
@@ -5232,7 +5437,7 @@ class WorkWorkerRegistry {
5232
5437
  const nodeId = `${WORKER_NODE_PREFIX}${name}`;
5233
5438
  await trx.selectFrom("worker_nodes").select("id").where("id", "=", nodeId).forUpdate().executeTakeFirst();
5234
5439
  const worker = await trx.updateTable("work_workers").set({
5235
- revoked_at: sql4`now()`,
5440
+ revoked_at: sql5`now()`,
5236
5441
  pending_credential_hash: null,
5237
5442
  pending_public_key: null,
5238
5443
  pending_issued_at: null,
@@ -5282,10 +5487,10 @@ class WorkWorkerRegistry {
5282
5487
  const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
5283
5488
  return this.deps.db.transaction().execute(async (trx) => {
5284
5489
  await this.machines.lockName({ name: args.name, transaction: trx });
5285
- const node = await trx.selectFrom("worker_nodes").select(sql4`enabled AND lease_expires_at > now()`.as("live")).where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).forUpdate().executeTakeFirst();
5490
+ const node = await trx.selectFrom("worker_nodes").select(sql5`enabled AND lease_expires_at > now()`.as("live")).where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).forUpdate().executeTakeFirst();
5286
5491
  const worker = await trx.selectFrom("work_workers").select([
5287
5492
  "revoked_at",
5288
- sql4`(extract(epoch from (now() - coalesce(last_seen_at, enrolled_at))) * 1000)::float8`.as("unseen_for_ms")
5493
+ sql5`(extract(epoch from (now() - coalesce(last_seen_at, enrolled_at))) * 1000)::float8`.as("unseen_for_ms")
5289
5494
  ]).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).executeTakeFirst();
5290
5495
  const serving = worker !== undefined && worker.revoked_at === null;
5291
5496
  if (args.lost) {
@@ -5294,7 +5499,11 @@ class WorkWorkerRegistry {
5294
5499
  if (serving && Number(worker.unseen_for_ms) < args.lost.unseenForMs)
5295
5500
  return false;
5296
5501
  } else if (serving) {
5297
- const held = await trx.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", nodeId).where("capacity_released_at", "is", null).executeTakeFirst();
5502
+ const machine = await this.machines.row({
5503
+ name: args.name,
5504
+ transaction: trx
5505
+ });
5506
+ const held = await trx.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", nodeId).where("capacity_released_at", "is", null).where("status", "not in", machine?.phase === "running" ? ["stopped"] : ["stopped", "released"]).executeTakeFirst();
5298
5507
  if (Number(held?.count ?? 0) > 0)
5299
5508
  return false;
5300
5509
  }
@@ -5310,7 +5519,7 @@ class WorkWorkerRegistry {
5310
5519
  if (!serving)
5311
5520
  return true;
5312
5521
  await trx.updateTable("work_workers").set({
5313
- revoked_at: sql4`now()`,
5522
+ revoked_at: sql5`now()`,
5314
5523
  pending_credential_hash: null,
5315
5524
  pending_public_key: null,
5316
5525
  pending_issued_at: null,
@@ -5325,7 +5534,7 @@ class WorkWorkerRegistry {
5325
5534
  const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
5326
5535
  return this.deps.db.transaction().execute(async (trx) => {
5327
5536
  await trx.selectFrom("worker_nodes").select("id").where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).forUpdate().executeTakeFirst();
5328
- const held = await trx.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", nodeId).where("capacity_released_at", "is", null).executeTakeFirst();
5537
+ const held = await trx.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", nodeId).where("capacity_released_at", "is", null).where("status", "<>", "stopped").executeTakeFirst();
5329
5538
  if (Number(held?.count ?? 0) > 0)
5330
5539
  return false;
5331
5540
  const moved = await this.machines.setPhase({
@@ -5361,13 +5570,13 @@ class WorkWorkerRegistry {
5361
5570
  await trx.updateTable("worker_nodes").set({
5362
5571
  enabled: machine?.disabled_at === null,
5363
5572
  admission_revision: null,
5364
- lease_expires_at: sql4`now()`
5573
+ lease_expires_at: sql5`now()`
5365
5574
  }).where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).where("authority_id", "=", this.deps.authorityId).execute();
5366
5575
  return true;
5367
5576
  });
5368
5577
  }
5369
5578
  async holding(args) {
5370
- const row = await this.deps.db.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", `${WORKER_NODE_PREFIX}${args.name}`).where("capacity_released_at", "is", null).executeTakeFirst();
5579
+ const row = await this.deps.db.selectFrom("execution_allocations").select((eb) => eb.fn.countAll().as("count")).where("worker_node_id", "=", `${WORKER_NODE_PREFIX}${args.name}`).where("capacity_released_at", "is", null).where("status", "<>", "stopped").executeTakeFirst();
5371
5580
  return Number(row?.count ?? 0);
5372
5581
  }
5373
5582
  async activeWorkspaces(args) {
@@ -5412,6 +5621,11 @@ class WorkWorkerRegistry {
5412
5621
  if (await this.holding({ name }) > 0)
5413
5622
  return "busy";
5414
5623
  await this.resetMachine({ name, timeoutMs });
5624
+ await this.retire({
5625
+ nodeId: `${WORKER_NODE_PREFIX}${name}`,
5626
+ name,
5627
+ reason: "replaced"
5628
+ });
5415
5629
  await this.machines.finishReset({ name });
5416
5630
  return "done";
5417
5631
  } finally {
@@ -5429,6 +5643,7 @@ class WorkWorkerRegistry {
5429
5643
  ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}
5430
5644
  });
5431
5645
  await this.deps.db.updateTable("environment_cache_fills").set({ status: "evicted" }).where("worker_node_id", "=", nodeId).where("status", "=", "succeeded").execute();
5646
+ await this.deps.db.deleteFrom("machine_preparations").where("worker_node_id", "=", nodeId).execute();
5432
5647
  }
5433
5648
  async list() {
5434
5649
  const [records, workers] = await Promise.all([
@@ -5532,7 +5747,8 @@ async function registerWorkMachine(args) {
5532
5747
  workerNodeId,
5533
5748
  allocationBindingId,
5534
5749
  requirements,
5535
- fill
5750
+ fill,
5751
+ environment
5536
5752
  }) => {
5537
5753
  const candidates = await nodes.list({
5538
5754
  tenantId,
@@ -5556,13 +5772,15 @@ async function registerWorkMachine(args) {
5556
5772
  });
5557
5773
  const holdsAllocation = (nodeId) => allocationBindingId === nodeId && workerNodeId === nodeId;
5558
5774
  const eligible = described.filter(({ node, policy, worker, labels }) => node.available && (!worker || policy && (policy.accepting || holdsAllocation(node.id))) && (!allocationBindingId || allocationBindingId === node.id) && (!workerNodeId || workerNodeId === node.id) && poolMatches(labels, pool) && (!requirements || environmentSatisfies(node.descriptor, requirements).compatible) && (!policy || policy.trusted || servesOneOwner(policy.for) || node.descriptor.isolation !== "process"));
5559
- const tierOf = (policy) => accessTier({
5775
+ const tierOf = (policy) => policy?.spare && !chatKey && !fill ? undefined : accessTier2({
5560
5776
  access: policy ? nodeAccess(policy.for) : { everyone: true },
5561
5777
  owner,
5562
5778
  ...projectId ? { projectId } : {},
5563
- ...chatKey ? { chatKey } : {}
5779
+ ...chatKey ? { chatKey } : {},
5780
+ ...fill ? { fill: true } : {}
5564
5781
  });
5565
- const ordered = placementOrder(eligible, ({ node, policy }) => tierOf(policy) ?? (holdsAllocation(node.id) ? 2 : undefined), { strict });
5782
+ const warm = (policy) => Boolean(environment && policy?.prepared?.some((entry) => entry.project === projectId && entry.environment === environment));
5783
+ const ordered = placementOrder([...eligible].sort((left, right) => Number(warm(right.policy)) - Number(warm(left.policy))), ({ node, policy }) => tierOf(policy) ?? (holdsAllocation(node.id) ? 2 : undefined), { strict });
5566
5784
  const storageMb = (requirements?.resources?.storageMb ?? 0) + (fill?.storageMb ?? 0);
5567
5785
  const workload = requirements?.workload && !fill ? { workload: requirements.workload } : {};
5568
5786
  const roomy = ({ node }) => diskFits({
@@ -5600,10 +5818,15 @@ async function registerWorkMachine(args) {
5600
5818
  };
5601
5819
  const servesOnlyOwner = Boolean(chosen.policy && servesOnlyThisOwner(tierOf(chosen.policy)));
5602
5820
  const ownSignIns = servesOnlyOwner || selected.id === lease.id && args.ownSignIns;
5821
+ const ceiling = ownerCeiling({
5822
+ for: chosen.policy?.for ?? null,
5823
+ capacity: chosen.node.capacity
5824
+ });
5603
5825
  return {
5604
5826
  descriptor: selected.descriptor,
5605
5827
  workerNodeId: selected.id,
5606
5828
  ...servesOnlyOwner ? { servesOnlyOwner } : {},
5829
+ ...ceiling ? { ceiling } : {},
5607
5830
  ...ownSignIns ? { ownSignIns: true } : {},
5608
5831
  ...selected.id === lease.id ? {
5609
5832
  sandboxProvider: args.sandboxProvider,
@@ -5698,7 +5921,8 @@ async function registerWorkMachine(args) {
5698
5921
  cleanup = cleanupWorkerAllocations2({
5699
5922
  db: args.db,
5700
5923
  workerNode: lease,
5701
- provider: args.sandboxProvider
5924
+ provider: args.sandboxProvider,
5925
+ ...args.roomFreed ? { roomFreed: args.roomFreed } : {}
5702
5926
  }).catch((error) => console.warn("[catamorphic] Workspace cleanup deferred", error)).finally(() => {
5703
5927
  cleanup = undefined;
5704
5928
  });
@@ -5715,7 +5939,7 @@ async function registerWorkMachine(args) {
5715
5939
  if (JSON.stringify(next) === JSON.stringify(signIns))
5716
5940
  return;
5717
5941
  signIns = next;
5718
- refreshing = args.db.updateTable("worker_nodes").set({ descriptor: JSON.stringify(describe()), updated_at: sql5`now()` }).where("id", "=", lease.id).where("lease_token", "=", lease.token).execute().catch((error) => console.warn("[catamorphic] Could not refresh this machine's sign-ins", error)).finally(() => {
5942
+ refreshing = args.db.updateTable("worker_nodes").set({ descriptor: JSON.stringify(describe()), updated_at: sql6`now()` }).where("id", "=", lease.id).where("lease_token", "=", lease.token).execute().catch((error) => console.warn("[catamorphic] Could not refresh this machine's sign-ins", error)).finally(() => {
5719
5943
  refreshing = undefined;
5720
5944
  if (!again)
5721
5945
  return;
@@ -5760,6 +5984,15 @@ function workPushKeys(secret) {
5760
5984
  }
5761
5985
  throw new Error("Could not derive the deployment's notification signing key");
5762
5986
  }
5987
+ function ownerCeiling(args) {
5988
+ if (!servesOneOwner(args.for) || !args.capacity)
5989
+ return;
5990
+ const { cpuMillis, memoryMb } = args.capacity;
5991
+ return cpuMillis === undefined && memoryMb === undefined ? undefined : {
5992
+ ...cpuMillis !== undefined ? { cpuMillis } : {},
5993
+ ...memoryMb !== undefined ? { memoryMb } : {}
5994
+ };
5995
+ }
5763
5996
 
5764
5997
  // src/company-sync.ts
5765
5998
  import {
@@ -5916,7 +6149,7 @@ import {
5916
6149
  DIRECTORY_EVENT_SOURCE,
5917
6150
  directoryProjectEvent
5918
6151
  } from "@catamorphic/server-sdk";
5919
- import { sql as sql6 } from "kysely";
6152
+ import { sql as sql7 } from "kysely";
5920
6153
  var tracer = getTracer("@catamorphic/work-server");
5921
6154
 
5922
6155
  class AccountLifecycle {
@@ -6124,7 +6357,7 @@ class AccountLifecycle {
6124
6357
  let claimed;
6125
6358
  try {
6126
6359
  return await this.deps.db.transaction().execute(async (trx) => {
6127
- const row = await trx.selectFrom("work_directory_announcements as event").selectAll("event").where("event.next_attempt_at", "<=", sql6`now()`).$if(input.externalId !== undefined, (query) => query.where("event.external_id", "=", input.externalId ?? "")).where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_directory_announcements as earlier").select("earlier.id").whereRef("earlier.user_id", "=", "event.user_id").whereRef("earlier.revision", "<", "event.revision")))).orderBy("event.created_at").limit(1).forUpdate().skipLocked().executeTakeFirst();
6360
+ const row = await trx.selectFrom("work_directory_announcements as event").selectAll("event").where("event.next_attempt_at", "<=", sql7`now()`).$if(input.externalId !== undefined, (query) => query.where("event.external_id", "=", input.externalId ?? "")).where(({ not, exists, selectFrom }) => not(exists(selectFrom("work_directory_announcements as earlier").select("earlier.id").whereRef("earlier.user_id", "=", "event.user_id").whereRef("earlier.revision", "<", "event.revision")))).orderBy("event.created_at").limit(1).forUpdate().skipLocked().executeTakeFirst();
6128
6361
  if (!row)
6129
6362
  return "none";
6130
6363
  claimed = {
@@ -6152,7 +6385,7 @@ class AccountLifecycle {
6152
6385
  await this.deps.db.updateTable("work_directory_announcements").set({
6153
6386
  attempts: attempts + 1,
6154
6387
  last_error: message,
6155
- next_attempt_at: sql6`now() + make_interval(secs => ${Math.min(300, 2 ** attempts)})`
6388
+ next_attempt_at: sql7`now() + make_interval(secs => ${Math.min(300, 2 ** attempts)})`
6156
6389
  }).where("id", "=", claimed.id).execute();
6157
6390
  this.deps.log?.(`Directory event ${claimed.externalId} did not reach its projects (attempt ${attempts + 1}): ${message}`);
6158
6391
  return "failed";
@@ -6513,6 +6746,8 @@ function workMachineWorld(deps) {
6513
6746
  created: (args) => machines.created(args),
6514
6747
  refused: (args) => machines.refused(args),
6515
6748
  configure: (args) => machines.configure(args),
6749
+ prepare: (args) => deps.prepare(args),
6750
+ heardConnected: (args) => machines.heardConnected(args),
6516
6751
  setFor: (args) => machines.setFor(args),
6517
6752
  beginReset: (args) => machines.beginReset(args),
6518
6753
  reset: ({ name }) => workers.resetPlacement({
@@ -6523,7 +6758,12 @@ function workMachineWorld(deps) {
6523
6758
  undrop: ({ name }) => machines.setDropped({ name, dropped: false }),
6524
6759
  retire: (args) => workers.retireMachine(args),
6525
6760
  declareLost: (args) => workers.declareLost(args),
6526
- beginStop: (args) => workers.beginStop(args),
6761
+ beginStop: async (args) => {
6762
+ await deps.stopQuietWorkspaces?.({
6763
+ workerNodeId: `${WORKER_NODE_PREFIX}${args.name}`
6764
+ });
6765
+ return workers.beginStop(args);
6766
+ },
6527
6767
  stopped: async ({ name }) => {
6528
6768
  await machines.setPhase({ name, phase: "stopped", from: ["stopping"] });
6529
6769
  },
@@ -7662,7 +7902,7 @@ import {
7662
7902
  identityMayUseEnvironment,
7663
7903
  normalizeDocumentPath
7664
7904
  } from "@catamorphic/core";
7665
- import { sql as sql7 } from "kysely";
7905
+ import { sql as sql8 } from "kysely";
7666
7906
  import { z as z17 } from "zod";
7667
7907
  var CreateShareSchema = z17.strictObject({
7668
7908
  kind: z17.enum(["document", "folder", "app"]),
@@ -7728,7 +7968,7 @@ class WorkSharesService {
7728
7968
  if (!hasProjectPermission3(args.identity, args.projectId, "publications:write")) {
7729
7969
  throw new ShareAccessError("Revoking shares needs publications:write");
7730
7970
  }
7731
- const row = await this.deps.db.updateTable("work_shares").set({ revoked_at: sql7`now()` }).where("id", "=", args.shareId).where("project_id", "=", args.projectId).where("revoked_at", "is", null).returning("id").executeTakeFirst();
7971
+ const row = await this.deps.db.updateTable("work_shares").set({ revoked_at: sql8`now()` }).where("id", "=", args.shareId).where("project_id", "=", args.projectId).where("revoked_at", "is", null).returning("id").executeTakeFirst();
7732
7972
  return Boolean(row);
7733
7973
  }
7734
7974
  async isGuest(userId) {
@@ -7741,7 +7981,7 @@ class WorkSharesService {
7741
7981
  async open(args) {
7742
7982
  const row = await this.deps.db.selectFrom("work_shares").innerJoin("projects", "projects.id", "work_shares.project_id").selectAll("work_shares").where("work_shares.id", "=", args.shareId).where("projects.tenant_id", "=", this.deps.tenantId).where("work_shares.revoked_at", "is", null).where(({ or, eb }) => or([
7743
7983
  eb("work_shares.expires_at", "is", null),
7744
- eb("work_shares.expires_at", ">", sql7`now()`)
7984
+ eb("work_shares.expires_at", ">", sql8`now()`)
7745
7985
  ])).executeTakeFirst();
7746
7986
  if (!row)
7747
7987
  return null;
@@ -8269,6 +8509,77 @@ function shareTools(shares, args) {
8269
8509
  ];
8270
8510
  }
8271
8511
 
8512
+ // src/workers/cache-archive-routes.ts
8513
+ import { Readable } from "node:stream";
8514
+ import {
8515
+ CacheArchiveTooLargeError,
8516
+ CacheTransferRefusedError
8517
+ } from "@catamorphic/core";
8518
+ var CACHE_ARCHIVE_ROUTE = "/api/cache-archives";
8519
+ function cacheArchiveUrl(args) {
8520
+ return `${args.base.replace(/\/+$/, "")}${CACHE_ARCHIVE_ROUTE}/${args.transferId}`;
8521
+ }
8522
+ function refuseUpload(args) {
8523
+ const { reply, body } = args;
8524
+ body.resume();
8525
+ reply.raw.once("finish", () => body.destroy());
8526
+ return reply.header("connection", "close").status(args.status).send({ error: args.error });
8527
+ }
8528
+ function bearerOf(request) {
8529
+ const header = request.headers.authorization;
8530
+ const value = Array.isArray(header) ? header[0] : header;
8531
+ return value?.startsWith("Bearer ") ? value.slice("Bearer ".length) : "";
8532
+ }
8533
+ function registerCacheArchiveRoutes(app, archives) {
8534
+ app.register(async (scope) => {
8535
+ scope.addContentTypeParser("application/x-tar", (_request, payload, done) => done(null, payload));
8536
+ scope.put(`${CACHE_ARCHIVE_ROUTE}/:id`, async (request, reply) => {
8537
+ const body = request.body;
8538
+ if (!(body instanceof Readable))
8539
+ return reply.status(415).send({ error: "Send the archive as application/x-tar" });
8540
+ try {
8541
+ return await archives.receive({
8542
+ transferId: request.params.id,
8543
+ token: bearerOf(request),
8544
+ body
8545
+ });
8546
+ } catch (error) {
8547
+ if (error instanceof CacheTransferRefusedError)
8548
+ return refuseUpload({
8549
+ reply,
8550
+ body,
8551
+ status: 404,
8552
+ error: error.message
8553
+ });
8554
+ if (error instanceof CacheArchiveTooLargeError)
8555
+ return refuseUpload({
8556
+ reply,
8557
+ body,
8558
+ status: 413,
8559
+ error: error.message
8560
+ });
8561
+ body.destroy();
8562
+ throw error;
8563
+ }
8564
+ });
8565
+ scope.get(`${CACHE_ARCHIVE_ROUTE}/:id`, async (request, reply) => {
8566
+ try {
8567
+ const archive = await archives.send({
8568
+ transferId: request.params.id,
8569
+ token: bearerOf(request)
8570
+ });
8571
+ if (!archive)
8572
+ return reply.status(404).send({ error: "The store has no archive of this cache" });
8573
+ return reply.header("content-type", "application/x-tar").send(Readable.from(archive));
8574
+ } catch (error) {
8575
+ if (error instanceof CacheTransferRefusedError)
8576
+ return reply.status(404).send({ error: error.message });
8577
+ throw error;
8578
+ }
8579
+ });
8580
+ });
8581
+ }
8582
+
8272
8583
  // src/workers/disk-care.ts
8273
8584
  import fs10 from "node:fs";
8274
8585
  import path8 from "node:path";
@@ -8425,8 +8736,12 @@ function startDiskCare(args) {
8425
8736
  import { spawn } from "node:child_process";
8426
8737
  import { randomUUID as randomUUID8 } from "node:crypto";
8427
8738
  import fs11 from "node:fs";
8739
+ import path9 from "node:path";
8428
8740
  import {
8429
- SIGN_IN_SPECS as SIGN_IN_SPECS2
8741
+ SANDBOX_CAPABILITIES as SANDBOX_CAPABILITIES2,
8742
+ SIGN_IN_SPECS as SIGN_IN_SPECS2,
8743
+ signInHomePath,
8744
+ spawnInSandbox
8430
8745
  } from "@catamorphic/sandbox";
8431
8746
  import { z as z21 } from "zod";
8432
8747
  var SIGN_IN_INPUT_MAX = 4096;
@@ -8451,6 +8766,7 @@ var CODE_TIMEOUT_MS = 30000;
8451
8766
  var DEFAULT_CODE_MINUTES = 15;
8452
8767
  var EXIT_DRAIN_MS = 500;
8453
8768
  var FINISHED_TTL_MS = 60 * 60000;
8769
+ var SANDBOX_NOTE = ".sandbox";
8454
8770
  function plainOutput(text) {
8455
8771
  return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
8456
8772
  }
@@ -8518,6 +8834,97 @@ class HarnessSignIns {
8518
8834
  constructor(options) {
8519
8835
  this.options = options;
8520
8836
  }
8837
+ recovered;
8838
+ recover() {
8839
+ this.recovered ??= (async () => {
8840
+ const pending = path9.join(this.options.signInRoot, ".pending");
8841
+ let names;
8842
+ try {
8843
+ names = fs11.readdirSync(pending);
8844
+ } catch {
8845
+ return;
8846
+ }
8847
+ for (const name of names) {
8848
+ if (!name.endsWith(SANDBOX_NOTE))
8849
+ continue;
8850
+ const note = path9.join(pending, name);
8851
+ const id = fs11.readFileSync(note, "utf8").trim();
8852
+ if (id)
8853
+ await this.options.provider?.destroySandbox(id).catch(() => {
8854
+ return;
8855
+ });
8856
+ fs11.rmSync(note.slice(0, -SANDBOX_NOTE.length), {
8857
+ recursive: true,
8858
+ force: true
8859
+ });
8860
+ fs11.rmSync(note, { force: true });
8861
+ }
8862
+ })();
8863
+ return this.recovered;
8864
+ }
8865
+ imageSandboxes() {
8866
+ const provider = this.options.provider;
8867
+ return provider?.processes && provider.capabilities?.includes(SANDBOX_CAPABILITIES2.images) ? provider : undefined;
8868
+ }
8869
+ async startLogin(input) {
8870
+ const spec = SIGN_IN_SPECS2[input.harness];
8871
+ const provider = this.imageSandboxes();
8872
+ if (!provider?.processes) {
8873
+ const login = signInCommand({
8874
+ harness: input.harness,
8875
+ home: input.staging
8876
+ });
8877
+ const child = spawn(login.command, login.args, {
8878
+ env: signInEnvironment({
8879
+ harness: input.harness,
8880
+ base: this.options.env ?? process.env,
8881
+ login: { ...login.env, NO_COLOR: "1" }
8882
+ }),
8883
+ stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"]
8884
+ });
8885
+ return { child, release: async () => {} };
8886
+ }
8887
+ const processes = provider.processes;
8888
+ let handle;
8889
+ try {
8890
+ handle = await provider.createSandbox({
8891
+ ...input.sandbox?.image ? { image: input.sandbox.image } : {},
8892
+ ...input.sandbox?.egress ? { egress: input.sandbox.egress } : {},
8893
+ signInLogin: {
8894
+ harness: input.harness,
8895
+ pending: path9.basename(input.staging)
8896
+ },
8897
+ labels: { purpose: "sign-in" }
8898
+ });
8899
+ } catch (error) {
8900
+ throw new HarnessSignInRefusedError(`Could not make a sandbox to sign in to ${spec.name} in: ${error instanceof Error ? error.message : String(error)}`);
8901
+ }
8902
+ const note = `${input.staging}${SANDBOX_NOTE}`;
8903
+ fs11.writeFileSync(note, handle.providerId, { mode: 384 });
8904
+ let released;
8905
+ const release = () => {
8906
+ released ??= provider.destroySandbox(handle.providerId).then(() => fs11.rmSync(note, { force: true }), () => {
8907
+ return;
8908
+ });
8909
+ return released;
8910
+ };
8911
+ const home = signInHomePath({
8912
+ workspaceRoot: provider.workspaceRoot,
8913
+ harness: input.harness
8914
+ });
8915
+ const child = spawnInSandbox({
8916
+ processes,
8917
+ sandboxId: handle.providerId,
8918
+ command: spec.command,
8919
+ args: [...spec.login, ...spec.defaultArgs],
8920
+ cwd: provider.workspaceRoot,
8921
+ env: { [spec.homeVariable]: home, NO_COLOR: "1" },
8922
+ name: `${spec.name} sign-in`
8923
+ });
8924
+ if (!spec.expects)
8925
+ child.stdin.end();
8926
+ return { child, release };
8927
+ }
8521
8928
  async handle(request) {
8522
8929
  const refusal = (error) => {
8523
8930
  if (error instanceof HarnessSignInRefusedError)
@@ -8551,6 +8958,7 @@ class HarnessSignIns {
8551
8958
  }
8552
8959
  async begin(input) {
8553
8960
  this.prune();
8961
+ await this.recover();
8554
8962
  const { harness, member } = input;
8555
8963
  const spec = SIGN_IN_SPECS2[harness];
8556
8964
  try {
@@ -8568,19 +8976,18 @@ class HarnessSignIns {
8568
8976
  harness,
8569
8977
  member
8570
8978
  });
8571
- const login = signInCommand({
8572
- harness,
8573
- home: staging,
8574
- env: this.options.env
8575
- });
8576
- const child = spawn(login.command, login.args, {
8577
- env: signInEnvironment({
8979
+ let started;
8980
+ try {
8981
+ started = await this.startLogin({
8578
8982
  harness,
8579
- base: this.options.env ?? process.env,
8580
- login: { ...login.env, NO_COLOR: "1" }
8581
- }),
8582
- stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"]
8583
- });
8983
+ staging,
8984
+ ...input.sandbox ? { sandbox: input.sandbox } : {}
8985
+ });
8986
+ } catch (error) {
8987
+ fs11.rmSync(staging, { recursive: true, force: true });
8988
+ throw error;
8989
+ }
8990
+ const { child, release } = started;
8584
8991
  child.stdin?.on("error", () => {
8585
8992
  return;
8586
8993
  });
@@ -8594,7 +9001,7 @@ class HarnessSignIns {
8594
9001
  settled = true;
8595
9002
  clearTimeout(timer);
8596
9003
  child.kill("SIGTERM");
8597
- fs11.rmSync(staging, { recursive: true, force: true });
9004
+ release().then(() => fs11.rmSync(staging, { recursive: true, force: true }));
8598
9005
  reject(new HarnessSignInRefusedError(message));
8599
9006
  };
8600
9007
  const timer = setTimeout(() => fail(`${spec.name} did not print a sign-in link within ${CODE_TIMEOUT_MS / 1000} seconds${lastWords(output) ? `: ${lastWords(output)}` : ""}`), CODE_TIMEOUT_MS);
@@ -8620,6 +9027,7 @@ class HarnessSignIns {
8620
9027
  harness,
8621
9028
  member,
8622
9029
  child,
9030
+ release,
8623
9031
  staging,
8624
9032
  expiresAt,
8625
9033
  state: "waiting",
@@ -8637,7 +9045,7 @@ class HarnessSignIns {
8637
9045
  child.stdout?.on("data", read);
8638
9046
  child.stderr?.on("data", read);
8639
9047
  child.once("error", (error) => fail(`Could not run ${spec.name} on this machine: ${error.message}. Install it there first`));
8640
- const ended = (code) => {
9048
+ const ended = async (code) => {
8641
9049
  if (!settled) {
8642
9050
  fail(lastWords(output) ?? `${spec.name} stopped before printing a sign-in link (exit ${code ?? "signal"})`);
8643
9051
  return;
@@ -8645,6 +9053,9 @@ class HarnessSignIns {
8645
9053
  const attempt = this.attempts.get(id);
8646
9054
  if (attempt?.state !== "waiting")
8647
9055
  return;
9056
+ await release();
9057
+ if (this.attempts.get(id)?.state !== "waiting")
9058
+ return;
8648
9059
  if (code === 0 && signedIn({ harness, home: staging })) {
8649
9060
  try {
8650
9061
  assertMachineFree({ root: this.options.signInRoot, member });
@@ -8669,6 +9080,7 @@ class HarnessSignIns {
8669
9080
  Promise.all([drained(child.stdout), drained(child.stderr)]),
8670
9081
  new Promise((resolve) => setTimeout(resolve, EXIT_DRAIN_MS))
8671
9082
  ]).then(() => ended(code));
9083
+ release();
8672
9084
  });
8673
9085
  });
8674
9086
  }
@@ -8729,8 +9141,10 @@ class HarnessSignIns {
8729
9141
  clearTimeout(attempt.deadline);
8730
9142
  if (attempt.child.exitCode === null)
8731
9143
  attempt.child.kill("SIGTERM");
8732
- if (state !== "signed-in")
8733
- fs11.rmSync(attempt.staging, { recursive: true, force: true });
9144
+ if (state === "signed-in")
9145
+ return;
9146
+ const { staging } = attempt;
9147
+ attempt.release().then(() => fs11.rmSync(staging, { recursive: true, force: true }));
8734
9148
  }
8735
9149
  prune() {
8736
9150
  const now = this.now();
@@ -8744,18 +9158,34 @@ class HarnessSignIns {
8744
9158
  }
8745
9159
 
8746
9160
  // src/workers/member-machine-routes.ts
8747
- import { ExecutorNotConnectedError } from "@catamorphic/core";
9161
+ import {
9162
+ AccessDeniedError,
9163
+ EnvironmentAccessDeniedError,
9164
+ EnvironmentIncompatibleError,
9165
+ EnvironmentNotFoundError,
9166
+ EnvironmentPolicyInvalidError,
9167
+ ExecutorNotConnectedError,
9168
+ ProjectNotFoundError
9169
+ } from "@catamorphic/core";
8748
9170
  import { signInHarness as signInHarness2 } from "@catamorphic/sandbox";
8749
9171
  import { z as z23 } from "zod";
8750
9172
 
8751
9173
  // src/workers/member-machines.ts
8752
9174
  import {
8753
- accessTier as accessTier2,
9175
+ accessTier as accessTier3,
8754
9176
  MACHINE_CAPABILITIES as MACHINE_CAPABILITIES5,
8755
9177
  parseSignInCapability as parseSignInCapability2,
9178
+ SIGN_IN_HARNESSES as SIGN_IN_HARNESSES4,
8756
9179
  signInCapability as signInCapability2
8757
9180
  } from "@catamorphic/sandbox";
8758
9181
  import { z as z22 } from "zod";
9182
+ var NOT_YET_SERVING = new Set([
9183
+ "starting",
9184
+ "stopping",
9185
+ "stopped",
9186
+ "resuming"
9187
+ ]);
9188
+
8759
9189
  class NotYourMachineError extends Error {
8760
9190
  constructor() {
8761
9191
  super("This is not a machine of your own, so your sign-in cannot go on it");
@@ -8768,30 +9198,79 @@ class MemberMachines {
8768
9198
  constructor(deps) {
8769
9199
  this.deps = deps;
8770
9200
  }
8771
- async list(identity) {
9201
+ async list(identity, options = {}) {
8772
9202
  const own = await this.own(identity);
8773
9203
  const nodes = new Map((await this.deps.nodes()).map((node) => [node.id, node]));
8774
9204
  const member = identity.externalUserId;
9205
+ const made = await this.deps.signIns.made({ member });
9206
+ const environments = options.projectId ? await this.deps.environments.signInEnvironments({
9207
+ identity,
9208
+ projectId: options.projectId
9209
+ }) : undefined;
8775
9210
  return [...own].map(([id, machine]) => {
8776
9211
  const node = nodes.get(id);
9212
+ const signIns = signInStates((harness) => node?.descriptor.capabilities.includes(signInCapability2({ harness, member })) ? "signed-in" : "signed-out");
8777
9213
  return {
8778
9214
  id,
8779
9215
  name: machine?.name ?? node?.descriptor.label ?? id,
8780
9216
  available: machine ? machine.state === "serving" : Boolean(node?.available),
8781
9217
  state: machine?.state ?? "serving",
8782
9218
  reason: machine?.reason ?? null,
8783
- signIns: signInStates((harness) => node?.descriptor.capabilities.includes(signInCapability2({ harness, member })) ? "signed-in" : "signed-out")
9219
+ signIns,
9220
+ made: Object.fromEntries(SIGN_IN_HARNESSES4.flatMap((harness) => {
9221
+ const entry = made.get(id)?.[harness];
9222
+ return entry && signIns[harness] === "signed-in" ? [[harness, entry]] : [];
9223
+ })),
9224
+ ...environments ? {
9225
+ environments: environments.filter((environment) => serves(machine, environment)).map(({ name, image }) => ({ name, image }))
9226
+ } : {}
8784
9227
  };
8785
9228
  });
8786
9229
  }
8787
9230
  async begin(args) {
9231
+ const own = await this.own(args.identity);
9232
+ if (!own.has(args.machineId))
9233
+ throw new NotYourMachineError;
9234
+ const machine = own.get(args.machineId);
9235
+ const resolved = await this.deps.environments.signInSandbox({
9236
+ identity: args.identity,
9237
+ projectId: args.projectId,
9238
+ environment: args.environment
9239
+ });
9240
+ if (!serves(machine, resolved))
9241
+ throw new HarnessSignInRefusedError(`Environment '${args.environment}' does not run on this machine. Choose one that does`);
9242
+ const member = args.identity.externalUserId;
9243
+ if (machine && NOT_YET_SERVING.has(machine.state)) {
9244
+ await this.deps.signIns.wait({
9245
+ machine: machine.name,
9246
+ member,
9247
+ harness: args.harness,
9248
+ project: args.projectId,
9249
+ environment: args.environment
9250
+ });
9251
+ return { state: "starting" };
9252
+ }
8788
9253
  const answer = z22.union([HarnessSignInStartedSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8789
9254
  action: "begin",
8790
9255
  harness: args.harness,
8791
- member: args.identity.externalUserId
9256
+ member,
9257
+ sandbox: resolved.sandbox
8792
9258
  }));
9259
+ if (machine)
9260
+ await this.deps.signIns.began({ machine: machine.name, member });
8793
9261
  if ("refused" in answer)
8794
9262
  throw new HarnessSignInRefusedError(answer.refused);
9263
+ await this.deps.signIns.begun({
9264
+ attempt: answer.attempt,
9265
+ nodeId: args.machineId,
9266
+ member,
9267
+ harness: args.harness,
9268
+ made: {
9269
+ project: args.projectId,
9270
+ environment: resolved.name,
9271
+ image: resolved.image
9272
+ }
9273
+ });
8795
9274
  return answer;
8796
9275
  }
8797
9276
  async status(args) {
@@ -8823,11 +9302,17 @@ class MemberMachines {
8823
9302
  });
8824
9303
  }
8825
9304
  async signOut(args) {
8826
- return HarnessSignedOutSchema.parse(await this.send(args, {
9305
+ const answer = HarnessSignedOutSchema.parse(await this.send(args, {
8827
9306
  action: "signOut",
8828
9307
  harness: args.harness,
8829
9308
  member: args.identity.externalUserId
8830
9309
  }));
9310
+ await this.deps.signIns.signedOut({
9311
+ nodeId: args.machineId,
9312
+ member: args.identity.externalUserId,
9313
+ harness: args.harness
9314
+ });
9315
+ return answer;
8831
9316
  }
8832
9317
  async usable(args, status) {
8833
9318
  if (status.state !== "signed-in")
@@ -8837,7 +9322,15 @@ class MemberMachines {
8837
9322
  harness: args.harness,
8838
9323
  member: args.identity.externalUserId
8839
9324
  }));
8840
- return reported ? status : { state: "waiting" };
9325
+ if (!reported)
9326
+ return { state: "waiting" };
9327
+ await this.deps.signIns.signedIn({
9328
+ attempt: args.attempt,
9329
+ nodeId: args.machineId,
9330
+ member: args.identity.externalUserId,
9331
+ harness: args.harness
9332
+ });
9333
+ return status;
8841
9334
  }
8842
9335
  async send(args, request) {
8843
9336
  const own = await this.own(args.identity);
@@ -8854,7 +9347,7 @@ class MemberMachines {
8854
9347
  for (const machine of await this.deps.machines()) {
8855
9348
  if (machine.state === "destroying" || machine.state === "draining")
8856
9349
  continue;
8857
- if (accessTier2({ access: nodeAccess(machine.for), owner }) === 1)
9350
+ if (accessTier3({ access: nodeAccess(machine.for), owner }) === 1)
8858
9351
  own.set(`${WORKER_NODE_PREFIX}${machine.name}`, machine);
8859
9352
  }
8860
9353
  const ownMachine = this.deps.ownMachine;
@@ -8868,6 +9361,12 @@ class MemberMachines {
8868
9361
  return own;
8869
9362
  }
8870
9363
  }
9364
+ function serves(machine, environment) {
9365
+ if (!machine)
9366
+ return true;
9367
+ const labels = { ...machine.labels, plane: "worker" };
9368
+ return Object.entries(environment.pool).every(([key, value]) => labels[key] === value);
9369
+ }
8871
9370
  function signInStates(state) {
8872
9371
  return {
8873
9372
  "claude-code": state("claude-code"),
@@ -8885,6 +9384,11 @@ function registerMemberMachineRoutes(app, options) {
8885
9384
  const inputBody = z23.strictObject({
8886
9385
  text: z23.string().min(1).max(SIGN_IN_INPUT_MAX)
8887
9386
  });
9387
+ const beginBody = z23.strictObject({
9388
+ project: z23.string().uuid(),
9389
+ environment: z23.string().min(1).max(200)
9390
+ });
9391
+ const listQuery = z23.object({ project: z23.string().uuid().optional() });
8888
9392
  const member = async (request, reply) => {
8889
9393
  const identity = await options.caller(request);
8890
9394
  if (!identity) {
@@ -8900,8 +9404,12 @@ function registerMemberMachineRoutes(app, options) {
8900
9404
  return harness;
8901
9405
  };
8902
9406
  const refusal = (reply, error) => {
8903
- if (error instanceof NotYourMachineError)
9407
+ if (error instanceof NotYourMachineError || error instanceof AccessDeniedError || error instanceof EnvironmentAccessDeniedError)
8904
9408
  return reply.status(403).send({ error: error.message });
9409
+ if (error instanceof EnvironmentNotFoundError || error instanceof ProjectNotFoundError)
9410
+ return reply.status(404).send({ error: error.message });
9411
+ if (error instanceof EnvironmentIncompatibleError || error instanceof EnvironmentPolicyInvalidError)
9412
+ return reply.status(409).send({ error: error.message, code: "environment_refused" });
8905
9413
  if (error instanceof HarnessSignInRefusedError)
8906
9414
  return reply.status(409).send({ error: error.message, code: "sign_in_refused" });
8907
9415
  if (error instanceof ExecutorNotConnectedError)
@@ -8917,7 +9425,16 @@ function registerMemberMachineRoutes(app, options) {
8917
9425
  const identity = await member(request, reply);
8918
9426
  if (!identity)
8919
9427
  return reply;
8920
- return { machines: await options.machines.list(identity) };
9428
+ const query = listQuery.safeParse(request.query);
9429
+ if (!query.success)
9430
+ return reply.status(400).send({ error: "project is a project's id" });
9431
+ try {
9432
+ return {
9433
+ machines: await options.machines.list(identity, query.data.project ? { projectId: query.data.project } : {})
9434
+ };
9435
+ } catch (error) {
9436
+ return refusal(reply, error);
9437
+ }
8921
9438
  });
8922
9439
  app.post("/api/work/me/machines/:id/:harness/sign-in", async (request, reply) => {
8923
9440
  const identity = await member(request, reply);
@@ -8927,12 +9444,21 @@ function registerMemberMachineRoutes(app, options) {
8927
9444
  const harness = await harnessOf(reply, params.harness);
8928
9445
  if (!harness)
8929
9446
  return reply;
9447
+ const body = beginBody.safeParse(request.body);
9448
+ if (!body.success)
9449
+ return reply.status(400).send({
9450
+ error: "Name the project and the Environment the sign-in is for as { project, environment }"
9451
+ });
8930
9452
  try {
8931
9453
  const started = await options.machines.begin({
8932
9454
  identity,
8933
9455
  machineId: params.id,
8934
- harness
9456
+ harness,
9457
+ projectId: body.data.project,
9458
+ environment: body.data.environment
8935
9459
  });
9460
+ if ("state" in started)
9461
+ return reply.status(202).send(started);
8936
9462
  return reply.status(201).send(started);
8937
9463
  } catch (error) {
8938
9464
  return refusal(reply, error);
@@ -9059,7 +9585,7 @@ import { z as z24 } from "zod";
9059
9585
  // src/workers/worker-protocol.ts
9060
9586
  var WORKER_PROTOCOL_HEADER = "work-protocol";
9061
9587
  var WORKER_PROTOCOL = {
9062
- server: 4,
9588
+ server: 6,
9063
9589
  minimum: 4
9064
9590
  };
9065
9591
  function workerProtocolRefusal(stated) {
@@ -9285,6 +9811,8 @@ async function createWorkServerInner(options, disposers, close) {
9285
9811
  const log = options.log ?? (() => {});
9286
9812
  const data = config.dataDir;
9287
9813
  const publicBase = config.publicBases[0] ?? "http://127.0.0.1:4700";
9814
+ const git = await assertNativeGit();
9815
+ log(`Git ${git.version}`);
9288
9816
  const workAuthConfig = parseWorkAuthConfig(config.auth ?? {});
9289
9817
  trustedProxies(config.trustedProxies ?? []);
9290
9818
  if (config.authRateLimit === false) {
@@ -9301,14 +9829,14 @@ async function createWorkServerInner(options, disposers, close) {
9301
9829
  throw new Error("Postgres deployments require the same WORK_OPERATOR_SECRET on every instance");
9302
9830
  }
9303
9831
  if (config.databaseUrl) {
9304
- fs12.rmSync(path9.join(data, "sandboxes"), { recursive: true, force: true });
9832
+ fs12.rmSync(path10.join(data, "sandboxes"), { recursive: true, force: true });
9305
9833
  }
9306
9834
  const dirs = config.databaseUrl ? ["projects", "sandboxes"] : ["db", "projects", "remotes", "app-bundles", "sandboxes"];
9307
9835
  for (const dir of dirs) {
9308
- fs12.mkdirSync(path9.join(data, dir), { recursive: true });
9836
+ fs12.mkdirSync(path10.join(data, dir), { recursive: true });
9309
9837
  }
9310
9838
  const disposable = Boolean(config.databaseUrl);
9311
- const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path9.join(data, "host-id"));
9839
+ const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path10.join(data, "host-id"));
9312
9840
  const nodeId = disposable ? `node.${randomUUID9()}` : `node.${createHash9("sha256").update(hostId).digest("hex").slice(0, 24)}`;
9313
9841
  const authSecret = loadWorkAuthSecret({
9314
9842
  dataDir: data,
@@ -9326,7 +9854,7 @@ async function createWorkServerInner(options, disposers, close) {
9326
9854
  databaseConfig = { db: ownDb };
9327
9855
  workerConcurrency = 4;
9328
9856
  } else {
9329
- const pglite = new PGlite2(path9.join(data, "db"), {
9857
+ const pglite = new PGlite2(path10.join(data, "db"), {
9330
9858
  extensions: { pgcrypto }
9331
9859
  });
9332
9860
  ownDb = withStorableParameters(new Kysely2({
@@ -9334,7 +9862,7 @@ async function createWorkServerInner(options, disposers, close) {
9334
9862
  plugins: [new WithSchemaPlugin(DEFAULT_SCHEMA)]
9335
9863
  }));
9336
9864
  disposers.push(() => ownDb.destroy());
9337
- await sql8.raw(`SET search_path TO "${DEFAULT_SCHEMA}", public`).execute(ownDb);
9865
+ await sql9.raw(`SET search_path TO "${DEFAULT_SCHEMA}", public`).execute(ownDb);
9338
9866
  databaseConfig = { db: ownDb };
9339
9867
  }
9340
9868
  const agentsHere = config.execution.workloads.includes("agent") && !config.execution.trustControlPlaneAgents;
@@ -9365,7 +9893,7 @@ async function createWorkServerInner(options, disposers, close) {
9365
9893
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
9366
9894
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
9367
9895
  graceMs: execution.imageRetentionMs,
9368
- runningFile: path9.join(data, RUNNING_TIME_FILE),
9896
+ runningFile: path10.join(data, RUNNING_TIME_FILE),
9369
9897
  log
9370
9898
  });
9371
9899
  disposers.push(async () => diskCare.stop());
@@ -9378,7 +9906,7 @@ async function createWorkServerInner(options, disposers, close) {
9378
9906
  if (objectStore && vaultKeys.length === 0) {
9379
9907
  throw new Error("Postgres deployments require WORK_VAULT_KEY (or the vaultKeys hook) on every instance");
9380
9908
  }
9381
- const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path9.join(data, "credentials"), vaultKeys);
9909
+ const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path10.join(data, "credentials"), vaultKeys);
9382
9910
  if (objectStore) {
9383
9911
  const key = "work/deployment-fingerprint";
9384
9912
  const fingerprint = createHash9("sha256").update(publicBase).update("\x00").update(authSecret).update("\x00").update(JSON.stringify({
@@ -9405,6 +9933,7 @@ async function createWorkServerInner(options, disposers, close) {
9405
9933
  }
9406
9934
  let workerConnected = () => {};
9407
9935
  let workRetired = () => {};
9936
+ let roomFreed = () => {};
9408
9937
  let machineEvent = async () => {};
9409
9938
  const workers = new WorkWorkerRegistry({
9410
9939
  db: ownDb,
@@ -9414,6 +9943,7 @@ async function createWorkServerInner(options, disposers, close) {
9414
9943
  enrollmentSecret: authSecret,
9415
9944
  connected: () => workerConnected(),
9416
9945
  retired: () => workRetired(),
9946
+ roomFreed: () => roomFreed(),
9417
9947
  event: (event) => machineEvent(event),
9418
9948
  log
9419
9949
  });
@@ -9436,7 +9966,8 @@ async function createWorkServerInner(options, disposers, close) {
9436
9966
  ownSignIns: singleServerSignIns,
9437
9967
  disk: () => diskCare.latest(),
9438
9968
  sandboxProvider,
9439
- placement: { workers: () => workers.placements() }
9969
+ placement: { workers: () => workers.placements() },
9970
+ roomFreed: () => roomFreed()
9440
9971
  });
9441
9972
  disposers.push(() => machine.stop());
9442
9973
  let maintaining;
@@ -9483,18 +10014,37 @@ async function createWorkServerInner(options, disposers, close) {
9483
10014
  memberIdForEmail: ({ email }) => verifiedUserIdForEmail({ auth: workAuth, email }),
9484
10015
  workerNode: machine.lease,
9485
10016
  caches: {
9486
- retentionDays: Math.round(execution.volumeRetentionMs / (24 * 60 * 60 * 1000))
10017
+ retentionDays: Math.round(execution.volumeRetentionMs / (24 * 60 * 60 * 1000)),
10018
+ machineAdmits: ({ projectId, machine }) => workers.machines.admitsProjectWork({ nodeId: machine, projectId }),
10019
+ ...hooks.cacheStore ? {
10020
+ store: hooks.cacheStore,
10021
+ transferUrl: ({ transferId }) => cacheArchiveUrl({ base: publicBase, transferId })
10022
+ } : {}
10023
+ },
10024
+ allocationPlaced: async ({
10025
+ transaction,
10026
+ workerNodeId,
10027
+ projectId,
10028
+ policy
10029
+ }) => {
10030
+ await workers.machines.claimSpare({
10031
+ transaction,
10032
+ nodeId: workerNodeId,
10033
+ projectId,
10034
+ chatKey: policy.chatKey
10035
+ });
9487
10036
  },
9488
10037
  clientExecution: true,
9489
10038
  database: databaseConfig,
9490
10039
  storage: objectStore ? {
9491
- projectManager: new ProjectManager(new FsBackend(path9.join(data, "projects")), new ObjectRemoteBackend({
10040
+ projectManager: new ProjectManager(new FsBackend(path10.join(data, "projects")), new ObjectRemoteBackend({
9492
10041
  store: objectStore,
9493
- keyPrefix: "origins/"
10042
+ keyPrefix: "origins/",
10043
+ cachePath: path10.join(data, "projects", ".origins")
9494
10044
  }))
9495
10045
  } : {
9496
- projectsPath: path9.join(data, "projects"),
9497
- remotesPath: path9.join(data, "remotes")
10046
+ projectsPath: path10.join(data, "projects"),
10047
+ remotesPath: path10.join(data, "remotes")
9498
10048
  },
9499
10049
  sandboxProvider,
9500
10050
  environmentProvider,
@@ -9514,8 +10064,8 @@ async function createWorkServerInner(options, disposers, close) {
9514
10064
  ...hooks.machines ? { placementWaitMinutes: config.machineWaitMinutes ?? 30 } : {},
9515
10065
  gatewayUrl: () => `${publicBase}/api/gateway`,
9516
10066
  ...agents.registry ? { codingAgent: agents.registry } : {},
9517
- appBundleStore: objectStore ?? new FsBundleStore(path9.join(data, "app-bundles")),
9518
- documentBlobStore: objectStore ?? new FsBundleStore(path9.join(data, "document-blobs")),
10067
+ appBundleStore: objectStore ?? new FsBundleStore(path10.join(data, "app-bundles")),
10068
+ documentBlobStore: objectStore ?? new FsBundleStore(path10.join(data, "document-blobs")),
9519
10069
  triggerKinds: [
9520
10070
  aiToolCall,
9521
10071
  schedule,
@@ -9581,6 +10131,7 @@ async function createWorkServerInner(options, disposers, close) {
9581
10131
  const core = catamorphic.core;
9582
10132
  workerConnected = () => core.wakeups.notify("agent");
9583
10133
  workRetired = () => core.wakeups.notify("agent");
10134
+ roomFreed = () => core.wakeups.notify("capacity");
9584
10135
  {
9585
10136
  const recover = (nodeIds) => core.nodeRecovery.recoverLostNodes({
9586
10137
  authorityId: hostId,
@@ -9649,7 +10200,7 @@ async function createWorkServerInner(options, disposers, close) {
9649
10200
  publicBase
9650
10201
  });
9651
10202
  machineEvent = async (event) => {
9652
- const projects = new Set((event.machine.for ?? []).flatMap((principal) => ("project" in principal) ? [principal.project] : []));
10203
+ const projects = machineEventProjects(event.machine);
9653
10204
  const record = machineProjectEvent({
9654
10205
  kind: event.kind,
9655
10206
  at: event.at,
@@ -9688,6 +10239,7 @@ async function createWorkServerInner(options, disposers, close) {
9688
10239
  roles: rolesOf.get(user.id) ?? {}
9689
10240
  })).sort((left, right) => left.id.localeCompare(right.id));
9690
10241
  };
10242
+ const machineSessions = core.agentSessions;
9691
10243
  const workMachines = hooks.machines ? new WorkMachines({
9692
10244
  db: core.db,
9693
10245
  tenantId: SERVER_TENANT_ID,
@@ -9699,6 +10251,30 @@ async function createWorkServerInner(options, disposers, close) {
9699
10251
  workers,
9700
10252
  controlPlaneUrl: publicBase,
9701
10253
  people,
10254
+ ...machineSessions ? {
10255
+ stopQuietWorkspaces: (args) => machineSessions.stopQuietWorkspaces(args)
10256
+ } : {},
10257
+ prepare: async ({ name, project, environment, commit }) => {
10258
+ const preparation = await core.machinePreparations.request({
10259
+ identity: projectPrincipalIdentity({
10260
+ tenantId: SERVER_TENANT_ID,
10261
+ projectId: project,
10262
+ environment
10263
+ }),
10264
+ projectId: project,
10265
+ environment,
10266
+ machine: `${WORKER_NODE_PREFIX}${name}`,
10267
+ ...commit !== undefined ? { commit } : {}
10268
+ });
10269
+ return {
10270
+ project,
10271
+ environment,
10272
+ status: preparation.status === "succeeded" ? "prepared" : preparation.status === "failed" ? "failed" : "preparing",
10273
+ commit: preparation.commit,
10274
+ error: preparation.error,
10275
+ since: preparation.finishedAt ?? preparation.createdAt
10276
+ };
10277
+ },
9702
10278
  event: async (event) => {
9703
10279
  await machineEvent(event).catch((error) => log(`Recording ${event.kind} for machine ${event.machine.name} failed: ${error instanceof Error ? error.message : String(error)}`));
9704
10280
  }
@@ -9864,6 +10440,8 @@ async function createWorkServerInner(options, disposers, close) {
9864
10440
  done(null, payload);
9865
10441
  });
9866
10442
  registerWorkerRoutes(app, workers);
10443
+ if (core.cacheArchives)
10444
+ registerCacheArchiveRoutes(app, core.cacheArchives);
9867
10445
  const machineManagement = {
9868
10446
  nodes: machine.nodes,
9869
10447
  workers,
@@ -9912,7 +10490,8 @@ async function createWorkServerInner(options, disposers, close) {
9912
10490
  signInRoot: execution.signInRoot,
9913
10491
  dataDir: data,
9914
10492
  env: { ...process.env, PATH: config.execution.path },
9915
- onChange: () => machine.refreshSignIns()
10493
+ onChange: () => machine.refreshSignIns(),
10494
+ provider: sandboxProvider
9916
10495
  }) : undefined;
9917
10496
  if (ownSignIns)
9918
10497
  disposers.push(async () => ownSignIns.stop());
@@ -9923,7 +10502,9 @@ async function createWorkServerInner(options, disposers, close) {
9923
10502
  nodes: () => memberNodes.list({ tenantId: SERVER_TENANT_ID, authorityId: hostId }),
9924
10503
  machines: async () => (await workers.machines.records()).map((record) => record.facts),
9925
10504
  ...ownSignIns ? { ownMachine: { nodeId: machine.lease.id, signIns: ownSignIns } } : {},
9926
- worker: (args) => workers.harnessSignIn(args)
10505
+ worker: (args) => workers.harnessSignIn(args),
10506
+ environments: core.executionEnvironments,
10507
+ signIns: workers.machines.signIns
9927
10508
  })
9928
10509
  });
9929
10510
  registerWorkAdmissionRoutes(app, {
@@ -10071,7 +10652,7 @@ async function createWorkServerInner(options, disposers, close) {
10071
10652
  return reply.status(400).send({ error: message });
10072
10653
  }
10073
10654
  });
10074
- const pwaDist = config.pwaDist ?? path9.resolve(import.meta.dirname, "../../../apps/pwa/dist");
10655
+ const pwaDist = config.pwaDist ?? path10.resolve(import.meta.dirname, "../../../apps/pwa/dist");
10075
10656
  serveSpaDist(app, () => pwaDist, (reply) => reply.type("text/html").send(LANDING_PAGE));
10076
10657
  await hooks.routes?.({ app, catamorphic });
10077
10658
  log(`agents: ${agents.description}`);
@@ -10087,7 +10668,7 @@ async function createWorkServerInner(options, disposers, close) {
10087
10668
  };
10088
10669
  }
10089
10670
  async function stopMemberWork(args) {
10090
- const running = await args.core.db.selectFrom("agent_turns as turn").innerJoin("agent_sessions as session", "session.id", "turn.session_id").select(["session.id", "session.project_id"]).distinct().where("session.external_user_id", "=", args.userId).where("turn.status", "in", [...ACTIVE_TURN_STATUSES]).execute();
10671
+ const running = await args.core.db.selectFrom("agent_turns as turn").innerJoin("agent_sessions as session", "session.id", "turn.session_id").select(["session.id", "session.project_id"]).distinct().where("session.external_user_id", "=", args.userId).where("turn.status", "in", [...ACTIVE_TURN_STATUSES2]).execute();
10091
10672
  for (const session of running) {
10092
10673
  try {
10093
10674
  await args.core.agentSessions?.interrupt(args.identity, session.project_id, session.id);
@@ -10126,12 +10707,13 @@ function isLoopbackBase(base) {
10126
10707
  // src/workers/worker-runtime.ts
10127
10708
  import { createPrivateKey, randomBytes as randomBytes10 } from "node:crypto";
10128
10709
  import fs14 from "node:fs";
10129
- import path11 from "node:path";
10710
+ import path12 from "node:path";
10130
10711
  import { nodeExecutor as nodeExecutor2, RETIRED_KEY_RETENTION_MS } from "@catamorphic/core";
10131
10712
  import {
10132
10713
  executorPublicKey,
10133
10714
  generateExecutorKeyPair,
10134
- MACHINE_CAPABILITIES as MACHINE_CAPABILITIES7
10715
+ MACHINE_CAPABILITIES as MACHINE_CAPABILITIES7,
10716
+ offeredCapabilities
10135
10717
  } from "@catamorphic/sandbox";
10136
10718
  import {
10137
10719
  ReceiptRefusedError,
@@ -10142,7 +10724,7 @@ import {
10142
10724
 
10143
10725
  // src/workers/worker-identity.ts
10144
10726
  import fs13 from "node:fs";
10145
- import path10 from "node:path";
10727
+ import path11 from "node:path";
10146
10728
  import { z as z26 } from "zod";
10147
10729
  var CREDENTIAL_FILE = "worker-credential";
10148
10730
  var KEY_FILE = "worker-key";
@@ -10156,20 +10738,20 @@ var NextIdentitySchema = PairSchema.extend({
10156
10738
  previous: PairSchema.optional()
10157
10739
  });
10158
10740
  function loadWorkerIdentity(dataDir) {
10159
- const next = readIfPresent(path10.join(dataDir, NEXT_FILE));
10741
+ const next = readIfPresent(path11.join(dataDir, NEXT_FILE));
10160
10742
  if (next !== undefined) {
10161
10743
  const parsed = NextIdentitySchema.safeParse(parseJson(next));
10162
10744
  if (parsed.success)
10163
10745
  install(dataDir, parsed.data);
10164
- fs13.rmSync(path10.join(dataDir, NEXT_FILE), { force: true });
10746
+ fs13.rmSync(path11.join(dataDir, NEXT_FILE), { force: true });
10165
10747
  }
10166
- const credential = readIfPresent(path10.join(dataDir, CREDENTIAL_FILE))?.trim();
10748
+ const credential = readIfPresent(path11.join(dataDir, CREDENTIAL_FILE))?.trim();
10167
10749
  if (!credential)
10168
10750
  return;
10169
- const privateKey = readIfPresent(path10.join(dataDir, KEY_FILE));
10751
+ const privateKey = readIfPresent(path11.join(dataDir, KEY_FILE));
10170
10752
  if (!privateKey)
10171
10753
  return { credential };
10172
- const previous = PairSchema.safeParse(parseJson(readIfPresent(path10.join(dataDir, PREVIOUS_FILE)) ?? ""));
10754
+ const previous = PairSchema.safeParse(parseJson(readIfPresent(path11.join(dataDir, PREVIOUS_FILE)) ?? ""));
10173
10755
  return {
10174
10756
  credential,
10175
10757
  privateKey,
@@ -10177,25 +10759,25 @@ function loadWorkerIdentity(dataDir) {
10177
10759
  };
10178
10760
  }
10179
10761
  function saveWorkerIdentity(dataDir, identity) {
10180
- writeAtomically(path10.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10762
+ writeAtomically(path11.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10181
10763
  install(dataDir, identity);
10182
- fs13.rmSync(path10.join(dataDir, NEXT_FILE), { force: true });
10764
+ fs13.rmSync(path11.join(dataDir, NEXT_FILE), { force: true });
10183
10765
  syncDirectory(dataDir);
10184
10766
  }
10185
10767
  function confirmWorkerIdentity(dataDir) {
10186
- fs13.rmSync(path10.join(dataDir, PREVIOUS_FILE), { force: true });
10768
+ fs13.rmSync(path11.join(dataDir, PREVIOUS_FILE), { force: true });
10187
10769
  syncDirectory(dataDir);
10188
10770
  }
10189
10771
  function saveWorkerKey(dataDir, privateKey) {
10190
- writeAtomically(path10.join(dataDir, KEY_FILE), privateKey);
10772
+ writeAtomically(path11.join(dataDir, KEY_FILE), privateKey);
10191
10773
  }
10192
10774
  function install(dataDir, identity) {
10193
10775
  if (identity.previous)
10194
- writeAtomically(path10.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10776
+ writeAtomically(path11.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10195
10777
  else
10196
- fs13.rmSync(path10.join(dataDir, PREVIOUS_FILE), { force: true });
10197
- writeAtomically(path10.join(dataDir, KEY_FILE), identity.privateKey);
10198
- writeAtomically(path10.join(dataDir, CREDENTIAL_FILE), `${identity.credential}
10778
+ fs13.rmSync(path11.join(dataDir, PREVIOUS_FILE), { force: true });
10779
+ writeAtomically(path11.join(dataDir, KEY_FILE), identity.privateKey);
10780
+ writeAtomically(path11.join(dataDir, CREDENTIAL_FILE), `${identity.credential}
10199
10781
  `);
10200
10782
  }
10201
10783
  function writeAtomically(file, content) {
@@ -10209,7 +10791,7 @@ function writeAtomically(file, content) {
10209
10791
  }
10210
10792
  fs13.chmodSync(temporary, 384);
10211
10793
  fs13.renameSync(temporary, file);
10212
- syncDirectory(path10.dirname(file));
10794
+ syncDirectory(path11.dirname(file));
10213
10795
  }
10214
10796
  function syncDirectory(dir) {
10215
10797
  try {
@@ -10330,7 +10912,7 @@ async function startWorkWorker(options) {
10330
10912
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
10331
10913
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
10332
10914
  graceMs: execution.imageRetentionMs,
10333
- runningFile: path11.join(options.dataDir, RUNNING_TIME_FILE),
10915
+ runningFile: path12.join(options.dataDir, RUNNING_TIME_FILE),
10334
10916
  log
10335
10917
  });
10336
10918
  await diskCare.measure();
@@ -10343,7 +10925,7 @@ async function startWorkWorker(options) {
10343
10925
  workspaceRoot: provider.workspaceRoot ?? "/workspace",
10344
10926
  processes: Boolean(provider.processes),
10345
10927
  capabilities: [
10346
- ...provider.capabilities ?? [],
10928
+ ...offeredCapabilities(provider.capabilities),
10347
10929
  ...execution.machineCapabilities,
10348
10930
  ...disk ? [MACHINE_CAPABILITIES7.disk] : [],
10349
10931
  ...signInCapabilities(execution.signInRoot)
@@ -10408,14 +10990,16 @@ async function startWorkWorker(options) {
10408
10990
  throw new Error(reason);
10409
10991
  throw new RunnerSessionEndedError(reason);
10410
10992
  };
10411
- const sandboxes = new PersistedSandboxes(path11.join(options.dataDir, "sandboxes.json"));
10993
+ const sandboxes = new PersistedSandboxes(path12.join(options.dataDir, "sandboxes.json"));
10412
10994
  const offerSignIns = { now: () => {} };
10413
10995
  const harnessSignIns = new HarnessSignIns({
10414
10996
  signInRoot: execution.signInRoot,
10415
10997
  dataDir: options.dataDir,
10416
10998
  env: { ...process.env, PATH: options.execution.path },
10417
- onChange: () => offerSignIns.now()
10999
+ onChange: () => offerSignIns.now(),
11000
+ provider
10418
11001
  });
11002
+ harnessSignIns.recover();
10419
11003
  const resets = { last: Promise.resolve() };
10420
11004
  const reset = () => {
10421
11005
  const next = resets.last.catch(() => {
@@ -10775,7 +11359,7 @@ export {
10775
11359
  MACHINE_EVENT_KINDS2 as MACHINE_EVENT_KINDS,
10776
11360
  MachineHeldError,
10777
11361
  SERVER_TENANT_ID,
10778
- SIGN_IN_HARNESSES3 as SIGN_IN_HARNESSES,
11362
+ SIGN_IN_HARNESSES5 as SIGN_IN_HARNESSES,
10779
11363
  SIGN_IN_SPECS3 as SIGN_IN_SPECS,
10780
11364
  WORKER_PROTOCOL,
10781
11365
  WORKER_PROTOCOL_HEADER,
@@ -10788,18 +11372,21 @@ export {
10788
11372
  defineModelConnectionProvider2 as defineModelConnectionProvider,
10789
11373
  definePostgresConnectionProvider2 as definePostgresConnectionProvider,
10790
11374
  executionSettingsFromEnv,
11375
+ handedOffKey2 as handedOffKey,
10791
11376
  isSecurePublicUrl,
10792
11377
  lanAddresses,
10793
11378
  listMachineSignIns,
11379
+ preparedFor2 as preparedFor,
10794
11380
  resolveExecutionSettings,
10795
11381
  signInHarness3 as signInHarness,
10796
11382
  signInOnMachine,
10797
11383
  signInRoot,
10798
11384
  signOutOnMachine,
11385
+ spareProject2 as spareProject,
10799
11386
  startMdnsResponder,
10800
11387
  startWorkWorker,
10801
11388
  workServerConfigFromEnv
10802
11389
  };
10803
11390
 
10804
- //# debugId=6D4AA9AD62CC45E964756E2164756E21
11391
+ //# debugId=A38F901DCE76FE4764756E2164756E21
10805
11392
  //# sourceMappingURL=index.js.map