@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45

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 (388) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +580 -320
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +92 -22
  28. package/dist/composio-preset.d.ts +4 -3
  29. package/dist/composio-preset.js +81 -11
  30. package/dist/composio-triggers.d.ts +34 -2
  31. package/dist/composio-triggers.js +261 -31
  32. package/dist/computer-attach.d.ts +40 -5
  33. package/dist/computer-attach.js +130 -15
  34. package/dist/computer-keys.d.ts +3 -0
  35. package/dist/computer-keys.js +7 -1
  36. package/dist/computer-live.js +3 -2
  37. package/dist/computer-lost.d.ts +11 -0
  38. package/dist/computer-lost.js +19 -0
  39. package/dist/computer-record.d.ts +10 -2
  40. package/dist/computer-record.js +50 -18
  41. package/dist/computer-setting.d.ts +1 -0
  42. package/dist/computer-setting.js +2 -2
  43. package/dist/computers.d.ts +21 -10
  44. package/dist/computers.js +39 -28
  45. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  46. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decisions.d.ts +1 -1
  49. package/dist/dial-relay.d.ts +29 -0
  50. package/dist/dial-relay.js +94 -0
  51. package/dist/email/tools.js +10 -5
  52. package/dist/env-proxy.d.ts +2 -0
  53. package/dist/env-proxy.js +35 -0
  54. package/dist/errors.d.ts +4 -1
  55. package/dist/errors.js +10 -4
  56. package/dist/faux-computers.d.ts +8 -2
  57. package/dist/faux-computers.js +83 -6
  58. package/dist/harness-archive.d.ts +67 -0
  59. package/dist/harness-archive.js +177 -0
  60. package/dist/harness-goose.d.ts +34 -0
  61. package/dist/harness-goose.js +87 -0
  62. package/dist/harness-install.d.ts +21 -0
  63. package/dist/harness-install.js +24 -11
  64. package/dist/harness-opencode/adapter.js +1 -1
  65. package/dist/harness-table.d.ts +59 -3
  66. package/dist/harness-table.js +119 -14
  67. package/dist/harness.d.ts +17 -1
  68. package/dist/harness.js +22 -11
  69. package/dist/host.d.ts +12 -10
  70. package/dist/host.js +19 -16
  71. package/dist/import-worker.d.ts +3 -0
  72. package/dist/import-worker.js +7 -5
  73. package/dist/import.d.ts +22 -1
  74. package/dist/import.js +141 -28
  75. package/dist/key-check.js +3 -0
  76. package/dist/learn/audit.d.ts +6 -6
  77. package/dist/learn/audit.js +3 -7
  78. package/dist/learn/check.d.ts +26 -89
  79. package/dist/learn/check.js +58 -336
  80. package/dist/learn/commit.d.ts +63 -90
  81. package/dist/learn/commit.js +124 -316
  82. package/dist/learn/compile.d.ts +53 -50
  83. package/dist/learn/compile.js +88 -103
  84. package/dist/learn/corrections.d.ts +13 -0
  85. package/dist/learn/corrections.js +23 -0
  86. package/dist/learn/delete.d.ts +17 -0
  87. package/dist/learn/delete.js +42 -0
  88. package/dist/learn/folder.d.ts +35 -47
  89. package/dist/learn/folder.js +118 -134
  90. package/dist/learn/index.d.ts +3 -5
  91. package/dist/learn/index.js +6 -9
  92. package/dist/learn/learning.sh +45 -15
  93. package/dist/learn/promote.d.ts +20 -2
  94. package/dist/learn/promote.js +17 -4
  95. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
  96. package/dist/learn/{skills.js → workflow-draft.js} +65 -59
  97. package/dist/learn/workflow-nodes.d.ts +22 -1
  98. package/dist/learn/workflow-nodes.js +29 -10
  99. package/dist/learned-workflow.js +2 -2
  100. package/dist/learning-cost.d.ts +127 -13
  101. package/dist/learning-cost.js +142 -10
  102. package/dist/learning-routes.d.ts +99 -170
  103. package/dist/learning-routes.js +199 -420
  104. package/dist/learning-run.d.ts +19 -40
  105. package/dist/learning-run.js +23 -93
  106. package/dist/learning-setting.d.ts +4 -4
  107. package/dist/learning-setting.js +6 -6
  108. package/dist/learning-words.d.ts +28 -74
  109. package/dist/learning-words.js +64 -162
  110. package/dist/learning.d.ts +62 -393
  111. package/dist/learning.js +101 -651
  112. package/dist/listen-first.d.ts +30 -0
  113. package/dist/listen-first.js +115 -0
  114. package/dist/live-reach.d.ts +25 -2
  115. package/dist/live-reach.js +46 -4
  116. package/dist/llms.txt +2 -1
  117. package/dist/local-models.d.ts +3 -11
  118. package/dist/local-models.js +5 -6
  119. package/dist/mcp-servers-store.d.ts +16 -16
  120. package/dist/model-form.js +6 -5
  121. package/dist/model.d.ts +12 -4
  122. package/dist/model.js +41 -16
  123. package/dist/native/binding.js +1 -1
  124. package/dist/native/connection.js +1 -1
  125. package/dist/native/discovery.js +1 -1
  126. package/dist/native/instructions.d.ts +3 -0
  127. package/dist/native/instructions.js +5 -3
  128. package/dist/native/remote-worker-bridge.js +9 -43
  129. package/dist/native/remote.d.ts +8 -15
  130. package/dist/native/remote.js +3 -3
  131. package/dist/native/schema.js +1 -1
  132. package/dist/native/types.d.ts +2 -2
  133. package/dist/openapi.js +375 -347
  134. package/dist/owner.d.ts +8 -0
  135. package/dist/owner.js +11 -0
  136. package/dist/paid-calls.d.ts +14 -0
  137. package/dist/paid-calls.js +31 -1
  138. package/dist/particle-provider.d.ts +11 -0
  139. package/dist/particle-provider.js +135 -0
  140. package/dist/place.d.ts +8 -3
  141. package/dist/place.js +13 -9
  142. package/dist/port-models.d.ts +12 -4
  143. package/dist/port-models.js +28 -11
  144. package/dist/print.d.ts +27 -0
  145. package/dist/print.js +21 -0
  146. package/dist/provider.d.ts +7 -0
  147. package/dist/provider.js +30 -2
  148. package/dist/reflect-range.js +2 -3
  149. package/dist/run-launch.d.ts +14 -28
  150. package/dist/run-launch.js +9 -12
  151. package/dist/run-learning-served.d.ts +16 -90
  152. package/dist/run-listing.d.ts +34 -0
  153. package/dist/run-listing.js +128 -0
  154. package/dist/run-model-key.d.ts +64 -0
  155. package/dist/run-model-key.js +147 -0
  156. package/dist/run-timeline-served.js +5 -3
  157. package/dist/run-trace.d.ts +97 -0
  158. package/dist/run-trace.js +253 -0
  159. package/dist/run-view.d.ts +15 -0
  160. package/dist/run-view.js +9 -0
  161. package/dist/runnable.js +2 -1
  162. package/dist/runner/adapter-loop.d.ts +14 -6
  163. package/dist/runner/adapter-loop.js +25 -14
  164. package/dist/runner/adapter-run-spec.d.ts +22 -7
  165. package/dist/runner/adapter-run-spec.js +130 -77
  166. package/dist/runner/adapters/index.d.ts +4 -2
  167. package/dist/runner/adapters/index.js +35 -4
  168. package/dist/runner/adapters/pi.d.ts +4 -12
  169. package/dist/runner/adapters/pi.js +2 -2
  170. package/dist/runner/audit.d.ts +5 -1
  171. package/dist/runner/audit.js +31 -12
  172. package/dist/runner/beside.d.ts +7 -2
  173. package/dist/runner/beside.js +41 -9
  174. package/dist/runner/claim-secrets.d.ts +66 -1
  175. package/dist/runner/claim-secrets.js +136 -3
  176. package/dist/runner/cli-run-spec.d.ts +2 -1
  177. package/dist/runner/cli-run-spec.js +82 -59
  178. package/dist/runner/commands.d.ts +3 -6
  179. package/dist/runner/conformance/harness.d.ts +6 -0
  180. package/dist/runner/conformance/harness.js +16 -5
  181. package/dist/runner/dispatch.d.ts +2 -2
  182. package/dist/runner/end-of-run.d.ts +6 -14
  183. package/dist/runner/end-of-run.js +8 -33
  184. package/dist/runner/feedback-round.d.ts +5 -4
  185. package/dist/runner/feedback-round.js +14 -10
  186. package/dist/runner/github-app.js +3 -1
  187. package/dist/runner/harness-loops.d.ts +0 -8
  188. package/dist/runner/harness-loops.js +30 -56
  189. package/dist/runner/held.d.ts +170 -0
  190. package/dist/runner/held.js +57 -0
  191. package/dist/runner/journal-kinds.d.ts +7 -3
  192. package/dist/runner/journal-kinds.js +2 -3
  193. package/dist/runner/learned-first.d.ts +40 -0
  194. package/dist/runner/learned-first.js +32 -0
  195. package/dist/runner/learning-end.d.ts +77 -66
  196. package/dist/runner/learning-end.js +250 -299
  197. package/dist/runner/learning-seed.d.ts +15 -33
  198. package/dist/runner/learning-seed.js +24 -45
  199. package/dist/runner/loop-contract.d.ts +8 -3
  200. package/dist/runner/loop-contract.js +4 -0
  201. package/dist/runner/loop.js +6 -2
  202. package/dist/runner/main.d.ts +18 -9
  203. package/dist/runner/main.js +82 -22
  204. package/dist/runner/mcp-run.d.ts +11 -0
  205. package/dist/runner/mcp-run.js +67 -0
  206. package/dist/runner/memory-claim.d.ts +14 -6
  207. package/dist/runner/memory-claim.js +18 -9
  208. package/dist/runner/model-route.d.ts +7 -4
  209. package/dist/runner/model-route.js +22 -10
  210. package/dist/runner/native-loop.d.ts +0 -7
  211. package/dist/runner/native-loop.js +9 -101
  212. package/dist/runner/promotion.d.ts +13 -6
  213. package/dist/runner/promotion.js +63 -17
  214. package/dist/runner/reflect-hook.d.ts +64 -91
  215. package/dist/runner/reflect-hook.js +112 -206
  216. package/dist/runner/run-channel.d.ts +43 -0
  217. package/dist/runner/run-channel.js +467 -0
  218. package/dist/runner/run-child-host.d.ts +169 -0
  219. package/dist/runner/run-child-host.js +1222 -0
  220. package/dist/runner/run-child.d.ts +1 -0
  221. package/dist/runner/run-child.js +254 -0
  222. package/dist/runner/run-errors.d.ts +2 -0
  223. package/dist/runner/run-errors.js +20 -0
  224. package/dist/runner/runner.js +58 -9
  225. package/dist/runner/sdk-ask.d.ts +78 -0
  226. package/dist/runner/sdk-ask.js +158 -0
  227. package/dist/runner/sdk-loop.d.ts +2 -4
  228. package/dist/runner/sdk-loop.js +29 -49
  229. package/dist/runner/store-secrets.d.ts +5 -3
  230. package/dist/runner/store-secrets.js +14 -6
  231. package/dist/runner/workflow-first.d.ts +5 -0
  232. package/dist/runner/workflow-first.js +4 -0
  233. package/dist/runner/workflow-spec.js +17 -4
  234. package/dist/runs-over-store.d.ts +21 -32
  235. package/dist/runs-over-store.js +44 -41
  236. package/dist/sdk/runs.d.ts +6 -11
  237. package/dist/sdk/runs.js +20 -41
  238. package/dist/sdk/schema.js +3 -4
  239. package/dist/sdk/workflows.d.ts +1 -1
  240. package/dist/seal-key.d.ts +5 -0
  241. package/dist/seal-key.js +7 -0
  242. package/dist/secrets.d.ts +3 -0
  243. package/dist/secrets.js +16 -3
  244. package/dist/server.d.ts +119 -83
  245. package/dist/server.js +1121 -419
  246. package/dist/sign-ins-store.d.ts +8 -0
  247. package/dist/sign-ins-store.js +36 -1
  248. package/dist/skills.js +1 -1
  249. package/dist/store/index.d.ts +3 -3
  250. package/dist/store/index.js +2 -2
  251. package/dist/store/journal/storage.js +3 -0
  252. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  253. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  254. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  255. package/dist/store/schema.d.ts +53 -4
  256. package/dist/store/schema.js +137 -6
  257. package/dist/store/seal.d.ts +20 -2
  258. package/dist/store/seal.js +24 -8
  259. package/dist/store/sqlite/connection.d.ts +2 -0
  260. package/dist/store/sqlite/connection.js +3 -1
  261. package/dist/store/sqlite/run-launch.d.ts +4 -1
  262. package/dist/store/sqlite/run-launch.js +12 -0
  263. package/dist/store/sqlite/run-patch.d.ts +0 -17
  264. package/dist/store/sqlite/run-patch.js +4 -33
  265. package/dist/store/sqlite/store.d.ts +3 -2
  266. package/dist/store/sqlite/store.js +360 -75
  267. package/dist/store/sqlite/worker.js +25 -0
  268. package/dist/store/store.d.ts +231 -39
  269. package/dist/store/store.js +25 -3
  270. package/dist/store-reads/analytics.js +11 -1
  271. package/dist/store-reads/learning.d.ts +131 -194
  272. package/dist/store-reads/learning.js +292 -301
  273. package/dist/store-reads/loop.d.ts +0 -1
  274. package/dist/store-reads/loop.js +1 -1
  275. package/dist/store-reads/stats.js +13 -3
  276. package/dist/store-view.d.ts +34 -2
  277. package/dist/store-view.js +108 -41
  278. package/dist/telemetry.d.ts +59 -0
  279. package/dist/telemetry.js +153 -0
  280. package/dist/template-eval.d.ts +3 -6
  281. package/dist/template-eval.js +22 -36
  282. package/dist/templates.d.ts +2 -1
  283. package/dist/templates.js +6 -3
  284. package/dist/timeline/index.d.ts +1 -1
  285. package/dist/timeline/index.js +1 -1
  286. package/dist/timeline/timeline.d.ts +5 -1
  287. package/dist/timeline/timeline.js +16 -0
  288. package/dist/tool-gate.d.ts +0 -7
  289. package/dist/tool-gate.js +1 -15
  290. package/dist/tool-keys-store.d.ts +1 -1
  291. package/dist/tool-keys.d.ts +6 -4
  292. package/dist/tool-keys.js +12 -6
  293. package/dist/tool-plane.d.ts +12 -12
  294. package/dist/tools.d.ts +13 -13
  295. package/dist/tools.js +29 -9
  296. package/dist/trigger-adapter.d.ts +3 -0
  297. package/dist/trigger-adapters.d.ts +4 -0
  298. package/dist/trigger-adapters.js +13 -0
  299. package/dist/trigger-composio.d.ts +58 -1
  300. package/dist/trigger-composio.js +160 -6
  301. package/dist/triggers.d.ts +64 -5
  302. package/dist/triggers.js +141 -17
  303. package/dist/validate.d.ts +11 -7
  304. package/dist/validate.js +9 -8
  305. package/dist/webhooks.d.ts +4 -1
  306. package/dist/webhooks.js +11 -4
  307. package/dist/workspace/agent-computer.d.ts +2 -0
  308. package/dist/workspace/agent-computer.js +2 -0
  309. package/dist/workspace/archil-claim.d.ts +7 -0
  310. package/dist/workspace/archil-claim.js +29 -0
  311. package/dist/workspace/archil.d.ts +9 -1
  312. package/dist/workspace/archil.js +165 -3
  313. package/dist/workspace/attach.d.ts +3 -1
  314. package/dist/workspace/attach.js +2 -0
  315. package/dist/workspace/attached-computers.d.ts +16 -5
  316. package/dist/workspace/attached-computers.js +25 -9
  317. package/dist/workspace/computer-deps.js +1 -1
  318. package/dist/workspace/computer-for-claim.d.ts +22 -8
  319. package/dist/workspace/computer-for-claim.js +339 -46
  320. package/dist/workspace/computer-hold.js +2 -1
  321. package/dist/workspace/computer-kept.d.ts +11 -1
  322. package/dist/workspace/computer-kept.js +24 -3
  323. package/dist/workspace/resolve-computer.d.ts +41 -21
  324. package/dist/workspace/resolve-computer.js +172 -64
  325. package/dist/workspace/revision-skills.d.ts +1 -2
  326. package/dist/workspace/revision-skills.js +3 -4
  327. package/dist/workspace/run-workspace.d.ts +1 -1
  328. package/dist/workspace/run-workspace.js +5 -0
  329. package/dist/workspace/synced-folder.d.ts +85 -0
  330. package/dist/workspace/synced-folder.js +230 -0
  331. package/dist/workspace/workspace.d.ts +4 -0
  332. package/launcher/agentrun-serve +1 -1
  333. package/package.json +10 -9
  334. package/templates/README.md +7 -7
  335. package/templates/inbound-lead/agent.md +3 -3
  336. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  337. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  338. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  339. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  340. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  341. package/templates/inbound-lead/lead.schema.json +6 -5
  342. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  343. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  344. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  345. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  346. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  347. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  348. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  349. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  350. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  351. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  352. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  353. package/dist/console/assets/index-Bz6IWncl.js +0 -711
  354. package/dist/learn/grade.d.ts +0 -138
  355. package/dist/learn/grade.js +0 -682
  356. package/dist/learn/notes.d.ts +0 -81
  357. package/dist/learn/notes.js +0 -178
  358. package/dist/learn/reflect.d.ts +0 -77
  359. package/dist/learn/reflect.js +0 -228
  360. package/dist/learn/relevance.d.ts +0 -24
  361. package/dist/learn/relevance.js +0 -91
  362. package/dist/learn/seed-check.d.ts +0 -74
  363. package/dist/learn/seed-check.js +0 -103
  364. package/dist/learning-batch.d.ts +0 -291
  365. package/dist/learning-batch.js +0 -600
  366. package/dist/learning-evals.d.ts +0 -33
  367. package/dist/learning-evals.js +0 -98
  368. package/dist/native/context.d.ts +0 -6
  369. package/dist/native/context.js +0 -22
  370. package/dist/propose.d.ts +0 -52
  371. package/dist/propose.js +0 -224
  372. package/dist/runner/learning-ask.d.ts +0 -47
  373. package/dist/runner/learning-ask.js +0 -128
  374. package/dist/runner/learning-dispatch.d.ts +0 -45
  375. package/dist/runner/learning-dispatch.js +0 -99
  376. package/dist/runner/learning-factory.d.ts +0 -16
  377. package/dist/runner/learning-factory.js +0 -50
  378. package/dist/runner/learning-loop.d.ts +0 -273
  379. package/dist/runner/learning-loop.js +0 -521
  380. package/dist/usage.d.ts +0 -11
  381. package/dist/usage.js +0 -11
  382. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  383. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  384. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  385. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  386. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  387. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  388. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,254 @@
