@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.34

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 (381) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +266 -201
  3. package/dist/adapters.d.ts +0 -4
  4. package/dist/adapters.js +11 -15
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/bash-read-only.d.ts +22 -0
  16. package/dist/bash-read-only.js +701 -0
  17. package/dist/box-settings.d.ts +3 -23
  18. package/dist/box-settings.js +7 -51
  19. package/dist/boxes.d.ts +17 -0
  20. package/dist/boxes.js +27 -20
  21. package/dist/browser-commands.d.ts +5 -2
  22. package/dist/browser-commands.js +4 -4
  23. package/dist/browser-computer.d.ts +5 -0
  24. package/dist/browser-computer.js +21 -0
  25. package/dist/browser-cost.d.ts +9 -6
  26. package/dist/browser-cost.js +92 -50
  27. package/dist/browser-live.d.ts +7 -20
  28. package/dist/browser-live.js +15 -93
  29. package/dist/browser-person.d.ts +18 -51
  30. package/dist/browser-person.js +94 -277
  31. package/dist/cap.d.ts +8 -5
  32. package/dist/cap.js +12 -5
  33. package/dist/cli.js +39 -13
  34. package/dist/closed-pipes.d.ts +2 -0
  35. package/dist/closed-pipes.js +13 -0
  36. package/dist/computer-commands.d.ts +2 -0
  37. package/dist/computer-commands.js +2 -0
  38. package/dist/computer-keys.js +5 -2
  39. package/dist/computer-setting.d.ts +20 -4
  40. package/dist/computer-setting.js +25 -5
  41. package/dist/computers.d.ts +30 -2
  42. package/dist/computers.js +70 -11
  43. package/dist/confine.d.ts +120 -0
  44. package/dist/confine.js +436 -0
  45. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  46. package/dist/console/assets/index-opTN5Naq.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decision-rows.d.ts +1 -1
  49. package/dist/decision-rows.js +1 -1
  50. package/dist/docker-daemon.d.ts +31 -0
  51. package/dist/docker-daemon.js +56 -0
  52. package/dist/effort-guidance.js +4 -3
  53. package/dist/environment.d.ts +0 -3
  54. package/dist/environment.js +3 -5
  55. package/dist/errors.d.ts +0 -2
  56. package/dist/errors.js +6 -9
  57. package/dist/filed-answer.d.ts +32 -0
  58. package/dist/filed-answer.js +160 -0
  59. package/dist/files.d.ts +1 -3
  60. package/dist/files.js +2 -4
  61. package/dist/github-connection.d.ts +1 -1
  62. package/dist/graph-view.d.ts +3 -5
  63. package/dist/graph-view.js +4 -14
  64. package/dist/handed-values.d.ts +9 -0
  65. package/dist/handed-values.js +26 -0
  66. package/dist/harness-install.d.ts +1 -7
  67. package/dist/harness-install.js +1 -18
  68. package/dist/harness-opencode/adapter.d.ts +7 -0
  69. package/dist/harness-opencode/adapter.js +23 -6
  70. package/dist/harness-opencode/index.d.ts +1 -1
  71. package/dist/harness-opencode/index.js +1 -1
  72. package/dist/harness-opencode/verify.d.ts +17 -0
  73. package/dist/harness-opencode/verify.js +30 -10
  74. package/dist/harness-table.js +6 -1
  75. package/dist/heard.js +1 -1
  76. package/dist/held-fd.d.ts +5 -0
  77. package/dist/held-fd.js +14 -0
  78. package/dist/host-calls.d.ts +20 -0
  79. package/dist/host-calls.js +12 -0
  80. package/dist/host-tools.d.ts +4 -21
  81. package/dist/host-tools.js +4 -61
  82. package/dist/host.d.ts +2 -4
  83. package/dist/host.js +2 -7
  84. package/dist/import-summary.d.ts +1 -5
  85. package/dist/import-summary.js +0 -21
  86. package/dist/import.d.ts +6 -6
  87. package/dist/import.js +14 -15
  88. package/dist/key-refusal.d.ts +5 -1
  89. package/dist/key-refusal.js +19 -4
  90. package/dist/learn/check.d.ts +6 -2
  91. package/dist/learn/check.js +83 -29
  92. package/dist/learn/folder.d.ts +5 -1
  93. package/dist/learn/folder.js +10 -3
  94. package/dist/learn/grade.d.ts +14 -0
  95. package/dist/learn/grade.js +68 -12
  96. package/dist/learn/index.d.ts +4 -4
  97. package/dist/learn/index.js +4 -4
  98. package/dist/learn/reflect.d.ts +31 -2
  99. package/dist/learn/reflect.js +79 -4
  100. package/dist/learn/relevance.d.ts +24 -0
  101. package/dist/learn/relevance.js +91 -0
  102. package/dist/learn/secrets.d.ts +7 -1
  103. package/dist/learn/secrets.js +86 -19
  104. package/dist/learn/skills.d.ts +112 -14
  105. package/dist/learn/skills.js +556 -52
  106. package/dist/learned-workflow.d.ts +32 -1
  107. package/dist/learned-workflow.js +100 -9
  108. package/dist/learning-routes.d.ts +8 -4
  109. package/dist/learning-routes.js +23 -9
  110. package/dist/learning-run.d.ts +9 -26
  111. package/dist/learning-run.js +22 -32
  112. package/dist/learning-words.d.ts +12 -5
  113. package/dist/learning-words.js +18 -9
  114. package/dist/learning.d.ts +93 -77
  115. package/dist/learning.js +176 -304
  116. package/dist/live/stream.js +1 -1
  117. package/dist/live/translate.js +12 -2
  118. package/dist/local-models.d.ts +11 -5
  119. package/dist/local-models.js +13 -8
  120. package/dist/mcp-gateway.d.ts +11 -49
  121. package/dist/mcp-gateway.js +44 -135
  122. package/dist/mcp-oauth.d.ts +10 -14
  123. package/dist/mcp-oauth.js +14 -32
  124. package/dist/mcp-probe.d.ts +0 -7
  125. package/dist/mcp-probe.js +4 -10
  126. package/dist/mcp-servers-store.d.ts +6 -6
  127. package/dist/mcp-servers-store.js +12 -14
  128. package/dist/mcp-store.js +3 -4
  129. package/dist/mcp.js +4 -3
  130. package/dist/model.d.ts +6 -7
  131. package/dist/model.js +43 -27
  132. package/dist/monid.d.ts +0 -2
  133. package/dist/monid.js +3 -6
  134. package/dist/openapi.d.ts +8 -1
  135. package/dist/openapi.js +121 -47
  136. package/dist/page.d.ts +1 -3
  137. package/dist/page.js +6 -18
  138. package/dist/paid-calls.d.ts +21 -27
  139. package/dist/paid-calls.js +25 -60
  140. package/dist/propose.js +83 -39
  141. package/dist/push-handler.d.ts +1 -1
  142. package/dist/reflect-range.d.ts +25 -0
  143. package/dist/reflect-range.js +30 -0
  144. package/dist/refusal-words.d.ts +5 -1
  145. package/dist/refusal-words.js +5 -1
  146. package/dist/rows.d.ts +1 -1
  147. package/dist/run-cut.d.ts +0 -6
  148. package/dist/run-cut.js +0 -6
  149. package/dist/run-db.d.ts +2 -11
  150. package/dist/run-db.js +2 -37
  151. package/dist/run-launch.d.ts +19 -2
  152. package/dist/run-launch.js +13 -5
  153. package/dist/run-learning-served.d.ts +10 -4
  154. package/dist/run-learning-served.js +23 -13
  155. package/dist/run-reads-over-store.d.ts +1 -1
  156. package/dist/run-reads-over-store.js +15 -6
  157. package/dist/run-secrets.d.ts +1 -1
  158. package/dist/run-timeline-served.d.ts +5 -1
  159. package/dist/run-timeline-served.js +15 -4
  160. package/dist/run-view.d.ts +7 -8
  161. package/dist/run-view.js +26 -7
  162. package/dist/runnable.d.ts +18 -10
  163. package/dist/runnable.js +21 -10
  164. package/dist/runner/adapter-loop.d.ts +6 -1
  165. package/dist/runner/adapter-loop.js +423 -53
  166. package/dist/runner/adapter-run-spec.d.ts +21 -8
  167. package/dist/runner/adapter-run-spec.js +90 -32
  168. package/dist/runner/adapters/index.js +11 -1
  169. package/dist/runner/adapters/pi.d.ts +12 -2
  170. package/dist/runner/adapters/pi.js +16 -5
  171. package/dist/runner/beside.d.ts +30 -3
  172. package/dist/runner/beside.js +36 -5
  173. package/dist/runner/claim-secrets.d.ts +10 -1
  174. package/dist/runner/claim-secrets.js +48 -14
  175. package/dist/runner/cli-run-spec.d.ts +2 -0
  176. package/dist/runner/cli-run-spec.js +45 -16
  177. package/dist/runner/commands.js +1 -1
  178. package/dist/runner/computer-journal.d.ts +15 -2
  179. package/dist/runner/computer-journal.js +41 -5
  180. package/dist/runner/conformance/harness.js +118 -8
  181. package/dist/runner/conformance/subject.d.ts +4 -1
  182. package/dist/runner/dispatch.d.ts +8 -1
  183. package/dist/runner/dispatch.js +81 -7
  184. package/dist/runner/end-of-run.d.ts +8 -2
  185. package/dist/runner/end-of-run.js +10 -4
  186. package/dist/runner/github-app.js +1 -1
  187. package/dist/runner/harness-loops.d.ts +9 -1
  188. package/dist/runner/harness-loops.js +15 -2
  189. package/dist/runner/journal-kinds.d.ts +24 -6
  190. package/dist/runner/journal-kinds.js +20 -5
  191. package/dist/runner/journal-reader.d.ts +1 -1
  192. package/dist/runner/journal-reader.js +2 -2
  193. package/dist/runner/learning-ask.d.ts +4 -0
  194. package/dist/runner/learning-ask.js +15 -1
  195. package/dist/runner/learning-end.d.ts +18 -3
  196. package/dist/runner/learning-end.js +113 -11
  197. package/dist/runner/learning-loop.d.ts +5 -0
  198. package/dist/runner/learning-loop.js +26 -6
  199. package/dist/runner/main.d.ts +56 -9
  200. package/dist/runner/main.js +127 -18
  201. package/dist/runner/mcp-claim.js +1 -2
  202. package/dist/runner/mcp-run.d.ts +2 -0
  203. package/dist/runner/mcp-run.js +15 -5
  204. package/dist/runner/memory-claim.d.ts +9 -0
  205. package/dist/runner/memory-claim.js +25 -0
  206. package/dist/runner/metrics.d.ts +33 -1
  207. package/dist/runner/metrics.js +85 -1
  208. package/dist/runner/model-route.d.ts +13 -0
  209. package/dist/runner/model-route.js +133 -9
  210. package/dist/runner/reflect-hook.d.ts +12 -1
  211. package/dist/runner/reflect-hook.js +33 -3
  212. package/dist/runner/runner.d.ts +20 -0
  213. package/dist/runner/runner.js +56 -10
  214. package/dist/runner/store-port.d.ts +1 -1
  215. package/dist/runner/store-secrets.d.ts +3 -3
  216. package/dist/runner/store-secrets.js +8 -12
  217. package/dist/runner/text-tools.d.ts +44 -0
  218. package/dist/runner/text-tools.js +237 -0
  219. package/dist/runner/workflow-loop.d.ts +6 -0
  220. package/dist/runner/workflow-loop.js +6 -4
  221. package/dist/runner/workflow-spec.d.ts +18 -0
  222. package/dist/runner/workflow-spec.js +63 -17
  223. package/dist/runs-over-store.d.ts +7 -2
  224. package/dist/runs-over-store.js +60 -14
  225. package/dist/seal-key.js +5 -43
  226. package/dist/sealed-settings-store.d.ts +19 -4
  227. package/dist/sealed-settings-store.js +9 -9
  228. package/dist/sealing.d.ts +4 -0
  229. package/dist/sealing.js +20 -0
  230. package/dist/secret-cut.d.ts +1 -1
  231. package/dist/secret-cut.js +1 -1
  232. package/dist/secret-name.d.ts +9 -0
  233. package/dist/secret-name.js +15 -0
  234. package/dist/secret-writes.d.ts +0 -1
  235. package/dist/secret-writes.js +0 -1
  236. package/dist/server-fs.d.ts +4 -0
  237. package/dist/server-fs.js +8 -2
  238. package/dist/server-lock.d.ts +0 -24
  239. package/dist/server-lock.js +1 -80
  240. package/dist/server-secrets-store.d.ts +4 -4
  241. package/dist/server-secrets-store.js +9 -31
  242. package/dist/server-secrets.d.ts +4 -9
  243. package/dist/server-secrets.js +12 -36
  244. package/dist/server.d.ts +16 -38
  245. package/dist/server.js +145 -106
  246. package/dist/sign-ins-store.d.ts +34 -36
  247. package/dist/sign-ins-store.js +27 -38
  248. package/dist/sign-ins.d.ts +2 -119
  249. package/dist/sign-ins.js +5 -311
  250. package/dist/standard-webhooks.d.ts +1 -1
  251. package/dist/standard-webhooks.js +1 -1
  252. package/dist/stats.d.ts +3 -2
  253. package/dist/stats.js +1 -1
  254. package/dist/store/agent-body.d.ts +8 -2
  255. package/dist/store/agent-body.js +16 -4
  256. package/dist/store/index.d.ts +2 -2
  257. package/dist/store/index.js +2 -2
  258. package/dist/store/open.d.ts +6 -3
  259. package/dist/store/open.js +2 -2
  260. package/dist/store/postgres/connection.d.ts +18 -2
  261. package/dist/store/postgres/connection.js +156 -32
  262. package/dist/store/postgres/migrate.d.ts +4 -0
  263. package/dist/store/postgres/migrate.js +9 -2
  264. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  265. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  266. package/dist/store/postgres/store.d.ts +9 -2
  267. package/dist/store/postgres/store.js +9 -0
  268. package/dist/store/schema.js +1 -1
  269. package/dist/store/seal.js +2 -2
  270. package/dist/store/sqlite/connection.js +49 -5
  271. package/dist/store/sqlite/run-patch.d.ts +3 -0
  272. package/dist/store/sqlite/run-patch.js +3 -0
  273. package/dist/store/sqlite/store.js +41 -12
  274. package/dist/store/store.d.ts +35 -6
  275. package/dist/store/store.js +12 -2
  276. package/dist/store-reads/cap.d.ts +1 -1
  277. package/dist/store-reads/cap.js +22 -4
  278. package/dist/store-reads/journal.d.ts +9 -6
  279. package/dist/store-reads/journal.js +93 -17
  280. package/dist/store-reads/learning.d.ts +26 -8
  281. package/dist/store-reads/learning.js +12 -4
  282. package/dist/store-reads/workflow.d.ts +1 -1
  283. package/dist/store-reads/workflow.js +1 -1
  284. package/dist/store-view.d.ts +5 -1
  285. package/dist/store-view.js +53 -18
  286. package/dist/template-eval.d.ts +60 -4
  287. package/dist/template-eval.js +120 -54
  288. package/dist/templates.d.ts +24 -10
  289. package/dist/templates.js +69 -38
  290. package/dist/timeline/group.d.ts +33 -0
  291. package/dist/timeline/group.js +77 -0
  292. package/dist/timeline/index.d.ts +7 -0
  293. package/dist/timeline/index.js +7 -0
  294. package/dist/timeline/labels.d.ts +79 -0
  295. package/dist/timeline/labels.js +150 -0
  296. package/dist/timeline/origin.d.ts +56 -0
  297. package/dist/timeline/origin.js +92 -0
  298. package/dist/timeline/render-text.d.ts +11 -0
  299. package/dist/timeline/render-text.js +62 -0
  300. package/dist/timeline/timeline.d.ts +274 -0
  301. package/dist/timeline/timeline.js +1308 -0
  302. package/dist/timeline/util.d.ts +17 -0
  303. package/dist/timeline/util.js +49 -0
  304. package/dist/tool-gate.d.ts +41 -216
  305. package/dist/tool-gate.js +79 -540
  306. package/dist/tool-keys-store.d.ts +11 -12
  307. package/dist/tool-keys-store.js +24 -31
  308. package/dist/tool-keys.d.ts +5 -101
  309. package/dist/tool-keys.js +8 -267
  310. package/dist/tool-plane.d.ts +14 -42
  311. package/dist/tool-plane.js +23 -81
  312. package/dist/tool-settings-store.d.ts +1 -2
  313. package/dist/tool-settings-store.js +5 -8
  314. package/dist/tools.d.ts +30 -18
  315. package/dist/tools.js +97 -107
  316. package/dist/trigger-adapter.d.ts +2 -2
  317. package/dist/trigger-targets.d.ts +13 -1
  318. package/dist/trigger-targets.js +31 -1
  319. package/dist/triggers.d.ts +2 -2
  320. package/dist/triggers.js +3 -3
  321. package/dist/turn-end.d.ts +1 -1
  322. package/dist/turn-end.js +1 -1
  323. package/dist/turns.d.ts +0 -6
  324. package/dist/turns.js +0 -19
  325. package/dist/uploads.js +1 -1
  326. package/dist/usage.d.ts +0 -2
  327. package/dist/usage.js +0 -2
  328. package/dist/validate.d.ts +2 -0
  329. package/dist/validate.js +23 -14
  330. package/dist/webhooks.d.ts +102 -76
  331. package/dist/webhooks.js +266 -233
  332. package/dist/workflow-run.d.ts +114 -0
  333. package/dist/workflow-run.js +144 -0
  334. package/dist/workspace/beneath.d.ts +19 -0
  335. package/dist/workspace/beneath.js +106 -0
  336. package/dist/workspace/computer-deps.d.ts +24 -6
  337. package/dist/workspace/computer-deps.js +108 -20
  338. package/dist/workspace/computer-for-claim.d.ts +12 -11
  339. package/dist/workspace/computer-for-claim.js +76 -15
  340. package/dist/workspace/computer-hold.d.ts +6 -1
  341. package/dist/workspace/computer-hold.js +6 -1
  342. package/dist/workspace/computer-janitor.d.ts +47 -0
  343. package/dist/workspace/computer-janitor.js +182 -0
  344. package/dist/workspace/grep-worker.d.ts +5 -0
  345. package/dist/workspace/grep-worker.js +9 -6
  346. package/dist/workspace/index.d.ts +3 -2
  347. package/dist/workspace/index.js +3 -3
  348. package/dist/workspace/local.d.ts +11 -2
  349. package/dist/workspace/local.js +161 -43
  350. package/dist/workspace/resolve-computer.d.ts +50 -10
  351. package/dist/workspace/resolve-computer.js +46 -11
  352. package/dist/workspace/run-tools.d.ts +13 -31
  353. package/dist/workspace/run-tools.js +10 -27
  354. package/dist/workspace-paths.d.ts +0 -17
  355. package/dist/workspace-paths.js +1 -41
  356. package/dist/workspace.d.ts +0 -14
  357. package/dist/workspace.js +3 -96
  358. package/package.json +13 -13
  359. package/templates/README.md +9 -3
  360. package/templates/market-monitor/agent.md +2 -2
  361. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  362. package/dist/bound-files.d.ts +0 -4
  363. package/dist/bound-files.js +0 -164
  364. package/dist/coding-tools.d.ts +0 -47
  365. package/dist/coding-tools.js +0 -189
  366. package/dist/computer-adb.d.ts +0 -12
  367. package/dist/computer-adb.js +0 -14
  368. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  369. package/dist/console/assets/index-DvW6Aled.css +0 -1
  370. package/dist/grade.d.ts +0 -63
  371. package/dist/grade.js +0 -150
  372. package/dist/mcp-servers.d.ts +0 -269
  373. package/dist/mcp-servers.js +0 -456
  374. package/dist/packs.d.ts +0 -71
  375. package/dist/packs.js +0 -180
  376. package/dist/sealed-settings.d.ts +0 -60
  377. package/dist/sealed-settings.js +0 -171
  378. package/dist/sessions.d.ts +0 -6
  379. package/dist/sessions.js +0 -109
  380. package/dist/workspace/computer-serves.d.ts +0 -12
  381. package/dist/workspace/computer-serves.js +0 -15
