@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51

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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -9,6 +9,9 @@
9
9
  // its turn for up to --drain-timeout (default AGENTRUN_DRAIN_TIMEOUT, else RUNNER_DRAIN_TIMEOUT), then every loop left is stopped where it can resume
10
10
  // and its run handed back for another runner (a loop that never stops is given up when its claim would run out, and its
11
11
  // run is claimable when its lease lapses); then 0. Bad arguments exit 2, a store it cannot open (yet) 3, anything else 1.
12
+ // A store a later server migrated past what this build can run beside (its runner floor rose above the version this build
13
+ // knows; read again at each renewal) is the same stop: nothing more claimed, the drain, its runs handed back; then 3, so
14
+ // its platform starts a runner of the new release in its place.
12
15
  // A run isolation it cannot give (run-child-host.ts runIsolationOf) is said, and it stays up claiming nothing until a stop: 0.
13
16
  // An error nothing handles exits 1 at once, said with its stack (lastResort).
14
17
  import { randomUUID } from "node:crypto";
@@ -23,13 +26,13 @@ import { dockerPathsForRuns } from "../box-paths.js";
23
26
  import { hostCommandRefusals } from "../computers.js";
24
27
  import { hostAddressesOnce } from "../docker-host-addresses.js";
25
28
  import { claimInstallsStopped } from "../harness-install.js";
26
- import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessModulesEnv, harnessModulesOf, harnessTable } from "../harness-table.js";
29
+ import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_TABLE_ENV, harnessModulesEnv, harnessModulesOf, harnessTable } from "../harness-table.js";
27
30
  import { DEFAULT_PORT, maxRunsOf } from "../host.js";
28
31
  import { FAUX_ENV, FAUX_PREFIX, withoutFaux } from "../model.js";
29
32
  import { durationMs, runLine } from "../print.js";
30
33
  import { bootSealKey } from "../seal-key.js";
31
34
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
32
- import { migrationsIn, openStore, SchemaVersionUnknown, StoreAwaitsServer, storePlace, storeTarget } from "../store/index.js";
35
+ import { migrationsIn, openStore, RunnerBelowFloor, SchemaVersionUnknown, StoreAwaitsServer, storePlace, storeTarget } from "../store/index.js";
33
36
  import { SCHEMA_VERSION } from "../store/schema.js";
34
37
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
35
38
  import { FAUX_BROWSER_ENV } from "../tools.js";
@@ -38,6 +41,7 @@ import { LOOPBACK as LIVE_LOOPBACK, runnerLiveOf } from "../live-reach.js";
38
41
  import { LOOPBACK } from "../mcp-oauth.js";
39
42
  import { serverOwn } from "../mcp-private-hosts.js";
40
43
  import { MCP_ALLOW_LOOPBACK_ENV } from "../mcp-servers-store.js";
44
+ import { PRIVATE_HOSTS_ENV, privateHostsSwitchValue } from "../mcp-private-hosts.js";
41
45
  import { envValue } from "../key-meta.js";
42
46
  import { fauxComputers } from "../faux-computers.js";
43
47
  import { computerDepsFrom } from "../workspace/computer-deps.js";
@@ -49,8 +53,11 @@ import { routeOf } from "./model-route.js";
49
53
  import { RUN_PROCESS_MIB, runnerMemory } from "./memory-claim.js";
50
54
  import { childLoops, isolationLoops, RunIsolationRefused, runIsolationOf } from "./run-child-host.js";
51
55
  import { sweepEndedScratch } from "./scratch-sweep.js";
