@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
@@ -0,0 +1,206 @@
1
+ // `agentrun-serve runner --check`: the runner's environment contract, checked and printed by name, never by value. A
2
+ // runner on a disk of its own (disk-free.ts) gets everything it needs from its environment and its store, so a name its
3
+ // launcher dropped is a run that fails at its claim, or a model request that goes to the wrong place. The check says
4
+ // each gap before that, and fails closed: any gap exits 1. What it reads:
5
+ //
6
+ // - the store: AGENTRUN_STORE_URL opens, at a schema this runner knows (else a SQLite store in --data, the server's own);
7
+ // - the seal key: AGENTRUN_SEAL_KEY (else the key file in --data) is the one the store's secrets are sealed under;
8
+ // - the server's run-facing names: every one the server held at its last start (it keeps their names, never their values,
9
+ // in the store: RUN_ENV_KEY), the runner holds too. These are what a run's claim reads from its runner's environment:
10
+ // model, tool and box keys, the Archil settings, each box provider's settings, the tiers' models (AGENT_MODEL,
11
+ // AGENT_MODEL_FAST, AGENT_MODEL_STRONG), AGENTRUN_BOX_ALLOW and the upstreams a model or a tool is sent to
12
+ // (*_BASE_URL, *_API_URL). A server older than this release says none: then that part is skipped, said, and fails
13
+ // nothing;
14
+ // - forwarder targets: each upstream the runner holds that names this machine's loopback (a forwarder beside the runner,
15
+ // such as a model gateway's) answers a TCP connect.
16
+ //
17
+ // A runner that holds the server's own secrets (its API tokens and key) is warned: a runner never needs them.
18
+ import { connect } from "node:net";
19
+ import { PROVIDERS } from "@parcha/agentrun-computer";
20
+ import { ARCHIL_SETTINGS_ENV } from "../archil-settings.js";
21
+ import { BOX_ALLOW_ENV } from "../box-settings.js";
22
+ import { TOOL_KEY_ROWS } from "../key-words.js";
23
+ import { PRIVATE_HOSTS_ENV } from "../mcp-private-hosts.js";
24
+ import { HARNESS_MODULES_SETTING } from "../harness-table.js";
25
+ import { GATEWAY_IDS_ENV } from "../model-gateway.js";
26
+ import { BOX_CPUS_ENV, BOX_MEMORY_ENV, BOX_PIDS_ENV, MCP_ALLOW_LOOPBACK_ENV } from "../start-switches.js";
27
+ import { DOCKER_IMAGE_ENV } from "../box-image.js";
28
+ import { bootSealKey } from "../seal-key.js";
29
+ import { SECRET_NAMES } from "../secrets.js";
30
+ import { SEAL_KEY_ENV } from "../tool-keys.js";
31
+ /** The store.settings key a server keeps the names of its run-facing environment under at each start: `{ v: 1, names }`. */
32
+ export const RUN_ENV_KEY = "server.run_env";
33
+ export const STORE_URL_ENV = "AGENTRUN_STORE_URL";
34
+ /** The most connections a Postgres store holds at once; its start refuses a value that is no size (store/open.ts). */
35
+ const POOL_SIZE_ENV = "AGENTRUN_STORE_POOL_SIZE";
36
+ /** The server's own secrets: never a runner's (runner/main.ts RUNNER_ONLY keeps them from its runs, too). */
37
+ const SERVER_ONLY = ["AGENTRUN_TOKEN", "AGENTRUN_TOKENS", "AGENTRUN_API_KEY"];
38
+ /** Names that are neither the server's run-facing environment nor the runner's: its own store and key (checked on their
39
+ * own), the server's secrets, and a client's address of the server. */
40
+ const NOT_RUN_FACING = new Set([...SERVER_ONLY, STORE_URL_ENV, SEAL_KEY_ENV, "AGENTRUN_BASE_URL"]);
41
+ /** An upstream a model or a tool is sent to, by its name's end. */
42
+ const UPSTREAM = /_(?:BASE_URL|API_URL)$/;
43
+ /** The fixed run-facing names: every secret the launcher hands over but the server's own, each tool key, each box
44
+ * provider's keys and settings by their environment names, the Archil settings, the default model and the boxes'
45
+ * network allow-list, and the operator's bound on owners' private hosts (each dial reads it from the process that dials). */
46
+ const FIXED = new Set([
47
+ ...SECRET_NAMES,
48
+ ...TOOL_KEY_ROWS.flatMap((row) => row.fields),
49
+ ...PROVIDERS.flatMap((provider) => provider.keys.map((key) => key.name)),
50
+ ...Object.values(ARCHIL_SETTINGS_ENV),
51
+ // The model of each tier (model.ts TIER_ENV): the default, and the fast and strong ones a subagent may pick.
52
+ "AGENT_MODEL",
53
+ "AGENT_MODEL_FAST",
54
+ "AGENT_MODEL_STRONG",
55
+ BOX_ALLOW_ENV,
56
+ PRIVATE_HOSTS_ENV,
57
+ // How a gateway is sent a model id (model-gateway.ts), and whether runs may reach an MCP server on loopback: each read
58
+ // from the environment of the process that runs the run.
59
+ GATEWAY_IDS_ENV,
60
+ MCP_ALLOW_LOOPBACK_ENV,
61
+ // The harness modules a server loads (harness-table.ts): a runner without them claims their runs and has no harness to
62
+ // run them on.
63
+ HARNESS_MODULES_SETTING,
64
+ // A Docker computer's image and size (box-image.ts, workspace/computer-deps.ts dockerLimitsOf): read where the run's
65
+ // computer starts, the runner.
66
+ DOCKER_IMAGE_ENV,
67
+ BOX_CPUS_ENV,
68
+ BOX_MEMORY_ENV,
69
+ BOX_PIDS_ENV,
70
+ ].filter((name) => !NOT_RUN_FACING.has(name)));
71
+ /** Whether `name` is one a run's claim reads from its runner's environment (FIXED, or an upstream's address). */
72
+ export const runFacing = (name) => !NOT_RUN_FACING.has(name) && (FIXED.has(name) || UPSTREAM.test(name));
73
+ /** The run-facing names `read` holds, sorted: of FIXED and of `listed` (the environment's own names, for its upstreams). */
74
+ export function runFacingNames(read, listed) {
75
+ const names = new Set([...FIXED, ...[...listed].filter(runFacing)]);
76
+ return [...names].filter((name) => Boolean(read(name)?.trim())).sort();
77
+ }
78
+ /** The server's start: the names of its run-facing environment, replacing the last start's. Names only, never a value. */
79
+ export async function recordRunEnv(store, names) {
80
+ await store.settings.put(RUN_ENV_KEY, { v: 1, names: [...names] });
81
+ }
82
+ /** The names the server kept at its last start (recordRunEnv), or undefined when it kept none (a server older than this). */
83
+ export async function serverRunEnv(store) {
84
+ const kept = await store.settings.get(RUN_ENV_KEY);
85
+ const names = typeof kept === "object" && kept !== null ? kept.names : undefined;
86
+ return Array.isArray(names) ? names.filter((name) => typeof name === "string") : undefined;
87
+ }
88
+ /** States that fail the check. */
89
+ export const failing = (row) => row.state === "missing" || row.state === "bad";
90
+ /** How long a forwarder has to answer the check's connect. */
91
+ export const FORWARDER_MS = 2_000;
92
+ /** Whether `host`:`port` takes a TCP connection within `ms`. */
93
+ export function tcpAnswers(host, port, ms) {
94
+ return new Promise((resolve) => {
95
+ const socket = connect({ host, port });
96
+ const done = (ok) => {
97
+ socket.destroy();
98
+ resolve(ok);
99
+ };
100
+ socket.setTimeout(ms, () => done(false));
101
+ socket.once("connect", () => done(true));
102
+ socket.once("error", () => done(false));
103
+ });
104
+ }
105
+ const LOOPBACK_HOST = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;
106
+ /** `value`'s host and port when it is an http(s) URL on this machine's loopback, else undefined. */
107
+ export function loopbackTarget(value) {
108
+ const url = URL.parse(value.trim());
109
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:") || !LOOPBACK_HOST.test(url.hostname))
110
+ return undefined;
111
+ const port = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
112
+ return { host: url.hostname.replace(/^\[|\]$/g, ""), port };
113
+ }
114
+ /** `text` with the store URL and its password taken out: a driver's error may quote what it was given. */
115
+ function withoutUrl(text, url) {
116
+ if (!url)
117
+ return text;
118
+ let out = text.split(url).join(`<${STORE_URL_ENV}>`);
119
+ const password = URL.parse(url)?.password;
120
+ if (password)
121
+ for (const form of new Set([password, decodeURIComponent(password)]))
122
+ if (form.length >= 4)
123
+ out = out.split(form).join("<password>");
124
+ return out;
125
+ }
126
+ /** The runner's environment checked (the header's contract), one row per name. The store is opened as a runner, with a
127
+ * pool of one, and closed before this returns. */
128
+ export async function checkRunnerEnv(options) {
129
+ const { env, read } = options;
130
+ const answers = options.answers ?? tcpAnswers;
131
+ const rows = [];
132
+ const url = read(STORE_URL_ENV)?.trim() || undefined;
133
+ const dataDir = options.dataDir ?? process.cwd();
134
+ let store;
135
+ if (!url && options.dataDir === undefined) {
136
+ rows.push({ state: "missing", name: STORE_URL_ENV, why: "the store's URL: unset, and no --data to find a SQLite store in" });
137
+ }
138
+ else {
139
+ // The check opens its store with a pool of one, so a pool size the runner's own start refuses (open.ts, on either
140
+ // store) is checked as given first: a runner whose start would fail never passes this check.
141
+ const { storePoolSize } = await import("../store/open.js");
142
+ try {
143
+ storePoolSize(env);
144
+ }
145
+ catch (error) {
146
+ rows.push({ state: "bad", name: POOL_SIZE_ENV, why: `the runner's store does not open with it: ${error?.message ?? String(error)}` });
147
+ }
148
+ try {
149
+ // Read when the check runs: the server imports this module for its names alone, never the runner's start.
150
+ const { openRunnerStore } = await import("./main.js");
151
+ const opened = await openRunnerStore(dataDir, { ...env, [POOL_SIZE_ENV]: "1" }, () => { }, url);
152
+ store = opened.store;
153
+ rows.push({ state: "ok", name: STORE_URL_ENV, why: url ? `the store opens: ${opened.kind}, schema v${opened.schema}` : "unset: the store is SQLite in the data directory, which is the server's" });
154
+ }
155
+ catch (error) {
156
+ const why = withoutUrl(error?.message ?? String(error), url);
157
+ rows.push({ state: url ? "bad" : "missing", name: STORE_URL_ENV, why: url ? `the store does not open: ${why}` : `unset, and the data directory holds no store a runner can open: ${why}` });
158
+ }
159
+ }
160
+ try {
161
+ const given = read(SEAL_KEY_ENV)?.trim() || undefined;
162
+ if (store) {
163
+ try {
164
+ const seal = await bootSealKey(store, dataDir, { given, role: "runner", write: false, say: () => { } });
165
+ seal?.release();
166
+ rows.push(seal ? { state: "ok", name: SEAL_KEY_ENV, why: given ? "the store's seal key" : "unset: the store's seal key is the one in the data directory" } : { state: "missing", name: SEAL_KEY_ENV, why: "the seal key: unset, and none in the data directory" });
167
+ }
168
+ catch (error) {
169
+ rows.push({ state: given ? "bad" : "missing", name: SEAL_KEY_ENV, why: error?.message ?? String(error) });
170
+ }
171
+ }
172
+ else
173
+ rows.push(given ? { state: "skipped", name: SEAL_KEY_ENV, why: "set, and not checked against the store, which did not open" } : { state: "missing", name: SEAL_KEY_ENV, why: "the seal key the store's secrets are sealed under: unset" });
174
+ const names = store ? await serverRunEnv(store) : undefined;
175
+ if (!store)
176
+ rows.push({ state: "skipped", name: RUN_ENV_KEY, why: "the server's run-facing names are read from the store, which did not open" });
177
+ else if (names === undefined)
178
+ rows.push({ state: "skipped", name: RUN_ENV_KEY, why: "the server has not said its run-facing names in this store (a server older than this runner): start the server of this release first" });
179
+ else
180
+ for (const name of names)
181
+ rows.push(read(name)?.trim() ? { state: "ok", name, why: "the server holds it, and so does this runner" } : { state: "missing", name, why: "the server holds it and a run's claim reads it here: hand it to this runner too" });
182
+ }
183
+ finally {
184
+ await store?.close().catch(() => undefined);
185
+ }
186
+ const listed = Object.keys(env);
187
+ for (const name of [...new Set(listed)].filter((one) => runFacing(one) && UPSTREAM.test(one)).sort()) {
188
+ const value = read(name);
189
+ const target = value ? loopbackTarget(value) : undefined;
190
+ if (!target)
191
+ continue;
192
+ rows.push((await answers(target.host, target.port, FORWARDER_MS)) ? { state: "ok", name, why: "on this machine's loopback, and a forwarder answers there" } : { state: "bad", name, why: `on this machine's loopback, and nothing answers there within ${FORWARDER_MS / 1000} s: start its forwarder` });
193
+ }
194
+ for (const name of SERVER_ONLY)
195
+ if (read(name)?.trim())
196
+ rows.push({ state: "warn", name, why: "the server's own secret: a runner never needs it, so leave it off the runner" });
197
+ return rows;
198
+ }
199
+ /** The check's lines: one per row (its state, its name, why), then the outcome. */
200
+ export function checkLines(rows) {
201
+ const width = Math.max(0, ...rows.map((row) => row.name.length));
202
+ const lines = rows.map((row) => `${row.state.padEnd(7)} ${row.name.padEnd(width)} ${row.why}`);
203
+ const gaps = rows.filter(failing);
204
+ lines.push(gaps.length === 0 ? `Runner environment: complete (${rows.filter((row) => row.state === "ok").length} ok)` : `Runner environment: ${gaps.length} gap${gaps.length === 1 ? "" : "s"}: ${gaps.map((row) => row.name).join(", ")}`);
205
+ return { lines, ok: gaps.length === 0 };
206
+ }
@@ -0,0 +1,19 @@
1
+ import type { RunnerEvent } from "./runner.js";
2
+ /** How often a runner says its gauge line. */
3
+ export declare const RUNNER_GAUGE_EVERY_MS = 60000;
4
+ /** The metric line of runner `runner`'s `event`, or undefined for an event that is none (a run's start and end have their
5
+ * own lines: print.ts runLine; an error is said as trouble: main.ts troubleLine). */
6
+ export declare function metricLine(runner: string, event: RunnerEvent): string | undefined;
7
+ /** The gauge line: `active` runs held of `slots`, and `rssBytes` as MiB. */
8
+ export declare const gaugeLine: (runner: string, active: number, slots: number, rssBytes: number) => string;
9
+ /** Says runner `runner`'s gauge line through `write` every `everyMs` (its timer never holds the process up) until stop(). */
10
+ export declare function startRunnerGauge({ runner, held, slots, write, everyMs, rssBytes }: {
11
+ runner: string;
12
+ held: () => number;
13
+ slots: number;
14
+ write: (line: string) => void;
15
+ everyMs?: number;
16
+ rssBytes?: () => number;
17
+ }): {
18
+ stop(): void;
19
+ };
@@ -0,0 +1,49 @@
1
+ // A runner's metrics as log lines, in the server's one log format (print.ts logLine: `at=<ISO> event=<name> key=value`),
2
+ // so a log-based metric counts them or reads a figure from them with no metrics server. Runner names, run ids, epochs,
3
+ // causes and numbers only: never a prompt, a key, a path or a customer's word. Five lines:
4
+ //
5
+ // - `runner_claimed runner run epoch from`, one per claim; `took_over=1` when it took the run over from a runner whose
6
+ // lease ran out (`lost_runner`, that runner): the run's earlier runner died or lost its claim.
7
+ // - `runner_hand_back runner run epoch cause`, one per run the runner gave back still running (runner.ts HandBackCause:
8
+ // drain, interrupted, end_retry, give_back), and `cause=claim_lost` with `why` (fenced, not_renewed) for a claim it lost.
9
+ // - `runner_drained runner ms held left`, once per close that held a run: how long the drain took, how many runs it began
10
+ // with and how many it handed back at its end.
11
+ // - `runner_gauge runner active slots rss_mib`, every RUNNER_GAUGE_EVERY_MS while the runner runs: the runs it holds, the
12
+ // most it holds at once, and its process's resident memory.
13
+ import { logLine } from "../print.js";
14
+ /** How often a runner says its gauge line. */
15
+ export const RUNNER_GAUGE_EVERY_MS = 60_000;
16
+ const MIB = 1024 * 1024;
17
+ /** The metric line of runner `runner`'s `event`, or undefined for an event that is none (a run's start and end have their
18
+ * own lines: print.ts runLine; an error is said as trouble: main.ts troubleLine). */
19
+ export function metricLine(runner, event) {
20
+ switch (event.type) {
21
+ case "claimed": {
22
+ const { claim } = event;
23
+ return logLine("runner_claimed", { runner, run: claim.runId, epoch: claim.epoch, from: claim.from, ...(claim.lost ? { took_over: 1, lost_runner: claim.lost.runner } : {}) });
24
+ }
25
+ case "handed-back":
26
+ return logLine("runner_hand_back", { runner, run: event.runId, epoch: event.epoch, cause: event.cause });
27
+ case "claim-lost":
28
+ return logLine("runner_hand_back", { runner, run: event.runId, epoch: event.epoch, cause: "claim_lost", why: event.why === "not-renewed" ? "not_renewed" : event.why });
29
+ case "drained":
30
+ return logLine("runner_drained", { runner, ms: event.ms, held: event.held, left: event.left });
31
+ default:
32
+ return undefined;
33
+ }
34
+ }
35
+ /** The gauge line: `active` runs held of `slots`, and `rssBytes` as MiB. */
36
+ export const gaugeLine = (runner, active, slots, rssBytes) => logLine("runner_gauge", { runner, active, slots, rss_mib: Math.round(rssBytes / MIB) });
37
+ /** Says runner `runner`'s gauge line through `write` every `everyMs` (its timer never holds the process up) until stop(). */
38
+ export function startRunnerGauge({ runner, held, slots, write, everyMs = RUNNER_GAUGE_EVERY_MS, rssBytes = () => process.memoryUsage.rss() }) {
39
+ const timer = setInterval(() => {
40
+ try {
41
+ write(gaugeLine(runner, held(), slots, rssBytes()));
42
+ }
43
+ catch {
44
+ // A gauge it could not read or write never stops the runner.
45
+ }
46
+ }, everyMs);
47
+ timer.unref();
48
+ return { stop: () => clearInterval(timer) };
49
+ }
@@ -103,6 +103,14 @@ export interface RunnerOptions {
103
103
  * loop is turning. The runner process writes its heartbeat from it (runner/main.ts), so a check sees a runner that is
104
104
  * idle and well, and not one whose loop has stopped. A throw is the caller's. */
105
105
  onBeat?: () => void;
106
+ /** Whether this runner may claim now: undefined while it may, else why not, in words a person can act on (runner/main.ts
107
+ * diskFreeGate: a runner whose data directory is not the server's, while the server keeps runs' folders on its own
108
+ * disk). Asked before each poll's claims (`fresh` false: an answer a few seconds old will do) and again, fresh, once a
109
+ * poll claimed any, before a loop starts on them: a run claimed as the answer changed is released at once, untouched,
110
+ * for a runner that can serve it. While it refuses, the runner claims nothing and says why on its presence row, where
111
+ * the server reads it (presence.ts runnersRefused); a throw is said as an error and that poll claims nothing. Absent:
112
+ * always. */
113
+ claimGate?: (fresh: boolean) => Promise<string | undefined>;
106
114
  /** For tests: the claim deadline's clock (the deadline a claim not renewed in time is lost at, and the time its claimed
107
115
  * until is reckoned from). Default: the real one. Nothing else in the runner reads it. */
108
116
  clock?: {
@@ -147,17 +155,46 @@ export type RunnerEvent = {
147
155
  runId: string;
148
156
  epoch: number;
149
157
  end: LoopEnd["state"];
158
+ }
159
+ /** A release that left the run running for another claim (the store keeps it: hand_backs), after its `released`, and
160
+ * why (HandBackCause). */
161
+ | {
162
+ type: "handed-back";
163
+ runId: string;
164
+ epoch: number;
165
+ cause: HandBackCause;
166
+ }
167
+ /** close()'s drain is over: how long it took (`ms`), how many held runs it began with (`held`) and how many were still
168
+ * going at its end (`left`: stopped for the shutdown and handed back). Said once per close that held a run, a drain of
169
+ * 0 ms (no --drain-timeout) included. */
170
+ | {
171
+ type: "drained";
172
+ ms: number;
173
+ held: number;
174
+ left: number;
150
175
  } | {
151
176
  type: "refused";
152
177
  runId: string;
153
178
  commandId: number;
154
179
  reason: string;
180
+ }
181
+ /** The runner stopped claiming (`reason`, its claimGate's words) or claims again (null): said once at each change. */
182
+ | {
183
+ type: "refusing";
184
+ reason: string | null;
155
185
  } | {
156
186
  type: "error";
157
187
  runId?: string;
158
188
  step: string;
159
189
  message: string;
160
190
  };
191
+ /** Why a runner handed a run back, still running, for another claim: `drain`, its close stopped the run's loop after the
192
+ * drain; `interrupted`, the run's loop ended interrupted with the runner not closing (its Session closed itself: its
193
+ * backoff doubles in a row); `end_retry`, a stopped end refused
194
+ * (EndNotWithdrawn), tried again after a backoff; `give_back`, a claim nothing here holds, given back at once (an
195
+ * Unanswered claim that had landed, or one made as the runner closed). A lost claim is no hand-back: it is said as
196
+ * `claim-lost`, and the store moves the run without the runner. */
197
+ export type HandBackCause = "drain" | "interrupted" | "end_retry" | "give_back";
161
198
  export interface Runner {
162
199
  readonly name: string;
163
200
  /** The claims this runner holds and has not lost. */
@@ -517,6 +517,7 @@ export function startRunner(options) {
517
517
  // whatever its backoff (a person's stop never waits on a failed resume's), so the run would be claimed again at once.
518
518
  await release(claim, { state: "running", backoffUntil: now() + wait });
519
519
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "interrupted" });
520
+ emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "end_retry" });
520
521
  };
