@parcha/agentrun-serve 0.1.0-beta.57 → 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 (404) hide show
  1. package/CHANGELOG.md +376 -0
  2. package/README.md +393 -118
  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/api-only.d.ts +2 -4
  11. package/dist/api-only.js +2 -4
  12. package/dist/attach-conformance.js +5 -4
  13. package/dist/box-paths.d.ts +7 -5
  14. package/dist/box-paths.js +12 -8
  15. package/dist/browser-computer.d.ts +3 -8
  16. package/dist/browser-computer.js +12 -35
  17. package/dist/browser-cost.js +94 -20
  18. package/dist/capacity.d.ts +1 -1
  19. package/dist/capacity.js +3 -3
  20. package/dist/chatgpt-plan.d.ts +5 -0
  21. package/dist/chatgpt-plan.js +25 -11
  22. package/dist/claude-login-token.d.ts +121 -0
  23. package/dist/claude-login-token.js +797 -0
  24. package/dist/claude-login.d.ts +119 -34
  25. package/dist/claude-login.js +551 -79
  26. package/dist/claude-sign-in.d.ts +3 -0
  27. package/dist/claude-sign-in.js +10 -1
  28. package/dist/cli.js +325 -328
  29. package/dist/composio-made.d.ts +1 -6
  30. package/dist/composio-made.js +1 -6
  31. package/dist/composio-owners.d.ts +26 -0
  32. package/dist/composio-owners.js +36 -0
  33. package/dist/composio-preset.d.ts +56 -23
  34. package/dist/composio-preset.js +173 -77
  35. package/dist/composio-triggers.d.ts +4 -4
  36. package/dist/composio-triggers.js +6 -7
  37. package/dist/compute-cost.js +11 -2
  38. package/dist/computer-attach.d.ts +40 -19
  39. package/dist/computer-attach.js +326 -62
  40. package/dist/computer-held-routes.d.ts +1 -1
  41. package/dist/computer-held-routes.js +9 -4
  42. package/dist/computer-keys.d.ts +11 -1
  43. package/dist/computer-keys.js +26 -1
  44. package/dist/computer-record.js +3 -1
  45. package/dist/computer-view.d.ts +5 -3
  46. package/dist/computer-view.js +10 -6
  47. package/dist/computer-viewer.js +36 -7
  48. package/dist/computers.d.ts +12 -11
  49. package/dist/computers.js +11 -8
  50. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  51. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  52. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  53. package/dist/console/assets/share-L84tlUDW.js +6 -0
  54. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  55. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  56. package/dist/console/index.html +4 -3
  57. package/dist/console/share.html +17 -0
  58. package/dist/decisions.d.ts +17 -7
  59. package/dist/decisions.js +41 -15
  60. package/dist/dial-relay.d.ts +25 -4
  61. package/dist/dial-relay.js +139 -5
  62. package/dist/docker-daemon.js +4 -5
  63. package/dist/docker-host-addresses.js +29 -11
  64. package/dist/email/account.d.ts +6 -0
  65. package/dist/email/account.js +6 -0
  66. package/dist/email/authentication.d.ts +21 -0
  67. package/dist/email/authentication.js +106 -0
  68. package/dist/email/email-faux.d.ts +11 -2
  69. package/dist/email/email-faux.js +21 -5
  70. package/dist/email/mail.d.ts +25 -0
  71. package/dist/email/mail.js +58 -2
  72. package/dist/email/names.js +2 -2
  73. package/dist/email/tools.d.ts +9 -4
  74. package/dist/email/tools.js +95 -13
  75. package/dist/env-switch.d.ts +13 -5
  76. package/dist/env-switch.js +24 -6
  77. package/dist/errors.d.ts +1 -0
  78. package/dist/errors.js +2 -0
  79. package/dist/fal-price.d.ts +12 -4
  80. package/dist/fal-price.js +110 -26
  81. package/dist/faux-computers.js +1 -1
  82. package/dist/filed-answer.d.ts +2 -2
  83. package/dist/filed-answer.js +2 -2
  84. package/dist/graph-served.d.ts +10 -5
  85. package/dist/graph-served.js +40 -10
  86. package/dist/handed-values.js +1 -2
  87. package/dist/harness-check.d.ts +2 -1
  88. package/dist/harness-check.js +45 -12
  89. package/dist/harness-keys.js +9 -6
  90. package/dist/harness-opencode/facts.js +2 -0
  91. package/dist/harness-recipe-entry.d.ts +9 -3
  92. package/dist/harness-recipe-entry.js +18 -9
  93. package/dist/harness-recipe.d.ts +21 -0
  94. package/dist/harness-recipe.js +25 -3
  95. package/dist/harness-table.d.ts +8 -0
  96. package/dist/harness-table.js +17 -6
  97. package/dist/helper-env.d.ts +4 -1
  98. package/dist/helper-env.js +4 -1
  99. package/dist/host-check.d.ts +2 -3
  100. package/dist/host-check.js +13 -7
  101. package/dist/hosted-search.js +1 -1
  102. package/dist/import.d.ts +11 -8
  103. package/dist/import.js +437 -186
  104. package/dist/key-refusal.d.ts +9 -2
  105. package/dist/key-refusal.js +86 -32
  106. package/dist/learn/audit.d.ts +8 -5
  107. package/dist/learn/audit.js +15 -7
  108. package/dist/learn/compile.d.ts +5 -2
  109. package/dist/learn/compile.js +45 -21
  110. package/dist/learn/field-check.d.ts +111 -0
  111. package/dist/learn/field-check.js +174 -0
  112. package/dist/learn/ledger.d.ts +173 -0
  113. package/dist/learn/ledger.js +225 -0
  114. package/dist/learn/promote.d.ts +82 -39
  115. package/dist/learn/promote.js +61 -66
  116. package/dist/learn/secrets.d.ts +4 -0
  117. package/dist/learn/secrets.js +12 -0
  118. package/dist/learned-nodes.d.ts +8 -5
  119. package/dist/learned-nodes.js +8 -5
  120. package/dist/learned-workflow.d.ts +2 -1
  121. package/dist/learned-workflow.js +13 -10
  122. package/dist/learning-cost.d.ts +40 -21
  123. package/dist/learning-cost.js +30 -21
  124. package/dist/learning-setting.d.ts +6 -0
  125. package/dist/learning-setting.js +11 -1
  126. package/dist/listen-first.d.ts +5 -4
  127. package/dist/listen-first.js +4 -5
  128. package/dist/live-reach.d.ts +9 -0
  129. package/dist/live-reach.js +9 -0
  130. package/dist/mcp-api-only-origins.d.ts +23 -3
  131. package/dist/mcp-api-only-origins.js +57 -17
  132. package/dist/mcp-gateway.d.ts +16 -2
  133. package/dist/mcp-gateway.js +41 -3
  134. package/dist/mcp-oauth.d.ts +1 -1
  135. package/dist/mcp-oauth.js +3 -2
  136. package/dist/mcp-probe.d.ts +3 -0
  137. package/dist/mcp-probe.js +3 -0
  138. package/dist/mcp-secret-writes.d.ts +24 -2
  139. package/dist/mcp-secret-writes.js +30 -2
  140. package/dist/mcp-servers-store.d.ts +52 -14
  141. package/dist/mcp-servers-store.js +165 -61
  142. package/dist/mcp-sources.d.ts +1 -2
  143. package/dist/mcp-sources.js +1 -2
  144. package/dist/mcp-store.d.ts +5 -5
  145. package/dist/mcp-store.js +3 -3
  146. package/dist/mcp.js +1 -1
  147. package/dist/micro.d.ts +2 -0
  148. package/dist/micro.js +2 -0
  149. package/dist/model-gateway.d.ts +1 -1
  150. package/dist/model-gateway.js +20 -36
  151. package/dist/model.d.ts +5 -4
  152. package/dist/model.js +7 -6
  153. package/dist/monid.d.ts +14 -1
  154. package/dist/monid.js +103 -26
  155. package/dist/ollama-provider.d.ts +23 -9
  156. package/dist/ollama-provider.js +49 -20
  157. package/dist/openapi.js +234 -61
  158. package/dist/otel/genai.d.ts +83 -7
  159. package/dist/otel/genai.js +69 -9
  160. package/dist/otel/tracer.d.ts +42 -13
  161. package/dist/otel/tracer.js +241 -56
  162. package/dist/page.d.ts +7 -1
  163. package/dist/page.js +76 -22
  164. package/dist/paid-calls.d.ts +6 -4
  165. package/dist/paid-calls.js +15 -7
  166. package/dist/place-offers.d.ts +59 -34
  167. package/dist/place-offers.js +100 -58
  168. package/dist/place.d.ts +13 -14
  169. package/dist/place.js +56 -41
  170. package/dist/print.js +1 -1
  171. package/dist/provider.d.ts +5 -4
  172. package/dist/provider.js +26 -13
  173. package/dist/redact/match.d.ts +27 -9
  174. package/dist/redact/match.js +266 -57
  175. package/dist/run-census.d.ts +1 -1
  176. package/dist/run-census.js +4 -5
  177. package/dist/run-cut.js +4 -5
  178. package/dist/run-export-store.d.ts +15 -0
  179. package/dist/run-export-store.js +30 -0
  180. package/dist/run-export.d.ts +139 -0
  181. package/dist/run-export.js +379 -0
  182. package/dist/run-file-cut.d.ts +5 -0
  183. package/dist/run-file-cut.js +13 -0
  184. package/dist/run-launch.js +16 -3
  185. package/dist/run-learning-served.d.ts +2 -2
  186. package/dist/run-model-key.d.ts +15 -6
  187. package/dist/run-model-key.js +30 -31
  188. package/dist/run-reads-over-store.js +4 -4
  189. package/dist/run-secrets.js +3 -5
  190. package/dist/run-timeline-served.js +3 -1
  191. package/dist/run-view.d.ts +1 -2
  192. package/dist/run-view.js +2 -1
  193. package/dist/runnable.js +2 -2
  194. package/dist/runner/adapter-loop.d.ts +35 -18
  195. package/dist/runner/adapter-loop.js +97 -63
  196. package/dist/runner/adapter-run-spec.d.ts +34 -14
  197. package/dist/runner/adapter-run-spec.js +120 -75
  198. package/dist/runner/adapters/pi.js +4 -2
  199. package/dist/runner/audit.d.ts +8 -5
  200. package/dist/runner/audit.js +37 -17
  201. package/dist/runner/beside.d.ts +9 -2
  202. package/dist/runner/beside.js +29 -13
  203. package/dist/runner/claim-secrets.d.ts +27 -18
  204. package/dist/runner/claim-secrets.js +61 -47
  205. package/dist/runner/cli-run-spec.d.ts +18 -0
  206. package/dist/runner/cli-run-spec.js +93 -46
  207. package/dist/runner/compare-end.d.ts +2 -1
  208. package/dist/runner/compare-end.js +25 -10
  209. package/dist/runner/conformance/harness.js +2 -3
  210. package/dist/runner/conformance/subject.d.ts +4 -1
  211. package/dist/runner/harness-loops.js +3 -3
  212. package/dist/runner/held.d.ts +19 -4
  213. package/dist/runner/journal-kinds.d.ts +4 -1
  214. package/dist/runner/journal-kinds.js +22 -4
  215. package/dist/runner/learned-first.js +20 -4
  216. package/dist/runner/learning-end.d.ts +2 -8
  217. package/dist/runner/learning-end.js +11 -19
  218. package/dist/runner/live-ticker.js +7 -5
  219. package/dist/runner/loop-contract.d.ts +0 -2
  220. package/dist/runner/loop.d.ts +7 -0
  221. package/dist/runner/loop.js +1 -0
  222. package/dist/runner/main.d.ts +11 -6
  223. package/dist/runner/main.js +24 -18
  224. package/dist/runner/mcp-claim.js +24 -7
  225. package/dist/runner/mcp-run.d.ts +3 -6
  226. package/dist/runner/mcp-run.js +3 -4
  227. package/dist/runner/meta-tools.js +3 -2
  228. package/dist/runner/metrics.d.ts +7 -0
  229. package/dist/runner/metrics.js +19 -0
  230. package/dist/runner/model-route.d.ts +10 -7
  231. package/dist/runner/model-route.js +79 -15
  232. package/dist/runner/native-loop.js +10 -8
  233. package/dist/runner/presence.d.ts +11 -4
  234. package/dist/runner/presence.js +11 -6
  235. package/dist/runner/promotion.d.ts +25 -13
  236. package/dist/runner/promotion.js +125 -50
  237. package/dist/runner/redact.d.ts +3 -1
  238. package/dist/runner/redact.js +5 -3
  239. package/dist/runner/reflect-hook.js +1 -1
  240. package/dist/runner/responses-fetch.d.ts +36 -0
  241. package/dist/runner/responses-fetch.js +511 -0
  242. package/dist/runner/run-child-host.d.ts +38 -12
  243. package/dist/runner/run-child-host.js +231 -83
  244. package/dist/runner/run-child.js +11 -4
  245. package/dist/runner/runner-check.js +5 -1
  246. package/dist/runner/runner.d.ts +5 -3
  247. package/dist/runner/runner.js +14 -10
  248. package/dist/runner/save-slots.js +2 -1
  249. package/dist/runner/sdk-loop.js +8 -8
  250. package/dist/runner/spec-holds.d.ts +8 -1
  251. package/dist/runner/spec-holds.js +9 -4
  252. package/dist/runner/subagent.d.ts +11 -0
  253. package/dist/runner/subagent.js +17 -3
  254. package/dist/runner/workflow-calls.d.ts +9 -0
  255. package/dist/runner/workflow-calls.js +150 -0
  256. package/dist/runner/workflow-first.d.ts +138 -37
  257. package/dist/runner/workflow-first.js +230 -99
  258. package/dist/runner/workflow-spec.js +2 -2
  259. package/dist/runs-over-store.js +8 -7
  260. package/dist/save-once.d.ts +14 -0
  261. package/dist/save-once.js +31 -0
  262. package/dist/scrub-command.d.ts +34 -31
  263. package/dist/scrub-command.js +116 -147
  264. package/dist/sdk/runs.d.ts +6 -0
  265. package/dist/sdk/runs.js +89 -10
  266. package/dist/seal-key.js +4 -4
  267. package/dist/secret-cut.d.ts +3 -0
  268. package/dist/secret-cut.js +7 -1
  269. package/dist/secret-rules.d.ts +8 -1
  270. package/dist/secret-rules.js +482 -53
  271. package/dist/secrets.d.ts +51 -9
  272. package/dist/secrets.js +311 -21
  273. package/dist/server-keys.d.ts +4 -3
  274. package/dist/server-keys.js +4 -3
  275. package/dist/server-secrets-store.js +2 -4
  276. package/dist/server.d.ts +33 -10
  277. package/dist/server.js +454 -136
  278. package/dist/share-context.d.ts +22 -0
  279. package/dist/share-context.js +76 -0
  280. package/dist/shell-lex.d.ts +105 -0
  281. package/dist/shell-lex.js +646 -0
  282. package/dist/sign-ins-store.d.ts +5 -7
  283. package/dist/sign-ins-store.js +12 -16
  284. package/dist/sign-ins.d.ts +7 -11
  285. package/dist/sign-ins.js +40 -41
  286. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  287. package/dist/slots.d.ts +9 -0
  288. package/dist/slots.js +45 -0
  289. package/dist/start-switches.d.ts +6 -5
  290. package/dist/start-switches.js +8 -4
  291. package/dist/stats.d.ts +5 -1
  292. package/dist/stats.js +1 -1
  293. package/dist/store/agent-body.js +2 -2
  294. package/dist/store/dialect.d.ts +4 -0
  295. package/dist/store/dialect.js +1 -0
  296. package/dist/store/index.d.ts +2 -2
  297. package/dist/store/index.js +1 -1
  298. package/dist/store/mcp-record-keys.d.ts +10 -0
  299. package/dist/store/mcp-record-keys.js +13 -0
  300. package/dist/store/postgres/dialect.js +2 -0
  301. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  302. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  303. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  304. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  305. package/dist/store/postgres/store.js +4 -0
  306. package/dist/store/schema.d.ts +44 -4
  307. package/dist/store/schema.js +111 -11
  308. package/dist/store/seal.d.ts +4 -1
  309. package/dist/store/sqlite/run-launch.d.ts +3 -10
  310. package/dist/store/sqlite/run-launch.js +12 -23
  311. package/dist/store/sqlite/run-patch.d.ts +19 -2
  312. package/dist/store/sqlite/run-patch.js +67 -2
  313. package/dist/store/sqlite/store.d.ts +3 -0
  314. package/dist/store/sqlite/store.js +177 -32
  315. package/dist/store/store-schema.js +3 -4
  316. package/dist/store/store.d.ts +74 -25
  317. package/dist/store/store.js +14 -11
  318. package/dist/store-reads/analytics.d.ts +2 -1
  319. package/dist/store-reads/analytics.js +7 -5
  320. package/dist/store-reads/learning.d.ts +102 -136
  321. package/dist/store-reads/learning.js +251 -302
  322. package/dist/store-reads/stats.d.ts +2 -2
  323. package/dist/store-reads/stats.js +13 -7
  324. package/dist/store-view.js +10 -7
  325. package/dist/suggestions.d.ts +1 -1
  326. package/dist/suggestions.js +29 -13
  327. package/dist/template-eval.d.ts +91 -9
  328. package/dist/template-eval.js +448 -105
  329. package/dist/template-import.d.ts +0 -10
  330. package/dist/template-import.js +5 -10
  331. package/dist/timeline/labels.d.ts +1 -1
  332. package/dist/timeline/labels.js +4 -3
  333. package/dist/timeline/timeline.d.ts +23 -11
  334. package/dist/timeline/timeline.js +115 -31
  335. package/dist/timeline/web-calls.d.ts +14 -14
  336. package/dist/timeline/web-calls.js +18 -30
  337. package/dist/tool-gate.d.ts +13 -1
  338. package/dist/tool-gate.js +43 -3
  339. package/dist/tool-keys-store.js +2 -4
  340. package/dist/tool-keys.d.ts +11 -0
  341. package/dist/tool-keys.js +16 -0
  342. package/dist/tool-plane.d.ts +50 -11
  343. package/dist/tool-plane.js +94 -30
  344. package/dist/tools.d.ts +5 -1
  345. package/dist/tools.js +7 -7
  346. package/dist/trigger-email.js +12 -6
  347. package/dist/triggers.d.ts +15 -34
  348. package/dist/triggers.js +119 -126
  349. package/dist/validate.d.ts +8 -1
  350. package/dist/validate.js +163 -23
  351. package/dist/web-fake.d.ts +2 -1
  352. package/dist/web-fake.js +8 -6
  353. package/dist/web-fetch.d.ts +8 -6
  354. package/dist/web-fetch.js +13 -11
  355. package/dist/web-holds.d.ts +32 -0
  356. package/dist/web-holds.js +86 -0
  357. package/dist/web-run.d.ts +32 -5
  358. package/dist/web-run.js +75 -28
  359. package/dist/web-save.d.ts +4 -9
  360. package/dist/web-save.js +27 -55
  361. package/dist/web-search.js +14 -25
  362. package/dist/wires.d.ts +4 -3
  363. package/dist/wires.js +5 -4
  364. package/dist/workspace/archil-claim.d.ts +12 -5
  365. package/dist/workspace/archil-claim.js +45 -5
  366. package/dist/workspace/attach.js +52 -19
  367. package/dist/workspace/attached-computers.d.ts +38 -11
  368. package/dist/workspace/attached-computers.js +81 -16
  369. package/dist/workspace/computer-deps.d.ts +29 -7
  370. package/dist/workspace/computer-deps.js +36 -18
  371. package/dist/workspace/computer-for-claim.d.ts +21 -4
  372. package/dist/workspace/computer-for-claim.js +166 -57
  373. package/dist/workspace/computer-intervals.d.ts +2 -0
  374. package/dist/workspace/computer-intervals.js +1 -1
  375. package/dist/workspace/computer-janitor.d.ts +48 -14
  376. package/dist/workspace/computer-janitor.js +153 -44
  377. package/dist/workspace/computer-kept.d.ts +158 -32
  378. package/dist/workspace/computer-kept.js +288 -63
  379. package/dist/workspace/computer-providers.d.ts +8 -3
  380. package/dist/workspace/computer-providers.js +12 -5
  381. package/dist/workspace/index.d.ts +1 -1
  382. package/dist/workspace/index.js +1 -1
  383. package/dist/workspace/local.js +41 -1
  384. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  385. package/dist/workspace/mount-revoke-left.js +72 -0
  386. package/dist/workspace/paired-route.d.ts +91 -0
  387. package/dist/workspace/paired-route.js +152 -0
  388. package/dist/workspace/resolve-computer.d.ts +5 -2
  389. package/dist/workspace/resolve-computer.js +9 -3
  390. package/dist/workspace/run-end-computers.d.ts +11 -5
  391. package/dist/workspace/run-end-computers.js +153 -28
  392. package/dist/workspace/run-tools.d.ts +22 -3
  393. package/dist/workspace/run-tools.js +17 -5
  394. package/dist/workspace/run-workspace.d.ts +14 -1
  395. package/dist/workspace/run-workspace.js +34 -1
  396. package/dist/workspace/workspace.d.ts +6 -0
  397. package/dist/wrapped.d.ts +8 -2
  398. package/dist/wrapped.js +21 -6
  399. package/package.json +12 -13
  400. package/skills/agentrun-serve/SKILL.md +5 -2
  401. package/templates/README.md +25 -9
  402. package/dist/console/assets/backend-DVhHzJX2.js +0 -166
  403. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  404. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -46,6 +46,7 @@ import { allows, CALL_TOOLS, learnedDraftTools, toolOf } from "./tools.js";
