@parcha/agentrun-serve 0.1.0-beta.58 → 0.1.0-beta.59

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 (375) hide show
  1. package/CHANGELOG.md +325 -1
  2. package/README.md +332 -88
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agents-store.js +1 -1
  8. package/dist/answer-text.d.ts +3 -0
  9. package/dist/answer-text.js +22 -0
  10. package/dist/attach-conformance.js +5 -4
  11. package/dist/box-paths.d.ts +3 -2
  12. package/dist/box-paths.js +5 -4
  13. package/dist/browser-computer.d.ts +3 -8
  14. package/dist/browser-computer.js +12 -35
  15. package/dist/browser-cost.js +94 -20
  16. package/dist/capacity.d.ts +1 -1
  17. package/dist/capacity.js +3 -3
  18. package/dist/chatgpt-plan.d.ts +5 -0
  19. package/dist/chatgpt-plan.js +25 -11
  20. package/dist/claude-login-token.d.ts +15 -11
  21. package/dist/claude-login-token.js +167 -107
  22. package/dist/claude-login.d.ts +76 -31
  23. package/dist/claude-login.js +426 -79
  24. package/dist/claude-sign-in.d.ts +3 -0
  25. package/dist/claude-sign-in.js +10 -1
  26. package/dist/cli.js +323 -292
  27. package/dist/composio-made.d.ts +1 -6
  28. package/dist/composio-made.js +1 -6
  29. package/dist/composio-owners.d.ts +26 -0
  30. package/dist/composio-owners.js +36 -0
  31. package/dist/composio-preset.d.ts +56 -23
  32. package/dist/composio-preset.js +173 -77
  33. package/dist/composio-triggers.d.ts +4 -4
  34. package/dist/composio-triggers.js +6 -7
  35. package/dist/compute-cost.js +11 -2
  36. package/dist/computer-attach.d.ts +6 -3
  37. package/dist/computer-attach.js +41 -29
  38. package/dist/computer-held-routes.d.ts +1 -1
  39. package/dist/computer-held-routes.js +9 -4
  40. package/dist/computer-keys.d.ts +11 -1
  41. package/dist/computer-keys.js +26 -1
  42. package/dist/computer-record.js +3 -1
  43. package/dist/computer-view.d.ts +5 -3
  44. package/dist/computer-view.js +10 -6
  45. package/dist/computer-viewer.js +36 -7
  46. package/dist/computers.d.ts +2 -1
  47. package/dist/computers.js +6 -3
  48. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  49. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  50. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  51. package/dist/console/assets/share-L84tlUDW.js +6 -0
  52. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  53. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  54. package/dist/console/index.html +4 -3
  55. package/dist/console/share.html +17 -0
  56. package/dist/decisions.d.ts +17 -7
  57. package/dist/decisions.js +41 -15
  58. package/dist/dial-relay.js +10 -4
  59. package/dist/docker-daemon.js +4 -5
  60. package/dist/docker-host-addresses.js +29 -11
  61. package/dist/email/account.d.ts +6 -0
  62. package/dist/email/account.js +6 -0
  63. package/dist/email/authentication.d.ts +21 -0
  64. package/dist/email/authentication.js +106 -0
  65. package/dist/email/email-faux.d.ts +11 -2
  66. package/dist/email/email-faux.js +21 -5
  67. package/dist/email/mail.d.ts +25 -0
  68. package/dist/email/mail.js +58 -2
  69. package/dist/email/names.js +2 -2
  70. package/dist/email/tools.d.ts +9 -4
  71. package/dist/email/tools.js +95 -13
  72. package/dist/env-switch.d.ts +12 -2
  73. package/dist/env-switch.js +23 -3
  74. package/dist/errors.d.ts +1 -0
  75. package/dist/errors.js +2 -0
  76. package/dist/fal-price.d.ts +11 -1
  77. package/dist/fal-price.js +33 -0
  78. package/dist/faux-computers.js +1 -1
  79. package/dist/filed-answer.d.ts +2 -2
  80. package/dist/filed-answer.js +2 -2
  81. package/dist/graph-served.d.ts +10 -5
  82. package/dist/graph-served.js +40 -10
  83. package/dist/handed-values.js +1 -2
  84. package/dist/harness-check.d.ts +2 -1
  85. package/dist/harness-check.js +45 -12
  86. package/dist/harness-keys.js +9 -6
  87. package/dist/harness-opencode/facts.js +2 -0
  88. package/dist/harness-recipe-entry.d.ts +9 -3
  89. package/dist/harness-recipe-entry.js +18 -9
  90. package/dist/harness-recipe.d.ts +21 -0
  91. package/dist/harness-recipe.js +25 -3
  92. package/dist/harness-table.d.ts +8 -0
  93. package/dist/harness-table.js +17 -6
  94. package/dist/helper-env.d.ts +4 -1
  95. package/dist/helper-env.js +4 -1
  96. package/dist/host-check.d.ts +2 -3
  97. package/dist/host-check.js +13 -7
  98. package/dist/hosted-search.js +1 -1
  99. package/dist/import.d.ts +11 -8
  100. package/dist/import.js +437 -186
  101. package/dist/key-refusal.d.ts +9 -2
  102. package/dist/key-refusal.js +86 -32
  103. package/dist/learn/audit.d.ts +8 -5
  104. package/dist/learn/audit.js +15 -7
  105. package/dist/learn/compile.d.ts +5 -2
  106. package/dist/learn/compile.js +45 -21
  107. package/dist/learn/field-check.d.ts +111 -0
  108. package/dist/learn/field-check.js +174 -0
  109. package/dist/learn/ledger.d.ts +32 -29
  110. package/dist/learn/ledger.js +26 -19
  111. package/dist/learn/promote.d.ts +79 -36
  112. package/dist/learn/promote.js +60 -65
  113. package/dist/learn/secrets.d.ts +4 -0
  114. package/dist/learn/secrets.js +12 -0
  115. package/dist/learned-nodes.d.ts +8 -5
  116. package/dist/learned-nodes.js +8 -5
  117. package/dist/learned-workflow.d.ts +2 -1
  118. package/dist/learned-workflow.js +13 -10
  119. package/dist/learning-cost.d.ts +25 -8
  120. package/dist/learning-cost.js +23 -8
  121. package/dist/learning-setting.d.ts +6 -0
  122. package/dist/learning-setting.js +11 -1
  123. package/dist/listen-first.d.ts +5 -4
  124. package/dist/listen-first.js +4 -5
  125. package/dist/live-reach.d.ts +7 -0
  126. package/dist/live-reach.js +7 -0
  127. package/dist/mcp-api-only-origins.d.ts +15 -0
  128. package/dist/mcp-api-only-origins.js +40 -0
  129. package/dist/mcp-gateway.d.ts +16 -2
  130. package/dist/mcp-gateway.js +41 -3
  131. package/dist/mcp-oauth.d.ts +1 -1
  132. package/dist/mcp-oauth.js +3 -2
  133. package/dist/mcp-probe.d.ts +3 -0
  134. package/dist/mcp-probe.js +3 -0
  135. package/dist/mcp-secret-writes.d.ts +24 -2
  136. package/dist/mcp-secret-writes.js +30 -2
  137. package/dist/mcp-servers-store.d.ts +52 -14
  138. package/dist/mcp-servers-store.js +165 -61
  139. package/dist/mcp-sources.d.ts +1 -2
  140. package/dist/mcp-sources.js +1 -2
  141. package/dist/mcp-store.d.ts +5 -5
  142. package/dist/mcp-store.js +3 -3
  143. package/dist/mcp.js +1 -1
  144. package/dist/model-gateway.d.ts +1 -1
  145. package/dist/model-gateway.js +20 -36
  146. package/dist/ollama-provider.d.ts +23 -9
  147. package/dist/ollama-provider.js +49 -20
  148. package/dist/openapi.js +202 -51
  149. package/dist/otel/genai.d.ts +83 -7
  150. package/dist/otel/genai.js +69 -9
  151. package/dist/otel/tracer.d.ts +42 -13
  152. package/dist/otel/tracer.js +241 -56
  153. package/dist/page.d.ts +7 -1
  154. package/dist/page.js +76 -22
  155. package/dist/paid-calls.d.ts +6 -4
  156. package/dist/paid-calls.js +15 -7
  157. package/dist/place-offers.d.ts +55 -34
  158. package/dist/place-offers.js +93 -54
  159. package/dist/place.d.ts +13 -14
  160. package/dist/place.js +56 -41
  161. package/dist/print.js +1 -1
  162. package/dist/provider.d.ts +3 -2
  163. package/dist/provider.js +17 -8
  164. package/dist/redact/match.d.ts +27 -9
  165. package/dist/redact/match.js +266 -57
  166. package/dist/run-census.d.ts +1 -1
  167. package/dist/run-census.js +4 -5
  168. package/dist/run-cut.js +4 -5
  169. package/dist/run-export-store.d.ts +15 -0
  170. package/dist/run-export-store.js +30 -0
  171. package/dist/run-export.d.ts +139 -0
  172. package/dist/run-export.js +379 -0
  173. package/dist/run-file-cut.d.ts +5 -0
  174. package/dist/run-file-cut.js +13 -0
  175. package/dist/run-launch.js +16 -3
  176. package/dist/run-model-key.d.ts +15 -6
  177. package/dist/run-model-key.js +30 -31
  178. package/dist/run-reads-over-store.js +4 -4
  179. package/dist/run-secrets.js +3 -5
  180. package/dist/run-timeline-served.js +3 -1
  181. package/dist/runnable.js +2 -2
  182. package/dist/runner/adapter-loop.d.ts +35 -18
  183. package/dist/runner/adapter-loop.js +94 -47
  184. package/dist/runner/adapter-run-spec.d.ts +14 -1
  185. package/dist/runner/adapter-run-spec.js +64 -28
  186. package/dist/runner/adapters/pi.js +4 -2
  187. package/dist/runner/audit.d.ts +8 -5
  188. package/dist/runner/audit.js +37 -17
  189. package/dist/runner/beside.js +5 -6
  190. package/dist/runner/claim-secrets.d.ts +10 -3
  191. package/dist/runner/claim-secrets.js +29 -13
  192. package/dist/runner/cli-run-spec.d.ts +18 -0
  193. package/dist/runner/cli-run-spec.js +81 -46
  194. package/dist/runner/compare-end.d.ts +2 -1
  195. package/dist/runner/compare-end.js +25 -10
  196. package/dist/runner/conformance/harness.js +2 -3
  197. package/dist/runner/conformance/subject.d.ts +4 -1
  198. package/dist/runner/harness-loops.js +3 -3
  199. package/dist/runner/held.d.ts +5 -2
  200. package/dist/runner/journal-kinds.d.ts +4 -1
  201. package/dist/runner/journal-kinds.js +22 -4
  202. package/dist/runner/learned-first.js +20 -4
  203. package/dist/runner/learning-end.d.ts +2 -8
  204. package/dist/runner/learning-end.js +11 -19
  205. package/dist/runner/live-ticker.js +7 -5
  206. package/dist/runner/loop-contract.d.ts +0 -2
  207. package/dist/runner/loop.d.ts +7 -0
  208. package/dist/runner/loop.js +1 -0
  209. package/dist/runner/main.js +12 -11
  210. package/dist/runner/mcp-claim.js +21 -5
  211. package/dist/runner/meta-tools.js +3 -2
  212. package/dist/runner/metrics.d.ts +7 -0
  213. package/dist/runner/metrics.js +19 -0
  214. package/dist/runner/model-route.d.ts +10 -7
  215. package/dist/runner/model-route.js +79 -15
  216. package/dist/runner/native-loop.js +10 -8
  217. package/dist/runner/presence.d.ts +1 -4
  218. package/dist/runner/presence.js +6 -8
  219. package/dist/runner/promotion.d.ts +25 -13
  220. package/dist/runner/promotion.js +125 -50
  221. package/dist/runner/redact.d.ts +3 -1
  222. package/dist/runner/redact.js +5 -3
  223. package/dist/runner/responses-fetch.d.ts +36 -0
  224. package/dist/runner/responses-fetch.js +511 -0
  225. package/dist/runner/run-child-host.d.ts +20 -5
  226. package/dist/runner/run-child-host.js +179 -77
  227. package/dist/runner/run-child.js +11 -4
  228. package/dist/runner/runner-check.js +5 -1
  229. package/dist/runner/runner.d.ts +2 -3
  230. package/dist/runner/runner.js +13 -9
  231. package/dist/runner/sdk-loop.js +8 -8
  232. package/dist/runner/spec-holds.d.ts +8 -1
  233. package/dist/runner/spec-holds.js +9 -4
  234. package/dist/runner/workflow-calls.d.ts +9 -0
  235. package/dist/runner/workflow-calls.js +150 -0
  236. package/dist/runner/workflow-first.d.ts +120 -32
  237. package/dist/runner/workflow-first.js +218 -94
  238. package/dist/runner/workflow-spec.js +1 -1
  239. package/dist/runs-over-store.js +8 -7
  240. package/dist/save-once.d.ts +14 -0
  241. package/dist/save-once.js +31 -0
  242. package/dist/scrub-command.d.ts +34 -31
  243. package/dist/scrub-command.js +116 -147
  244. package/dist/sdk/runs.d.ts +6 -0
  245. package/dist/sdk/runs.js +89 -10
  246. package/dist/seal-key.js +4 -4
  247. package/dist/secret-cut.d.ts +3 -0
  248. package/dist/secret-cut.js +7 -1
  249. package/dist/secret-rules.d.ts +8 -1
  250. package/dist/secret-rules.js +482 -53
  251. package/dist/secrets.d.ts +51 -9
  252. package/dist/secrets.js +311 -21
  253. package/dist/server-keys.d.ts +4 -3
  254. package/dist/server-keys.js +4 -3
  255. package/dist/server-secrets-store.js +2 -4
  256. package/dist/server.d.ts +15 -3
  257. package/dist/server.js +312 -80
  258. package/dist/share-context.d.ts +22 -0
  259. package/dist/share-context.js +76 -0
  260. package/dist/shell-lex.d.ts +105 -0
  261. package/dist/shell-lex.js +646 -0
  262. package/dist/sign-ins-store.d.ts +5 -7
  263. package/dist/sign-ins-store.js +12 -16
  264. package/dist/sign-ins.d.ts +7 -11
  265. package/dist/sign-ins.js +40 -41
  266. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  267. package/dist/start-switches.d.ts +6 -5
  268. package/dist/start-switches.js +8 -4
  269. package/dist/stats.d.ts +5 -1
  270. package/dist/stats.js +1 -1
  271. package/dist/store/agent-body.js +2 -2
  272. package/dist/store/dialect.d.ts +4 -0
  273. package/dist/store/dialect.js +1 -0
  274. package/dist/store/index.d.ts +2 -2
  275. package/dist/store/index.js +1 -1
  276. package/dist/store/mcp-record-keys.d.ts +10 -0
  277. package/dist/store/mcp-record-keys.js +13 -0
  278. package/dist/store/postgres/dialect.js +2 -0
  279. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  280. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  281. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  282. package/dist/store/postgres/store.js +4 -0
  283. package/dist/store/schema.d.ts +33 -10
  284. package/dist/store/schema.js +70 -16
  285. package/dist/store/seal.d.ts +4 -1
  286. package/dist/store/sqlite/run-launch.d.ts +3 -10
  287. package/dist/store/sqlite/run-launch.js +12 -23
  288. package/dist/store/sqlite/run-patch.d.ts +17 -10
  289. package/dist/store/sqlite/run-patch.js +50 -13
  290. package/dist/store/sqlite/store.d.ts +3 -0
  291. package/dist/store/sqlite/store.js +116 -34
  292. package/dist/store/store-schema.js +3 -4
  293. package/dist/store/store.d.ts +67 -32
  294. package/dist/store/store.js +14 -11
  295. package/dist/store-reads/analytics.d.ts +2 -1
  296. package/dist/store-reads/analytics.js +7 -5
  297. package/dist/store-reads/learning.d.ts +35 -26
  298. package/dist/store-reads/learning.js +120 -92
  299. package/dist/store-reads/stats.d.ts +2 -2
  300. package/dist/store-reads/stats.js +13 -7
  301. package/dist/store-view.js +10 -7
  302. package/dist/suggestions.d.ts +1 -1
  303. package/dist/suggestions.js +29 -13
  304. package/dist/template-eval.d.ts +72 -9
  305. package/dist/template-eval.js +358 -64
  306. package/dist/timeline/labels.d.ts +1 -1
  307. package/dist/timeline/labels.js +4 -3
  308. package/dist/timeline/timeline.d.ts +23 -11
  309. package/dist/timeline/timeline.js +115 -31
  310. package/dist/timeline/web-calls.d.ts +8 -6
  311. package/dist/timeline/web-calls.js +10 -6
  312. package/dist/tool-gate.d.ts +13 -1
  313. package/dist/tool-gate.js +43 -3
  314. package/dist/tool-keys-store.js +2 -4
  315. package/dist/tool-keys.d.ts +11 -0
  316. package/dist/tool-keys.js +16 -0
  317. package/dist/tool-plane.d.ts +50 -11
  318. package/dist/tool-plane.js +94 -30
  319. package/dist/tools.d.ts +5 -1
  320. package/dist/tools.js +7 -7
  321. package/dist/trigger-email.js +12 -6
  322. package/dist/triggers.d.ts +15 -34
  323. package/dist/triggers.js +119 -126
  324. package/dist/validate.d.ts +8 -1
  325. package/dist/validate.js +163 -23
  326. package/dist/web-fake.d.ts +2 -1
  327. package/dist/web-fake.js +8 -6
  328. package/dist/web-fetch.d.ts +8 -6
  329. package/dist/web-fetch.js +13 -11
  330. package/dist/web-holds.d.ts +32 -0
  331. package/dist/web-holds.js +86 -0
  332. package/dist/web-run.d.ts +32 -5
  333. package/dist/web-run.js +75 -28
  334. package/dist/web-save.js +23 -12
  335. package/dist/web-search.js +14 -25
  336. package/dist/wires.d.ts +4 -3
  337. package/dist/wires.js +5 -4
  338. package/dist/workspace/archil-claim.d.ts +12 -5
  339. package/dist/workspace/archil-claim.js +45 -5
  340. package/dist/workspace/attach.js +52 -19
  341. package/dist/workspace/attached-computers.d.ts +6 -2
  342. package/dist/workspace/attached-computers.js +5 -4
  343. package/dist/workspace/computer-deps.d.ts +23 -6
  344. package/dist/workspace/computer-deps.js +35 -17
  345. package/dist/workspace/computer-for-claim.d.ts +21 -4
  346. package/dist/workspace/computer-for-claim.js +160 -54
  347. package/dist/workspace/computer-intervals.d.ts +2 -0
  348. package/dist/workspace/computer-intervals.js +1 -1
  349. package/dist/workspace/computer-janitor.d.ts +48 -14
  350. package/dist/workspace/computer-janitor.js +153 -44
  351. package/dist/workspace/computer-kept.d.ts +158 -32
  352. package/dist/workspace/computer-kept.js +288 -63
  353. package/dist/workspace/computer-providers.d.ts +8 -3
  354. package/dist/workspace/computer-providers.js +12 -5
  355. package/dist/workspace/index.d.ts +1 -1
  356. package/dist/workspace/index.js +1 -1
  357. package/dist/workspace/local.js +41 -1
  358. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  359. package/dist/workspace/mount-revoke-left.js +72 -0
  360. package/dist/workspace/paired-route.js +4 -5
  361. package/dist/workspace/resolve-computer.d.ts +5 -2
  362. package/dist/workspace/resolve-computer.js +9 -3
  363. package/dist/workspace/run-end-computers.d.ts +11 -5
  364. package/dist/workspace/run-end-computers.js +153 -28
  365. package/dist/workspace/run-tools.d.ts +22 -3
  366. package/dist/workspace/run-tools.js +17 -5
  367. package/dist/workspace/run-workspace.d.ts +14 -1
  368. package/dist/workspace/run-workspace.js +34 -1
  369. package/dist/workspace/workspace.d.ts +6 -0
  370. package/package.json +12 -13
  371. package/skills/agentrun-serve/SKILL.md +5 -2
  372. package/templates/README.md +22 -6
  373. package/dist/console/assets/backend-CSAWUqtZ.js +0 -166
  374. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  375. package/dist/console/assets/index-DPh29cyz.js +0 -747