521
522
  /** Whether the run under `claim` never started: its journal has no conversation yet, so no input of it went out. A
522
523
  * journal that cannot be read says no (the claim's loop applies the stop as it would). */
@@ -611,6 +612,9 @@ export function startRunner(options) {
611
612
  : inARow > 0 ? { backoffUntil: Date.now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
612
613
  : {});
613
614
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: end.state });
615
+ // Left running for another claim: a hand-back, by its cause (this runner's close stopped its loop, or it ended so).
616
+ if (end.state === "interrupted")
617
+ emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: closed && !closedItself ? "drain" : "interrupted" });
614
618
  if (end.state === "ended" || end.state === "stopped" || end.state === "failed")
615
619
  await announceEnd(claim);
616
620
  }
@@ -775,7 +779,7 @@ export function startRunner(options) {
775
779
  if (runs.get(claim.runId)?.claim.epoch === claim.epoch || endingClaims.has(`${claim.runId}:${claim.epoch}`) || known.some((k) => k.runId === claim.runId && k.epoch === claim.epoch))
776
780
  continue;
777
781
  emit({ type: "error", runId: claim.runId, step: "claim", message: `run ${claim.runId}: a claim answered Unanswered had landed (epoch ${claim.epoch}); given back` });
778
- await release(claim, {}).catch((error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
782
+ await release(claim, {}).then(() => emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "give_back" }), (error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
779
783
  }
780
784
  }
781
785
  };
