@parcha/agentrun-serve 0.1.0-beta.32 → 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 (444) hide show
  1. package/CHANGELOG.md +270 -0
  2. package/README.md +343 -246
  3. package/dist/adapters.d.ts +0 -7
  4. package/dist/adapters.js +11 -22
  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 +14 -0
  14. package/dist/api-only.js +33 -0
  15. package/dist/archil-routes.d.ts +1 -1
  16. package/dist/bash-read-only.d.ts +22 -0
  17. package/dist/bash-read-only.js +701 -0
  18. package/dist/box-egress-vm.d.ts +0 -8
  19. package/dist/box-egress-vm.js +0 -10
  20. package/dist/box-egress.d.ts +0 -4
  21. package/dist/box-egress.js +1 -16
  22. package/dist/box-paths.d.ts +25 -2
  23. package/dist/box-paths.js +79 -11
  24. package/dist/box-relay.d.ts +0 -11
  25. package/dist/box-relay.js +0 -20
  26. package/dist/box-settings.d.ts +26 -0
  27. package/dist/box-settings.js +63 -0
  28. package/dist/boxes.d.ts +21 -1
  29. package/dist/boxes.js +27 -20
  30. package/dist/browser-commands.d.ts +5 -2
  31. package/dist/browser-commands.js +4 -4
  32. package/dist/browser-computer.d.ts +5 -0
  33. package/dist/browser-computer.js +21 -0
  34. package/dist/browser-cost.d.ts +9 -6
  35. package/dist/browser-cost.js +94 -51
  36. package/dist/browser-live.d.ts +7 -20
  37. package/dist/browser-live.js +15 -93
  38. package/dist/browser-person.d.ts +18 -53
  39. package/dist/browser-person.js +94 -279
  40. package/dist/budget.d.ts +0 -4
  41. package/dist/budget.js +0 -7
  42. package/dist/cap.d.ts +8 -12
  43. package/dist/cap.js +12 -27
  44. package/dist/cli.js +61 -20
  45. package/dist/closed-pipes.d.ts +2 -0
  46. package/dist/closed-pipes.js +13 -0
  47. package/dist/computer-commands.d.ts +2 -0
  48. package/dist/computer-commands.js +2 -0
  49. package/dist/computer-keys.js +5 -2
  50. package/dist/computer-setting.d.ts +20 -4
  51. package/dist/computer-setting.js +25 -5
  52. package/dist/computers.d.ts +31 -3
  53. package/dist/computers.js +70 -11
  54. package/dist/confine.d.ts +120 -0
  55. package/dist/confine.js +436 -0
  56. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  57. package/dist/console/assets/index-opTN5Naq.css +1 -0
  58. package/dist/console/index.html +2 -2
  59. package/dist/daytona-api.d.ts +0 -11
  60. package/dist/daytona-api.js +1 -82
  61. package/dist/decision-rows.d.ts +1 -1
  62. package/dist/decision-rows.js +1 -1
  63. package/dist/docker-daemon.d.ts +31 -0
  64. package/dist/docker-daemon.js +56 -0
  65. package/dist/docker-host-addresses.d.ts +37 -0
  66. package/dist/docker-host-addresses.js +110 -0
  67. package/dist/effort-guidance.js +4 -3
  68. package/dist/environment.d.ts +0 -3
  69. package/dist/environment.js +3 -5
  70. package/dist/errors.d.ts +0 -2
  71. package/dist/errors.js +6 -9
  72. package/dist/filed-answer.d.ts +32 -0
  73. package/dist/filed-answer.js +160 -0
  74. package/dist/files.d.ts +1 -11
  75. package/dist/files.js +2 -21
  76. package/dist/github-connection.d.ts +2 -2
  77. package/dist/github-connection.js +1 -1
  78. package/dist/graph-view.d.ts +3 -5
  79. package/dist/graph-view.js +4 -14
  80. package/dist/handed-values.d.ts +9 -0
  81. package/dist/handed-values.js +26 -0
  82. package/dist/harness-install.d.ts +22 -5
  83. package/dist/harness-install.js +98 -20
  84. package/dist/harness-opencode/adapter.d.ts +7 -0
  85. package/dist/harness-opencode/adapter.js +23 -6
  86. package/dist/harness-opencode/index.d.ts +1 -1
  87. package/dist/harness-opencode/index.js +1 -1
  88. package/dist/harness-opencode/verify.d.ts +17 -0
  89. package/dist/harness-opencode/verify.js +30 -10
  90. package/dist/harness-table.js +6 -1
  91. package/dist/harness.d.ts +4 -3
  92. package/dist/harness.js +16 -1
  93. package/dist/heard.js +1 -1
  94. package/dist/held-fd.d.ts +5 -0
  95. package/dist/held-fd.js +14 -0
  96. package/dist/host-calls.d.ts +20 -0
  97. package/dist/host-calls.js +12 -0
  98. package/dist/host-tools.d.ts +4 -21
  99. package/dist/host-tools.js +4 -61
  100. package/dist/host.d.ts +2 -4
  101. package/dist/host.js +2 -7
  102. package/dist/import-summary.d.ts +1 -5
  103. package/dist/import-summary.js +0 -21
  104. package/dist/import.d.ts +6 -6
  105. package/dist/import.js +62 -24
  106. package/dist/key-refusal.d.ts +5 -1
  107. package/dist/key-refusal.js +19 -4
  108. package/dist/learn/check.d.ts +6 -2
  109. package/dist/learn/check.js +83 -29
  110. package/dist/learn/folder.d.ts +5 -1
  111. package/dist/learn/folder.js +10 -3
  112. package/dist/learn/grade.d.ts +14 -0
  113. package/dist/learn/grade.js +68 -12
  114. package/dist/learn/index.d.ts +4 -4
  115. package/dist/learn/index.js +4 -4
  116. package/dist/learn/reflect.d.ts +31 -2
  117. package/dist/learn/reflect.js +79 -4
  118. package/dist/learn/relevance.d.ts +24 -0
  119. package/dist/learn/relevance.js +91 -0
  120. package/dist/learn/secrets.d.ts +8 -1
  121. package/dist/learn/secrets.js +95 -15
  122. package/dist/learn/skills.d.ts +112 -14
  123. package/dist/learn/skills.js +556 -52
  124. package/dist/learned-workflow.d.ts +37 -5
  125. package/dist/learned-workflow.js +106 -12
  126. package/dist/learning-routes.d.ts +16 -49
  127. package/dist/learning-routes.js +46 -36
  128. package/dist/learning-run.d.ts +6 -250
  129. package/dist/learning-run.js +11 -665
  130. package/dist/learning-words.d.ts +12 -5
  131. package/dist/learning-words.js +18 -9
  132. package/dist/learning.d.ts +93 -77
  133. package/dist/learning.js +176 -304
  134. package/dist/live/stream.js +1 -1
  135. package/dist/live/translate.js +13 -3
  136. package/dist/local-models.d.ts +11 -5
  137. package/dist/local-models.js +13 -8
  138. package/dist/mcp-gateway.d.ts +11 -52
  139. package/dist/mcp-gateway.js +44 -148
  140. package/dist/mcp-oauth.d.ts +10 -14
  141. package/dist/mcp-oauth.js +14 -32
  142. package/dist/mcp-probe.d.ts +0 -7
  143. package/dist/mcp-probe.js +4 -10
  144. package/dist/mcp-servers-store.d.ts +6 -6
  145. package/dist/mcp-servers-store.js +13 -15
  146. package/dist/mcp-store.js +3 -4
  147. package/dist/mcp.js +4 -3
  148. package/dist/model.d.ts +6 -7
  149. package/dist/model.js +43 -27
  150. package/dist/monid.d.ts +0 -2
  151. package/dist/monid.js +3 -6
  152. package/dist/openapi.d.ts +8 -1
  153. package/dist/openapi.js +124 -50
  154. package/dist/page.d.ts +1 -3
  155. package/dist/page.js +9 -19
  156. package/dist/paid-calls.d.ts +21 -27
  157. package/dist/paid-calls.js +28 -62
  158. package/dist/pause.d.ts +0 -2
  159. package/dist/pause.js +1 -8
  160. package/dist/place.d.ts +0 -5
  161. package/dist/place.js +0 -10
  162. package/dist/print.d.ts +2 -1
  163. package/dist/print.js +4 -2
  164. package/dist/propose.js +83 -39
  165. package/dist/push-handler.d.ts +1 -1
  166. package/dist/reflect-range.d.ts +25 -0
  167. package/dist/reflect-range.js +30 -0
  168. package/dist/refusal-words.d.ts +5 -1
  169. package/dist/refusal-words.js +5 -1
  170. package/dist/rows.d.ts +1 -1
  171. package/dist/run-cut.d.ts +0 -6
  172. package/dist/run-cut.js +0 -6
  173. package/dist/run-db.d.ts +2 -13
  174. package/dist/run-db.js +2 -41
  175. package/dist/run-launch.d.ts +19 -2
  176. package/dist/run-launch.js +13 -5
  177. package/dist/run-learning-served.d.ts +46 -2
  178. package/dist/run-learning-served.js +26 -7
  179. package/dist/run-reads-over-store.d.ts +1 -1
  180. package/dist/run-reads-over-store.js +15 -6
  181. package/dist/run-secrets.d.ts +33 -0
  182. package/dist/run-secrets.js +53 -0
  183. package/dist/run-timeline-served.d.ts +5 -1
  184. package/dist/run-timeline-served.js +19 -5
  185. package/dist/run-view.d.ts +12 -17
  186. package/dist/run-view.js +29 -28
  187. package/dist/runnable.d.ts +18 -10
  188. package/dist/runnable.js +21 -10
  189. package/dist/runner/adapter-loop.d.ts +14 -3
  190. package/dist/runner/adapter-loop.js +464 -62
  191. package/dist/runner/adapter-run-spec.d.ts +29 -8
  192. package/dist/runner/adapter-run-spec.js +96 -37
  193. package/dist/runner/adapters/index.js +11 -1
  194. package/dist/runner/adapters/pi.d.ts +15 -1
  195. package/dist/runner/adapters/pi.js +19 -5
  196. package/dist/runner/beside.d.ts +30 -3
  197. package/dist/runner/beside.js +54 -12
  198. package/dist/runner/claim-secrets.d.ts +10 -1
  199. package/dist/runner/claim-secrets.js +49 -15
  200. package/dist/runner/cli-run-spec.d.ts +2 -0
  201. package/dist/runner/cli-run-spec.js +60 -17
  202. package/dist/runner/commands.js +1 -1
  203. package/dist/runner/computer-journal.d.ts +15 -2
  204. package/dist/runner/computer-journal.js +41 -5
  205. package/dist/runner/conformance/harness.js +118 -8
  206. package/dist/runner/conformance/subject.d.ts +4 -1
  207. package/dist/runner/dispatch.d.ts +8 -1
  208. package/dist/runner/dispatch.js +81 -7
  209. package/dist/runner/end-of-run.d.ts +8 -2
  210. package/dist/runner/end-of-run.js +10 -4
  211. package/dist/runner/github-app.js +1 -1
  212. package/dist/runner/harness-loops.d.ts +9 -1
  213. package/dist/runner/harness-loops.js +15 -2
  214. package/dist/runner/journal-kinds.d.ts +30 -6
  215. package/dist/runner/journal-kinds.js +20 -5
  216. package/dist/runner/journal-reader.d.ts +1 -1
  217. package/dist/runner/journal-reader.js +2 -2
  218. package/dist/runner/learning-ask.d.ts +4 -0
  219. package/dist/runner/learning-ask.js +15 -1
  220. package/dist/runner/learning-end.d.ts +18 -3
  221. package/dist/runner/learning-end.js +113 -11
  222. package/dist/runner/learning-loop.d.ts +5 -0
  223. package/dist/runner/learning-loop.js +26 -6
  224. package/dist/runner/live-ticker.d.ts +1 -1
  225. package/dist/runner/live-ticker.js +28 -4
  226. package/dist/runner/loop-contract.d.ts +3 -2
  227. package/dist/runner/main.d.ts +64 -10
  228. package/dist/runner/main.js +165 -27
  229. package/dist/runner/mcp-claim.d.ts +1 -1
  230. package/dist/runner/mcp-claim.js +2 -3
  231. package/dist/runner/mcp-run.d.ts +2 -0
  232. package/dist/runner/mcp-run.js +15 -5
  233. package/dist/runner/memory-claim.d.ts +9 -0
  234. package/dist/runner/memory-claim.js +25 -0
  235. package/dist/runner/metrics.d.ts +33 -1
  236. package/dist/runner/metrics.js +85 -1
  237. package/dist/runner/model-route.d.ts +13 -0
  238. package/dist/runner/model-route.js +154 -11
  239. package/dist/runner/redact.d.ts +8 -2
  240. package/dist/runner/redact.js +11 -2
  241. package/dist/runner/reflect-hook.d.ts +12 -1
  242. package/dist/runner/reflect-hook.js +33 -3
  243. package/dist/runner/runner.d.ts +20 -0
  244. package/dist/runner/runner.js +56 -10
  245. package/dist/runner/store-port.d.ts +1 -1
  246. package/dist/runner/store-secrets.d.ts +3 -3
  247. package/dist/runner/store-secrets.js +8 -12
  248. package/dist/runner/text-tools.d.ts +44 -0
  249. package/dist/runner/text-tools.js +237 -0
  250. package/dist/runner/workflow-loop.d.ts +6 -0
  251. package/dist/runner/workflow-loop.js +6 -4
  252. package/dist/runner/workflow-spec.d.ts +18 -0
  253. package/dist/runner/workflow-spec.js +68 -26
  254. package/dist/runs-over-store.d.ts +8 -3
  255. package/dist/runs-over-store.js +76 -19
  256. package/dist/seal-key.d.ts +54 -15
  257. package/dist/seal-key.js +232 -82
  258. package/dist/sealed-settings-store.d.ts +19 -4
  259. package/dist/sealed-settings-store.js +9 -9
  260. package/dist/sealing.d.ts +4 -0
  261. package/dist/sealing.js +20 -0
  262. package/dist/secret-cut.d.ts +1 -1
  263. package/dist/secret-cut.js +1 -1
  264. package/dist/secret-name.d.ts +9 -0
  265. package/dist/secret-name.js +15 -0
  266. package/dist/secret-writes.d.ts +0 -1
  267. package/dist/secret-writes.js +0 -1
  268. package/dist/secrets.d.ts +2 -10
  269. package/dist/secrets.js +21 -17
  270. package/dist/server-fs.d.ts +4 -0
  271. package/dist/server-fs.js +8 -2
  272. package/dist/server-lock.d.ts +0 -24
  273. package/dist/server-lock.js +1 -80
  274. package/dist/server-secrets-store.d.ts +4 -4
  275. package/dist/server-secrets-store.js +10 -32
  276. package/dist/server-secrets.d.ts +4 -9
  277. package/dist/server-secrets.js +12 -33
  278. package/dist/server.d.ts +26 -44
  279. package/dist/server.js +229 -142
  280. package/dist/sign-ins-store.d.ts +34 -36
  281. package/dist/sign-ins-store.js +27 -38
  282. package/dist/sign-ins.d.ts +2 -119
  283. package/dist/sign-ins.js +5 -311
  284. package/dist/standard-webhooks.d.ts +1 -1
  285. package/dist/standard-webhooks.js +1 -1
  286. package/dist/stats.d.ts +3 -2
  287. package/dist/stats.js +1 -1
  288. package/dist/store/agent-body.d.ts +8 -2
  289. package/dist/store/agent-body.js +16 -4
  290. package/dist/store/index.d.ts +3 -3
  291. package/dist/store/index.js +3 -3
  292. package/dist/store/open.d.ts +18 -5
  293. package/dist/store/open.js +23 -3
  294. package/dist/store/postgres/connection.d.ts +18 -2
  295. package/dist/store/postgres/connection.js +156 -32
  296. package/dist/store/postgres/migrate.d.ts +4 -0
  297. package/dist/store/postgres/migrate.js +27 -3
  298. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  299. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  300. package/dist/store/postgres/store.d.ts +9 -2
  301. package/dist/store/postgres/store.js +9 -0
  302. package/dist/store/schema.js +1 -1
  303. package/dist/store/seal.js +2 -2
  304. package/dist/store/sqlite/connection.js +49 -5
  305. package/dist/store/sqlite/run-patch.d.ts +3 -0
  306. package/dist/store/sqlite/run-patch.js +3 -0
  307. package/dist/store/sqlite/store.js +64 -20
  308. package/dist/store/store.d.ts +38 -6
  309. package/dist/store/store.js +12 -2
  310. package/dist/store-reads/cap.d.ts +1 -1
  311. package/dist/store-reads/cap.js +22 -4
  312. package/dist/store-reads/journal.d.ts +25 -6
  313. package/dist/store-reads/journal.js +173 -21
  314. package/dist/store-reads/learning.d.ts +26 -8
  315. package/dist/store-reads/learning.js +12 -4
  316. package/dist/store-reads/workflow.d.ts +1 -1
  317. package/dist/store-reads/workflow.js +1 -1
  318. package/dist/store-view.d.ts +5 -1
  319. package/dist/store-view.js +91 -23
  320. package/dist/template-eval.d.ts +60 -4
  321. package/dist/template-eval.js +120 -54
  322. package/dist/templates.d.ts +24 -10
  323. package/dist/templates.js +69 -38
  324. package/dist/timeline/group.d.ts +33 -0
  325. package/dist/timeline/group.js +77 -0
  326. package/dist/timeline/index.d.ts +7 -0
  327. package/dist/timeline/index.js +7 -0
  328. package/dist/timeline/labels.d.ts +79 -0
  329. package/dist/timeline/labels.js +150 -0
  330. package/dist/timeline/origin.d.ts +56 -0
  331. package/dist/timeline/origin.js +92 -0
  332. package/dist/timeline/render-text.d.ts +11 -0
  333. package/dist/timeline/render-text.js +62 -0
  334. package/dist/timeline/timeline.d.ts +274 -0
  335. package/dist/timeline/timeline.js +1308 -0
  336. package/dist/timeline/util.d.ts +17 -0
  337. package/dist/timeline/util.js +49 -0
  338. package/dist/tool-gate.d.ts +41 -216
  339. package/dist/tool-gate.js +79 -540
  340. package/dist/tool-keys-store.d.ts +11 -12
  341. package/dist/tool-keys-store.js +24 -31
  342. package/dist/tool-keys.d.ts +9 -104
  343. package/dist/tool-keys.js +15 -271
  344. package/dist/tool-plane.d.ts +14 -42
  345. package/dist/tool-plane.js +23 -81
  346. package/dist/tool-settings-store.d.ts +1 -2
  347. package/dist/tool-settings-store.js +5 -8
  348. package/dist/tools.d.ts +31 -19
  349. package/dist/tools.js +101 -108
  350. package/dist/trigger-adapter.d.ts +2 -2
  351. package/dist/trigger-schedule.js +2 -1
  352. package/dist/trigger-secrets-shown.js +5 -1
  353. package/dist/trigger-targets.d.ts +13 -1
  354. package/dist/trigger-targets.js +31 -1
  355. package/dist/triggers.d.ts +2 -2
  356. package/dist/triggers.js +3 -3
  357. package/dist/turn-end.d.ts +1 -1
  358. package/dist/turn-end.js +1 -1
  359. package/dist/turns.d.ts +0 -6
  360. package/dist/turns.js +0 -19
  361. package/dist/uploads.js +1 -1
  362. package/dist/usage.d.ts +0 -2
  363. package/dist/usage.js +0 -2
  364. package/dist/validate.d.ts +2 -0
  365. package/dist/validate.js +23 -14
  366. package/dist/webhooks.d.ts +102 -76
  367. package/dist/webhooks.js +266 -233
  368. package/dist/workflow-run.d.ts +114 -0
  369. package/dist/workflow-run.js +144 -0
  370. package/dist/workspace/beneath.d.ts +19 -0
  371. package/dist/workspace/beneath.js +106 -0
  372. package/dist/workspace/computer-deps.d.ts +52 -5
  373. package/dist/workspace/computer-deps.js +154 -19
  374. package/dist/workspace/computer-for-claim.d.ts +19 -14
  375. package/dist/workspace/computer-for-claim.js +77 -16
  376. package/dist/workspace/computer-hold.d.ts +6 -1
  377. package/dist/workspace/computer-hold.js +6 -1
  378. package/dist/workspace/computer-janitor.d.ts +47 -0
  379. package/dist/workspace/computer-janitor.js +182 -0
  380. package/dist/workspace/computer-providers.d.ts +6 -2
  381. package/dist/workspace/computer-providers.js +1 -1
  382. package/dist/workspace/grep-worker.d.ts +5 -0
  383. package/dist/workspace/grep-worker.js +9 -6
  384. package/dist/workspace/index.d.ts +4 -3
  385. package/dist/workspace/index.js +4 -4
  386. package/dist/workspace/local.d.ts +11 -2
  387. package/dist/workspace/local.js +161 -43
  388. package/dist/workspace/resolve-computer.d.ts +50 -10
  389. package/dist/workspace/resolve-computer.js +46 -11
  390. package/dist/workspace/run-tools.d.ts +13 -31
  391. package/dist/workspace/run-tools.js +10 -27
  392. package/dist/workspace-paths.d.ts +0 -17
  393. package/dist/workspace-paths.js +1 -41
  394. package/dist/workspace.d.ts +0 -17
  395. package/dist/workspace.js +3 -99
  396. package/launcher/agentrun-serve +6 -33
  397. package/package.json +14 -14
  398. package/templates/README.md +9 -3
  399. package/templates/inbound-lead/agent.md +1 -1
  400. package/templates/kyb/agent.md +1 -1
  401. package/templates/market-monitor/agent.md +2 -2
  402. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  403. package/dist/app.d.ts +0 -5
  404. package/dist/app.js +0 -514
  405. package/dist/bound-files.d.ts +0 -4
  406. package/dist/bound-files.js +0 -164
  407. package/dist/bounds.d.ts +0 -26
  408. package/dist/bounds.js +0 -137
  409. package/dist/coding-tools.d.ts +0 -47
  410. package/dist/coding-tools.js +0 -189
  411. package/dist/computer-adb.d.ts +0 -12
  412. package/dist/computer-adb.js +0 -14
  413. package/dist/console/assets/index-35-7aeIZ.js +0 -519
  414. package/dist/console/assets/index-Cejbov-Y.css +0 -1
  415. package/dist/content-filter.d.ts +0 -7
  416. package/dist/content-filter.js +0 -23
  417. package/dist/disk.d.ts +0 -33
  418. package/dist/disk.js +0 -85
  419. package/dist/door-line.d.ts +0 -23
  420. package/dist/door-line.js +0 -83
  421. package/dist/grade.d.ts +0 -63
  422. package/dist/grade.js +0 -150
  423. package/dist/harness-app.d.ts +0 -69
  424. package/dist/harness-app.js +0 -1162
  425. package/dist/mcp-servers.d.ts +0 -269
  426. package/dist/mcp-servers.js +0 -456
  427. package/dist/packs.d.ts +0 -71
  428. package/dist/packs.js +0 -180
  429. package/dist/request-start.d.ts +0 -27
  430. package/dist/request-start.js +0 -381
  431. package/dist/run-box.d.ts +0 -205
  432. package/dist/run-box.js +0 -661
  433. package/dist/run-holder.d.ts +0 -52
  434. package/dist/run-holder.js +0 -139
  435. package/dist/runs.d.ts +0 -1200
  436. package/dist/runs.js +0 -4103
  437. package/dist/sealed-settings.d.ts +0 -60
  438. package/dist/sealed-settings.js +0 -178
  439. package/dist/served-only.d.ts +0 -5
  440. package/dist/served-only.js +0 -12
  441. package/dist/sessions.d.ts +0 -6
  442. package/dist/sessions.js +0 -109
  443. package/dist/workspace/computer-serves.d.ts +0 -12
  444. package/dist/workspace/computer-serves.js +0 -15