46
46
  import { isMcpName } from "./tool-names.js";
47
47
  import { workflowNodes } from "./model.js";
48
48
  import { SKIPPED_WRITE, toolWord, unmarkedWords } from "./learn/replay-calls.js";
49
+ import { WORKFLOW_FIRST_CALL, workflowDigest } from "./runner/workflow-first.js";
49
50
  /** What a learned_workflow call's approval card says of its MCP actions' arguments: a `{name}` in one is filled in as
50
51
  * the workflow runs. */
51
52
  export const LEARNED_MCP_ARGUMENTS = "each {name} is filled in while the workflow runs, from its input or an earlier step";
@@ -272,13 +273,14 @@ export function learnedWorkflowTool(run) {
272
273
  const loops = [];
273
274
  // A replay's write the recording did not have (learn/replay-calls.ts) rides on the same entry, ran a node or not; so
274
275
  // does how the workflow ended (`ended`, LearnedEnded), the one thing a replay's outcome reads (workflow-first.ts
275
- // pathMetrics): a replay run keeps its entry whatever ran, so a refusal before any node is read as one.
276
- const keep = (signal, ended) => {
276
+ // pathMetrics). The entry is the call's record whatever ran (runner/workflow-calls.ts workflowCallsOf): its
277
+ // workflow's digest, who called it (the platform's call before the agent's first turn, WORKFLOW_FIRST_CALL, or the
278
+ // agent's own), so a refusal before any node is one call too (`refused`: it ran nothing, and the money rule counts
279
+ // it on no side), and a call stopped part way one with no `ended`.
280
+ const record = { call: ledger.call, workflow: flow.name, digest: workflowDigest(flow), caller: ledger.call === WORKFLOW_FIRST_CALL ? "platform" : "agent" };
281
+ const keep = (signal, ended, refused) => {
277
282
  const skipped = run.replay?.skipped;
278
- // A loop's exit counts too: a loop over an empty map ends no node, yet its row is the run's (metrics `loops`).
279
- if (!trace.length && !loops.length && !skipped && !(run.replay && ended))
280
- return undefined;
281
- return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { call: ledger.call, workflow: flow.name, nodes: trace, ...(loops.length ? { loops } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}) } })), signal).catch(() => undefined);
283
+ return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { ...record, nodes: trace, ...(loops.length ? { loops } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}), ...(refused ? { refused } : {}) } })), signal).catch(() => undefined);
282
284
  };