52
- import { RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
56
+ import { RUNNER_LOOPS, RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
53
57
  import { keepPresence } from "./presence.js";
58
+ import { diskFreeGate } from "./disk-free.js";
59
+ import { checkLines, checkRunnerEnv } from "./runner-check.js";
60
+ import { metricLine, startRunnerGauge } from "./runner-metrics.js";
54
61
  export { RUNNER_RENEW_EVERY_MS } from "./runner.js";
55
62
  /** A store this runner cannot use, or arguments it cannot take, in words a person starting it can act on. */
56
63
  export class RunnerRefused extends Error {
@@ -73,6 +80,8 @@ export async function openRunnerStore(dataDir, env, warn, url) {
73
80
  catch (error) {
74
81
  if (error instanceof StoreAwaitsServer)
75
82
  throw new RunnerRefused(`The store in ${where} is behind this runner: start the server first, which upgrades the store in place, then the runner.`, { cause: error });
83
+ if (error instanceof RunnerBelowFloor)
84
+ throw new RunnerRefused(`The store in ${where} is at schema version ${error.found}, and a runner on it must know version ${error.floor} or later; this runner knows ${error.known}: run a runner of the server's release.`, { cause: error });
76
85
  if (!(error instanceof SchemaVersionUnknown))
77
86
  throw error;
78
87
  const { found, known } = error;
@@ -140,6 +149,11 @@ export function runnerLoop(store, dataDir, env = process.env, booted, isolation,
140
149
  // relay's: dial-relay.ts); with none, its provider refuses.
141
150
  const computers = runnerComputers(store, runs, sealKey, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(dial ? { dial } : {}) });
142
151
  const loopback = runnerLoopback(env);
152
+ // The operator's bound on owner-allowed private hosts (mcp-private-hosts.ts), read by every dial this runner and its
153
+ // runs' processes make (they inherit it, runEnv): said at the start when it narrows the owner's list.
154
+ const privateBound = privateHostsSwitchValue(env);
155
+ if (privateBound !== null)
156
+ process.stderr.write(`agentrun-serve runner: ${PRIVATE_HOSTS_ENV}=${privateBound}: an owner's private-network hosts for MCP servers and calendars are ${privateBound.startsWith("none") ? "never allowed" : `allowed only in ${privateBound}`} on this runner\n`);
143
157
  if (loopback)
144
158
  process.stderr.write(`agentrun-serve runner: ${MCP_ALLOW_LOOPBACK_ENV}=1: this runner's runs may reach an MCP server on this machine's loopback, never at ${loopback.own.join(" or ")} nor where its server listens\n`);
145
159
  const deps = {
@@ -218,6 +232,10 @@ export async function startRunnerProcess(options) {
218
232
  const warn = options.warn ?? ((message) => void process.stderr.write(`agentrun-serve runner: ${message}\n`));
219
233
  const env = options.env ?? process.env;
220
234
  const { store, kind, schema } = await openRunnerStore(options.dataDir, env, warn, options.storeUrl);
235
+ // A store a later server migrated, additively: said once, so a runner behind its server is seen where it runs.
236
+ const opened = await store.schemaState?.().catch(() => undefined);
237
+ if (opened?.version != null && opened.version > schema)
238
+ warn(`the store is at schema version ${opened.version}, ahead of this runner's ${schema}; its runner floor is ${opened.runnerFloor}, so this runner runs on it until a later migration raises the floor`);
221
239
  const memory = options.memory ?? runnerMemory(store, undefined, env, options.processMib ?? 0);
222
240
  let runner;
223
241
  let seal;
@@ -234,7 +252,8 @@ export async function startRunnerProcess(options) {
234
252
  // One incarnation for this process: its word in the store that it is there (presence.ts) and its relay's minted
235
253
  // tokens and proofs name the same one, so the server's "restarted since" and the runner's row speak of one process.
236
254
  // The presence first, then the relay says where it answers on the presence's row.
237
- presence = keepPresence(store.runners, name, null, { warn, incarnation: randomUUID() });
255
+ // Its row says this build's version and the most runs it holds (its loops), for the server's capacity read.
256
+ presence = keepPresence(store.runners, name, null, { warn, incarnation: randomUUID(), slots: options.loops ?? RUNNER_LOOPS });
238
257
  // Its relay (dial-relay.ts), where its environment names the server's public address: a machine that dials the
239
258
  // server lands in this runner's hub, through the server. Its log lines are the runner's warnings.
240
259
  relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, presence, env, log: warn });
@@ -260,6 +279,9 @@ export async function startRunnerProcess(options) {
260
279
  memory,
261
280
  ...(options.onEvent ? { onEvent: options.onEvent } : {}),
262
281
  ...(runEnded ? { runEnded } : {}),
282
+ // A runner on a disk of its own claims nothing while the server keeps runs' folders on the server's disk (Mode 1),
283
+ // and says why on its presence row (disk-free.ts): those runs wait for a runner on the server's disk.
284
+ claimGate: diskFreeGate(store, options.dataDir, env, kind),
263
285
  onBeat: heartbeat(options.dataDir, name, options.now ?? Date.now),
264
286
  });
265
287
  }
@@ -275,22 +297,69 @@ export async function startRunnerProcess(options) {
275
297
  const held = seal;
276
298
  const relayed = relay;
277
299
  const kept = presence;
300
+ const floor = watchFloor(store, schema, options.floorEveryMs ?? RUNNER_RENEW_EVERY_MS);
301
+ const close = () => (closing ??= (async () => {
302
+ floor.stop();
303
+ // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
304
+ await Promise.all([janitor?.close(), runner.close()]);
305
+ // Its relay after its runs: a run's release revokes its machine's token through it. Then its word that it is
306
+ // there: it claims no more.
307
+ await relayed?.close();
308
+ await kept.close();
309
+ // A first-use install its claims started, stopped as they let go: its npm ends before this process can.
310
+ await claimInstallsStopped();
311
+ await store.close();
312
+ held.release();
313
+ })());
314
+ // A floor above this runner closes it at once: it claims nothing from the read that saw the floor on, drains and hands
315
+ // its runs back. The process's own close (runnerMain, after `outdated`) is this same close, awaited.
316
+ // Its failure is the process's to say: runnerMain awaits this same close.
317
+ void floor.outdated.then(() => close()).catch(() => undefined);
278
318
  return {
279
319
  runner,
280
320
  store: { kind, schema },
281
321
  memoryMib: memory.budgetMib,
282
- close: () => (closing ??= (async () => {
283
- // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
284
- await Promise.all([janitor?.close(), runner.close()]);
285
- // Its relay after its runs: a run's release revokes its machine's token through it. Then its word that it is
286
- // there: it claims no more.
287
- await relayed?.close();
288
- await kept.close();
289
- // A first-use install its claims started, stopped as they let go: its npm ends before this process can.
290
- await claimInstallsStopped();
291
- await store.close();
292
- held.release();
293
- })()),
322
+ outdated: floor.outdated,
323
+ close,
324
+ };
325
+ }
326
+ /** Reads `store`'s runner floor every `everyMs` (Store.schemaState): `outdated` settles, once, with the words of why,
327
+ * when it is above `known`, the version this runner's build knows, and the reads stop. A read that fails (a busy store,
328
+ * a connection down) is tried at the next one: a renew's own failure says so, and only a floor read says to stop. */
329
+ function watchFloor(store, known, everyMs) {
330
+ let settle;
331
+ const outdated = new Promise((resolve) => (settle = resolve));
332
+ if (!store.schemaState)
333
+ return { outdated, stop: () => { } };
334
+ let reading = false;
335
+ let done = false;
336
+ const read = async () => {
337
+ if (reading || done)
338
+ return;
339
+ reading = true;
340
+ try {
341
+ const state = await store.schemaState();
342
+ if (done || state.runnerFloor === null || state.runnerFloor <= known)
343
+ return;
344
+ done = true;
345
+ clearInterval(timer);
346
+ settle(`the store is at schema version ${state.version}, and its runner floor rose to ${state.runnerFloor}, above the version this runner knows (${known}): a later server changed the schema in a way this runner cannot run beside`);
347
+ }
348
+ catch {
349
+ // Tried again at the next read.
350
+ }
351
+ finally {
352
+ reading = false;
353
+ }
354
+ };
355
+ const timer = setInterval(() => void read(), everyMs);
356
+ timer.unref();
357
+ return {
358
+ outdated,
359
+ stop: () => {
360
+ done = true;
361
+ clearInterval(timer);
362
+ },
294
363
  };
295
364
  }
296
365
  const storeFactories = new WeakSet();
@@ -347,6 +416,8 @@ export function runnerHolds(args, env) {
347
416
  * fake browser's module, with --faux only, as the server's. */
348
417
  export function runnerArgs(argv) {
349
418
  let dataDir;
419
+ let envOnly = false;
420
+ let heartbeatOnly = false;
350
421
  let loops;
351
422
  let drainMs;
352
423
  let name;
@@ -388,30 +459,52 @@ export function runnerArgs(argv) {
388
459
  harnessModules.push(value());
389
460
  else if (arg === "--check")
390
461
  check = true;
462
+ else if (arg === "--env")
463
+ envOnly = true;
464
+ else if (arg === "--heartbeat")
465
+ heartbeatOnly = true;
391
466
  else
392
- throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--drain-timeout D] [--name N] [--faux M [--faux-browser M]] [--harness-module M ...], or --check --data D [--name N]`);
467
+ throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--drain-timeout D] [--name N] [--faux M [--faux-browser M]] [--harness-module M ...], or --check --data D [--name N], or --check --env [--data D], or --check --heartbeat --data D [--name N]`);
393
468
  }
469
+ if (envOnly && !check)
470
+ throw new RunnerRefused("--env goes with --check: runner --check --env [--data D]");
471
+ if (heartbeatOnly && !check)
472
+ throw new RunnerRefused("--heartbeat goes with --check: runner --check --heartbeat --data D [--name N]");
473
+ if (heartbeatOnly && envOnly)
474
+ throw new RunnerRefused("--check takes --env (its environment alone) or --heartbeat (its heartbeat alone), not both: give neither to check both");
475
+ // `--check --env` checks the environment alone, which needs no data directory where the store is AGENTRUN_STORE_URL's.
476
+ if (envOnly)
477
+ return { dataDir: dataDir ?? "", check: true, envOnly: true, ...(harnessModules.length ? { harnessModules } : {}), ...(loops === undefined ? {} : { loops }), ...(drainMs === undefined ? {} : { drainMs }), ...(name === undefined ? {} : { name }) };
394
478
  if (!dataDir)
395
479
  throw new RunnerRefused("a runner needs its data directory: --data D");
480
+ if (heartbeatOnly)
481
+ return { dataDir, check: true, heartbeatOnly: true, ...(name === undefined ? {} : { name }) };
396
482
  if (fauxBrowser !== undefined && faux === undefined)
397
483
  throw new RunnerRefused("--faux-browser goes with --faux");
398
484
  return { dataDir, ...(harnessModules.length ? { harnessModules } : {}), ...(loops === undefined ? {} : { loops }), ...(drainMs === undefined ? {} : { drainMs }), ...(name === undefined ? {} : { name }), ...(faux === undefined ? {} : { faux }), ...(fauxBrowser === undefined ? {} : { fauxBrowser }), ...(check ? { check: true } : {}) };
399
485
  }
400
- /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
401
- * says the runner is ready (on a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one
402
- * that came before the handlers would end the process unclosed. */
403
- export async function runUntilSignalled(process, signals = ["SIGTERM", "SIGINT"], ready = () => { }) {
404
- await new Promise((resolve) => {
405
- const onSignal = () => {
486
+ /** Runs until SIGTERM or SIGINT, or until the store's runner floor rises above this runner (RunnerProcess.outdated),
487
+ * then closes: nothing more claimed, the drain, its runs handed back. Answers the floor's words when that was the stop,
488
+ * else undefined. `ready` is called once the signals are handled, never before: a line that says the runner is ready (on
489
+ * a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one that came before the
490
+ * handlers would end the process unclosed. `outdated`: told the floor's words before the close begins. */
491
+ export async function runUntilSignalled(process, signals = ["SIGTERM", "SIGINT"], ready = () => { }, outdated = () => { }) {
492
+ const why = await new Promise((resolve) => {
493
+ const done = (value) => {
406
494
  for (const signal of signals)
407
495
  globalThis.process.off(signal, onSignal);
408
- resolve();
496
+ resolve(value);
409
497
  };
498
+ const onSignal = () => done(undefined);
410
499
  for (const signal of signals)
411
500
  globalThis.process.on(signal, onSignal);
501
+ void process.outdated?.then(done);
412
502
  ready();
413
503
  });
504
+ if (why !== undefined)
505
+ outdated(why);
414
506
  await process.close();
507
+ return why;
415
508
  }
416
509
  /** The runner process's last resort (runnerMain installs it for unhandledRejection and uncaughtException): says what
417
510
  * went wrong, in the runner's name with its stack, then exits 1 at once, closing nothing. A runner that went on after
@@ -428,6 +521,8 @@ export function lastResort(name, write = (line) => void writeSync(2, line), exit
428
521
  }
429
522
  /** One line of what the runner did, in its name. */
430
523
  function said(name, event) {
524
+ if (event.type === "refusing")
525
+ return event.reason === null ? `Runner ${name} claims runs again` : undefined;
431
526
  if (event.type === "claimed")
432
527
  return `Runner ${name} claimed ${event.claim.runId} (epoch ${event.claim.epoch})`;
433
528
  if (event.type === "released")
@@ -440,6 +535,8 @@ function said(name, event) {
440
535
  * goes to stderr. Undefined for any other event. The runner beside a server says them the same way (beside.ts), so a
441
536
  * lapse of every claim at once shows its cause. */
442
537
  export function troubleLine(name, event) {
538
+ if (event.type === "refusing" && event.reason !== null)
539
+ return `Runner ${name} claims nothing: ${event.reason}`;
443
540
  if (event.type === "claim-lost")
444
541
  return `Runner ${name} lost its claim on ${event.runId} (${event.why})`;
445
542
  if (event.type === "error")
@@ -447,8 +544,8 @@ export function troubleLine(name, event) {
447
544
  return undefined;
448
545
  }
449
546
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store this runner cannot open (a schema it does not
450
- * know, none set up yet, or one its server has yet to upgrade); 1: anything else; 0: closed on a signal, or --check found
451
- * a fresh heartbeat. AGENTRUN_RUNNER_NAME names it when --name does not. */
547
+ * know, none set up yet, or one its server has yet to upgrade), or one whose runner floor rose above it while it ran
548
+ * (closed, its runs handed back); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names it when --name does not. */
452
549
  export async function runnerMain(argv, given = process.env, hooks = {}) {
453
550
  let args;
454
551
  try {
@@ -479,19 +576,8 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
479
576
  }
480
577
  const env = { ...withoutFaux(given), ...modules, ...(args.faux ? { [FAUX_ENV]: resolve(args.faux) } : {}), ...(args.fauxBrowser ? { [FAUX_BROWSER_ENV]: resolve(args.fauxBrowser) } : {}) };
481
578
  const name = args.name ?? env.AGENTRUN_RUNNER_NAME ?? undefined;
482
- if (args.check) {
483
- if (!name) {
484
- console.error("agentrun-serve runner: --check needs the runner's name: --name N or AGENTRUN_RUNNER_NAME");
485
- return 2;
486
- }
487
- const checked = checkRunner({ dataDir: args.dataDir, name });
488
- if (checked.ok) {
489
- console.log(`Runner ${name} is alive`);
490
- return 0;
491
- }
492
- console.error(`agentrun-serve runner: ${checked.why}`);
493
- return 1;
494
- }
579
+ if (args.check)
580
+ return runnerCheck(args, env, name);
495
581
  let holds;
496
582
  try {
497
583
  holds = runnerHolds(args, env);
@@ -564,11 +650,15 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
564
650
  // The runner subcommand ends what a crashed runner of this server left (never under --faux).
565
651
  janitor: true,
566
652
  onEvent: (event) => {
567
- if (event.type === "error")
653
+ if (event.type === "error" || (event.type === "refusing" && event.reason !== null))
568
654
  return void console.error(troubleLine(runnerOf, event));
569
655
  const line = said(runnerOf, event);
570
656
  if (line)
571
657
  console.log(line);
658
+ // Its metric line beside it (runner-metrics.ts): claims, hand-backs by cause, the drain.
659
+ const metric = metricLine(runnerOf, event);
660
+ if (metric)
661
+ console.log(metric);
572
662
  },
573
663
  });
574
664
  }
@@ -585,14 +675,66 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
585
675
  await started.close();
586
676
  return 0;
587
677
  }
678
+ // Its gauge (runner-metrics.ts): the runs it holds of its loops, and its process's memory, every minute until its stop.
679
+ const gauge = startRunnerGauge({ runner: started.runner.name, held: () => started.runner.held().length, slots: holds.loops, write: (line) => console.log(line) });
588
680
  // Ready is said once SIGTERM and SIGINT are handled, so a stop sent on reading it always closes the runner.
589
681
  // Then its memory budget, a line of its own (the ready line's shape is read by deploy checks): what a container's limit
590
682
  // gave it is seen where it runs.
591
- await runUntilSignalled(started, RUNNER_SIGNALS, () => {
592
- console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${holds.loops} loops`);
593
- console.log(`Runner ${started.runner.name} memory: ${started.memoryMib} MiB for runs, each weighed by its harness`);
594
- });
595
- return 0;
683
+ try {
684
+ const outdated = await runUntilSignalled(started, RUNNER_SIGNALS, () => {
685
+ console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${holds.loops} loops`);
686
+ console.log(`Runner ${started.runner.name} memory: ${started.memoryMib} MiB for runs, each weighed by its harness`);
687
+ }, (why) => console.error(`agentrun-serve runner: Runner ${started.runner.name} stops claiming and hands its runs back: ${why}. Run a runner of the server's release.`));
688
+ // Past the floor: non-zero, so its platform starts a runner of the new release in its place.
689
+ return outdated === undefined ? 0 : 3;
690
+ }
691
+ finally {
692
+ gauge.stop();
693
+ }
694
+ }
695
+ /** `runner --check`: the runner's environment (runner-check.ts checkRunnerEnv), by name, never by value, then, without
696
+ * --env, its heartbeat in --data under its name (checkRunner). `--heartbeat`: the heartbeat alone, with no store and no
697
+ * secret (a liveness check a database blip does not fail). Each row on stdout, each gap on stderr too. 0 when nothing is
698
+ * missing or bad and the heartbeat is fresh, 1 otherwise, 2 for a heartbeat check with no name. */
699
+ async function runnerCheck(args, env, name) {
700
+ if (!args.envOnly && !name) {
701
+ console.error("agentrun-serve runner: --check needs the runner's name: --name N or AGENTRUN_RUNNER_NAME (or --check --env, for its environment alone)");
702
+ return 2;
703
+ }
704
+ // Harness modules given as --harness-module hold what AGENTRUN_SERVE_HARNESS_MODULES would (harness-table.ts
705
+ // harnessModulesOf): a runner started with the flag is checked with it.
706
+ const flagged = "harnessModules" in args && args.harnessModules?.length ? args.harnessModules.join(",") : undefined;
707
+ const read = (one) => (one === HARNESS_MODULES_SETTING && flagged !== undefined ? flagged : (secret(one) ?? env[one]));
708
+ const rows = args.heartbeatOnly ? [] : await checkRunnerEnv({ ...(args.dataDir ? { dataDir: args.dataDir } : {}), env, read });
709
+ // What the runner's start refuses before it claims (runnerMain): its run slots, drain and free-model requests, the
710
+ // Archil settings it is given, and its runs' isolation (the user each run runs as, and the image's helper that switches
711
+ // to it), checked the same way, so a runner whose start would stop or claim nothing never passes this check.
712
+ if (!args.heartbeatOnly) {
713
+ try {
714
+ // The flags the runner is started with win over the environment there (--loops, --drain-timeout), and here.
715
+ const loops = "loops" in args ? args.loops : undefined;
716
+ const holds = runnerHolds({ ...(loops !== undefined ? { loops } : {}), ...("drainMs" in args && args.drainMs !== undefined ? { drainMs: args.drainMs } : {}) }, env);
717
+ archilSettingsFromEnv(env);
718
+ await runIsolationOf(env, loops !== undefined || Boolean(env.AGENTRUN_MAX_RUNS) ? holds.loops : undefined, () => { });
719
+ rows.push({ state: "ok", name: "start", why: "the runner's start takes its settings: run slots, drain, free-model requests, Archil, run isolation" });
720
+ }
721
+ catch (error) {
722
+ if (!(error instanceof RunnerRefused) && !(error instanceof ArchilSettingsEnvInvalid) && !(error instanceof RunIsolationRefused))
723
+ throw error;
724
+ rows.push({ state: "bad", name: "start", why: `the runner's start refuses its environment: ${error.message}` });
725
+ }
726
+ }
727
+ if (!args.envOnly && name) {
728
+ const checked = checkRunner({ dataDir: args.dataDir, name });
729
+ rows.push(checked.ok ? { state: "ok", name: "heartbeat", why: `Runner ${name} is alive` } : { state: "bad", name: "heartbeat", why: checked.why });
730
+ }
731
+ const { lines, ok } = checkLines(rows);
732
+ for (const line of lines)
733
+ console.log(line);
734
+ for (const row of rows)
735
+ if (row.state === "missing" || row.state === "bad")
736
+ console.error(`agentrun-serve runner: ${row.name}: ${row.why}`);
737
+ return ok ? 0 : 1;
596
738
  }
597
739
  /** The signals that stop a runner process. */
598
740
  const RUNNER_SIGNALS = ["SIGTERM", "SIGINT"];
@@ -3,6 +3,9 @@ import type { Runners } from "../store/store.js";
3
3
  export declare const PRESENCE_RENEW_MS = 10000;
4
4
  /** How old a runner's word can be and still count: three renewals missed. */
5
5
  export declare const PRESENCE_STALE_MS: number;
6
+ /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
7
+ * capacity read (GET /v2/capacity). */
8
+ export declare const RUNNER_VERSION: string;
6
9
  /** Where a runner's relay takes the dials the server relays to it (dial-relay.ts). */
7
10
  export interface RelayAt {
8
11
  readonly host: string;
@@ -15,20 +18,26 @@ export interface Presence {
15
18
  /** Says on its row where its relay answers (`at`), or that it answers nowhere (null, the relay's close), and keeps that
16
19
  * through every put again. Rejects when that write fails, which the renewals then try again. */
17
20
  relay(at: RelayAt | null): Promise<void>;
21
+ /** Says on its row why this runner claims nothing now (`words`), or that it claims again (null), and keeps that through
22
+ * every put again: a runner that cannot serve the runs this store holds for a while (runner.ts claimGate) says so where
23
+ * the server reads it (runnersRefused). Rejects when that write fails, which the renewals then try again. */
24
+ refuse(words: string | null): Promise<void>;
18
25
  /** Stops renewing it and removes the row (its incarnation's alone). */
19
26
  close(): Promise<void>;
20
27
  /** Stops renewing it and leaves the row to go stale, as a crash would. */
21
28
  stop(): void;
22
29
  }
23
- /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), renewed every `renewMs`; put
30
+ /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), with this build's version
31
+ * (RUNNER_VERSION) and `slots`, the most runs it holds at once (none for a refusing runner), renewed every `renewMs`; put
24
32
  * again when it went (a row pruned, a store restored), never over a later process's of the same name while that one is
25
33
  * live; its relay's place is written on its own row only. A write that
26
34
  * fails is tried again at the next renewal: it never stops the runner, and `warn` hears it once. `incarnation` is the
27
35
  * runner process's one (runner/main.ts hands its relay the same), a new one by default. */
28
- export declare function keepPresence(runners: Runners, runner: string, refused: string | null, { renewMs, warn, incarnation }?: {
36
+ export declare function keepPresence(runners: Runners, runner: string, refused: string | null, { renewMs, warn, incarnation, slots }?: {
29
37
  renewMs?: number;
30
38
  warn?: (line: string) => void;
31
39
  incarnation?: string;
40
+ slots?: number | null;
32
41
  }): Presence;
33
42
  /** Why no runner here can take a run, in the runners' own words, or undefined while one can (or none is there): the rows
34
43
  * seen within `staleMs` on the store's clock (Runners.live), when there is one at least and every one refused. */
@@ -10,17 +10,22 @@
10
10
  // runs still queued (server.ts). With no runner there at all (a server with --no-runner and its runner not started yet),
11
11
  // it refuses nothing: runs queue for the runner to come, as before.
12
12
  import { randomUUID } from "node:crypto";
13
+ import { readFileSync } from "node:fs";
13
14
  import { ApiError } from "../errors.js";
14
15
  /** How often a runner says again that it is there. */
15
16
  export const PRESENCE_RENEW_MS = 10_000;
16
17
  /** How old a runner's word can be and still count: three renewals missed. */
17
18
  export const PRESENCE_STALE_MS = 3 * PRESENCE_RENEW_MS;
18
- /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), renewed every `renewMs`; put
19
+ /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
20
+ * capacity read (GET /v2/capacity). */
21
+ export const RUNNER_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
22
+ /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), with this build's version
23
+ * (RUNNER_VERSION) and `slots`, the most runs it holds at once (none for a refusing runner), renewed every `renewMs`; put
19
24
  * again when it went (a row pruned, a store restored), never over a later process's of the same name while that one is
20
25
  * live; its relay's place is written on its own row only. A write that
21
26
  * fails is tried again at the next renewal: it never stops the runner, and `warn` hears it once. `incarnation` is the
22
27
  * runner process's one (runner/main.ts hands its relay the same), a new one by default. */
23
- export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENEW_MS, warn = (_line) => { }, incarnation = randomUUID() } = {}) {
28
+ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENEW_MS, warn = (_line) => { }, incarnation = randomUUID(), slots = null } = {}) {
24
29
  let warned = false;
25
30
  const failed = (error) => {
26
31
  if (warned)
@@ -29,13 +34,24 @@ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENE
29
34
  warn(`could not say in the store that runner ${runner} is there: ${error instanceof Error ? error.message : String(error)}`);
30
35
  };
31
36
  let at = null;
32
- const row = () => ({ runner, incarnation, refused, host: at?.host ?? null, port: at?.port ?? null });
37
+ let said = refused;
38
+ const row = () => ({ runner, incarnation, refused: said, host: at?.host ?? null, port: at?.port ?? null, version: RUNNER_VERSION, slots });
33
39
  // Its first put takes the name over from an earlier process's row. Every write after it (a renewal, the relay's place:
34
40
  // one Runners.renew, with the place it holds now) touches its own row only, or puts one where no other process of the
35
41
  // name is live (Runners.put unlessLiveMs): an older process overlapping a restart never takes the later one's row back,
36
42
  // nor clears its relay.
37
43
  const again = () => runners.put(row(), { unlessLiveMs: PRESENCE_STALE_MS });
44
+ // A refusal changed (refuse) and not yet on the row: a renewal only marks the row seen, so until a put of the row lands
45
+ // each renewal is that put. A put that fails leaves it unsaid, for the next renewal.
46
+ let unsaid = false;
47
+ const sayRefusal = async () => {
48
+ unsaid = true;
49
+ await again();
50
+ unsaid = false;
51
+ };
38
52
  const renew = async () => {
53
+ if (unsaid)
54
+ return void (await sayRefusal());
39
55
  if (!(await runners.renew(runner, incarnation, at)))
40
56
  await again();
41
57
  };
@@ -57,6 +73,18 @@ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENE
57
73
  writing = wrote.catch(failed);
58
74
  return wrote;
59
75
  },
76
+ refuse(words) {
77
+ if (words === said)
78
+ return Promise.resolve();
79
+ said = words;
80
+ if (stopped)
81
+ return Promise.resolve();
82
+ // Its words are on the row, not on a renewal (Runners.renew writes the seen time and the relay's place alone): the
83
+ // row is put again, its own incarnation's, never over a later process's of the same name.
84
+ const wrote = writing.then(sayRefusal);
85
+ writing = wrote.catch(failed);
86
+ return wrote;
87
+ },
60
88
  async close() {
61
89
  if (stopped)
62
90
  return;
@@ -1,4 +1,3 @@
1
- import { type Stats } from "node:fs";
2
1
  import type { Duplex } from "node:stream";
3
2
  import type { Workspace } from "../workspace/workspace.js";
4
3
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
@@ -74,19 +73,16 @@ export declare class SlotHold {
74
73
  }
75
74
  /** The run's own top folders: its folder (work and recordings beneath it) and its scratch folder. */
76
75
  export declare const runTops: (data: string, agentId: string, runId: string) => string[];
77
- /** Every entry under `dir` the server's user owns, given to group `gid` as the helper's reown gives a slot's: a folder
78
- * the group's to enter and write (2770), a file's owner bits copied to the group, none for others. The whole tree, a
79
- * symlink never followed nor changed (an lstat's). Run while no process of the slot is alive (after its reap), so
80
- * nothing it walks is swapped under it. */
81
- export declare function toSlotGroup(dir: string, gid: number): Promise<void>;
82
- /** The other slots that own an entry anywhere under `dir`, as the helper's reown walks it: the whole tree, a symlink
83
- * never followed (an lstat's, never a directory). `statOf`: the stat it reads (a test's). */
84
- export declare function slotsUnder(dir: string, slot: number, statOf?: (path: string) => Promise<Stats>): Promise<number[]>;
76
+ /** At a claim, before anything of the run is placed: its top folders and everything in them the server's user's again
77
+ * (the helper's `own runner`), whoever an earlier claim left them to. Throws, in words, when they could not be. */
78
+ export declare function takeBackRunFolders(isolation: Extract<RunIsolation, {
79
+ kind: "uid";
80
+ }>, tops: readonly string[]): Promise<void>;
85
81
  /** After the run's process ended: every process of the slot's uid killed, its files in the shared temporary folders
86
- * removed, what it left in its folders readable and removable by the server's group, and its top folders the server's
87
- * own again (0770), which the slot's next run cannot enter. Whether the reap held: the helper kills until no process of
88
- * the uid is left, and says so; false when one still is, or the reap could not run (the slot is then never run on
89
- * again by this runner). */
82
+ * removed, and its top folders with everything in them given back to the server's user (the helper's `own runner`:
83
+ * the server's uid and group, folders 2770), which the slot's next run cannot enter. Whether the reap held: the helper
84
+ * kills until no process of the uid is left, and says so, and the folders were given back; false when a process still
85
+ * is, or either step could not run (the slot is then never run on again by this runner). */
90
86
  export declare function reapSlot(isolation: Extract<RunIsolation, {
91
87
  kind: "uid";
92
88
  }>, slot: number, tops: readonly string[], log: (line: string) => void): Promise<boolean>;
@@ -154,9 +150,10 @@ export declare const childArgv: () => string[];
154
150
  * A built-in learning run (its launch names harness "learning"): its grade is one ask through the runner's model route,
155
151
  * and its one write is the merge into the agent's learning folder, which no run's process may write. An SDK backend
156
152
  * run (launch.sdk): its agent runs in the caller's application, and its loop here reads the evidence it posts and closes
157
- * its inbox. A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
153
+ * its inbox. A CLI capture (launch.cli_learning) likewise only receives source evidence and serves owner corrections.
154
+ * A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
158
155
  * connectors, whose rows are the server's. */
159
- export declare const runsInRunner: (harness: string, launch: Pick<RunLaunch, "sdk" | "native">) => boolean;
156
+ export declare const runsInRunner: (harness: string, launch: Pick<RunLaunch, "sdk" | "native" | "cli_learning">) => boolean;
160
157
  /** The words a run on Claude Code's login on this machine is refused in where each run is a user of its own. */
161
158
  export declare const LOGIN_NEEDS_SERVER_USER = "A run on Claude Code's login on this machine needs runs under the server's own user, and this runner runs each run as a user of its own: set AGENTRUN_RUN_USER=same, or give the run a model_key.";
162
159
  /** Whether run `runId` stays in its runner's process: runsInRunner's, and a workflow run on a server with a documents