@@ -1,23 +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
- import { SECRET_NAMES, secret } from "../secrets.js";
15
+ import { dockerPathsForRuns } from "../box-paths.js";
16
+ import { hostAddressesOnce } from "../docker-host-addresses.js";
17
+ import { HARNESS_TABLE_ENV } from "../harness-table.js";
18
+ import { maxRunsOf } from "../host.js";
19
+ import { FAUX_PREFIX } from "../model.js";
20
+ import { durationMs } from "../print.js";
21
+ import { bootSealKey } from "../seal-key.js";
22
+ import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
13
23
  import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget } from "../store/index.js";
14
24
  import { SCHEMA_VERSION } from "../store/schema.js";
15
25
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
16
26
  import { computerDepsFrom } from "../workspace/computer-deps.js";
27
+ import { startJanitor } from "../workspace/computer-janitor.js";
17
28
  import { createDispatchLoop } from "./dispatch.js";
18
29
  import { resolveRunnerLoop } from "./harness-loops.js";
19
30
  import { routeOf } from "./model-route.js";
20
- 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";
21
33
  export { RUNNER_RENEW_EVERY_MS } from "./runner.js";
22
34
  /** A store this runner cannot use, or arguments it cannot take, in words a person starting it can act on. */
23
35
  export class RunnerRefused extends Error {
@@ -68,22 +80,36 @@ export function runEnv(env = process.env) {
68
80
  }
69
81
  return out;
70
82
  }