@@ -1,28 +1,35 @@
1
- // The runner process: `agentrun-serve runner --data D [--loops N] [--name N]` (cli.ts, through the server's launcher, the
1
+ // The runner process: `agentrun-serve runner --data D [--loops N] [--drain-timeout D] [--name N]` (cli.ts, through the server's launcher, the
2
2
  // same bin and Node, its secrets over the launcher's pipe). A long-lived process of its own, beside the server, with its
3
3
  // own connection to the store (in the data directory, or the Postgres AGENTRUN_STORE_URL names). It never sets the store up: a store whose schema it does not know
4
4
  // (or one the server has not set up yet) is refused before any run is claimed. Once it can claim it says so in one line,
5
5
  // `Runner <name> ready: store <kind> schema v<N>, <N> loops`; from then it writes its heartbeat (runner-<name>.alive under
6
6
  // the data directory) as its loop turns, which `agentrun-serve runner --check --data D [--name N]` reads without a store
7
- // connection. SIGTERM or SIGINT closes it: every loop stopped where it can resume and its run handed back at once for
8
- // another runner (a loop that never stops is given up when its claim would run out, and its run is claimable when its
9
- // lease lapses); then 0. Bad arguments exit 2, a store schema it does not know 3, anything else 1.
10
- import { mkdirSync, statSync, utimesSync, writeFileSync } from "node:fs";
7
+ // connection. It holds at most --loops runs at once (default AGENTRUN_MAX_RUNS, else as many pi runs as this host's
8
+ // memory holds: the server's --max-runs default, host.ts maxRunsOf). SIGTERM or SIGINT closes it: each busy run finishes
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
+ // 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.
12
+ // An error nothing handles exits 1 at once, said with its stack (lastResort).
13
+ import { mkdirSync, statSync, utimesSync, writeFileSync, writeSync } from "node:fs";
11
14
  import { join } from "node:path";
