@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -56,8 +56,8 @@ export declare class RunnerRefused extends Error {
56
56
  name: string;
57
57
  }
58
58
  /** The store, opened as a runner, its kind and its schema version: refused when its schema is one this build does not
59
- * know, or not set up yet. The one place the runner opens its store (store/open.ts: Postgres when AGENTRUN_STORE_URL
60
- * names one, else SQLite in the data directory). */
59
+ * know, not set up yet, or not yet upgraded by its server. The one place the runner opens its store (store/open.ts:
60
+ * Postgres when AGENTRUN_STORE_URL names one, else SQLite in the data directory). */
61
61
  export declare function openRunnerStore(dataDir: string, env: NodeJS.ProcessEnv, warn: (message: string) => void, url: string | undefined): Promise<{
62
62
  store: Store;
63
63
  kind: string;
@@ -174,9 +174,9 @@ export declare function lastResort(name: string, write?: (line: string) => void,
174
174
  * goes to stderr. Undefined for any other event. The runner beside a server says them the same way (beside.ts), so a
175
175
  * lapse of every claim at once shows its cause. */
176
176
  export declare function troubleLine(name: string, event: RunnerEvent): string | undefined;
177
- /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
178
- * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
179
- * it when --name does not. */
177
+ /** `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. */
180
180
  export declare function runnerMain(argv: readonly string[], given?: NodeJS.ProcessEnv, hooks?: RunnerMainHooks): Promise<number>;
181
181
  /** A test's hooks into runnerMain: `started`, awaited once the runner has started claiming and before its stop handlers
182
182
  * take over from the ones its start listened on (the window a stop must not fall through). */
@@ -8,11 +8,13 @@
8
8
  // memory holds: the server's --max-runs default, host.ts maxRunsOf). SIGTERM or SIGINT closes it: each busy run finishes
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
- // run is claimable when its lease lapses); then 0. Bad arguments exit 2, a store schema it does not know 3, anything else 1.
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
12
  // A run isolation it cannot give (run-child-host.ts runIsolationOf) is said, and it stays up claiming nothing until a stop: 0.
13
13
  // An error nothing handles exits 1 at once, said with its stack (lastResort).
14
+ import { randomUUID } from "node:crypto";
14
15
  import { mkdirSync, statSync, utimesSync, writeFileSync, writeSync } from "node:fs";
15
16
  import { join, resolve } from "node:path";
17
+ import { setTimeout as sleep } from "node:timers/promises";
16
18
  import { PROVIDERS } from "@parcha/agentrun-computer";
17
19
  import { startRunnerRelay } from "../dial-relay.js";
18
20
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -27,7 +29,7 @@ import { FAUX_ENV, FAUX_PREFIX, withoutFaux } from "../model.js";
27
29
  import { durationMs, runLine } from "../print.js";
28
30
  import { bootSealKey } from "../seal-key.js";
29
31
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
30
- import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget } from "../store/index.js";
32
+ import { migrationsIn, openStore, SchemaVersionUnknown, StoreAwaitsServer, storePlace, storeTarget } from "../store/index.js";
31
33
  import { SCHEMA_VERSION } from "../store/schema.js";
32
34
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
33
35
  import { FAUX_BROWSER_ENV } from "../tools.js";
@@ -48,14 +50,15 @@ import { RUN_PROCESS_MIB, runnerMemory } from "./memory-claim.js";
48
50
  import { childLoops, isolationLoops, RunIsolationRefused, runIsolationOf } from "./run-child-host.js";
49
51
  import { sweepEndedScratch } from "./scratch-sweep.js";
50
52
  import { RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
53
+ import { keepPresence } from "./presence.js";
51
54
  export { RUNNER_RENEW_EVERY_MS } from "./runner.js";
52
55
  /** A store this runner cannot use, or arguments it cannot take, in words a person starting it can act on. */
53
56
  export class RunnerRefused extends Error {
54
57
  name = "RunnerRefused";
55
58
  }
56
59
  /** The store, opened as a runner, its kind and its schema version: refused when its schema is one this build does not
57
- * know, or not set up yet. The one place the runner opens its store (store/open.ts: Postgres when AGENTRUN_STORE_URL
58
- * names one, else SQLite in the data directory). */
60
+ * know, not set up yet, or not yet upgraded by its server. The one place the runner opens its store (store/open.ts:
61
+ * Postgres when AGENTRUN_STORE_URL names one, else SQLite in the data directory). */
59
62
  export async function openRunnerStore(dataDir, env, warn, url) {
60
63
  // The store module owns where the store is (design: only the store adapter knows a file or a schema). The URL is this
61
64
  // process's secret (as the launcher handed it over), unless a test hands one.
@@ -68,6 +71,8 @@ export async function openRunnerStore(dataDir, env, warn, url) {
68
71
  return { store, kind: target.kind, schema: target.kind === "sqlite" ? SCHEMA_VERSION : migrationsIn().at(-1).version };
69
72
  }
70
73
  catch (error) {
74
+ if (error instanceof StoreAwaitsServer)
75
+ 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 });
71
76
  if (!(error instanceof SchemaVersionUnknown))
72
77
  throw error;
73
78
  const { found, known } = error;
@@ -218,6 +223,7 @@ export async function startRunnerProcess(options) {
218
223
  let seal;
219
224
  let janitor;
220
225
  let relay;
226
+ let presence;
221
227
  try {
222
228
  // The server's seal key, booted the one way the server boots it (seal-key.ts): the one handed over, else the one in
223
229
  // this data directory, checked against what the store records. A runner on a store whose secrets another key sealed
@@ -225,9 +231,13 @@ export async function startRunnerProcess(options) {
225
231
  // or records a key.
226
232
  seal = await bootSealKey(store, options.dataDir, { given: handedSecret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV], role: "runner" });
227
233
  const name = options.name ?? runnerName();
234
+ // One incarnation for this process: its word in the store that it is there (presence.ts) and its relay's minted
235
+ // tokens and proofs name the same one, so the server's "restarted since" and the runner's row speak of one process.
236
+ // 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() });
228
238
  // Its relay (dial-relay.ts), where its environment names the server's public address: a machine that dials the
229
239
  // server lands in this runner's hub, through the server. Its log lines are the runner's warnings.
230
- relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, env, log: warn });
240
+ relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, presence, env, log: warn });
231
241
  const made = options.createLoop ?? ofStore((opened, sealKey, dial) => runnerLoop(opened, options.dataDir, undefined, sealKey, undefined, dial));
