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

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.
package/dist/index.js CHANGED
@@ -1411,8 +1411,8 @@ function startMdnsResponder(hostname, log = () => {}) {
1411
1411
  }
1412
1412
  // src/server.ts
1413
1413
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
1414
- import fs11 from "node:fs";
1415
- import path8 from "node:path";
1414
+ import fs12 from "node:fs";
1415
+ import path9 from "node:path";
1416
1416
  import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
1417
1417
  import {
1418
1418
  FULL_TOKEN_SCOPE as FULL_TOKEN_SCOPE3,
@@ -1451,6 +1451,7 @@ import {
1451
1451
  machineProjectEvent,
1452
1452
  ObjectRemoteBackend,
1453
1453
  PostgresObjectStore,
1454
+ PROJECT_TRIGGER_KINDS,
1454
1455
  ProjectManager,
1455
1456
  SESSION_TRIGGER_KINDS,
1456
1457
  schedule,
@@ -1462,7 +1463,7 @@ import { PGlite as PGlite2 } from "@electric-sql/pglite";
1462
1463
  import { pgcrypto } from "@electric-sql/pglite/contrib/pgcrypto";
1463
1464
  import Fastify from "fastify";
1464
1465
  import { Kysely as Kysely2, PGliteDialect as PGliteDialect2, sql as sql8, WithSchemaPlugin } from "kysely";
1465
- import { z as z24 } from "zod";
1466
+ import { z as z25 } from "zod";
1466
1467
 
1467
1468
  // src/admission/admission-service.ts
1468
1469
  import {
@@ -2118,6 +2119,7 @@ import { createAnthropic } from "@ai-sdk/anthropic";
2118
2119
  import { createOpenAI } from "@ai-sdk/openai";
2119
2120
  import { createAiSdkAdapter } from "@catamorphic/ai-sdk";
2120
2121
  import {
2122
+ acpToolTimeoutMs,
2121
2123
  normalizeConnectionRequirement
2122
2124
  } from "@catamorphic/core";
2123
2125
  import {
@@ -2532,6 +2534,7 @@ function sandboxProjectAgent(input) {
2532
2534
  const common = {
2533
2535
  id: input.id,
2534
2536
  ...harness,
2537
+ ...definition.kind === "acp" ? { toolTimeoutMs: acpToolTimeoutMs(definition.acp) } : {},
2535
2538
  topology: "controller",
2536
2539
  sandboxing: definition.sandboxing ?? "propose",
2537
2540
  environment: definition.environment,
@@ -4105,6 +4108,7 @@ import { z as z10 } from "zod";
4105
4108
  import { createHash as createHash3, createHmac, randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
4106
4109
  import {
4107
4110
  isProjectPrincipal,
4111
+ PLACEMENT_FREE_JOB_KINDS,
4108
4112
  PLACEMENT_WAIT_FRESH_SECONDS
4109
4113
  } from "@catamorphic/core";
4110
4114
  import { parseSignInCapability } from "@catamorphic/sandbox";
@@ -4624,7 +4628,7 @@ function waitFresh() {
4624
4628
  }
4625
4629
  function queuedPlacementWait(db) {
4626
4630
  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()`);
4631
+ const jobs = db.selectFrom("workflow_runs as root").innerJoin("workflow_runs as run", "run.allocation_id", "root.allocation_id").innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id").select("job.id").where("root.id", "=", sql3`placement_waits.root_workload_id`).where("root.status", "in", ["pending", "running", "waiting"]).where("run.status", "in", ["pending", "running", "waiting"]).where("job.status", "=", "pending").where("job.kind", "not in", [...PLACEMENT_FREE_JOB_KINDS]).where("job.available_at", "<=", sql3`now()`);
4628
4632
  const fills = db.selectFrom("environment_cache_fills").select("id").where("id", "=", sql3`placement_waits.root_workload_id`).where("status", "=", "queued");
4629
4633
  return sql3`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
4630
4634
  (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})) OR
@@ -6483,6 +6487,7 @@ function registerAdministratorRoutes(app, options) {
6483
6487
  import { randomUUID as randomUUID7 } from "node:crypto";
6484
6488
  import {
6485
6489
  PlacementWaitsService as PlacementWaitsService2,
6490
+ PollPacer,
6486
6491
  releaseReplicaClaim as releaseReplicaClaim2,
6487
6492
  renewReplicaClaim as renewReplicaClaim2,
6488
6493
  takeReplicaClaim as takeReplicaClaim3
@@ -6490,6 +6495,8 @@ import {
6490
6495
  import { getTracer as getTracer2, withSpan as withSpan2 } from "@catamorphic/otel";
6491
6496
  var tracer2 = getTracer2("@catamorphic/work-server");
6492
6497
  var RESET_WAIT_MS = 3 * 60000;
6498
+ var MACHINE_CHECK_INTERVAL_MS = 1e4;
6499
+ var MACHINE_CHECK_QUICK_MS = 500;
6493
6500
  function workMachineWorld(deps) {
6494
6501
  const { workers } = deps;
6495
6502
  const machines = workers.machines;
@@ -6564,6 +6571,21 @@ class WorkMachines {
6564
6571
  return;
6565
6572
  this.passSoon();
6566
6573
  }
6574
+ async watch(args) {
6575
+ const pacer = new PollPacer({
6576
+ quickMs: args.quickMs ?? MACHINE_CHECK_QUICK_MS,
6577
+ idleMs: args.intervalMs ?? MACHINE_CHECK_INTERVAL_MS,
6578
+ signal: args.signal,
6579
+ wakeups: args.wakeups,
6580
+ topic: "placement"
6581
+ });
6582
+ while (!args.signal.aborted) {
6583
+ await pacer.wait();
6584
+ if (args.signal.aborted)
6585
+ return;
6586
+ await this.check().catch((error) => this.deps.log?.(`Machine check failed: ${message(error)}`));
6587
+ }
6588
+ }
6567
6589
  get leaseMs() {
6568
6590
  return this.deps.leaseMs ?? 120000;
6569
6591
  }
@@ -8248,16 +8270,96 @@ function shareTools(shares, args) {
8248
8270
  }
8249
8271
 
8250
8272
  // src/workers/disk-care.ts
8273
+ import fs10 from "node:fs";
8274
+ import path8 from "node:path";
8251
8275
  import {
8252
8276
  describeDisk as describeDisk3,
8253
8277
  diskLow,
8254
8278
  measureDisk
8255
8279
  } from "@catamorphic/sandbox";
8280
+ import { z as z20 } from "zod";
8256
8281
  var DISK_MEASURE_INTERVAL_MS = 30000;
8257
8282
  var DISK_CLEAN_INTERVAL_MS = 60 * 60000;
8258
8283
  var DISK_LOW_CLEAN_INTERVAL_MS = 10 * 60000;
8284
+ var DISK_AWAY_AFTER_MS = 5 * 60000;
8285
+ var RUNNING_TIME_FILE = "running-time.json";
8286
+ function reachOfRunningTime(args) {
8287
+ let left = args.ranMs;
8288
+ let cursor = args.now;
8289
+ for (const stretch of [...args.away].sort((a, b) => b.to - a.to)) {
8290
+ const to = Math.min(stretch.to, cursor);
8291
+ if (stretch.from >= to)
8292
+ continue;
8293
+ const ran = cursor - to;
8294
+ if (ran >= left)
8295
+ break;
8296
+ left -= ran;
8297
+ cursor = stretch.from;
8298
+ }
8299
+ return args.now - (cursor - left);
8300
+ }
8301
+ var RunningNotes = z20.object({
8302
+ seenAt: z20.number(),
8303
+ away: z20.array(z20.tuple([z20.number(), z20.number()]))
8304
+ });
8305
+
8306
+ class RunningTime {
8307
+ args;
8308
+ seenAt;
8309
+ away = [];
8310
+ failed = false;
8311
+ constructor(args) {
8312
+ this.args = args;
8313
+ const notes = RunningNotes.safeParse(read(args.file)).data;
8314
+ if (!notes)
8315
+ return;
8316
+ this.seenAt = notes.seenAt;
8317
+ this.away = notes.away.map(([from, to]) => ({ from, to }));
8318
+ }
8319
+ note() {
8320
+ const now = this.args.now();
8321
+ if (this.seenAt !== undefined && now - this.seenAt > this.args.awayAfterMs)
8322
+ this.away.push({ from: this.seenAt, to: now });
8323
+ this.seenAt = now;
8324
+ const reach = reachOfRunningTime({
8325
+ ranMs: this.args.keepMs,
8326
+ now,
8327
+ away: this.away
8328
+ });
8329
+ this.away = this.away.filter((stretch) => stretch.to > now - reach && stretch.from < now);
8330
+ try {
8331
+ fs10.mkdirSync(path8.dirname(this.args.file), { recursive: true });
8332
+ const temporary = `${this.args.file}.${process.pid}.tmp`;
8333
+ fs10.writeFileSync(temporary, JSON.stringify({
8334
+ seenAt: this.seenAt,
8335
+ away: this.away.map((stretch) => [stretch.from, stretch.to])
8336
+ }), { mode: 384 });
8337
+ fs10.renameSync(temporary, this.args.file);
8338
+ this.failed = false;
8339
+ } catch (error) {
8340
+ if (!this.failed)
8341
+ this.args.log?.(`Could not note that this machine is running: ${error instanceof Error ? error.message : String(error)}`);
8342
+ this.failed = true;
8343
+ }
8344
+ return reach;
8345
+ }
8346
+ }
8347
+ function read(file) {
8348
+ try {
8349
+ return JSON.parse(fs10.readFileSync(file, "utf8"));
8350
+ } catch {
8351
+ return;
8352
+ }
8353
+ }
8259
8354
  function startDiskCare(args) {
8260
8355
  const measure = args.measureDisk ?? measureDisk;
8356
+ const running = args.runningFile && args.provider.disk?.clean ? new RunningTime({
8357
+ file: args.runningFile,
8358
+ keepMs: args.graceMs,
8359
+ awayAfterMs: args.awayAfterMs ?? DISK_AWAY_AFTER_MS,
8360
+ now: args.now ?? Date.now,
8361
+ ...args.log ? { log: args.log } : {}
8362
+ }) : undefined;
8261
8363
  let latest;
8262
8364
  let wasLow = false;
8263
8365
  let stopped = false;
@@ -8268,7 +8370,7 @@ function startDiskCare(args) {
8268
8370
  if (!run || cleaning || stopped)
8269
8371
  return;
8270
8372
  lastClean = Date.now();
8271
- cleaning = run({ graceMs: args.graceMs }).then((lines) => {
8373
+ cleaning = run({ graceMs: running?.note() ?? args.graceMs }).then((lines) => {
8272
8374
  for (const line of lines)
8273
8375
  args.log?.(line);
8274
8376
  }).catch((error) => args.log?.(`Removing what Work left on this machine failed: ${error instanceof Error ? error.message : String(error)}`)).finally(() => {
@@ -8302,8 +8404,12 @@ function startDiskCare(args) {
8302
8404
  });
8303
8405
  return measuring;
8304
8406
  };
8407
+ running?.note();
8305
8408
  measureNow();
8306
- const timer = setInterval(() => void measureNow(), args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS);
8409
+ const timer = setInterval(() => {
8410
+ running?.note();
8411
+ measureNow();
8412
+ }, args.measureEveryMs ?? DISK_MEASURE_INTERVAL_MS);
8307
8413
  timer.unref();
8308
8414
  return {
8309
8415
  latest: () => latest,
@@ -8318,28 +8424,28 @@ function startDiskCare(args) {
8318
8424
  // src/workers/harness-sign-ins.ts
8319
8425
  import { spawn } from "node:child_process";
8320
8426
  import { randomUUID as randomUUID8 } from "node:crypto";
8321
- import fs10 from "node:fs";
8427
+ import fs11 from "node:fs";
8322
8428
  import {
8323
8429
  SIGN_IN_SPECS as SIGN_IN_SPECS2
8324
8430
  } from "@catamorphic/sandbox";
8325
- import { z as z20 } from "zod";
8431
+ import { z as z21 } from "zod";
8326
8432
  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()
8433
+ var HarnessSignInStartedSchema = z21.strictObject({
8434
+ attempt: z21.string().uuid(),
8435
+ verificationUrl: z21.string().url().max(8192),
8436
+ userCode: z21.string().min(1).max(32).optional(),
8437
+ expects: z21.literal("code").optional(),
8438
+ expiresAt: z21.string().datetime()
8333
8439
  });
8334
- var HarnessSignInStatusSchema = z20.strictObject({
8335
- state: z20.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
8336
- message: z20.string().max(400).optional()
8440
+ var HarnessSignInStatusSchema = z21.strictObject({
8441
+ state: z21.enum(["waiting", "signed-in", "failed", "expired", "cancelled"]),
8442
+ message: z21.string().max(400).optional()
8337
8443
  });
8338
- var HarnessSignedOutSchema = z20.strictObject({
8339
- signedOut: z20.boolean()
8444
+ var HarnessSignedOutSchema = z21.strictObject({
8445
+ signedOut: z21.boolean()
8340
8446
  });
8341
- var HarnessSignInRefusedSchema = z20.strictObject({
8342
- refused: z20.string().min(1).max(400)
8447
+ var HarnessSignInRefusedSchema = z21.strictObject({
8448
+ refused: z21.string().min(1).max(400)
8343
8449
  });
8344
8450
  var CODE_TIMEOUT_MS = 30000;
8345
8451
  var DEFAULT_CODE_MINUTES = 15;
@@ -8488,7 +8594,7 @@ class HarnessSignIns {
8488
8594
  settled = true;
8489
8595
  clearTimeout(timer);
8490
8596
  child.kill("SIGTERM");
8491
- fs10.rmSync(staging, { recursive: true, force: true });
8597
+ fs11.rmSync(staging, { recursive: true, force: true });
8492
8598
  reject(new HarnessSignInRefusedError(message));
8493
8599
  };
8494
8600
  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);
@@ -8624,7 +8730,7 @@ class HarnessSignIns {
8624
8730
  if (attempt.child.exitCode === null)
8625
8731
  attempt.child.kill("SIGTERM");
8626
8732
  if (state !== "signed-in")
8627
- fs10.rmSync(attempt.staging, { recursive: true, force: true });
8733
+ fs11.rmSync(attempt.staging, { recursive: true, force: true });
8628
8734
  }
8629
8735
  prune() {
8630
8736
  const now = this.now();
@@ -8640,7 +8746,7 @@ class HarnessSignIns {
8640
8746
  // src/workers/member-machine-routes.ts
8641
8747
  import { ExecutorNotConnectedError } from "@catamorphic/core";
8642
8748
  import { signInHarness as signInHarness2 } from "@catamorphic/sandbox";
8643
- import { z as z22 } from "zod";
8749
+ import { z as z23 } from "zod";
8644
8750
 
8645
8751
  // src/workers/member-machines.ts
8646
8752
  import {
@@ -8649,7 +8755,7 @@ import {
8649
8755
  parseSignInCapability as parseSignInCapability2,
8650
8756
  signInCapability as signInCapability2
8651
8757
  } from "@catamorphic/sandbox";
8652
- import { z as z21 } from "zod";
8758
+ import { z as z22 } from "zod";
8653
8759
  class NotYourMachineError extends Error {
8654
8760
  constructor() {
8655
8761
  super("This is not a machine of your own, so your sign-in cannot go on it");
@@ -8679,7 +8785,7 @@ class MemberMachines {
8679
8785
  });
8680
8786
  }
8681
8787
  async begin(args) {
8682
- const answer = z21.union([HarnessSignInStartedSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8788
+ const answer = z22.union([HarnessSignInStartedSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8683
8789
  action: "begin",
8684
8790
  harness: args.harness,
8685
8791
  member: args.identity.externalUserId
@@ -8697,7 +8803,7 @@ class MemberMachines {
8697
8803
  })));
8698
8804
  }
8699
8805
  async input(args) {
8700
- const answer = z21.union([HarnessSignInStatusSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8806
+ const answer = z22.union([HarnessSignInStatusSchema, HarnessSignInRefusedSchema]).parse(await this.send(args, {
8701
8807
  action: "input",
8702
8808
  harness: args.harness,
8703
8809
  member: args.identity.externalUserId,
@@ -8771,13 +8877,13 @@ function signInStates(state) {
8771
8877
 
8772
8878
  // src/workers/member-machine-routes.ts
8773
8879
  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)
8880
+ const harnessParams = z23.object({
8881
+ id: z23.string().min(1).max(200),
8882
+ harness: z23.string().min(1).max(40)
8777
8883
  });
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)
8884
+ const attemptParams = harnessParams.extend({ attempt: z23.string().uuid() });
8885
+ const inputBody = z23.strictObject({
8886
+ text: z23.string().min(1).max(SIGN_IN_INPUT_MAX)
8781
8887
  });
8782
8888
  const member = async (request, reply) => {
8783
8889
  const identity = await options.caller(request);
@@ -8948,7 +9054,7 @@ import {
8948
9054
  RemoteReceiptRefusedError
8949
9055
  } from "@catamorphic/core";
8950
9056
  import { ExecutorPublicKeySchema as ExecutorPublicKeySchema2 } from "@catamorphic/sandbox";
8951
- import { z as z23 } from "zod";
9057
+ import { z as z24 } from "zod";
8952
9058
 
8953
9059
  // src/workers/worker-protocol.ts
8954
9060
  var WORKER_PROTOCOL_HEADER = "work-protocol";
@@ -8974,17 +9080,17 @@ function upgradeMessage(input) {
8974
9080
  }
8975
9081
 
8976
9082
  // src/workers/worker-routes.ts
8977
- var Session = z23.strictObject({ session: z23.string().uuid() });
9083
+ var Session = z24.strictObject({ session: z24.string().uuid() });
8978
9084
  var Renewal = Session.extend({ disk: MachineDiskSchema2.optional() });
8979
9085
  var Poll = Session.extend({
8980
- pollId: z23.string().uuid(),
8981
- max: z23.number().int().min(1).max(64).default(1)
9086
+ pollId: z24.string().uuid(),
9087
+ max: z24.number().int().min(1).max(64).default(1)
8982
9088
  });
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()
9089
+ var Completion = z24.strictObject({
9090
+ session: z24.string().uuid(),
9091
+ jobId: z24.string().uuid(),
9092
+ response: z24.unknown().optional(),
9093
+ error: z24.string().max(1e4).optional()
8988
9094
  });
8989
9095
  function registerWorkerRoutes(app, registry) {
8990
9096
  const authenticated = async (request, reply) => {
@@ -9001,8 +9107,8 @@ function registerWorkerRoutes(app, registry) {
9001
9107
  app.post("/api/workers/enroll", async (request, reply) => {
9002
9108
  if (await refusedProtocol(request, reply))
9003
9109
  return reply;
9004
- const body = z23.strictObject({
9005
- code: z23.string().min(10),
9110
+ const body = z24.strictObject({
9111
+ code: z24.string().min(10),
9006
9112
  publicKey: ExecutorPublicKeySchema2
9007
9113
  }).safeParse(request.body);
9008
9114
  if (!body.success) {
@@ -9049,9 +9155,9 @@ function registerWorkerRoutes(app, registry) {
9049
9155
  const worker = await authenticated(request, reply);
9050
9156
  if (!worker)
9051
9157
  return reply;
9052
- const body = z23.strictObject({
9158
+ const body = z24.strictObject({
9053
9159
  publicKey: ExecutorPublicKeySchema2,
9054
- rotation: z23.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
9160
+ rotation: z24.string().regex(REMOTE_EPOCH_PATTERN2, "Use a UUIDv7 rotation id")
9055
9161
  }).safeParse(request.body);
9056
9162
  if (!body.success)
9057
9163
  return reply.status(400).send({ error: "Provide the new public key and a rotation id" });
@@ -9195,14 +9301,14 @@ async function createWorkServerInner(options, disposers, close) {
9195
9301
  throw new Error("Postgres deployments require the same WORK_OPERATOR_SECRET on every instance");
9196
9302
  }
9197
9303
  if (config.databaseUrl) {
9198
- fs11.rmSync(path8.join(data, "sandboxes"), { recursive: true, force: true });
9304
+ fs12.rmSync(path9.join(data, "sandboxes"), { recursive: true, force: true });
9199
9305
  }
9200
9306
  const dirs = config.databaseUrl ? ["projects", "sandboxes"] : ["db", "projects", "remotes", "app-bundles", "sandboxes"];
9201
9307
  for (const dir of dirs) {
9202
- fs11.mkdirSync(path8.join(data, dir), { recursive: true });
9308
+ fs12.mkdirSync(path9.join(data, dir), { recursive: true });
9203
9309
  }
9204
9310
  const disposable = Boolean(config.databaseUrl);
9205
- const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path8.join(data, "host-id"));
9311
+ const hostId = config.databaseUrl ? workAuthorityId(publicBase) : loadOrCreateHostId(path9.join(data, "host-id"));
9206
9312
  const nodeId = disposable ? `node.${randomUUID9()}` : `node.${createHash9("sha256").update(hostId).digest("hex").slice(0, 24)}`;
9207
9313
  const authSecret = loadWorkAuthSecret({
9208
9314
  dataDir: data,
@@ -9220,7 +9326,7 @@ async function createWorkServerInner(options, disposers, close) {
9220
9326
  databaseConfig = { db: ownDb };
9221
9327
  workerConcurrency = 4;
9222
9328
  } else {
9223
- const pglite = new PGlite2(path8.join(data, "db"), {
9329
+ const pglite = new PGlite2(path9.join(data, "db"), {
9224
9330
  extensions: { pgcrypto }
9225
9331
  });
9226
9332
  ownDb = withStorableParameters(new Kysely2({
@@ -9259,6 +9365,7 @@ async function createWorkServerInner(options, disposers, close) {
9259
9365
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
9260
9366
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
9261
9367
  graceMs: execution.imageRetentionMs,
9368
+ runningFile: path9.join(data, RUNNING_TIME_FILE),
9262
9369
  log
9263
9370
  });
9264
9371
  disposers.push(async () => diskCare.stop());
@@ -9271,7 +9378,7 @@ async function createWorkServerInner(options, disposers, close) {
9271
9378
  if (objectStore && vaultKeys.length === 0) {
9272
9379
  throw new Error("Postgres deployments require WORK_VAULT_KEY (or the vaultKeys hook) on every instance");
9273
9380
  }
9274
- const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path8.join(data, "credentials"), vaultKeys);
9381
+ const credentialVault = objectStore ? new EncryptedCredentialVault2({ store: objectStore, keys: vaultKeys }) : new EncryptedFileCredentialVault(path9.join(data, "credentials"), vaultKeys);
9275
9382
  if (objectStore) {
9276
9383
  const key = "work/deployment-fingerprint";
9277
9384
  const fingerprint = createHash9("sha256").update(publicBase).update("\x00").update(authSecret).update("\x00").update(JSON.stringify({
@@ -9287,7 +9394,7 @@ async function createWorkServerInner(options, disposers, close) {
9287
9394
  }
9288
9395
  });
9289
9396
  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())) : []);
9397
+ const known = await objectStore.get(keysRecord).then((record) => record ? z25.array(z25.string()).parse(JSON.parse(Buffer.from(record.data).toString())) : []);
9291
9398
  const ids = credentialVault.keyIds;
9292
9399
  if (known.length > 0 && !ids.some((id) => known.includes(id))) {
9293
9400
  throw new Error("WORK_VAULT_KEY and WORK_VAULT_PREVIOUS_KEYS share no key with this Postgres deployment");
@@ -9381,13 +9488,13 @@ async function createWorkServerInner(options, disposers, close) {
9381
9488
  clientExecution: true,
9382
9489
  database: databaseConfig,
9383
9490
  storage: objectStore ? {
9384
- projectManager: new ProjectManager(new FsBackend(path8.join(data, "projects")), new ObjectRemoteBackend({
9491
+ projectManager: new ProjectManager(new FsBackend(path9.join(data, "projects")), new ObjectRemoteBackend({
9385
9492
  store: objectStore,
9386
9493
  keyPrefix: "origins/"
9387
9494
  }))
9388
9495
  } : {
9389
- projectsPath: path8.join(data, "projects"),
9390
- remotesPath: path8.join(data, "remotes")
9496
+ projectsPath: path9.join(data, "projects"),
9497
+ remotesPath: path9.join(data, "remotes")
9391
9498
  },
9392
9499
  sandboxProvider,
9393
9500
  environmentProvider,
@@ -9407,13 +9514,14 @@ async function createWorkServerInner(options, disposers, close) {
9407
9514
  ...hooks.machines ? { placementWaitMinutes: config.machineWaitMinutes ?? 30 } : {},
9408
9515
  gatewayUrl: () => `${publicBase}/api/gateway`,
9409
9516
  ...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")),
9517
+ appBundleStore: objectStore ?? new FsBundleStore(path9.join(data, "app-bundles")),
9518
+ documentBlobStore: objectStore ?? new FsBundleStore(path9.join(data, "document-blobs")),
9412
9519
  triggerKinds: [
9413
9520
  aiToolCall,
9414
9521
  schedule,
9415
9522
  webhook,
9416
9523
  ...SESSION_TRIGGER_KINDS,
9524
+ ...PROJECT_TRIGGER_KINDS,
9417
9525
  ...DIRECTORY_TRIGGER_KINDS,
9418
9526
  ...MACHINE_TRIGGER_KINDS
9419
9527
  ],
@@ -9601,18 +9709,16 @@ async function createWorkServerInner(options, disposers, close) {
9601
9709
  if (workMachines) {
9602
9710
  const machineTimer = setInterval(planMachines, 60000);
9603
9711
  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();
9712
+ const watching = new AbortController;
9713
+ const watched = workMachines.watch({
9714
+ signal: watching.signal,
9715
+ wakeups: core.wakeups
9716
+ });
9611
9717
  planMachines();
9612
9718
  disposers.push(async () => {
9613
9719
  clearInterval(machineTimer);
9614
- clearInterval(checkTimer);
9615
- await checking;
9720
+ watching.abort();
9721
+ await watched;
9616
9722
  await workMachines.settle();
9617
9723
  });
9618
9724
  }
@@ -9965,7 +10071,7 @@ async function createWorkServerInner(options, disposers, close) {
9965
10071
  return reply.status(400).send({ error: message });
9966
10072
  }
9967
10073
  });
9968
- const pwaDist = config.pwaDist ?? path8.resolve(import.meta.dirname, "../../../apps/pwa/dist");
10074
+ const pwaDist = config.pwaDist ?? path9.resolve(import.meta.dirname, "../../../apps/pwa/dist");
9969
10075
  serveSpaDist(app, () => pwaDist, (reply) => reply.type("text/html").send(LANDING_PAGE));
9970
10076
  await hooks.routes?.({ app, catamorphic });
9971
10077
  log(`agents: ${agents.description}`);
@@ -9992,12 +10098,12 @@ async function stopMemberWork(args) {
9992
10098
  }
9993
10099
  function loadOrCreateHostId(file) {
9994
10100
  try {
9995
- const existing = fs11.readFileSync(file, "utf8").trim();
10101
+ const existing = fs12.readFileSync(file, "utf8").trim();
9996
10102
  if (existing)
9997
10103
  return existing;
9998
10104
  } catch {}
9999
10105
  const hostId = `server:${randomUUID9()}`;
10000
- fs11.writeFileSync(file, `${hostId}
10106
+ fs12.writeFileSync(file, `${hostId}
10001
10107
  `, { mode: 384 });
10002
10108
  return hostId;
10003
10109
  }
@@ -10019,8 +10125,8 @@ function isLoopbackBase(base) {
10019
10125
  }
10020
10126
  // src/workers/worker-runtime.ts
10021
10127
  import { createPrivateKey, randomBytes as randomBytes10 } from "node:crypto";
10022
- import fs13 from "node:fs";
10023
- import path10 from "node:path";
10128
+ import fs14 from "node:fs";
10129
+ import path11 from "node:path";
10024
10130
  import { nodeExecutor as nodeExecutor2, RETIRED_KEY_RETENTION_MS } from "@catamorphic/core";
10025
10131
  import {
10026
10132
  executorPublicKey,
@@ -10035,35 +10141,35 @@ import {
10035
10141
  } from "@catamorphic/server-sdk";
10036
10142
 
10037
10143
  // src/workers/worker-identity.ts
10038
- import fs12 from "node:fs";
10039
- import path9 from "node:path";
10040
- import { z as z25 } from "zod";
10144
+ import fs13 from "node:fs";
10145
+ import path10 from "node:path";
10146
+ import { z as z26 } from "zod";
10041
10147
  var CREDENTIAL_FILE = "worker-credential";
10042
10148
  var KEY_FILE = "worker-key";
10043
10149
  var PREVIOUS_FILE = "worker-identity.previous";
10044
10150
  var NEXT_FILE = "worker-identity.next";
10045
- var PairSchema = z25.strictObject({
10046
- credential: z25.string().min(1),
10047
- privateKey: z25.string().min(1)
10151
+ var PairSchema = z26.strictObject({
10152
+ credential: z26.string().min(1),
10153
+ privateKey: z26.string().min(1)
10048
10154
  });
10049
10155
  var NextIdentitySchema = PairSchema.extend({
10050
10156
  previous: PairSchema.optional()
10051
10157
  });
10052
10158
  function loadWorkerIdentity(dataDir) {
10053
- const next = readIfPresent(path9.join(dataDir, NEXT_FILE));
10159
+ const next = readIfPresent(path10.join(dataDir, NEXT_FILE));
10054
10160
  if (next !== undefined) {
10055
10161
  const parsed = NextIdentitySchema.safeParse(parseJson(next));
10056
10162
  if (parsed.success)
10057
10163
  install(dataDir, parsed.data);
10058
- fs12.rmSync(path9.join(dataDir, NEXT_FILE), { force: true });
10164
+ fs13.rmSync(path10.join(dataDir, NEXT_FILE), { force: true });
10059
10165
  }
10060
- const credential = readIfPresent(path9.join(dataDir, CREDENTIAL_FILE))?.trim();
10166
+ const credential = readIfPresent(path10.join(dataDir, CREDENTIAL_FILE))?.trim();
10061
10167
  if (!credential)
10062
10168
  return;
10063
- const privateKey = readIfPresent(path9.join(dataDir, KEY_FILE));
10169
+ const privateKey = readIfPresent(path10.join(dataDir, KEY_FILE));
10064
10170
  if (!privateKey)
10065
10171
  return { credential };
10066
- const previous = PairSchema.safeParse(parseJson(readIfPresent(path9.join(dataDir, PREVIOUS_FILE)) ?? ""));
10172
+ const previous = PairSchema.safeParse(parseJson(readIfPresent(path10.join(dataDir, PREVIOUS_FILE)) ?? ""));
10067
10173
  return {
10068
10174
  credential,
10069
10175
  privateKey,
@@ -10071,53 +10177,53 @@ function loadWorkerIdentity(dataDir) {
10071
10177
  };
10072
10178
  }
10073
10179
  function saveWorkerIdentity(dataDir, identity) {
10074
- writeAtomically(path9.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10180
+ writeAtomically(path10.join(dataDir, NEXT_FILE), JSON.stringify(identity));
10075
10181
  install(dataDir, identity);
10076
- fs12.rmSync(path9.join(dataDir, NEXT_FILE), { force: true });
10182
+ fs13.rmSync(path10.join(dataDir, NEXT_FILE), { force: true });
10077
10183
  syncDirectory(dataDir);
10078
10184
  }
10079
10185
  function confirmWorkerIdentity(dataDir) {
10080
- fs12.rmSync(path9.join(dataDir, PREVIOUS_FILE), { force: true });
10186
+ fs13.rmSync(path10.join(dataDir, PREVIOUS_FILE), { force: true });
10081
10187
  syncDirectory(dataDir);
10082
10188
  }
10083
10189
  function saveWorkerKey(dataDir, privateKey) {
10084
- writeAtomically(path9.join(dataDir, KEY_FILE), privateKey);
10190
+ writeAtomically(path10.join(dataDir, KEY_FILE), privateKey);
10085
10191
  }
10086
10192
  function install(dataDir, identity) {
10087
10193
  if (identity.previous)
10088
- writeAtomically(path9.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10194
+ writeAtomically(path10.join(dataDir, PREVIOUS_FILE), JSON.stringify(identity.previous));
10089
10195
  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}
10196
+ fs13.rmSync(path10.join(dataDir, PREVIOUS_FILE), { force: true });
10197
+ writeAtomically(path10.join(dataDir, KEY_FILE), identity.privateKey);
10198
+ writeAtomically(path10.join(dataDir, CREDENTIAL_FILE), `${identity.credential}
10093
10199
  `);
10094
10200
  }
10095
10201
  function writeAtomically(file, content) {
10096
10202
  const temporary = `${file}.tmp`;
10097
- const handle = fs12.openSync(temporary, "w", 384);
10203
+ const handle = fs13.openSync(temporary, "w", 384);
10098
10204
  try {
10099
- fs12.writeSync(handle, content);
10100
- fs12.fsyncSync(handle);
10205
+ fs13.writeSync(handle, content);
10206
+ fs13.fsyncSync(handle);
10101
10207
  } finally {
10102
- fs12.closeSync(handle);
10208
+ fs13.closeSync(handle);
10103
10209
  }
10104
- fs12.chmodSync(temporary, 384);
10105
- fs12.renameSync(temporary, file);
10106
- syncDirectory(path9.dirname(file));
10210
+ fs13.chmodSync(temporary, 384);
10211
+ fs13.renameSync(temporary, file);
10212
+ syncDirectory(path10.dirname(file));
10107
10213
  }
10108
10214
  function syncDirectory(dir) {
10109
10215
  try {
10110
- const handle = fs12.openSync(dir, "r");
10216
+ const handle = fs13.openSync(dir, "r");
10111
10217
  try {
10112
- fs12.fsyncSync(handle);
10218
+ fs13.fsyncSync(handle);
10113
10219
  } finally {
10114
- fs12.closeSync(handle);
10220
+ fs13.closeSync(handle);
10115
10221
  }
10116
10222
  } catch {}
10117
10223
  }
10118
10224
  function readIfPresent(file) {
10119
10225
  try {
10120
- return fs12.readFileSync(file, "utf8");
10226
+ return fs13.readFileSync(file, "utf8");
10121
10227
  } catch (error) {
10122
10228
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
10123
10229
  return;
@@ -10157,7 +10263,7 @@ async function startWorkWorker(options) {
10157
10263
  }
10158
10264
  });
10159
10265
  const log = options.log ?? (() => {});
10160
- fs13.mkdirSync(options.dataDir, { recursive: true, mode: 448 });
10266
+ fs14.mkdirSync(options.dataDir, { recursive: true, mode: 448 });
10161
10267
  const enrolled = await loadOrEnroll({
10162
10268
  base,
10163
10269
  dataDir: options.dataDir,
@@ -10224,6 +10330,7 @@ async function startWorkWorker(options) {
10224
10330
  ...execution.diskFloorMb !== undefined ? { floorMb: execution.diskFloorMb } : {},
10225
10331
  ...execution.diskCriticalMb !== undefined ? { criticalMb: execution.diskCriticalMb } : {},
10226
10332
  graceMs: execution.imageRetentionMs,
10333
+ runningFile: path11.join(options.dataDir, RUNNING_TIME_FILE),
10227
10334
  log
10228
10335
  });
10229
10336
  await diskCare.measure();
@@ -10301,7 +10408,7 @@ async function startWorkWorker(options) {
10301
10408
  throw new Error(reason);
10302
10409
  throw new RunnerSessionEndedError(reason);
10303
10410
  };
10304
- const sandboxes = new PersistedSandboxes(path10.join(options.dataDir, "sandboxes.json"));
10411
+ const sandboxes = new PersistedSandboxes(path11.join(options.dataDir, "sandboxes.json"));
10305
10412
  const offerSignIns = { now: () => {} };
10306
10413
  const harnessSignIns = new HarnessSignIns({
10307
10414
  signInRoot: execution.signInRoot,
@@ -10632,7 +10739,7 @@ class PersistedSandboxes extends Set {
10632
10739
  super();
10633
10740
  this.file = file;
10634
10741
  try {
10635
- const stored = JSON.parse(fs13.readFileSync(file, "utf8"));
10742
+ const stored = JSON.parse(fs14.readFileSync(file, "utf8"));
10636
10743
  if (Array.isArray(stored)) {
10637
10744
  for (const id of stored)
10638
10745
  if (typeof id === "string")
@@ -10655,7 +10762,7 @@ class PersistedSandboxes extends Set {
10655
10762
  save() {
10656
10763
  if (!this.ready)
10657
10764
  return;
10658
- fs13.writeFileSync(this.file, JSON.stringify([...this]), { mode: 384 });
10765
+ fs14.writeFileSync(this.file, JSON.stringify([...this]), { mode: 384 });
10659
10766
  }
10660
10767
  }
10661
10768
  export {
@@ -10694,5 +10801,5 @@ export {
10694
10801
  workServerConfigFromEnv
10695
10802
  };
10696
10803
 
10697
- //# debugId=0E6681C1FDBFFAD764756E2164756E21
10804
+ //# debugId=6D4AA9AD62CC45E964756E2164756E21
10698
10805
  //# sourceMappingURL=index.js.map