@@ -15,19 +15,23 @@
15
15
  // cost. Both are the cost page's own (store-reads/learning.ts, over learn/ledger.ts summarize): the served side reads a
16
16
  // run's all-in (its booked cost, the workflow and any handback's agent work together, and every learning round booked
17
17
  // for it), and the by-hand cost is the job's own cost of the agent's runs on its own path among the same runs (its newest
18
- // PAST_RUNS on no named disk since its learning's reset), so a compile turn is never by hand: it is its revision's spend. A run
19
- // whose cost is unknown is left out of its side's mean and counted, never read as 0. Over that line it stops running
20
- // first: the agent takes the run, the run's journal keeps why with the two numbers (WORKFLOW_FIRST, outcome
21
- // needs_revision), and the agent's cost per run shows it stopped. The stop asks for no compile. A new revision of it (a
18
+ // PAST_RUNS on no named disk since its learning's reset; with none there, the newest COST_WINDOW before them), so a
19
+ // compile turn is never by hand: it is its revision's spend. A run
20
+ // whose cost is unknown is left out of its side's mean and counted, never read as 0. Over that line it stops, whoever
21
+ // made its calls: it no longer runs first, the agent's own learned_workflow tool leaves it out (toolStopsOf), the run's
22
+ // journal keeps why with the two numbers (WORKFLOW_FIRST, outcome needs_revision), and the agent's cost per run shows it
23
+ // stopped. The stop asks for no compile. A new revision of it (a
22
24
  // new digest: one its hold asked, or its owner's) serves again from zero. Fewer than
