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

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 (232) hide show
  1. package/CHANGELOG.md +185 -0
  2. package/README.md +236 -30
  3. package/dist/adapters.js +1 -1
  4. package/dist/agent-delete.d.ts +13 -2
  5. package/dist/agent-delete.js +14 -5
  6. package/dist/agents-store.d.ts +5 -1
  7. package/dist/agents-store.js +17 -7
  8. package/dist/api-only.d.ts +6 -3
  9. package/dist/api-only.js +8 -5
  10. package/dist/archil-routes.d.ts +1 -0
  11. package/dist/archil-routes.js +28 -2
  12. package/dist/capacity.d.ts +50 -0
  13. package/dist/capacity.js +49 -0
  14. package/dist/cli-learning/claude-wire.d.ts +41 -0
  15. package/dist/cli-learning/claude-wire.js +258 -0
  16. package/dist/cli-learning/cli.d.ts +11 -0
  17. package/dist/cli-learning/cli.js +241 -0
  18. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  19. package/dist/cli-learning/codex-worktree.js +119 -0
  20. package/dist/cli-learning/connections.d.ts +62 -0
  21. package/dist/cli-learning/connections.js +87 -0
  22. package/dist/cli-learning/entry.d.ts +1 -0
  23. package/dist/cli-learning/entry.js +4 -0
  24. package/dist/cli-learning/evidence.d.ts +78 -0
  25. package/dist/cli-learning/evidence.js +492 -0
  26. package/dist/cli-learning/hook.d.ts +33 -0
  27. package/dist/cli-learning/hook.js +544 -0
  28. package/dist/cli-learning/install.d.ts +33 -0
  29. package/dist/cli-learning/install.js +335 -0
  30. package/dist/cli-learning/observation-proof.d.ts +14 -0
  31. package/dist/cli-learning/observation-proof.js +10 -0
  32. package/dist/cli-learning/policy.d.ts +48 -0
  33. package/dist/cli-learning/policy.js +363 -0
  34. package/dist/cli-learning/schema.d.ts +16 -0
  35. package/dist/cli-learning/schema.js +27 -0
  36. package/dist/cli-learning/state.d.ts +23 -0
  37. package/dist/cli-learning/state.js +61 -0
  38. package/dist/cli.js +24 -2
  39. package/dist/computer-setting.d.ts +8 -0
  40. package/dist/computer-setting.js +11 -0
  41. package/dist/computers.d.ts +6 -2
  42. package/dist/computers.js +2 -2
  43. package/dist/console/assets/index-B-D0EM3j.js +733 -0
  44. package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
  45. package/dist/console/index.html +2 -2
  46. package/dist/email/email-faux.d.ts +3 -1
  47. package/dist/email/email-faux.js +3 -2
  48. package/dist/email/routes.js +22 -12
  49. package/dist/fal-price.d.ts +76 -0
  50. package/dist/fal-price.js +368 -0
  51. package/dist/harness-install.d.ts +6 -2
  52. package/dist/harness-install.js +40 -8
  53. package/dist/harness.d.ts +1 -1
  54. package/dist/harness.js +2 -2
  55. package/dist/learn/commit.d.ts +5 -0
  56. package/dist/learn/commit.js +4 -1
  57. package/dist/learn/compile.d.ts +13 -5
  58. package/dist/learn/compile.js +24 -7
  59. package/dist/learn/delete.d.ts +12 -6
  60. package/dist/learn/delete.js +17 -11
  61. package/dist/learn/folder.d.ts +11 -0
  62. package/dist/learn/folder.js +20 -3
  63. package/dist/learn/learning-of.d.ts +8 -0
  64. package/dist/learn/learning-of.js +8 -0
  65. package/dist/learn/learning.sh +14 -1
  66. package/dist/learn/promote.d.ts +51 -7
  67. package/dist/learn/promote.js +51 -8
  68. package/dist/learn/secrets.js +14 -3
  69. package/dist/learning-reset.d.ts +18 -0
  70. package/dist/learning-reset.js +115 -0
  71. package/dist/learning-routes.d.ts +1 -1
  72. package/dist/learning-words.d.ts +6 -1
  73. package/dist/learning-words.js +6 -1
  74. package/dist/learning.d.ts +8 -6
  75. package/dist/learning.js +5 -4
  76. package/dist/llms.txt +1 -0
  77. package/dist/mcp-gateway.d.ts +39 -2
  78. package/dist/mcp-gateway.js +41 -10
  79. package/dist/mcp-pin-first.js +3 -2
  80. package/dist/mcp-private-hosts.d.ts +24 -3
  81. package/dist/mcp-private-hosts.js +53 -3
  82. package/dist/mcp-servers-store.d.ts +1 -0
  83. package/dist/mcp-servers-store.js +2 -1
  84. package/dist/media-duration.d.ts +2 -0
  85. package/dist/media-duration.js +136 -0
  86. package/dist/model-gateway.d.ts +2 -0
  87. package/dist/model-gateway.js +3 -1
  88. package/dist/native/runtimes.d.ts +2 -0
  89. package/dist/native/runtimes.js +2 -0
  90. package/dist/observation/learning.d.ts +32 -0
  91. package/dist/observation/learning.js +66 -0
  92. package/dist/observation/observer.d.ts +8 -1
  93. package/dist/observation/observer.js +89 -9
  94. package/dist/observation/schema.js +12 -4
  95. package/dist/observation/usage-identity.d.ts +9 -0
  96. package/dist/observation/usage-identity.js +11 -0
  97. package/dist/openapi.js +133 -24
  98. package/dist/provider.d.ts +8 -0
  99. package/dist/provider.js +14 -2
  100. package/dist/refusal-words.d.ts +0 -3
  101. package/dist/refusal-words.js +0 -3
  102. package/dist/request-metadata.d.ts +20 -0
  103. package/dist/request-metadata.js +24 -0
  104. package/dist/run-launch.d.ts +27 -4
  105. package/dist/run-launch.js +18 -3
  106. package/dist/run-learning-served.d.ts +2 -2
  107. package/dist/run-usage.d.ts +48 -4
  108. package/dist/run-usage.js +156 -39
  109. package/dist/run-view.d.ts +2 -0
  110. package/dist/run-view.js +8 -7
  111. package/dist/runner/adapter-loop.d.ts +3 -1
  112. package/dist/runner/adapter-loop.js +41 -35
  113. package/dist/runner/adapter-run-spec.d.ts +1 -1
  114. package/dist/runner/adapter-run-spec.js +15 -15
  115. package/dist/runner/audit.d.ts +8 -3
  116. package/dist/runner/audit.js +21 -6
  117. package/dist/runner/beside.d.ts +13 -0
  118. package/dist/runner/beside.js +27 -8
  119. package/dist/runner/claim-secrets.d.ts +2 -1
  120. package/dist/runner/claim-secrets.js +5 -3
  121. package/dist/runner/cli-run-spec.d.ts +1 -1
  122. package/dist/runner/cli-run-spec.js +14 -13
  123. package/dist/runner/conformance/harness.js +4 -2
  124. package/dist/runner/disk-free.d.ts +44 -0
  125. package/dist/runner/disk-free.js +96 -0
  126. package/dist/runner/dispatch.js +4 -2
  127. package/dist/runner/feedback-round.d.ts +12 -8
  128. package/dist/runner/feedback-round.js +16 -30
  129. package/dist/runner/harness-loops.js +8 -3
  130. package/dist/runner/journal-kinds.d.ts +4 -1
  131. package/dist/runner/learning-end.d.ts +2 -1
  132. package/dist/runner/learning-end.js +51 -22
  133. package/dist/runner/main.d.ts +17 -6
  134. package/dist/runner/main.js +187 -45
  135. package/dist/runner/mcp-claim.js +1 -1
  136. package/dist/runner/mcp-run.d.ts +9 -0
  137. package/dist/runner/mcp-run.js +16 -1
  138. package/dist/runner/model-route.js +7 -4
  139. package/dist/runner/presence.d.ts +11 -2
  140. package/dist/runner/presence.js +31 -3
  141. package/dist/runner/promotion.d.ts +40 -21
  142. package/dist/runner/promotion.js +130 -59
  143. package/dist/runner/run-child-host.d.ts +12 -15
  144. package/dist/runner/run-child-host.js +52 -112
  145. package/dist/runner/run-errors.js +2 -0
  146. package/dist/runner/runner-check.d.ts +51 -0
  147. package/dist/runner/runner-check.js +206 -0
  148. package/dist/runner/runner-metrics.d.ts +19 -0
  149. package/dist/runner/runner-metrics.js +49 -0
  150. package/dist/runner/runner.d.ts +37 -0
  151. package/dist/runner/runner.js +58 -6
  152. package/dist/runner/sdk-loop.d.ts +2 -2
  153. package/dist/runner/sdk-loop.js +37 -25
  154. package/dist/runner/store-port.d.ts +3 -0
  155. package/dist/runner/workflow-spec.js +3 -3
  156. package/dist/runs-over-store.d.ts +13 -3
  157. package/dist/runs-over-store.js +71 -16
  158. package/dist/sdk/check.d.ts +6 -5
  159. package/dist/sdk/check.js +17 -16
  160. package/dist/sdk/runs.d.ts +22 -2
  161. package/dist/sdk/runs.js +167 -82
  162. package/dist/server.d.ts +3 -0
  163. package/dist/server.js +230 -43
  164. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  165. package/dist/start-switches.js +2 -0
  166. package/dist/stats.d.ts +4 -0
  167. package/dist/stats.js +1 -1
  168. package/dist/store/agent-body.d.ts +16 -0
  169. package/dist/store/agent-body.js +20 -3
  170. package/dist/store/dialect.d.ts +2 -0
  171. package/dist/store/dialect.js +1 -0
  172. package/dist/store/index.d.ts +3 -3
  173. package/dist/store/index.js +2 -2
  174. package/dist/store/journal/storage.d.ts +2 -0
  175. package/dist/store/journal/storage.js +2 -1
  176. package/dist/store/postgres/connection.d.ts +5 -2
  177. package/dist/store/postgres/connection.js +19 -7
  178. package/dist/store/postgres/dialect.js +1 -0
  179. package/dist/store/postgres/migrate.d.ts +30 -0
  180. package/dist/store/postgres/migrate.js +72 -5
  181. package/dist/store/postgres/migration-lint.d.ts +8 -0
  182. package/dist/store/postgres/migration-lint.js +119 -0
  183. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  184. package/dist/store/postgres/migrations/0025_run_attempts.sql +27 -0
  185. package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
  186. package/dist/store/postgres/store.d.ts +8 -3
  187. package/dist/store/postgres/store.js +31 -11
  188. package/dist/store/schema.d.ts +32 -2
  189. package/dist/store/schema.js +74 -5
  190. package/dist/store/sqlite/run-launch.d.ts +31 -1
  191. package/dist/store/sqlite/run-launch.js +111 -2
  192. package/dist/store/sqlite/run-patch.d.ts +2 -1
  193. package/dist/store/sqlite/run-patch.js +4 -3
  194. package/dist/store/sqlite/store.d.ts +17 -0
  195. package/dist/store/sqlite/store.js +226 -37
  196. package/dist/store/store-schema.d.ts +34 -0
  197. package/dist/store/store-schema.js +125 -0
  198. package/dist/store/store.d.ts +120 -5
  199. package/dist/store/store.js +13 -0
  200. package/dist/store-reads/analytics.d.ts +3 -2
  201. package/dist/store-reads/analytics.js +20 -8
  202. package/dist/store-reads/learning.d.ts +12 -8
  203. package/dist/store-reads/learning.js +33 -24
  204. package/dist/store-reads/loop.d.ts +4 -3
  205. package/dist/store-reads/loop.js +7 -5
  206. package/dist/store-view.d.ts +4 -3
  207. package/dist/store-view.js +11 -7
  208. package/dist/template-eval.js +4 -4
  209. package/dist/templates.d.ts +6 -2
  210. package/dist/templates.js +7 -5
  211. package/dist/timeline/labels.js +1 -1
  212. package/dist/tool-gate.d.ts +4 -2
  213. package/dist/tools.js +1 -1
  214. package/dist/unified-usage.d.ts +24 -0
  215. package/dist/unified-usage.js +400 -0
  216. package/dist/uploads-archil.d.ts +100 -0
  217. package/dist/uploads-archil.js +431 -0
  218. package/dist/uploads.d.ts +52 -1
  219. package/dist/uploads.js +186 -108
  220. package/dist/validate.js +5 -1
  221. package/dist/web-save.d.ts +3 -0
  222. package/dist/web-save.js +17 -2
  223. package/dist/workspace/archil-disk.d.ts +6 -5
  224. package/dist/workspace/archil-disk.js +27 -12
  225. package/dist/workspace/archil-exec.js +1 -1
  226. package/dist/workspace/archil.js +4 -3
  227. package/dist/workspace/revision-skills.js +24 -11
  228. package/dist/workspace/synced-folder.d.ts +3 -3
  229. package/dist/workspace/synced-folder.js +7 -6
  230. package/package.json +10 -10
  231. package/skills/agentrun-serve/SKILL.md +52 -7
  232. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -17,7 +17,9 @@