83
+ /** The beside-runner's environment (the CLI start's server-and-runner): runEnv of `env` with every test switch this
84
+ * process inherited taken out (AGENTRUN_SERVE_FAUX*, the harness table: a leftover in a shell would otherwise reach a
85
+ * run without --faux, as the server's own withoutFaux keeps it from the server), then `switches`, the ones this start
86
+ * enabled (server.ts fauxEnvOf). Deleted from runEnv's result, never spread: its secrets are non-enumerable and a spread
87
+ * drops them. */
88
+ export function besideRunEnv(env, switches) {
89
+ const out = runEnv(env);
90
+ for (const name of Object.keys(out))
91
+ if (name.startsWith(FAUX_PREFIX) || name === HARNESS_TABLE_ENV)
92
+ delete out[name];
93
+ return Object.assign(out, switches);
94
+ }
71
95
  /** The runner's loop for every run: the dispatch over the store (createDispatchLoop), each run's harness loop picked by
72
96
  * its launch (harness-loops.ts resolveRunnerLoop), with the data directory, the run environment (runEnv), the store's
73
- * journal, the seal key and the model route. Refused in words with no seal key. */
74
- export function runnerLoop(store, dataDir, env = process.env) {
75
- const sealKey = sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
97
+ * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
98
+ * this process's, as it was handed or booted). Refused in words with no seal key. */
99
+ export function runnerLoop(store, dataDir, env = process.env, booted) {
100
+ const sealKey = booted ?? sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
76
101
  if (!sealKey)
77
102
  throw new RunnerRefused(`A runner needs the server's seal key (${SEAL_KEY_ENV}): start it through the server's launcher, which hands it over.`);
78
103
  const runs = runEnv(env);
79
104
  // The run's computer at its claim, composed once (workspace/computer-deps.ts): none for the runner's place, a box's
80
- // computer by the agent's setting, its keys read from the run environment first, then the store's sealed rows.
81
- const computers = computerDepsFrom({ env: runs, store, sealKey });
105
+ // computer by the agent's setting, its keys read from the run environment first, then the store's sealed rows; a
106
+ // Docker computer's mounts by where this process's Docker has the data directory (box-paths.ts), read once.
107
+ const computers = computerDepsFrom({ env: runs, store, sealKey, dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs) });
82
108
  const deps = {
83
109
  env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey, routeOf,
84
110
  computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps,
85
111
  };
86
- 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 };
87
113
  }