@@ -787,6 +791,8 @@ export function startRunner(options) {
787
791
  const free = loops - runs.size - replaced.size;
788
792
  if (free <= 0)
789
793
  return;
794
+ if (!(await gateOpen(false)))
795
+ return;
790
796
  // By count alone, one store call claims the batch, each run at its own epoch + 1 (store.runs.claimMany): filling 300
791
797
  // loops, or taking a dead runner's runs over, is one transaction, not 300. By memory, each run that fits is claimed
792
798
  // on its own (claimByMemory).
@@ -801,6 +807,13 @@ export function startRunner(options) {
801
807
  await giveBackUnknown([]);
802
808
  throw error;
803
809
  }
810
+ // Asked again, fresh, before any loop starts on what this poll claimed: a run claimed as the gate's answer changed is
811
+ // given back untouched (released at its epoch, as a closing runner gives back a batch), for a runner that can serve it.
812
+ if (claims.length > 0 && !(await gateOpen(true))) {
813
+ for (const claim of claims)
814
+ await release(claim, {}).catch((error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
815
+ return;
816
+ }
804
817
  // A claim whose run must only end, with no loop (endRetried), so no turn, model request or tool runs on it:
805
818
  // - a run stopped or cancelled while it had not started: claimed from queued, or claimed from running when an earlier
806
819
  // claim was lost before the run's journal had anything (its runner gone before it wrote a word). Nothing of it
@@ -830,7 +843,7 @@ export function startRunner(options) {
830
843
  // Closed while the batch was claimed (or a run this runner still holds, which a claim cannot be): given back.
831
844
  if (before && !before.fence.lost)
832
845
  emit({ type: "error", runId: claim.runId, step: "claim", message: "claimed a run this runner still holds" });
833
- await release(claim, {}).catch(() => { });
846
+ await release(claim, {}).then(() => emit({ type: "handed-back", runId: claim.runId, epoch: claim.epoch, cause: "give_back" }), () => { });
834
847
  continue;
835
848
  }
836
849
  try {
@@ -895,6 +908,29 @@ export function startRunner(options) {
895
908
  }
896
909
  return claims;
897
910
  };
911
+ /** The claim gate's last answer (RunnerOptions.claimGate): null while it lets this runner claim. */
912
+ let refusing = null;
913
+ /** Whether this runner may claim now (claimGate), its presence row and its lines told at each change of answer. A gate
914
+ * that throws is said, and claims nothing this poll; its last answer stands. */
915
+ const gateOpen = async (fresh) => {
916
+ if (!options.claimGate)
917
+ return true;
918
+ let words;
919
+ try {
920
+ words = await options.claimGate(fresh);
921
+ }
922
+ catch (error) {
923
+ emit({ type: "error", step: "claim gate", message: message(error) });
924
+ return false;
925
+ }
926
+ const now = words ?? null;
927
+ if (now !== refusing) {
928
+ refusing = now;
929
+ emit({ type: "refusing", reason: now });
930
+ await (options.presence ?? presence)?.refuse(now).catch(() => undefined);
931
+ }
932
+ return now === null;
933
+ };
898
934
  /** The poll's claim in flight, if any: close() waits for it, so a runner whose close resolved claims nothing after it. */
899
935
  let claiming;
900
936
  /** A run was queued while a poll was in flight (claimNow): one more poll follows that poll's end at once. */
@@ -930,7 +966,7 @@ export function startRunner(options) {
930
966
  };
931
967
  // Its word in the store that a runner that claims is here (presence.ts), for as long as it runs: a server reads a
932
968
  // refusal left by an earlier runner as over once this is there. One its caller keeps is its caller's to close.
933
- const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }) }) : undefined;
969
+ const presence = options.presence ? undefined : store.runners ? keepPresence(store.runners, name, null, { warn: (line) => emit({ type: "error", step: "presence", message: line }), slots: loops }) : undefined;
934
970
  poll();
