@parcha/agentrun-serve 0.1.0-beta.49 → 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 (216) hide show
  1. package/CHANGELOG.md +173 -9
  2. package/README.md +246 -39
  3. package/dist/agent-delete.d.ts +3 -2
  4. package/dist/agent-delete.js +29 -4
  5. package/dist/agents-store.js +7 -3
  6. package/dist/api-only.d.ts +8 -10
  7. package/dist/api-only.js +11 -12
  8. package/dist/capacity.d.ts +50 -0
  9. package/dist/capacity.js +49 -0
  10. package/dist/cli-learning/claude-wire.d.ts +41 -0
  11. package/dist/cli-learning/claude-wire.js +258 -0
  12. package/dist/cli-learning/cli.d.ts +11 -0
  13. package/dist/cli-learning/cli.js +241 -0
  14. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  15. package/dist/cli-learning/codex-worktree.js +119 -0
  16. package/dist/cli-learning/connections.d.ts +62 -0
  17. package/dist/cli-learning/connections.js +87 -0
  18. package/dist/cli-learning/entry.d.ts +1 -0
  19. package/dist/cli-learning/entry.js +4 -0
  20. package/dist/cli-learning/evidence.d.ts +78 -0
  21. package/dist/cli-learning/evidence.js +492 -0
  22. package/dist/cli-learning/hook.d.ts +33 -0
  23. package/dist/cli-learning/hook.js +544 -0
  24. package/dist/cli-learning/install.d.ts +33 -0
  25. package/dist/cli-learning/install.js +335 -0
  26. package/dist/cli-learning/observation-proof.d.ts +14 -0
  27. package/dist/cli-learning/observation-proof.js +10 -0
  28. package/dist/cli-learning/policy.d.ts +48 -0
  29. package/dist/cli-learning/policy.js +363 -0
  30. package/dist/cli-learning/schema.d.ts +16 -0
  31. package/dist/cli-learning/schema.js +27 -0
  32. package/dist/cli-learning/state.d.ts +23 -0
  33. package/dist/cli-learning/state.js +61 -0
  34. package/dist/cli.js +24 -2
  35. package/dist/compute-cost.d.ts +101 -0
  36. package/dist/compute-cost.js +250 -0
  37. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  38. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/email/email-faux.d.ts +3 -1
  41. package/dist/email/email-faux.js +3 -2
  42. package/dist/email/routes.js +22 -12
  43. package/dist/eval-previous.d.ts +52 -0
  44. package/dist/eval-previous.js +164 -0
  45. package/dist/file-types.d.ts +2 -0
  46. package/dist/file-types.js +3 -1
  47. package/dist/harness-install.d.ts +6 -2
  48. package/dist/harness-install.js +40 -8
  49. package/dist/harness.d.ts +1 -1
  50. package/dist/harness.js +3 -2
  51. package/dist/learn/check.d.ts +8 -5
  52. package/dist/learn/check.js +25 -24
  53. package/dist/learn/repick.d.ts +22 -13
  54. package/dist/learn/repick.js +57 -56
  55. package/dist/learn/secrets.js +14 -3
  56. package/dist/learn/workflow-draft.d.ts +4 -0
  57. package/dist/learn/workflow-draft.js +10 -7
  58. package/dist/learned-workflow.js +8 -8
  59. package/dist/learning-setting.js +2 -2
  60. package/dist/learning-words.d.ts +1 -1
  61. package/dist/learning-words.js +1 -1
  62. package/dist/mcp-pin-first.js +2 -1
  63. package/dist/mcp-private-hosts.d.ts +24 -3
  64. package/dist/mcp-private-hosts.js +53 -3
  65. package/dist/model-gateway.d.ts +2 -0
  66. package/dist/model-gateway.js +3 -1
  67. package/dist/native/runtimes.d.ts +2 -0
  68. package/dist/native/runtimes.js +2 -0
  69. package/dist/observation/learning.d.ts +32 -0
  70. package/dist/observation/learning.js +66 -0
  71. package/dist/observation/observer.d.ts +8 -1
  72. package/dist/observation/observer.js +89 -9
  73. package/dist/observation/schema.js +12 -4
  74. package/dist/observation/usage-identity.d.ts +9 -0
  75. package/dist/observation/usage-identity.js +11 -0
  76. package/dist/openapi.js +113 -29
  77. package/dist/paid-calls.d.ts +13 -6
  78. package/dist/paid-calls.js +14 -8
  79. package/dist/run-launch.d.ts +16 -2
  80. package/dist/run-launch.js +6 -1
  81. package/dist/run-timeline-served.js +5 -3
  82. package/dist/run-usage.d.ts +23 -8
  83. package/dist/run-usage.js +100 -18
  84. package/dist/run-view.d.ts +2 -0
  85. package/dist/run-view.js +12 -7
  86. package/dist/runner/adapter-loop.d.ts +4 -0
  87. package/dist/runner/adapter-loop.js +44 -27
  88. package/dist/runner/adapter-run-spec.d.ts +8 -3
  89. package/dist/runner/adapter-run-spec.js +15 -8
  90. package/dist/runner/beside.d.ts +13 -0
  91. package/dist/runner/beside.js +27 -8
  92. package/dist/runner/big-writes.d.ts +33 -0
  93. package/dist/runner/big-writes.js +105 -0
  94. package/dist/runner/cli-run-spec.js +16 -8
  95. package/dist/runner/disk-free.d.ts +44 -0
  96. package/dist/runner/disk-free.js +96 -0
  97. package/dist/runner/feedback-round.d.ts +12 -8
  98. package/dist/runner/feedback-round.js +16 -30
  99. package/dist/runner/harness-loops.js +3 -1
  100. package/dist/runner/held.d.ts +4 -1
  101. package/dist/runner/journal-kinds.d.ts +1 -1
  102. package/dist/runner/learning-end.js +13 -4
  103. package/dist/runner/main.d.ts +17 -6
  104. package/dist/runner/main.js +187 -45
  105. package/dist/runner/metrics.d.ts +4 -0
  106. package/dist/runner/metrics.js +9 -0
  107. package/dist/runner/presence.d.ts +11 -2
  108. package/dist/runner/presence.js +31 -3
  109. package/dist/runner/run-child-host.d.ts +27 -17
  110. package/dist/runner/run-child-host.js +70 -116
  111. package/dist/runner/run-child.js +3 -0
  112. package/dist/runner/run-errors.js +2 -0
  113. package/dist/runner/runner-check.d.ts +51 -0
  114. package/dist/runner/runner-check.js +206 -0
  115. package/dist/runner/runner-metrics.d.ts +19 -0
  116. package/dist/runner/runner-metrics.js +49 -0
  117. package/dist/runner/runner.d.ts +37 -0
  118. package/dist/runner/runner.js +43 -3
  119. package/dist/runner/save-slots.d.ts +9 -0
  120. package/dist/runner/save-slots.js +91 -0
  121. package/dist/runner/sdk-loop.js +34 -22
  122. package/dist/runs-over-store.d.ts +8 -1
  123. package/dist/runs-over-store.js +57 -9
  124. package/dist/sdk/runs.d.ts +25 -6
  125. package/dist/sdk/runs.js +107 -35
  126. package/dist/sdk/runtimes.d.ts +19 -0
  127. package/dist/sdk/runtimes.js +23 -0
  128. package/dist/sdk/schema.d.ts +14 -8
  129. package/dist/sdk/schema.js +18 -6
  130. package/dist/server.d.ts +7 -0
  131. package/dist/server.js +151 -28
  132. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  133. package/dist/start-switches.js +2 -0
  134. package/dist/stats.d.ts +4 -0
  135. package/dist/stats.js +1 -1
  136. package/dist/store/agent-body.d.ts +13 -2
  137. package/dist/store/agent-body.js +19 -4
  138. package/dist/store/dialect.d.ts +2 -0
  139. package/dist/store/dialect.js +1 -0
  140. package/dist/store/index.d.ts +3 -3
  141. package/dist/store/index.js +2 -2
  142. package/dist/store/postgres/connection.d.ts +5 -2
  143. package/dist/store/postgres/connection.js +19 -7
  144. package/dist/store/postgres/dialect.js +1 -0
  145. package/dist/store/postgres/migrate.d.ts +30 -0
  146. package/dist/store/postgres/migrate.js +72 -5
  147. package/dist/store/postgres/migration-lint.d.ts +8 -0
  148. package/dist/store/postgres/migration-lint.js +119 -0
  149. package/dist/store/postgres/migrations/0023_computer_interval_resources.sql +14 -0
  150. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  151. package/dist/store/postgres/store.d.ts +8 -3
  152. package/dist/store/postgres/store.js +31 -11
  153. package/dist/store/schema.d.ts +26 -4
  154. package/dist/store/schema.js +45 -4
  155. package/dist/store/sqlite/connection.d.ts +3 -3
  156. package/dist/store/sqlite/connection.js +3 -3
  157. package/dist/store/sqlite/run-launch.d.ts +9 -1
  158. package/dist/store/sqlite/run-launch.js +44 -0
  159. package/dist/store/sqlite/store.d.ts +19 -4
  160. package/dist/store/sqlite/store.js +180 -93
  161. package/dist/store/store-schema.d.ts +34 -0
  162. package/dist/store/store-schema.js +125 -0
  163. package/dist/store/store.d.ts +61 -2
  164. package/dist/store/store.js +13 -0
  165. package/dist/store-reads/analytics.d.ts +3 -2
  166. package/dist/store-reads/analytics.js +20 -8
  167. package/dist/store-reads/cap.d.ts +9 -5
  168. package/dist/store-reads/cap.js +28 -2
  169. package/dist/store-reads/decisions.d.ts +21 -0
  170. package/dist/store-reads/decisions.js +22 -0
  171. package/dist/store-reads/journal.d.ts +8 -2
  172. package/dist/store-reads/journal.js +27 -8
  173. package/dist/store-view.d.ts +9 -4
  174. package/dist/store-view.js +48 -25
  175. package/dist/template-eval.d.ts +15 -1
  176. package/dist/template-eval.js +92 -13
  177. package/dist/templates.d.ts +4 -3
  178. package/dist/templates.js +4 -3
  179. package/dist/timeline/labels.js +17 -0
  180. package/dist/tool-gate.d.ts +4 -2
  181. package/dist/tool-list.js +1 -0
  182. package/dist/tools.d.ts +6 -2
  183. package/dist/tools.js +13 -1
  184. package/dist/trigger-targets.d.ts +21 -5
  185. package/dist/trigger-targets.js +13 -10
  186. package/dist/unified-usage.d.ts +24 -0
  187. package/dist/unified-usage.js +400 -0
  188. package/dist/uploads-archil.d.ts +100 -0
  189. package/dist/uploads-archil.js +430 -0
  190. package/dist/uploads.d.ts +55 -1
  191. package/dist/uploads.js +185 -98
  192. package/dist/validate.js +1 -1
  193. package/dist/web-fake.d.ts +25 -0
  194. package/dist/web-fake.js +38 -1
  195. package/dist/web-save.d.ts +75 -0
  196. package/dist/web-save.js +235 -0
  197. package/dist/workspace/archil-claim.d.ts +5 -2
  198. package/dist/workspace/archil-claim.js +5 -2
  199. package/dist/workspace/archil-disk.d.ts +11 -1
  200. package/dist/workspace/archil-disk.js +43 -10
  201. package/dist/workspace/archil.d.ts +3 -0
  202. package/dist/workspace/archil.js +102 -16
  203. package/dist/workspace/computer-for-claim.d.ts +14 -0
  204. package/dist/workspace/computer-for-claim.js +46 -7
  205. package/dist/workspace/computer-intervals.d.ts +9 -3
  206. package/dist/workspace/computer-intervals.js +17 -8
  207. package/dist/workspace/pieced.d.ts +14 -0
  208. package/dist/workspace/pieced.js +23 -0
  209. package/dist/workspace/run-disk.js +32 -12
  210. package/dist/workspace/run-workspace.d.ts +1 -1
  211. package/dist/workspace/run-workspace.js +11 -6
  212. package/package.json +10 -10
  213. package/skills/agentrun-serve/SKILL.md +52 -7
  214. package/templates/README.md +36 -7
  215. package/dist/console/assets/index-Bzn4eUYF.js +0 -715
  216. package/dist/console/assets/index-CR2ZGei1.css +0 -1