283
285
  let said;
284
286
  try {
@@ -288,20 +290,20 @@ export function learnedWorkflowTool(run) {
288
290
  await keep(BACKGROUND_CONTEXT);
289
291
  throw error;
290
292
  }
291
- await keep(context, said.ended);
293
+ await keep(context, said.ended, said.refused);
292
294
  return forModel(said.text, { isError: said.isError });
293
295
  },
294
296
  });
295
297
  }
296
298
  /** `flow` run on `input` for `run`: its output as its tool hands it back (learnedOutput), or why it did not run, and each of its nodes that ran (at most
297
- * LEARNED_NODES_MAX), none for one refused before any node ran. Never throws, but on an abort. `ledger`: the tool call's,
299
+ * LEARNED_NODES_MAX), none for one refused before any node ran (`refused`). Never throws, but on an abort. `ledger`: the tool call's,
298
300
  * which each call node's paid requests are booked under, as a call of its own within it. `nodes`: where each node is
299
301
  * added as it ends, the caller's to keep when the call is aborted (and so throws) part way. `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
300
302
  * fixed (`memo`), so a rerun of the call (after a park, a crash) goes on from what its model, decision and call nodes
301
303
  * answered then, its MCP calls with the arguments they were asked and approved with, each recorded one answered from its
302
304
  * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), never capped. */
