@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
@@ -301,16 +301,6 @@ export function runPathOf(rows) {
301
301
  return "agent";
302
302
  return onlyLearnedWorkflows(rows) ? "workflow" : "handed_back";
303
303
  }
304
- /** The learned workflow a run's job called last by its call's `name` (callArgsOf's arguments, in the job's order: `calls`),
305
- * or null when it called none by a name. */
306
- export function workflowNameOf(calls) {
307
- for (let i = calls.length - 1; i >= 0; i--) {
308
- const call = calls[i];
309
- if (LEARNED_NAMES.has(call.tool) && typeof call.args.name === "string")
310
- return call.args.name;
311
- }
312
- return null;
313
- }
314
304
  /** Whether a draft's workflow.json (`json`) waits for its owner's OK whatever its checks say: a step of it calls an MCP
315
305
  * tool with no declared price (workflow-draft.ts unpricedCalls), from the prices each server's row keeps (mcp-probe.ts
316
306
  * McpPrices), or an SDK run's manifest gives. A server the store can't read gives no price: held. */
@@ -498,7 +488,7 @@ export async function recordDraftFailed(deps, input) {
498
488
  const digest = draftFailedDigest(input.runId);
499
489
  const failed = input.errors.join("; ").slice(0, CHECK_TEXT_MAX) || "no draft passed";
500
490
  const reason = `${DRAFT_FAILED}: ${failed}. ${attempt === 2 ? "It was the recompile, so it stops: nothing compiles again until its owner acts" : "It is not promoted; the next due run compiles it once more"}`;
501
- const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
491
+ const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, agent_agreed: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
502
492
  const kept = await recordPromotion(deps.store.settings, input.agentId, { workflow, digest, at: new Date().toISOString(), decided: "hold", reason, check }, (was) => was === undefined, refusedIn(() => deps.learningFolder(input.agentId), deps.store, deps.log));
503
493
  if (kept.won)
504
494
  deps.log?.(`learning: run ${input.runId}: the compile of ${workflow} failed its checks (attempt ${attempt}${attempt === 2 ? ", stopped" : ""})`);
@@ -535,8 +525,8 @@ export function traceFrom(timeline, refuse) {
535
525
  /** The compile turn's facts for run `runId` of agent `agentId` (learn/compile.ts): a revision of the learned workflow
536
526
  * that fits the run's input and whose promotion holds it at main's digest (runner/promotion.ts: its one check on the
537
527
  * agent's own runs fell under the bar; its champion served the run, or the agent did by hand), its text as main holds
538
- * it, with the check's numbers and the inputs it disagreed on, once per hold (none when any run since the hold compiled
539
- * it, read from the agent's kept learning; a stopped check's none; a connected agent's hold on give-backs only once it
528
+ * it, with the check's numbers and the inputs it disagreed on, once per hold (none when any run since the hold was asked
529
+ * its revise, read from the agent's kept learning; a stopped check's none; a connected agent's hold on give-backs only once it
540
530
  * is due, as a first compile is, on its runs since the hold); else, when the job is due (compileDue: the run
541
531
  * completed, the agent has no learned workflow active or waiting, and it has its definition's compile_after completed
542
532
  * agent runs), a new one, compiled once: one more after a first compile whose drafts all failed their checks, and none
@@ -653,15 +643,17 @@ export async function compileAskOf(deps, input) {
653
643
  const sinceHold = own.filter(after).length + (after(listed[at]) ? ending : 0);
654
644
  if (heldOnGiveBacks(read.held.check) && !(ending === 1 && sinceHold >= compileAfter))
655
645
  return sayLeftOut(), undefined;
656
- // Once per hold: a run since it that compiled this workflow asked already, whatever came of it (its revision is on its
657
- // way to a replay, or its draft failed its checks), however many runs ago. Read from the agent's kept learning since
658
- // the hold, never a window of its last runs; one that can't be read asks nothing. A draft that failed since, not stopped
659
- // (only a revise of a connected agent's hold on give-backs: reviseAttemptOf), asks once more: counted from it, its own
660
- // run's kept learning (written after its record, at the run's end) not counted.
646
+ // Once per hold: a run since it that was asked this hold's revise (its compile record names the held digest) asked
647
+ // already, whatever came of it (its revision is on its way to a replay, or its draft failed its checks), however many
648
+ // runs ago. A new compile asked before the hold (in flight as it was decided) that drafted the same workflow and ended
649
+ // after it is no revise. Read from the agent's kept learning since the hold, never a window of its last runs; one that
650
+ // can't be read asks nothing. A draft that failed since, not stopped (only a revise of a connected agent's hold on
651
+ // give-backs: reviseAttemptOf), asks once more: counted from it, its own run's kept learning (written after its record,
652
+ // at the run's end) not counted.
661
653
  const failed = records.findLast((one) => one.workflow === read.held.workflow && draftFailedOf(one) && !one.check?.stopped && !(one.at < read.held.at));
662
654
  const since = Date.parse(failed?.at ?? read.held.at);
663
655
  const kept = await deps.store.learning.proposals(agentId, { limit: HELD_ASKED_READ }).catch(() => undefined);
664
- const asked = (one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow && draftFailedDigest(one.runId) !== failed?.digest;
656
+ const asked = (one) => !(one.createdAt < since) && compiledOf(one)?.workflow === read.held.workflow && compiledOf(one)?.held === read.held.digest && draftFailedDigest(one.runId) !== failed?.digest;
665
657
  if (!kept || kept.some(asked))
666
658
  return sayLeftOut(), undefined;
667
659
  const { workflow, digest, reason, check, audit } = read.held;
@@ -1,8 +1,10 @@
1
- import { redactedAnswer, redactedLive, redactedOutput } from "../key-refusal.js";
1
+ import { redactedAnswer, redactedLive, redactedOutputWhole } from "../key-refusal.js";
2
2
  /** A run's held state as the live view keeps it, under `values`, every secret value the run's one redactor holds. A
3
- * running tool's id and name are cut whole (redactedAnswer). Its args by a workflow output's rule (redactedOutput): every
4
- * string, property names included; a number whose digits hold a held value or that equals one, withheld; an object two of
5
- * whose names come out the same once cut, withheld whole, never one value dropped over the other. What is still
3
+ * running tool's id and name are cut whole (redactedAnswer). Its args by a workflow output's rule (redactedOutputWhole):
4
+ * read whole first, so a held value split across two of its fields withholds them as "[redacted]", as a call's arguments
5
+ * are in its Timeline; else every string, property names included; a number whose digits hold a held value or that
6
+ * equals one, withheld; an object two of whose names come out the same once cut, withheld whole, never one value
7
+ * dropped over the other. What is still
6
8
  * streaming (the tool's output, the partial answer) by redactedLive: a tail as long as a held value's widest form is held
7
9
  * back, so a secret half streamed at a tick shows none of itself; the settled record replaces it whole once it ends. */
8
10
  function cutHeld(state, values) {
@@ -11,7 +13,7 @@ function cutHeld(state, values) {
11
13
  const tools = state.tools.map((tool) => ({
12
14
  callId: redactedAnswer(tool.callId, values),
13
15
  name: redactedAnswer(tool.name, values),
14
- ...(tool.args !== undefined ? { args: redactedOutput(tool.args, values) } : {}),
16
+ ...(tool.args !== undefined ? { args: redactedOutputWhole(tool.args, values) } : {}),
15
17
  ...(tool.output !== undefined ? { output: redactedLive(tool.output, values) } : {}),
16
18
  }));
17
19
  return { tools, ...(state.partial ? { partial: { text: redactedLive(state.partial.text, values) } } : {}) };
@@ -171,8 +171,6 @@ export interface LoopDeps {
171
171
  flush(): Promise<void>;
172
172
  /** Aborted on claim loss, self-stop or shutdown: in-flight model and tool calls are cut at once. */
173
173
  signal: AbortSignal;
174
- /** The end-of-run step (EndOfRunTurn): asked once before a run that answered or failed writes its end. Absent: none. */
175
- endOfRun?: EndOfRunTurn;
176
174
  /** Resolves once the claim's first delivery has handed every untaken row it read to command() (each call returned),
177
175
  * or at once when there were none: a resumed ask with no answer row waits for it before it parks again, so an
178
176
  * approve already on its way is never raced. Never rejects. */
@@ -31,6 +31,13 @@ export declare const END_PATCH_UNKNOWN: {
31
31
  readonly costUsd: null;
32
32
  readonly metrics: null;
33
33
  };
34
+ /** What a loop's bound is armed on: the timer half of the runner's clock (RunnerOptions.clock). Every runner arms the real
35
+ * one (REAL_TIMER); a test's fires when its case says, so a stalled read is let go on an event, never after a real wait. */
36
+ export interface BoundTimer {
37
+ setTimeout(fn: () => void, ms: number): unknown;
38
+ clearTimeout(handle: unknown): void;
39
+ }
40
+ export declare const REAL_TIMER: BoundTimer;
34
41
  /** How many times an end reads its cost before it is written unknown, and the pause between reads: all within the end's
35
42
  * bound (END_PATCH_MS), so a store that refused one read never leaves the cost null. The stored cost is every reader's
36
43
  * answer for an ended run (the list, the view, usage, learning), so a null there stays only when no read could be made. */
@@ -30,6 +30,7 @@ export const END_PATCH_MS = 30_000;
30
30
  /** What an end whose patch was late or failed writes: its cost and metrics unknown (null), never left as an earlier end
31
31
  * of the run stored them, never read as a run that cost $0 by the agent's own path. */
32
32
  export const END_PATCH_UNKNOWN = { costUsd: null, metrics: null };
33
+ export const REAL_TIMER = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) };
33
34
  /** How many times an end reads its cost before it is written unknown, and the pause between reads: all within the end's
34
35
  * bound (END_PATCH_MS), so a store that refused one read never leaves the cost null. The stored cost is every reader's
35
36
  * answer for an ended run (the list, the view, usage, learning), so a null there stays only when no read could be made. */
@@ -35,7 +35,7 @@ import { bootSealKey } from "../seal-key.js";
35
35
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
36
36
  import { migrationsIn, openStore, RunnerBelowFloor, SchemaVersionUnknown, StoreAwaitsServer, storePlace, storeTarget } from "../store/index.js";
37
37
  import { SCHEMA_VERSION } from "../store/schema.js";
38
- import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
38
+ import { SEAL_KEY_ENV, sealKeyIn } from "../tool-keys.js";
39
39
  import { LAUNCH_HOOK_SECRET_ENV } from "../trigger-launch-hook.js";
40
40
  import { FAUX_BROWSER_ENV } from "../tools.js";
41
41
  import { claimViewOpener } from "../computer-live.js";
@@ -99,8 +99,9 @@ export async function openRunnerStore(dataDir, env, warn, url) {
99
99
  * tokens (the token and the token list) and API key, the seal key (the runner holds it as its sealKey), the store's connection (its URL holds a
100
100
  * database password), the launch hook's signing secret (the server's alone), and the Composio account key, which the
101
101
  * runner's claim alone reads (composio-made.ts composioEnvKey) and sends only as a granted Composio server's MCP header.
102
- * And every OpenTelemetry setting (OTEL_*: OTEL_EXPORTER_OTLP_HEADERS holds a backend's key): a run's process is handed
103
- * them on its pipe (secrets.ts OTEL_PAIR), never in an environment, so no harness, tool or computer of a run has them. */
102
+ * And every OpenTelemetry setting (OTEL_*: OTEL_EXPORTER_OTLP_HEADERS holds a backend's key): a run's process is never
103
+ * handed them, in an environment or on its pipe. It posts its trace over its channel and the runner exports it
104
+ * (otel/tracer.ts postedTracing, tracePosts), so no harness, tool or computer of a run has them. */
104
105
  const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_TOKENS" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name === LAUNCH_HOOK_SECRET_ENV || name === COMPOSIO_KEY_ENV || name.startsWith("AGENTRUN_STORE_") || name.startsWith("OTEL_");
105
106
  /** A run's environment as the runner hands its loops (AdapterSpecDeps.env): this process's, less the runner's own
106
107
  * secrets, with every other secret the launcher's pipe handed it (a model key, a tool key, a box key) readable by name
@@ -146,9 +147,7 @@ export function besideRunEnv(env, switches) {
146
147
  * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
147
148
  * this process's, as it was handed or booted). Refused in words with no seal key. */
148
149
  export function runnerLoop(store, dataDir, env = process.env, booted, isolation, dial, paired) {
149
- const sealKey = booted ?? sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
150
- if (!sealKey)
151
- throw new RunnerRefused(`A runner needs the server's seal key (${SEAL_KEY_ENV}): start it through the server's launcher, which hands it over.`);
150
+ const sealKey = booted ?? sealKeyIn(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV], "a runner's secrets", { Refused: RunnerRefused, none: "start the runner through the server's launcher, which hands it over" });
152
151
  const runs = runEnv(env);
153
152
  // The run's computer at its claim, composed once (runnerComputers): none for the runner's place, a box's computer by the
154
153
  // agent's setting, its keys read from the run environment first, then the store's sealed rows; a Docker computer's
@@ -274,14 +273,16 @@ export async function startRunnerProcess(options) {
274
273
  // The janitor sweeps with the computers the loop composed, never a second composition. Its lines are the runner's
275
274
  // warnings, said where the runner says its others (warn: stderr unless a test gives its own).
276
275
  // It sweeps as this runner (its name and its presence's incarnation): a computer kept at a park pinned to another
277
- // runner still there is that runner's to end (computer-kept.ts sweepKept).
276
+ // runner still there is that runner's to end (computer-kept.ts sweepKept). The seal key is the claims' too: it opens
277
+ // the Archil key a kept computer's mount credential is removed with.
278
278
  if (options.janitor && typeof parts !== "function")
279
- janitor = startJanitor({ store, computers: parts.computers, env: parts.env, log: warn, self: { runner: name, incarnation } });
279
+ janitor = startJanitor({ store, computers: parts.computers, env: parts.env, sealKey: seal.key, log: warn, self: { runner: name, incarnation } });
280
280
  // Before it claims: the scratch folders of runs that ended after their runner died (scratch-sweep.ts), said as warnings.
281
281
  await sweepEndedScratch(store, options.dataDir, { log: warn });
282
- // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts), as
283
- // this runner, as the janitor sweeps: a computer kept pinned to another runner still keeping it is that runner's.
284
- const runEnded = projectRunEnded(store, typeof parts !== "function" ? runEndComputers({ store, computers: parts.computers, log: warn, self: () => ({ runner: name, incarnation }) }) : undefined);
282
+ // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts),
283
+ // and with the janitor's environment and seal key, so a machine kept on Archil it deletes has its mount credential
284
+ // removed.
285
+ const runEnded = projectRunEnded(store, typeof parts !== "function" ? runEndComputers({ store, computers: parts.computers, log: warn, env: parts.env, sealKey: seal.key }) : undefined);
285
286
  runner = startRunner({
286
287
  store,
287
288
  createLoop,
@@ -26,7 +26,10 @@
26
26
  // refused unsent (UNUSABLE.perRunMissing).
27
27
  //
28
28
  // A per-run Composio server (composio-made.ts composioPerRun) is bound by each run's caller ({composio_user_id,
29
- // connected_account_id?} in mcp_auth, sealed in its launch): its entry carries them as `query` (mcp-gateway.ts).
29
+ // connected_account_id?} in mcp_auth, sealed in its launch): its entry carries them as `query` (mcp-gateway.ts). Each
30
+ // open reads the owner's Composio users again (composio-owners.ts): a binding of one that the owner's session didn't hand
31
+ // (the token's, or one sealed before the seal marked who handed it) is refused unsent (UNUSABLE.composioOwnersUser); on
32
+ // an API-only store, any binding of one is (COMPOSIO_OWNERS_USER_WORDS).
30
33
  // A Composio server saved with api_key_env (composio-made.ts key_env) seals no key: each open reads the variable's value
31
34
  // as the runner was handed it at its start (secrets.ts secret, never its environment), for an address on Composio's origin
32
35
  // alone (composioEnvKey), and only for a server the run is granted: the run's process never holds it. Unset, or a row at
@@ -55,13 +58,14 @@
55
58
  // the next call sends the new one (or is refused for the move); and an OAuth access token within REFRESH_MARGIN_MS of its
56
59
  // end is refreshed through open's lease path: behind the call while the token is still valid (the call goes at once on
57
60
  // it), waited on only when it has run out. Concurrent calls to one server share one such open.
58
- import { heldApiOnlyMcpOrigins, offApiOnlyMcpOrigins } from "../mcp-api-only-origins.js";
61
+ import { composioOutsideNamespace, heldApiOnlyMcpOrigins, offApiOnlyMcpOrigins } from "../mcp-api-only-origins.js";
62
+ import { bindingRuns, ownersComposioUsers, ownersUser } from "../composio-owners.js";
59
63
  import { randomUUID } from "node:crypto";
60
64
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
61
65
  import { pinFirst } from "../mcp-pin-first.js";
62
66
  import { mcpNameOf } from "../tool-names.js";
63
67
  import { composioEnvKey, composioMadeKey, composioPerRun, recordedMade } from "../composio-made.js";
64
- import { composioRunQuery } from "../composio-preset.js";
68
+ import { COMPOSIO_OWNERS_USER_WORDS, composioRunQuery } from "../composio-preset.js";
65
69
  import { META_REASON, metaToolOf } from "../mcp-meta.js";
66
70
  import { resourceToolProblem } from "../mcp-resources.js";
67
71
  import { credentialInQuery, credentialInQueryWords, shownUrl } from "../mcp-probe.js";
@@ -237,6 +241,10 @@ export async function mcpClaim(options) {
237
241
  const account = row.auth === "headers" ? await composioAccount(name, row) : undefined;
238
242
  if (account && "unopened" in account)
239
243
  return entry({ unopened: account.unopened }), { awaited: false };
244
+ // One the API token saved calling as a user outside its namespace (saved before it): refused unsent, as said at start.
245
+ const outside = account ? undefined : await composioOutsideNamespace(store, name, row);
246
+ if (outside)
247
+ return entry({ unopened: outside }), { awaited: false };
240
248
  const query = account?.query;
241
249
  // Its key named by api_key_env: the value the runner was handed at its start, for an address on Composio's origin
242
250
  // alone; else its calls refused unsent, naming why (composioEnvKey).
@@ -406,12 +414,20 @@ export async function mcpClaim(options) {
406
414
  };
407
415
  /** A per-run Composio server's account for this run, as the query its requests add (composio-preset.ts
408
416
  * composioRunQuery); or why there is none. Undefined: `row` is no per-run Composio server (its own record says so:
409
- * composioPerRun). */
417
+ * composioPerRun). A binding of a user the owner calls as (composio-owners.ts ownersComposioUsers, the start's own
418
+ * check, read again: one sealed before the check, or before the owner's server was saved) is refused unsent: on an
419
+ * API-only store whoever handed it, on a full one unless the owner's session did (bindingRuns). */
410
420
  const composioAccount = async (name, row) => {
411
421
  if (!composioPerRun(row, await store.settings.get(composioMadeKey(name))))
412
422
  return undefined;
413
423
  const given = await handed(name, row.url, "composio");
414
- return "unopened" in given ? given : { query: composioRunQuery(given.composio) };
424
+ if ("unopened" in given)
425
+ return given;
426
+ const owners = await ownersComposioUsers(store);
427
+ const apiOnly = (await heldApiOnlyMcpOrigins(store)) !== undefined;
428
+ if (apiOnly ? ownersUser(owners, given.composio.user_id) : !bindingRuns(given.composio, owners))
429
+ return { unopened: apiOnly ? COMPOSIO_OWNERS_USER_WORDS : UNUSABLE.composioOwnersUser };
430
+ return { query: composioRunQuery(given.composio) };
415
431
  };
416
432
  const fresh = async () => {
417
433
  if (!pin || released)
@@ -69,7 +69,7 @@ export function refusedName(caller, name, tools, hostName = (given) => given) {
69
69
  }
70
70
  const NO_NESTED = (caller) => `${caller} can't run here: this harness gives it no way to call the run's tools. Nothing was run.`;
71
71
  /** A nested answer as a tool's answer. */
72
- const answered = (result) => ({ text: result.text, ...(result.isError ? { isError: true } : {}), ...(result.images?.length ? { images: result.images } : {}), ...(result.structured !== undefined ? { structured: result.structured } : {}) });
72
+ const answered = (result) => ({ text: result.text, ...(result.isError ? { isError: true } : {}), ...(result.images?.length ? { images: result.images } : {}), ...(result.structured !== undefined ? { structured: result.structured } : {}), ...(result.refused ? { refused: true } : {}) });
73
73
  /** A script's `computer` (the computer package's bindComputer, over its card) as one expression of the script's isolate
74
74
  * over its `tools`: an observe, an act or a screenshot calls its own step tool, every other op computer_op, so each is a
75
75
  * nested call of the run's tool, asked about and recorded as that tool's. On an agent whose exec is off, reaching for
@@ -337,8 +337,9 @@ function scriptValue(result) {
337
337
  * rerun, after a person's answer or a crash) that call's outcome, with every call before it as recorded. */
338
338
  function endedWith(told, last, ranNow) {
339
339
  const lines = told.map(({ name, result }, i) => lineOf(i + 1, name, result));
340
+ // Marked refused: the script's own row reads Refused, as the call it stopped at does, never a red Error.
340
341
  if (last.refused)
341
- return { text: `${last.text}\nThe script stopped at this refused call, and nothing after it ran. Its calls, in order:\n${lines.join("\n")}`, isError: true };
342
+ return { text: `${last.text}\nThe script stopped at this refused call, and nothing after it ran. Its calls, in order:\n${lines.join("\n")}`, isError: true, refused: true };
342
343
  if (!ranNow)
343
344
  return { text: `The script stopped at a call cut off before it reported a result, and nothing after it ran. Its calls, in order:\n${lines.join("\n")}`, isError: true };
344
345
  const head = `The script was stopped (it waited for a person's answer, or the session stopped), and run again only as far as its next call, which ran once: ${last.isError ? "it failed" : "its outcome is below"}. The rest of the script did not run; run what is still needed again.`;
@@ -74,6 +74,13 @@ export declare function bookedSpend(entries: readonly EntryLike[], which: "model
74
74
  * every other decision left out: the ones a vendor charged as a paid call (store-reads/decisions.ts
75
75
  * parallelChargedDecisions), which the run's tools figures count beside its paid tool calls. */
76
76
  export declare function bookedDecisionsOf(entries: readonly EntryLike[], ids: ReadonlySet<string>): BookedSpend;
77
+ /** What one call of a tool booked, over `entries` (every conversation of the run's journal, in log order), by the run's
78
+ * one rule (runCostOf): each request whose record names the call or one nested in it (`call`: `callId`, or
79
+ * `callId/...`), and each request of host work (a side or host call, a paid tool call, a decision) admitted after the
80
+ * call's start (`from`, an index in `entries`) and at or before its end (`to`). The caller holds the window to the one
81
+ * call (runner/workflow-calls.ts). $0 for none; null once one has no known cost, or one a crash cut is counted at its
82
+ * hold (`atMost`: the most it can cost, never what it cost). */
83
+ export declare function callCostOf(entries: readonly EntryLike[], callId: string, from: number, to: number): number | null;
77
84
  /** A cost of charges as a usage row or a run's cost block says it (costsofar/1, cutathold/1), by the kernel's one rule
78
85
  * (costOfParts) over `parts`, its float noise rounded off (floatNoiseOff): `usd` their sum, `upper_bound` when it counts
79
86
  * a cut request at its hold, with `so_far_usd` the charges' own figures alone and `unpriced` how many it counts at their
@@ -169,6 +169,25 @@ export function bookedDecisionsOf(entries, ids) {
169
169
  const kept = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request && typeof named(e) === "string" && named(e).startsWith("decision:") && ids.has(named(e).slice("decision:".length))).map(turnOf));
170
170
  return bookedSpend(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))), "decisions");
171
171
  }
172
+ /** What one call of a tool booked, over `entries` (every conversation of the run's journal, in log order), by the run's
173
+ * one rule (runCostOf): each request whose record names the call or one nested in it (`call`: `callId`, or
174
+ * `callId/...`), and each request of host work (a side or host call, a paid tool call, a decision) admitted after the
175
+ * call's start (`from`, an index in `entries`) and at or before its end (`to`). The caller holds the window to the one
176
+ * call (runner/workflow-calls.ts). $0 for none; null once one has no known cost, or one a crash cut is counted at its
177
+ * hold (`atMost`: the most it can cost, never what it cost). */
178
+ export function callCostOf(entries, callId, from, to) {
179
+ const keyed = sessionConversations(entries);
180
+ const hosted = new Set([keyed.get(TOOL_SESSION), keyed.get(DECISION_SESSION)].filter((one) => one !== undefined));
181
+ const ours = (e, at) => {
182
+ const d = (e.data ?? {});
183
+ if (typeof d.call === "string" && (d.call === callId || d.call.startsWith(`${callId}/`)))
184
+ return true;
185
+ return at > from && at <= to && (typeof d.host === "string" || d.side === true || hosted.has(Number(e.conversationId)));
186
+ };
187
+ const kept = new Set(entries.flatMap((e, at) => (e.kind === RUNNER_RECORDS.request && ours(e, at) ? [turnOf(e)] : [])));
188
+ const cost = runCostOf(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))));
189
+ return cost.atMost > 0 ? null : cost.usd;
190
+ }
172
191
  /** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
173
192
  * decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
174
193
  const floatNoiseOff = (usd) => Math.round(usd * 1e12) / 1e12;
@@ -146,16 +146,19 @@ export declare function routeOf(model: string | PinnedModel | undefined, env?: N
146
146
  * as one the model proxy sends there does; a request to any other provider carries none. */
147
147
  export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch, env?: NodeJS.ProcessEnv): typeof fetch;
148
148
  /** `route` (a translated route's fetch, which streams every answer, as pi-ai asks) for any Messages client on the wire it
149
- * translates onto, which asks two things pi-ai never does. Its token count (POST /v1/messages/count_tokens, free, asked
150
- * beside its turns) is answered here and never run on the model, which has no count of its own: the body's bytes over
151
- * four (COUNT_BYTES_PER_TOKEN), a bound for its context, not a price. A request with no `stream: true` (a side request)
152
- * gets its answer whole, one JSON message as Messages writes it, joined from the stream (wholeOf). A tool_choice that
153
- * forces a call is refused with a 400 before the model is asked (forcedChoice). */
149
+ * translates onto, which asks things pi-ai never does. It takes POST /v1/messages and POST /v1/messages/count_tokens
150
+ * alone; anything else is a 404, never run as a chat. Its token count (free, asked beside its turns) is answered here
151
+ * and never run on the model, which has no count of its own: the body's bytes over four (COUNT_BYTES_PER_TOKEN), a
152
+ * bound for its context, not a price. A request with no `stream: true` (a side request) gets its answer whole, one JSON
153
+ * message as Messages writes it, joined from the stream (wholeOf). Its output schema (output_config.format) is the
154
+ * model's format (outputSchema). What the model here cannot keep is refused with a 400 before it is asked: a tool_choice
155
+ * that forces a call (forcedChoice), an output schema beside tools. */
154
156
  export declare function forMessagesClients(route: typeof fetch): typeof fetch;
155
157
  /** The route's translation onto each wire it translates a model onto (wires.ts TRANSLATED), by wire: what a harness's
156
158
  * proxy on that wire forwards with for `model` (`provider/model-id`), made on `env`. Anthropic's Messages: the route's
157
- * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). provider.ts routedProvider reads
158
- * it; a wire with no entry has no translation, whatever TRANSLATED says. */
159
+ * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). OpenAI's Responses: that same
160
+ * fetch under a Responses edge (responsesFetch). provider.ts routedProvider reads it; a wire with no entry has no
161
+ * translation, whatever TRANSLATED says. */
159
162
  export declare const TRANSLATORS: Readonly<Partial<Record<Wire, (model: string, env: NodeJS.ProcessEnv) => Promise<typeof fetch>>>>;
160
163
  /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
161
164
  * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
@@ -20,6 +20,7 @@ import { chooseModel, FAUX_PROVIDER, MODEL_PROVIDER, runModels } from "../model.
20
20
  import { OLLAMA_PROVIDER } from "../ollama-provider.js";
21
21
  import { gatewayHeadersAt, providerFor } from "../provider.js";
22
22
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
23
+ import { responsesFetch } from "./responses-fetch.js";
23
24
  import { callsOfText, toolsAsText } from "./text-tools.js";
24
25
  /** The wires a caller of routeOf speaks when it names none: Anthropic's Messages alone. */
25
26
  const MESSAGES_ONLY = ["anthropic-messages"];
@@ -123,6 +124,7 @@ function tapped(upstream) {
123
124
  export function messagesFetch(models, target, redact = keepText, upstream, env = process.env) {
124
125
  const attribution = piOnOpenRouter(target) ? openRouterAttribution(env) : {};
125
126
  const particle = target.provider === "particle";
127
+ const ollama = target.provider === OLLAMA_PROVIDER;
126
128
  // Side requests without a Pi session id retain affinity for this route's lifetime.
127
129
  const cacheSession = particle ? randomUUID() : undefined;
128
130
  // A tool call's id as Messages carries it (letters, digits, _ and -), and back to the provider's own on its result.
@@ -146,7 +148,7 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
146
148
  // Particle's cache affinity: the session's id (the Messages hop's metadata.user_id), else this route's own; an
147
149
  // empty id is a caller that asked for no cache hint.
148
150
  const affinity = !particle ? {} : body.metadata?.user_id === "" ? { cacheRetention: "none" } : { sessionId: body.metadata?.user_id || cacheSession };
149
- const streamOptions = { ...affinity, ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
151
+ const streamOptions = { ...affinity, ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(ollama && init.edgeAsks ? ollamaAsks(init.edgeAsks) : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
150
152
  const events = models.streamSimple(target, context, streamOptions);
151
153
  const encoder = new TextEncoder();
152
154
  const stream = new ReadableStream({
@@ -397,8 +399,40 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
397
399
  }
398
400
  /** The bytes of a request a token count answers per token (forMessagesClients' count_tokens). */
399
401
  const COUNT_BYTES_PER_TOKEN = 4;
400
- /** Whether a request asks Messages' token count (its path's last segment, any query after it). */
401
- const countsTokens = (url) => /\/count_tokens(?:\?|$)/.test(String(url));
402
+ /** The two requests a Messages client sends the route: its turns and its token count, each a POST. */
403
+ const MESSAGES_PATH = "/v1/messages";
404
+ const COUNT_PATH = "/v1/messages/count_tokens";
405
+ /** The method and path of a request as a fetch is handed it (a URL's string, a URL, a Request). */
406
+ function requestLine(url, init) {
407
+ const href = typeof url === "string" ? url : url instanceof URL ? url.href : url.url;
408
+ let path = "";
409
+ try {
410
+ path = new URL(href).pathname;
411
+ }
412
+ catch {
413
+ // Not a URL: no path, so a 404.
414
+ }
415
+ const method = init.method ?? (typeof url === "object" && !(url instanceof URL) ? url.method : "GET");
416
+ return { method: method.toUpperCase(), path };
417
+ }
418
+ /** The JSON schema a Messages `output_config.format` holds the answer to, Ollama's `format` (asked on the in-process
419
+ * call, EdgeAsks, so the body is sent as it is); none when it asks none. Ollama holds the whole answer to it, which
420
+ * leaves the model no way to call a tool, so beside tools it is refused, as is any shape but json_schema with a schema
421
+ * object, in the words of the Responses edge's own refusal (responses-fetch.ts schemaOf): never dropped. */
422
+ function outputSchema(config, tools) {
423
+ const format = typeof config === "object" && config !== null ? config.format : undefined;
424
+ if (format === undefined || format === null)
425
+ return {};
426
+ const plain = typeof format === "object" && !Array.isArray(format) ? format : undefined;
427
+ if (plain?.type !== "json_schema")
428
+ return { refused: `output_config.format ${JSON.stringify(plain ? (plain.type ?? "(no type)") : format)} is not taken on this model's route: "json_schema" only` };
429
+ const schema = plain.schema;
430
+ if (typeof schema !== "object" || schema === null || Array.isArray(schema))
431
+ return { refused: "output_config.format json_schema with no schema object is not taken on this model's route" };
432
+ if (Array.isArray(tools) && tools.length > 0)
433
+ return { refused: "output_config.format json_schema beside tools is not taken on this model's route: Ollama holds the whole answer to the format, which leaves the model no way to call a tool, so drop the output schema, or use a model route that takes tools with a format" };
434
+ return { schema: schema };
435
+ }
402
436
  /** Why a Messages `tool_choice` that forces a call is refused (its 400's words), else undefined: the model behind the
403
437
  * route (Ollama's chat) takes no tool choice, so a call forced by "any" or by a tool's name cannot be kept. "auto",
404
438
  * "none" and none at all are taken; any other type is refused too. */
@@ -417,15 +451,20 @@ function forcedChoice(choice) {
417
451
  return `tool_choice ${JSON.stringify(type ?? "(no type)")} is not taken on this model's route: "auto" and "none" only`;
418
452
  }
419
453
  /** `route` (a translated route's fetch, which streams every answer, as pi-ai asks) for any Messages client on the wire it
420
- * translates onto, which asks two things pi-ai never does. Its token count (POST /v1/messages/count_tokens, free, asked
421
- * beside its turns) is answered here and never run on the model, which has no count of its own: the body's bytes over
422
- * four (COUNT_BYTES_PER_TOKEN), a bound for its context, not a price. A request with no `stream: true` (a side request)
423
- * gets its answer whole, one JSON message as Messages writes it, joined from the stream (wholeOf). A tool_choice that
424
- * forces a call is refused with a 400 before the model is asked (forcedChoice). */
454
+ * translates onto, which asks things pi-ai never does. It takes POST /v1/messages and POST /v1/messages/count_tokens
455
+ * alone; anything else is a 404, never run as a chat. Its token count (free, asked beside its turns) is answered here
456
+ * and never run on the model, which has no count of its own: the body's bytes over four (COUNT_BYTES_PER_TOKEN), a
457
+ * bound for its context, not a price. A request with no `stream: true` (a side request) gets its answer whole, one JSON
458
+ * message as Messages writes it, joined from the stream (wholeOf). Its output schema (output_config.format) is the
459
+ * model's format (outputSchema). What the model here cannot keep is refused with a 400 before it is asked: a tool_choice
460
+ * that forces a call (forcedChoice), an output schema beside tools. */
425
461
  export function forMessagesClients(route) {
426
462
  return (async (url, init = {}) => {
463
+ const { method, path } = requestLine(url, init);
464
+ if (method !== "POST" || (path !== MESSAGES_PATH && path !== COUNT_PATH))
465
+ return messagesError(`${method} ${path || "(no path)"} is not on this model's route: POST ${MESSAGES_PATH} and ${COUNT_PATH} only`, 404, "not_found_error");
427
466
  const body = String(init.body ?? "");
428
- if (countsTokens(url))
467
+ if (path === COUNT_PATH)
429
468
  return Response.json({ input_tokens: Math.ceil(new TextEncoder().encode(body).length / COUNT_BYTES_PER_TOKEN) });
430
469
  const read = (() => {
431
470
  try {
@@ -435,20 +474,32 @@ export function forMessagesClients(route) {
435
474
  return undefined;
436
475
  }
437
476
  })();
438
- const refused = forcedChoice(read?.tool_choice);
439
- if (refused)
440
- return messagesError(refused, 400, "invalid_request_error");
477
+ const forced = forcedChoice(read?.tool_choice);
478
+ if (forced)
479
+ return messagesError(forced, 400, "invalid_request_error");
480
+ const output = outputSchema(read?.output_config, read?.tools);
481
+ if (output.refused)
482
+ return messagesError(output.refused, 400, "invalid_request_error");
441
483
  const streamed = read === undefined || read.stream === true;
442
- const answer = await route(url, init);
484
+ // The schema rides the in-process call (messagesFetch reads edgeAsks on an Ollama model), never the body.
485
+ const asked = output.schema ? { ...init, edgeAsks: { format: output.schema } } : init;
486
+ const answer = await route(url, asked);
443
487
  return streamed || answer.status !== 200 ? answer : wholeOf(await answer.text());
444
488
  });
445
489
  }
446
490
  /** The route's translation onto each wire it translates a model onto (wires.ts TRANSLATED), by wire: what a harness's
447
491
  * proxy on that wire forwards with for `model` (`provider/model-id`), made on `env`. Anthropic's Messages: the route's
448
- * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). provider.ts routedProvider reads
449
- * it; a wire with no entry has no translation, whatever TRANSLATED says. */
492
+ * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). OpenAI's Responses: that same
493
+ * fetch under a Responses edge (responsesFetch). provider.ts routedProvider reads it; a wire with no entry has no
494
+ * translation, whatever TRANSLATED says. */
450
495
  export const TRANSLATORS = Object.freeze({
451
496
  "anthropic-messages": async (model, env) => forMessagesClients((await routeOf(model, env)).fetch),
497
+ // OpenAI's Responses: the same Messages fetch under a Responses edge (responses-fetch.ts), a model that reasons asked its
498
+ // effort by name as on Messages.
499
+ "openai-responses": async (model, env) => {
500
+ const route = await routeOf(model, env);
501
+ return responsesFetch(route.fetch, { reasons: route.like?.reasoning === true });
502
+ },
452
503
  });
453
504
  /** One Messages answer whole, from the events of its stream (`sse`): the message_start's message, each block joined from
454
505
  * its deltas (a tool call's input parsed from its pieces), the last message_delta's stop and usage over the start's. An
@@ -525,6 +576,19 @@ function levelOf(body) {
525
576
  const effort = body.output_config?.effort;
526
577
  return body.thinking?.type === "adaptive" && NAMED_LEVELS.includes(effort) ? effort : undefined;
527
578
  }
579
+ /** What the Responses edge asks an Ollama model past the Messages body (responses-fetch.ts EdgeAsks, on the in-process
580
+ * call's init, never the body) as pi-ai's options and ollama-provider.ts chatBody read them: the format and think as
581
+ * they are, temperature as pi-ai's own, top_p as its samplingParams. Read on an Ollama model alone. A Messages client's
582
+ * output schema is asked the same way (forMessagesClients, the format alone); its own sampling and thinking fields are
583
+ * not asked. */
584
+ function ollamaAsks(asks) {
585
+ return {
586
+ ...(asks.format ? { format: asks.format } : {}),
587
+ ...(asks.temperature === undefined ? {} : { temperature: asks.temperature }),
588
+ ...(asks.top_p === undefined ? {} : { samplingParams: { top_p: asks.top_p } }),
589
+ ...(asks.think === false ? { think: false } : {}),
590
+ };
591
+ }
528
592
  const textOf = (content) => (typeof content === "string" ? content : (content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n"));
529
593
  /** A Messages block as pi-ai's part: a text as text, a base64 image as an image; anything else none. */
530
594
  const partOf = (block) => block.type === "text" ? [{ type: "text", text: block.text ?? "" }] : block.type === "image" && block.source?.data ? [{ type: "image", data: block.source.data, mimeType: block.source.media_type ?? "image/png" }] : [];
@@ -16,14 +16,14 @@ import { inputMessage } from '../run-manifest.js';
16
16
  import { outputContract, outputMiss, outputRetryWords } from '../answer-json.js';
17
17
  import { cutStrings, redactedOutput } from '../key-refusal.js';
18
18
  import { learningEndOfRun } from './learning-end.js';
19
- import { pathMetrics } from './workflow-first.js';
19
+ import { runPathMetricsOverStore } from '../store-reads/learning.js';
20
20
  import { reflectRequestId } from './end-of-run.js';
21
21
  import { journalEntries } from './journal-reader.js';
22
22
  import { HOST_PHASE } from '../timeline/index.js';
23
23
  import { KINDS } from './journal-kinds.js';
24
24
  import { bookedSpend, cliRunMetrics } from './metrics.js';
25
25
  import { stopEnd } from './loop-contract.js';
26
- import { END_PATCH_MS, END_PATCH_UNKNOWN } from './loop.js';
26
+ import { END_PATCH_MS, END_PATCH_UNKNOWN, REAL_TIMER } from './loop.js';
27
27
  import { storeSecrets } from './store-secrets.js';
28
28
  import { runnerSecrets, heldRedactor, processSecretRedactor } from './redact.js';
29
29
  import { secretRedactor } from './redact.js';
@@ -188,14 +188,17 @@ export function createNativeLoop(launch, host) {
188
188
  const readEndPatch = async (model, runtime, usage) => {
189
189
  if (endPatch !== undefined)
190
190
  return endPatch;
191
+ const bound = host.endPatchTimer ?? REAL_TIMER;
191
192
  let timer;
192
- const late = new Promise(resolve => { timer = setTimeout(() => resolve(END_PATCH_UNKNOWN), END_PATCH_MS); });
193
+ const late = new Promise(resolve => { timer = bound.setTimeout(() => resolve(END_PATCH_UNKNOWN), END_PATCH_MS); });
193
194
  try {
194
195
  // Only reads race the deadline. A late result never writes a patch or changes the chosen end.
195
196
  const read = async () => {
196
197
  const entries = await journalEntries(journal, ctx);
197
198
  const spend = bookedSpend(entries, 'model');
198
- return { costUsd: spend.usd, metrics: { ...nativeMetrics(launch, entries, spend, model, turn, runtime), native_session_id: nativeSessionId, ...(usage ? { native_usage: usage } : {}) } };
199
+ // Its path by the one writer every harness's end calls: a native task never calls a learned workflow, so `agent`.
200
+ const path = await runPathMetricsOverStore(host.store, claim.runId, launch);
201
+ return { costUsd: spend.usd, metrics: { ...nativeMetrics(entries, spend, model, turn, path, runtime), native_session_id: nativeSessionId, ...(usage ? { native_usage: usage } : {}) } };
199
202
  };
200
203
  endPatch = await Promise.race([read(), late]);
201
204
  }
@@ -203,7 +206,7 @@ export function createNativeLoop(launch, host) {
203
206
  endPatch = END_PATCH_UNKNOWN;
204
207
  }
205
208
  finally {
206
- clearTimeout(timer);
209
+ bound.clearTimeout(timer);
207
210
  }
208
211
  return endPatch;
209
212
  };
@@ -337,10 +340,9 @@ function nativeInput(usage, runtime) {
337
340
  return usage.input_tokens;
338
341
  return usage.input_tokens === null || usage.cache_read_tokens === null || usage.cache_write_tokens === null ? null : Math.max(0, usage.input_tokens - usage.cache_read_tokens - usage.cache_write_tokens);
339
342
  }
340
- function nativeMetrics(launch, entries, spend, model, turns, runtime) {
343
+ function nativeMetrics(entries, spend, model, turns, path, runtime) {
341
344
  const counted = cliRunMetrics(entries, spend, { model });
342
345
  const usage = entries.filter(e => e.kind === `${MARK}.usage`).map(e => e.data.usage);
343
346
  const count = (native, key) => usage.length < turns || usage.some(u => u[native] === null) ? null : counted[key];
344
- // Native tasks always run their agent: this lane never serves or calls an AgentRun learned workflow.
345
- return { ...counted, ...pathMetrics(launch, { path: 'agent', workflow: null }, entries), input: usage.some(u => nativeInput(u, runtime) === null) ? null : count('input_tokens', 'input'), output: count('output_tokens', 'output'), cacheRead: count('cache_read_tokens', 'cacheRead'), cacheWrite: count('cache_write_tokens', 'cacheWrite'), requests: null, unmetered: null, models: {}, native_model_requests: null, native_turns: turns };
347
+ return { ...counted, ...path, input: usage.some(u => nativeInput(u, runtime) === null) ? null : count('input_tokens', 'input'), output: count('output_tokens', 'output'), cacheRead: count('cache_read_tokens', 'cacheRead'), cacheWrite: count('cache_write_tokens', 'cacheWrite'), requests: null, unmetered: null, models: {}, native_model_requests: null, native_turns: turns };
346
348
  }
@@ -1,15 +1,12 @@
1
1
  import { type RunnerRow, type Runners } from "../store/store.js";
2
2
  /** How often a runner says again that it is there. */
3
3
  export declare const PRESENCE_RENEW_MS = 10000;
4
- /** How old a runner's word can be and still count: three renewals missed. The store's (RUNNER_STALE_MS), which its claim
5
- * rule reads for a kept computer's pin. */
6
- export declare const PRESENCE_STALE_MS = 30000;
7
4
  /** A runner's row that says where its relay answers. */
8
5
  export type RelayRow = RunnerRow & {
9
6
  readonly host: string;
10
7
  readonly port: number;
11
8
  };
12
- /** The runners whose relay takes dials now: their rows seen within PRESENCE_STALE_MS on the store's clock (Runners.live,
9
+ /** The runners whose relay takes dials now: their rows seen within RUNNER_STALE_MS on the store's clock (Runners.live,
13
10
  * the database's on Postgres), never one process's, that say where their relay answers. The server relays a dial only
14
11
  * to one of these (computer-attach.ts), says a dial provider is served while one answers at a host it dials (server.ts
15
12
  * relayed), and a paired computer's route to a runner not among them is stale (workspace/paired-route.ts). */