935
971
  commandTimer = setTimeout(deliverAll, commandPollMs);
936
972
  // A run queued in this process is claimed now (claimNow). A command written for a run this runner holds is handed on
@@ -1024,12 +1060,16 @@ export function startRunner(options) {
1024
1060
  // them), its claims renewed, for up to drainMs; a turn in flight then finishes, never cut and paid again on the
1025
1061
  // resume. Whatever is still going at the bound is stopped below, for a shutdown, where it can resume.
1026
1062
  const going = [...runs.values()].filter((held) => !held.fence.lost && !held.ending);
1063
+ const drainFrom = Date.now();
1027
1064
  if (draining && going.length > 0) {
1028
1065
  let bound;
1029
1066
  await Promise.race([Promise.all(going.map((held) => held.done)), new Promise((resolve) => (bound = setTimeout(resolve, drainMs)))]);
1030
1067
  clearTimeout(bound);
1031
1068
  }
1032
1069
  draining = false;
1070
+ // How long the drain took, and what it left for the shutdown to hand back (the runner's metrics: runner-metrics.ts).
1071
+ if (going.length > 0)
1072
+ emit({ type: "drained", ms: Date.now() - drainFrom, held: going.length, left: going.filter((held) => !held.ending && !held.fence.lost).length });
1033
1073
  clearTimeout(commandTimer);
1034
1074
  const live = [...runs.values()].filter((held) => !held.fence.lost);
1035
1075
  // One window for the stop after the drain, the one runnerCloseBoundMs counts (the lease less its margin): the read
@@ -0,0 +1,9 @@
1
+ import { type Channel } from "./run-channel.js";
2
+ import { type SaveSlots } from "../web-save.js";
3
+ /** The most takes one run may have held or waiting at once: a run's waiters live in the runner, so a run may not queue
4
+ * without bound. */
5
+ export declare const SAVE_SLOTS_PER_RUN = 16;
6
+ /** Exposes `gate` on the runner's side of a run's `channel`. Answers what the runner calls when that channel ends. */
7
+ export declare function exposeSaveSlots(channel: Pick<Channel, "expose">, gate: SaveSlots): () => void;
8
+ /** A run process's web_save slots: its runner's gate, taken over `channel`. */
9
+ export declare function remoteSaveSlots(channel: Pick<Channel, "call">): SaveSlots;
@@ -0,0 +1,91 @@
1
+ // web_save's download slots (web-save.ts saveSlots) across a runner's runs. Each run runs in a process of its own
2
+ // (run-child-host.ts), so a gate in that process would be one per run. The bound is per runner, the process that holds
3
+ // the claims: its one gate (web-save.ts SERVER_SLOTS) is exposed on each run's channel, and a run's web_save takes its
4
+ // slots there. The run's process is untrusted: a release frees only its own take's slot, once, and every slot a run
5
+ // holds or waits for is let go when its channel ends (its process crashed, was killed, or its run ended).
6
+ import { ClaimRefused } from "./loop-contract.js";
7
+ import { ChannelClosed } from "./run-channel.js";
8
+ import { SAVE_CONCURRENCY } from "../web-save.js";
9
+ const TARGET = "saves";
10
+ /** The most takes one run may have held or waiting at once: a run's waiters live in the runner, so a run may not queue
11
+ * without bound. */
12
+ export const SAVE_SLOTS_PER_RUN = 16;
13
+ /** Exposes `gate` on the runner's side of a run's `channel`. Answers what the runner calls when that channel ends. */
14
+ export function exposeSaveSlots(channel, gate) {
15
+ const held = new Set();
16
+ const waits = new Set();
17
+ let closed = false;
18
+ channel.expose(TARGET, async (method, args) => {
19
+ if (method !== "take")
20
+ throw new ClaimRefused(`the runner has no ${method} for a run's download slots`);
21
+ const [signal] = args;
22
+ if (!(signal instanceof AbortSignal))
23
+ throw new TypeError("a download slot is taken under the call's signal");
24
+ if (closed)
25
+ throw new ChannelClosed("the run's channel ended");
26
+ if (held.size + waits.size >= SAVE_SLOTS_PER_RUN)
27
+ throw new ClaimRefused(`this run already has ${SAVE_SLOTS_PER_RUN} web_save downloads held or waiting`);
28
+ const left = new AbortController();
29
+ waits.add(left);
30
+ let release;
31
+ try {
32
+ release = await gate.take(AbortSignal.any([signal, left.signal]));
33
+ }
34
+ finally {
35
+ waits.delete(left);
36
+ }
37
+ // Granted as the channel ended: no answer reaches the run, so the slot goes back now.
38
+ if (closed) {
39
+ release();
40
+ throw new ChannelClosed("the run's channel ended");
41
+ }
42
+ held.add(release);
43
+ // The gate's release is once only: a second call frees nothing.
44
+ return () => {
45
+ held.delete(release);
46
+ release();
47
+ };
48
+ });
49
+ return () => {
50
+ if (closed)
51
+ return;
52
+ closed = true;
53
+ for (const wait of waits)
54
+ wait.abort(new ChannelClosed("the run's channel ended"));
55
+ for (const release of held)
56
+ release();
57
+ held.clear();
58
+ };
59
+ }
60
+ /** A run process's web_save slots: its runner's gate, taken over `channel`. */
61
+ export function remoteSaveSlots(channel) {
62
+ let busy = 0;
63
+ let waiting = 0;
64
+ return {
65
+ size: SAVE_CONCURRENCY,
66
+ get busy() { return busy; },
67
+ get waiting() { return waiting; },
68
+ async take(signal) {
69
+ waiting++;
70
+ let release;
71
+ try {
72
+ release = await channel.call(TARGET, "take", [signal]);
73
+ }
74
+ finally {
75
+ waiting--;
76
+ }
77
+ if (typeof release !== "function")
78
+ throw new TypeError("the runner answered no release for a download slot");
79
+ busy++;
80
+ let done = false;
81
+ return () => {
82
+ if (done)
83
+ return;
84
+ done = true;
85
+ busy--;
86
+ // A release that cannot cross (the channel ended) is no loss: the runner frees the slot when the channel ends.
87
+ Promise.resolve(release()).catch(() => { });
88
+ };
89
+ },
90
+ };
91
+ }