12
15
  import { dockerPathsForRuns } from "../box-paths.js";
13
16
  import { hostAddressesOnce } from "../docker-host-addresses.js";
14
17
  import { HARNESS_TABLE_ENV } from "../harness-table.js";
18
+ import { maxRunsOf } from "../host.js";
15
19
  import { FAUX_PREFIX } from "../model.js";
20
+ import { durationMs } from "../print.js";
16
21
  import { bootSealKey } from "../seal-key.js";
17
22
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
18
23
  import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget } from "../store/index.js";
19
24
  import { SCHEMA_VERSION } from "../store/schema.js";
20
25
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
21
26
  import { computerDepsFrom } from "../workspace/computer-deps.js";
27
+ import { startJanitor } from "../workspace/computer-janitor.js";
22
28
  import { createDispatchLoop } from "./dispatch.js";
23
29
  import { resolveRunnerLoop } from "./harness-loops.js";
24
30
  import { routeOf } from "./model-route.js";
25
- import { RUNNER_LOOPS, RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
31
+ import { runnerMemory } from "./memory-claim.js";
32
+ import { RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
26
33
  export { RUNNER_RENEW_EVERY_MS } from "./runner.js";
27
34
  /** A store this runner cannot use, or arguments it cannot take, in words a person starting it can act on. */
28
35
  export class RunnerRefused extends Error {
@@ -102,7 +109,7 @@ export function runnerLoop(store, dataDir, env = process.env, booted) {
102
109
  env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey, routeOf,
103
110
  computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps,
104
111
  };
105
- return createDispatchLoop({ launchOf: (runId) => store.runs.launch(runId), resolve: resolveRunnerLoop(deps) });
112
+ return { createLoop: createDispatchLoop({ launchOf: (runId) => store.runs.launch(runId), resolve: resolveRunnerLoop(deps) }), computers: computers.computerDeps, env: runs };
106
113
  }
107
114
  /** Where runner `name` writes its heartbeat in `dataDir`. */
108
115
  export const heartbeatFile = (dataDir, name) => join(dataDir, `runner-${name.replace(/[^A-Za-z0-9._:-]/g, "_")}.alive`);
@@ -149,6 +156,7 @@ export async function startRunnerProcess(options) {
149
156
  const { store, kind, schema } = await openRunnerStore(options.dataDir, env, warn, options.storeUrl);
150
157
  let runner;
151
158
  let seal;
159
+ let janitor;
152
160
  try {
153
161
  // The server's seal key, booted the one way the server boots it (seal-key.ts): the one handed over, else the one in
154
162
  // this data directory, checked against what the store records. A runner on a store whose secrets another key sealed
@@ -158,17 +166,25 @@ export async function startRunnerProcess(options) {
158
166
  const name = options.name ?? runnerName();
159
167
  const made = options.createLoop ?? ofStore((opened, sealKey) => runnerLoop(opened, options.dataDir, undefined, sealKey));
160
168
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
161
- const createLoop = isStoreFactory(made) ? made(store, seal.key) : made;
169
+ const parts = isStoreFactory(made) ? made(store, seal.key) : made;
170
+ const createLoop = typeof parts === "function" ? parts : parts.createLoop;
171
+ // The janitor sweeps with the computers the loop composed, never a second composition. Its lines are the runner's
172
+ // warnings, said where the runner says its others (warn: stderr unless a test gives its own).
173
+ if (options.janitor && typeof parts !== "function")
174
+ janitor = startJanitor({ store, computers: parts.computers, env: parts.env, log: warn });
162
175
  runner = startRunner({
163
176
  store,
164
177
  createLoop,
165
178
  name,
166
179
  ...(options.loops ? { loops: options.loops } : {}),
180
+ ...(options.drainMs ? { drainMs: options.drainMs } : {}),
181
+ memory: options.memory ?? runnerMemory(store),
167
182
  ...(options.onEvent ? { onEvent: options.onEvent } : {}),
168
183
  onBeat: heartbeat(options.dataDir, name, options.now ?? Date.now),
169
184
  });
170
185
  }
171
186
  catch (error) {
187
+ await janitor?.close();
172
188
  seal?.release();
173
189
  await store.close();
174
190
  throw error;
@@ -179,7 +195,8 @@ export async function startRunnerProcess(options) {
179
195
  runner,
180
196
  store: { kind, schema },
181
197
  close: () => (closing ??= (async () => {
182
- await runner.close();
198
+ // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
199
+ await Promise.all([janitor?.close(), runner.close()]);
183
200
  await store.close();
184
201
  held.release();
185
202
  })()),
@@ -192,17 +209,49 @@ export function ofStore(make) {
192
209
  return make;
193
210
  }
194
211
  const isStoreFactory = (made) => storeFactories.has(made);
195
- /** The runner process's arguments: `--data D [--loops N] [--name N]`, or `--check --data D [--name N]`. Each option with
196
- * a value is also taken as `--option=value` (the bin hands a data directory that starts with "-" so, never read as an
197
- * option); an empty one is refused like a missing one. */
212
+ /** How long a runner process lets each busy run finish its turn on SIGTERM, unless --drain-timeout or
213
+ * AGENTRUN_DRAIN_TIMEOUT says: the image's server drain (its CMD's --drain-timeout 6s), so a runner beside a --no-runner
214
+ * server drains as the server's own runner would.
215
+ * BOUND: this drain plus the stuck-loop stop after it (runner.ts runnerCloseBoundMs: the claim's lease less its margin,
216
+ * 30 s - 5 s = 25 s) is 6 + 25 = 31 s, inside deploy/compose.yaml's 35 s stop_grace_period for its runners
217
+ * (runner-beside-flags.test.mjs pins it). Raise this default only with that grace. */
218
+ export const RUNNER_DRAIN_TIMEOUT = "6s";
219
+ /** The environment's drain for a runner process when --drain-timeout gives none. */
220
+ export const RUNNER_DRAIN_ENV = "AGENTRUN_DRAIN_TIMEOUT";
221
+ /** What a runner process holds, from its arguments and `env`: --loops, else the server's --max-runs default
222
+ * (AGENTRUN_MAX_RUNS, else as many pi runs as this host's memory holds; maxRunsOf); --drain-timeout, else
223
+ * AGENTRUN_DRAIN_TIMEOUT, else RUNNER_DRAIN_TIMEOUT. A bad AGENTRUN_MAX_RUNS or AGENTRUN_DRAIN_TIMEOUT is RunnerRefused. */
224
+ export function runnerHolds(args, env) {
225
+ let loops = args.loops;
226
+ if (loops === undefined) {
227
+ try {
228
+ loops = maxRunsOf(env);
229
+ }
230
+ catch (error) {
231
+ throw new RunnerRefused(error.message);
232
+ }
233
+ }
234
+ let drainMs = args.drainMs;
235
+ if (drainMs === undefined) {
236
+ const given = env[RUNNER_DRAIN_ENV];
237
+ drainMs = durationMs(given || RUNNER_DRAIN_TIMEOUT);
238
+ if (drainMs === undefined)
239
+ throw new RunnerRefused(`${RUNNER_DRAIN_ENV} is a duration such as 6s, 500ms or 1m, not ${JSON.stringify(given)}`);
240
+ }
241
+ return { loops, drainMs };
242
+ }
243
+ /** The runner process's arguments: `--data D [--loops N] [--drain-timeout D] [--name N]`, or `--check --data D [--name
244
+ * N]`. Each option with a value is also taken as `--option=value` (the bin hands a data directory that starts with "-"
245
+ * so, never read as an option); an empty one is refused like a missing one. */
198
246
  export function runnerArgs(argv) {
199
247
  let dataDir;
200
248
  let loops;
249
+ let drainMs;
201
250
  let name;
202
251
  let check = false;
203
252
  for (let i = 0; i < argv.length; i++) {
204
253
  const given = argv[i];
205
- const equals = /^(--(?:data|loops|name))=(.*)$/s.exec(given);
254
+ const equals = /^(--(?:data|loops|drain-timeout|name))=(.*)$/s.exec(given);
206
255
  const arg = equals ? equals[1] : given;
207
256
  const value = () => {
208
257
  const next = equals ? equals[2] : argv[++i];
@@ -218,16 +267,22 @@ export function runnerArgs(argv) {
218
267
  if (!Number.isSafeInteger(loops) || loops < 1)
219
268
  throw new RunnerRefused(`--loops is a whole number of runs above zero, not ${JSON.stringify(text)}`);
220
269
  }
270
+ else if (arg === "--drain-timeout") {
271
+ const text = value();
272
+ drainMs = durationMs(text);
273
+ if (drainMs === undefined)
274
+ throw new RunnerRefused(`--drain-timeout is a duration such as 6s, 500ms or 1m, not ${JSON.stringify(text)}`);
275
+ }
221
276
  else if (arg === "--name")
222
277
  name = value();
223
278
  else if (arg === "--check")
224
279
  check = true;
225
280
  else
226
- throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--name N], or --check --data D [--name N]`);
281
+ throw new RunnerRefused(`unknown argument ${JSON.stringify(arg)}: a runner takes --data D [--loops N] [--drain-timeout D] [--name N], or --check --data D [--name N]`);
227
282
  }
228
283
  if (!dataDir)
229
284
  throw new RunnerRefused("a runner needs its data directory: --data D");
230
- return { dataDir, ...(loops === undefined ? {} : { loops }), ...(name === undefined ? {} : { name }), ...(check ? { check: true } : {}) };
285
+ return { dataDir, ...(loops === undefined ? {} : { loops }), ...(drainMs === undefined ? {} : { drainMs }), ...(name === undefined ? {} : { name }), ...(check ? { check: true } : {}) };
231
286
  }
232
287
  /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
233
288
  * says the runner is ready (on a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one
@@ -245,6 +300,19 @@ export async function runUntilSignalled(process, signals = ["SIGTERM", "SIGINT"]
245
300
  });
246
301
  await process.close();
247
302
  }
303
+ /** The runner process's last resort (runnerMain installs it for unhandledRejection and uncaughtException): says what
304
+ * went wrong, in the runner's name with its stack, then exits 1 at once, closing nothing. A runner that went on after
305
+ * an error nothing handled could keep renewing the claim of a run whose loop is dead, and that run would hang claimed
306
+ * by a live runner. Exiting lets the claim lapse: another runner (or this one, started again) takes the run back at the
307
+ * next epoch, and the fence refuses the dead loop's late writes. The line is written to stderr synchronously
308
+ * (writeSync), so a pipe's slow reader still gets the whole stack before the exit. Exported for its test. */
309
+ export function lastResort(name, write = (line) => void writeSync(2, line), exit = (code) => process.exit(code)) {
310
+ return (reason) => {
311
+ const said = reason instanceof Error ? (reason.stack ?? `${reason.name}: ${reason.message}`) : String(reason);
312
+ write(`agentrun-serve runner: Runner ${name}: an error nothing handled, so the runner exits (its claims lapse, and are taken back): ${said}\n`);
313
+ exit(1);
314
+ };
315
+ }
248
316
  /** One line of what the runner did, in its name. */
249
317
  function said(name, event) {
250
318
  if (event.type === "claimed")
@@ -258,7 +326,7 @@ function said(name, event) {
258
326
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
259
327
  * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
260
328
  * it when --name does not. */
261
- export async function runnerMain(argv, env = process.env) {
329
+ export async function runnerMain(argv, env = process.env, hooks = {}) {
262
330
  let args;
263
331
  try {
264
332
  args = runnerArgs(argv);
@@ -283,15 +351,45 @@ export async function runnerMain(argv, env = process.env) {
283
351
  console.error(`agentrun-serve runner: ${checked.why}`);
284
352
  return 1;
285
353
  }
354
+ let holds;
355
+ try {
356
+ holds = runnerHolds(args, env);
357
+ }
358
+ catch (error) {
359
+ if (!(error instanceof RunnerRefused))
360
+ throw error;
361
+ console.error(`agentrun-serve runner: ${error.message}`);
362
+ return 2;
363
+ }
286
364
  let started;
287
365
  const runnerOf = name ?? runnerName();
366
+ // The last resort, in this process only (never the library, the server's CLI or the runner beside a server): an error
367
+ // nothing handled is said with its stack, and the process exits 1 at once (lastResort: crashing is the safe failure).
368
+ const fatal = lastResort(runnerOf);
369
+ process.on("unhandledRejection", fatal);
370
+ process.on("uncaughtException", fatal);
371
+ // The stop is listened for before the start, as the server's CLI listens (cli.ts): startRunnerProcess starts claiming
372
+ // runs before it returns, so a SIGTERM or SIGINT during it (a platform's redeploy) would otherwise end the process by the
373
+ // signal itself, its claims held and a paid request in flight cut. A stop asked then is kept, and the runner closes as
374
+ // soon as its start is done, through the same close as a stop after it: its runs handed back, its store closed.
375
+ let asked = false;
376
+ const early = () => void (asked = true);
377
+ for (const signal of RUNNER_SIGNALS)
378
+ process.on(signal, early);
379
+ const unlisten = () => {
380
+ for (const signal of RUNNER_SIGNALS)
381
+ process.off(signal, early);
382
+ };
288
383
  try {
289
384
  started = await startRunnerProcess({
290
385
  dataDir: args.dataDir,
291
386
  name: runnerOf,
292
387
  env,
293
- ...(args.loops ? { loops: args.loops } : {}),
388
+ loops: holds.loops,
389
+ drainMs: holds.drainMs,
294
390
  createLoop: ofStore((store, sealKey) => runnerLoop(store, args.dataDir, env, sealKey)),
391
+ // The runner subcommand ends what a crashed runner of this server left (never under --faux).
392
+ janitor: true,
295
393
  onEvent: (event) => {
296
394
  if (event.type === "error")
297
395
  return void console.error(`Runner ${runnerOf}: ${event.step}${event.runId ? ` ${event.runId}` : ""}: ${event.message}`);
@@ -302,10 +400,21 @@ export async function runnerMain(argv, env = process.env) {
302
400
  });
303
401
  }
304
402
  catch (error) {
403
+ unlisten();
305
404
  console.error(`agentrun-serve runner: ${error?.message ?? String(error)}`);
306
405
  return error instanceof RunnerRefused && error.cause instanceof SchemaVersionUnknown ? 3 : 1;
307
406
  }
407
+ await hooks.started?.(started);
408
+ // From here the handlers below take the stop, with nothing awaited between: no signal falls in a gap.
409
+ unlisten();
410
+ if (asked) {
411
+ console.log(`Runner ${started.runner.name} stopping: a stop came during its start`);
412
+ await started.close();
413
+ return 0;
414
+ }
308
415
  // Ready is said once SIGTERM and SIGINT are handled, so a stop sent on reading it always closes the runner.
309
- await runUntilSignalled(started, ["SIGTERM", "SIGINT"], () => console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${args.loops ?? RUNNER_LOOPS} loops`));
416
+ await runUntilSignalled(started, RUNNER_SIGNALS, () => console.log(`Runner ${started.runner.name} ready: store ${started.store.kind} schema v${started.store.schema}, ${holds.loops} loops`));
310
417
  return 0;
311
418
  }
419
+ /** The signals that stop a runner process. */
420
+ const RUNNER_SIGNALS = ["SIGTERM", "SIGINT"];
@@ -39,7 +39,7 @@ import { privateOAuthHosts } from "../mcp-private-hosts.js";
39
39
  import { GITHUB_MCP_ONLY, GITHUB_MCP_ORIGIN, githubMcpUrl } from "../github.js";
40
40
  import { githubTokens } from "./mcp-github.js";
41
41
  import { ClaimRefused } from "./loop-contract.js";
42
- import { REFRESH_MARGIN_MS, UNKNOWN_EXPIRY_MS, UNUSABLE } from "../mcp-servers.js";
42
+ import { REFRESH_MARGIN_MS, UNKNOWN_EXPIRY_MS, UNUSABLE } from "../mcp-probe.js";
43
43
  import { tokenLeftOf } from "../mcp-probe.js";
44
44
  import { openMcpCredential, sealMcpCredential } from "../store/seal.js";
45
45
  import { Fenced, MCP_REFRESH_CALL_MS } from "../store/index.js";
@@ -331,7 +331,6 @@ async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN
331
331
  // The registry keeps each tool as its server listed it (input_schema); the pin holds the harnesses' shape.
332
332
  return row && { url: row.url, tools: (row.tools ?? []).map(boundTool), ...(row.prices ? { prices: row.prices } : {}) };
333
333
  },
334
- headers: () => undefined,
335
334
  });
336
335
  }
337
336
  catch (error) {
@@ -103,6 +103,8 @@ export interface ParkedFollowUpOptions {
103
103
  text: string;
104
104
  isError?: boolean;
105
105
  }>;
106
+ /** A parked call refused (the person's deny, or its tool denied since): its end on the run's record, in those words. */
107
+ refused?(call: McpGateCall, text: string): Promise<void>;
106
108
  }
107
109
  /** For a harness with its own MCP client, on a claim that finds its MCP calls parked through the door: each asked call's
108
110
  * answer acted on once, as main's gate did after a person answered (tool-gate.ts): an allow runs the call through the
@@ -3,6 +3,7 @@ import { wireName } from "../catalog.js";
3
3
  import { mcpGateway, noCallId } from "../mcp-gateway.js";
4
4
  import { argsPreview, mcpToolName, resumeText, RESUME_PREFIX, waitingText } from "../tool-gate.js";
5
5
  import { deniedText } from "./loop-contract.js";
6
+ import { STOPPED_WHILE_WAITING } from "../refusal-words.js";
6
7
  import { endedAnswer, KINDS } from "./journal-kinds.js";
7
8
  import { mcpClaim } from "./mcp-claim.js";
8
9
  const said = (text, isError = false) => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
@@ -42,7 +43,6 @@ export async function mcpForClaim(options) {
42
43
  const gateway = mcpGateway({
43
44
  pin,
44
45
  credentials: step.credentials,
45
- liveCredentials: true,
46
46
  work: options.work,
47
47
  commit: () => (change) => options.harness.commit(change, BACKGROUND_CONTEXT),
48
48
  ...(options.fetch ? { fetch: options.fetch } : {}),
@@ -137,13 +137,23 @@ export async function parkedFollowUp(mcp, options) {
137
137
  if (answer === "park")
138
138
  return "park";
139
139
  let result;
140
- if (!answer.approved)
141
- result = { text: deniedText(call.tool, answer.note), isError: true };
140
+ if (!answer.approved) {
141
+ // A stop's withdrawal (a reopened run's parked call) reads as one; any other deny in its words.
142
+ result = { text: answer.decision === "withdrawn" ? STOPPED_WHILE_WAITING : deniedText(call.tool, answer.note), isError: true };
143
+ await options.refused?.(call, result.text);
144
+ }
142
145
  else {
143
146
  const done = ended.get(call.callId);
144
- const denied = await options.deniedNow(call);
147
+ const denied = done ? undefined : await options.deniedNow(call);
145
148
  // A call that already ended is answered from its end (endedAnswer: a crash-cut one in the kernel's words).
146
- result = done ? endedAnswer(call.tool, done) : denied !== undefined ? { text: denied, isError: true } : await options.run(call);
149
+ if (done)
150
+ result = endedAnswer(call.tool, done);
151
+ else if (denied !== undefined) {
152
+ result = { text: denied, isError: true };
153
+ await options.refused?.(call, denied);
154
+ }
155
+ else
156
+ result = await options.run(call);
147
157
  }
148
158
  texts.push(resumeText({ tool: call.tool, call_id: call.callId }, argsPreview(call.args), answer.approved ? "allow" : "deny", { text: result.text, isError: result.isError === true }));
149
159
  callIds.push(call.callId);
@@ -0,0 +1,9 @@
1
+ import type { Store } from "../store/store.js";
2
+ import type { RunnerMemory } from "./runner.js";
3
+ /** What a run launched on `harness` weighs: its table entry's run size, or a pi run's for a run on no harness of the
4
+ * table (a learning run, which runs in the runner's own process as a pi run does). */
5
+ export declare function claimMibOf(harness: string): number;
6
+ /** The runner's memory budget over `store`: `memory` bytes (default the host's, hostMemory) less the server's own, each
7
+ * waiting run weighed by the harness its launch names (store.runs.launch). A run whose launch cannot be read weighs a pi
8
+ * run: its claim fails it at once (dispatch.ts), holding nothing for long. */
9
+ export declare function runnerMemory(store: Pick<Store, "runs">, memory?: number): RunnerMemory;
@@ -0,0 +1,25 @@
1
+ // What a runner's memory holds of runs (RunnerOptions.memory): the budget is the host's memory less the server's own
2
+ // (host.ts runsMemoryMib, of the container's limit when it has one), and each waiting run weighs what a run of its
3
+ // harness reserves (its table entry's runMib: pi 128 MiB, codex 192, claude-agent 288, opencode 704). The count alone
4
+ // (--max-runs, by default as many pi runs as fit) would let a 2 GB host take 15 claude-agent runs, about 3.2 GB as
5
+ // measured, and the host's OOM kill would take every run on it; by weight it holds 6 and the rest wait queued.
6
+ import { DEFAULT_HARNESS, harnessOfBody } from "../harness.js";
7
+ import { builtinHarness } from "../harness-table.js";
8
+ import { hostMemory, runsMemoryMib } from "../host.js";
9
+ /** What a run launched on `harness` weighs: its table entry's run size, or a pi run's for a run on no harness of the
10
+ * table (a learning run, which runs in the runner's own process as a pi run does). */
11
+ export function claimMibOf(harness) {
12
+ return (builtinHarness(harness) ?? builtinHarness(DEFAULT_HARNESS)).runMib;
13
+ }
14
+ /** The runner's memory budget over `store`: `memory` bytes (default the host's, hostMemory) less the server's own, each
15
+ * waiting run weighed by the harness its launch names (store.runs.launch). A run whose launch cannot be read weighs a pi
16
+ * run: its claim fails it at once (dispatch.ts), holding nothing for long. */
17
+ export function runnerMemory(store, memory = hostMemory()) {
18
+ return {
19
+ budgetMib: runsMemoryMib(memory),
20
+ weigh: async (runIds) => new Map(await Promise.all(runIds.map(async (runId) => {
21
+ const harness = await store.runs.launch(runId).then((row) => harnessOfBody((row.body ?? {})), () => DEFAULT_HARNESS);
22
+ return [runId, claimMibOf(harness)];
23
+ }))),
24
+ };
25
+ }
@@ -1,4 +1,36 @@
1
- import { type DecisionLike, type EntryLike, type RunMetrics } from "@parcha/pi-durable-agent/timeline";
1
+ import { type DecisionLike, type EntryLike, type RunMetrics } from "../timeline/index.js";
2
+ /** What a run's booking says one of its sessions spent: its requests (a hold given back unused is none), their known
3
+ * sum, how many have no known cost, and their tokens. */
4
+ export type BookedSpend = {
5
+ readonly usd: number | null;
6
+ readonly known: number;
7
+ readonly unpriced: number;
8
+ readonly requests: number;
9
+ readonly tokens: {
10
+ input: number;
11
+ output: number;
12
+ cacheRead: number;
13
+ cacheWrite: number;
14
+ };
15
+ };
16
+ /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
17
+ * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
18
+ * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
19
+ * session alone), or its decisions (`decisions`: that session alone, which their receipts also show, so no usage row
20
+ * counts them twice). Each request at what it was booked at (`bookedUsd`, else its `usd`); one booked at no known cost,
21
+ * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
22
+ * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
23
+ * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
24
+ * booking's. */
25
+ export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions"): BookedSpend;
26
+ /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
27
+ * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
28
+ * booking (adapters/pi.ts afterResponse). */
29
+ export declare function costIsBooked(entries: readonly EntryLike[], cli: boolean): boolean;
30
+ /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
31
+ * out at its hold and bound), for a run whose cost is its booking: the runs list's figure while it runs. Null when one
32
+ * session's is unknown, never 0 for it. */
33
+ export declare function bookedCapSpend(entries: readonly EntryLike[]): number | null;
2
34
  /** A run's metrics as the end commit writes them (the StoredMetrics JSON on the run row): the timeline's count, with the
3
35
  * effort the run ran at and, on a harness other than pi, the model its revision named. */
