@catamorphic/work-server 0.1.0-alpha.42 → 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 (74) hide show
  1. package/README.md +4 -1
  2. package/dist/agents.d.ts.map +1 -1
  3. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  4. package/dist/chunk-ynxz0am9.js.map +11 -0
  5. package/dist/cluster.d.ts +19 -1
  6. package/dist/cluster.d.ts.map +1 -1
  7. package/dist/execution-config.d.ts +2 -1
  8. package/dist/execution-config.d.ts.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +962 -268
  12. package/dist/index.js.map +21 -19
  13. package/dist/machines/contract.d.ts +138 -14
  14. package/dist/machines/contract.d.ts.map +1 -1
  15. package/dist/machines/sequencer.d.ts +33 -6
  16. package/dist/machines/sequencer.d.ts.map +1 -1
  17. package/dist/machines/simulation.d.ts +64 -0
  18. package/dist/machines/simulation.d.ts.map +1 -1
  19. package/dist/machines/work-machines.d.ts +40 -2
  20. package/dist/machines/work-machines.d.ts.map +1 -1
  21. package/dist/server.d.ts +11 -1
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/testing.d.ts +1 -1
  24. package/dist/testing.d.ts.map +1 -1
  25. package/dist/testing.js +208 -17
  26. package/dist/testing.js.map +4 -4
  27. package/dist/workers/cache-archive-routes.d.ts +24 -0
  28. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  29. package/dist/workers/disk-care.d.ts +36 -1
  30. package/dist/workers/disk-care.d.ts.map +1 -1
  31. package/dist/workers/harness-sign-ins.d.ts +32 -1
  32. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  33. package/dist/workers/machine-store.d.ts +37 -0
  34. package/dist/workers/machine-store.d.ts.map +1 -1
  35. package/dist/workers/member-machine-routes.d.ts +3 -0
  36. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  37. package/dist/workers/member-machines.d.ts +52 -5
  38. package/dist/workers/member-machines.d.ts.map +1 -1
  39. package/dist/workers/placement.d.ts +10 -0
  40. package/dist/workers/placement.d.ts.map +1 -1
  41. package/dist/workers/sign-in-store.d.ts +67 -0
  42. package/dist/workers/sign-in-store.d.ts.map +1 -0
  43. package/dist/workers/sign-ins.d.ts +4 -6
  44. package/dist/workers/sign-ins.d.ts.map +1 -1
  45. package/dist/workers/worker-protocol.d.ts +9 -1
  46. package/dist/workers/worker-protocol.d.ts.map +1 -1
  47. package/dist/workers/worker-registry.d.ts +20 -6
  48. package/dist/workers/worker-registry.d.ts.map +1 -1
  49. package/dist/workers/worker-runtime.d.ts.map +1 -1
  50. package/package.json +18 -19
  51. package/src/agents.ts +5 -0
  52. package/src/cluster.ts +62 -7
  53. package/src/execution-config.ts +2 -1
  54. package/src/index.ts +7 -0
  55. package/src/machines/contract-kit.ts +1 -1
  56. package/src/machines/contract.ts +191 -19
  57. package/src/machines/sequencer.ts +106 -11
  58. package/src/machines/simulation.ts +370 -20
  59. package/src/machines/work-machines.ts +71 -3
  60. package/src/server.ts +120 -29
  61. package/src/testing.ts +1 -0
  62. package/src/workers/cache-archive-routes.ts +125 -0
  63. package/src/workers/disk-care.ts +157 -6
  64. package/src/workers/harness-sign-ins.ts +207 -22
  65. package/src/workers/machine-store.ts +341 -58
  66. package/src/workers/member-machine-routes.ts +58 -3
  67. package/src/workers/member-machines.ts +168 -14
  68. package/src/workers/placement.ts +7 -0
  69. package/src/workers/sign-in-store.ts +241 -0
  70. package/src/workers/sign-ins.ts +9 -33
  71. package/src/workers/worker-protocol.ts +9 -1
  72. package/src/workers/worker-registry.ts +47 -6
  73. package/src/workers/worker-runtime.ts +9 -3
  74. 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) {
@@ -1411,12 +1394,13 @@ function startMdnsResponder(hostname, log = () => {}) {
1411
1394
  }
1412
1395
  // src/server.ts
1413
1396
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
1414
- import fs11 from "node:fs";
1415
- import path8 from "node:path";
1416
- import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
1397
+ import fs12 from "node:fs";
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,9 +1433,11 @@ import {
1448
1433
  FsBundleStore,
1449
1434
  githubCodeHost,
1450
1435
  MACHINE_TRIGGER_KINDS,
1436
+ machineEventProjects,
1451
1437
  machineProjectEvent,
1452
1438
  ObjectRemoteBackend,
1453
1439
  PostgresObjectStore,
1440
+ PROJECT_TRIGGER_KINDS,
1454
1441
  ProjectManager,
1455
1442
  SESSION_TRIGGER_KINDS,
1456
1443
  schedule,
@@ -1461,8 +1448,8 @@ import { PROJECT_AGENTS_DIR } from "@catamorphic/workflow/project-layout";
1461
1448
  import { PGlite as PGlite2 } from "@electric-sql/pglite";
1462
1449
  import { pgcrypto } from "@electric-sql/pglite/contrib/pgcrypto";
1463
1450
  import Fastify from "fastify";
1464
- import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql8, WithSchemaPlugin } from "kysely";
1465
- import { z as z24 } from "zod";
1451
+ import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql9, WithSchemaPlugin } from "kysely";
1452
+ import { z as z25 } from "zod";
1466
1453
 
1467
1454
  // src/admission/admission-service.ts