88
114
  /** Where runner `name` writes its heartbeat in `dataDir`. */
89
115
  export const heartbeatFile = (dataDir, name) => join(dataDir, `runner-${name.replace(/[^A-Za-z0-9._:-]/g, "_")}.alive`);
@@ -126,33 +152,53 @@ export function checkRunner(options) {
126
152
  /** Opens the store as a runner and starts claiming runs. */
127
153
  export async function startRunnerProcess(options) {
128
154
  const warn = options.warn ?? ((message) => void process.stderr.write(`agentrun-serve runner: ${message}\n`));
129
- const { store, kind, schema } = await openRunnerStore(options.dataDir, options.env ?? process.env, warn, options.storeUrl);
155
+ const env = options.env ?? process.env;
156
+ const { store, kind, schema } = await openRunnerStore(options.dataDir, env, warn, options.storeUrl);
130
157
  let runner;
158
+ let seal;
159
+ let janitor;
131
160
  try {
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
162
+ // this data directory, checked against what the store records. A runner on a store whose secrets another key sealed
163
+ // (another machine's key on a shared Postgres, a lost key file) is refused in the server's words; a runner never makes
164
+ // or records a key.
165
+ seal = await bootSealKey(store, options.dataDir, { given: handedSecret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV], role: "runner" });
132
166
  const name = options.name ?? runnerName();
133
- const made = options.createLoop ?? ofStore((opened) => runnerLoop(opened, options.dataDir));
167
+ const made = options.createLoop ?? ofStore((opened, sealKey) => runnerLoop(opened, options.dataDir, undefined, sealKey));
134
168
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
135
- const createLoop = isStoreFactory(made) ? made(store) : 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 });
136
175
  runner = startRunner({
137
176
  store,
138
177
  createLoop,
139
178
  name,
140
179
  ...(options.loops ? { loops: options.loops } : {}),
180
+ ...(options.drainMs ? { drainMs: options.drainMs } : {}),
181
+ memory: options.memory ?? runnerMemory(store),
141
182
  ...(options.onEvent ? { onEvent: options.onEvent } : {}),
142
183
  onBeat: heartbeat(options.dataDir, name, options.now ?? Date.now),
143
184
  });