4
36
  export type RunMetricsStored = RunMetrics & {
@@ -7,7 +7,91 @@
7
7
  // A pi run has no workflow decision receipts, so the decisions list is empty; a workflow run (when it joins the runner)
8
8
  // passes its decisions. `effort` is the level the run ran at and `model`, on a harness other than pi, the model its
9
9
  // revision named — both as storedMetrics added them, resolved by the caller from the run's launch and harness.
10
- import { runMetricsWithDecisions, timelineOf } from "@parcha/pi-durable-agent/timeline";
10
+ import { runMetricsWithDecisions, timelineOf } from "../timeline/index.js";
11
+ import { answeredUnpriced, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
12
+ import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
13
+ import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
14
+ /** The conversation each of the run's sessions books in, by its key: the first `agentrun.session.key` entry naming it. */
15
+ function sessionConversations(entries) {
16
+ const out = new Map();
17
+ for (const e of entries) {
18
+ if (e.kind !== KINDS.sessionKey)
19
+ continue;
20
+ const d = (e.data ?? {});
21
+ if (typeof d.key === "string" && !out.has(d.key) && Number.isFinite(Number(d.conversation)))
22
+ out.set(d.key, Number(d.conversation));
23
+ }
24
+ return out;
25
+ }
26
+ /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
27
+ * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
28
+ * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
29
+ * session alone), or its decisions (`decisions`: that session alone, which their receipts also show, so no usage row
30
+ * counts them twice). Each request at what it was booked at (`bookedUsd`, else its `usd`); one booked at no known cost,
31
+ * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
32
+ * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
33
+ * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
34
+ * booking's. */
35
+ export function bookedSpend(entries, which) {
36
+ const keyed = sessionConversations(entries);
37
+ const paidConv = keyed.get(TOOL_SESSION);
38
+ const decisionsConv = keyed.get(DECISION_SESSION);
39
+ const conv = (e) => Number(e.conversationId);
40
+ const chosen = (e) => (which === "paid" ? conv(e) === paidConv : which === "decisions" ? conv(e) === decisionsConv : conv(e) !== paidConv && conv(e) !== decisionsConv);
41
+ const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
42
+ const answered = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.turn && chosen(e)).map(turnOf));
43
+ let known = 0;
44
+ let unpriced = 0;
45
+ let requests = 0;
46
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
47
+ for (const e of entries) {
48
+ if (!chosen(e))
49
+ continue;
50
+ if (e.kind === RUNNER_RECORDS.request && !answered.has(turnOf(e))) {
51
+ requests += 1;
52
+ unpriced += 1;
53
+ continue;
54
+ }
55
+ if (e.kind !== RUNNER_RECORDS.turn)
56
+ continue;
57
+ const d = (e.data ?? {});
58
+ if (d.givenBack === true || d.unsent === true)
59
+ continue;
60
+ requests += 1;
61
+ // An answer with no price of its own was booked at its hold for the cap (answeredUnpriced): as a cost it is unknown.
62
+ const usd = answeredUnpriced(d) ? null : typeof d.bookedUsd === "number" && Number.isFinite(d.bookedUsd) ? d.bookedUsd : typeof d.usd === "number" && Number.isFinite(d.usd) ? d.usd : null;
63
+ if (usd === null)
64
+ unpriced += 1;
65
+ else
66
+ known += usd;
67
+ for (const key of Object.keys(tokens))
68
+ if (typeof d.usage?.[key] === "number")
69
+ tokens[key] += d.usage[key];
70
+ }
71
+ return { usd: unpriced ? null : known, known, unpriced, requests, tokens };
72
+ }
73
+ /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
74
+ * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
75
+ * booking (adapters/pi.ts afterResponse). */
76
+ export function costIsBooked(entries, cli) {
77
+ return cli || sessionConversations(entries).has(WORKFLOW_SESSION);
78
+ }
79
+ /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
80
+ * out at its hold and bound), for a run whose cost is its booking: the runs list's figure while it runs. Null when one
81
+ * session's is unknown, never 0 for it. */
82
+ export function bookedCapSpend(entries) {
83
+ let spent = 0;
84
+ // Every conversation that holds booking records, keyed or not, as bookedSpend reads them.
85
+ const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
86
+ for (const conversation of booking) {
87
+ const records = entries.filter((e) => Number(e.conversationId) === conversation && e.kind !== KINDS.sessionKey).map((e) => ({ kind: e.kind, data: (e.data ?? null) }));
88
+ const read = sessionSpendOf(records).spentUsd;
89
+ if (read === null)
90
+ return null;
91
+ spent += read;
92
+ }
93
+ return spent;
94
+ }
11
95
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
12
96
  * `effort`/`model`: the enrichment the old storedMetrics added. `costUsd` is the usage row's cost: null when a