232
242
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
233
243
  const parts = isStoreFactory(made) ? made(store, seal.key, relay?.dial) : made;
@@ -244,6 +254,7 @@ export async function startRunnerProcess(options) {
244
254
  store,
245
255
  createLoop,
246
256
  name,
257
+ presence,
247
258
  ...(options.loops ? { loops: options.loops } : {}),
248
259
  ...(options.drainMs ? { drainMs: options.drainMs } : {}),
249
260
  memory,
@@ -255,6 +266,7 @@ export async function startRunnerProcess(options) {
255
266
  catch (error) {
256
267
  await janitor?.close();
257
268
  await relay?.close();
269
+ await presence?.close();
258
270
  seal?.release();
259
271
  await store.close();
260
272
  throw error;
@@ -262,6 +274,7 @@ export async function startRunnerProcess(options) {
262
274
  let closing;
263
275
  const held = seal;
264
276
  const relayed = relay;
277
+ const kept = presence;
265
278
  return {
266
279
  runner,
267
280
  store: { kind, schema },
@@ -269,8 +282,10 @@ export async function startRunnerProcess(options) {
269
282
  close: () => (closing ??= (async () => {
270
283
  // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
271
284
  await Promise.all([janitor?.close(), runner.close()]);
272
- // Its relay after its runs: a run's release revokes its machine's token through it.
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.
273
287
  await relayed?.close();
288
+ await kept.close();
274
289
  // A first-use install its claims started, stopped as they let go: its npm ends before this process can.
275
290
  await claimInstallsStopped();
276
291
  await store.close();
@@ -431,9 +446,9 @@ export function troubleLine(name, event) {
431
446
  return `Runner ${name}: ${event.step}${event.runId ? ` ${event.runId}` : ""}: ${event.message}`;
432
447
  return undefined;
433
448
  }
434
- /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
435
- * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
436
- * it when --name does not. */
449
+ /** `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. */
437
452
  export async function runnerMain(argv, given = process.env, hooks = {}) {
438
453
  let args;
439
454
  try {
@@ -506,7 +521,10 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
506
521
  // Said, then up and claiming nothing until a stop: in the image's server-and-runner either process's exit stops the
507
522
  // container, which a platform that restarts it (Render, Railway) would loop on, the refusal lost in the restarts.
508
523
  console.error(`agentrun-serve runner: ${error.message}`);
509
- await untilSignalled(RUNNER_SIGNALS);
524
+ // And said in the store until the stop (presence.ts), so the server, in its own process or on another host, refuses a
525
+ // launch in these words and fails the runs left queued while no runner that claims is there.
526
+ const stop = untilSignalled(RUNNER_SIGNALS);
527
+ await refusedInStore(args.dataDir, env, name ?? runnerName(), error.message, stop);
510
528
  return 0;
511
529
  }
512
530
  if (isolation.kind === "uid" && holds.loops > isolation.slots)
@@ -557,7 +575,7 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
557
575
  catch (error) {
558
576
  unlisten();
559
577
  console.error(`agentrun-serve runner: ${error?.message ?? String(error)}`);
560
- return error instanceof RunnerRefused && error.cause instanceof SchemaVersionUnknown ? 3 : 1;
578
+ return error instanceof RunnerRefused && (error.cause instanceof SchemaVersionUnknown || error.cause instanceof StoreAwaitsServer) ? 3 : 1;
561
579
  }
562
580
  await hooks.started?.(started);
563
581
  // From here the handlers below take the stop, with nothing awaited between: no signal falls in a gap.
@@ -578,6 +596,39 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
578
596
  }
579
597
  /** The signals that stop a runner process. */
580
598
  const RUNNER_SIGNALS = ["SIGTERM", "SIGINT"];
599
+ /** How long a refusing runner waits before it tries its store again (refusedInStore). */
600
+ const REFUSED_STORE_RETRY_MS = 5_000;
601
+ /** A runner whose run isolation was refused: its `words` kept in its store (presence.ts) until `stopped`, then its row
602
+ * removed and the store closed. A store that does not open (not set up yet, one its server has yet to upgrade, a
603
+ * connection down) is said, once for each reason, and tried again every REFUSED_STORE_RETRY_MS until it opens or the
604
+ * stop: a runner that starts before its server still tells that server, once it is there. */
605
+ async function refusedInStore(dataDir, env, name, words, stopped) {
606
+ const warn = (line) => void console.error(`agentrun-serve runner: ${line}`);
607
+ let stop = false;
608
+ void stopped.then(() => void (stop = true));
609
+ let said;
610
+ while (!stop) {
611
+ let store;
612
+ try {
613
+ ({ store } = await openRunnerStore(dataDir, env, warn, undefined));
614
+ }
615
+ catch (error) {
616
+ const why = error?.message ?? String(error);
617
+ if (why !== said)
618
+ warn(`the server is not told yet that this runner claims nothing, since its store did not open (tried again every ${REFUSED_STORE_RETRY_MS / 1000} s): ${why}`);
619
+ said = why;
620
+ await Promise.race([sleep(REFUSED_STORE_RETRY_MS, undefined, { ref: false }), stopped]);
621
+ continue;
622
+ }
623
+ if (said !== undefined)
624
+ warn("its store opened: the server is told that this runner claims nothing");
625
+ const presence = keepPresence(store.runners, name, words, { warn });
626
+ await stopped;
627
+ await presence.close();
628
+ await store.close();
629
+ return;
630
+ }
631
+ }
581
632
  /** Holds the process up, with nothing else to do, until one of `signals`. */
582
633
  function untilSignalled(signals) {
583
634
  return new Promise((resolve) => {
@@ -25,6 +25,9 @@
25
25
  // opens it again, so a message's new credential reaches the run's next model request; a run handed none gets its calls
26
26
  // refused unsent (UNUSABLE.perRunMissing).
27
27
  //
28
+ // A per-run Composio server (composio-made.ts composioPerRun) is bound by each run's caller ({composio_user_id,
29
+ // connected_account_id?} in mcp_auth, sealed in its launch): its entry carries them as `query` (mcp-gateway.ts).
30
+ //
28
31
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
29
32
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
30
33
  // only when it provably never left: a refused or unmade connection, an address check out of time; one request that left
@@ -50,6 +53,8 @@ import { randomUUID } from "node:crypto";
50
53
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
51
54
  import { pinFirst } from "../mcp-pin-first.js";
52
55
  import { mcpNameOf } from "../tool-names.js";
56
+ import { composioMadeKey, composioPerRun } from "../composio-made.js";
57
+ import { composioRunQuery } from "../composio-preset.js";
53
58
  import { META_REASON, metaToolOf } from "../mcp-meta.js";
54
59
  import { credentialInQuery, credentialInQueryWords, shownUrl } from "../mcp-probe.js";
55
60
  import { privateOAuthHosts } from "../mcp-private-hosts.js";
@@ -193,10 +198,14 @@ export async function mcpClaim(options) {
193
198
  // Held by the run's redactor before anything else: a value opened is a value to cut, sent or not.
194
199
  if (extra.headers)
195
200
  options.hold?.(credentialValues(extra.headers));
201
+ if (extra.query)
202
+ options.hold?.(Object.values(extra.query));
196
203
  if (released || gone.has(name))
197
204
  return;
198
- // Headers go only to the URL the run was pinned to: a server moved since is refused per call by the gateway.
199
- credentials[name] = { url: row.url, ...(extra.unopened ? { unopened: extra.unopened } : extra.headers && row.url === pinnedUrl ? { headers: extra.headers } : {}) };
205
+ // Headers and a run's account go only to the URL the run was pinned to: a server moved since is refused per call by
206
+ // the gateway.
207
+ const pinned = row.url === pinnedUrl;
208
+ credentials[name] = { url: row.url, ...(extra.unopened ? { unopened: extra.unopened } : { ...(extra.headers && pinned ? { headers: extra.headers } : {}), ...(extra.query && pinned ? { query: extra.query } : {}) }) };
200
209
  };
201
210
  // A GitHub App's server keeps no credential: its token is minted for this run (awaited, so the claim is confirmed
202
211
  // after it), kept fresh mid-run, and never stored.
@@ -206,15 +215,20 @@ export async function mcpClaim(options) {
206
215
  // run's launch, read again at every fresh() so a message's new one reaches the run's next request.
207
216
  if (row.auth === "per_run")
208
217
  return entry(await perRun(name, row.url)), { awaited: false };
218
+ // A per-run Composio server: the run's account, or its calls refused unsent; its key is opened below as any server's.
219
+ const account = row.auth === "headers" ? await composioAccount(name, row) : undefined;
220
+ if (account && "unopened" in account)
221
+ return entry({ unopened: account.unopened }), { awaited: false };
222
+ const query = account?.query;
209
223
  if (row.sealed === null)
210
- return entry({}), { awaited: false };
224
+ return entry({ ...(query ? { query } : {}) }), { awaited: false };
211
225
  // A seal problem first: no refresh is ever sent for a credential this runner cannot open.
212
226
  const opened = openMcpRow(sealKey, row);
213
227
  if (!("credential" in opened))
214
228
  return entry(opened.unusable === "none" ? {} : { unopened: UNUSABLE.damaged }), { awaited: false };
215
229
  const credential = opened.credential;
216
230
  if (credential.type === "headers")
217
- return entry({ headers: { ...credential.headers } }), { awaited: false };
231
+ return entry({ headers: { ...credential.headers }, ...(query ? { query } : {}) }), { awaited: false };
218
232
  const oauth = credential;
219
233
  if (oauth.expired)
220
234
  return entry({ unopened: UNUSABLE.signedOut }), { awaited: false };
@@ -346,19 +360,33 @@ export async function mcpClaim(options) {
346
360
  };
347
361
  /** The run's handed MCP credentials, opened from its launch: read once per fresh() (perRunRead), not once per server. */
348
362
  let perRunRead;
349
- /** A per_run server's headers for this run, from its launch; or why there are none. Only for the origin its url had
350
- * when they were handed: a server moved since gets none. */
351
- const perRun = async (name, url) => {
363
+ /** What the run's caller handed `name` (mcp_auth, opened from its launch) when it is of `shape`; or why there is none.
364
+ * Only for the origin its url had when it was handed: a server moved since gets none. */
365
+ const handed = async (name, url, shape) => {
352
366
  perRunRead ??= store.runs.launch(claim.runId).then((launch) => openRunMcpAuth(sealKey, claim.runId, launch.sealed));
353
- const handed = await perRunRead;
354
- if (handed === undefined)
367
+ const all = await perRunRead;
368
+ if (all === undefined)
355
369
  return { unopened: UNUSABLE.damaged };
356
- const given = Object.hasOwn(handed, name) ? handed[name] : undefined;
357
- if (!given)
370
+ const given = Object.hasOwn(all, name) ? all[name] : undefined;
371
+ if (!given || !(shape in given))
358
372
  return { unopened: UNUSABLE.perRunMissing };
359
373
  if (given.origin !== new URL(url).origin)
360
374
  return { unopened: UNUSABLE.damaged };
361
- return { headers: { ...given.headers } };
375
+ return given;
376
+ };
377
+ /** A per_run server's headers for this run; or why there are none. */
378
+ const perRun = async (name, url) => {
379
+ const given = await handed(name, url, "headers");
380
+ return "unopened" in given ? given : { headers: { ...given.headers } };
381
+ };
382
+ /** A per-run Composio server's account for this run, as the query its requests add (composio-preset.ts
383
+ * composioRunQuery); or why there is none. Undefined: `row` is no per-run Composio server (its own record says so:
384
+ * composioPerRun). */
385
+ const composioAccount = async (name, row) => {
386
+ if (!composioPerRun(row, await store.settings.get(composioMadeKey(name))))
387
+ return undefined;
388
+ const given = await handed(name, row.url, "composio");
389
+ return "unopened" in given ? given : { query: composioRunQuery(given.composio) };
362
390
  };
363
391
  const fresh = async () => {
364
392
  if (!pin || released)
@@ -158,7 +158,9 @@ export function metaTools(options) {
158
158
  * value is null (an op that answers none: a computer's files.write) is told by its answer's words ("wrote <path>"), as
159
159
  * it answered, never as null. */
160
160
  function lineOf(index, name, result) {
161
- const quoted = (text) => JSON.stringify(text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text);
161
+ // Whole: the model reads these values nowhere else (the script's own output went with the stop), and the answer is held
162
+ // to the host's bound as every tool answer is (boundResult). A cut here once hid an approved call's title from it.
163
+ const quoted = (text) => JSON.stringify(text);
162
164
  const label = `${index}. ${name}`;
163
165
  if (result.refused)
164
166
  return `${label} was refused: ${quoted(result.text)}. It did not run.`;
@@ -168,7 +170,7 @@ function lineOf(index, name, result) {
168
170
  return `${label} failed: ${quoted(result.text)}. It was not run again.`;
169
171
  const value = result.structured === null ? result.text : scriptValue(result);
170
172
  const json = typeof value === "string" ? undefined : JSON.stringify(withoutImageData(value));
171
- const said = json === undefined ? quoted(value) : json.length > 2_000 ? `${json.slice(0, 2_000)}…` : json;
173
+ const said = json === undefined ? quoted(value) : json;
172
174
  return `${label} completed: ${said}. Its effect is done; it was not run again.`;
173
175
  }
174
176
  /** The script's output and value, as the model reads them, and the images: the returned value's own first, then the ones
@@ -8,6 +8,11 @@ import { type CostParts } from "@parcha/agentrun-kernel";
8
8
  * its runner.request's model, "" for one that names none). `free`: it booked requests, every one on a free model (its
9
9
  * runner.turn's `free`: its known price $0 for every token), so its $0 says why. A reader that joins sessions, or says
10
10
  * what is known of an unknown cost, takes the parts through costOfParts, never `usd` and `known` alone. */
11
+ /** `priced`: of its requests with a known figure (a plan's aside, which cost no dollars), how many the provider or its
12
+ * gateway priced (`reported`: the proxy's reportedCostOf or usageCostOf, its runner.turn keeping the table's figure beside
13
+ * it as `tableUsd`) and how many a price table did (`estimated`: its runner.turn's `estimated`, or a cut request's hold,
14
+ * or a native or SDK task's `aggregate` booking, its harness's own figure).
15
+ * A figure that is neither ($0 for a request refused or never sent, a charge settled through the cap) counts in neither. */
11
16
  export type BookedSpend = {
12
17
  readonly usd: number | null;
13
18
  readonly known: number;
@@ -23,8 +28,28 @@ export type BookedSpend = {
23
28
  cacheRead: number;
24
29
  cacheWrite: number;
25
30
  };
31
+ readonly priced: {
32
+ readonly reported: number;
33
+ readonly estimated: number;
34
+ };
26
35
  readonly free?: true;
27
36
  };
37
+ /** How a run's cost was reached, by how its model requests were priced: `reported` when every request priced had the
38
+ * provider's or its gateway's own figure (LiteLLM's `x-litellm-response-cost`, OpenRouter's usage `cost`); `estimate`
39
+ * when any was priced from a price table (the catalog, AGENT_MODEL_PRICE, a cut request's hold); `unpriced` when no
40
+ * request was priced (none was sent, or none had a figure). The run's cost block (`cost.basis`), its stored metrics
41
+ * (`costBasis`) and the sums over runs (GET /stats, GET /usage) say it in these words. */
42
+ export declare const COST_BASES: readonly ["reported", "estimate", "unpriced"];
43
+ export type CostBasis = (typeof COST_BASES)[number];
44
+ /** The basis of a booking's model requests (bookedSpend "model"): COST_BASES. */
45
+ export declare const costBasisOf: (spend: Pick<BookedSpend, "priced">) => CostBasis;
46
+ /** The basis of a sum of costs: `estimate` when any is, else `reported` when any is, else `unpriced`. */
47
+ export declare function joinedBasis(bases: Iterable<CostBasis>): CostBasis;
48
+ /** A run's basis as its end stored it (its metrics' `costBasis`); an imported run's catalog estimate (import.ts stores
49
+ * `costBasis: "catalog"` beside `costUsdEst`, the figure store-reads/runs.ts costOfRun reads) is an `estimate`, at $0 too;
50
+ * a run that stored none (one that ended before the end stored it, a workflow's, a native, SDK or imported run's: their
51
+ * figures are the harness's) is an `estimate` when it cost anything, else `unpriced`. */
52
+ export declare function storedBasisOf(metrics: unknown, usd: number | null | undefined): CostBasis;
28
53
  /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
29
54
  * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
30
55
  * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
@@ -114,6 +139,7 @@ export declare function bookedListSpend(entries: readonly EntryLike[]): number |
114
139
  export type RunMetricsStored = RunMetrics & {
115
140
  effort?: string;
116
141
  model?: string;
142
+ costBasis?: CostBasis;
117
143
  };
118
144
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
119
145
  * `effort`/`model`: the enrichment the old storedMetrics added. `catalog`: the run's MCP tools called by a hashed wire
@@ -13,6 +13,37 @@ import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/c
13
13
  import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
14
14
  import { anthropicModelId } from "../provider.js";
15
15
  import { WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
16
+ /** How a run's cost was reached, by how its model requests were priced: `reported` when every request priced had the
17
+ * provider's or its gateway's own figure (LiteLLM's `x-litellm-response-cost`, OpenRouter's usage `cost`); `estimate`
18
+ * when any was priced from a price table (the catalog, AGENT_MODEL_PRICE, a cut request's hold); `unpriced` when no
19
+ * request was priced (none was sent, or none had a figure). The run's cost block (`cost.basis`), its stored metrics
20
+ * (`costBasis`) and the sums over runs (GET /stats, GET /usage) say it in these words. */
21
+ export const COST_BASES = ["reported", "estimate", "unpriced"];
22
+ /** The basis of a booking's model requests (bookedSpend "model"): COST_BASES. */
23
+ export const costBasisOf = (spend) => (spend.priced.estimated > 0 ? "estimate" : spend.priced.reported > 0 ? "reported" : "unpriced");
24
+ /** The basis of a sum of costs: `estimate` when any is, else `reported` when any is, else `unpriced`. */
25
+ export function joinedBasis(bases) {
26
+ let reported = false;
27
+ for (const basis of bases) {
28
+ if (basis === "estimate")
29
+ return "estimate";
30
+ if (basis === "reported")
31
+ reported = true;
32
+ }
33
+ return reported ? "reported" : "unpriced";
34
+ }
35
+ /** A run's basis as its end stored it (its metrics' `costBasis`); an imported run's catalog estimate (import.ts stores
36
+ * `costBasis: "catalog"` beside `costUsdEst`, the figure store-reads/runs.ts costOfRun reads) is an `estimate`, at $0 too;
37
+ * a run that stored none (one that ended before the end stored it, a workflow's, a native, SDK or imported run's: their
38
+ * figures are the harness's) is an `estimate` when it cost anything, else `unpriced`. */
39
+ export function storedBasisOf(metrics, usd) {
40
+ const stored = metrics?.costBasis;
41
+ if (COST_BASES.includes(stored))
42
+ return stored;
43
+ if (stored === "catalog" && typeof usd === "number")
44
+ return "estimate";
45
+ return typeof usd === "number" && usd > 0 ? "estimate" : "unpriced";
46
+ }
16
47
  /** The conversation each of the run's sessions books in, by its key: the first `agentrun.session.key` entry naming it. */
17
48
  function sessionConversations(entries) {
18
49
  const out = new Map();
@@ -61,6 +92,8 @@ export function bookedSpend(entries, which) {
61
92
  let unmetered = 0;
62
93
  let free = 0;
63
94
  let atMost = 0;
95
+ let reported = 0;
96
+ let estimated = 0;
64
97
  const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
65
98
  // Each request is booked once, as the kernel's sessionSpendOf reads it: a second runner.turn of a turn already booked
66
99
  // (two bookings of one session that each read it open, a cut written twice) counts no money and no request again.
@@ -96,6 +129,16 @@ export function bookedSpend(entries, which) {
96
129
  (bounded += own.usd), (atMost += 1);
97
130
  else
98
131
  known += own.usd;
132
+ // How its figure was reached (costBasisOf): a price table's (the proxy's `estimated`, or a hold), or the provider's own
133
+ // (the proxy keeps the table's figure beside a reported one, `tableUsd`). A native or SDK task's one booking for the whole
134
+ // task (`aggregate`, native-loop.ts and sdk-loop.ts) carries its harness's own figure, an estimate. A plan's request
135
+ // costs no dollars: neither.
136
+ if (own.usd !== null && d.billing !== "plan") {
137
+ if (own.atMost || d.estimated === true || d.aggregate === true)
138
+ estimated += 1;
139
+ else if (d.tableUsd !== undefined)
140
+ reported += 1;
141
+ }
99
142
  // The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
100
143
  if (d.usage === undefined)
101
144
  unmetered += 1;
@@ -103,7 +146,7 @@ export function bookedSpend(entries, which) {
103
146
  if (typeof d.usage?.[key] === "number")
104
147
  tokens[key] += d.usage[key];
105
148
  }
106
- return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, ...(requests > 0 && free === requests ? { free: true } : {}) };
149
+ return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, priced: { reported, estimated }, ...(requests > 0 && free === requests ? { free: true } : {}) };
107
150
  }
108
151
  /** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
109
152
  * decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
@@ -0,0 +1,44 @@
1
+ import type { Runners } from "../store/store.js";
2
+ /** How often a runner says again that it is there. */
3
+ export declare const PRESENCE_RENEW_MS = 10000;
4
+ /** How old a runner's word can be and still count: three renewals missed. */
5
+ export declare const PRESENCE_STALE_MS: number;
6
+ /** Where a runner's relay takes the dials the server relays to it (dial-relay.ts). */
7
+ export interface RelayAt {
8
+ readonly host: string;
9
+ readonly port: number;
10
+ }
11
+ /** A runner's word kept in the store until its close. */
12
+ export interface Presence {
13
+ /** The runner's process since its start, on its row: its relay's minted tokens and proofs name the same one. */
14
+ readonly incarnation: string;
15
+ /** Says on its row where its relay answers (`at`), or that it answers nowhere (null, the relay's close), and keeps that
16
+ * through every put again. Rejects when that write fails, which the renewals then try again. */
17
+ relay(at: RelayAt | null): Promise<void>;
18
+ /** Stops renewing it and removes the row (its incarnation's alone). */
19
+ close(): Promise<void>;
20
+ /** Stops renewing it and leaves the row to go stale, as a crash would. */
21
+ stop(): void;
22
+ }
23
+ /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), renewed every `renewMs`; put
24
+ * again when it went (a row pruned, a store restored), never over a later process's of the same name while that one is
25
+ * live; its relay's place is written on its own row only. A write that
26
+ * fails is tried again at the next renewal: it never stops the runner, and `warn` hears it once. `incarnation` is the
27
+ * runner process's one (runner/main.ts hands its relay the same), a new one by default. */
28
+ export declare function keepPresence(runners: Runners, runner: string, refused: string | null, { renewMs, warn, incarnation }?: {
29
+ renewMs?: number;
30
+ warn?: (line: string) => void;
31
+ incarnation?: string;
32
+ }): Presence;
33
+ /** Why no runner here can take a run, in the runners' own words, or undefined while one can (or none is there): the rows
34
+ * seen within `staleMs` on the store's clock (Runners.live), when there is one at least and every one refused. */
35
+ export declare function runnersRefused(runners: Pick<Runners, "live">, staleMs?: number): Promise<string | undefined>;
36
+ /** Refuses a run no runner here can take (runner_refused, in the runners' words: runnersRefused), before anything is made
37
+ * for it; nothing while one can, or none is there yet. Every refusal of a start or a message is this one throw. */
38
+ export declare function refuseWhileNoRunner(runners: Pick<Runners, "live">): Promise<void>;
39
+ /** The code a run fails with when no runner here could take it (its error's code, and a launch's refusal's). */
40
+ export declare const RUNNER_REFUSED_CODE = "runner_refused";
41
+ /** The summary of a queued run failed because no runner here can take it (Runs.failUnclaimed): the code, then `words`. */
42
+ export declare const refusedEnd: (words: string) => string;
43
+ /** The words of a summary refusedEnd wrote, or undefined for any other (store-view.ts errorOfRow). */
44
+ export declare const refusedEndMessage: (summary: string | null | undefined) => string | undefined;
@@ -0,0 +1,96 @@
1
+ // Each runner's word that it is there (store `runners`), and what the server makes of them: whether any runner here can take
2
+ // a run. A runner that claims keeps a row with no refusal for as long as it runs (startRunner); a runner whose run isolation
3
+ // was refused (run-child-host.ts runIsolationOf) keeps one with its words, beside a server (cli.ts, through Serve.refuseRuns)
4
+ // or in a process of its own (runner/main.ts), so a server in another process, or on another host over one Postgres, reads
5
+ // it. A runner in a process of its own with a relay (dial-relay.ts) says on the same row where its relay answers, under the
6
+ // same incarnation (runner/main.ts makes one per process), so the server relays a dial only to a runner this row says is
7
+ // there. Each row is renewed every PRESENCE_RENEW_MS and read as gone once it is PRESENCE_STALE_MS old: a runner that died
8
+ // without its close stops counting within that. While every runner still there refused, and one at least is, the server
9
+ // refuses a launch in their words (runs-over-store.ts prepareLaunch), says so in capabilities and health, and fails the
10
+ // runs still queued (server.ts). With no runner there at all (a server with --no-runner and its runner not started yet),
11
+ // it refuses nothing: runs queue for the runner to come, as before.
12
+ import { randomUUID } from "node:crypto";
13
+ import { ApiError } from "../errors.js";
14
+ /** How often a runner says again that it is there. */
15
+ export const PRESENCE_RENEW_MS = 10_000;
16
+ /** How old a runner's word can be and still count: three renewals missed. */
17
+ export const PRESENCE_STALE_MS = 3 * PRESENCE_RENEW_MS;
18
+ /** Keeps `runner`'s row in `runners` (refused: its words, or null for a runner that claims), renewed every `renewMs`; put
19
+ * again when it went (a row pruned, a store restored), never over a later process's of the same name while that one is
20
+ * live; its relay's place is written on its own row only. A write that
21
+ * fails is tried again at the next renewal: it never stops the runner, and `warn` hears it once. `incarnation` is the
22
+ * runner process's one (runner/main.ts hands its relay the same), a new one by default. */
23
+ export function keepPresence(runners, runner, refused, { renewMs = PRESENCE_RENEW_MS, warn = (_line) => { }, incarnation = randomUUID() } = {}) {
24
+ let warned = false;
25
+ const failed = (error) => {
26
+ if (warned)
27
+ return;
28
+ warned = true;
29
+ warn(`could not say in the store that runner ${runner} is there: ${error instanceof Error ? error.message : String(error)}`);
30
+ };
31
+ let at = null;
32
+ const row = () => ({ runner, incarnation, refused, host: at?.host ?? null, port: at?.port ?? null });
33
+ // Its first put takes the name over from an earlier process's row. Every write after it (a renewal, the relay's place:
34
+ // one Runners.renew, with the place it holds now) touches its own row only, or puts one where no other process of the
35
+ // name is live (Runners.put unlessLiveMs): an older process overlapping a restart never takes the later one's row back,
36
+ // nor clears its relay.
37
+ const again = () => runners.put(row(), { unlessLiveMs: PRESENCE_STALE_MS });
38
+ const renew = async () => {
39
+ if (!(await runners.renew(runner, incarnation, at)))
40
+ await again();
41
+ };
42
+ let writing = runners.put(row()).catch(failed);
43
+ const timer = setInterval(() => {
44
+ writing = writing.then(renew).catch(failed);
45
+ }, renewMs);
46
+ timer.unref();
47
+ let stopped = false;
48
+ return {
49
+ incarnation,
50
+ relay(next) {
51
+ at = next;
52
+ // Once closed or stopped it writes nothing more: a relay's close after its presence's never puts the row back.
53
+ if (stopped)
54
+ return Promise.resolve();
55
+ // After any write in flight, so a renewal's put never lands over it with the place before.
56
+ const wrote = writing.then(renew);
57
+ writing = wrote.catch(failed);
58
+ return wrote;
59
+ },
60
+ async close() {
61
+ if (stopped)
62
+ return;
63
+ stopped = true;
64
+ clearInterval(timer);
65
+ await writing;
66
+ await runners.remove(runner, incarnation).catch(() => undefined);
67
+ },
68
+ stop() {
69
+ stopped = true;
70
+ clearInterval(timer);
71
+ },
72
+ };
73
+ }
74
+ /** Why no runner here can take a run, in the runners' own words, or undefined while one can (or none is there): the rows
75
+ * seen within `staleMs` on the store's clock (Runners.live), when there is one at least and every one refused. */
76
+ export async function runnersRefused(runners, staleMs = PRESENCE_STALE_MS) {
77
+ const live = await runners.live(staleMs);
78
+ if (live.length === 0 || live.some((row) => row.refused === null))
79
+ return undefined;
80
+ const reasons = [...new Set(live.map((row) => row.refused))];
81
+ return `No runner of this server can take a run: ${reasons.join(" ")}`;
82
+ }
83
+ /** Refuses a run no runner here can take (runner_refused, in the runners' words: runnersRefused), before anything is made
84
+ * for it; nothing while one can, or none is there yet. Every refusal of a start or a message is this one throw. */
85
+ export async function refuseWhileNoRunner(runners) {
86
+ const refused = await runnersRefused(runners);
87
+ if (refused !== undefined)
88
+ throw new ApiError(RUNNER_REFUSED_CODE, refused);
89
+ }
90
+ /** The code a run fails with when no runner here could take it (its error's code, and a launch's refusal's). */
91
+ export const RUNNER_REFUSED_CODE = "runner_refused";
92
+ const REFUSED_END = `${RUNNER_REFUSED_CODE}: `;
93
+ /** The summary of a queued run failed because no runner here can take it (Runs.failUnclaimed): the code, then `words`. */
94
+ export const refusedEnd = (words) => `${REFUSED_END}${words}`;
95
+ /** The words of a summary refusedEnd wrote, or undefined for any other (store-view.ts errorOfRow). */
96
+ export const refusedEndMessage = (summary) => typeof summary === "string" && summary.startsWith(REFUSED_END) ? summary.slice(REFUSED_END.length) : undefined;