17
17
  // keeps sealed (store-secrets.ts storeSecrets), the runner's secrets, the keys its claim handed it, and the sign-in
18
18
  // pointers its row says it was handed, read back from the store (handed-values.ts handedValuesOf). A run whose
19
19
  // pointers can't be read back learns nothing (the hook drops it, saying why), never over a shorter list.
20
- // A run whose seed could not be read keeps that drop.
20
+ // A run whose seed could not be read keeps that drop. A run whose seed was read at or before a reset of its agent's
21
+ // learning learns nothing at all, dropped at its entry with reason `reset`. Every read of the agent's runs here reads
22
+ // only those after the reset (learn/compile.ts sinceReset).
21
23
  import { createHash } from "node:crypto";
22
24
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
25
  import { isMessageRow } from "../timeline/index.js";
@@ -25,10 +27,11 @@ import { correctionRefused, learningCommit } from "../learn/commit.js";
25
27
  import { CAPS, checkDraft, problemWords, unstorable } from "../learn/index.js";
26
28
  import { repickSiteOf } from "../learn/check.js";
27
29
  import { repickLabelOf, repickRewrite } from "../learn/repick.js";
28
- import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
29
- import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
30
+ import { folderAt, holdsCommit, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
31
+ import { completedRun, compileStoppedOf, lastOwnRuns, sinceReset, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, draftFailedOf, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
32
+ import { reviseAttemptOf } from "./promotion.js";
30
33
  import { loopOf, repickOf } from "../learning-setting.js";
31
- import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion } from "../learn/promote.js";
34
+ import { CHECK_TEXT_MAX, promotionOf, promotionsOf, recordPromotion, resetAtOf } from "../learn/promote.js";
32
35
  import { draftDecisionProviders, draftDryRun, draftFiles, draftMcpTools, unpricedCalls, WORKFLOWS_DIR } from "../learn/workflow-draft.js";
33
36
  import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
34
37
  import { handedValuesOf } from "../handed-values.js";
@@ -36,7 +39,7 @@ import { excerptShown, MIN_SECRET, redactSecrets } from "../learn/secrets.js";
36
39
  import { LEARNED_WORKFLOW_TOOL } from "../learned-workflow.js";
37
40
  import { META_TOOLS } from "../meta-tool-names.js";
38
41
  import { holdsSecret, LEARNING_LABEL, secretsShown } from "../learning.js";
39
- import { said, STOPPED } from "../learning-words.js";
42
+ import { said, seedStopped } from "../learning-words.js";
40
43
  import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
41
44
  import { FINAL_STATES } from "../store/store.js";
42
45
  import { shadowRunId } from "../learn/audit.js";
@@ -64,7 +67,7 @@ export function learningEndOfRun(launch, deps) {
64
67
  if (held())
65
68
  return heldEndOfRun();
66
69
  const env = deps.env ?? process.env;
67
- const hookFor = (seed, round) => createReflectHook({
70
+ const hookFor = (seed, round, mustHold) => createReflectHook({
68
71
  round,
69
72
  // A run its cap stopped has no room left, and one whose spend is unknown under a cap cannot be kept within it. The cap
70
73
  // is the run's now (capNowOf: its newest raise's, else its launch's), the one its requests were admitted under. Its
@@ -92,6 +95,10 @@ export function learningEndOfRun(launch, deps) {
92
95
  // A grade's feedback round always has something new, the grade's words (feedback-round.ts), whatever the job did.
93
96
  nothingNew: async (runId) => !pendingFeedbackOf(await runEntries(deps.store, runId, BACKGROUND_CONTEXT)) && onlyLearnedWorkflows(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })),
94
97
  feedback: async (runId) => {
98
+ // A source hook uploads task dialogue, not owner feedback addressed to AgentRun.
99
+ // CLI corrections are written explicitly through the owner corrections API.
100
+ if (launch.cli_learning)
101
+ return [];
95
102
  const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
96
103
  return ownerWords(entries, rows);
97
104
  },
@@ -126,7 +133,7 @@ export function learningEndOfRun(launch, deps) {
126
133
  commit: async ({ runId, agentId, round: at, draft, correction, refuse }) => {
127
134
  const reason = draft ? `Compiled the job as workflow ${draft.name}${correction !== undefined ? ", with its owner's correction" : ""}.` : "Its owner's correction.";
128
135
  const done = await commitDirect({ folder: () => deps.learningFolder(agentId), log: deps.log ?? (() => undefined) }, {
129
- runId, round: at, reason, seed, files: draft ? draft.files.map((file) => ({ ...file })) : [],
136
+ runId, round: at, reason, seed, ...(mustHold ? { mustHold } : {}), files: draft ? draft.files.map((file) => ({ ...file })) : [],
130
137
  ...(draft?.held?.length ? { held: [...draft.held] } : {}), ...(draft?.bases ? { bases: draft.bases } : {}),
131
138
  ...(correction !== undefined ? { correction, refuseValues: refuse } : {}),
132
139
  });
@@ -138,15 +145,26 @@ export function learningEndOfRun(launch, deps) {
138
145
  // Why, as its start recorded it: a folder that could not be read, or a start that could not be made from it; a
139
146
  // start that records none names no reason.
140
147
  if (seedFailed(start)) {
141
- const failed = start.seedFailed;
142
- const why = failed === "unreadable" ? STOPPED.unreadable : failed === "not_copied" ? STOPPED.notCopied : STOPPED.noSeed;
148
+ const why = seedStopped(start.seedFailed);
143
149
  // Every end of it: the first's drop stands for a later one (the store keeps one a round, so it adds nothing new).
144
150
  return { also: [{ table: "learning_proposals", row: { turn: null, proposal: { state: "dropped", reason: "seed_failed", detail: said.stopped(why) } } }] };
145
151
  }
152
+ // The one check at the entry of a run's learning end, before any merge, look-back, compile, draft check or record: a
153
+ // run whose seed was read at or before a reset of its agent's learning (its watermark, learn/promote.ts resetAtOf; a
154
+ // start that records no time is read as before it) learns nothing, whole. Its corrections and compile would land on
155
+ // what the reset left. Read by time alone: a Mode 2 run's end writes the folder on its disk, which never held the
156
+ // seed the server read from its own folder, so a commit missing here says nothing of a reset.
157
+ const reset = await resetAtOf(deps.store.settings, input.agentId);
158
+ if (reset !== undefined && !(start.seededAt !== undefined && start.seededAt > reset)) {
159
+ return { also: [{ table: "learning_proposals", row: { turn: null, proposal: { state: "dropped", reason: "reset", detail: said.reset } } }] };
160
+ }
161
+ // The second wall, once the agent's learning was reset: a seed this folder holds now is one its merge must still
162
+ // find (commit.ts mustHold), so a reset after this check refuses the merge whole in the script.
163
+ const mustHold = reset !== undefined && (await withFolder(deps, input.agentId, (folder) => holdsCommit(folder.workspace, start.seed))) ? start.seed : undefined;
146
164
  // Which end of the run this is: the round after the newest it kept (a follow-up opened the run again after it), else
147
165
  // its first. A replayed end reads the same round: its rows are written only with the end that closes it.
148
166
  const prior = await deps.store.learning.proposal(input.runId);
149
- return hookFor(start.seed, prior ? prior.round + 1 : 1)(input);
167
+ return hookFor(start.seed, prior ? prior.round + 1 : 1, mustHold)(input);
150
168
  };
151
169
  }
152
170
  /** What every cap gate of run `runId` reads as spent beside it on its behalf (adapter-loop.ts RunCapConfig.beside): its
@@ -460,20 +478,23 @@ const workflowText = (doc) => {
460
478
  const text = `${JSON.stringify(doc, null, 2)}\n`;
461
479
  return Buffer.byteLength(text) <= CAPS.file ? text : `${JSON.stringify(doc)}\n`;
462
480
  };
481
+ /** The digest of the failed-draft record run `runId`'s compile keeps (recordDraftFailed): one per run. */
482
+ const draftFailedDigest = (runId) => createHash("sha256").update(`draft-failed\n${runId}`).digest("hex").slice(0, 16);
463
483
  /** Compile once: run `runId`'s compile turn whose drafts all failed their checks is the compile's attempt, kept as a
464
484
  * promotion record of the shape a check's stop has (runner/promotion.ts stopUnchecked): a hold with nothing checked,
465
485
  * its reason (DRAFT_FAILED) naming the failed checks. A first compile's earns the one recompile, as a check's hold
466
486
  * does (the agent's next due run compiles once more: learn/compile.ts newCompileAttempt); a recompile's (a revision of
467
487
  * a held workflow, or a new one after a first compile's failed drafts) stops (compileStoppedOf, heldNamesOf): nothing
468
- * compiles it again. One record per run (its digest is the run's), written once: a claim that ends the run again
488
+ * compiles it again. A revision of a connected agent's hold on give-backs is no recompile (runner/promotion.ts
489
+ * reviseAttemptOf). One record per run (its digest is the run's), written once: a claim that ends the run again
469
490
  * writes none. */
470
491
  export async function recordDraftFailed(deps, input) {
471
492
  try {
472
493
  const records = await promotionsOf(deps.store.settings, input.agentId);
473
- const attempt = input.compile.mode === "revise" ? 2 : newCompileAttempt(records);
494
+ const attempt = input.compile.mode === "revise" ? reviseAttemptOf(records, input.compile.held) : newCompileAttempt(records);
474
495
  const { compile_after, agree_min, alone_min } = await loopOfRun(deps.store, input.runId);
475
496
  const workflow = input.compile.mode === "revise" ? input.compile.workflow : input.workflow;
476
- const digest = createHash("sha256").update(`draft-failed\n${input.runId}`).digest("hex").slice(0, 16);
497
+ const digest = draftFailedDigest(input.runId);
477
498
  const failed = input.errors.join("; ").slice(0, CHECK_TEXT_MAX) || "no draft passed";
478
499
  const reason = `${DRAFT_FAILED}: ${failed}. ${attempt === 2 ? "It was the recompile, so it stops: nothing compiles again until its owner acts" : "It is not promoted; the next due run compiles it once more"}`;
479
500
  const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
@@ -526,19 +547,23 @@ export function traceFrom(timeline, refuse) {
526
547
  * session, also carries the owner's standing corrections it was laid with (`corrections`, its # Learned section), as an
527
548
  * in-session compile reads them in its session. Undefined when it compiles nothing, or when the folder can't be read. */
528
549
  export async function compileAskOf(deps, input) {
550
+ const { agentId } = input;
529
551
  // A revision is asked only of a workflow its promotion holds, once per hold. The workflows whose newest revision other
530
552
  // than their champion (learn/promote.ts championOf: it serves while that one is held) is held: the run's own may be one.
531
- const records = await promotionsOf(deps.store.settings, input.agentId).catch(() => []);
553
+ const records = await promotionsOf(deps.store.settings, agentId).catch(() => []);
532
554
  const heldNames = heldNamesOf(records);
533
555
  // The loop's numbers on the agent's definition (the revision this run runs): the first compile waits for compile_after
534
556
  // completed agent runs, the ending one counted.
535
557
  const { compile_after: compileAfter } = await loopOfRun(deps.store, input.runId);
536
- // The agent's latest runs, newest first: those after the ending one in the list started before it.
537
- const listed = await deps.store.runs.list({ agentId: input.agentId, limit: Math.max(200, 2 * compileAfter) });
558
+ // The agent's latest runs, newest first: those after the ending one in the list started before it, and after its
559
+ // learning's reset (sinceReset): a run before the reset is never a compile's trace. None on a named disk: it learns
560
+ // nothing (learn/learning-of.ts).
561
+ const listed = await deps.store.runs.list({ agentId, disk: null, limit: Math.max(200, 2 * compileAfter) });
538
562
  const at = listed.findIndex((run) => run.id === input.runId);
539
- const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === input.agentId);
563
+ const since = await sinceReset(deps.store, agentId);
564
+ const earlier = (at < 0 ? listed : listed.slice(at + 1)).filter((run) => run.agentId === agentId && since(run));
540
565
  const done = earlier.filter(completedRun);
541
- const byHand = (await lastOwnRuns(deps.store, input.agentId, compileAfter, input.runId)).length;
566
+ const byHand = (await lastOwnRuns(deps.store, agentId, compileAfter, input.runId)).length;
542
567
  const dueWith = (workflows) => compileDue({ completed: input.outcome === "completed", runs: byHand + (input.outcome === "completed" ? 1 : 0), workflows, compileAfter });
543
568
  const compiledOf = (kept) => kept?.proposal?.compiled;
544
569
  // Compile once: a recompile whose drafts failed their checks stopped the agent's new compiles (recordDraftFailed).
@@ -613,10 +638,14 @@ export async function compileAskOf(deps, input) {
613
638
  if (read.held) {
614
639
  // Once per hold: a run since it that compiled this workflow asked already, whatever came of it (its revision is on its
615
640
  // way to a replay, or its draft failed its checks), however many runs ago. Read from the agent's kept learning since
616
- // the hold, never a window of its last runs; one that can't be read asks nothing.
617
- const since = Date.parse(read.held.at);
618
- const kept = await deps.store.learning.proposals(input.agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
619
- if (!kept || kept.some((one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow))
641
+ // the hold, never a window of its last runs; one that can't be read asks nothing. A draft that failed since, not stopped
642
+ // (only a revise of a connected agent's hold on give-backs: reviseAttemptOf), asks once more: counted from it, its own
643
+ // run's kept learning (written after its record, at the run's end) not counted.
644
+ const failed = records.findLast((one) => one.workflow === read.held.workflow && draftFailedOf(one) && !one.check?.stopped && !(one.at < read.held.at));
645
+ const since = Date.parse(failed?.at ?? read.held.at);
646
+ const kept = await deps.store.learning.proposals(agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
647
+ const asked = (one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow && draftFailedDigest(one.runId) !== failed?.digest;
648
+ if (!kept || kept.some(asked))
620
649
  return sayLeftOut(), undefined;
621
650
  const { workflow, digest, reason, check, audit } = read.held;
622
651
  // A check's or an audit's disagreements are the agent's own inputs and answers: cut of the run's secrets as a trace is
@@ -37,6 +37,9 @@ export interface RunnerProcessOptions {
37
37
  storeUrl?: string;
38
38
  /** What a person should see at the start (a clock far from the store's Postgres): stderr by default. */
39
39
  warn?: (message: string) => void;
40
+ /** How often the store's runner floor is read again (Store.schemaState): each renewal (RUNNER_RENEW_EVERY_MS) unless a
41
+ * test says. */
42
+ floorEveryMs?: number;
40
43
  }
41
44
  export interface RunnerProcess {
42
45
  readonly runner: Runner;
@@ -48,6 +51,10 @@ export interface RunnerProcess {
48
51
  /** What its runs may hold, in MiB (RunnerMemory.budgetMib): its host's memory, or its container's limit, less the
49
52
  * server's own. Said once at its start, after the ready line. */
50
53
  readonly memoryMib: number;
54
+ /** Settles, once, with the words of why, when the store's runner floor rises above the version this build knows (a
55
+ * later server applied a migration that breaks earlier runners): this runner should close, handing its runs back, and
56
+ * its process exit non-zero. Never settles otherwise. */
57
+ readonly outdated: Promise<string>;
51
58
  /** Closes the runner (its loops stopped, its runs released), then its store connection. */
52
59
  close(): Promise<void>;
53
60
  }
@@ -157,12 +164,16 @@ export declare function runnerArgs(argv: readonly string[]): {
157
164
  faux?: string;
158
165
  fauxBrowser?: string;
159
166
  check?: true;
167
+ envOnly?: true;
168
+ heartbeatOnly?: true;
160
169
  harnessModules?: string[];
161
170
  };
162
- /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
163
- * says the runner is ready (on a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one
164
- * that came before the handlers would end the process unclosed. */
165
- export declare function runUntilSignalled(process: RunnerProcess, signals?: readonly NodeJS.Signals[], ready?: () => void): Promise<void>;
171
+ /** Runs until SIGTERM or SIGINT, or until the store's runner floor rises above this runner (RunnerProcess.outdated),
172
+ * then closes: nothing more claimed, the drain, its runs handed back. Answers the floor's words when that was the stop,
173
+ * else undefined. `ready` is called once the signals are handled, never before: a line that says the runner is ready (on
174
+ * a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one that came before the
175
+ * handlers would end the process unclosed. `outdated`: told the floor's words before the close begins. */
176
+ export declare function runUntilSignalled(process: Pick<RunnerProcess, "close"> & Partial<Pick<RunnerProcess, "outdated">>, signals?: readonly NodeJS.Signals[], ready?: () => void, outdated?: (why: string) => void): Promise<string | undefined>;
166
177
  /** The runner process's last resort (runnerMain installs it for unhandledRejection and uncaughtException): says what
167
178
  * went wrong, in the runner's name with its stack, then exits 1 at once, closing nothing. A runner that went on after
168
179
  * an error nothing handled could keep renewing the claim of a run whose loop is dead, and that run would hang claimed
@@ -175,8 +186,8 @@ export declare function lastResort(name: string, write?: (line: string) => void,
175
186
  * lapse of every claim at once shows its cause. */
176
187
  export declare function troubleLine(name: string, event: RunnerEvent): string | undefined;
177
188
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store this runner cannot open (a schema it does not
178
- * know, none set up yet, or one its server has yet to upgrade); 1: anything else; 0: closed on a signal, or --check found
179
- * a fresh heartbeat. AGENTRUN_RUNNER_NAME names it when --name does not. */
189
+ * know, none set up yet, or one its server has yet to upgrade), or one whose runner floor rose above it while it ran
190
+ * (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. */
180
191
  export declare function runnerMain(argv: readonly string[], given?: NodeJS.ProcessEnv, hooks?: RunnerMainHooks): Promise<number>;
181
192
  /** A test's hooks into runnerMain: `started`, awaited once the runner has started claiming and before its stop handlers
182
193
  * take over from the ones its start listened on (the window a stop must not fall through). */
@@ -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"];