23
- // COST_WINDOW served runs, or no by-hand cost at all (said in the log): it serves. Every input is the run record's path
25
+ // COST_WINDOW served runs: it serves. Past runs it can't read, or no by-hand cost at all: it fails closed, the agent
26
+ // takes the run and its learned_workflow tool runs none of it (said in the log), never served unchecked. Every input is the run record's path
24
27
  // (metrics.path, one classifier: store-reads/learning.ts runPathOverStore). The rule catches a workflow that costs more
25
28
  // than doing the job by hand; it does not catch one that answers wrong with confidence. The spec builders
26
29
  // (adapter-run-spec.ts, cli-run-spec.ts) choose here, once per claim; the adapter loop serves it (adapter-loop.ts, before
27
30
  // the first input), through the run's own learned_workflow tool, gate, record and ledger.
28
31
  import { createHash } from "node:crypto";
29
32
  import { LEARNING_LABEL } from "../learning.js";
30
- import { COST_WINDOW, SERVED_PATHS } from "../learning-cost.js";
33
+ import { COST_WINDOW, SERVED_PATHS, workflowCallsIn } from "../learning-cost.js";
34
+ import { workflowCallsOf } from "./workflow-calls.js";
31
35
  import { auditableLaunch } from "../learn/audit.js";
32
36
  export { COST_WINDOW };
33
37
  import { KINDS } from "./journal-kinds.js";
@@ -39,28 +43,42 @@ import { comparedOf, sameAnswer } from "../learn/promote.js";
39
43
  export const WORKFLOW_FIRST = "agentrun.workflow_first";
40
44
  /** The one call id a run's workflow-first call goes under: replay never, a crash's call is ended interrupted. */
41
45
  export const WORKFLOW_FIRST_CALL = "workflow-first";
42
- /** No runs read: nothing to stop. */
43
- export const NO_PAST_RUNS = { runs: [], by_hand: null, by_hand_unknown: 0 };
44
46
  /** How many of the agent's newest runs on no named disk the money rule reads, both sides (store-reads/learning.ts
45
47
  * pastRunsOf): a launch's read is bounded whatever the agent's history, and the cost page reads the same window. */