1
+ // A run's own process (run-child-host.ts starts it, one per claim): `node --import dist/secrets.js dist/runner/run-child.js`,
2
+ // as its slot's uid where the image's helper can switch. secrets.js has read the run's own keys from descriptor 3 and
3
+ // closed it before this module loads; descriptor 4 is the channel to its runner (run-channel.ts).
4
+ //
5
+ // It runs the claim's loop as the runner would have in its own process (the dispatch, the run's harness loop), with what
6
+ // the runner holds asked over the channel: the run's journal (the runner's, behind its fence), the store's reads of the
7
+ // claim (bound to it by the runner), and what the seal key opens for the claim (held.ts). It holds no seal key, no store
8
+ // connection and no other run's anything. It ends when its loop ended and the runner closed the channel, or at once when
9
+ // the channel closes under it (its runner gone).
10
+ import { Socket } from "node:net";
11
+ import { readBackOf } from "@parcha/agentrun-computer";
12
+ import { heldInstall, setHeld } from "./held.js";
13
+ import { createDispatchLoop } from "./dispatch.js";
14
+ import { resolveRunnerLoop } from "./harness-loops.js";
15
+ import { routeOf } from "./model-route.js";
16
+ import { heldRedactor, processSecretRedactor } from "./redact.js";
17
+ import { Channel } from "./run-channel.js";
18
+ import { registerRunErrors } from "./run-errors.js";
19
+ import { runEnv } from "./main.js";
20
+ import { carriedLedger } from "../paid-calls.js";
21
+ import { heldHands } from "../workspace/computer-hold.js";
22
+ /** How often the run's process reads its loop's held state (LoopDeps.live) and posts it to its runner when it moved: the
23
+ * runner's live ticker reads the newest it was posted. */
24
+ const LIVE_POLL_MS = 200;
25
+ registerRunErrors();
26
+ const socket = new Socket({ fd: 4, readable: true, writable: true });
27
+ const channel = new Channel(socket, {
28
+ // The runner closed the channel (the loop's end answered) or is gone: nothing of the run's goes on.
29
+ onClose: () => void setImmediate(() => process.exit(0)),
30
+ // Each call carries the ledger of the tool call it is made in: what the runner does for it (an MCP tool's call, a
31
+ // computer's) books on the run's one ledger, as it would in the run's own process.
32
+ context: carriedLedger,
33
+ });
34
+ /** A journal's reads for run `runId`, each `call(read, args)` to the runner with the arguments the caller gave but its
35
+ * context (the runner reads with its own: run-child-host.ts readOf). */
36
+ function readerOf(runId, call) {
37
+ const read = (method, ...args) => call(method, args);
38
+ return {
39
+ runId,
40
+ conversation: (id) => read("conversation", id),
41
+ scanConversations: (query, limit, cursor) => read("scanConversations", query, limit, cursor),
42
+ entry: ((...args) => (args.length >= 3 ? read("entry", args[0], args[1]) : read("entry", args[0]))),
43
+ findLatestHeadMarker: (conversation, at) => read("findLatestHeadMarker", conversation, at),
44
+ scanEntries: (query, limit, cursor) => read("scanEntries", query, limit, cursor),
45
+ task: (id) => read("task", id),
46
+ scanTasks: (query, limit, cursor) => read("scanTasks", query, limit, cursor),
47
+ submission: (id) => read("submission", id),
48
+ scanSubmissions: (query, limit, cursor) => read("scanSubmissions", query, limit, cursor),
49
+ submissionByRequest: (conversation, request) => read("submissionByRequest", conversation, request),
50
+ findDocument: (address, at) => read("findDocument", address, at),
51
+ document: ((address, at) => read("document", address, at)),
52
+ scanDocuments: ((query, limit, cursor) => read("scanDocuments", query, limit, cursor)),
53
+ commitsAfter: (after, limit) => read("commitsAfter", after, limit),
54
+ close: async () => { },
55
+ };
56
+ }
57
+ /** The run's journal, the runner's of the claim: every write and read made there, under its fence. */
58
+ function remoteJournal(claim) {
59
+ return {
60
+ ...readerOf(claim.runId, (read, args) => channel.call("journal", read, args)),
61
+ async commit(batches, receive) {
62
+ const { result, seqs } = (await channel.call("journal", "commit", [batches]));
63
+ for (const [index, seq] of seqs)
64
+ receive(index, seq);
65
+ return result;
66
+ },
67
+ publishing: (publish) => publish(),
68
+ // Posted, in order before the commit it rides with; a refusal of it fails that commit (run-child-host.ts).
69
+ stage: (staged) => channel.post("journal", "stage", [staged]),
70
+ mintId: () => channel.call("journal", "mintId", []),
71
+ };
72
+ }
73
+ /** The person's hold on the claim's computer (computer-hold.ts), as the run's loop reads it here: the runner's hold, where
74
+ * the live viewer takes and gives it, mirrored. What the loop reads at once (who drives, the take, the epoch, the open
75
+ * ask, whether the run is ending) is the runner's as its last change left it; each change the runner's hold makes comes
76
+ * here as its event, the mirror read again before this process's listeners hear it. A take, a hand-back or an answer
77
+ * the loop makes is the runner's to apply, answered here as the runner's hold answers it from the same state. */
78
+ async function mirroredHold(remote) {
79
+ const read = async () => {
80
+ const [state, current, epoch, asked, finishing] = await Promise.all([remote.state(), remote.current(), remote.epoch(), remote.asked(), remote.finishing()]);
81
+ return { state, current, epoch, asked, finishing };
82
+ };
83
+ let seen = await read();
84
+ const listeners = new Set();
85
+ let heard = Promise.resolve();
86
+ await remote.on((event) => {
87
+ heard = heard.then(async () => {
88
+ seen = await read().catch(() => seen);
89
+ for (const listener of [...listeners]) {
90
+ try {
91
+ listener(event);
92
+ }
93
+ catch {
94
+ // A listener's error is not the hold's.
95
+ }
96
+ }
97
+ });
98
+ });
99
+ const forward = (made) => void Promise.resolve(made).catch(() => undefined);
100
+ return {
101
+ state: () => seen.state,
102
+ current: () => seen.current,
103
+ epoch: () => seen.epoch,
104
+ asked: () => seen.asked,
105
+ finishing: () => seen.finishing,
106
+ take(options) {
107
+ if (seen.finishing || seen.state !== "agent")
108
+ return false;
109
+ seen = { ...seen, state: "pending", current: options?.by !== undefined ? `c${options.by}` : seen.current, epoch: seen.epoch + 1 };
110
+ forward(remote.take(options));
111
+ return true;
112
+ },
113
+ finish() {
114
+ seen = { ...seen, finishing: true };
115
+ forward(remote.finish());
116
+ },
117
+ give(why, options) {
118
+ if (seen.state === "agent")
119
+ return false;
120
+ seen = { ...seen, state: "agent", current: undefined, epoch: seen.epoch + 1 };
121
+ forward(remote.give(why, options));
122
+ return true;
123
+ },
124
+ away: () => forward(remote.away()),
125
+ touched: () => forward(remote.touched()),
126
+ ask: (request, signal) => remote.ask(request, signal),
127
+ answer(id, outcome, options) {
128
+ if (seen.asked?.id !== id)
129
+ return false;
130
+ seen = { ...seen, asked: undefined, ...(seen.state !== "agent" ? { state: "agent", current: undefined, epoch: seen.epoch + 1 } : {}) };
131
+ forward(remote.answer(id, outcome, options));
132
+ return true;
133
+ },
134
+ enter: (signal) => remote.enter(signal),
135
+ on(listener) {
136
+ listeners.add(listener);
137
+ return () => listeners.delete(listener);
138
+ },
139
+ close: () => forward(remote.close()),
140
+ };
141
+ }
142
+ /** The claim's computer as the runner made it (Held.computer), with what must run here put back: the mount check attach
143
+ * runs at once (the computer package's read-back, by its epoch, of a synced folder where it is one) and the person's hold over the computer's port (the
144
+ * runner's hold, mirrored: mirroredHold). */
145
+ async function computerHere(got) {
146
+ const made = got;
147
+ const check = made.computer?.check;
148
+ const computer = made.computer && check ? { ...made.computer, check: { readBackOf, ...(check.epoch !== undefined ? { epoch: check.epoch } : {}), ...(check.sync ? { sync: true } : {}) } } : made.computer;
149
+ const hold = got.held ? await mirroredHold(got.held.hold) : undefined;
150
+ return {
151
+ ...got,
152
+ ...(computer ? { computer: computer } : {}),
153
+ ...(got.held && hold ? { held: { kind: got.held.kind, hold }, hold: (ports) => heldHands(ports, hold) } : {}),
154
+ };
155
+ }
156
+ /** The deps the run's loop runs with in this process: the runner's, with each thing it holds asked over the channel. */
157
+ function childDeps(init, store, journal, held) {
158
+ const computerForClaim = (async (_launch, _store, given) => {
159
+ const recordings = given.recordings;
160
+ const ask = {
161
+ hadComputer: given.hadComputer,
162
+ ...(given.signal instanceof AbortSignal ? { signal: given.signal } : {}),
163
+ ...(recordings?.say ? { say: recordings.say } : {}),
164
+ ...(typeof given.onImageWait === "function" ? { onImageWait: given.onImageWait } : {}),
165
+ ...(typeof given.onStarting === "function" ? { onStarting: given.onStarting } : {}),
166
+ ...(typeof given.onConnected === "function" ? { onConnected: given.onConnected } : {}),
167
+ ...(typeof given.onComputerNote === "function" ? { onComputerNote: given.onComputerNote } : {}),
168
+ };
169
+ return await computerHere((await held.computer(ask)));
170
+ });
171
+ return {
172
+ env: runEnv(process.env),
173
+ data: init.data,
174
+ journal: () => journal,
175
+ store: store,
176
+ sealKey: undefined,
177
+ routeOf,
178
+ log: (line) => channel.post("runner", "log", [line]),
179
+ computerForClaim,
180
+ computerDeps: {},
181
+ installForClaim: heldInstall,
182
+ ...(init.githubApi ? { githubApi: init.githubApi } : {}),
183
+ ...(init.githubWeb ? { githubWeb: init.githubWeb } : {}),
184
+ ...(init.githubMcpOrigin ? { githubMcpOrigin: init.githubMcpOrigin } : {}),
185
+ ...(init.mcpLoopback ? { mcpLoopback: true, mcpOwn: init.mcpOwn ?? [] } : {}),
186
+ };
187
+ }
188
+ let loop;
189
+ let made;
190
+ const loopMade = new Promise((resolve) => (made = resolve));
191
+ /** The loop target the runner calls: the claim's start, then its commands and its stop. */
192
+ channel.expose("loop", async (method, args) => {
193
+ switch (method) {
194
+ case "start": {
195
+ if (loop)
196
+ throw new Error("the run's process runs one claim");
197
+ const init = args[0];
198
+ const held = channel.remote("held");
199
+ setHeld(held);
200
+ // Store.readJournal answers at once (a reader, its reads asynchronous): the process's own reader, each read one call.
201
+ const readJournal = (runId) => readerOf(runId, (read, args) => channel.call("store", "readJournal", [runId, read, args]));
202
+ const store = channel.remote("store", { where: init.where, readJournal });
203
+ const journal = remoteJournal(init.claim);
204
+ const deps = childDeps(init, store, journal, held);
205
+ let read;
206
+ const loopDeps = {
207
+ journal: () => journal,
208
+ flush: () => channel.call("runner", "flush", []),
209
+ signal: init.signal,
210
+ delivered: channel.call("runner", "delivered", []).catch(() => undefined),
211
+ deliverNow: () => channel.call("runner", "deliverNow", []),
212
+ live: (reader) => void (read = reader),
213
+ redact: heldRedactor(processSecretRedactor()),
214
+ };
215
+ loop = createDispatchLoop({ launchOf: (runId) => store.runs.launch(runId), resolve: resolveRunnerLoop(deps) })(loopDeps);
216
+ made(loop);
217
+ // The loop's held state and whether a plain stop keeps its computer, posted when either moved.
218
+ let last = "";
219
+ const poll = setInterval(() => {
220
+ let state;
221
+ try {
222
+ state = read?.();
223
+ }
224
+ catch {
225
+ state = undefined;
226
+ }
227
+ const keeps = loop?.keepsComputer?.({ kind: "command", commandId: 0 }) === true;
228
+ let said;
229
+ try {
230
+ said = JSON.stringify([state ?? null, keeps]);
231
+ }
232
+ catch {
233
+ return;
234
+ }
235
+ if (said === last)
236
+ return;
237
+ last = said;
238
+ channel.post("runner", "live", [state, keeps]);
239
+ }, LIVE_POLL_MS);
240
+ try {
241
+ return await loop.start(init.claim);
242
+ }
243
+ finally {
244
+ clearInterval(poll);
245
+ }
246
+ }
247
+ case "command":
248
+ return (await loopMade).command(args[0]);
249
+ case "stop":
250
+ return (await loopMade).stop(args[0]);
251
+ default:
252
+ throw new Error(`a run's loop has no ${method}`);
253
+ }
254
+ });
@@ -0,0 +1,2 @@
1
+ /** Registers every error class a run's process and its runner hand each other (run-channel.ts registerErrors). */
2
+ export declare function registerRunErrors(): void;
@@ -0,0 +1,20 @@
1
+ // The errors a runner and a run's own process hand each other over their channel (run-channel.ts), made again on the
2
+ // other side as instances of their own class, so a check such as `instanceof Fenced` or `instanceof ClaimRefused` holds
3
+ // across the channel as it did in one process. Both sides register the same list.
4
+ import { ConversationBusy, ConversationIdle, ReadAfterWrite, ReadOnlySession, SessionFailed, StorageRequestError } from "@earendil-works/pi-durable";
5
+ import { CommandTaken, Fenced, RunFinal, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreLaunchMissing, StoreWorkerLost } from "../store/store.js";
6
+ import { Unanswered } from "../store/postgres/connection.js";
7
+ import { LaunchUnreadable, UnknownHarness } from "./dispatch.js";
8
+ import { NeverFits } from "./harness-loops.js";
9
+ import { ClaimRefused } from "./loop-contract.js";
10
+ import { McpClaimRefused } from "./mcp-claim.js";
11
+ import { registerErrors } from "./run-channel.js";
12
+ import { ClaimLost } from "./runner.js";
13
+ /** Registers every error class a run's process and its runner hand each other (run-channel.ts registerErrors). */
14
+ export function registerRunErrors() {
15
+ registerErrors({
16
+ ClaimRefused, NeverFits, McpClaimRefused, ClaimLost, UnknownHarness, LaunchUnreadable,
17
+ Fenced, CommandTaken, RunFinal, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreLaunchMissing, StoreWorkerLost, Unanswered,
18
+ ConversationBusy, ConversationIdle, ReadAfterWrite, ReadOnlySession, SessionFailed, StorageRequestError,
19
+ });
20
+ }
@@ -11,6 +11,10 @@ import { randomUUID } from "node:crypto";
11
11
  import { hostname } from "node:os";