@@ -15,18 +15,12 @@ import { RunFinal } from "../store/store.js";
15
15
  import { KINDS } from "./journal-kinds.js";
16
16
  import { commandRequest } from "./loop.js";
17
17
  export const FEEDBACK_ROUNDS = ["correction"];
18
- const END_STATES = ["ended", "stopped", "failed"];
19
- const OUTCOMES = ["completed", "escalated", "stopped", "cancelled"];
20
- /** A kept end as a steer's body or a journal entry holds it, else undefined. */
21
- function keptOf(value) {
22
- const kept = value;
23
- if (!kept || typeof kept !== "object" || !END_STATES.includes(kept.state) || typeof kept.endedAt !== "number")
18
+ /** A feedback round's `round`, `correct` and words, else undefined. */
19
+ function roundOf(fed, text) {
20
+ const round = fed;
21
+ if (!round || typeof round !== "object" || !FEEDBACK_ROUNDS.includes(round.round) || typeof round.correct !== "boolean" || typeof text !== "string")
24
22
  return undefined;
25
- if (kept.summary !== undefined && typeof kept.summary !== "string")
26
- return undefined;
27
- if (kept.outcome !== undefined && !OUTCOMES.includes(kept.outcome))
28
- return undefined;
29
- return { state: kept.state, ...(kept.summary !== undefined ? { summary: kept.summary } : {}), ...(kept.outcome !== undefined ? { outcome: kept.outcome } : {}), endedAt: kept.endedAt };
23
+ return { round: round.round, correct: round.correct, text };
30
24
  }
31
25
  /** The end run `run` has now, as a grade's round keeps it: only one a round opens again (reopenableWhere: ended, or
32
26
  * stopped by a person), with its end time. */
@@ -43,21 +37,16 @@ export function jobEndOpen(entries) {
43
37
  }
44
38
  /** The end run's look-back keeps while it runs, from the run's root `entries` and its command rows, else undefined (no
45
39
  * look-back under way, or one whose job's end was never kept):
46
- * - the job's end its claim kept before the end-of-run step (KINDS.jobEnd, with its time), newer than the run's last end;
47
- * - else the end a grade's round kept, from its FEEDBACK entry newer than the run's last end;
40
+ * - the job's end kept for it (KINDS.jobEnd, with its time), newer than the run's last end: by its claim before the
41
+ * end-of-run step, or for a grade's round by the steer's taking;
48
42
  * - else from the round's steer the grade wrote, not taken yet (the run opened again, no runner on it yet).
49
43
  * A follow-up's own turn keeps none until its job's end is kept: its run reads as going on, as main's does. */
50
44
  export function keptEndOf(entries, commands) {
51
- const last = (kind) => entries.findLastIndex((entry) => entry.kind === kind);
52
- const end = last(KINDS.end);
53
45
  if (jobEndOpen(entries)) {
54
- const data = entries[last(KINDS.jobEnd)].data;
55
- return keptOf(data?.end && data.endedAt !== undefined ? { ...data.end, endedAt: data.endedAt } : undefined);
46
+ const { end, endedAt } = entries.findLast((entry) => entry.kind === KINDS.jobEnd).data;
47
+ return { state: end.state, ...(end.summary !== undefined ? { summary: end.summary } : {}), ...(end.outcome !== undefined ? { outcome: end.outcome } : {}), endedAt };
56
48
  }
57
- const fed = last(KINDS.feedback);
58
- if (fed > end)
59
- return keptOf(entries[fed].data?.kept);
60
- const steer = commands.find((command) => command.kind === "steer" && command.takenAt === null && command.refused === null && feedbackOf(command.body)?.kept !== undefined);
49
+ const steer = commands.find((command) => command.kind === "steer" && command.takenAt === null && command.refused === null && feedbackOf(command.body) !== undefined);
61
50
  return steer ? feedbackOf(steer.body).kept : undefined;
62
51
  }
63
52
  /** What a grade asks for: `correction` for a graded run the agent finished when the grade has words, else none
@@ -66,15 +55,12 @@ export function keptEndOf(entries, commands) {
66
55
  export function feedbackRoundOf(grade, label) {
67
56
  return (grade.path === "agent" || grade.path === "handed_back") && label ? "correction" : undefined;
68
57
  }
69
- /** The feedback round a steer's body asks for (`body.feedback`, the server's own: server.ts gradeRun writes it, and the
70
- * message API never does), else undefined. */
58
+ /** The feedback round a steer's body asks for (`body.feedback`, the server's own: openFeedbackRound writes it with the
59
+ * end it kept, and the message API never does), else undefined. */
71
60
  export function feedbackOf(body) {
72
61
  const fed = body?.feedback;
73
- const text = body?.text;
74
- if (!fed || typeof fed !== "object" || !FEEDBACK_ROUNDS.includes(fed.round) || typeof fed.correct !== "boolean" || typeof text !== "string")
75
- return undefined;
76
- const kept = keptOf(fed.kept);
77
- return { round: fed.round, correct: fed.correct, text, ...(kept ? { kept } : {}) };
62
+ const round = roundOf(fed, body?.text);
63
+ return round && fed?.kept ? { ...round, kept: fed.kept } : undefined;
78
64
  }
79
65
  /** The feedback round the run's root `entries` say its next end closes: its newest FEEDBACK entry when no end came after
80
66
  * it, else undefined. */
@@ -82,7 +68,7 @@ export function pendingFeedbackOf(entries) {
82
68
  const at = entries.findLastIndex((entry) => entry.kind === KINDS.feedback);
83
69
  if (at < 0 || entries.slice(at + 1).some((entry) => entry.kind === KINDS.end))
84
70
  return undefined;
85
- return feedbackOf({ feedback: entries[at].data, text: entries[at].data?.text });
71
+ return roundOf(entries[at].data, entries[at].data?.text);
86
72
  }
87
73
  /** What the end-of-run turn of a feedback round is told before its prompt: the grade and its words. */
88
74
  export function feedbackAsk(feedback) {
@@ -125,7 +111,7 @@ export async function openFeedbackRound(store, grade, label, canTurn = () => tru
125
111
  const launched = await store.runs.launch(grade.run).catch(() => undefined);
126
112
  const launch = launched ? readLaunchBody(launched.body) : undefined;
127
113
  // Source sessions and application-owned SDK tasks cannot consume a managed feedback steer.
128
- if (launch?.native || launch?.sdk)
114
+ if (launch?.native || launch?.sdk || launch?.cli_learning)
129
115
  return null;
130
116
  const learning = launch?.learning;
131
117
  if (!learning || learning.use)
@@ -72,8 +72,10 @@ async function loopOn(deps, harness, launch, runId) {
72
72
  }
73
73
  // A backend SDK run's compile turn is asked on the runner's one model route, on the agent's own model (its learning
74
74
  // start's), its key from the runner's environment, else the one saved in Settings → Model keys, read at each ask.
75
- if (launch.sdk)
75
+ if (launch.sdk || launch.cli_learning)
76
76
  return createSdkLoop(launch, deps, async () => {
77
+ if (launch.cli_learning)
78
+ throw new Error("Connected CLI capture has no workflow execution bridge.");
77
79
  const base = deps.env ?? process.env;
78
80
  const env = withModelKeys(base, await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: base }));
79
81
  // It runs after its backend reported the run complete, on no run's key: on a server that holds no gateway key it is
@@ -7,6 +7,7 @@ import type { ApprovalPrice, ToolEffect } from "../tool-gate.js";
7
7
  import type { OpenedAccount } from "../email/account.js";
8
8
  import type { SavedCalendar } from "../calendar/address.js";
9
9
  import type { Workspace } from "../workspace/workspace.js";
10
+ import type { Pieces } from "../workspace/pieced.js";
10
11
  import type { GithubAppAccessAt } from "./github-app.js";
11
12
  import type { HarnessInstallEntry, HarnessPins } from "../harness-install.js";
12
13
  import type { RunModelKey } from "../store/seal.js";
@@ -111,9 +112,11 @@ export interface Held {
111
112
  install(name: string, signal?: AbortSignal): Promise<void>;
112
113
  /** The claim's computer (workspace/computer-for-claim.ts), made and held by the runner. */
113
114
  computer(ask: HeldComputerAsk): Promise<unknown>;
114
- /** A Mode 2 claim: the run's folder on its Archil disk, as the runner opens it; its mount credential's revoke. */
115
+ /** A Mode 2 claim: the run's folder on its Archil disk, as the runner opens it; its mount credential's revoke. `pieces`:
116
+ * the runner's pieced write on that Workspace (big-writes.ts), what a write bigger than a piece goes through. */
115
117
  archil(): Promise<{
116
118
  readonly workspace: Workspace;
119
+ readonly pieces?: Pieces;
117
120
  revoke(): Promise<void>;
118
121
  inherit(): Promise<void>;
119
122
  release(): Promise<void>;
@@ -348,7 +348,7 @@ export interface EndData {
348
348
  export interface JobEndData {
349
349
  readonly end: EndData;
350
350
  readonly failedWith?: string;
351
- readonly endedAt?: number;
351
+ readonly endedAt: number;
352
352
  }
353
353
  /** An escalated workflow run's review as its end keeps it: the escalation's kind, the escalate node's label (else the node
354
354
  * it escalated at), and its summary (else the run's). Served as the run's `review`, `at` its end. */
@@ -23,7 +23,8 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
23
23
  import { isMessageRow } from "../timeline/index.js";
24
24
  import { correctionRefused, learningCommit } from "../learn/commit.js";
25
25
  import { CAPS, checkDraft, problemWords, unstorable } from "../learn/index.js";
26
- import { repickRewrite } from "../learn/repick.js";
26
+ import { repickSiteOf } from "../learn/check.js";
27
+ import { repickLabelOf, repickRewrite } from "../learn/repick.js";
27
28
  import { folderAt, readLearning, readSnapshot, runMergeOf, snapshotAt, textsAt } from "../learn/folder.js";
28
29
  import { completedRun, compileStoppedOf, lastOwnRuns, compileDue, compilePrompt, compileReference, COMPILE_TRACES, DRAFT_FAILED, heldNamesOf, newCompileAttempt } from "../learn/compile.js";
29
30
  import { loopOf, repickOf } from "../learning-setting.js";
@@ -91,6 +92,10 @@ export function learningEndOfRun(launch, deps) {
91
92
  // A grade's feedback round always has something new, the grade's words (feedback-round.ts), whatever the job did.
92
93
  nothingNew: async (runId) => !pendingFeedbackOf(await runEntries(deps.store, runId, BACKGROUND_CONTEXT)) && onlyLearnedWorkflows(await runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })),
93
94
  feedback: async (runId) => {
95
+ // A source hook uploads task dialogue, not owner feedback addressed to AgentRun.
96
+ // CLI corrections are written explicitly through the owner corrections API.
97
+ if (launch.cli_learning)
98
+ return [];
94
99
  const [entries, rows] = await Promise.all([runEntries(deps.store, runId, BACKGROUND_CONTEXT), runTimeline(deps.store, runId, BACKGROUND_CONTEXT, { settled: false })]);
95
100
  return ownerWords(entries, rows);
96
101
  },
@@ -379,10 +384,14 @@ export async function checkDraftOf(deps, input) {
379
384
  return refused(problems);
380
385
  // With learning.repick on, what is committed is the draft with its answer's re-pick reading the run's pages on its
381
386
  // second pass (learn/repick.ts), through the same checks and dry run, so the digest that serves is the doc the
382
- // promotion check replays. A rewrite they refuse (one past CAPS.file even on one line) leaves the draft as compiled,
383
- // which the log says by rule alone.
387
+ // promotion check replays. A re-pick the rewrite does not reach, or a rewrite they refuse (one past CAPS.file even on
388
+ // one line), leaves the draft as compiled, which the log says (the latter by rule alone).
384
389
  let text = json;
385
- const rewritten = repick?.repick ? repickRewrite(JSON.parse(json), repick.repick_max_chars) : undefined;
390
+ const doc = repick?.repick ? JSON.parse(json) : undefined;
391
+ const site = repickSiteOf(doc);
392
+ const rewritten = repick?.repick ? repickRewrite(doc, site, repick.repick_max_chars) : undefined;
393
+ if (site && repick?.repick && !rewritten)
394
+ deps.log?.(`learning.repick: workflow ${name} is kept as compiled: its re-pick ${JSON.stringify(repickLabelOf(site))} is not one the rewrite reaches`);
386
395
  if (rewritten) {
387
396
  const marked = workflowText(rewritten);
388
397
  const again = marked === json ? [] : await checked(marked);
@@ -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"];