46
48
  export const PAST_RUNS = 500;
47
- const SERVED = ["workflow", "handed_back"];
48
49
  const usd = (value) => Math.round(value * 1e6) / 1e6;
49
- const meanOf = (costs) => (costs.length ? { runs: costs.length, mean_usd: usd(costs.reduce((a, b) => a + b, 0) / costs.length) } : null);
50
- const pathFields = (metrics) => (isObject(metrics) ? metrics : {});
50
+ /** The mean of `costs`, rounded to 1e-6; null for none. */
51
+ export const meanOf = (costs) => (costs.length ? { runs: costs.length, mean_usd: usd(costs.reduce((a, b) => a + b, 0) / costs.length) } : null);
52
+ /** The calls a run's all-in is charged to, of those its record keeps (`metrics.workflow_calls`, learning-cost.ts
53
+ * workflowCallsIn) that ran (one refused before any node ran ran nothing): the platform's, when it served the run first
54
+ * (the run is that workflow's alone, whatever the agent called after it handed back), else each the agent called. A
55
+ * record that keeps no calls (a run that ended before they were kept) is charged as its path says, the rule calls
56
+ * replaced: the workflow and digest it names when its path is one a workflow served (`workflow`, `handed_back`), so a
57
+ * stop made on those runs stays made. */
58
+ const chargedCallsIn = (metrics) => {
59
+ const calls = workflowCallsIn(metrics);
60
+ if (!calls.length) {
61
+ const { path, workflow, workflow_digest: digest } = (metrics ?? {});
62
+ return SERVED_PATHS.includes(path) && typeof workflow === "string" && typeof digest === "string" ? [{ workflow, digest, caller: "platform", outcome: path === "workflow" ? "answered" : "handed_back", usd: null }] : [];
63
+ }
64
+ const ran = calls.filter((call) => call.outcome !== "refused");
65
+ const first = ran.filter((call) => call.caller === "platform");
66
+ return first.length ? first : ran;
67
+ };
51
68
  /** The money rule's two sides for workflow `name` at `digest`, over the agent's runs (`past`): `served`, the mean all-in
52
- * of its newest COST_WINDOW runs served first at that digest (path workflow or handed_back) whose all-in is known (the
53
- * cost page's `after` side reads the same figure); `by_hand`, as given (PastRuns: the job's own $ over the same runs,
54
- * never a second baseline here); `unknown_runs`, the runs either side would have read that it left out for an unknown cost (the cost
55
- * page's rule: left out and counted). */
69
+ * of its newest COST_WINDOW runs charged to it at that digest (their record's `workflow_calls`, chargedCallsIn: the
70
+ * platform's call before the agent's first turn, else the agent's own) whose all-in is known
71
+ * (the cost page's `after` side reads the same figure); `by_hand`, as given (PastRuns: the job's own $ over the same
72
+ * runs, never a second baseline here); `unknown_runs`, the runs either side would have read that it left out for an
73
+ * unknown cost (the cost page's rule: left out and counted). */
56
74
  export function costLineOf(past, name, digest) {
57
75
  const newest = [...past.runs].sort((a, b) => b.startedAt - a.startedAt);
58
76
  const known = (run) => typeof run.allInUsd === "number" && Number.isFinite(run.allInUsd);
59
- const ran = (run) => { const m = pathFields(run.metrics); return m.workflow === name && SERVED.includes(m.path); };
77
+ const called = (run) => chargedCallsIn(run.metrics).some((call) => call.workflow === name && call.digest === digest);
60
78
  // Newest first, until COST_WINDOW known: an unknown one met before the window filled is one it left out.
61
79
  const served = [];
62
80
  let servedUnknown = 0;
63
- for (const run of newest.filter((run) => ran(run) && pathFields(run.metrics).workflow_digest === digest)) {
81
+ for (const run of newest.filter(called)) {
64
82
  if (served.length >= COST_WINDOW)
65
83
  break;
66
84
  if (known(run))
@@ -73,25 +91,41 @@ export function costLineOf(past, name, digest) {
73
91
  /** Whether a cost line is over the money rule's line: COST_WINDOW served runs or more at the digest, a by-hand cost to
74
92
  * hold them to, and their mean at or over it. */
75
93
  export const overLine = (line) => line.served.runs >= COST_WINDOW && line.by_hand !== null && line.served.mean_usd !== null && line.served.mean_usd >= line.by_hand.mean_usd;
94
+ export const stopReasonOf = (line) => overLine(line) ? "over_line" : line.served.runs >= COST_WINDOW && line.by_hand === null ? "no_by_hand_cost" : null;
76
95
  /** The money rule's decision over the agent's runs (`past`, store-reads/learning.ts pastRunsOverStore): whether it stops a
77
- * workflow at a digest from running first (overLine), the one workflowFirstOf reads at a claim. Each workflow's state
78
- * (learn/promote.ts servingStateOf) folds it in at its champion's digest. */
79
- export const costStopOf = (past) => (workflow, digest) => overLine(costLineOf(past, workflow, digest));
80
- /** Each learned workflow that has served one of the agent's runs (`past`) first, at the digest its newest served run
81
- * ran, with the money rule's two sides there, the runs they left out for an unknown all-in, and where it stands:
82
- * `serving`, or `needs_revision` once over the line (overLine). What the agent's cost per run shows its owner. */
96
+ * workflow at a digest from running first (stopReasonOf). Each workflow's state (learn/promote.ts servingStateOf) folds
97
+ * it in at its champion's digest. */
98
+ export const costStopOf = (past) => (workflow, digest) => stopReasonOf(costLineOf(past, workflow, digest)) !== null;
99
+ /** Each learned workflow one of the agent's runs (`past`) is charged to (its record's `workflow_calls`, chargedCallsIn),
100
+ * at the digest its newest such call ran, with the money rule's two sides there, the runs they left out for an unknown
101
+ * all-in, and where it stands: `serving`, or `needs_revision` with why once the money rule stops it (stopReasonOf, the
102
+ * launch's decision). What the agent's cost per run shows its owner. */
83
103
  export function workflowCostsOf(past) {
84
104
  const newest = new Map();
85
105
  for (const run of [...past.runs].sort((a, b) => b.startedAt - a.startedAt)) {
86
- const m = pathFields(run.metrics);
87
- if (SERVED.includes(m.path) && typeof m.workflow === "string" && typeof m.workflow_digest === "string" && !newest.has(m.workflow))
88
- newest.set(m.workflow, m.workflow_digest);
106
+ for (const call of chargedCallsIn(run.metrics).reverse())
107
+ if (!newest.has(call.workflow))
108
+ newest.set(call.workflow, call.digest);
89
109
  }
90
110
  return [...newest].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([workflow, digest]) => {
91
111
  const line = costLineOf(past, workflow, digest);
92
- return { workflow, digest, state: overLine(line) ? "needs_revision" : "serving", served: line.served.runs ? line.served : null, by_hand: line.by_hand, unknown_cost_runs: line.unknown_runs };
112
+ const reason = stopReasonOf(line);
113
+ return { workflow, digest, state: reason ? "needs_revision" : "serving", reason, served: line.served.runs ? line.served : null, by_hand: line.by_hand, unknown_cost_runs: line.unknown_runs };
93
114
  });
94
115
  }
116
+ /** Why the platform did or did not run a learned workflow first (firstChoice), kept on every learning run's record
117
+ * (metrics.first_choice): `served`, one serves; `replay`, a replay run serves the workflow it replays;
118
+ * `replay_missing`, its claim laid no workflow by that name, or its input is no object; `none_laid`, the run is not
119
+ * agentic, learns nothing, or its claim laid no workflow; `off`, its launch forces the agent (workflow_first: false);
120
+ * `none_fit`, no laid workflow (nor a champion in place of one) takes its input; `many_fit`, more than one laid
121
+ * workflow does; `not_promoted`, the one that does is not promoted, nor a champion of it; `champion_misfit`, its
122
+ * champion does not take the input; `many_champions`, more than one champion does; `cost_stop`, the money rule
123
+ * stopped it (costLineOf), or, nothing else served or stopped first, one the agent's own tool would run (toolStopsOf:
124
+ * runner/learned-first.ts); `no_by_hand_cost`, the one that serves has COST_WINDOW served runs and no by-hand cost to
125
+ * hold them to (stopReasonOf), and fails closed: the agent takes the run, no revision asked; `past_unread`, the money
126
+ * rule could not read the agent's past runs, and fails closed: the agent takes the run; `held`, a check refused the
127
+ * claim's workflow and nothing serves this claim. */
128
+ export const FIRST_REASONS = ["served", "replay", "replay_missing", "none_laid", "off", "none_fit", "many_fit", "not_promoted", "champion_misfit", "many_champions", "cost_stop", "no_by_hand_cost", "past_unread", "held"];
95
129
  /** The laid learned workflows with a first choice's champion (FirstChoice) in place of its laid revision: what
96
130
  * runner/promotion.ts toolFlowsFor reads the rest of from the promotion records, so the run's tool runs only what serves. */
97
131
  export const laidFor = (laid, choice) => choice.champion ? laid.map((one) => (one.name === choice.champion.name ? choice.champion : one)) : [...laid];
@@ -138,100 +172,185 @@ export function sdkTakes(workflow, task, resolve) {
138
172
  }
139
173
  /** A learned workflow's digest: the first 16 hex of its text's sha256. A new revision of it is a new digest. */
140
174
  export const workflowDigest = (workflow) => createHash("sha256").update(workflow.workflow).digest("hex").slice(0, 16);
141
- /** The workflow a run serves first (`serve`), or the one the money rule stopped (`revise`), or neither: the run is
142
- * agentic, its claim laid learned workflows (`workflows`: the active ones the seed lay chose, so learning is neither off
143
- * nor notes-only), its launch does not force the agent path, and exactly one of them fits its input; then its promotion
144
- * (`promoted`, runner/promotion.ts: a new digest serves only once its replay on the agent's graded inputs clears the bar,
145
- * learn/promote.ts, its champion serving meanwhile when it fits the input too, `champion`; none leaves the run to the
146
- * agent), then costLineOf over the agent's runs (`past`, store-reads/learning.ts pastRunsOverStore) at the digest that
147
- * serves. When none of them fits, the revisions allowed to serve in their place are asked (`promoted.champion`: a
148
- * champion whose revision on the folder changed its input, a new required field say): exactly one champion that fits
149
- * serves. `outputSchema`: the agent's, when it has one: the workflow's answer is served shaped to it (answer-json.ts
150
- * answerAsServed), on a replay too, so a replay scores the answer a run would serve. `log`: one line when the launch
151
- * forces the agent, more than one fits, there is no by-hand cost to hold the workflow to, or the rule stops it. A replay
152
- * run (launch.replay) serves the workflow it replays, by name, alone: no promotion, no money rule; none when its claim
153
- * laid no workflow by that name at that digest (runner/promotion.ts replayClaimed then refuses the claim: the run ends
154
- * failed, never on the agent's path). */
175
+ /** A claim's first choice (firstChoice), with each fact it asks for read here: the promotion's verdict on the laid
176
+ * digest (`promoted`, runner/promotion.ts promotionGate, which settles that digest's checks as it answers), the
177
+ * champions that serve in place of their revision (`promoted.champion`), the agent's past runs (`past`,
178
+ * store-reads/learning.ts pastRunsOverStore). Each line firstChoice says goes to `log`. */
155
179
  export async function workflowFirstOf(kind, workflows, launch, log, past, promoted, outputSchema) {
180
+ const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
181
+ let facts = {
182
+ kind, workflows, launch, ...(outputSchema !== undefined ? { outputSchema } : {}),
183
+ fits: (workflow) => fits(workflow, launch.input, resolveSchemaForWorkflow),
184
+ promotion: !promoted ? "none" : promoted.champion ? "champions" : "laid",
185
+ money: past !== undefined,
186
+ };
187
+ // Each fact firstChoice asks for, read here and handed back to it: the promotion's verdict (which settles the laid
188
+ // digest's checks: runner/promotion.ts promotionGate), the champions, the agent's past runs. Past runs it can't read
189
+ // fail closed (firstChoice's past_unread): the agent takes the run, and the log says why.
190
+ for (;;) {
191
+ const step = firstChoice(facts);
192
+ if (!("ask" in step)) {
193
+ for (const line of step.said)
194
+ log?.(line);
195
+ const { said: _said, ...choice } = step;
196
+ return choice;
197
+ }
198
+ if (step.ask === "verdict")
199
+ facts = { ...facts, verdict: { digest: step.digest, serving: await promoted(step.workflow, step.digest) } };
200
+ else if (step.ask === "champions") {
201
+ const champions = [];
202
+ for (const one of workflows)
203
+ champions.push(await promoted.champion(one, workflowDigest(one)));
204
+ facts = { ...facts, champions };
205
+ }
206
+ else
207
+ facts = { ...facts, past: await past().catch((error) => ({ unread: error instanceof Error ? error.message : String(error) })) };
208
+ }
209
+ }
210
+ /** The workflow a run serves first (`serve`), or the one the money rule stopped (`revise`), or neither, and why
211
+ * (`reason`, FIRST_REASONS), over what it is told (`facts`), or the fact it asks for next (FirstAsk); pure: it reads,
212
+ * settles and starts nothing (the gatherer, workflowFirstOf, does). The run is agentic, its claim laid learned
213
+ * workflows, its launch does not force the agent path, and exactly one of them fits its input; then its promotion's
214
+ * verdict (runner/promotion.ts: a new digest serves only once its replay on the agent's graded inputs clears the bar,
215
+ * learn/promote.ts, its champion serving meanwhile when it fits the input too, `champion`; none leaves the run to the
216
+ * agent), then costLineOf over the agent's runs at the digest that serves (runs it can't read: none serves,
217
+ * `past_unread`). When none of them fits, the revisions allowed
218
+ * to serve in their place are asked (`champions`: a champion whose revision on the folder changed its input, a new
219
+ * required field say): exactly one champion that fits serves. `outputSchema`: the agent's, when it has one: the
220
+ * workflow's answer is served shaped to it (answer-json.ts answerAsServed), on a replay too, so a replay scores the
221
+ * answer a run would serve. A line is said when the launch forces the agent, more than one fits, a champion does not
222
+ * fit or serves in place of its revision, the past runs could not be read, there is no by-hand cost to hold the workflow
223
+ * to, or the rule stops it. A replay run (launch.replay) serves the workflow it replays, by name, alone: no promotion,
224
+ * no money rule; none when its claim laid no workflow by that name (runner/promotion.ts replayClaimed then refuses the
225
+ * claim: the run ends failed, never on the agent's path). */
226
+ export function firstChoice(facts) {
227
+ const { kind, workflows, launch, outputSchema } = facts;
228
+ const said = [];
229
+ const done = (reason, chosen = {}) => ({ ...chosen, reason, said });
156
230
  if (kind !== "agentic" || workflows.length === 0 || !launch.learning)
157
- return {};
231
+ return done("none_laid");
232
+ const shaped = outputSchema !== undefined ? { outputSchema } : {};
158
233
  if (launch.replay) {
159
234
  const { workflow: name, digest } = launch.replay;
160
- const chosen = workflows.find((one) => one.name === name);
161
- if (!chosen || !isObject(launch.input)) {
162
- log?.(`workflow-first: replay of ${name} at ${digest}: the run's claim laid no workflow by that name, or its input is no object; the replay fails`);
163
- return {};
235
+ if (!workflows.some((one) => one.name === name) || !isObject(launch.input)) {
236
+ said.push(`workflow-first: replay of ${name} at ${digest}: the run's claim laid no workflow by that name, or its input is no object; the replay fails`);
237
+ return done("replay_missing");
164
238
  }
165
- return { serve: { name, digest, input: launch.input, revision: launch.learning.seed, replay: true, ...(outputSchema !== undefined ? { outputSchema } : {}) } };
239
+ return done("replay", { serve: { name, digest, input: launch.input, revision: launch.learning.seed, replay: true, ...shaped } });
166
240
  }
167
241
  if (launch.workflowFirst === false) {
168
- log?.("workflow-first: off for this run (workflow_first: false); the agent takes it");
169
- return {};
242
+ said.push("workflow-first: off for this run (workflow_first: false); the agent takes it");
243
+ return done("off");
170
244
  }
171
- const { resolveSchemaForWorkflow } = await import("@parcha/agentrun-dsl");
172
- const fitting = workflows.filter((workflow) => fits(workflow, launch.input, resolveSchemaForWorkflow));
245
+ const fitting = workflows.filter(facts.fits);
173
246
  // None fitting is the common case (a workflow for another job): nothing to say. More than one: which serves is not
174
247
  // the engine's call, in one line.
175
- if (fitting.length > 1)
176
- log?.(`workflow-first: ${fitting.length} of ${workflows.length} learned workflows fit this run's input; the agent takes it`);
177
- if (fitting.length > 1)
178
- return {};
248
+ if (fitting.length > 1) {
249
+ said.push(`workflow-first: ${fitting.length} of ${workflows.length} learned workflows fit this run's input; the agent takes it`);
250
+ return done("many_fit");
251
+ }
179
252
  let chosen;
180
253
  let laid;
181
254
  let promotion;
182
255
  if (fitting.length === 1) {
183
256
  laid = fitting[0];
184
- const serving = promoted ? await promoted(laid, workflowDigest(laid)) : { workflow: laid };
257
+ let serving = { workflow: laid };
258
+ if (facts.promotion !== "none") {
259
+ const digest = workflowDigest(laid);
260
+ if (facts.verdict?.digest !== digest)
261
+ return { ask: "verdict", workflow: laid, digest };
262
+ serving = facts.verdict.serving;
263
+ }
185
264
  if (!serving)
186
- return {};
265
+ return done("not_promoted");
187
266
  chosen = serving.workflow;
188
267
  promotion = serving.promotion;
189
- if (chosen !== laid && !fits(chosen, launch.input, resolveSchemaForWorkflow)) {
190
- log?.(`workflow-first: ${laid.name}'s champion does not take this run's input; the agent takes it`);
191
- return {};
268
+ if (chosen !== laid && !facts.fits(chosen)) {
269
+ said.push(`workflow-first: ${laid.name}'s champion does not take this run's input; the agent takes it`);
270
+ return done("champion_misfit");
192
271
  }
193
272
  }
194
273
  else {
195
274
  // None laid fits: a champion serving in place of its revision may (the revision changed its input).
196
- if (!promoted?.champion)
197
- return {};
198
- const champions = [];
199
- for (const one of workflows) {
200
- const champion = await promoted.champion(one, workflowDigest(one));
201
- if (champion && fits(champion.workflow, launch.input, resolveSchemaForWorkflow))
202
- champions.push(champion);
275
+ if (facts.promotion !== "champions")
276
+ return done("none_fit");
277
+ if (!facts.champions)
278
+ return { ask: "champions" };
279
+ const champions = facts.champions.filter((one) => one !== undefined && facts.fits(one.workflow));
280
+ if (champions.length > 1) {
281
+ said.push(`workflow-first: ${champions.length} learned workflows' champions fit this run's input; the agent takes it`);
282
+ return done("many_champions");
203
283
  }
204
- if (champions.length > 1)
205
- log?.(`workflow-first: ${champions.length} learned workflows' champions fit this run's input; the agent takes it`);
206
284
  if (champions.length !== 1)
207
- return {};
285
+ return done("none_fit");
208
286
  chosen = champions[0].workflow;
209
287
  promotion = champions[0].promotion;
210
- log?.(`workflow-first: ${chosen.name}'s revision does not take this run's input; its champion at ${workflowDigest(chosen)} does, and serves it`);
288
+ said.push(`workflow-first: ${chosen.name}'s revision does not take this run's input; its champion at ${workflowDigest(chosen)} does, and serves it`);
211
289
  }
212
290
  const champion = chosen !== laid ? { champion: chosen } : {};
213
291
  const digest = workflowDigest(chosen);
214
- const serve = { ...champion, serve: { name: chosen.name, digest, ...(promotion !== undefined ? { promotion } : {}), input: launch.input, revision: launch.learning.seed, ...(outputSchema !== undefined ? { outputSchema } : {}) } };
215
- if (!past)
216
- return serve;
217
- // Runs it can't read stop nothing: the run is served unchecked, and the log says so.
218
- const read = await past().catch((error) => {
219
- log?.(`workflow-first: the money rule could not read the agent's past runs (${error instanceof Error ? error.message : String(error)}); ${chosen.name} serves this run unchecked`);
220
- return NO_PAST_RUNS;
221
- });
222
- const line = costLineOf(read, chosen.name, digest);
223
- if (line.served.runs < COST_WINDOW)
224
- return serve;
225
- if (line.by_hand === null) {
226
- log?.(`workflow-first: no by-hand cost to hold ${chosen.name} to (no run of known cost on the agent's path before a learned workflow first served); it runs first`);
227
- return serve;
292
+ const serve = { ...champion, serve: { name: chosen.name, digest, ...(promotion !== undefined ? { promotion } : {}), input: launch.input, revision: launch.learning.seed, ...shaped } };
293
+ if (!facts.money)
294
+ return done("served", serve);
295
+ if (!facts.past)
296
+ return { ask: "past" };
297
+ // Fails closed: runs it can't read leave the run to the agent, and the log says why.
298
+ if ("unread" in facts.past) {
299
+ said.push(`workflow-first: the money rule could not read the agent's past runs (${facts.past.unread}); ${chosen.name} does not run first, the agent takes this run`);
300
+ return done("past_unread");
301
+ }
302
+ const line = costLineOf(facts.past, chosen.name, digest);
303
+ const stopped = stopReasonOf(line);
304
+ if (!stopped)
305
+ return done("served", serve);
306
+ // Fails closed: COST_WINDOW served runs and no by-hand cost to hold them to leave the run to the agent, never served
307
+ // unchecked, and ask for no revision (there is no by-hand figure to say).
308
+ if (stopped === "no_by_hand_cost") {
309
+ said.push(`workflow-first: no by-hand cost to hold ${chosen.name} to (no run of known cost on the agent's path since the reset, among its newest ${PAST_RUNS} runs or the ${COST_WINDOW} by hand before them); the agent takes this run`);
310
+ return done("no_by_hand_cost");
228
311
  }
229
- if (!overLine(line))
230
- return serve;
231
- const revise = { workflow: chosen.name, digest, served_usd: line.served.mean_usd, by_hand_usd: line.by_hand.mean_usd, runs: line.served.runs, revision: launch.learning.seed, ...(outputSchema !== undefined ? { outputSchema } : {}) };
312
+ const { stop, words } = stopOf(chosen.name, digest, line);
313
+ said.push(`workflow-first: ${words}; it does not run first until a new revision of it; the agent takes this run`);
314
+ return done("cost_stop", { ...champion, revise: { ...stop, revision: launch.learning.seed, ...shaped } });
315
+ }
316
+ /** The money rule's stop of workflow `name` at `digest` over its line (one overLine holds), and the words it is said in. */
317
+ function stopOf(name, digest, line) {
318
+ const stop = { workflow: name, digest, served_usd: line.served.mean_usd, by_hand_usd: line.by_hand.mean_usd, runs: line.served.runs };
232
319
  const unknown = line.unknown_runs ? ` (${line.unknown_runs} run${line.unknown_runs === 1 ? "" : "s"} of unknown cost left out)` : "";
233
- log?.(`workflow-first: ${chosen.name} cost $${revise.served_usd} a run over its last ${revise.runs} served runs, at or over $${revise.by_hand_usd} by hand (served all-in, by hand the job's own, over the same runs)${unknown}; it does not run first until a new revision of it; the agent takes this run`);
234
- return { ...champion, revise };
320
+ return { stop, words: `${name} cost $${stop.served_usd} a run over its last ${stop.runs} served runs, at or over $${stop.by_hand_usd} by hand (served all-in, by hand the job's own, over the same runs)${unknown}` };
321
+ }
322
+ /** The money rule over the learned workflows a run's own learned_workflow tool runs (`flows`, runner/promotion.ts
323
+ * toolFlowsFor), whoever would call them, by the stop firstChoice reads (stopReasonOf over costLineOf of the agent's
324
+ * runs, `past`, at the digest the tool runs): over the line (`over_line`) it leaves the tool (`flows`) and is a stop that
325
+ * asks for its revision (`stops`, Revise), as firstChoice's cost_stop; with COST_WINDOW served runs and no by-hand cost
326
+ * to hold them to (`no_by_hand_cost`) it leaves the tool with no stop, as firstChoice's no_by_hand_cost (no by-hand
327
+ * figure for a revision to beat). Past runs it can't read (`unread`) leave the tool none: it fails closed, as
328
+ * firstChoice does. `said`: the log lines. Pure. */
329
+ export function toolStopsOf(past, flows) {
330
+ if (!flows.length)
331
+ return { flows: [], stops: [], said: [] };
332
+ if ("unread" in past)
333
+ return { flows: [], stops: [], said: [`workflow-first: the money rule could not read the agent's past runs (${past.unread}); the learned_workflow tool runs none of ${flows.map((one) => one.name).join(", ")}`] };
334
+ const kept = [];
335
+ const stops = [];
336
+ const said = [];
337
+ for (const flow of flows) {
338
+ const digest = workflowDigest(flow);
339
+ const line = costLineOf(past, flow.name, digest);
340
+ const stopped = stopReasonOf(line);
341
+ if (!stopped) {
342
+ kept.push(flow);
343
+ continue;
344
+ }
345
+ if (stopped === "no_by_hand_cost") {
346
+ said.push(`workflow-first: no by-hand cost to hold ${flow.name} to (${line.served.runs} served runs and no run of known cost on the agent's path); the learned_workflow tool leaves it out`);
347
+ continue;
348
+ }
349
+ const { stop, words } = stopOf(flow.name, digest, line);
350
+ stops.push(stop);
351
+ said.push(`workflow-first: ${words}; the learned_workflow tool leaves it out until a new revision of it`);
352
+ }
353
+ return { flows: kept, stops, said };
235
354
  }
236
355
  /** What a run's workflow-first step did, from its root entries (the WORKFLOW_FIRST entry): the workflow, its digest, the
237
356
  * promotion it served under (WorkflowFirst.promotion), and whether it answered or handed back; undefined when it served
@@ -251,9 +370,13 @@ export function servedOf(entries) {
251
370
  * called by its agent) and, for one served first, its digest and the promotion it served under (`workflow_promotion`,
252
371
  * which its grade keeps), `workflow_cut` on a hand-back a restart cut (servedOf `cut`: the workflow handed nothing back
253
372
  * itself), and `not_auditable` when a trigger started it (never audited); and from its root `entries`,
254
- * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran. learning-cost reads path
373
+ * each loop's exit (`loops`, loopsOf: a quote re-pick is a loop's second pass), when one ran, and every learned
374
+ * workflow call it made, the platform's and the agent's (`workflow_calls`, runner/workflow-calls.ts workflowCallsOf:
375
+ * what the money rule and the ledger count; none on a replay or a shadow, which serve no one). `choice`: why its
376
+ * ending claim's first choice served or did not (`first_choice`, FirstReason), for a run whose spec chose one. `entries`
377
+ * are every conversation's (store-reads/journal.ts runEntries), so a call's booking is read. learning-cost reads path
255
378
  * and workflow from here. None for a run that does not learn. */
256
- export function pathMetrics(launch, classified, entries = []) {
379
+ export function pathMetrics(launch, classified, entries = [], choice) {
257
380
  // The grader's verdict its end-of-run step kept (runner/compare-end.ts), for a replay run and a shadow.
258
381
  const compared = comparedOf(entries.findLast((entry) => entry.kind === KINDS.compared)?.data);
259
382
  const verdict = compared ? { compared } : {};
@@ -265,6 +388,7 @@ export function pathMetrics(launch, classified, entries = []) {
265
388
  const { path, workflow, digest, promotion, cut } = classified ?? { path: "agent", workflow: null };
266
389
  const loops = loopsOf(entries);
267
390
  const rows = loops.length ? { loops } : {};
391
+ const chose = choice ? { first_choice: choice } : {};
268
392
  if (launch.replay) {
269
393
  // A replay run (runner/promotion.ts): path `replay`, whatever its workflow did, so the money rule and the agent's
270
394
  // by-hand cost never read it; how its workflow ended, for the replay's score (learn/promote.ts ReplayRow).
@@ -275,14 +399,14 @@ export function pathMetrics(launch, classified, entries = []) {
275
399
  // evidence. Skipped when a write it needed is not in the graded run's recording (learn/replay-calls.ts): never run.
276
400
  const skipped = replaySkippedIn(entries);
277
401
  const outcome = skipped ? "skipped_write" : path === "workflow" && workflow === name ? "answered" : path === "handed_back" && workflow === name && endedIn(entries, name) === "escalated" ? "handed_back" : "failed";
278
- return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, replay: { of, outcome, ...(skipped ? { skipped } : {}), ...verdict } };
402
+ return { path: "replay", ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), workflow: name, workflow_digest: at, ...rows, ...chose, replay: { of, outcome, ...(skipped ? { skipped } : {}), ...verdict } };
279
403
  }
280
404
  // A served run a trigger started (learn/audit.ts auditableLaunch) is never audited: counted on the promotions read.
281
405
  const notAuditable = SERVED_PATHS.includes(path) && !auditableLaunch(launch);
282
406
  // The money rule stopped its workflow from running first (its WORKFLOW_FIRST entry asks for a revision): why it was not
283
407
  // served, the ledger's (learn/ledger.ts record).
284
408
  const costStop = path === "agent" && entries.some((entry) => entry.kind === WORKFLOW_FIRST && entry.data?.outcome === "needs_revision");
285
- return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(cut && path === "handed_back" ? { workflow_cut: true } : {}), ...(notAuditable ? { not_auditable: true } : {}), ...(costStop ? { not_served: "cost_stop" } : {}), ...rows };
409
+ return { path, ...(launch.learning.seed ? { learned_revision: launch.learning.seed } : {}), ...(workflow ? { workflow } : {}), ...(digest ? { workflow_digest: digest } : {}), ...(promotion !== undefined ? { workflow_promotion: promotion } : {}), ...(cut && path === "handed_back" ? { workflow_cut: true } : {}), ...(notAuditable ? { not_auditable: true } : {}), ...(costStop ? { not_served: "cost_stop" } : {}), ...rows, workflow_calls: workflowCallsOf(entries), ...chose };
286
410
  }
287
411
  /** What run `entries` (its root's) say its learned workflow answered alone: the workflow and its answer (the model's
288
412
  * message written just before the WORKFLOW_FIRST entry, in its commit); undefined for a run it did not answer. A follow-up that opens such a
@@ -948,7 +948,7 @@ const openrouterModel = (id, price, outputCeiling) => ({ id, api: "openrouter",
948
948
  /** A finite, non-negative cost, else null (the answer reported none): settled so, the hold books (`charged:held`). */
949
949
  const finiteUsd = (usd) => (typeof usd === "number" && Number.isFinite(usd) && usd >= 0 ? usd : null);
950
950
  /** A provider failure that says the request was never billed (main's `unbilled`): booked at $0. */
951
- const UNBILLED = new Set(["configuration", "auth", "invalid_request", "rate_limited", "connection"]);
951
+ const UNBILLED = new Set(["configuration", "auth", "payment_required", "invalid_request", "rate_limited", "connection"]);
952
952
  const unbilled = (error) => error instanceof DecisionProviderError && (error.unsent === true || UNBILLED.has(error.code));
953
953
  /** The tiers the workflow's model nodes run on (model.ts): the llm tiers over its nodes, read as toolsOf reads them (its
954
954
  * inspection's node paths), else the default. */
@@ -22,7 +22,7 @@ import { ApiError, invalid, unsupported } from "./errors.js";
22
22
  import { labelsOf } from "./run-labels.js";
23
23
  import { harnessOfBody } from "./harness.js";
24
24
  import { uuidv7 } from "./ids.js";
25
- import { redacted, redactedOutput } from "./key-refusal.js";
25
+ import { redacted, redactedOutput, redactedOutputWhole } from "./key-refusal.js";
26
26
  import { chooseWorkflows, learnedSection, learnsOf, RUN_LEARNING_USE } from "./learning.js";
27
27
  import { thinkingLevel } from "./model.js";
28
28
  import { resolvePlace } from "./place.js";
@@ -471,7 +471,7 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
471
471
  if (entry.revision?.body?.sdk)
472
472
  throw new ApiError("agent_not_runnable", "This agent runs in your backend SDK. Start it through its SDK learning wrapper; AgentRun does not launch its tools or credentials.");
473
473
  const { launch, revision } = await prepareLaunch(deps, entry, body, { ...(trigger ? { trigger } : {}), capped, ...(from ? { from } : {}), ...(title !== undefined ? { title } : {}), ...(keys ? { keys } : {}) });
474
- const target = keyTargetOf(deps.planeEnv(), launch, revision);
474
+ const target = keyTargetOf(launch, revision);
475
475
  keyedOrRefused(deps, target, sealed);
476
476
  const runId = (deps.newRunId ?? uuidv7)();
477
477
  try {
@@ -494,10 +494,10 @@ export async function startRun(store, deps, entry, body, { trigger, origin, capp
494
494
  /** A start with no launch secrets (`sealed`: a trigger's firing, a learning batch's row) whose route goes to the model
495
495
  * gateway, on a server that holds no key for it (run-model-key.ts serverKeyMissing): 422 model_key_required, nothing
496
496
  * written, never a failure at its first model call. A start with them (the API's) is the sealer's to check. `target`:
497
- * the run's (run-model-key.ts keyTargetOf), a held run's whose model was refused at its create among them. */
497
+ * the run's (run-model-key.ts keyTargetOf). */
498
498
  function keyedOrRefused(deps, target, sealed) {
499
499
  if (!sealed && serverKeyMissing(deps.planeEnv(), target))
500
- throw modelKeyRequired(false);
500
+ throw modelKeyRequired(false, deps.planeEnv());
501
501
  }
502
502
  /** Writes run `runId` of agent `agentId` with `write`, its files (launch.files) held for it first (StartDeps.files): a
503
503
  * hold that fails part way, a write that fails, or one that answers another run (an origin key's run started before),
@@ -682,7 +682,7 @@ async function startInlineOnce(store, deps, inline, body, { origin, sealed, keys
682
682
  // A store revision is the revision the run path reads as a pi Revision (its body is the revision body), as pinnedOf hands
683
683
  // one across.
684
684
  const { launch } = await prepareLaunch(deps, entry, body, { revision: (storedRevision ?? revision), ...(keys ? { keys } : {}) });
685
- const target = keyTargetOf(deps.planeEnv(), launch, storedRevision ?? revision);
685
+ const target = keyTargetOf(launch, storedRevision ?? revision);
686
686
  keyedOrRefused(deps, target, sealed);
687
687
  const runId = (deps.newRunId ?? uuidv7)();
688
688
  const labels = labelsOf(body.labels);
@@ -770,8 +770,9 @@ export async function prepareLaunch(deps, entry, body, { trigger, capped = false
770
770
  // is not refused: those words ride its hold, for its start to answer (computer-held.ts).
771
771
  const modelRefused = await deps.runnable(deps.pinFirst ? await deps.pinFirst(revision) : revision, place, { capped: cap !== undefined, carried, held: hold !== undefined });
772
772
  // The title shows on the run's page, the runs list and Mission Control: built from its input as shown, each held value
773
- // redacted before a long one is cut (a cut key could no longer be found).
774
- const shown = redactedOutput(input, deps.serverSecrets());
773
+ // redacted before a long one is cut (a cut key could no longer be found). Read whole first (redactedOutputWhole): an input
774
+ // a held value is split across two fields of is "[redacted]", so a workflow's title is made of none of it.
775
+ const shown = redactedOutputWhole(input, deps.serverSecrets());
775
776
  // A starter's title (a trigger's "<Source> <name>") is shown words too: cut as the input is, then as every title is below.
776
777
  const title = given !== undefined ? String(redactedOutput(given, deps.serverSecrets())) : revision.kind === "workflow" ? deps.workflowTitle(entry.agent.name || entry.agent.id, isObject(shown) ? shown : {}) : typeof input.content === "string" ? input.content : (Object.values(input).find((v) => typeof v === "string") ?? JSON.stringify(input));
777
778
  // Its tools' providers, resolved before the run exists (tool-plane.ts) and kept in its launch body, so a claim reads them
@@ -0,0 +1,14 @@
1
+ import { type Stat, type Workspace } from "./workspace/index.js";
2
+ /** What is already at `at`, never followed: undefined when nothing is. Throws the Workspace's error (a link on the way). */
3
+ export declare const heldAt: (work: Workspace, at: string) => Promise<Stat["kind"] | undefined>;
4
+ /** `bytes` saved at `at` when nothing is there (`saved`), else what is there, kept (`held`). Throws the Workspace's
5
+ * error (a link on the way, a write that failed). On a Workspace that cannot make a file without the chance of
6
+ * replacing one (no writeNew) it throws REFUSED, unless `checkThenWrite` is set: then it checks, then writes, and
7
+ * a file landing between the two is not kept (Parcha-ai/agentrun#3777). */
8
+ export declare function saveOnce(work: Workspace, at: string, bytes: Uint8Array | string, options?: {
9
+ checkThenWrite?: boolean;
10
+ }): Promise<{
11
+ saved: true;
12
+ } | {
13
+ held: Stat["kind"];
14
+ }>;
@@ -0,0 +1,31 @@
1
+ // A file saved once in a run's files, never over anything: what web_save writes, and the results a server's reply
2
+ // carries that the gateway files (fal's completed jobs, mcp-gateway.ts). One set of rules for both: the Workspace walks
3
+ // to the path without following a link (a link on the way is ESCAPE), and whatever is already at the path (a file, a
4
+ // folder, a link) is kept, so a save never follows or replaces it. The create itself never replaces (Workspace.writeNew,
5
+ // on the local Workspace and an attached one): a file that lands at the path after the check is kept too.
6
+ // A Workspace with no such create (an Archil run disk, follow-up Parcha-ai/agentrun#3777): a filed result is not saved
7
+ // there at all, while web_save, asking for `checkThenWrite`, keeps its check then a write, so a file that lands at the
8
+ // path between the two can be replaced there, as before writeNew.
9
+ import { WorkspaceError } from "./workspace/index.js";
10
+ /** What is already at `at`, never followed: undefined when nothing is. Throws the Workspace's error (a link on the way). */
11
+ export const heldAt = async (work, at) => (await work.stat(at))?.kind;
12
+ /** `bytes` saved at `at` when nothing is there (`saved`), else what is there, kept (`held`). Throws the Workspace's
13
+ * error (a link on the way, a write that failed). On a Workspace that cannot make a file without the chance of
14
+ * replacing one (no writeNew) it throws REFUSED, unless `checkThenWrite` is set: then it checks, then writes, and
15
+ * a file landing between the two is not kept (Parcha-ai/agentrun#3777). */
16
+ export async function saveOnce(work, at, bytes, options = {}) {
17
+ const create = typeof work.writeNew === "function" ? work.writeNew.bind(work) : undefined;
18
+ if (!create && !options.checkThenWrite)
19
+ throw new WorkspaceError("REFUSED", "this run's files cannot make a file without the chance of replacing one, so nothing is saved there once", { path: at });
20
+ const held = await heldAt(work, at);
21
+ if (held)
22
+ return { held };
23
+ if (!create) {
24
+ await work.write(at, bytes);
25
+ return { saved: true };
26
+ }
27
+ if (await create(at, bytes))
28
+ return { saved: true };
29
+ // Something landed at the path after the check: what it is now, kept.
30
+ return { held: (await heldAt(work, at)) ?? "other" };
31
+ }