144
185
  }
145
186
  catch (error) {
187
+ await janitor?.close();
188
+ seal?.release();
146
189
  await store.close();
147
190
  throw error;
148
191
  }
149
192
  let closing;
193
+ const held = seal;
150
194
  return {
151
195
  runner,
152
196
  store: { kind, schema },
153
197
  close: () => (closing ??= (async () => {
154
- 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()]);
155
200
  await store.close();
201
+ held.release();
156
202
  })()),
157
203
  };
158
204
  }
@@ -163,17 +209,49 @@ export function ofStore(make) {
163
209
  return make;
164
210
  }
165
211
  const isStoreFactory = (made) => storeFactories.has(made);
166
- /** The runner process's arguments: `--data D [--loops N] [--name N]`, or `--check --data D [--name N]`. Each option with
167
- * a value is also taken as `--option=value` (the bin hands a data directory that starts with "-" so, never read as an
168
- * 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. */
169
246
  export function runnerArgs(argv) {
170
247
  let dataDir;
171
248
  let loops;
249
+ let drainMs;
172
250
  let name;
173
251
  let check = false;
174
252
  for (let i = 0; i < argv.length; i++) {
175
253
  const given = argv[i];
176
- const equals = /^(--(?:data|loops|name))=(.*)$/s.exec(given);
254
+ const equals = /^(--(?:data|loops|drain-timeout|name))=(.*)$/s.exec(given);
177
255
  const arg = equals ? equals[1] : given;
178
256
  const value = () => {
179
257
  const next = equals ? equals[2] : argv[++i];
@@ -189,16 +267,22 @@ export function runnerArgs(argv) {
189
267
  if (!Number.isSafeInteger(loops) || loops < 1)
190
268
  throw new RunnerRefused(`--loops is a whole number of runs above zero, not ${JSON.stringify(text)}`);
191
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
+ }
192
276
  else if (arg === "--name")
193
277
  name = value();
194
278
  else if (arg === "--check")
195
279
  check = true;
196
280
  else
197
- 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]`);
198
282
  }
199
283
  if (!dataDir)
200
284
  throw new RunnerRefused("a runner needs its data directory: --data D");
201
- 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 } : {}) };
202
286
  }
203
287
  /** Runs until SIGTERM or SIGINT, then closes. `ready` is called once the signals are handled, never before: a line that
204
288
  * says the runner is ready (on a pipe, written at once) may bring a SIGTERM back before the next statement runs, and one
@@ -216,6 +300,19 @@ export async function runUntilSignalled(process, signals = ["SIGTERM", "SIGINT"]
216
300
  });
217
301
  await process.close();
218
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
+ }
219
316
  /** One line of what the runner did, in its name. */
220
317
  function said(name, event) {
221
318
  if (event.type === "claimed")
@@ -229,7 +326,7 @@ function said(name, event) {
229
326
  /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
230
327
  * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
231
328
  * it when --name does not. */
232
- export async function runnerMain(argv, env = process.env) {
329
+ export async function runnerMain(argv, env = process.env, hooks = {}) {
233
330
  let args;
234
331
  try {
235
332
  args = runnerArgs(argv);
@@ -254,15 +351,45 @@ export async function runnerMain(argv, env = process.env) {
254
351
  console.error(`agentrun-serve runner: ${checked.why}`);
255
352
  return 1;
256
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
+ }
257
364
  let started;
258
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
+ };
259
383
  try {
260
384
  started = await startRunnerProcess({
261
385
  dataDir: args.dataDir,
262
386
  name: runnerOf,
263
387
  env,
264
- ...(args.loops ? { loops: args.loops } : {}),
265
- createLoop: ofStore((store) => runnerLoop(store, args.dataDir, env)),
388
+ loops: holds.loops,
389
+ drainMs: holds.drainMs,
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,
266
393
  onEvent: (event) => {
267
394
  if (event.type === "error")
268
395
  return void console.error(`Runner ${runnerOf}: ${event.step}${event.runId ? ` ${event.runId}` : ""}: ${event.message}`);
@@ -273,10 +400,21 @@ export async function runnerMain(argv, env = process.env) {
273
400
  });
274
401
  }
275
402
  catch (error) {
403
+ unlisten();
276
404
  console.error(`agentrun-serve runner: ${error?.message ?? String(error)}`);
277
405
  return error instanceof RunnerRefused && error.cause instanceof SchemaVersionUnknown ? 3 : 1;
278
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
+ }
279
415
  // Ready is said once SIGTERM and SIGINT are handled, so a stop sent on reading it always closes the runner.
280
- 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`));
281
417
  return 0;