12
12
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
13
13
  import { COMMAND_KINDS, endedReason } from "./commands.js";
14
+ import { COMPUTER_CALL } from "../computer-channel.js";
15
+ import { COMPUTER_HAND_BACK, COMPUTER_TAKE_OVER } from "../computer-commands.js";
16
+ import { HELD_COMMANDS } from "../computer-held.js";
17
+ import { HAND_BACK } from "./hand-back.js";
14
18
  import { KINDS, withdrawnAnswers } from "./journal-kinds.js";
15
19
  import { journalEntries } from "./journal-reader.js";
16
20
  import { ClaimRefused, stopEnd } from "./loop-contract.js";
@@ -59,6 +63,9 @@ class EndNotWithdrawn extends Error {
59
63
  }
60
64
  /** The first wait after a stopped end that withdraws a call is refused; each later one doubles (RunnerOptions). */
61
65
  export const END_RETRY_BACKOFF_MS = 5_000;
66
+ /** The command rows a row that cannot be delivered yet does not hold back (runner.ts deliver), beside a stop and a cancel:
67
+ * those that act on the run's computer for its owner, so a stop that kept the computer can still let it go. */
68
+ const PASSES_A_BLOCKED_ROW = new Set([...HELD_COMMANDS, COMPUTER_CALL, HAND_BACK, COMPUTER_TAKE_OVER, COMPUTER_HAND_BACK]);
62
69
  /** The longest wait between those tries: 5 min. */