1468
1455
  import {
@@ -2036,7 +2023,7 @@ function invalidInput(reply, issues) {
2036
2023
 
2037
2024
  // src/agent-capabilities.ts
2038
2025
  import { readFile } from "node:fs/promises";
2039
- import { createRequire as createRequire2 } from "node:module";
2026
+ import { createRequire } from "node:module";
2040
2027
  import {
2041
2028
  defineAgentCapability,
2042
2029
  defineRegistryCapability,
@@ -2048,7 +2035,7 @@ import { projectToolCapabilities } from "@catamorphic/fastify-plugin";
2048
2035
  import { z as z5 } from "zod";
2049
2036
  var SERVER_PROJECT_TOOLS = new Set(["set_session_metadata"]);
2050
2037
  var registry = defineRegistryCapability({
2051
- 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"))
2052
2039
  });
2053
2040
  function workAgentCapabilities(args) {
2054
2041
  const directory = defineAgentCapability({
@@ -2118,6 +2105,7 @@ import { createAnthropic } from "@ai-sdk/anthropic";
2118
2105
  import { createOpenAI } from "@ai-sdk/openai";
2119
2106
  import { createAiSdkAdapter } from "@catamorphic/ai-sdk";
2120
2107
  import {
2108
+ acpToolTimeoutMs,
2121
2109
  normalizeConnectionRequirement
2122
2110
  } from "@catamorphic/core";
2123
2111
  import {
@@ -2532,6 +2520,7 @@ function sandboxProjectAgent(input) {
2532
2520
  const common = {
2533
2521
  id: input.id,
2534
2522
  ...harness,
2523
+ ...definition.kind === "acp" ? { toolTimeoutMs: acpToolTimeoutMs(definition.acp) } : {},
2535
2524
  topology: "controller",
2536
2525
  sandboxing: definition.sandboxing ?? "propose",
2537
2526
  environment: definition.environment,
@@ -4057,7 +4046,7 @@ import {
4057
4046
  WorkerNodesService
4058
4047
  } from "@catamorphic/core";
4059
4048
  import {
4060
- accessTier,
4049
+ accessTier as accessTier2,
4061
4050
  describeDisk as describeDisk2,
4062
4051
  diskBudgetMb as diskBudgetMb2,
4063
4052
  environmentSatisfies,
@@ -4066,7 +4055,7 @@ import {
4066
4055
  poolMatches,
4067
4056
  servesOnlyThisOwner
4068
4057
  } from "@catamorphic/sandbox";
4069
- import { sql as sql5 } from "kysely";
4058
+ import { sql as sql6 } from "kysely";
4070
4059
 
4071
4060
  // src/workers/worker-registry.ts
4072
4061
  import {
@@ -4098,20 +4087,126 @@ import {
4098
4087
  MACHINE_CAPABILITIES as MACHINE_CAPABILITIES3,
4099
4088
  SANDBOX_CAPABILITIES
4100
4089
  } from "@catamorphic/sandbox";
4101
- import { sql as sql4 } from "kysely";
4090
+ import { sql as sql5 } from "kysely";
4102
4091
  import { z as z10 } from "zod";
4103
4092
 
4104
4093
  // src/workers/machine-store.ts
4105
4094
  import { createHash as createHash3, createHmac, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
4095
+ import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
4106
4096
  import {
4107
4097
  isProjectPrincipal,
4108
- PLACEMENT_WAIT_FRESH_SECONDS
4098
+ PLACEMENT_FREE_JOB_KINDS,
4099
+ PLACEMENT_WAIT_FRESH_SECONDS,
4100
+ WORKSPACE_IN_USE_SECONDS
4109
4101
  } from "@catamorphic/core";
4110
- import { parseSignInCapability } from "@catamorphic/sandbox";
4102
+ import { accessTier, parseSignInCapability } from "@catamorphic/sandbox";
4111
4103
  import {
4112
- sql as sql3
4104
+ sql as sql4
4113
4105
  } from "kysely";
4114
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
4115
4210
  var WORKER_NODE_PREFIX = "worker.";
4116
4211
  var ENROLLMENT_MINUTES = 60;
4117
4212
  var PHASES = [
@@ -4130,7 +4225,8 @@ var VERBS = [
4130
4225
  "destroy",
4131
4226
  "stop",
4132
4227
  "start",
4133
- "describe"
4228
+ "describe",
4229
+ "onConnected"
4134
4230
  ];
4135
4231
  var OptionsSchema = z9.record(z9.string(), z9.unknown());
4136
4232
  var WaitPool = z9.record(z9.string(), z9.string());
@@ -4149,7 +4245,9 @@ class MachineStore {
4149
4245
  deps;
4150
4246
  constructor(deps) {
4151
4247
  this.deps = deps;
4248
+ this.signIns = new SignInStore(deps);
4152
4249
  }
4250
+ signIns;
4153
4251
  get defaultLostMinutes() {
4154
4252
  return this.deps.lostMinutes ?? DEFAULT_LOST_AFTER_MINUTES2;
4155
4253
  }
@@ -4179,6 +4277,8 @@ class MachineStore {
4179
4277
  idempotency_key: key,
4180
4278
  labels: JSON.stringify(machine.labels),
4181
4279
  serves: machine.for === null ? null : JSON.stringify(machine.for),
4280
+ spare: machine.spare,
4281
+ project_id: machine.project,
4182
4282
  trusted: machine.trusted,
4183
4283
  options: JSON.stringify(machine.options),
4184
4284
  lost_after_minutes: machine.lostAfterMinutes,
@@ -4198,7 +4298,7 @@ class MachineStore {
4198
4298
  if (!row?.enrollment_nonce || !row.idempotency_key)
4199
4299
  return null;
4200
4300
  await this.deps.db.updateTable("work_worker_enrollments").set({
4201
- expires_at: sql3`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4301
+ expires_at: sql4`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4202
4302
  }).where("tenant_id", "=", this.deps.tenantId).where("code_hash", "=", row.idempotency_key).where("used_at", "is", null).execute();
4203
4303
  return {
4204
4304
  code: this.code({ name: args.name, nonce: row.enrollment_nonce }),
@@ -4216,7 +4316,7 @@ class MachineStore {
4216
4316
  await trx.updateTable("work_machines").set({
4217
4317
  enrollment_nonce: nonce,
4218
4318
  idempotency_key: key,
4219
- updated_at: sql3`now()`
4319
+ updated_at: sql4`now()`
4220
4320
  }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4221
4321
  await this.insertEnrollment({ name: args.name, key, transaction: trx });
4222
4322
  });
@@ -4227,11 +4327,11 @@ class MachineStore {
4227
4327
  code_hash: args.key,
4228
4328
  tenant_id: this.deps.tenantId,
4229
4329
  name: args.name,
4230
- expires_at: sql3`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4330
+ expires_at: sql4`now() + make_interval(mins => ${ENROLLMENT_MINUTES})`
4231
4331
  }).execute();
4232
4332
  }
4233
4333
  async lockName(args) {
4234
- 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);
4235
4335
  }
4236
4336
  async created(args) {
4237
4337
  await this.update(args.name, {
@@ -4249,16 +4349,16 @@ class MachineStore {
4249
4349
  const failure = {
4250
4350
  last_error: `Its platform refused: ${args.reason}`.slice(0, 4000),
4251
4351
  last_error_verb: "create",
4252
- last_error_at: sql3`now()`,
4253
- updated_at: sql3`now()`
4352
+ last_error_at: sql4`now()`,
4353
+ updated_at: sql4`now()`
4254
4354
  };
4255
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;
4256
4356
  await trx.updateTable("work_machines").set(withdrawn ? {
4257
4357
  ...failure,
4258
4358
  enrollment_nonce: null,
4259
4359
  idempotency_key: null,
4260
- refused_count: sql3`refused_count + 1`,
4261
- refused_at: sql3`now()`
4360
+ refused_count: sql4`refused_count + 1`,
4361
+ refused_at: sql4`now()`
4262
4362
  } : failure).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4263
4363
  });
4264
4364
  }
@@ -4267,8 +4367,44 @@ class MachineStore {
4267
4367
  labels: JSON.stringify(args.labels),
4268
4368
  trusted: args.trusted,
4269
4369
  reason: args.reason,
4270
- 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 } : {}
4373
+ });
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)
4271
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 });
4272
4408
  }
4273
4409
  async setFor(args) {
4274
4410
  await this.updatePlacement(args.name, {
@@ -4285,14 +4421,14 @@ class MachineStore {
4285
4421
  }
4286
4422
  async finishReset(args) {
4287
4423
  await this.updatePlacement(args.name, {
4288
- 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`,
4289
4425
  reset_pending: false,
4290
4426
  reset_serves: null
4291
4427
  });
4292
4428
  }
4293
4429
  async setDropped(args) {
4294
4430
  await this.updatePlacement(args.name, {
4295
- dropped_at: args.dropped ? sql3`coalesce(dropped_at, now())` : null
4431
+ dropped_at: args.dropped ? sql4`coalesce(dropped_at, now())` : null
4296
4432
  });
4297
4433
  }
4298
4434
  async openPlacement({ name }) {
@@ -4301,24 +4437,28 @@ class MachineStore {
4301
4437
  async setPhase(args) {
4302
4438
  const moved = await (args.transaction ?? this.deps.db).updateTable("work_machines").set({
4303
4439
  phase: args.phase,
4304
- phase_since: args.at === undefined ? sql3`now()` : new Date(args.at),
4440
+ phase_since: args.at === undefined ? sql4`now()` : new Date(args.at),
4305
4441
  verb_done_at: null,
4306
- updated_at: sql3`now()`,
4442
+ updated_at: sql4`now()`,
4307
4443
  ...args.phase === "destroying" ? {
4308
- destroy_requested_at: sql3`coalesce(destroy_requested_at, now())`
4444
+ destroy_requested_at: sql4`coalesce(destroy_requested_at, now())`
4309
4445
  } : {},
4310
- ...args.lost ? { lost_at: sql3`coalesce(lost_at, now())` } : {},
4311
- ...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
+ } : {}
4312
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();
4313
4452
  return Boolean(moved);
4314
4453
  }
4315
4454
  async startAsked(args) {
4316
- 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();
4317
4456
  }
4318
4457
  async forget(args) {
4319
4458
  const db = args.transaction ?? this.deps.db;
4320
4459
  await db.deleteFrom("work_machines").where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).execute();
4321
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();
4322
4462
  }
4323
4463
  async note(args) {
4324
4464
  await this.update(args.name, { notice: args.notice });
@@ -4327,14 +4467,14 @@ class MachineStore {
4327
4467
  await this.update(args.name, {
4328
4468
  last_error: args.message.slice(0, 4000),
4329
4469
  last_error_verb: args.verb,
4330
- last_error_at: sql3`now()`
4470
+ last_error_at: sql4`now()`
4331
4471
  });
4332
4472
  }
4333
4473
  async succeeded(args) {
4334
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();
4335
4475
  }
4336
4476
  async planned(args) {
4337
- 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 };
4338
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();
4339
4479
  }
4340
4480
  async plan() {
@@ -4351,7 +4491,7 @@ class MachineStore {
4351
4491
  const node = await trx.selectFrom("worker_nodes").select(["id", "admission_revision"]).where("id", "=", nodeId).where("tenant_id", "=", tenantId).forUpdate().executeTakeFirst();
4352
4492
  if (options.onlyWhenUnopened && (!node || node.admission_revision))
4353
4493
  return;
4354
- 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();
4355
4495
  if (node && updated)
4356
4496
  await trx.updateTable("worker_nodes").set({
4357
4497
  admission_revision: updated.reset_pending || updated.dropped_at || updated.phase !== "running" ? null : randomUUID4()
@@ -4359,7 +4499,7 @@ class MachineStore {
4359
4499
  });
4360
4500
  }
4361
4501
  async update(name, values) {
4362
- 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();
4363
4503
  }
4364
4504
  async placementOf(args) {
4365
4505
  const row = await this.row(args);
@@ -4368,7 +4508,7 @@ class MachineStore {
4368
4508
  return storedPlacement(row);
4369
4509
  }
4370
4510
  async placements() {
4371
- 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([
4372
4512
  "machine.name",
4373
4513
  "machine.labels",
4374
4514
  "machine.serves",
@@ -4376,12 +4516,19 @@ class MachineStore {
4376
4516
  "machine.phase",
4377
4517
  "machine.dropped_at",
4378
4518
  "machine.reset_pending",
4519
+ "machine.spare",
4379
4520
  "node.admission_revision"
4380
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();
4381
4523
  return new Map(rows.map((row) => [
4382
4524
  `${WORKER_NODE_PREFIX}${row.name}`,
4383
4525
  {
4384
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
+ })),
4385
4532
  admissionRevision: row.admission_revision,
4386
4533
  accepting: row.phase === "running" && row.admission_revision !== null && row.dropped_at === null && !row.reset_pending
4387
4534
  }
@@ -4389,22 +4536,45 @@ class MachineStore {
4389
4536
  }
4390
4537
  async records() {
4391
4538
  const { db, tenantId } = this.deps;
4392
- const [rows, workers, nodes, holdings, loads, clock] = await Promise.all([
4539
+ const [rows, workers, nodes, holdings, loads, clock, preparations] = await Promise.all([
4393
4540
  db.selectFrom("work_machines").selectAll().where("tenant_id", "=", tenantId).orderBy("name").execute(),
4394
4541
  db.selectFrom("work_workers").select(["name", "enrolled_at", "last_seen_at", "revoked_at"]).where("tenant_id", "=", tenantId).execute(),
4395
4542
  this.deps.nodes.list({ tenantId, authorityId: this.deps.authorityId }),
4396
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([
4397
4544
  "allocation.worker_node_id",
4398
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",
4399
4551
  "session.external_user_id",
4400
4552
  "session.chat_key"
4401
- ]).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(),
4402
4562
  db.selectFrom("execution_allocations").select([
4403
4563
  "worker_node_id",
4404
- sql3`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as("holding"),
4405
- 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")
4406
4566
  ]).where("tenant_id", "=", tenantId).where("worker_node_id", "like", `${WORKER_NODE_PREFIX}%`).groupBy("worker_node_id").execute(),
4407
- 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()
4408
4578
  ]);
4409
4579
  const now = clock.rows[0]?.now ?? new Date;
4410
4580
  const workerOf = new Map(workers.map((worker) => [worker.name, worker]));
@@ -4415,7 +4585,14 @@ class MachineStore {
4415
4585
  const worker = workerOf.get(row.name);
4416
4586
  const node = nodeOf.get(nodeId);
4417
4587
  const load = loadOf.get(nodeId);
4418
- 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));
4419
4596
  const phase = phaseOf(row.phase);
4420
4597
  const seen = worker?.last_seen_at ?? worker?.enrolled_at ?? row.phase_since;
4421
4598
  const lostAfterMs = lostAfterMsOf({
@@ -4441,17 +4618,33 @@ class MachineStore {
4441
4618
  since: sinceOf({ row, state, seen }).toISOString(),
4442
4619
  labels: placement.labels,
4443
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
+ })),
4444
4631
  trusted: placement.trusted,
4445
4632
  options: OptionsSchema.parse(row.options),
4446
4633
  reason: row.reason,
4447
4634
  holding: {
4448
4635
  workspaces: held.length,
4636
+ stopped,
4449
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 }))
4450
4638
  },
4451
- idleSince: (state === "serving" || state === "draining") && Number(load?.holding ?? 0) === 0 ? latest([
4639
+ quietSince: (state === "serving" || state === "draining") && quiet ? latest([
4452
4640
  row.phase_since,
4453
4641
  load?.last_released ?? null,
4454
- 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
+ ])
4455
4648
  ]).toISOString() : null,
4456
4649
  lastSeenAt: worker?.last_seen_at?.toISOString() ?? null,
4457
4650
  capacity: everConnected && node?.capacity ? node.capacity : null,
@@ -4477,12 +4670,13 @@ class MachineStore {
4477
4670
  startAsked: row.verb_done_at !== null,
4478
4671
  destroyRequestedAt: row.destroy_requested_at?.toISOString() ?? null,
4479
4672
  lostAfterMinutes: row.lost_after_minutes,
4480
- revoked: Boolean(worker?.revoked_at)
4673
+ revoked: Boolean(worker?.revoked_at),
4674
+ connectedPending: row.connect_pending
4481
4675
  };
4482
4676
  });
4483
4677
  }
4484
4678
  async now() {
4485
- 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);
4486
4680
  return (clock.rows[0]?.now ?? new Date).toISOString();
4487
4681
  }
4488
4682
  async work() {
@@ -4497,8 +4691,9 @@ class MachineStore {
4497
4691
  "placement_waits.requirements",
4498
4692
  "placement_waits.reason",
4499
4693
  "placement_waits.waiting_since",
4694
+ "placement_waits.worker_node_id",
4500
4695
  "work_accounts.disabled_at",
4501
- 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")
4502
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();
4503
4698
  const work = [];
4504
4699
  for (const row of rows) {
@@ -4518,26 +4713,31 @@ class MachineStore {
4518
4713
  pool: pool.data,
4519
4714
  requirements: requirements.data,
4520
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,
4521
4717
  waitingSince: row.waiting_since.toISOString()
4522
4718
  });
4523
4719
  }
4524
- return work;
4720
+ return [...work, ...await this.signIns.waiting()];
4525
4721
  }
4526
4722
  async signature() {
4527
4723
  const row = await this.deps.db.selectNoFrom((eb) => [
4528
- 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"),
4529
- 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"),
4530
- 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"),
4531
- eb.selectFrom("work_accounts").select(sql3`count(*)::text || '/' || coalesce(max(updated_at)::text, '')`.as("accounts")).as("accounts"),
4532
- 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")
4533
4731
  ]).executeTakeFirst();
4534
4732
  const reach = [...await this.reach()].map(([name, entry]) => `${name}:${entry.state}`).join(",");
4535
4733
  return [
4536
4734
  row?.waits ?? "",
4537
4735
  row?.work ?? "",
4538
4736
  row?.machines ?? "",
4737
+ row?.preparations ?? "",
4539
4738
  row?.accounts ?? "",
4540
4739
  row?.roles ?? "",
4740
+ row?.signIns ?? "",
4541
4741
  reach
4542
4742
  ].join("|");
4543
4743
  }
@@ -4551,9 +4751,9 @@ class MachineStore {
4551
4751
  "machine.disabled_at",
4552
4752
  "machine.lost_at",
4553
4753
  "machine.lost_after_minutes",
4554
- sql3`coalesce(node.enabled AND node.lease_expires_at > now() AND worker.revoked_at IS NULL, false)`.as("live"),
4555
- sql3`(extract(epoch from (now() - coalesce(worker.last_seen_at, worker.enrolled_at, machine.phase_since))) * 1000)::float8`.as("unseen_for_ms"),
4556
- 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")
4557
4757
  ]).where("machine.tenant_id", "=", this.deps.tenantId).execute();
4558
4758
  return new Map(rows.map((row) => [
4559
4759
  row.name,
@@ -4583,6 +4783,12 @@ function hash(value) {
4583
4783
  function principalsJson(principals) {
4584
4784
  return principals === null ? null : JSON.stringify(normalizePrincipals(principals));
4585
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
+ }
4586
4792
  function latest(dates) {
4587
4793
  return dates.reduce((best, date) => date && date > best ? date : best, new Date(0));
4588
4794
  }
@@ -4620,13 +4826,14 @@ function signedInOf(node) {
4620
4826
  return [...members].sort();
4621
4827
  }
4622
4828
  function waitFresh() {
4623
- return sql3`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
4829
+ return sql4`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
4624
4830
  }
4625
4831
  function queuedPlacementWait(db) {
4626
- const turns = db.selectFrom("agent_turns").select("id").where("session_id", "=", sql3`placement_waits.root_workload_id`).where("status", "=", "queued");
4627
- 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", "!=", "durable_pause_timeout").where("job.available_at", "<=", sql3`now()`);
4628
- const fills = db.selectFrom("environment_cache_fills").select("id").where("id", "=", sql3`placement_waits.root_workload_id`).where("status", "=", "queued");
4629
- 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
4630
4837
  (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})) OR
4631
4838
  EXISTS (${fills}))`;
4632
4839
  }
@@ -4807,6 +5014,7 @@ class WorkWorkerRegistry {
4807
5014
  managed: row.managed,
4808
5015
  labels: placement.labels,
4809
5016
  for: placement.for,
5017
+ project: row.project_id,
4810
5018
  options: z10.record(z10.string(), z10.unknown()).parse(row.options),
4811
5019
  reason: row.reason
4812
5020
  },
@@ -4837,13 +5045,13 @@ class WorkWorkerRegistry {
4837
5045
  throw await this.ended(args);
4838
5046
  }
4839
5047
  async seen(nodeId) {
4840
- 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([
4841
5049
  eb("last_seen_at", "is", null),
4842
- eb("last_seen_at", "<", sql4`now() - interval '5 seconds'`)
5050
+ eb("last_seen_at", "<", sql5`now() - interval '5 seconds'`)
4843
5051
  ])).execute();
4844
5052
  }
4845
5053
  async serving(args) {
4846
- 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();
4847
5055
  const { name } = args;
4848
5056
  if (await this.machines.setPhase({
4849
5057
  name,
@@ -4913,7 +5121,7 @@ class WorkWorkerRegistry {
4913
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();
4914
5122
  if (machine?.phase !== "starting" || machine.dropped_at)
4915
5123
  throw invalid();
4916
- 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();
4917
5125
  if (!consumed)
4918
5126
  throw invalid();
4919
5127
  const nodeId = `${WORKER_NODE_PREFIX}${enrollment.name}`;
@@ -4928,7 +5136,7 @@ class WorkWorkerRegistry {
4928
5136
  await trx.updateTable("worker_nodes").set({
4929
5137
  enabled: machine.disabled_at === null,
4930
5138
  admission_revision: null,
4931
- lease_expires_at: sql4`now()`,
5139
+ lease_expires_at: sql5`now()`,
4932
5140
  disk: null,
4933
5141
  disk_low_at: null,
4934
5142
  disk_low_recorded_at: null
@@ -4957,7 +5165,7 @@ class WorkWorkerRegistry {
4957
5165
  return;
4958
5166
  const nodeId = match[1];
4959
5167
  const presented = hash2(match[2]);
4960
- 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();
4961
5169
  if (!row)
4962
5170
  return;
4963
5171
  if (sameHash(row.credential_hash, presented))
@@ -4982,13 +5190,13 @@ class WorkWorkerRegistry {
4982
5190
  return;
4983
5191
  const promoted = await trx.updateTable("work_workers").set({
4984
5192
  credential_hash: args.credentialHash,
4985
- credential_issued_at: sql4`COALESCE(pending_issued_at, now())`,
5193
+ credential_issued_at: sql5`COALESCE(pending_issued_at, now())`,
4986
5194
  pending_credential_hash: null,
4987
5195
  pending_public_key: null,
4988
5196
  pending_issued_at: null,
4989
5197
  pending_rotation: null,
4990
- rotation_requested_at: sql4`CASE WHEN rotation_requested_at <= pending_issued_at THEN NULL ELSE rotation_requested_at END`
4991
- }).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();
4992
5200
  await registerExecutorKey({
4993
5201
  db: trx,
4994
5202
  executor: nodeExecutor(args.nodeId),
@@ -5012,14 +5220,14 @@ class WorkWorkerRegistry {
5012
5220
  await trx.updateTable("work_workers").set({
5013
5221
  pending_credential_hash: hash2(secret),
5014
5222
  pending_public_key: publicKey,
5015
- pending_issued_at: sql4`now()`,
5223
+ pending_issued_at: sql5`now()`,
5016
5224
  pending_rotation: args.rotation
5017
5225
  }).where("node_id", "=", args.nodeId).execute();
5018
5226
  });
5019
5227
  return { credential: `${args.nodeId}:${secret}` };
5020
5228
  }
5021
5229
  async requestRotation(args) {
5022
- 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();
5023
5231
  return Boolean(row);
5024
5232
  }
5025
5233
  async connect(args) {
@@ -5131,8 +5339,8 @@ class WorkWorkerRegistry {
5131
5339
  async setDisabled(args) {
5132
5340
  const name = WorkerName.parse(args.name);
5133
5341
  const row = await this.deps.db.updateTable("work_machines").set({
5134
- disabled_at: args.disabled ? sql4`coalesce(disabled_at, now())` : null,
5135
- updated_at: sql4`now()`
5342
+ disabled_at: args.disabled ? sql5`coalesce(disabled_at, now())` : null,
5343
+ updated_at: sql5`now()`
5136
5344
  }).where("tenant_id", "=", this.deps.tenantId).where("name", "=", name).returning("phase").executeTakeFirst();
5137
5345
  if (!row)
5138
5346
  return false;
@@ -5155,7 +5363,7 @@ class WorkWorkerRegistry {
5155
5363
  }
5156
5364
  cleaning;
5157
5365
  async forgetNeverEnrolled() {
5158
- 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();
5159
5367
  }
5160
5368
  async retireGone() {
5161
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();
@@ -5171,7 +5379,7 @@ class WorkWorkerRegistry {
5171
5379
  await this.retire({ nodeId: machine.nodeId, name, reason: "lost" });
5172
5380
  if (machine.managed || machine.lostNoted)
5173
5381
  continue;
5174
- 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();
5175
5383
  if (noted)
5176
5384
  await this.emit({ kind: "machine.lost", name });
5177
5385
  }
@@ -5214,7 +5422,8 @@ class WorkWorkerRegistry {
5214
5422
  nodeId: node.id,
5215
5423
  offer: node.remote,
5216
5424
  label: "The worker"
5217
- })
5425
+ }),
5426
+ ...this.deps.roomFreed ? { roomFreed: this.deps.roomFreed } : {}
5218
5427
  }).catch((error) => this.deps.log?.(`Workspace cleanup on ${node.id} deferred: ${error instanceof Error ? error.message : String(error)}`));
5219
5428
  }
5220
5429
  }
@@ -5228,7 +5437,7 @@ class WorkWorkerRegistry {
5228
5437
  const nodeId = `${WORKER_NODE_PREFIX}${name}`;
5229
5438
  await trx.selectFrom("worker_nodes").select("id").where("id", "=", nodeId).forUpdate().executeTakeFirst();
5230
5439
  const worker = await trx.updateTable("work_workers").set({
5231
- revoked_at: sql4`now()`,
5440
+ revoked_at: sql5`now()`,
5232
5441
  pending_credential_hash: null,
5233
5442
  pending_public_key: null,
5234
5443
  pending_issued_at: null,
@@ -5278,10 +5487,10 @@ class WorkWorkerRegistry {
5278
5487
  const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
5279
5488
  return this.deps.db.transaction().execute(async (trx) => {
5280
5489
  await this.machines.lockName({ name: args.name, transaction: trx });
5281
- 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();
5282
5491
  const worker = await trx.selectFrom("work_workers").select([
5283
5492
  "revoked_at",
5284
- 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")
5285
5494
  ]).where("tenant_id", "=", this.deps.tenantId).where("name", "=", args.name).executeTakeFirst();
5286
5495
  const serving = worker !== undefined && worker.revoked_at === null;
5287
5496
  if (args.lost) {
@@ -5290,7 +5499,11 @@ class WorkWorkerRegistry {
5290
5499
  if (serving && Number(worker.unseen_for_ms) < args.lost.unseenForMs)
5291
5500
  return false;
5292
5501
  } else if (serving) {
5293
- 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();
5294
5507
  if (Number(held?.count ?? 0) > 0)
5295
5508
  return false;
5296
5509
  }
@@ -5306,7 +5519,7 @@ class WorkWorkerRegistry {
5306
5519
  if (!serving)
5307
5520
  return true;
5308
5521
  await trx.updateTable("work_workers").set({
5309
- revoked_at: sql4`now()`,
5522
+ revoked_at: sql5`now()`,
5310
5523
  pending_credential_hash: null,
5311
5524
  pending_public_key: null,
5312
5525
  pending_issued_at: null,
@@ -5321,7 +5534,7 @@ class WorkWorkerRegistry {
5321
5534
  const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
5322
5535
  return this.deps.db.transaction().execute(async (trx) => {
5323
5536
  await trx.selectFrom("worker_nodes").select("id").where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).forUpdate().executeTakeFirst();
5324
- 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();
5325
5538
  if (Number(held?.count ?? 0) > 0)
5326
5539
  return false;
5327
5540
  const moved = await this.machines.setPhase({
@@ -5357,13 +5570,13 @@ class WorkWorkerRegistry {
5357
5570
  await trx.updateTable("worker_nodes").set({
5358
5571
  enabled: machine?.disabled_at === null,
5359
5572
  admission_revision: null,
5360
- lease_expires_at: sql4`now()`
5573
+ lease_expires_at: sql5`now()`
5361
5574
  }).where("id", "=", nodeId).where("tenant_id", "=", this.deps.tenantId).where("authority_id", "=", this.deps.authorityId).execute();
5362
5575
  return true;
5363
5576
  });
5364
5577
  }
5365
5578
  async holding(args) {
5366
- 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();
5367
5580
  return Number(row?.count ?? 0);
5368
5581
  }
5369
5582
  async activeWorkspaces(args) {
@@ -5408,6 +5621,11 @@ class WorkWorkerRegistry {
5408
5621
  if (await this.holding({ name }) > 0)
5409
5622
  return "busy";
5410
5623
  await this.resetMachine({ name, timeoutMs });
5624
+ await this.retire({
5625
+ nodeId: `${WORKER_NODE_PREFIX}${name}`,
5626
+ name,
5627
+ reason: "replaced"
5628
+ });
5411
5629
  await this.machines.finishReset({ name });
5412
5630
  return "done";
5413
5631
  } finally {
@@ -5425,6 +5643,7 @@ class WorkWorkerRegistry {
5425
5643
  ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}
5426
5644
  });
5427
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();
5428
5647
  }
5429
5648
  async list() {
5430
5649
  const [records, workers] = await Promise.all([
@@ -5528,7 +5747,8 @@ async function registerWorkMachine(args) {
5528
5747
  workerNodeId,
5529
5748
  allocationBindingId,
5530
5749
  requirements,
5531
- fill
5750
+ fill,
5751
+ environment
5532
5752
  }) => {
5533
5753
  const candidates = await nodes.list({
5534
5754
  tenantId,
@@ -5552,13 +5772,15 @@ async function registerWorkMachine(args) {
5552
5772
  });
5553
5773
  const holdsAllocation = (nodeId) => allocationBindingId === nodeId && workerNodeId === nodeId;
5554
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"));
5555
- const tierOf = (policy) => accessTier({
5775
+ const tierOf = (policy) => policy?.spare && !chatKey && !fill ? undefined : accessTier2({
5556
5776
  access: policy ? nodeAccess(policy.for) : { everyone: true },
5557
5777
  owner,
5558
5778
  ...projectId ? { projectId } : {},
5559
- ...chatKey ? { chatKey } : {}
5779
+ ...chatKey ? { chatKey } : {},
5780
+ ...fill ? { fill: true } : {}
5560
5781
  });
5561
- 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 });
5562
5784
  const storageMb = (requirements?.resources?.storageMb ?? 0) + (fill?.storageMb ?? 0);
5563
5785
  const workload = requirements?.workload && !fill ? { workload: requirements.workload } : {};
5564
5786
  const roomy = ({ node }) => diskFits({
@@ -5596,10 +5818,15 @@ async function registerWorkMachine(args) {
5596
5818
  };
5597
5819
  const servesOnlyOwner = Boolean(chosen.policy && servesOnlyThisOwner(tierOf(chosen.policy)));
5598
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
+ });
5599
5825
  return {
5600
5826
  descriptor: selected.descriptor,
5601
5827
  workerNodeId: selected.id,
5602
5828
  ...servesOnlyOwner ? { servesOnlyOwner } : {},
5829
+ ...ceiling ? { ceiling } : {},
5603
5830
  ...ownSignIns ? { ownSignIns: true } : {},
5604
5831
  ...selected.id === lease.id ? {
5605
5832
  sandboxProvider: args.sandboxProvider,
@@ -5694,7 +5921,8 @@ async function registerWorkMachine(args) {
5694
5921
  cleanup = cleanupWorkerAllocations2({
5695
5922
  db: args.db,
5696
5923
  workerNode: lease,
5697
- provider: args.sandboxProvider
5924
+ provider: args.sandboxProvider,
5925
+ ...args.roomFreed ? { roomFreed: args.roomFreed } : {}
5698
5926
  }).catch((error) => console.warn("[catamorphic] Workspace cleanup deferred", error)).finally(() => {
5699
5927
  cleanup = undefined;
5700
5928
  });
@@ -5711,7 +5939,7 @@ async function registerWorkMachine(args) {
5711
5939
  if (JSON.stringify(next) === JSON.stringify(signIns))
5712
5940
  return;
5713
5941
  signIns = next;
5714
- 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(() => {
5715
5943
  refreshing = undefined;
5716
5944
  if (!again)
5717
5945
  return;
@@ -5756,6 +5984,15 @@ function workPushKeys(secret) {
5756
5984
  }
5757
5985
  throw new Error("Could not derive the deployment's notification signing key");
5758
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
+ }
5759
5996
 
5760
5997
  // src/company-sync.ts
5761
5998
  import {
@@ -5912,7 +6149,7 @@ import {
5912
6149
  DIRECTORY_EVENT_SOURCE,
5913
6150
  directoryProjectEvent
5914
6151
  } from "@catamorphic/server-sdk";
5915
- import { sql as sql6 } from "kysely";
6152
+ import { sql as sql7 } from "kysely";
5916
6153
  var tracer = getTracer("@catamorphic/work-server");
5917
6154
 
5918
6155
  class AccountLifecycle {
@@ -6120,7 +6357,7 @@ class AccountLifecycle {
6120
6357
  let claimed;
6121
6358
  try {
6122
6359
  return await this.deps.db.transaction().execute(async (trx) => {
6123
- 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();
6124
6361
  if (!row)
6125
6362
  return "none";
6126
6363
  claimed = {
@@ -6148,7 +6385,7 @@ class AccountLifecycle {
6148
6385
  await this.deps.db.updateTable("work_directory_announcements").set({
6149
6386
  attempts: attempts + 1,
6150
6387
  last_error: message,
6151
- 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)})`
6152
6389
  }).where("id", "=", claimed.id).execute();
6153
6390
  this.deps.log?.(`Directory event ${claimed.externalId} did not reach its projects (attempt ${attempts + 1}): ${message}`);
6154
6391
  return "failed";
@@ -6483,6 +6720,7 @@ function registerAdministratorRoutes(app, options) {
6483
6720
  import { randomUUID as randomUUID7 } from "node:crypto";
6484
6721
  import {
6485
6722
  PlacementWaitsService as PlacementWaitsService2,
6723
+ PollPacer,
6486
6724
  releaseReplicaClaim as releaseReplicaClaim2,
6487
6725
  renewReplicaClaim as renewReplicaClaim2,
6488
6726
  takeReplicaClaim as takeReplicaClaim3
@@ -6490,6 +6728,8 @@ import {
6490
6728
  import { getTracer as getTracer2, withSpan as withSpan2 } from "@catamorphic/otel";
6491
6729
  var tracer2 = getTracer2("@catamorphic/work-server");
6492
6730
  var RESET_WAIT_MS = 3 * 60000;
6731
+ var MACHINE_CHECK_INTERVAL_MS = 1e4;
6732
+ var MACHINE_CHECK_QUICK_MS = 500;
6493
6733
  function workMachineWorld(deps) {
6494
6734
  const { workers } = deps;
6495
6735
  const machines = workers.machines;
@@ -6506,6 +6746,8 @@ function workMachineWorld(deps) {
6506
6746
  created: (args) => machines.created(args),
6507
6747
  refused: (args) => machines.refused(args),
6508
6748
  configure: (args) => machines.configure(args),
6749
+ prepare: (args) => deps.prepare(args),
6750
+ heardConnected: (args) => machines.heardConnected(args),
6509
6751
  setFor: (args) => machines.setFor(args),
6510
6752
  beginReset: (args) => machines.beginReset(args),
6511
6753
  reset: ({ name }) => workers.resetPlacement({
@@ -6516,7 +6758,12 @@ function workMachineWorld(deps) {
6516
6758
  undrop: ({ name }) => machines.setDropped({ name, dropped: false }),
6517
6759
  retire: (args) => workers.retireMachine(args),
6518
6760
  declareLost: (args) => workers.declareLost(args),
6519
- 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
+ },
6520
6767
  stopped: async ({ name }) => {
6521
6768
  await machines.setPhase({ name, phase: "stopped", from: ["stopping"] });
6522
6769
  },
@@ -6564,6 +6811,21 @@ class WorkMachines {
6564
6811
  return;
6565
6812
  this.passSoon();
6566
6813
  }
6814
+ async watch(args) {
6815
+ const pacer = new PollPacer({
6816
+ quickMs: args.quickMs ?? MACHINE_CHECK_QUICK_MS,
6817
+ idleMs: args.intervalMs ?? MACHINE_CHECK_INTERVAL_MS,
6818
+ signal: args.signal,
6819
+ wakeups: args.wakeups,
6820
+ topic: "placement"
6821
+ });
6822
+ while (!args.signal.aborted) {
6823
+ await pacer.wait();
6824
+ if (args.signal.aborted)
6825
+ return;
6826
+ await this.check().catch((error) => this.deps.log?.(`Machine check failed: ${message(error)}`));
6827
+ }
6828
+ }
6567
6829
  get leaseMs() {
6568
6830
  return this.deps.leaseMs ?? 120000;
6569
6831
  }
@@ -7640,7 +7902,7 @@ import {
7640
7902
  identityMayUseEnvironment,
7641
7903
  normalizeDocumentPath
7642
7904
  } from "@catamorphic/core";
7643
- import { sql as sql7 } from "kysely";
7905
+ import { sql as sql8 } from "kysely";
7644
7906
  import { z as z17 } from "zod";
7645
7907
  var CreateShareSchema = z17.strictObject({
7646
7908
  kind: z17.enum(["document", "folder", "app"]),
@@ -7706,7 +7968,7 @@ class WorkSharesService {
7706
7968
  if (!hasProjectPermission3(args.identity, args.projectId, "publications:write")) {
7707
7969
  throw new ShareAccessError("Revoking shares needs publications:write");
7708
7970
  }
7709
- 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();
7710
7972
  return Boolean(row);
7711
7973
  }
7712
7974
  async isGuest(userId) {
@@ -7719,7 +7981,7 @@ class WorkSharesService {
7719
7981
  async open(args) {
7720
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([
7721
7983
  eb("work_shares.expires_at", "is", null),
7722
- eb("work_shares.expires_at", ">", sql7`now()`)
7984
+ eb("work_shares.expires_at", ">", sql8`now()`)
7723
7985
  ])).executeTakeFirst();
7724
7986
  if (!row)
7725
7987
  return null;
@@ -8247,17 +8509,168 @@ function shareTools(shares, args) {
8247
8509
  ];
8248
8510
  }
8249
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
+
8250
8583
  // src/workers/disk-care.ts
8584
+ import fs10 from "node:fs";
8585
+ import path8 from "node:path";
8251
8586
  import {
8252
8587
  describeDisk as describeDisk3,
8253
8588
  diskLow,
8254
8589
  measureDisk
8255
8590
  } from "@catamorphic/sandbox";
8591
+ import { z as z20 } from "zod";
8256
8592
  var DISK_MEASURE_INTERVAL_MS = 30000;
8257
8593
  var DISK_CLEAN_INTERVAL_MS = 60 * 60000;
8258
8594
  var DISK_LOW_CLEAN_INTERVAL_MS = 10 * 60000;
8595
+ var DISK_AWAY_AFTER_MS = 5 * 60000;
8596
+ var RUNNING_TIME_FILE = "running-time.json";
8597
+ function reachOfRunningTime(args) {
8598
+ let left = args.ranMs;
8599
+ let cursor = args.now;
8600
+ for (const stretch of [...args.away].sort((a, b) => b.to - a.to)) {
8601
+ const to = Math.min(stretch.to, cursor);
8602
+ if (stretch.from >= to)
8603
+ continue;
8604
+ const ran = cursor - to;
8605
+ if (ran >= left)
8606
+ break;
8607
+ left -= ran;
8608
+ cursor = stretch.from;
8609
+ }
8610
+ return args.now - (cursor - left);
8611
+ }
8612
+ var RunningNotes = z20.object({
8613
+ seenAt: z20.number(),
8614
+ away: z20.array(z20.tuple([z20.number(), z20.number()]))
8615
+ });
8616
+
8617
+ class RunningTime {
8618
+ args;
8619
+ seenAt;
8620
+ away = [];
8621
+ failed = false;
8622
+ constructor(args) {
8623
+ this.args = args;
8624
+ const notes = RunningNotes.safeParse(read(args.file)).data;
8625
+ if (!notes)
8626
+ return;
8627
+ this.seenAt = notes.seenAt;
8628
+ this.away = notes.away.map(([from, to]) => ({ from, to }));
8629
+ }
8630
+ note() {
8631
+ const now = this.args.now();
8632
+ if (this.seenAt !== undefined && now - this.seenAt > this.args.awayAfterMs)
8633
+ this.away.push({ from: this.seenAt, to: now });
8634
+ this.seenAt = now;
8635
+ const reach = reachOfRunningTime({
8636
+ ranMs: this.args.keepMs,
8637
+ now,
8638
+ away: this.away
8639
+ });
8640
+ this.away = this.away.filter((stretch) => stretch.to > now - reach && stretch.from < now);
8641
+ try {
8642
+ fs10.mkdirSync(path8.dirname(this.args.file), { recursive: true });
8643
+ const temporary = `${this.args.file}.${process.pid}.tmp`;
8644
+ fs10.writeFileSync(temporary, JSON.stringify({
8645
+ seenAt: this.seenAt,
8646
+ away: this.away.map((stretch) => [stretch.from, stretch.to])
8647
+ }), { mode: 384 });
8648
+ fs10.renameSync(temporary, this.args.file);
8649
+ this.failed = false;
8650
+ } catch (error) {
8651
+ if (!this.failed)
8652
+ this.args.log?.(`Could not note that this machine is running: ${error instanceof Error ? error.message : String(error)}`);
8653
+ this.failed = true;
8654
+ }
8655
+ return reach;
8656
+ }
8657
+ }
8658
+ function read(file) {
8659
+ try {
8660
+ return JSON.parse(fs10.readFileSync(file, "utf8"));
8661
+ } catch {
8662
+ return;
8663
+ }
8664
+ }
8259
8665
  function startDiskCare(args) {
8260
8666
  const measure = args.measureDisk ?? measureDisk;
8667
+ const running = args.runningFile && args.provider.disk?.clean ? new RunningTime({
8668
+ file: args.runningFile,
8669
+ keepMs: args.graceMs,
8670
+ awayAfterMs: args.awayAfterMs ?? DISK_AWAY_AFTER_MS,
8671
+ now: args.now ?? Date.now,
8672
+ ...args.log ? { log: args.log } : {}
8673
+ }) : undefined;
8261
8674
  let latest;
8262
8675
  let wasLow = false;
8263
8676
  let stopped = false;
@@ -8268,7 +8681,7 @@ function startDiskCare(args) {
8268
8681
  if (!run || cleaning || stopped)
8269
8682
  return;
8270
8683
  lastClean = Date.now();
8271
- cleaning = run({ graceMs: args.graceMs }).then((lines) => {
8684
+ cleaning = run({ graceMs: running?.note() ?? args.graceMs }).then((lines) => {
8272
8685
  for (const line of lines)
8273
8686
  args.log?.(line);
8274
8687
  }).catch((error) => args.log?.(`Removing what Work left on this machine failed: ${error instanceof Error ? error.message : String(error)}`)).finally(() => {
@@ -8302,8 +8715,12 @@ function startDiskCare(args) {
8302
8715
  });
8303
8716
  return measuring;
8304
8717
  };
8718
+ running?.note();
8305
8719
  measureNow();
8306
- const timer = setInterval(() => void measureNow(), args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS);
8720
+ const timer = setInterval(() => {
8721
+ running?.note();
8722
+ measureNow();
8723
+ }, args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS);
8307
8724
  timer.unref();
8308
8725
  return {
8309
8726
  latest: () => latest,
@@ -8318,33 +8735,38 @@ function startDiskCare(args) {
8318
8735
  // src/workers/harness-sign-ins.ts
8319
8736
  import { spawn } from "node:child_process";
8320
8737
  import { randomUUID as randomUUID8 } from "node:crypto";
8321
- import fs10 from "node:fs";
8738
+ import fs11 from "node:fs";
8739
+ import path9 from "node:path";
8322
8740
  import {
8323
- 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
8324
8745
  } from "@catamorphic/sandbox";
8325
- import { z as z20 } from "zod";
8746
+ import { z as z21 } from "zod";
8326
8747
  var SIGN_IN_INPUT_MAX = 4096;
8327
- var HarnessSignInStartedSchema = z20.strictObject({
8328
- attempt: z20.string().uuid(),
8329
- verificationUrl: z20.string().url().max(8192),
8330
- userCode: z20.string().min(1).max(32).optional(),
8331
- expects: z20.literal("code").optional(),
8332
- expiresAt: z20.string().datetime()
8748
+ var HarnessSignInStartedSchema = z21.strictObject({
8749
+ attempt: z21.string().uuid(),
8750
+ verificationUrl: z21.string().url().max(8192),
8751
+ userCode: z21.string().min(1).max(32).optional(),
8752
+ expects: z21.literal("code").optional(),
8753
+ expiresAt: z21.string().datetime()
8333
8754
  });
8334
- var HarnessSignInStatusSchema = z20.strictObject({
8335
- state: z20.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
8336
- message: z20.string().max(400).optional()
8755
+ var HarnessSignInStatusSchema = z21.strictObject({
8756
+ state: z21.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
8757
+ message: z21.string().max(400).optional()
8337
8758
  });
8338
- var HarnessSignedOutSchema = z20.strictObject({
8339
- signedOut: z20.boolean()
8759
+ var HarnessSignedOutSchema = z21.strictObject({
8760
+ signedOut: z21.boolean()
8340
8761
  });
8341
- var HarnessSignInRefusedSchema = z20.strictObject({
8342
- refused: z20.string().min(1).max(400)
8762
+ var HarnessSignInRefusedSchema = z21.strictObject({
8763
+ refused: z21.string().min(1).max(400)
8343
8764
  });
8344
8765
  var CODE_TIMEOUT_MS = 30000;
8345
8766
  var DEFAULT_CODE_MINUTES = 15;
8346
8767
  var EXIT_DRAIN_MS = 500;
8347
8768
  var FINISHED_TTL_MS = 60 * 60000;
8769
+ var SANDBOX_NOTE = ".sandbox";
8348
8770
  function plainOutput(text) {
8349
8771
  return text.replace(/\u001b\[[0-9;]*[A-Za-z]/g, "");
8350
8772
  }
@@ -8412,6 +8834,97 @@ class HarnessSignIns {
8412
8834
  constructor(options) {
8413
8835
  this.options = options;
8414
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
+ }
8415
8928
  async handle(request) {
8416
8929
  const refusal = (error) => {
8417
8930
  if (error instanceof HarnessSignInRefusedError)
@@ -8445,6 +8958,7 @@ class HarnessSignIns {
8445
8958
  }
8446
8959
  async begin(input) {
8447
8960
  this.prune();
8961
+ await this.recover();
8448
8962
  const { harness, member } = input;
8449
8963
  const spec = SIGN_IN_SPECS2[harness];
8450
8964
  try {
@@ -8462,19 +8976,18 @@ class HarnessSignIns {
8462
8976
  harness,
8463
8977
  member
8464
8978
  });
8465
- const login = signInCommand({
8466
- harness,
8467
- home: staging,
8468
- env: this.options.env
8469
- });
8470
- const child = spawn(login.command, login.args, {
8471
- env: signInEnvironment({
8979
+ let started;
8980
+ try {
8981
+ started = await this.startLogin({
8472
8982
  harness,
8473
- base: this.options.env ?? process.env,
8474
- login: { ...login.env, NO_COLOR: "1" }
8475
- }),
8476
- stdio: [spec.expects ? "pipe" : "ignore", "pipe", "pipe"]
8477
- });
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;
8478
8991
  child.stdin?.on("error", () => {
8479
8992
  return;
8480
8993
  });
@@ -8488,7 +9001,7 @@ class HarnessSignIns {
8488
9001
  settled = true;
8489
9002
  clearTimeout(timer);
8490
9003
  child.kill("SIGTERM");
8491
- fs10.rmSync(staging, { recursive: true, force: true });
9004
+ release().then(() => fs11.rmSync(staging, { recursive: true, force: true }));
8492
9005
  reject(new HarnessSignInRefusedError(message));
8493
9006
  };
8494
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);
@@ -8514,6 +9027,7 @@ class HarnessSignIns {
8514
9027
  harness,
8515
9028
  member,
8516
9029
  child,
9030
+ release,
8517
9031
  staging,
8518
9032
  expiresAt,
8519
9033
  state: "waiting",
@@ -8531,7 +9045,7 @@ class HarnessSignIns {
8531
9045
  child.stdout?.on("data", read);
8532
9046
  child.stderr?.on("data", read);
8533
9047
  child.once("error", (error) => fail(`Could not run ${spec.name} on this machine: ${error.message}. Install it there first`));
8534
- const ended = (code) => {
9048
+ const ended = async (code) => {
8535
9049
  if (!settled) {
8536
9050
  fail(lastWords(output) ?? `${spec.name} stopped before printing a sign-in link (exit ${code ?? "signal"})`);
8537
9051
  return;
@@ -8539,6 +9053,9 @@ class HarnessSignIns {
8539
9053
  const attempt = this.attempts.get(id);
8540
9054
  if (attempt?.state !== "waiting")
8541
9055
  return;
9056
+ await release();
9057
+ if (this.attempts.get(id)?.state !== "waiting")
9058
+ return;
8542
9059
  if (code === 0 && signedIn({ harness, home: staging })) {
8543
9060
  try {
8544
9061
  assertMachineFree({ root: this.options.signInRoot, member });
@@ -8563,6 +9080,7 @@ class HarnessSignIns {
8563
9080
  Promise.all([drained(child.stdout), drained(child.stderr)]),
8564
9081
  new Promise((resolve) => setTimeout(resolve, EXIT_DRAIN_MS))
8565
9082
  ]).then(() => ended(code));
9083
+ release();
8566
9084
  });
8567
9085
  });
8568
9086
  }
@@ -8623,8 +9141,10 @@ class HarnessSignIns {
8623
9141
  clearTimeout(attempt.deadline);
8624
9142
  if (attempt.child.exitCode === null)
8625
9143
  attempt.child.kill("SIGTERM");
8626
- if (state !== "signed-in")
8627
- fs10.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 }));
8628
9148
  }
8629
9149
  prune() {
8630
9150
  const now = this.now();
@@ -8638,18 +9158,34 @@ class HarnessSignIns {
8638
9158
  }
8639
9159
 
8640
9160
  // src/workers/member-machine-routes.ts
8641
- 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";
8642
9170
  import { signInHarness as signInHarness2 } from "@catamorphic/sandbox";
8643
- import { z as z22 } from "zod";
9171
+ import { z as z23 } from "zod";
8644
9172
 
8645
9173
  // src/workers/member-machines.ts
8646
9174
  import {
8647
- accessTier as accessTier2,
9175
+ accessTier as accessTier3,
8648
9176
  MACHINE_CAPABILITIES as MACHINE_CAPABILITIES5,
8649
9177
  parseSignInCapability as parseSignInCapability2,
9178
+ SIGN_IN_HARNESSES as SIGN_IN_HARNESSES4,
8650
9179
  signInCapability as signInCapability2
8651
9180
  } from "@catamorphic/sandbox";
8652
- import { z as z21 } from "zod";
9181
+ import { z as z22 } from "zod";
9182
+ var NOT_YET_SERVING = new Set([
9183
+ "starting",
9184
+ "stopping",
9185
+ "stopped",
9186
+ "resuming"
9187
+ ]);
9188
+
8653
9189
  class NotYourMachineError extends Error {
8654
9190
  constructor() {
8655
9191
  super("This is not a machine of your own, so your sign-in cannot go on it");
@@ -8662,30 +9198,79 @@ class MemberMachines {
8662
9198
  constructor(deps) {
8663
9199
  this.deps = deps;
8664
9200
  }
8665
- async list(identity) {
9201
+ async list(identity, options = {}) {
8666
9202
  const own = await this.own(identity);
8667
9203
  const nodes = new Map((await this.deps.nodes()).map((node) => [node.id, node]));
8668
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;
8669
9210
  return [...own].map(([id, machine]) => {
8670
9211
  const node = nodes.get(id);
9212
+ const signIns = signInStates((harness) => node?.descriptor.capabilities.includes(signInCapability2({ harness, member })) ? "signed-in" : "signed-out");
8671
9213
  return {
8672
9214
  id,
8673
9215
  name: machine?.name ?? node?.descriptor.label ?? id,
8674
9216
  available: machine ? machine.state === "serving" : Boolean(node?.available),
8675
9217
  state: machine?.state ?? "serving",
8676
9218
  reason: machine?.reason ?? null,
8677
- 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
+ } : {}
8678
9227
  };
8679
9228
  });
8680
9229
  }
8681
9230
  async begin(args) {
8682
- const answer = z21.union([HarnessSignInStartedSchema, HarnessSignInRefusedSchema]).parse(await this.send(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
+ }
9253
+ const answer = z22.union([HarnessSignInStartedSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8683
9254
  action: "begin",
8684
9255
  harness: args.harness,
8685
- member: args.identity.externalUserId
9256
+ member,
9257
+ sandbox: resolved.sandbox
8686
9258
  }));
9259
+ if (machine)
9260
+ await this.deps.signIns.began({ machine: machine.name, member });
8687
9261
  if ("refused" in answer)
8688
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
+ });
8689
9274
  return answer;
8690
9275
  }
8691
9276
  async status(args) {
@@ -8697,7 +9282,7 @@ class MemberMachines {
8697
9282
  })));
8698
9283
  }
8699
9284
  async input(args) {
8700
- const answer = z21.union([HarnessSignInStatusSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
9285
+ const answer = z22.union([HarnessSignInStatusSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8701
9286
  action: "input",
8702
9287
  harness: args.harness,
8703
9288
  member: args.identity.externalUserId,
@@ -8717,11 +9302,17 @@ class MemberMachines {
8717
9302
  });
8718
9303
  }
8719
9304
  async signOut(args) {
8720
- return HarnessSignedOutSchema.parse(await this.send(args, {
9305
+ const answer = HarnessSignedOutSchema.parse(await this.send(args, {
8721
9306
  action: "signOut",
8722
9307
  harness: args.harness,
8723
9308
  member: args.identity.externalUserId
8724
9309
  }));
9310
+ await this.deps.signIns.signedOut({
9311
+ nodeId: args.machineId,
9312
+ member: args.identity.externalUserId,
9313
+ harness: args.harness
9314
+ });
9315
+ return answer;
8725
9316
  }
8726
9317
  async usable(args, status) {
8727
9318
  if (status.state !== "signed-in")
@@ -8731,7 +9322,15 @@ class MemberMachines {
8731
9322
  harness: args.harness,
8732
9323
  member: args.identity.externalUserId
8733
9324
  }));
8734
- 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;
8735
9334
  }
8736
9335
  async send(args, request) {
8737
9336
  const own = await this.own(args.identity);
@@ -8748,7 +9347,7 @@ class MemberMachines {
8748
9347
  for (const machine of await this.deps.machines()) {
8749
9348
  if (machine.state === "destroying" || machine.state === "draining")
8750
9349
  continue;
8751
- if (accessTier2({ access: nodeAccess(machine.for), owner }) === 1)
9350
+ if (accessTier3({ access: nodeAccess(machine.for), owner }) === 1)
8752
9351
  own.set(`${WORKER_NODE_PREFIX}${machine.name}`, machine);
8753
9352
  }
8754
9353
  const ownMachine = this.deps.ownMachine;
@@ -8762,6 +9361,12 @@ class MemberMachines {
8762
9361
  return own;
8763
9362
  }
8764
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
+ }
8765
9370
  function signInStates(state) {
8766
9371
  return {
8767
9372
  "claude-code": state("claude-code"),
@@ -8771,14 +9376,19 @@ function signInStates(state) {
8771
9376
 
8772
9377
  // src/workers/member-machine-routes.ts
8773
9378
  function registerMemberMachineRoutes(app, options) {
8774
- const harnessParams = z22.object({
8775
- id: z22.string().min(1).max(200),
8776
- harness: z22.string().min(1).max(40)
9379
+ const harnessParams = z23.object({
9380
+ id: z23.string().min(1).max(200),
9381
+ harness: z23.string().min(1).max(40)
9382
+ });
9383
+ const attemptParams = harnessParams.extend({ attempt: z23.string().uuid() });
9384
+ const inputBody = z23.strictObject({
9385
+ text: z23.string().min(1).max(SIGN_IN_INPUT_MAX)
8777
9386
  });
8778
- const attemptParams = harnessParams.extend({ attempt: z22.string().uuid() });
8779
- const inputBody = z22.strictObject({
8780
- text: z22.string().min(1).max(SIGN_IN_INPUT_MAX)
9387
+ const beginBody = z23.strictObject({
9388
+ project: z23.string().uuid(),
9389
+ environment: z23.string().min(1).max(200)
8781
9390
  });
9391
+ const listQuery = z23.object({ project: z23.string().uuid().optional() });
8782
9392
  const member = async (request, reply) => {
8783
9393
  const identity = await options.caller(request);
8784
9394
  if (!identity) {
@@ -8794,8 +9404,12 @@ function registerMemberMachineRoutes(app, options) {
8794
9404
  return harness;
8795
9405
  };
8796
9406
  const refusal = (reply, error) => {
8797
- if (error instanceof NotYourMachineError)
9407
+ if (error instanceof NotYourMachineError || error instanceof AccessDeniedError || error instanceof EnvironmentAccessDeniedError)
8798
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" });
8799
9413
  if (error instanceof HarnessSignInRefusedError)
8800
9414
  return reply.status(409).send({ error: error.message, code: "sign_in_refused" });
8801
9415
  if (error instanceof ExecutorNotConnectedError)
@@ -8811,7 +9425,16 @@ function registerMemberMachineRoutes(app, options) {
8811
9425
  const identity = await member(request, reply);
8812
9426
  if (!identity)
8813
9427
  return reply;
8814
- 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
+ }
8815
9438
  });
8816
9439
  app.post("/api/work/me/machines/:id/:harness/sign-in", async (request, reply) => {
8817
9440
  const identity = await member(request, reply);
@@ -8821,12 +9444,21 @@ function registerMemberMachineRoutes(app, options) {
8821
9444
  const harness = await harnessOf(reply, params.harness);
8822
9445
  if (!harness)
8823
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
+ });
8824
9452
  try {
8825
9453
  const started = await options.machines.begin({
8826
9454
  identity,
8827
9455
  machineId: params.id,
8828
- harness
9456
+ harness,
9457
+ projectId: body.data.project,
9458
+ environment: body.data.environment
8829
9459
  });
9460
+ if ("state" in started)
9461
+ return reply.status(202).send(started);
8830
9462
  return reply.status(201).send(started);
8831
9463
  } catch (error) {
8832
9464
  return refusal(reply, error);
@@ -8948,12 +9580,12 @@ import {
8948
9580
  RemoteReceiptRefusedError
8949
9581
  } from "@catamorphic/core";
8950
9582
  import { ExecutorPublicKeySchema as ExecutorPublicKeySchema2 } from "@catamorphic/sandbox";
8951
- import { z as z23 } from "zod";
9583
+ import { z as z24 } from "zod";
8952
9584
 
8953
9585
  // src/workers/worker-protocol.ts
8954
9586
  var WORKER_PROTOCOL_HEADER = "work-protocol";
8955
9587
  var WORKER_PROTOCOL = {
8956
- server: 4,
9588
+ server: 6,
8957
9589
  minimum: 4
8958
9590
  };
8959
9591
  function workerProtocolRefusal(stated) {
@@ -8974,17 +9606,17 @@ function upgradeMessage(input) {
8974
9606
  }
8975
9607
 
8976
9608
  // src/workers/worker-routes.ts
8977
- var Session = z23.strictObject({ session: z23.string().uuid() });
9609
+ var Session = z24.strictObject({ session: z24.string().uuid() });
8978
9610
  var Renewal = Session.extend({ disk: MachineDiskSchema2.optional() });
8979
9611
  var Poll = Session.extend({
8980
- pollId: z23.string().uuid(),
8981
- max: z23.number().int().min(1).max(64).default(1)
9612
+ pollId: z24.string().uuid(),
9613
+ max: z24.number().int().min(1).max(64).default(1)
8982
9614
  });
8983
- var Completion = z23.strictObject({
8984
- session: z23.string().uuid(),
8985
- jobId: z23.string().uuid(),
8986
- response: z23.unknown().optional(),
8987
- error: z23.string().max(1e4).optional()
9615
+ var Completion = z24.strictObject({
9616
+ session: z24.string().uuid(),
9617
+ jobId: z24.string().uuid(),
9618
+ response: z24.unknown().optional(),
9619
+ error: z24.string().max(1e4).optional()
8988
9620
  });
8989
9621
  function registerWorkerRoutes(app, registry) {
8990
9622
  const authenticated = async (request, reply) => {
@@ -9001,8 +9633,8 @@ function registerWorkerRoutes(app, registry) {
9001
9633
  app.post("/api/workers/enroll", async (request, reply) => {
9002
9634
  if (await refusedProtocol(request, reply))
9003
9635
  return reply;
9004
- const body = z23.strictObject({
9005
- code: z23.string().min(10),
9636
+ const body = z24.strictObject({
9637
+ code: z24.string().min(10),
9006
9638
  publicKey: ExecutorPublicKeySchema2
9007
9639
  }).safeParse(request.body);
9008
9640
  if (!body.success) {
@@ -9049,9 +9681,9 @@ function registerWorkerRoutes(app, registry) {
9049
9681
  const worker = await authenticated(request, reply);
9050
9682
  if (!worker)
9051
9683
  return reply;
9052
- const body = z23.strictObject({
9684
+ const body = z24.strictObject({
9053
9685
  publicKey: ExecutorPublicKeySchema2,
9054
- rotation: z23.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
9686
+ rotation: z24.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
9055
9687
  }).safeParse(request.body);
9056
9688
  if (!body.success)
9057
9689
  return reply.status(400).send({ error: "Provide the new public key and a rotation id" });
@@ -9179,6 +9811,8 @@ async function createWorkServerInner(options, disposers, close) {
9179
9811
  const log = options.log ?? (() => {});
9180
9812
  const data = config.dataDir;
9181
9813
  const publicBase = config.publicBases[0] ?? "http://127.0.0.1:4700";
9814
+ const git = await assertNativeGit();
9815
+ log(`Git ${git.version}`);
9182
9816
  const workAuthConfig = parseWorkAuthConfig(config.auth ?? {});
9183
9817
  trustedProxies(config.trustedProxies ?? []);
9184
9818
  if (config.authRateLimit === false) {
@@ -9195,14 +9829,14 @@ async function createWorkServerInner(options, disposers, close) {
9195
9829
  throw new Error("Postgres deployments require the same WORK_OPERATOR_SECRET on every instance");
9196
9830
  }
9197
9831
  if (config.databaseUrl) {
9198
- fs11.rmSync(path8.join(data, "sandboxes"), { recursive: true, force: true });
9832
+ fs12.rmSync(path10.join(data, "sandboxes"), { recursive: true, force: true });
9199
9833
  }
9200
9834
  const dirs = config.databaseUrl ? ["projects", "sandboxes"] : ["db", "projects", "remotes", "app-bundles", "sandboxes"];
9201
9835
  for (const dir of dirs) {
9202
- fs11.mkdirSync(path8.join(data, dir), { recursive: true });
9836
+ fs12.mkdirSync(path10.join(data, dir), { recursive: true });
9203
9837
  }
9204
9838
  const disposable = Boolean(config.databaseUrl);
9205
- const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path8.join(data, "host-id"));
9839
+ const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path10.join(data, "host-id"));
9206
9840
  const nodeId = disposable ? `node.${randomUUID9()}` : `node.${createHash9("sha256").update(hostId).digest("hex").slice(0, 24)}`;
9207
9841
  const authSecret = loadWorkAuthSecret({
9208
9842
  dataDir: data,
@@ -9220,7 +9854,7 @@ async function createWorkServerInner(options, disposers, close) {
9220
9854
  databaseConfig = { db: ownDb };
9221
9855
  workerConcurrency = 4;
9222
9856
  } else {
9223
- const pglite = new PGlite2(path8.join(data, "db"), {
9857
+ const pglite = new PGlite2(path10.join(data, "db"), {
9224
9858
  extensions: { pgcrypto }
9225
9859
  });
9226
9860
  ownDb = withStorableParameters(new Kysely2({
@@ -9228,7 +9862,7 @@ async function createWorkServerInner(options, disposers, close) {
9228
9862
  plugins: [new WithSchemaPlugin(DEFAULT_SCHEMA)]
9229
9863
  }));
9230
9864
  disposers.push(() => ownDb.destroy());
9231
- 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);
9232
9866
  databaseConfig = { db: ownDb };
9233
9867
  }
9234
9868
  const agentsHere = config.execution.workloads.includes("agent") && !config.execution.trustControlPlaneAgents;
@@ -9259,6 +9893,7 @@ async function createWorkServerInner(options, disposers, close) {
9259
9893
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
9260
9894
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
9261
9895
  graceMs: execution.imageRetentionMs,
9896
+ runningFile: path10.join(data, RUNNING_TIME_FILE),
9262
9897
  log
9263
9898
  });
9264
9899
  disposers.push(async () => diskCare.stop());
@@ -9271,7 +9906,7 @@ async function createWorkServerInner(options, disposers, close) {
9271
9906
  if (objectStore && vaultKeys.length === 0) {
9272
9907
  throw new Error("Postgres deployments require WORK_VAULT_KEY (or the vaultKeys hook) on every instance");
9273
9908
  }
9274
- const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path8.join(data, "credentials"), vaultKeys);
9909
+ const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path10.join(data, "credentials"), vaultKeys);
9275
9910
  if (objectStore) {
9276
9911
  const key = "work/deployment-fingerprint";
9277
9912
  const fingerprint = createHash9("sha256").update(publicBase).update("\x00").update(authSecret).update("\x00").update(JSON.stringify({
@@ -9287,7 +9922,7 @@ async function createWorkServerInner(options, disposers, close) {
9287
9922
  }
9288
9923
  });
9289
9924
  const keysRecord = "work/vault-key-ids";
9290
- const known = await objectStore.get(keysRecord).then((record) => record ? z24.array(z24.string()).parse(JSON.parse(Buffer.from(record.data).toString())) : []);
9925
+ const known = await objectStore.get(keysRecord).then((record) => record ? z25.array(z25.string()).parse(JSON.parse(Buffer.from(record.data).toString())) : []);
9291
9926
  const ids = credentialVault.keyIds;
9292
9927
  if (known.length > 0 && !ids.some((id) => known.includes(id))) {
9293
9928
  throw new Error("WORK_VAULT_KEY and WORK_VAULT_PREVIOUS_KEYS share no key with this Postgres deployment");
@@ -9298,6 +9933,7 @@ async function createWorkServerInner(options, disposers, close) {
9298
9933
  }
9299
9934
  let workerConnected = () => {};
9300
9935
  let workRetired = () => {};
9936
+ let roomFreed = () => {};
9301
9937
  let machineEvent = async () => {};
9302
9938
  const workers = new WorkWorkerRegistry({
9303
9939
  db: ownDb,
@@ -9307,6 +9943,7 @@ async function createWorkServerInner(options, disposers, close) {
9307
9943
  enrollmentSecret: authSecret,
9308
9944
  connected: () => workerConnected(),
9309
9945
  retired: () => workRetired(),
9946
+ roomFreed: () => roomFreed(),
9310
9947
  event: (event) => machineEvent(event),
9311
9948
  log
9312
9949
  });
@@ -9329,7 +9966,8 @@ async function createWorkServerInner(options, disposers, close) {
9329
9966
  ownSignIns: singleServerSignIns,
9330
9967
  disk: () => diskCare.latest(),
9331
9968
  sandboxProvider,
9332
- placement: { workers: () => workers.placements() }
9969
+ placement: { workers: () => workers.placements() },
9970
+ roomFreed: () => roomFreed()
9333
9971
  });
9334
9972
  disposers.push(() => machine.stop());
9335
9973
  let maintaining;
@@ -9376,18 +10014,37 @@ async function createWorkServerInner(options, disposers, close) {
9376
10014
  memberIdForEmail: ({ email }) => verifiedUserIdForEmail({ auth: workAuth, email }),
9377
10015
  workerNode: machine.lease,
9378
10016
  caches: {
9379
- 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
+ });
9380
10036
  },
9381
10037
  clientExecution: true,
9382
10038
  database: databaseConfig,
9383
10039
  storage: objectStore ? {
9384
- projectManager: new ProjectManager(new FsBackend(path8.join(data, "projects")), new ObjectRemoteBackend({
10040
+ projectManager: new ProjectManager(new FsBackend(path10.join(data, "projects")), new ObjectRemoteBackend({
9385
10041
  store: objectStore,
9386
- keyPrefix: "origins/"
10042
+ keyPrefix: "origins/",
10043
+ cachePath: path10.join(data, "projects", ".origins")
9387
10044
  }))
9388
10045
  } : {
9389
- projectsPath: path8.join(data, "projects"),
9390
- remotesPath: path8.join(data, "remotes")
10046
+ projectsPath: path10.join(data, "projects"),
10047
+ remotesPath: path10.join(data, "remotes")
9391
10048
  },
9392
10049
  sandboxProvider,
9393
10050
  environmentProvider,
@@ -9407,13 +10064,14 @@ async function createWorkServerInner(options, disposers, close) {
9407
10064
  ...hooks.machines ? { placementWaitMinutes: config.machineWaitMinutes ?? 30 } : {},
9408
10065
  gatewayUrl: () => `${publicBase}/api/gateway`,
9409
10066
  ...agents.registry ? { codingAgent: agents.registry } : {},
9410
- appBundleStore: objectStore ?? new FsBundleStore(path8.join(data, "app-bundles")),
9411
- documentBlobStore: objectStore ?? new FsBundleStore(path8.join(data, "document-blobs")),
10067
+ appBundleStore: objectStore ?? new FsBundleStore(path10.join(data, "app-bundles")),
10068
+ documentBlobStore: objectStore ?? new FsBundleStore(path10.join(data, "document-blobs")),
9412
10069
  triggerKinds: [
9413
10070
  aiToolCall,
9414
10071
  schedule,
9415
10072
  webhook,
9416
10073
  ...SESSION_TRIGGER_KINDS,
10074
+ ...PROJECT_TRIGGER_KINDS,
9417
10075
  ...DIRECTORY_TRIGGER_KINDS,
9418
10076
  ...MACHINE_TRIGGER_KINDS
9419
10077
  ],
@@ -9473,6 +10131,7 @@ async function createWorkServerInner(options, disposers, close) {
9473
10131
  const core = catamorphic.core;
9474
10132
  workerConnected = () => core.wakeups.notify("agent");
9475
10133
  workRetired = () => core.wakeups.notify("agent");
10134
+ roomFreed = () => core.wakeups.notify("capacity");
9476
10135
  {
9477
10136
  const recover = (nodeIds) => core.nodeRecovery.recoverLostNodes({
9478
10137
  authorityId: hostId,
@@ -9541,7 +10200,7 @@ async function createWorkServerInner(options, disposers, close) {
9541
10200
  publicBase
9542
10201
  });
9543
10202
  machineEvent = async (event) => {
9544
- const projects = new Set((event.machine.for ?? []).flatMap((principal) => ("project" in principal) ? [principal.project] : []));
10203
+ const projects = machineEventProjects(event.machine);
9545
10204
  const record = machineProjectEvent({
9546
10205
  kind: event.kind,
9547
10206
  at: event.at,
@@ -9580,6 +10239,7 @@ async function createWorkServerInner(options, disposers, close) {
9580
10239
  roles: rolesOf.get(user.id) ?? {}
9581
10240
  })).sort((left, right) => left.id.localeCompare(right.id));
9582
10241
  };
10242
+ const machineSessions = core.agentSessions;
9583
10243
  const workMachines = hooks.machines ? new WorkMachines({
9584
10244
  db: core.db,
9585
10245
  tenantId: SERVER_TENANT_ID,
@@ -9591,6 +10251,30 @@ async function createWorkServerInner(options, disposers, close) {
9591
10251
  workers,
9592
10252
  controlPlaneUrl: publicBase,
9593
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
+ },
9594
10278
  event: async (event) => {
9595
10279
  await machineEvent(event).catch((error) => log(`Recording ${event.kind} for machine ${event.machine.name} failed: ${error instanceof Error ? error.message : String(error)}`));
9596
10280
  }
@@ -9601,18 +10285,16 @@ async function createWorkServerInner(options, disposers, close) {
9601
10285
  if (workMachines) {
9602
10286
  const machineTimer = setInterval(planMachines, 60000);
9603
10287
  machineTimer.unref();
9604
- let checking;
9605
- const checkTimer = setInterval(() => {
9606
- checking ??= workMachines.check().catch((error) => log(`Machine check failed: ${error instanceof Error ? error.message : String(error)}`)).finally(() => {
9607
- checking = undefined;
9608
- });
9609
- }, 1e4);
9610
- checkTimer.unref();
10288
+ const watching = new AbortController;
10289
+ const watched = workMachines.watch({
10290
+ signal: watching.signal,
10291
+ wakeups: core.wakeups
10292
+ });
9611
10293
  planMachines();
9612
10294
  disposers.push(async () => {
9613
10295
  clearInterval(machineTimer);
9614
- clearInterval(checkTimer);
9615
- await checking;
10296
+ watching.abort();
10297
+ await watched;
9616
10298
  await workMachines.settle();
9617
10299
  });
9618
10300
  }
@@ -9758,6 +10440,8 @@ async function createWorkServerInner(options, disposers, close) {
9758
10440
  done(null, payload);
9759
10441
  });
9760
10442
  registerWorkerRoutes(app, workers);
10443
+ if (core.cacheArchives)
10444
+ registerCacheArchiveRoutes(app, core.cacheArchives);
9761
10445
  const machineManagement = {
9762
10446
  nodes: machine.nodes,
9763
10447
  workers,
@@ -9806,7 +10490,8 @@ async function createWorkServerInner(options, disposers, close) {
9806
10490
  signInRoot: execution.signInRoot,
9807
10491
  dataDir: data,
9808
10492
  env: { ...process.env, PATH: config.execution.path },
9809
- onChange: () => machine.refreshSignIns()
10493
+ onChange: () => machine.refreshSignIns(),
10494
+ provider: sandboxProvider
9810
10495
  }) : undefined;
9811
10496
  if (ownSignIns)
9812
10497
  disposers.push(async () => ownSignIns.stop());
@@ -9817,7 +10502,9 @@ async function createWorkServerInner(options, disposers, close) {
9817
10502
  nodes: () => memberNodes.list({ tenantId: SERVER_TENANT_ID, authorityId: hostId }),
9818
10503
  machines: async () => (await workers.machines.records()).map((record) => record.facts),
9819
10504
  ...ownSignIns ? { ownMachine: { nodeId: machine.lease.id, signIns: ownSignIns } } : {},
9820
- worker: (args) => workers.harnessSignIn(args)
10505
+ worker: (args) => workers.harnessSignIn(args),
10506
+ environments: core.executionEnvironments,
10507
+ signIns: workers.machines.signIns
9821
10508
  })
9822
10509
  });
9823
10510
  registerWorkAdmissionRoutes(app, {
@@ -9965,7 +10652,7 @@ async function createWorkServerInner(options, disposers, close) {
9965
10652
  return reply.status(400).send({ error: message });
9966
10653
  }
9967
10654
  });
9968
- const pwaDist = config.pwaDist ?? path8.resolve(import.meta.dirname, "../../../apps/pwa/dist");
10655
+ const pwaDist = config.pwaDist ?? path10.resolve(import.meta.dirname, "../../../apps/pwa/dist");
9969
10656
  serveSpaDist(app, () => pwaDist, (reply) => reply.type("text/html").send(LANDING_PAGE));
9970
10657
  await hooks.routes?.({ app, catamorphic });
9971
10658
  log(`agents: ${agents.description}`);
@@ -9981,7 +10668,7 @@ async function createWorkServerInner(options, disposers, close) {
9981
10668
  };
9982
10669
  }
9983
10670
  async function stopMemberWork(args) {
9984
- 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();
9985
10672
  for (const session of running) {
9986
10673
  try {
9987
10674
  await args.core.agentSessions?.interrupt(args.identity, session.project_id, session.id);
@@ -9992,12 +10679,12 @@ async function stopMemberWork(args) {
9992
10679
  }
9993
10680
  function loadOrCreateHostId(file) {
9994
10681
  try {
9995
- const existing = fs11.readFileSync(file, "utf8").trim();
10682
+ const existing = fs12.readFileSync(file, "utf8").trim();
9996
10683
  if (existing)
9997
10684
  return existing;
9998
10685
  } catch {}
9999
10686
  const hostId = `server:${randomUUID9()}`;
10000
- fs11.writeFileSync(file, `${hostId}
10687
+ fs12.writeFileSync(file, `${hostId}
10001
10688
  `, { mode: 384 });
10002
10689
  return hostId;
10003
10690
  }
@@ -10019,13 +10706,14 @@ function isLoopbackBase(base) {
10019
10706
  }
10020
10707
  // src/workers/worker-runtime.ts
10021
10708
  import { createPrivateKey, randomBytes as randomBytes10 } from "node:crypto";
10022
- import fs13 from "node:fs";
10023
- import path10 from "node:path";
10709
+ import fs14 from "node:fs";
10710
+ import path12 from "node:path";
10024
10711
  import { nodeExecutor as nodeExecutor2, RETIRED_KEY_RETENTION_MS } from "@catamorphic/core";
10025
10712
  import {
10026
10713
  executorPublicKey,
10027
10714
  generateExecutorKeyPair,
10028
- MACHINE_CAPABILITIES as MACHINE_CAPABILITIES7
10715
+ MACHINE_CAPABILITIES as MACHINE_CAPABILITIES7,
10716
+ offeredCapabilities
10029
10717
  } from "@catamorphic/sandbox";
10030
10718
  import {
10031
10719
  ReceiptRefusedError,
@@ -10035,35 +10723,35 @@ import {
10035
10723
  } from "@catamorphic/server-sdk";
10036
10724
 
10037
10725
  // src/workers/worker-identity.ts
10038
- import fs12 from "node:fs";
10039
- import path9 from "node:path";
10040
- import { z as z25 } from "zod";
10726
+ import fs13 from "node:fs";
10727
+ import path11 from "node:path";
10728
+ import { z as z26 } from "zod";
10041
10729
  var CREDENTIAL_FILE = "worker-credential";
10042
10730
  var KEY_FILE = "worker-key";
10043
10731
  var PREVIOUS_FILE = "worker-identity.previous";
10044
10732
  var NEXT_FILE = "worker-identity.next";
10045
- var PairSchema = z25.strictObject({
10046
- credential: z25.string().min(1),
10047
- privateKey: z25.string().min(1)
10733
+ var PairSchema = z26.strictObject({
10734
+ credential: z26.string().min(1),
10735
+ privateKey: z26.string().min(1)
10048
10736
  });
10049
10737
  var NextIdentitySchema = PairSchema.extend({
10050
10738
  previous: PairSchema.optional()
10051
10739
  });
10052
10740
  function loadWorkerIdentity(dataDir) {
10053
- const next = readIfPresent(path9.join(dataDir, NEXT_FILE));
10741
+ const next = readIfPresent(path11.join(dataDir, NEXT_FILE));
10054
10742
  if (next !== undefined) {
10055
10743
  const parsed = NextIdentitySchema.safeParse(parseJson(next));
10056
10744
  if (parsed.success)
10057
10745
  install(dataDir, parsed.data);
10058
- fs12.rmSync(path9.join(dataDir, NEXT_FILE), { force: true });
10746
+ fs13.rmSync(path11.join(dataDir, NEXT_FILE), { force: true });
10059
10747
  }
10060
- const credential = readIfPresent(path9.join(dataDir, CREDENTIAL_FILE))?.trim();
10748
+ const credential = readIfPresent(path11.join(dataDir, CREDENTIAL_FILE))?.trim();
10061
10749
  if (!credential)
10062
10750
  return;
10063
- const privateKey = readIfPresent(path9.join(dataDir, KEY_FILE));
10751
+ const privateKey = readIfPresent(path11.join(dataDir, KEY_FILE));
10064
10752
  if (!privateKey)
10065
10753
  return { credential };
10066
- const previous = PairSchema.safeParse(parseJson(readIfPresent(path9.join(dataDir, PREVIOUS_FILE)) ?? ""));
10754
+ const previous = PairSchema.safeParse(parseJson(readIfPresent(path11.join(dataDir, PREVIOUS_FILE)) ?? ""));
10067
10755
  return {
10068
10756
  credential,
10069
10757
  privateKey,
@@ -10071,53 +10759,53 @@ function loadWorkerIdentity(dataDir) {
10071
10759
  };
10072
10760
  }
10073
10761
  function saveWorkerIdentity(dataDir, identity) {
10074
- writeAtomically(path9.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10762
+ writeAtomically(path11.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10075
10763
  install(dataDir, identity);
10076
- fs12.rmSync(path9.join(dataDir, NEXT_FILE), { force: true });
10764
+ fs13.rmSync(path11.join(dataDir, NEXT_FILE), { force: true });
10077
10765
  syncDirectory(dataDir);
10078
10766
  }
10079
10767
  function confirmWorkerIdentity(dataDir) {
10080
- fs12.rmSync(path9.join(dataDir, PREVIOUS_FILE), { force: true });
10768
+ fs13.rmSync(path11.join(dataDir, PREVIOUS_FILE), { force: true });
10081
10769
  syncDirectory(dataDir);
10082
10770
  }
10083
10771
  function saveWorkerKey(dataDir, privateKey) {
10084
- writeAtomically(path9.join(dataDir, KEY_FILE), privateKey);
10772
+ writeAtomically(path11.join(dataDir, KEY_FILE), privateKey);
10085
10773
  }
10086
10774
  function install(dataDir, identity) {
10087
10775
  if (identity.previous)
10088
- writeAtomically(path9.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10776
+ writeAtomically(path11.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10089
10777
  else
10090
- fs12.rmSync(path9.join(dataDir, PREVIOUS_FILE), { force: true });
10091
- writeAtomically(path9.join(dataDir, KEY_FILE), identity.privateKey);
10092
- writeAtomically(path9.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}
10093
10781
  `);
10094
10782
  }
10095
10783
  function writeAtomically(file, content) {
10096
10784
  const temporary = `${file}.tmp`;
10097
- const handle = fs12.openSync(temporary, "w", 384);
10785
+ const handle = fs13.openSync(temporary, "w", 384);
10098
10786
  try {
10099
- fs12.writeSync(handle, content);
10100
- fs12.fsyncSync(handle);
10787
+ fs13.writeSync(handle, content);
10788
+ fs13.fsyncSync(handle);
10101
10789
  } finally {
10102
- fs12.closeSync(handle);
10790
+ fs13.closeSync(handle);
10103
10791
  }
10104
- fs12.chmodSync(temporary, 384);
10105
- fs12.renameSync(temporary, file);
10106
- syncDirectory(path9.dirname(file));
10792
+ fs13.chmodSync(temporary, 384);
10793
+ fs13.renameSync(temporary, file);
10794
+ syncDirectory(path11.dirname(file));
10107
10795
  }
10108
10796
  function syncDirectory(dir) {
10109
10797
  try {
10110
- const handle = fs12.openSync(dir, "r");
10798
+ const handle = fs13.openSync(dir, "r");
10111
10799
  try {
10112
- fs12.fsyncSync(handle);
10800
+ fs13.fsyncSync(handle);
10113
10801
  } finally {
10114
- fs12.closeSync(handle);
10802
+ fs13.closeSync(handle);
10115
10803
  }
10116
10804
  } catch {}
10117
10805
  }
10118
10806
  function readIfPresent(file) {
10119
10807
  try {
10120
- return fs12.readFileSync(file, "utf8");
10808
+ return fs13.readFileSync(file, "utf8");
10121
10809
  } catch (error) {
10122
10810
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
10123
10811
  return;
@@ -10157,7 +10845,7 @@ async function startWorkWorker(options) {
10157
10845
  }
10158
10846
  });
10159
10847
  const log = options.log ?? (() => {});
10160
- fs13.mkdirSync(options.dataDir, { recursive: true, mode: 448 });
10848
+ fs14.mkdirSync(options.dataDir, { recursive: true, mode: 448 });
10161
10849
  const enrolled = await loadOrEnroll({
10162
10850
  base,
10163
10851
  dataDir: options.dataDir,
@@ -10224,6 +10912,7 @@ async function startWorkWorker(options) {
10224
10912
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
10225
10913
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
10226
10914
  graceMs: execution.imageRetentionMs,
10915
+ runningFile: path12.join(options.dataDir, RUNNING_TIME_FILE),
10227
10916
  log
10228
10917
  });
10229
10918
  await diskCare.measure();
@@ -10236,7 +10925,7 @@ async function startWorkWorker(options) {
10236
10925
  workspaceRoot: provider.workspaceRoot ?? "/workspace",
10237
10926
  processes: Boolean(provider.processes),
10238
10927
  capabilities: [
10239
- ...provider.capabilities ?? [],
10928
+ ...offeredCapabilities(provider.capabilities),
10240
10929
  ...execution.machineCapabilities,
10241
10930
  ...disk ? [MACHINE_CAPABILITIES7.disk] : [],
10242
10931
  ...signInCapabilities(execution.signInRoot)
@@ -10301,14 +10990,16 @@ async function startWorkWorker(options) {
10301
10990
  throw new Error(reason);
10302
10991
  throw new RunnerSessionEndedError(reason);
10303
10992
  };
10304
- const sandboxes = new PersistedSandboxes(path10.join(options.dataDir, "sandboxes.json"));
10993
+ const sandboxes = new PersistedSandboxes(path12.join(options.dataDir, "sandboxes.json"));
10305
10994
  const offerSignIns = { now: () => {} };
10306
10995
  const harnessSignIns = new HarnessSignIns({
10307
10996
  signInRoot: execution.signInRoot,
10308
10997
  dataDir: options.dataDir,
10309
10998
  env: { ...process.env, PATH: options.execution.path },
10310
- onChange: () => offerSignIns.now()
10999
+ onChange: () => offerSignIns.now(),
11000
+ provider
10311
11001
  });
11002
+ harnessSignIns.recover();
10312
11003
  const resets = { last: Promise.resolve() };
10313
11004
  const reset = () => {
10314
11005
  const next = resets.last.catch(() => {
@@ -10632,7 +11323,7 @@ class PersistedSandboxes extends Set {
10632
11323
  super();
10633
11324
  this.file = file;
10634
11325
  try {
10635
- const stored = JSON.parse(fs13.readFileSync(file, "utf8"));
11326
+ const stored = JSON.parse(fs14.readFileSync(file, "utf8"));
10636
11327
  if (Array.isArray(stored)) {
10637
11328
  for (const id of stored)
10638
11329
  if (typeof id === "string")
@@ -10655,7 +11346,7 @@ class PersistedSandboxes extends Set {
10655
11346
  save() {
10656
11347
  if (!this.ready)
10657
11348
  return;
10658
- fs13.writeFileSync(this.file, JSON.stringify([...this]), { mode: 384 });
11349
+ fs14.writeFileSync(this.file, JSON.stringify([...this]), { mode: 384 });
10659
11350
  }
10660
11351
  }
10661
11352
  export {
@@ -10668,7 +11359,7 @@ export {
10668
11359
  MACHINE_EVENT_KINDS2 as MACHINE_EVENT_KINDS,
10669
11360
  MachineHeldError,
10670
11361
  SERVER_TENANT_ID,
10671
- SIGN_IN_HARNESSES3 as SIGN_IN_HARNESSES,
11362
+ SIGN_IN_HARNESSES5 as SIGN_IN_HARNESSES,
10672
11363
  SIGN_IN_SPECS3 as SIGN_IN_SPECS,
10673
11364
  WORKER_PROTOCOL,
10674
11365
  WORKER_PROTOCOL_HEADER,
@@ -10681,18 +11372,21 @@ export {
10681
11372
  defineModelConnectionProvider2 as defineModelConnectionProvider,
10682
11373
  definePostgresConnectionProvider2 as definePostgresConnectionProvider,
10683
11374
  executionSettingsFromEnv,
11375
+ handedOffKey2 as handedOffKey,
10684
11376
  isSecurePublicUrl,
10685
11377
  lanAddresses,
10686
11378
  listMachineSignIns,
11379
+ preparedFor2 as preparedFor,
10687
11380
  resolveExecutionSettings,
10688
11381
  signInHarness3 as signInHarness,
10689
11382
  signInOnMachine,
10690
11383
  signInRoot,
10691
11384
  signOutOnMachine,
11385
+ spareProject2 as spareProject,
10692
11386
  startMdnsResponder,
10693
11387
  startWorkWorker,
10694
11388
  workServerConfigFromEnv
10695
11389
  };
10696
11390
 
10697
- //# debugId=0E6681C1FDBFFAD764756E2164756E21
11391
+ //# debugId=A38F901DCE76FE4764756E2164756E21
10698
11392
  //# sourceMappingURL=index.js.map