13
97
  * response's cost is unknown, 0 before any request (costOf). */
@@ -1,4 +1,5 @@
1
1
  import type { Wire } from "@parcha/agentrun-kernel";
2
+ import type { ToolsAs } from "../local-models.js";
2
3
  import { type PinnedModel, type Tier } from "../model.js";
3
4
  import { type Redact } from "./redact.js";
4
5
  /** What a request on a model costs, USD per million tokens, as pi-ai's catalog lists it (tiers included). */
@@ -67,6 +68,7 @@ type PiModel = {
67
68
  contextWindow?: number;
68
69
  input?: readonly string[];
69
70
  inputLimits?: unknown;
71
+ toolsAs?: ToolsAs;
70
72
  };
71
73
  type PiModels = {
72
74
  getModel(provider: string, id: string): unknown;
@@ -96,6 +98,11 @@ type PiMessage = {
96
98
  usage?: RouteUsage;
97
99
  stopReason?: string;
98
100
  errorMessage?: string;
101
+ content?: {
102
+ type: string;
103
+ text?: string;
104
+ thinking?: string;
105
+ }[];
99
106
  };
100
107
  /** The route of `model` ("provider/model-id"; undefined for the host's model of `tier`; a claimed run's pin, sent as
101
108
  * pinned: chooseModel's PinnedModel), resolved from `env` as main resolves a run's model, on a wire of `wires` (the
@@ -108,4 +115,10 @@ export declare function routeOf(model: string | PinnedModel | undefined, env?: N
108
115
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
109
116
  * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
110
117
  export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch): typeof fetch;
118
+ /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
119
+ * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
120
+ * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
121
+ * cap prices a fresh input. Never more than `outputHeld`; 0 when nothing is left. So the one hold the cap took for
122
+ * the request covers every try it makes. */
123
+ export declare function reaskTokens(target: PiModel, last: RouteUsage, leftUsd: number, outputHeld: number): number;
111
124
  export {};