63
70
  export const END_RETRY_CAP_MS = 300_000;
64
71
  /** The tries at that cap before the run ends stopped on its row alone (about an hour of retries in all; endRefused). */
@@ -270,6 +277,11 @@ export function startRunner(options) {
270
277
  delivery = (async () => {
271
278
  try {
272
279
  const rows = given ?? (await store.commands(held.claim.runId, held.cursor));
280
+ // A row whose delivery threw (its loop could not take it yet: a message whose model key cannot be read, adapter-
281
+ // loop.ts command) blocks the rows after it, which wait in order behind it, but a stop or a cancel: those still
282
+ // reach the loop, so a run is never kept turning and spending behind a row it cannot take. The cursor stays before
283
+ // the blocked row, which the next poll delivers again; the error is said once the rows are read.
284
+ let blocked;
273
285
  for (const row of rows) {
274
286
  if (held.stopping || held.ending || held.fence.lost || killed)
275
287
  break;
@@ -279,16 +291,55 @@ export function startRunner(options) {
279
291
  // The cursor moves past a row only once its delivery went through (handed to the loop, and any refusal written):
280
292
  // a delivery that throws leaves the row for the next poll, never skipped for the rest of the claim.
281
293
  if (row.takenAt !== null) {
282
- held.cursor = Math.max(held.cursor, row.id);
294
+ if (!blocked)
295
+ held.cursor = Math.max(held.cursor, row.id);
296
+ continue;
297
+ }
298
+ // A row handed on past a blocked row earlier (PASSES_A_BLOCKED_ROW) is never handed on again.
299
+ if (held.passed.has(row.id)) {
300
+ if (!blocked)
301
+ held.cursor = Math.max(held.cursor, row.id);
283
302
  continue;
284
303
  }
285
304
  if (row.kind === "stop" || row.kind === "cancel") {
286
- held.cursor = Math.max(held.cursor, row.id);
305
+ if (!blocked)
306
+ held.cursor = Math.max(held.cursor, row.id);
287
307
  stopLoop(held, { kind: "command", commandId: row.id, ...(row.kind === "cancel" ? { cancel: true } : {}) });
288
308
  // A stop that keeps the run's computer leaves the rows after it to be handed on (the loop head ends the rest).
289
309
  continue;
290
310
  }
291
- const outcome = COMMAND_KINDS.has(row.kind) ? await held.loop.command(row) : { refused: `no command is of kind ${JSON.stringify(row.kind)}` };
311
+ // Past a blocked row, the commands that act on the run's computer for its owner go on too (a release, a start,
312
+ // a call, a take-over and a hand-back): a stop that kept the computer must still be able to let it go. Each is
313
+ // handed on once (held.passed), the cursor still before the blocked row; the message itself is never handed on.
314
+ if (blocked) {
315
+ if (!PASSES_A_BLOCKED_ROW.has(row.kind) || held.passed.has(row.id))
316
+ continue;
317
+ try {
318
+ const passed = await held.loop.command(row);
319
+ // Marked handed on only once its answer is kept: a refusal whose write fails is asked of the loop again at the
320
+ // next delivery, so its caller hears it once the store answers, never a silence.
321
+ if ("refused" in passed) {
322
+ await store.take(held.claim, row.id, "refused", passed.refused);
323
+ emit({ type: "refused", runId: held.claim.runId, commandId: row.id, reason: passed.refused });
324
+ }
325
+ held.passed.add(row.id);
326
+ }
327
+ catch (error) {
328
+ if (isFenced(error) || held.sealed || killed)
329
+ throw error;
330
+ }
331
+ continue;
332
+ }
333
+ let outcome;
334
+ try {
335
+ outcome = COMMAND_KINDS.has(row.kind) ? await held.loop.command(row) : { refused: `no command is of kind ${JSON.stringify(row.kind)}` };
336
+ }
337
+ catch (error) {
338
+ if (isFenced(error) || held.sealed || killed)
339
+ throw error;
340
+ blocked = { error };
341
+ continue;
342
+ }
292
343
  if (held.sealed || killed)
293
344
  return;
294
345
  // `taken`: the loop's commit took it. `later`: left untaken for the run's next claim. Only a refusal is written here.
@@ -298,6 +349,8 @@ export function startRunner(options) {
298
349
  }
299
350
  held.cursor = Math.max(held.cursor, row.id);
300
351
  }
352
+ if (blocked)
353
+ throw blocked.error;
301
354
  }
302
355
  catch (error) {
303
356
  if (held.sealed || killed)
@@ -410,12 +463,8 @@ export function startRunner(options) {
410
463
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
411
464
  const endStopped = async (claim, stop) => {
412
465
  try {
413
- // A learning run is never reopened (reopenableWhere), so its person's stop keeps no outcome 'stopped' (which would
414
- // read it waiting on a message for good): it reads stopped, as the learning loop's own stop end leaves it.
415
466
  const end = stopEnd(stop.kind === "cancel");
416
- const launch = end.outcome === "stopped" ? await store.runs.launch?.(claim.runId).catch(() => undefined) : undefined;
417
- const learning = launch?.body?.harness === "learning";
418
- await endRun(claim, learning ? { state: end.state, summary: end.summary } : end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
467
+ await endRun(claim, end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
419
468
  return true;
420
469
  }
421
470
  catch (error) {
@@ -631,7 +680,7 @@ export function startRunner(options) {
631
680
  },
632
681
  redact,
633
682
  });
634
- const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
683
+ const held = { passed: new Set(), claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
635
684
  heldNow = held;
636
685
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
637
686
  ending = () => {
@@ -0,0 +1,78 @@
1
+ import { type Wire } from "@parcha/agentrun-kernel";
2
+ import type { Journal } from "./loop-contract.js";
3
+ import type { RouteCost } from "./model-route.js";
4
+ /** How long the ask waits, once it answered, for the proxy to book its request: the proxy books a request after its
5
+ * client has the whole answer, so the spend is read once it is booked. One booked later than this reads unknown. */
6
+ export declare const ASK_BOOKING_WAIT_MS = 10000;
7
+ /** The session an SDK run's end-of-run asks are booked under, in the run's journal. */
8
+ export declare const SDK_ASK_SESSION = "learning.sdk";
9
+ /** Where the ask goes: the route's wire (`api`, Anthropic's Messages or OpenAI's Responses) at `origin`, for `model`,
10
+ * priced by `price`. A model on neither wire comes as the route's Messages translation (model-route.ts messagesFetch). */
11
+ export interface AskRoute {
12
+ readonly provider: {
13
+ readonly api: Wire;
14
+ readonly origin: string;
15
+ readonly credential: () => string | Promise<string>;
16
+ readonly headers?: Readonly<Record<string, string>>;
17
+ readonly auth?: "bearer" | "x-api-key";
18
+ };
19
+ readonly model: string;
20
+ /** The catalog's entry for the model (whether it reasons, its window), as pi's session takes it (model-route.ts). */
21
+ readonly like?: {
22
+ readonly reasoning?: boolean;
23
+ readonly contextWindow?: number;
24
+ readonly maxTokens?: number;
25
+ };
26
+ /** A request's price from its usage (the proxy's booking reads it). */
27
+ readonly price?: (model: string, usage: {
28
+ input: number;
29
+ output: number;
30
+ cacheRead: number;
31
+ cacheWrite: number;
32
+ }) => number | null;
33
+ /** The upstream fetch (a test's scripted origin). */
34
+ readonly fetch?: typeof fetch;
35
+ readonly cost?: RouteCost;
36
+ readonly unpriced?: boolean;
37
+ readonly outputCeiling?: number | null;
38
+ }
39
+ /** The run's cap the ask is held to: its figure now (a raise's, else its launch's; undefined: none, and only the run's
40
+ * limit of requests on free models holds), what the run spent outside its sessions (null: unknown, which a cap refuses
41
+ * on), and that limit (`freeRequests`). */
42
+ export interface AskCap {
43
+ readonly capUsd: number | undefined;
44
+ beside(): Promise<number | null>;
45
+ readonly freeRequests: number;
46
+ }
47
+ /** An ask the run's cap refused before it left: nothing of it was sent. Its message is the cap's words; `booked`, what the
48
+ * ask's session had booked before it (an earlier attempt's requests; usd null: unknown). */
49
+ export declare class AskOverCap extends Error {
50
+ readonly booked: {
51
+ readonly usd: number | null;
52
+ readonly turns: number;
53
+ };
54
+ name: string;
55
+ constructor(message: string, booked: {
56
+ readonly usd: number | null;
57
+ readonly turns: number;
58
+ });
59
+ }
60
+ /** One booked ask on `route`, held to the run's `cap`: its text, and what it spent (null: unknown). */
61
+ export declare function bookedAsk(route: AskRoute, cap: AskCap): (request: {
62
+ prompt: string;
63
+ maxTokens: number;
64
+ }, signal: AbortSignal, run: {
65
+ journal(): Journal;
66
+ flush(): Promise<void>;
67
+ }) => Promise<{
68
+ text: string;
69
+ usd: number | null;
70
+ }>;
71
+ /** The ask's route for `model` (the agent's own), from the runner's one route (`routeOf`), but where this host reaches the
72
+ * model's vendor only through OpenRouter (provider.ts openRouterOnly):
73
+ * - an Anthropic model, at OpenRouter's Messages endpoint as a claude-agent run's requests go (providerFor), priced at
74
+ * OpenRouter's catalog price of the model;
75
+ * - an OpenAI model, the same model on OpenRouter (`openrouter/openai/<id>`, the route's own translation).
76
+ * A faux host (FAUX_ENV) and a gateway take the model as named. Every other Anthropic model goes by Anthropic's own id
77
+ * (anthropicModelId), so the catalog finds it. */
78
+ export declare function askRouteOf(model: string | undefined, env: NodeJS.ProcessEnv, routeOf: (model: string | undefined) => AskRoute | Promise<AskRoute>): Promise<AskRoute>;
@@ -0,0 +1,158 @@
1
+ // A backend SDK run's end-of-run asks (its compile turn): a paid model request like a pi turn, on the same path. Its
2
+ // session (SDK_ASK_SESSION) lives in the run's own journal (journalSessions). Before it leaves, the run's cap judges it as
3
+ // it judges every paid step (the kernel's runCap: beforeRequestOf over runBooking), with every session of the run summed
4
+ // and what the run spent outside them (`AskCap.beside`: its backend's reported job), never the ask's own spend alone; it is
5
+ // held at its whole input uncached and its whole output bound, so a compile never runs on a cut answer. One the cap refuses
6
+ // is never sent: the ask throws AskOverCap in the cap's words. An admitted one's record is written and made durable before
7
+ // it leaves, and its cost booked when it answers (modelPortFor); it reaches the provider only through the kernel's model
8
+ // proxy (startModelProxy with the booking's port), which sends only what the cap admitted.
9
+ import { randomBytes } from "node:crypto";
10
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
11
+ import { createModels } from "@earendil-works/pi-ai/models";
12
+ import { createRegistry, Harness } from "@earendil-works/pi-durable";
13
+ import { modelPortFor } from "@parcha/agentrun-kernel";
14
+ import { runCap } from "@parcha/agentrun-kernel/kernel/cap";
15
+ import { startModelProxy } from "@parcha/agentrun-kernel/host";
16
+ import { FAUX_ENV } from "../model.js";
17
+ import { sessionProvider } from "../port-models.js";
18
+ import { anthropicModelId, openRouterOnly, providerFor } from "../provider.js";
19
+ import { capModelOf } from "./adapter-run-spec.js";
20
+ import { policyFor } from "./adapters/pi.js";
21
+ import { journalSessions } from "./sessions.js";
22
+ /** How long the ask waits, once it answered, for the proxy to book its request: the proxy books a request after its
23
+ * client has the whole answer, so the spend is read once it is booked. One booked later than this reads unknown. */
24
+ export const ASK_BOOKING_WAIT_MS = 10_000;
25
+ /** The session an SDK run's end-of-run asks are booked under, in the run's journal. */
26
+ export const SDK_ASK_SESSION = "learning.sdk";
27
+ const PROVIDER = "agentrun-sdk-ask";
28
+ /** An ask the run's cap refused before it left: nothing of it was sent. Its message is the cap's words; `booked`, what the
29
+ * ask's session had booked before it (an earlier attempt's requests; usd null: unknown). */
30
+ export class AskOverCap extends Error {
31
+ booked;
32
+ name = "AskOverCap";
33
+ constructor(message, booked) {
34
+ super(message);
35
+ this.booked = booked;
36
+ }
37
+ }
38
+ /** `journal` as its Harness sees it: every method its own, but close, which is the claim's to do, not the ask's. */
39
+ function unclosed(journal) {
40
+ return new Proxy(journal, {
41
+ get(target, key) {
42
+ if (key === "close")
43
+ return async () => undefined;
44
+ const value = Reflect.get(target, key, target);
45
+ return typeof value === "function" ? value.bind(target) : value;
46
+ },
47
+ });
48
+ }
49
+ /** One booked ask on `route`, held to the run's `cap`: its text, and what it spent (null: unknown). */
50
+ export function bookedAsk(route, cap) {
51
+ const { model } = route;
52
+ const capModel = capModelOf(route);
53
+ return async (request, signal, run) => {
54
+ const context = withAbortSignal(signal, BACKGROUND_CONTEXT);
55
+ const harness = await Harness.open(unclosed(run.journal()), { models: createModels(), registry: createRegistry(), onReport: () => { } }, context);
56
+ try {
57
+ const sessions = journalSessions(harness, context, { flush: () => run.flush() });
58
+ const writer = await sessions.open(SDK_ASK_SESSION);
59
+ // The run's one rule, as every paid step takes it: asked with every session of the run summed and its spend beside them.
60
+ const held = runCap({
61
+ sessions: { keys: () => sessions.keys(), read: (key) => sessions.read(key), beside: () => cap.beside() },
62
+ capUsd: () => cap.capUsd,
63
+ modelOf: (id) => (id === model ? capModel : undefined),
64
+ freeRequests: cap.freeRequests,
65
+ stopped: signal,
66
+ });
67
+ let refused;
68
+ let booked;
69
+ const booking = await modelPortFor(writer, {
70
+ key: SDK_ASK_SESSION,
71
+ label: "learning",
72
+ // Its whole output bound is the least it is sent with: refused, never cut.
73
+ beforeRequest: async (asked) => {
74
+ const answer = await held.before(asked.outputTokensAsked === undefined ? asked : { ...asked, outputTokensLeast: asked.outputTokensAsked });
75
+ if (answer && "refuse" in answer)
76
+ refused = answer;
77
+ return answer;
78
+ },
79
+ // The rule before a side effect: the request's record is durable before the request leaves.
80
+ onEvent: async (event) => {
81
+ if (event.type === "request_start")
82
+ await run.flush();
83
+ if (event.type === "request_end")
84
+ booked?.();
85
+ },
86
+ });
87
+ // A request an earlier attempt sent and a crash cut is booked first, at its held figure.
88
+ await booking.bookCut();
89
+ const before = booking.spentUsd();
90
+ const bookedOnce = new Promise((resolve) => (booked = () => resolve(true)));
91
+ const proxy = await startModelProxy({
92
+ policy: await policyFor(route.provider, model, []),
93
+ hooks: booking.models,
94
+ model,
95
+ origin: route.provider.origin,
96
+ credential: async () => (await route.provider.credential()) ?? "",
97
+ ...(route.price ? { price: route.price } : {}),
98
+ ...(route.provider.headers ? { headers: route.provider.headers } : {}),
99
+ ...(route.fetch ? { fetch: route.fetch } : {}),
100
+ }, randomBytes(32).toString("base64url"));
101
+ try {
102
+ const models = createModels();
103
+ models.setProvider(sessionProvider(route.provider.api, proxy, model, { provider: PROVIDER, keyName: "AGENTRUN_SDK_ASK_KEY", like: { ...route.like, maxTokens: request.maxTokens }, reasoning: false }));
104
+ const target = models.getModel(PROVIDER, model);
105
+ // Refused by the cap before it left, however its client came back: nothing of it was sent or spent.
106
+ const overCap = () => (refused ? new AskOverCap(refused.refuse, { usd: booking.spentUsd(), turns: booking.turns() }) : undefined);
107
+ let answer;
108
+ try {
109
+ answer = (await models.completeSimple(target, { messages: [{ role: "user", content: request.prompt, timestamp: Date.now() }] }, { signal, maxTokens: request.maxTokens }));
110
+ }
111
+ catch (error) {
112
+ throw overCap() ?? error;
113
+ }
114
+ const over = overCap();
115
+ if (over)
116
+ throw over;
117
+ if (answer.stopReason === "error" || answer.stopReason === "aborted")
118
+ throw new Error(`the request failed: ${answer.errorMessage ?? answer.stopReason}`);
119
+ const text = answer.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("");
120
+ let timer;
121
+ const inTime = await Promise.race([bookedOnce, new Promise((resolve) => (timer = setTimeout(() => resolve(false), ASK_BOOKING_WAIT_MS)))]);
122
+ clearTimeout(timer);
123
+ const after = inTime ? booking.spentUsd() : null;
124
+ return { text, usd: before === null || after === null ? null : after - before };
125
+ }
126
+ finally {
127
+ await proxy.close().catch(() => undefined);
128
+ }
129
+ }
130
+ finally {
131
+ await harness.close(context).catch(() => undefined);
132
+ }
133
+ };
134
+ }
135
+ /** The ask's route for `model` (the agent's own), from the runner's one route (`routeOf`), but where this host reaches the
136
+ * model's vendor only through OpenRouter (provider.ts openRouterOnly):
137
+ * - an Anthropic model, at OpenRouter's Messages endpoint as a claude-agent run's requests go (providerFor), priced at
138
+ * OpenRouter's catalog price of the model;
139
+ * - an OpenAI model, the same model on OpenRouter (`openrouter/openai/<id>`, the route's own translation).
140
+ * A faux host (FAUX_ENV) and a gateway take the model as named. Every other Anthropic model goes by Anthropic's own id
141
+ * (anthropicModelId), so the catalog finds it. */
142
+ export async function askRouteOf(model, env, routeOf) {
143
+ const slash = model?.indexOf("/") ?? -1;
144
+ if (model === undefined || slash < 1 || env.AGENT_MODEL_BASE_URL || env[FAUX_ENV])
145
+ return routeOf(model);
146
+ const [vendor, id] = [model.slice(0, slash), model.slice(slash + 1)];
147
+ if (vendor === "anthropic" && openRouterOnly("anthropic-messages", env)) {
148
+ const sent = providerFor("anthropic-messages", env, { provider: "anthropic", modelId: id }, "the SDK run's learning");
149
+ const priced = await routeOf(`${sent.priceModel.provider}/${sent.priceModel.modelId}`);
150
+ const capped = { ...(priced.cost ? { cost: priced.cost } : {}), ...(priced.unpriced ? { unpriced: true } : {}), ...(priced.outputCeiling !== undefined ? { outputCeiling: priced.outputCeiling } : {}) };
151
+ return { model: sent.modelId, provider: { api: "anthropic-messages", origin: sent.origin, credential: sent.credential, auth: sent.auth }, ...(priced.like ? { like: priced.like } : {}), ...(priced.price ? { price: priced.price } : {}), ...capped };
152
+ }
153
+ if (vendor === "openai" && openRouterOnly("openai-responses", env))
154
+ return routeOf(`openrouter/openai/${id}`);
155
+ if (vendor === "anthropic")
156
+ return routeOf(`anthropic/${anthropicModelId({ provider: "anthropic", modelId: id })}`);
157
+ return routeOf(model);
158
+ }
@@ -1,7 +1,5 @@
1
1
  import type { RunLaunch } from "../run-launch.js";
2
- import type { Store } from "../store/store.js";
3
2
  import type { AdapterSpecDeps } from "./adapter-run-spec.js";
4
- import { type GraderRoute } from "./learning-ask.js";
3
+ import { type AskRoute } from "./sdk-ask.js";
5
4
  import { type LoopFactory } from "./loop-contract.js";
6
- export declare function sdkSourceInstructions(store: Store, runId: string): Promise<string>;
7
- export declare function createSdkLoop(launch: RunLaunch, host: AdapterSpecDeps, route: () => Promise<GraderRoute>): LoopFactory;
5
+ export declare function createSdkLoop(launch: RunLaunch, host: AdapterSpecDeps, route: () => Promise<AskRoute>): LoopFactory;