282
418
  }
419
+ /** The signals that stop a runner process. */
420
+ const RUNNER_SIGNALS = ["SIGTERM", "SIGINT"];
@@ -14,7 +14,7 @@ export interface McpClaimOptions {
14
14
  claim: Pick<Claim, "runId" | "epoch">;
15
15
  /** The run's granted tools, by catalog name (`mcp:<server>/<tool>` among them). */
16
16
  grants: readonly string[];
17
- /** The runner's seal key (the server's): a runner never starts without one (seal-key.ts ensureSealKey). */
17
+ /** The runner's seal key (the server's): a runner never starts without one (seal-key.ts bootSealKey). */
18
18
  sealKey: Buffer;
19
19
  /** The claim's signal: aborted when the claim is lost or the runner stops. */
20
20
  signal: AbortSignal;
@@ -14,7 +14,7 @@
14
14
  // aborts. A credential that can't be used gives its server's calls a reason (mcp-probe.ts UNUSABLE) and they are refused
15
15
  // unsent: sealed under another key or for another origin than its row's url (damaged), a sign-in refused or expired
16
16
  // (signedOut), a refresh that got no answer (silent), an address the check refuses (blocked). A runner never starts
17
- // without the seal key (seal-key.ts ensureSealKey), so a claim always has one.
17
+ // without the seal key (seal-key.ts bootSealKey), so a claim always has one.
18
18
  //
19
19
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
20
20
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
@@ -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 {};