303
305
  export async function runLearned(run, flow, input, signal, ledger, nodes = [], nested, loops = []) {
304
- const refuse = (why) => ({ text: `The learned workflow ${flow.name} was not run: ${why}`, isError: true, nodes, ended: "failed" });
306
+ const refuse = (why) => ({ text: `The learned workflow ${flow.name} was not run: ${why}`, isError: true, nodes, ended: "failed", refused: true });
305
307
  if (!input || typeof input !== "object" || Array.isArray(input))
306
308
  return refuse("its input must be a JSON object");
307
309
  const dsl = await import("@parcha/agentrun-dsl");
@@ -480,8 +482,9 @@ export async function runLearned(run, flow, input, signal, ledger, nodes = [], n
480
482
  return skipped;
481
483
  if (result.status === "escalated")
482
484
  return { text: learnedText(handedBackText(flow.name, result.escalation, result.state, nodes)), isError: true, nodes, ended: "escalated" };
485
+ // It ran and ended neither way: failed, never a refusal (its nodes ran).
483
486
  if (result.status !== "complete")
484
- return refuse(`it ended ${result.status}`);
487
+ return { text: `The learned workflow ${flow.name} was not run: it ended ${result.status}`, isError: true, nodes, ended: "failed" };
485
488
  return { text: learnedText(learnedOutput(result.output)), isError: false, nodes, ended: "complete" };
486
489
  }
487
490
  catch (error) {
@@ -9,30 +9,33 @@
9
9
  * record at its end (metrics.path). */
10
10
  export declare const RUN_PATHS: readonly ["agent", "handed_back", "workflow", "replay", "audit"];
11
11
  export type RunPath = (typeof RUN_PATHS)[number];
12
- /** What a run that looked back kept of its costs as it answered (runner/reflect-hook.ts: store-reads/learning.ts
13
- * answeredOf): when the job answered, what it had cost by then and what looking back cost after it. */
14
- export type CostLooked = {
15
- answered_at?: string;
16
- job_cost_usd?: number | null;
17
- look_back_usd?: number | null;
12
+ /** Who called a learned workflow: the `platform` (it ran first, before the agent's first turn: runner/workflow-first.ts
13
+ * WORKFLOW_FIRST_CALL) or the `agent` (its own learned_workflow call). */
14
+ export declare const WORKFLOW_CALLERS: readonly ["platform", "agent"];
15
+ export type WorkflowCaller = (typeof WORKFLOW_CALLERS)[number];
16
+ /** How a learned workflow's call ended: `answered`, `handed_back` (it escalated, or a run served first took its answer
17
+ * back to the agent), `failed` (it threw, or was stopped), or `refused` (refused before any node ran: its input, a
18
+ * check, a tool its gate denies; it ran nothing, so the money rule counts it on no side). */
19
+ export declare const WORKFLOW_CALL_OUTCOMES: readonly ["answered", "handed_back", "failed", "refused"];
20
+ export type WorkflowCallOutcome = (typeof WORKFLOW_CALL_OUTCOMES)[number];
21
+ /** One call of a learned workflow in a run, as its record keeps it (runner/workflow-calls.ts workflowCallsOf, from the
22
+ * call's own journal entry): the workflow at its `digest`, who called it, how it ended, and what it booked (`usd`: the
23
+ * requests its nodes made, the run's one booking read; null when that can't be told apart from other work or is not
24
+ * known). A run's metrics keep each as `workflow_calls`, in call order; the ledger row and the money rule read them. */
25
+ export type WorkflowCall = {
26
+ readonly workflow: string;
27
+ readonly digest: string;
28
+ readonly caller: WorkflowCaller;
29
+ readonly outcome: WorkflowCallOutcome;
30
+ readonly usd: number | null;
18
31
  };
32
+ /** The workflow calls a run's metrics keep (`workflow_calls`), each checked field by field: one off its shape is left
33
+ * out; none for a run that keeps none. */
34
+ export declare function workflowCallsIn(metrics: unknown): WorkflowCall[];
19
35
  /** A booked figure with its float noise rounded off, nothing more (runner/metrics.ts floatNoiseOff, the precision a run's
20
36
  * own cost is kept at): a decision costs millionths of a dollar, so a figure rounded to the millionth would lose it, and
21
37
  * the run's cost here would read other than its usage row (A8). `+ 0` makes a noise-sized negative a plain 0, never -0. */
22
38
  export declare const noiseOff: (value: number) => number;
23
- /** A run's own cost and what learning added for it, from its row's cost (`rowUsd`: the job, its look-back and any turn a
24
- * person asked of it after) and what it kept as it answered (`looked`, none for a run that did not look back):
25
- * - `cost_usd`: the job's own $: its row's cost less its look-back, never under what it had cost when it answered (a
26
- * later turn's spend is the job's too); its row's cost for a run that did not look back;
27
- * - `learning_usd`: what learning cost for it: its look-back (its compile turn) and what was spent beside it
28
- * (`besideUsd`: its audit's shadow run), 0 for a run that does not learn; null when unknown (a turn stopped mid-ask
29
- * spent what no one knows, or a shadow still running);
30
- * - `total_usd`: their sum, the run's all-in $; null when either is. */
31
- export declare function runCostOf(rowUsd: number | null, looked: CostLooked | null, besideUsd?: number | null): {
32
- cost_usd: number | null;
33
- learning_usd: number | null;
34
- total_usd: number | null;
35
- };
36
39
  /** One run of the series, in the order the agent's runs started: `n` its number among the runs that do a job (JOB_PATHS,
37
40
  * 1 the first: the bill's numbering), null for a replay, which checks a revision and does no job. */
38
41
  export type CostRun = {
@@ -56,7 +59,23 @@ export type CostRun = {
56
59
  cost_upper_bound: boolean;
57
60
  learning_usd: number | null;
58
61
  total_usd: number | null;
62
+ /** `learning_usd`'s parts, each null when unknown: its own compile turns (`compile_usd`, which GET /runs/{id} charges
63
+ * to the revision they drafted instead), its follow-up rounds' turns (`followup_usd`) and its audit's shadow run
64
+ * (`shadow_usd`). `share_usd`: its share of its revision's compile and check (amortize), which GET /runs/{id}'s
65
+ * `learning_usd` carries in place of `compile_usd`. */
66
+ compile_usd: number | null;
67
+ followup_usd: number | null;
68
+ shadow_usd: number | null;
69
+ share_usd: number | null;
70
+ /** Why a learned workflow did not serve it alone (NOT_SERVED), null when nothing says. */
71
+ not_served: NotServed | null;
59
72
  };
73
+ /** Why a run's learned workflow did not serve it alone: `cost_stop`, the money rule stopped it from running first
74
+ * (runner/workflow-first.ts costLineOf: its WORKFLOW_FIRST entry's `needs_revision`, metrics.not_served); `cut`, a
75
+ * restart cut its call and the run was handed back (metrics.workflow_cut, servedOf `cut`), never the workflow's own
76
+ * hand-back: costSummary counts it in `hand_backs.cut`, not `back`. */
77
+ export declare const NOT_SERVED: readonly ["cost_stop", "cut"];
78
+ export type NotServed = (typeof NOT_SERVED)[number];
60
79
  /** The fewest runs after the takeover a "times cheaper" figure needs: fewer say too little. */
61
80
  export declare const CHEAPER_AFTER_RUNS = 20;
62
81
  /** How many of a learned workflow's newest runs served first at one version the money rule reads
@@ -66,8 +85,8 @@ export declare const COST_WINDOW = 10;
66
85
  export declare const COST_RUNS_DEFAULT = 1000;
67
86
  export declare const COST_RUNS_MAX = 10000;
68
87
  /** The serving promotion's check (store-reads/learning.ts servingReplayOf): on `n` inputs, the workflow's agreement and the
69
- * agent's own in percent to a tenth, whether it `cleared` the bar (learn/promote.ts checkPasses), and the agreement check
70
- * itself: `agreed` of the `alone` inputs it answered alone said what the agent said, against the bar `agree_min` (0-1).
88
+ * agent's own in percent to a tenth, whether it `cleared` the bar `agree_min` (learn/field-check.ts check's joint floor), and the agreement check
89
+ * itself: `agreed` of the `alone` inputs it answered alone were right on every field, against the bar `agree_min` (0-1).
71
90
  * Passing that bar is all it says: never that the workflow is as accurate as the agent. */
72
91
  export type CostReplay = {
73
92
  n: number;
@@ -1,8 +1,8 @@
1
1
  // An agent's cost per run, run after run (GET /agents/{id}/learning/cost): what each run of its cost, what learning added
2
2
  // for it, and the path it took, so a person sees the cost fall once a learned workflow does the job, and by how much.
3
- // Aggregates only: no run's input, answer or tool text. The store's reader (store-reads/learning.ts agentCostOverStore)
4
- // gives each run's figures and its path (its run record's metrics.path, store-reads/learning.ts runPathOverStore); this module sums its learning and says what the
5
- // series shows (costSummary), the rule the console, the CLI and the CSV all read. It imports only the errors, so the API
3
+ // Aggregates only: no run's input, answer or tool text. Each run's figures come from the ledger (learn/ledger.ts: one row
4
+ // a run written at its end, one spend row a learning cost, read by summarize); this module says what the series shows
5
+ // (costSummary, billOf), the rule the console, the CLI and the CSV all read. It imports only the errors, so the API
6
6
  // document reads its words.
7
7
  import { ApiError } from "./errors.js";
8
8
  /** The path a run took: `workflow`, a learned workflow finished it alone (served first and answered, or its job's only
@@ -15,30 +15,38 @@ import { ApiError } from "./errors.js";
15
15
  * learning). One classifier (store-reads/learning.ts runPathOverStore) writes it on the run's
16
16
  * record at its end (metrics.path). */
17
17
  export const RUN_PATHS = ["agent", "handed_back", "workflow", "replay", "audit"];
18
+ /** Who called a learned workflow: the `platform` (it ran first, before the agent's first turn: runner/workflow-first.ts
19
+ * WORKFLOW_FIRST_CALL) or the `agent` (its own learned_workflow call). */
20
+ export const WORKFLOW_CALLERS = ["platform", "agent"];
21
+ /** How a learned workflow's call ended: `answered`, `handed_back` (it escalated, or a run served first took its answer
22
+ * back to the agent), `failed` (it threw, or was stopped), or `refused` (refused before any node ran: its input, a
23
+ * check, a tool its gate denies; it ran nothing, so the money rule counts it on no side). */
24
+ export const WORKFLOW_CALL_OUTCOMES = ["answered", "handed_back", "failed", "refused"];
25
+ /** The workflow calls a run's metrics keep (`workflow_calls`), each checked field by field: one off its shape is left
26
+ * out; none for a run that keeps none. */
27
+ export function workflowCallsIn(metrics) {
28
+ const calls = metrics && typeof metrics === "object" ? metrics.workflow_calls : undefined;
29
+ if (!Array.isArray(calls))
30
+ return [];
31
+ return calls.flatMap((one) => {
32
+ const c = (one ?? {});
33
+ const usdOk = c.usd === null || (typeof c.usd === "number" && Number.isFinite(c.usd));
34
+ if (typeof c.workflow !== "string" || typeof c.digest !== "string" || !WORKFLOW_CALLERS.includes(c.caller) || !WORKFLOW_CALL_OUTCOMES.includes(c.outcome) || !usdOk)
35
+ return [];
36
+ return [{ workflow: c.workflow, digest: c.digest, caller: c.caller, outcome: c.outcome, usd: c.usd }];
37
+ });
38
+ }
18
39
  /** A mean, rounded to the millionth: a quotient, never a booked figure. */
19
40
  const usd = (value) => Math.round(value * 1e6) / 1e6;
20
41
  /** A booked figure with its float noise rounded off, nothing more (runner/metrics.ts floatNoiseOff, the precision a run's
21
42
  * own cost is kept at): a decision costs millionths of a dollar, so a figure rounded to the millionth would lose it, and
22
43
  * the run's cost here would read other than its usage row (A8). `+ 0` makes a noise-sized negative a plain 0, never -0. */
23
44
  export const noiseOff = (value) => Math.round(value * 1e12) / 1e12 + 0;
24
- /** A run's own cost and what learning added for it, from its row's cost (`rowUsd`: the job, its look-back and any turn a
25
- * person asked of it after) and what it kept as it answered (`looked`, none for a run that did not look back):
26
- * - `cost_usd`: the job's own $: its row's cost less its look-back, never under what it had cost when it answered (a
27
- * later turn's spend is the job's too); its row's cost for a run that did not look back;
28
- * - `learning_usd`: what learning cost for it: its look-back (its compile turn) and what was spent beside it
29
- * (`besideUsd`: its audit's shadow run), 0 for a run that does not learn; null when unknown (a turn stopped mid-ask
30
- * spent what no one knows, or a shadow still running);
31
- * - `total_usd`: their sum, the run's all-in $; null when either is. */
32
- export function runCostOf(rowUsd, looked, besideUsd = 0) {
33
- const answered = looked?.answered_at !== undefined;
34
- const asAnswered = answered ? (looked.job_cost_usd ?? null) : rowUsd;
35
- const back = answered ? (looked.look_back_usd ?? null) : 0;
36
- // What the row holds past the answer and its look-back is a later turn's spend, unknown once the row's cost is; with the
37
- // look-back's cost unknown the two can't be told apart, and the job is what it had cost when it answered.
38
- const job = !answered || asAnswered === null || back === null ? asAnswered : rowUsd === null ? null : Math.max(asAnswered, rowUsd - back);
39
- const spent = back === null || besideUsd === null ? null : back + besideUsd;
40
- return { cost_usd: job === null ? null : noiseOff(job), learning_usd: spent === null ? null : noiseOff(spent), total_usd: job === null || spent === null ? null : noiseOff(job + spent) };
41
- }
45
+ /** Why a run's learned workflow did not serve it alone: `cost_stop`, the money rule stopped it from running first
46
+ * (runner/workflow-first.ts costLineOf: its WORKFLOW_FIRST entry's `needs_revision`, metrics.not_served); `cut`, a
47
+ * restart cut its call and the run was handed back (metrics.workflow_cut, servedOf `cut`), never the workflow's own
48
+ * hand-back: costSummary counts it in `hand_backs.cut`, not `back`. */
49
+ export const NOT_SERVED = ["cost_stop", "cut"];
42
50
  /** The fewest runs after the takeover a "times cheaper" figure needs: fewer say too little. */
43
51
  export const CHEAPER_AFTER_RUNS = 20;
44
52
  /** How many of a learned workflow's newest runs served first at one version the money rule reads
@@ -69,6 +77,7 @@ export function tookOverOf(runs) {
69
77
  export const AFTER_STATES = ["priced", "no_served_runs", "cost_unknown"];
70
78
  export function costSummary(runs, replay = null, cut = new Set()) {
71
79
  const first = runs.findIndex((run) => SERVED_PATHS.includes(run.path));
80
+ // The by-hand side: the `agent` runs before the first one served, every one when none has been.
72
81
  const beforeSide = (first < 0 ? runs : runs.slice(0, first)).filter((run) => run.path === "agent").map((run) => ({ value: run.cost_usd, bound: run.cost_upper_bound }));
73
82
  // Served runs alone: a replay (a check of a new revision, at workflow cost) and a run by hand are never the after side.
74
83
  const served = first < 0 ? [] : runs.slice(first).filter((run) => SERVED_PATHS.includes(run.path));
@@ -40,6 +40,12 @@ export declare const AGREE_ON_PATH_MAX = 128;
40
40
  export declare const AGREE_ON_SEGMENTS_MAX = 8;
41
41
  /** An agree_on path's segments: each a key of an object, from the answer's top level down (a dot always splits). */
42
42
  export declare const pathSegments: (path: string) => string[];
43
+ /** The one name an object literal's prototype setter answers to: never an agree_on segment, nor a key of a grade's
44
+ * expected answer (server.ts), so no field a check or an audit reads is named by it. Refused on a write and on a read. */
45
+ export declare const RESERVED_SEGMENT = "__proto__";
46
+ /** Whether `value` holds an own key RESERVED_SEGMENT at any depth (in an object, or one inside an array): a grade's
47
+ * expected answer that does is refused. */
48
+ export declare const holdsReservedKey: (value: unknown) => boolean;
43
49
  /** Whether `learning` has the agent's runs learn (true, or an object): never false or absent. */
44
50
  export declare const learnsOf: (learning: unknown) => boolean;
45
51
  /** The paths a revision's two answers are compared on: its `learning.agree_on`; undefined, the whole answer. */
@@ -11,7 +11,7 @@
11
11
  // hold_window, hold_disagree: it stops serving (a hold) when its last hold_window audit rows hold at least
12
12
  // hold_disagree disagreements;
13
13
  // stop_window: a second hold within this many served runs of the first stops it for good.
14
- // Both compare two answers (learn/promote.ts sameAnswer) on agree_on, the definition's dotted paths into the answer's
14
+ // Both judge an answer (runner/promotion.ts checkInputOf, one field each) on agree_on, the definition's dotted paths into the answer's
15
15
  // JSON object that say the decision (`verdict.decision`); absent, the whole answer. Nothing is read off the output
16
16
  // schema: its enum can be an echo of the owner's setting, not the decision, and a wrong field that promotes is worse than
17
17
  // none.
@@ -40,6 +40,14 @@ export const AGREE_ON_PATH_MAX = 128;
40
40
  export const AGREE_ON_SEGMENTS_MAX = 8;
41
41
  /** An agree_on path's segments: each a key of an object, from the answer's top level down (a dot always splits). */
42
42
  export const pathSegments = (path) => path.split(".");
43
+ /** The one name an object literal's prototype setter answers to: never an agree_on segment, nor a key of a grade's
44
+ * expected answer (server.ts), so no field a check or an audit reads is named by it. Refused on a write and on a read. */
45
+ export const RESERVED_SEGMENT = "__proto__";
46
+ /** Whether `value` holds an own key RESERVED_SEGMENT at any depth (in an object, or one inside an array): a grade's
47
+ * expected answer that does is refused. */
48
+ export const holdsReservedKey = (value) => Array.isArray(value) ? value.some(holdsReservedKey)
49
+ : value !== null && typeof value === "object" ? Object.hasOwn(value, RESERVED_SEGMENT) || Object.values(value).some(holdsReservedKey)
50
+ : false;
43
51
  /** What is wrong with one agree_on path, in words, or undefined. */
44
52
  function pathIssue(path) {
45
53
  if (path.length > AGREE_ON_PATH_MAX)
@@ -47,6 +55,8 @@ function pathIssue(path) {
47
55
  const segments = pathSegments(path);
48
56
  if (segments.some((segment) => !segment))
49
57
  return "an empty segment";
58
+ if (segments.includes(RESERVED_SEGMENT))
59
+ return `a reserved segment (${RESERVED_SEGMENT})`;
50
60
  if (segments.length > AGREE_ON_SEGMENTS_MAX)
51
61
  return `more than ${AGREE_ON_SEGMENTS_MAX} segments`;
52
62
  return undefined;
@@ -17,11 +17,12 @@ export declare function listenOn(server: Server, host: string, first: number, ne
17
17
  /** Where a server listening on every address (`host` 0.0.0.0 or ::) at `port` is reached from another machine: this
18
18
  * machine's own IPv4 addresses, loopback, link-local and container bridges left out, at most three. None for a server on one address, and
19
19
  * none in a container, whose addresses are its own network's, not the ones its host publishes the port on. None on a
20
- * machine that cannot list its addresses: the links are a convenience, never a reason not to start. `interfaces` and
21
- * `container` are the tests'. */
22
- export declare function elsewhereOf(host: string, port: number, { interfaces, container }?: {
20
+ * machine that cannot list its addresses: the links are a convenience, never a reason not to start. `container` says
21
+ * whether this server runs in one (server.ts asks computer's containerSigns; this file loads before the rest of the
22
+ * server, so it imports node's own modules alone). `interfaces` is the tests'. */
23
+ export declare function elsewhereOf(host: string, port: number, { interfaces, container }: {
23
24
  interfaces?: () => ReturnType<typeof networkInterfaces>;
24
- container?: () => boolean;
25
+ container: () => boolean;
25
26
  }): string[];
26
27
  /** The URL a listening `server` on `host` is reached at on this machine: an address of every interface at its loopback one. */
27
28
  export declare function urlOf(server: Server, host: string): string;
@@ -4,7 +4,6 @@
4
4
  // server is warming. GET /v2/health says so (503, status "warming", the store "opening"), the API answers 503
5
5
  // `unavailable` with a Retry-After, and a browser gets a page that reloads itself. Only node's own modules load here.
6
6
  import { randomBytes } from "node:crypto";
7
- import { existsSync } from "node:fs";
8
7
  import { statfs } from "node:fs/promises";
9
8
  import { createServer } from "node:http";
10
9
  import { networkInterfaces } from "node:os";
@@ -48,13 +47,13 @@ export async function listenOn(server, host, first, nextFreePort) {
48
47
  const everyAddress = (host) => host === "0.0.0.0" || host === "::";
49
48
  // A container network's bridge (Docker's, a VM's) is this machine's alone: no other machine reaches it there.
50
49
  const BRIDGES = /^(docker|br-|veth|virbr|cni|flannel|vmnet|bridge\d)/;
51
- const inContainer = () => existsSync("/.dockerenv") || existsSync("/run/.containerenv");
52
50
  /** Where a server listening on every address (`host` 0.0.0.0 or ::) at `port` is reached from another machine: this
53
51
  * machine's own IPv4 addresses, loopback, link-local and container bridges left out, at most three. None for a server on one address, and
54
52
  * none in a container, whose addresses are its own network's, not the ones its host publishes the port on. None on a
55
- * machine that cannot list its addresses: the links are a convenience, never a reason not to start. `interfaces` and
56
- * `container` are the tests'. */
57
- export function elsewhereOf(host, port, { interfaces = networkInterfaces, container = inContainer } = {}) {
53
+ * machine that cannot list its addresses: the links are a convenience, never a reason not to start. `container` says
54
+ * whether this server runs in one (server.ts asks computer's containerSigns; this file loads before the rest of the
55
+ * server, so it imports node's own modules alone). `interfaces` is the tests'. */
56
+ export function elsewhereOf(host, port, { interfaces = networkInterfaces, container }) {
58
57
  if (!everyAddress(host) || container())
59
58
  return [];
60
59
  let found;
@@ -69,6 +69,15 @@ export declare const liveForRun: (live: RunnerLive, runId: string) => RunnerLive
69
69
  export declare function provenFor(req: Pick<IncomingMessage, "headers">, live: Pick<RunnerLive, "key">, viewerId: string, now?: number, windowMs?: number): boolean;
70
70
  /** How far a relay's proof's time may be from the runner's clock: the one hop's time, and no more. */
71
71
  export declare const RELAY_PROOF_MS = 10000;
72
+ /** The header the server's relay hop names a paired computer's token in, by its SHA-256 (lower-case hex) alone: the
73
+ * runner's listener needs no more (the proof binds that hash, and the box's row is found by it), and a paired token
74
+ * never expires, so it never leaves the server. A minted machine's token, of one run and ending with it, goes as its
75
+ * bearer. */
76
+ export declare const RELAY_TOKEN_HEADER = "x-agentrun-relay-token";
77
+ /** A SHA-256 as RELAY_TOKEN_HEADER carries it. */
78
+ export declare const isTokenSha256: (value: unknown) => value is string;
79
+ /** How long the server waits for a runner's attach listener to take a relayed dial. */
80
+ export declare const RELAY_CONNECT_MS = 10000;
72
81
  /** What a relay's proof binds: the machine's token (its SHA-256), the runner its row names, and that runner's
73
82
  * incarnation. A viewer's id has no newline, so no relay subject is ever a viewer's. */
74
83
  export type RelayTo = {
@@ -143,6 +143,15 @@ export function provenFor(req, live, viewerId, now = Date.now(), windowMs = LIVE
143
143
  // runner and nowhere else. Its window is RELAY_PROOF_MS, and the runner takes each proof once (relayProofs).
144
144
  /** How far a relay's proof's time may be from the runner's clock: the one hop's time, and no more. */
145
145
  export const RELAY_PROOF_MS = 10_000;
146
+ /** The header the server's relay hop names a paired computer's token in, by its SHA-256 (lower-case hex) alone: the
147
+ * runner's listener needs no more (the proof binds that hash, and the box's row is found by it), and a paired token
148
+ * never expires, so it never leaves the server. A minted machine's token, of one run and ending with it, goes as its
149
+ * bearer. */
150
+ export const RELAY_TOKEN_HEADER = "x-agentrun-relay-token";
151
+ /** A SHA-256 as RELAY_TOKEN_HEADER carries it. */
152
+ export const isTokenSha256 = (value) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
153
+ /** How long the server waits for a runner's attach listener to take a relayed dial. */
154
+ export const RELAY_CONNECT_MS = 10_000;
146
155
  const relaySubject = (to) => `attach relay\n${to.tokenSha256}\n${to.runner}\n${to.incarnation}`;
147
156
  /** The server's proof for relaying the dial of token `to.tokenSha256` to runner `to.runner`, at `at` (ms). */
148
157
  export const relayProof = (reach, to, at = Date.now()) => liveProof(reach, relaySubject(to), at);
@@ -18,13 +18,33 @@ export declare function holdApiOnlyMcpOrigins(store: SettingsWriter, apiOnly: bo
18
18
  /** The list the store holds, or undefined when it holds none (a full server's store). */
19
19
  export declare function heldApiOnlyMcpOrigins(store: SettingsReader): Promise<readonly unknown[] | undefined>;
20
20
  /** Why the saved server `name` (`row`) can't be used, or undefined when it can. It can't be used when it is a per_run
21
- * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. */
21
+ * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. `held`:
22
+ * the list a caller already read (heldApiOnlyMcpOrigins); without it, the list is read here, for a per_run row alone.
23
+ * Undefined means "not read", never "none held": a caller passes the list only when the store holds one. */
22
24
  export declare function offApiOnlyMcpOrigins(store: SettingsReader, name: string, row: {
23
25
  auth: string;
24
26
  url: string;
25
27
  createdAt?: number;
26
- }): Promise<string | undefined>;
28
+ }, held?: readonly unknown[]): Promise<string | undefined>;
29
+ /** The words a per_run server the token saved at an origin off the list is refused with (offApiOnlyMcpOrigins). */
30
+ export declare const offApiOnlyMcpOriginsWords: (name: string) => string;
27
31
  /** The names of the saved servers offApiOnlyMcpOrigins refuses now, sorted: none when the store holds no list. What an
28
- * API-only start says once in its log (server.ts), by name alone, never an address. */
32
+ * API-only start says once in its log (server.ts), by name alone, never an address: on an upgrade with the setting
33
+ * unset, the only notice before a run that grants one fails. */
29
34
  export declare function offApiOnlyMcpServers(store: SettingsReader & Parameters<typeof listMcpServers>[0]): Promise<string[]>;
35
+ /** Why the Composio server `name` (`row`) the API token saved can't be used on an API-only store, or undefined when it
36
+ * can: one calling as a single user (not per-run) whose address names a user outside the token's namespace
37
+ * (composioTokenNamespaced), as a save before the namespace (0.1.0-beta.56 and earlier) left it, which may be the
38
+ * owner's. Its claim is refused unsent, in words that say to delete it, since a re-save of it is refused where the
39
+ * owner's server stands on its auth config. A server the owner saved, or any on a full server's store, is as it was. */
40
+ export declare function composioOutsideNamespace(store: SettingsReader, name: string, row: {
41
+ auth: string;
42
+ url: string;
43
+ createdAt: number;
44
+ }, held?: readonly unknown[]): Promise<string | undefined>;
45
+ /** The words a Composio server the token saved before the namespace is refused with (composioOutsideNamespace). */
46
+ export declare const composioOutsideNamespaceWords: (name: string) => string;
47
+ /** The names of the saved servers composioOutsideNamespace refuses now, sorted: none on a full server's store. What an
48
+ * API-only start says once in its log, by name alone, never a user or an address. */
49
+ export declare function composioOutsideNamespaceServers(store: SettingsReader & Parameters<typeof listMcpServers>[0]): Promise<string[]>;
30
50
  export {};
@@ -1,12 +1,6 @@
1
- // The API-only profile's MCP origins (AGENTRUN_API_ONLY_MCP_ORIGINS, env-switch.ts) held to past the save. The server
2
- // writes the list it started with into the store (`mcp.api_only_origins`), and removes it when it starts without the
3
- // profile, so every reader on that store holds a per_run server the token saved to the list as it is now. The readers
4
- // are the server's pin at an agent's save, a runner's first pin, a run's claim and each of its calls. Drop an origin and restart, and a
5
- // server the token saved there sends nothing more: no listing, no run's mcp_auth. A server saved from the owner's
6
- // signed-in session (which an API-only server doesn't serve) is the owner's, whenever it was saved, and the list does not
7
- // govern it. An API-only start with the setting
8
- // unset holds an empty list, so a per_run server the token saved with the profile off is refused until its origin is
9
- // listed; that start says so once in its log, naming each such server (offApiOnlyMcpServers).
1
+ // The API-only MCP origin list (API_ONLY_MCP_ORIGINS_ENV), held in the store past the save: the serve README's API-only section.
2
+ import { composioMadeKey, composioPerRun } from "./composio-made.js";
3
+ import { COMPOSIO_TOKEN_USER_PREFIX, COMPOSIO_USER, composioTokenNamespaced } from "./composio-preset.js";
10
4
  import { mcpSourceKey, savedByToken } from "./mcp-sources.js";
11
5
  import { listMcpServers } from "./mcp-store.js";
12
6
  import { isObject } from "./validate.js";
@@ -26,12 +20,14 @@ export async function heldApiOnlyMcpOrigins(store) {
26
20
  return isObject(held) && Array.isArray(held.origins) ? held.origins : undefined;
27
21
  }
28
22
  /** Why the saved server `name` (`row`) can't be used, or undefined when it can. It can't be used when it is a per_run
29
- * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. */
30
- export async function offApiOnlyMcpOrigins(store, name, row) {
23
+ * server the API token saved, the store holds an API-only list, and its address's origin is not on that list. `held`:
24
+ * the list a caller already read (heldApiOnlyMcpOrigins); without it, the list is read here, for a per_run row alone.
25
+ * Undefined means "not read", never "none held": a caller passes the list only when the store holds one. */
26
+ export async function offApiOnlyMcpOrigins(store, name, row, held) {
31
27
  if (row.auth !== "per_run")
32
28
  return undefined;
33
- const held = await heldApiOnlyMcpOrigins(store);
34
- if (!held)
29
+ const origins = held ?? (await heldApiOnlyMcpOrigins(store));
30
+ if (!origins)
35
31
  return undefined;
36
32
  if (!savedByToken(await store.settings.get(mcpSourceKey(name)), row.createdAt))
37
33
  return undefined;
@@ -42,16 +38,60 @@ export async function offApiOnlyMcpOrigins(store, name, row) {
42
38
  catch {
43
39
  origin = "";
44
40
  }
45
- if (held.includes(origin))
41
+ if (origins.includes(origin))
46
42
  return undefined;
47
- return `The MCP server ${name} can't be used: the API token saved it at an origin that is no longer on this server's AGENTRUN_API_ONLY_MCP_ORIGINS. Nothing was sent.`;
43
+ return offApiOnlyMcpOriginsWords(name);
48
44
  }
45
+ /** The words a per_run server the token saved at an origin off the list is refused with (offApiOnlyMcpOrigins). */
46
+ export const offApiOnlyMcpOriginsWords = (name) => `The MCP server ${name} can't be used: the API token saved it at an origin that is no longer on this server's AGENTRUN_API_ONLY_MCP_ORIGINS. Nothing was sent.`;
49
47
  /** The names of the saved servers offApiOnlyMcpOrigins refuses now, sorted: none when the store holds no list. What an
50
- * API-only start says once in its log (server.ts), by name alone, never an address. */
48
+ * API-only start says once in its log (server.ts), by name alone, never an address: on an upgrade with the setting
49
+ * unset, the only notice before a run that grants one fails. */
51
50
  export async function offApiOnlyMcpServers(store) {
51
+ const held = await heldApiOnlyMcpOrigins(store);
52
+ if (!held)
53
+ return [];
52
54
  const off = [];
53
55
  for (const row of await listMcpServers(store))
54
- if (await offApiOnlyMcpOrigins(store, row.name, row))
56
+ if (await offApiOnlyMcpOrigins(store, row.name, row, held))
55
57
  off.push(row.name);
56
58
  return off.sort();
57
59
  }
60
+ /** Why the Composio server `name` (`row`) the API token saved can't be used on an API-only store, or undefined when it
61
+ * can: one calling as a single user (not per-run) whose address names a user outside the token's namespace
62
+ * (composioTokenNamespaced), as a save before the namespace (0.1.0-beta.56 and earlier) left it, which may be the
63
+ * owner's. Its claim is refused unsent, in words that say to delete it, since a re-save of it is refused where the
64
+ * owner's server stands on its auth config. A server the owner saved, or any on a full server's store, is as it was. */
65
+ export async function composioOutsideNamespace(store, name, row, held) {
66
+ if (row.auth !== "headers")
67
+ return undefined;
68
+ if (!(held ?? (await heldApiOnlyMcpOrigins(store))))
69
+ return undefined;
70
+ const source = await store.settings.get(mcpSourceKey(name));
71
+ if (!savedByToken(source, row.createdAt) || !isObject(source) || source.source !== "composio")
72
+ return undefined;
73
+ if (composioPerRun(row, await store.settings.get(composioMadeKey(name))))
74
+ return undefined;
75
+ let user;
76
+ try {
77
+ user = new URL(row.url).searchParams.get("user_id") ?? COMPOSIO_USER;
78
+ }
79
+ catch {
80
+ user = "";
81
+ }
82
+ return composioTokenNamespaced(user) ? undefined : composioOutsideNamespaceWords(name);
83
+ }
84
+ /** The words a Composio server the token saved before the namespace is refused with (composioOutsideNamespace). */
85
+ export const composioOutsideNamespaceWords = (name) => `The MCP server ${name} can't be used: the API token saved it before its Composio users were kept in the token's namespace (${COMPOSIO_TOKEN_USER_PREFIX}), so it calls as a user that may be the owner's. Delete it, then save it again. Nothing was sent.`;
86
+ /** The names of the saved servers composioOutsideNamespace refuses now, sorted: none on a full server's store. What an
87
+ * API-only start says once in its log, by name alone, never a user or an address. */
88
+ export async function composioOutsideNamespaceServers(store) {
89
+ const held = await heldApiOnlyMcpOrigins(store);
90
+ if (!held)
91
+ return [];
92
+ const out = [];
93
+ for (const row of await listMcpServers(store))
94
+ if (await composioOutsideNamespace(store, row.name, row, held))
95
+ out.push(row.name);
96
+ return out.sort();
97
+ }
@@ -51,11 +51,23 @@ export type McpKeys = {
51
51
  out(tool: string, args: Record<string, unknown>): Record<string, unknown>;
52
52
  back(text: string): string;
53
53
  };
54
+ /** A server's results kept as files: under `dir` (relative to the run's files), what `of` reads from a tool's answer. */
55
+ export type McpResults = {
56
+ dir: string;
57
+ of(tool: string, reply: Record<string, unknown>): {
58
+ name: string;
59
+ value: unknown;
60
+ }[];
61
+ };
54
62
  /** A server that prices its own calls. `ask` calls one of the server's tools with the run's credential, unbooked and
55
63
  * unrecorded, and answers its raw result (none: it failed). `keys`: the keys it scopes to the run, on every call of
56
64
  * the server, billed or not. */
57
65
  export interface McpMeter {
58
66
  keys?: McpKeys;
67
+ /** The results a server's answers carry that the run keeps as data (fal's completed jobs, fal-price.ts falResults):
68
+ * each one's `name` (one the meter vouches for as a plain file name: fal's request_id, a UUID) and `value`, filed by
69
+ * the gateway at `<dir>/<name>.json` in the run's files, saved once (save-once.ts). */
70
+ results?: McpResults;
59
71
  bills(tool: string): boolean;
60
72
  quote(tool: string, args: Record<string, unknown>, ask: (tool: string, args: Record<string, unknown>) => Promise<Record<string, unknown> | undefined>, signal: AbortSignal): Promise<McpQuote>;
61
73
  }
@@ -81,8 +93,10 @@ export interface McpGatewayOptions {
81
93
  pin: McpPin;
82
94
  credentials: McpCredentials;
83
95
  /** The run's Workspace, where an answer too long for the model is filed (the run's process still hands its folder's
84
- * path). */
85
- work: () => Workspace | string;
96
+ * path in Mode 1). Read only when a call's answer files something, and awaited: a host may open the Workspace then,
97
+ * once, rather than for every claim (run-child-host.ts). A Workspace that cannot be opened files nothing, as a write
98
+ * that fails does. */
99
+ work: () => Workspace | string | Promise<Workspace>;
86
100
  /** For tests: the fetch the upstream client sends with. */
87
101
  fetch?: typeof fetch;
88
102
  /** For tests: the bound on one call (CALL_MS) and on a server's first connection (CONNECT_MS). */
@@ -25,6 +25,7 @@ import { TOOL_UNMETERED } from "./timeline/index.js";
25
25
  import { until } from "./until.js";
26
26
  import { meterFor, meterNamed } from "./fal-price.js";
27
27
  import { filedAnswer } from "./filed-answer.js";
28
+ import { saveOnce } from "./save-once.js";
28
29
  import { paidLedger, paidStep } from "./paid-calls.js";
29
30
  import { metaToolOf } from "./mcp-meta.js";
30
31
  import { SIGN_IN_AGAIN } from "./mcp-oauth.js";
@@ -304,10 +305,10 @@ export function mcpGateway(options) {
304
305
  return text;
305
306
  const name = `${tool}-${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID().slice(0, 8)}`;
306
307
  if (other === 0)
307
- return filedAnswer(() => workspaceAt(options.work()), `evidence/mcp/${server}`, name, text, MCP_CLIP);
308
+ return filedAnswer(async () => workspaceAt(await options.work()), `evidence/mcp/${server}`, name, text, MCP_CLIP);
308
309
  const head = text.length > MCP_CLIP ? `${text.slice(0, MCP_CLIP)}\n[cut at ${MCP_CLIP} of ${text.length} characters; ` : `${text}\n[${other} block${other > 1 ? "s" : ""} that ${other > 1 ? "are" : "is"} not text; `;
309
310
  try {
310
- await workspaceAt(options.work()).write(`evidence/mcp/${server}/${name}.json`, clean(JSON.stringify(result)));
311
+ await workspaceAt(await options.work()).write(`evidence/mcp/${server}/${name}.json`, clean(JSON.stringify(result)));
311
312
  }
312
313
  catch (error) {
313
314
  // The Workspace's code and the port's line for it, never the error's message, which names paths.
@@ -315,6 +316,39 @@ export function mcpGateway(options) {
315
316
  }
316
317
  return `${head}the whole answer is in the run's files at evidence/mcp/${server}/${name}.json]`;
317
318
  };
319
+ /** The results `result` carries that `server`'s meter keeps (McpMeter.results), each filed at its `<dir>/<name>.json`
320
+ * in the run's files, once (save-once.ts): a file, folder or link already there is kept, and a link on the way is never
321
+ * followed. Scrubbed as the model's text is. Nothing is said of it in the answer, and a result that could not be filed
322
+ * is left out: a filing never fails the call. */
323
+ const fileResults = async (server, tool, result, clean) => {
324
+ const results = meters.get(server)?.results;
325
+ if (!results)
326
+ return;
327
+ let found;
328
+ try {
329
+ found = results.of(tool, result);
330
+ }
331
+ catch {
332
+ return;
333
+ }
334
+ if (!found.length)
335
+ return;
336
+ let work;
337
+ try {
338
+ work = workspaceAt(await options.work());
339
+ }
340
+ catch {
341
+ return;
342
+ }
343
+ for (const { name, value } of found) {
344
+ try {
345
+ await saveOnce(work, `${results.dir}/${name}.json`, clean(JSON.stringify(value) ?? "null"));
346
+ }
347
+ catch {
348
+ // Not filed: a link on the way, a write that failed. The answer stands as the server gave it.
349
+ }
350
+ }
351
+ };
318
352
  /** The call itself, to a server whose address is the pinned one. A gate's decision or a paid call's hold goes around
319
353
  * it, in `call` below: the one place every harness's call passes before anything is sent. */
320
354
  /** `sending`, when given, runs once the server is connected and right before the call leaves: its refusal (a text)
@@ -345,7 +379,11 @@ export function mcpGateway(options) {
345
379
  : (await upstream.callTool({ name: tool.name, arguments: args }, { signal, timeout: options.bounds?.callMs ?? CALL_MS, toolDefinition: { name: tool.name, inputSchema: tool.inputSchema } }));
346
380
  outcome.raw = result;
347
381
  // A meter's own read (`quiet`): its raw result is all that is wanted, nothing filed for a model to read.
348
- return said(outcome.quiet ? "" : await textOf(server, tool.name, result, clean), result.isError === true);
382
+ if (outcome.quiet)
383
+ return said("", result.isError === true);
384
+ // Filed before the answer is given, so a model that reads it next finds it.
385
+ await fileResults(server, tool.name, result, clean);
386
+ return said(await textOf(server, tool.name, result, clean), result.isError === true);
349
387
  }
350
388
  catch (error) {
351
389
  if (signal.aborted)