@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
@@ -9,12 +9,15 @@
9
9
  // At every claim the pin is checked again: a pinned tool that is a meta tool now refuses the claim in words, nothing sent.
10
10
  //
11
11
  // The credentials. The pinned servers' credentials are unsealed (store/seal.ts openMcpCredential) into this step's
12
- // memory only: handed to the run's gateway, never written to the journal, a command row, the timeline or a log line. The
13
- // redaction set is fed from the same map. Both are dropped at release(), at the loop's end, or when the claim's signal
14
- // aborts. A credential that can't be used gives its server's calls a reason (mcp-probe.ts UNUSABLE) and they are refused
15
- // unsent: sealed under another key or for another origin than its row's url (damaged), a sign-in refused or expired
16
- // (signedOut), a refresh that got no answer (silent), an address the check refuses (blocked). A runner never starts
17
- // without the seal key (seal-key.ts bootSealKey), so a claim always has one.
12
+ // memory only: handed to the run's gateway, never written to the journal, a command row, the timeline or a log line.
13
+ // Every value handed over (a header's, a bearer's token alone, an access token refreshed mid-claim, a github_app token
14
+ // minted or minted again) is held by the run's redactors (`hold`) at that moment, through the one place an entry is
15
+ // made, so a log line or error text the run writes is cut of it as the gateway's own scrub cuts a call's answer. The
16
+ // entries are dropped at release(), at the loop's end, or when the claim's signal aborts. A credential that can't be
17
+ // used gives its server's calls a reason (mcp-probe.ts UNUSABLE) and they are refused unsent: sealed under another key
18
+ // or for another origin than its row's url (damaged), a sign-in refused or expired (signedOut), a refresh that got no
19
+ // answer (silent), an address the check refuses (blocked). A runner never starts without the seal key
20
+ // (seal-key.ts bootSealKey), so a claim always has one.
18
21
  //
19
22
  // A per_run server keeps no credential: the run's caller hands one with the run or a message (mcp_auth), sealed in the
20
23
  // run's launch row for the run's life (store/seal.ts sealRunMcpAuth) and erased by the write that ends it. Each fresh()
@@ -35,11 +38,18 @@
35
38
  // authorization server may already have spent the old refresh token. A token still valid but near its expiry is
36
39
  // used at once and refreshed behind it, never holding the claim. After any awaited refresh the claim's epoch is
37
40
  // confirmed again: a claim lost meanwhile is Fenced, and the loop never starts.
41
+ //
42
+ // check(). Before each call leaves (the gateway's `before`), the server's row stamp is read (store.mcp.stamp: its url,
43
+ // auth, credential_changed_at and its token's end by the store's clock; no tools, no sealed bytes): a server removed
44
+ // since loses its entry, so the call is refused unsent; a credential replaced or a server moved since is opened again, so
45
+ // the next call sends the new one (or is refused for the move); and an OAuth access token within REFRESH_MARGIN_MS of its
46
+ // end is refreshed through open's lease path: behind the call while the token is still valid (the call goes at once on
47
+ // it), waited on only when it has run out. Concurrent calls to one server share one such open.
38
48
  import { randomUUID } from "node:crypto";
39
49
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
40
50
  import { mcpPinOf } from "../mcp-gateway.js";
41
51
  import { META_REASON, metaToolOf } from "../mcp-meta.js";
42
- import { boundTool } from "../mcp-probe.js";
52
+ import { boundTool, credentialInQuery, credentialInQueryWords, shownUrl } from "../mcp-probe.js";
43
53
  import { privateOAuthHosts } from "../mcp-private-hosts.js";
44
54
  import { GITHUB_MCP_ONLY, GITHUB_MCP_ORIGIN, githubMcpUrl } from "../github.js";
45
55
  import { githubTokens } from "./mcp-github.js";
@@ -48,6 +58,9 @@ import { REFRESH_MARGIN_MS, UNKNOWN_EXPIRY_MS, UNUSABLE } from "../mcp-probe.js"
48
58
  import { tokenLeftOf } from "../mcp-probe.js";
49
59
  import { openMcpCredential, openRunMcpAuth, sealMcpCredential } from "../store/seal.js";
50
60
  import { Fenced, MCP_REFRESH_CALL_MS } from "../store/index.js";
61
+ /** Every credential value of `headers`: each header's value, and its token alone with any one-word scheme taken off
62
+ * (`Bearer `), which a server may echo bare (as the gateway's scrub cuts them). */
63
+ const credentialValues = (headers) => Object.values(headers).flatMap((value) => [value, value.replace(/^[A-Za-z][A-Za-z0-9_-]*\s+(?=\S+$)/, "")]);
51
64
  /** Whether two sealed credentials are the same bytes (none equals none). */
52
65
  const sameSealed = (a, b) => (a === null || b === null ? a === b : Buffer.from(a).equals(Buffer.from(b)));
53
66
  /** A claim the MCP step refused, in the words a person reads: nothing was sent. */
@@ -70,10 +83,18 @@ export async function mcpClaim(options) {
70
83
  const holder = `${claim.runId}@${claim.epoch}:${randomUUID()}`;
71
84
  const pin = await pinOf(options);
72
85
  const credentials = Object.create(null);
73
- const secrets = new Set();
74
86
  // Refreshes started behind a token still valid: stopped at release.
75
87
  const behind = new AbortController();
76
88
  let released = false;
89
+ /** What each pinned server's entry was opened from (its row's url, auth and credential time, and an OAuth token's end
90
+ * on this claim's clock), which check() compares the row's stamp with. */
91
+ const stamps = new Map();
92
+ /** The servers check() found removed: nothing (a github_app token's refresh among it) puts their entry back. */
93
+ const gone = new Set();
94
+ /** The opens check() started, by server: concurrent calls share one. */
95
+ const reopening = new Map();
96
+ // Servers whose refresh behind a still-valid token is going: one at a time per server from this claim.
97
+ const behindGoing = new Set();
77
98
  // A github_app server's installation token: minted at each claim, refreshed mid-run, held here only.
78
99
  const github = githubTokens(options.githubApp, { now, ...(options.githubTimer ? { arm: options.githubTimer } : {}) });
79
100
  const release = () => {
@@ -82,7 +103,6 @@ export async function mcpClaim(options) {
82
103
  github.release();
83
104
  for (const name of Object.keys(credentials))
84
105
  delete credentials[name];
85
- secrets.clear();
86
106
  };
87
107
  signal.addEventListener("abort", release, { once: true });
88
108
  /** The OAuth token set refreshed at its authorization server, bounded: the new set, or why not. One request is sent per
@@ -95,7 +115,7 @@ export async function mcpClaim(options) {
95
115
  if (!set.tokens.refresh_token)
96
116
  return { refused: true };
97
117
  const call = AbortSignal.timeout(callMs);
98
- const reach = { allowed: await privateOAuthHosts(store) };
118
+ const reach = { allowed: await privateOAuthHosts(store), loopback: options.loopback === true };
99
119
  for (let tried = 0; tried < tries && !call.aborted; tried++) {
100
120
  // Every try before this one provably never left: nothing is spent.
101
121
  if (stop.aborted)
@@ -154,22 +174,27 @@ export async function mcpClaim(options) {
154
174
  return kept;
155
175
  };
156
176
  /** One pinned server's credential, opened, refreshed when due (awaited for an expired token; behind it for one near
157
- * its expiry). `again`: a row another claim's refresh left, opened as it is, never refreshed from here once more. */
177
+ * its expiry, at the claim and before a call alike). `again`: a row another claim's refresh left,
178
+ * opened as it is, never refreshed from here once more. */
158
179
  const open = async (name, pinnedUrl, again) => {
159
180
  const row = again ?? (await store.mcp.server(name));
160
181
  // Forgotten since the pin: its entry goes (an earlier open's URL and headers with it), so the gateway finds no URL
161
182
  // for it and refuses its calls unsent.
162
183
  if (!row) {
184
+ stamps.delete(name);
163
185
  delete credentials[name];
164
186
  return { awaited: false };
165
187
  }
188
+ gone.delete(name);
189
+ stamps.set(name, { url: row.url, auth: row.auth, changedAt: row.credentialChangedAt });
166
190
  const entry = (extra) => {
167
- if (released)
191
+ // Held by the run's redactor before anything else: a value opened is a value to cut, sent or not.
192
+ if (extra.headers)
193
+ options.hold?.(credentialValues(extra.headers));
194
+ if (released || gone.has(name))
168
195
  return;
169
196
  // Headers go only to the URL the run was pinned to: a server moved since is refused per call by the gateway.
170
197
  credentials[name] = { url: row.url, ...(extra.unopened ? { unopened: extra.unopened } : extra.headers && row.url === pinnedUrl ? { headers: extra.headers } : {}) };
171
- for (const value of Object.values(extra.headers ?? {}))
172
- secrets.add(value);
173
198
  };
174
199
  // A GitHub App's server keeps no credential: its token is minted for this run (awaited, so the claim is confirmed
175
200
  // after it), kept fresh mid-run, and never stored.
@@ -200,6 +225,22 @@ export async function mcpClaim(options) {
200
225
  const readAt = now();
201
226
  const end = set.expires_at ? Date.parse(set.expires_at) : Date.parse(set.obtained_at) + UNKNOWN_EXPIRY_MS;
202
227
  const left = () => (row.tokenLeftMs === null ? end - now() : row.tokenLeftMs - (now() - readAt));
228
+ // The token's end as the store stamped it, for the per-call check: another claim's refresh moves it (stamp.tokenUntil).
229
+ // Read with the sealed set in the one row (never a second query): a refresh between two reads would pair the old token
230
+ // with the new token's end, and the old one would be sent past its expiry.
231
+ const until = row.tokenUntil;
232
+ stamps.set(name, { url: row.url, auth: row.auth, changedAt: row.credentialChangedAt, end: readAt + left(), until });
233
+ /** The refresh's outcome, put only while the server's stamp is still the credential this open read: a later open
234
+ * that read another one (the owner signed in again or replaced it, another claim's refresh moved its token) set the
235
+ * entry from that row, and a refresh of the old one that ends after it (failed past the old token's end, say) never
236
+ * writes over it. A later open of the same credential (a fresh(), a call's check) leaves it this refresh's to put. */
237
+ const settledEntry = (extra) => {
238
+ const now_ = stamps.get(name);
239
+ if (now_ && now_.url === row.url && now_.auth === row.auth && now_.changedAt === row.credentialChangedAt && now_.until === until)
240
+ entry(extra);
241
+ else if (extra.headers)
242
+ options.hold?.(credentialValues(extra.headers));
243
+ };
203
244
  if (left() > REFRESH_MARGIN_MS)
204
245
  return entry({ headers: bearer(set) }), { awaited: false };
205
246
  // Another claim's refresh left this row and it is still due: never refreshed from here once more.
@@ -249,7 +290,7 @@ export async function mcpClaim(options) {
249
290
  if ("blocked" in got) {
250
291
  await store.mcp.releaseRefresh(name, holder).catch(() => undefined);
251
292
  if (left() <= 0)
252
- entry({ unopened: `${UNUSABLE.blocked}: ${got.blocked}` });
293
+ settledEntry({ unopened: `${UNUSABLE.blocked}: ${got.blocked}` });
253
294
  return;
254
295
  }
255
296
  if ("set" in got) {
@@ -257,7 +298,7 @@ export async function mcpClaim(options) {
257
298
  // spent the old refresh token, so the new set is the only one any claim can use. The write is the server's row,
258
299
  // not the run's; entry() hands it to this step only while it is held.
259
300
  if (await keep(lease.row, { type: "oauth", set: got.set }))
260
- return entry({ headers: bearer(got.set) });
301
+ return settledEntry({ headers: bearer(got.set) });
261
302
  if (stop.aborted || released)
262
303
  return;
263
304
  // The credential changed while it refreshed (a newer set, an owner's save): use the row as it is now.
@@ -268,7 +309,7 @@ export async function mcpClaim(options) {
268
309
  // The sign-in is over: kept as expired, so no later claim tries the refresh token again. A credential changed
269
310
  // meanwhile is the one to use.
270
311
  if (await keep(lease.row, { ...oauth, expired: true }))
271
- return entry({ unopened: UNUSABLE.signedOut });
312
+ return settledEntry({ unopened: UNUSABLE.signedOut });
272
313
  if (stop.aborted || released)
273
314
  return;
274
315
  return void (await takeLeft(await store.mcp.server(name)));
@@ -280,7 +321,7 @@ export async function mcpClaim(options) {
280
321
  if (!("held" in got))
281
322
  await store.mcp.releaseRefresh(name, holder).catch(() => undefined);
282
323
  if (left() <= 0)
283
- entry({ unopened: UNUSABLE.silent });
324
+ settledEntry({ unopened: UNUSABLE.silent });
284
325
  }
285
326
  finally {
286
327
  // The lease is let go (kept, released, or left to lapse on a failed write): the claims waiting on it read the row.
@@ -288,11 +329,16 @@ export async function mcpClaim(options) {
288
329
  }
289
330
  };
290
331
  if (left() > 0) {
291
- // Still valid: used at once, refreshed behind it.
332
+ // Still valid: used at once, refreshed behind it (one at a time per server from this claim: a call that finds one
333
+ // going starts none), so an authorization server that is slow or down never holds a call whose token still works.
292
334
  entry({ headers: bearer(set) });
293
- void settle(AbortSignal.any([signal, behind.signal])).catch(() => undefined);
335
+ if (!behindGoing.has(name)) {
336
+ behindGoing.add(name);
337
+ void settle(AbortSignal.any([signal, behind.signal])).catch(() => undefined).finally(() => behindGoing.delete(name));
338
+ }
294
339
  return { awaited: false };
295
340
  }
341
+ // Run out: the refresh is waited on, bounded by its call's deadline.
296
342
  await settle(signal);
297
343
  return { awaited: true };
298
344
  };
@@ -310,8 +356,6 @@ export async function mcpClaim(options) {
310
356
  return { unopened: UNUSABLE.perRunMissing };
311
357
  if (given.origin !== new URL(url).origin)
312
358
  return { unopened: UNUSABLE.damaged };
313
- const values = Object.values(given.headers).flatMap((value) => [value, ...(/^Bearer\s+(.+)$/i.exec(value)?.slice(1) ?? [])]);
314
- options.hold?.(values);
315
359
  return { headers: { ...given.headers } };
316
360
  };
317
361
  const fresh = async () => {
@@ -326,21 +370,66 @@ export async function mcpClaim(options) {
326
370
  if (awaited)
327
371
  await confirm(store, claim);
328
372
  };
373
+ const check = async (name) => {
374
+ if (!pin || released || !Object.hasOwn(pin, name))
375
+ return;
376
+ const stamp = await store.mcp.stamp(name);
377
+ if (released)
378
+ return;
379
+ if (!stamp) {
380
+ // Removed since: its entry goes, so its calls are refused unsent; nothing puts it back.
381
+ gone.add(name);
382
+ stamps.delete(name);
383
+ delete credentials[name];
384
+ return;
385
+ }
386
+ const was = stamps.get(name);
387
+ const changed = !was || gone.has(name) || was.url !== stamp.url || was.auth !== stamp.auth || was.changedAt !== stamp.credentialChangedAt;
388
+ // The token's end by the store's clock (tokenLeftMs), else as this claim opened it.
389
+ const left = stamp.tokenLeftMs ?? (was?.end !== undefined ? was.end - now() : null);
390
+ // And whether the row still holds the token this claim opened: another claim's refresh moves the row's token end (not
391
+ // its credential's change time), so the row has a fresh token while this claim holds the one about to expire.
392
+ const moved = stamp.auth === "oauth" && was?.until !== undefined && stamp.tokenUntil !== was.until;
393
+ // An entry that did not open (a refresh that failed or never answered, a sign-in that expired) is read again only when
394
+ // the row changed (the owner signed in again or replaced it) or another claim moved its token: never refreshed once
395
+ // more on its own, since a refresh that left may already have spent the refresh token.
396
+ const unopened = credentials[name]?.unopened !== undefined;
397
+ const due = moved || (!unopened && stamp.auth === "oauth" && left !== null && left <= REFRESH_MARGIN_MS);
398
+ if (!changed && !due)
399
+ return;
400
+ let going = reopening.get(name);
401
+ if (!going) {
402
+ going = open(name, pin[name].url).finally(() => reopening.delete(name));
403
+ reopening.set(name, going);
404
+ }
405
+ await going;
406
+ };
329
407
  await fresh();
408
+ // Before each call (the gateway's beforeCall; a throw refuses the call unsent): the server's
409
+ // row stamp first (removed: dropped and refused; changed: opened again; an access token near its end: refreshed under
410
+ // the lease, behind the call while still valid, waited on once run out), then a github_app token's App (disconnected or replaced since the mint: dropped and refused).
330
411
  const beforeCall = async (server, signal) => {
331
412
  signal.throwIfAborted();
413
+ if (released)
414
+ return;
415
+ await check(server);
332
416
  if (!released)
333
417
  await github.check(server);
334
418
  };
335
- return { pin, credentials, secrets, fresh, release, beforeCall };
419
+ return { pin, credentials, fresh, release, beforeCall };
336
420
  }
337
421
  /** The run's pin: read, and checked against the meta tools known now; or made at its first claim and written once. */
338
422
  async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN }) {
339
423
  // A github_app server anywhere but GitHub's hosted MCP ends the run here, before any token is minted or anything sent:
340
424
  // the App's tokens go to GitHub alone (github.ts githubMcpUrl, the one check).
341
425
  const offGithub = (server, url, auth) => {
426
+ // A URL with a credential in its query (a row saved before the save refused one) ends the run before it is pinned or
427
+ // anything sent; the URL is never named, its credential with it.
428
+ const inQuery = credentialInQuery(url);
429
+ if (inQuery)
430
+ throw new McpClaimRefused(`The MCP server ${server} can't be used: ${credentialInQueryWords(inQuery)} Nothing was sent.`);
342
431
  if (auth === "github_app" && !githubMcpUrl(url, githubMcpOrigin))
343
- throw new McpClaimRefused(`The MCP server ${server} (${url}) can't be used: ${GITHUB_MCP_ONLY}. Nothing was sent.`);
432
+ throw new McpClaimRefused(`The MCP server ${server} (${shownUrl(url)}) can't be used: ${GITHUB_MCP_ONLY}. Nothing was sent.`);
344
433
  };
345
434
  const stored = await store.mcp.pin(claim.runId);
346
435
  if (stored) {
@@ -3,7 +3,7 @@ export const REFRESH_BEFORE_MS = 5 * 60_000;
3
3
  /** Why a github_app server's calls are refused unsent, in the words the gateway gives the model. */
4
4
  export const GITHUB_UNUSABLE = {
5
5
  noAccess: "this server has no GitHub App set up for its runs (Settings → GitHub)",
6
- noRepo: "this run names no GitHub repository, so the GitHub App has no repository to make a token for",
6
+ noRepo: "this run names no GitHub repository, so the GitHub App has no repository to make a token for. The server is connected: start the run with a repository (`repo` in the start body, or https://github.com/<owner>/<repo> in its first message), or bind the agent to one repository with a GitHub trigger",
7
7
  notInstalled: (repo) => `the GitHub App is not installed on ${repo}: install it from Settings → GitHub`,
8
8
  failed: (message) => `GitHub did not make a token for this run (${message})`,
9
9
  expired: (message) => `its GitHub App token expired and a new one could not be made (${message})`,
@@ -1,7 +1,7 @@
1
1
  import type { HostTool, SessionMcp } from "@parcha/agentrun-kernel";
2
2
  import type { Harness } from "@earendil-works/pi-durable";
3
3
  import { type McpGatewayOptions } from "../mcp-gateway.js";
4
- import type { OAuthNetwork } from "../mcp-oauth.js";
4
+ import { type OAuthNetwork } from "../mcp-oauth.js";
5
5
  import type { Store, TriggerSettings } from "../store/index.js";
6
6
  import { type ApprovalPrice } from "../tool-gate.js";
7
7
  import { type AnswerData } from "./journal-kinds.js";
@@ -35,6 +35,9 @@ export interface McpForClaimOptions {
35
35
  /** A test's fake GitHub MCP origin, handed to the claim step (mcpClaim's githubMcpOrigin): for tests only: no environment variable, flag or setting maps onto it; absent, GitHub's hosted MCP
36
36
  * (github.ts GITHUB_MCP_ORIGIN). */
37
37
  readonly githubMcpOrigin?: string;
38
+ /** Whether this runner may reach an MCP server whose URL is on loopback (AdapterSpecDeps.mcpLoopback): only a runner
39
+ * beside a local-install server is. Absent, never. */
40
+ readonly loopback?: boolean;
38
41
  /** For tests: the authorization servers' network, a refresh's bound, the gateway's upstream fetch and bounds, and the
39
42
  * timer a github_app token's refresh is armed on. */
40
43
  readonly network?: OAuthNetwork;
@@ -48,7 +51,7 @@ export interface McpForClaimOptions {
48
51
  connectMs?: number;
49
52
  };
50
53
  readonly githubTimer?: GithubTimer;
51
- /** Each credential value the claim opens for a per_run server, for the run's redactors (mcp-claim.ts `hold`). */
54
+ /** Each credential value the claim opens, refreshes or mints, for the run's redactors (mcp-claim.ts `hold`). */
52
55
  readonly hold?: (values: string[]) => void;
53
56
  }
54
57
  /** A call as the loop's gate is asked about it: the tool by its catalog name. */
@@ -77,9 +80,6 @@ export interface ClaimMcp {
77
80
  * sent; or parked, answered the gate's waiting words marked parked, nothing sent), then its host tool from `wrapped`,
78
81
  * as the loop wrapped it. */
79
82
  session(wrapped: ReadonlyMap<string, HostTool>, gate: (call: McpGateCall) => Promise<McpGateAnswer>): SessionMcp;
80
- /** The credential values the gateway's calls in flight hold, for a redaction: each call's for as long as it is out,
81
- * with any token refreshed while it was; none when idle. */
82
- redactions(): string[];
83
83
  /** The claim step's credentials opened again on the same pin (an expired OAuth token refreshed), then the claim
84
84
  * confirmed: before a resumed loop's next model request. */
85
85
  fresh(): Promise<void>;
@@ -1,7 +1,9 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { wireName } from "../catalog.js";
3
3
  import { mcpGateway, noCallId } from "../mcp-gateway.js";
4
- import { argsPreview, mcpToolName, resumeText, RESUME_PREFIX, waitingText } from "../tool-gate.js";
4
+ import { dialAt, mcpServerAt, systemNetwork } from "../mcp-oauth.js";
5
+ import { privateOAuthHosts } from "../mcp-private-hosts.js";
6
+ import { argsPreview, mcpToolName, RESUME_GO_ON, resumeText, RESUME_PREFIX, waitingText } from "../tool-gate.js";
5
7
  import { deniedText } from "./loop-contract.js";
6
8
  import { STOPPED_WHILE_WAITING } from "../refusal-words.js";
7
9
  import { endedAnswer, KINDS } from "./journal-kinds.js";
@@ -26,6 +28,7 @@ export async function mcpForClaim(options) {
26
28
  signal: held.signal,
27
29
  ...(options.bounds ? { bounds: options.bounds } : {}),
28
30
  ...(options.network ? { network: options.network } : {}),
31
+ ...(options.loopback ? { loopback: true } : {}),
29
32
  ...(githubApp ? { githubApp } : {}),
30
33
  ...(options.githubMcpOrigin ? { githubMcpOrigin: options.githubMcpOrigin } : {}),
31
34
  ...(options.githubTimer ? { githubTimer: options.githubTimer } : {}),
@@ -41,9 +44,19 @@ export async function mcpForClaim(options) {
41
44
  held.abort();
42
45
  return undefined;
43
46
  }
47
+ const network = options.network ?? systemNetwork;
44
48
  const gateway = mcpGateway({
45
49
  pin,
46
50
  credentials: step.credentials,
51
+ // Each request's address checked as the server checks it at a save (mcp-oauth.ts mcpServerAt), with the owner's
52
+ // private-network hosts read now, and dialled at the address checked: a name that resolves somewhere private since the
53
+ // save, or a host the owner no longer allows, is refused unsent. A URL on loopback is reached only by a runner told
54
+ // so by the local-install server beside it, in its own process (options.loopback): never by what a store says, so
55
+ // one host's local install never opens loopback for another host's runner on a shared store.
56
+ reach: async (url, signal) => {
57
+ const at = await mcpServerAt(new URL(url), signal, network, { allowed: await privateOAuthHosts(options.store), loopback: options.loopback === true });
58
+ return "refused" in at ? { refused: at.refused } : { send: dialAt(network, at.address, options.fetch ?? fetch) };
59
+ },
47
60
  beforeCall: step.beforeCall,
48
61
  work: options.work,
49
62
  commit: () => (change) => options.harness.commit(change, BACKGROUND_CONTEXT),
@@ -101,7 +114,6 @@ export async function mcpForClaim(options) {
101
114
  return said(result.text, result.isError === true);
102
115
  },
103
116
  }),
104
- redactions: () => gateway.heldValues(),
105
117
  fresh: () => step.fresh(),
106
118
  release: () => held.abort(),
107
119
  };
@@ -160,5 +172,5 @@ export async function parkedFollowUp(mcp, options) {
160
172
  texts.push(resumeText({ tool: call.tool, call_id: call.callId }, argsPreview(call.args), answer.approved ? "allow" : "deny", { text: result.text, isError: result.isError === true }));
161
173
  callIds.push(call.callId);
162
174
  }
163
- return texts.length ? { text: texts.join("\n\n"), callIds } : undefined;
175
+ return texts.length ? { text: `${texts.join("\n\n")}\n\n${RESUME_GO_ON}`, callIds } : undefined;
164
176
  }
@@ -25,8 +25,17 @@ export type BookedSpend = {
25
25
  * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
26
26
  * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
27
27
  * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
28
- * booking's. */
29
- export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions"): BookedSpend;
28
+ * booking's. `side`: of the model requests, those booked as side calls (another model than the session's, or the host's
29
+ * own, as a learned workflow's node is: the proxy's `side`/`host`), which no answer of a pi run carries. */
30
+ export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions" | "side"): BookedSpend;
31
+ /** An agent run's cost as its end commit stores it: its model requests' (`model`), its paid tool calls' (`paid`, the
32
+ * run's ledger.paid) and its decisions' (`decisions`, a learned workflow's decision nodes, LS-07: bookedSpend over
33
+ * their own session's records, so one that reported no cost is unknown, never the cap's hold for it), summed; null (unknown) when any of them is. Never a known figure that leaves an unknown part out. */
34
+ export declare function runEndCost(parts: {
35
+ readonly model: number | null;
36
+ readonly paid: number | null;
37
+ readonly decisions: number | null;
38
+ }): number | null;
30
39
  /** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
31
40
  * its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
32
41
  * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
@@ -32,14 +32,18 @@ function sessionConversations(entries) {
32
32
  * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
33
33
  * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
34
34
  * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
35
- * booking's. */
35
+ * booking's. `side`: of the model requests, those booked as side calls (another model than the session's, or the host's
36
+ * own, as a learned workflow's node is: the proxy's `side`/`host`), which no answer of a pi run carries. */
36
37
  export function bookedSpend(entries, which) {
37
38
  const keyed = sessionConversations(entries);
38
39
  const paidConv = keyed.get(TOOL_SESSION);
39
40
  const decisionsConv = keyed.get(DECISION_SESSION);
40
41
  const conv = (e) => Number(e.conversationId);
41
- const chosen = (e) => (which === "paid" ? conv(e) === paidConv : which === "decisions" ? conv(e) === decisionsConv : conv(e) !== paidConv && conv(e) !== decisionsConv);
42
42
  const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
43
+ const model = (e) => conv(e) !== paidConv && conv(e) !== decisionsConv;
44
+ // The side calls among the model requests: each request that says so, by its conversation and turn.
45
+ const sides = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request && model(e) && (e.data?.side === true || typeof e.data?.host === "string")).map(turnOf));
46
+ const chosen = (e) => (which === "paid" ? conv(e) === paidConv : which === "decisions" ? conv(e) === decisionsConv : which === "side" ? model(e) && sides.has(turnOf(e)) : model(e));
43
47
  const answered = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.turn && chosen(e)).map(turnOf));
44
48
  // The model each request was sent on, by its turn (its runner.request's `model`).
45
49
  const sentOn = new Map(entries.filter((e) => e.kind === RUNNER_RECORDS.request && chosen(e)).map((e) => [turnOf(e), e.data?.model]));
@@ -86,6 +90,12 @@ export function bookedSpend(entries, which) {
86
90
  }
87
91
  return { usd: unpriced ? null : known, known, unpriced, requests, unmetered, models, tokens };
88
92
  }
93
+ /** An agent run's cost as its end commit stores it: its model requests' (`model`), its paid tool calls' (`paid`, the
94
+ * run's ledger.paid) and its decisions' (`decisions`, a learned workflow's decision nodes, LS-07: bookedSpend over
95
+ * their own session's records, so one that reported no cost is unknown, never the cap's hold for it), summed; null (unknown) when any of them is. Never a known figure that leaves an unknown part out. */
96
+ export function runEndCost(parts) {
97
+ return parts.model === null || parts.paid === null || parts.decisions === null ? null : parts.model + parts.paid + parts.decisions;
98
+ }
89
99
  /** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
90
100
  * its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
91
101
  * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
@@ -48,6 +48,7 @@ export declare function prCheckout(options: PrCheckoutOptions): Promise<PrChecko
48
48
  * moment the fetch starts, and `signal` (the claim's, a person's stop included) ending the fetch. */
49
49
  export declare function prCheckoutForClaim(deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "githubApi" | "githubWeb">, workspace: Workspace, launch: {
50
50
  readonly input: unknown;
51
+ readonly repo?: string | undefined;
51
52
  readonly inputOrigin?: {
52
53
  readonly kind: string;
53
54
  readonly source?: string;
@@ -171,6 +171,6 @@ function checkoutNote(pull, mergeBase) {
171
171
  * moment the fetch starts, and `signal` (the claim's, a person's stop included) ending the fetch. */
172
172
  export async function prCheckoutForClaim(deps, workspace, launch, redact, signal, held) {
173
173
  const fromGitHub = launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github";
174
- const access = await githubAppAccess(deps.store, deps.sealKey, launch.input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub, hold: (values) => redact.hold(values) });
174
+ const access = await githubAppAccess(deps.store, deps.sealKey, launch.input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub, hold: (values) => redact.hold(values), ...(launch.repo !== undefined ? { repo: launch.repo } : {}) });
175
175
  return prCheckout({ workspace, input: launch.input, fromGitHub, ...(access ? { mint: access.mint } : {}), ...(access?.revoke ? { revoke: access.revoke } : {}), hold: (secrets) => redact.hold(secrets), ...(deps.githubWeb ? { web: deps.githubWeb } : {}), ...(signal ? { signal } : {}), ...(held ? { held } : {}) });
176
176
  }
@@ -1,3 +1,4 @@
1
+ import type { DraftDecisions } from "../learn/skills.js";
1
2
  import type { EndOfRunTurn } from "./loop-contract.js";
2
3
  /** How long a run's end-of-run turn may take before it is aborted and the run ends without it. */
3
4
  export declare const REFLECT_TIMEOUT_MS: number;
@@ -55,6 +56,7 @@ export interface ReflectDeps {
55
56
  readonly promptFacts: (runId: string, agentId: string) => Promise<{
56
57
  active: number;
57
58
  tools: readonly string[];
59
+ decisions?: DraftDecisions;
58
60
  draftFor?: readonly string[];
59
61
  described?: readonly {
60
62
  readonly name: string;
@@ -84,6 +86,22 @@ export interface ReflectDeps {
84
86
  /** The grade model the server names (learning.ts gradeModelOf: --grade-model, AGENTRUN_SERVE_GRADE_MODEL, else
85
87
  * AGENT_MODEL_STRONG), carried on the learning run's launch; none, the agent's own model grades it, as main's. */
86
88
  readonly gradeModel?: string;
89
+ /** The cap the learning run's grade runs under, read once the turn closed (learning-end.ts gradeCapOf): what the run's
90
+ * cap leaves once everything the run spent is counted, carried on the learning run's launch as its own cap, so the
91
+ * grade never takes the run past its cap. Undefined for an uncapped run: its grade is capped by nothing. */
92
+ readonly gradeCap?: (runId: string) => Promise<number | undefined>;
93
+ /** Which end of the run this is: 1, its first (the default); an end after a follow-up opened the run again is the next
94
+ * round, asked anew (its prompt says it looked back before), kept as a proposal of its own beside the earlier rounds'
95
+ * (every row the hook gives carries it), graded and merged by a learning run of its own. */
96
+ readonly round?: number;
97
+ /** A later round's: what the round before it kept of the run's spend (its job's and its look-back's), so the follow-up's
98
+ * own share, between that look-back and this one, is kept apart (`follow_up_usd`); and whether it was asked its turn
99
+ * (`looked`: a round cut before it was asked says nothing of looking back before). */
100
+ readonly before?: {
101
+ readonly job_cost_usd?: number | null;
102
+ readonly look_back_usd?: number | null;
103
+ readonly looked?: boolean;
104
+ };
87
105
  /** The turn's deadline. Default REFLECT_TIMEOUT_MS. Its re-ask is inside it. */
88
106
  readonly deadlineMs?: number;
89
107
  /** For tests: the clock the turn's deadline is measured by. Default Date.now. */
@@ -28,9 +28,12 @@ function dryRunFailure(checked) {
28
28
  const found = problems.find((problem) => problem?.rule === "workflow" && typeof problem.path === "string" && typeof problem.detail === "string" && problem.detail.startsWith(DRY_RUN_FAILED));
29
29
  return found ? { path: found.path, detail: found.detail } : undefined;
30
30
  }
31
+ /** `rows` with round `round` on each learning row (none on a run's first, round 1). */
32
+ const roundOf = (rows, round) => !rows || round === 1 ? rows : { also: rows.also.map((row) => (row.table === "learning_proposals" || row.table === "learning_run" ? { ...row, row: { ...row.row, round } } : row)) };
31
33
  /** The end-of-run turn for runs that learn. */
32
34
  export function createReflectHook(deps) {
33
- return async (input) => {
35
+ const round = deps.round ?? 1;
36
+ const hook = async (input) => {
34
37
  const facts = await deps.facts(input.runId);
35
38
  if (!facts.learns)
36
39
  return undefined;
@@ -54,18 +57,22 @@ export function createReflectHook(deps) {
54
57
  // spend so far is the job's.
55
58
  const answeredAt = new Date(now()).toISOString();
56
59
  const job = facts.costUsd;
60
+ // A later round's: the follow-up's own spend, the run's spend now less what the round before it kept (its job's and
61
+ // its look-back's), unknown when any is.
62
+ const earlier = deps.before;
63
+ const followUp = round === 1 ? {} : { follow_up_usd: job === null || typeof earlier?.job_cost_usd !== "number" || typeof earlier.look_back_usd !== "number" ? null : Math.max(0, Math.round((job - earlier.job_cost_usd - earlier.look_back_usd) * 1e9) / 1e9) };
57
64
  // closeLearning: what looking back cost, the run's spend once the turn closed (its re-ask included) less the job's,
58
65
  // unknown when either is. Kept with every end the turn reaches from here, beside when the job answered and its cost.
59
66
  const looked = async (rows) => {
60
67
  const total = (await deps.facts(input.runId)).costUsd;
61
- const answered = { answered_at: answeredAt, job_cost_usd: job, look_back_usd: total === null || job === null ? null : Math.max(0, Math.round((total - job) * 1e9) / 1e9) };
68
+ const answered = { answered_at: answeredAt, job_cost_usd: job, look_back_usd: total === null || job === null ? null : Math.max(0, Math.round((total - job) * 1e9) / 1e9), ...followUp };
62
69
  return { also: rows.also.map((row) => (row.table === "learning_proposals" ? { ...row, row: { ...row.row, proposal: { ...row.row.proposal, ...answered } } } : row)) };
63
70
  };
64
71
  // A job that only ran its learned workflows, each answering, with nothing said after its first message, gave nothing
65
72
  // new to learn: it is not asked (no model request), and looking back cost nothing, $0 whether or not the job's own
66
73
  // cost is known. Its words are the server's own.
67
74
  if (input.outcome === "completed" && deps.nothingNew && (await deps.nothingNew(input.runId).catch(() => false))) {
68
- return { also: [droppedRow(null, "empty", said.onlyWorkflow, { answered_at: answeredAt, job_cost_usd: job, look_back_usd: 0 })] };
75
+ return { also: [droppedRow(null, "empty", said.onlyWorkflow, { answered_at: answeredAt, job_cost_usd: job, look_back_usd: 0, ...followUp })] };
69
76
  }
70
77
  // What the run must never learn, read once, before it is asked anything: a run whose list can't be read learns
71
78
  // nothing, never over a shorter one.
@@ -76,10 +83,11 @@ export function createReflectHook(deps) {
76
83
  const close = async (rows) => ({ also: (await looked({ also: rows })).also.map((row) => cutRow(row, refuse)) });
77
84
  if (read === "unreadable")
78
85
  return close([droppedRow(null, "propose_failed", said.stopped(STOPPED.refuseUnread))]);
79
- const { active, tools, draftFor, described, workflows } = await deps.promptFacts(input.runId, input.agentId);
86
+ const { active, tools, draftFor, described, decisions, workflows } = await deps.promptFacts(input.runId, input.agentId);
80
87
  const deadlineMs = deps.deadlineMs ?? REFLECT_TIMEOUT_MS;
81
88
  const started = now();
82
- const end = await input.ask(reflectPrompt({ dir: LEARNED_DIR, active, tools, ...(workflows === false ? { workflows: false } : draftFor?.length ? { draftFor, ...(described?.length ? { described } : {}) } : {}) }), { origin: "reflect", deadlineMs });
89
+ const ask = { origin: "reflect", ...(round > 1 ? { round } : {}) };
90
+ const end = await input.ask(reflectPrompt({ dir: LEARNED_DIR, active, tools, ...(decisions ? { decisions } : {}), ...(workflows === false ? { workflows: false } : draftFor?.length ? { draftFor, ...(described?.length ? { described } : {}) } : {}), ...(round > 1 && deps.before?.looked !== false ? { later: true } : {}) }), { ...ask, deadlineMs });
83
91
  // closeLearning: how the turn ended.
84
92
  if ("timedOut" in end)
85
93
  return close([droppedRow(null, "reflect_timeout", said.stopped(STOPPED.timedOut))]);
@@ -104,7 +112,7 @@ export function createReflectHook(deps) {
104
112
  // within the turn's own deadline; a re-ask that times out or fails leaves the first answer's drop.
105
113
  if (checked.state === "dropped" && checked.reason === "unparsed") {
106
114
  const left = deadlineMs - (now() - started);
107
- const again = left > 0 ? await input.ask(reflectAgain(checked.detail, ...(workflows === false ? [false] : [])), { origin: "reflect", deadlineMs: left, again: true }) : undefined;
115
+ const again = left > 0 ? await input.ask(reflectAgain(checked.detail, ...(workflows === false ? [false] : [])), { ...ask, deadlineMs: left, again: true }) : undefined;
108
116
  if (again && "ended" in again) {
109
117
  turn = turnOf(again.answer);
110
118
  checked = await checkOf(turn);
@@ -119,7 +127,7 @@ export function createReflectHook(deps) {
119
127
  // never costs a note the first answer kept). Never a third time (a turn asks again once, for either reason).
120
128
  const dry = dryRunFailure(checked);
121
129
  const left = deadlineMs - (now() - started);
122
- const again = dry && left > 0 ? await input.ask(reflectDryRun(dry.path, dry.detail), { origin: "reflect", deadlineMs: left, again: true }) : undefined;
130
+ const again = dry && left > 0 ? await input.ask(reflectDryRun(dry.path, dry.detail), { ...ask, deadlineMs: left, again: true }) : undefined;
123
131
  if (again && "ended" in again) {
124
132
  const second = turnOf(again.answer);
125
133
  const kept = await checkOf(second);
@@ -133,9 +141,13 @@ export function createReflectHook(deps) {
133
141
  const detail = checked.reason === "empty" ? said.empty : checked.reason === "unparsed" ? said.unparsed : said.checker(checked.problems);
134
142
  return close([droppedRow(turn, checked.reason, detail, checked)]);
135
143
  }
144
+ // The learning run's cap: what the run's cap leaves now its look-back is spent, read after the checks (a read that
145
+ // fails is no room, never no cap: the grade is then skipped, never run past the cap).
146
+ const capUsd = deps.gradeCap ? await deps.gradeCap(input.runId).catch(() => 0) : undefined;
136
147
  return close([
137
148
  { table: "learning_proposals", row: { turn, proposal: { ...checked, detail: said.proposed(checked.notes, checked.skills, checked.workflows) } } },
138
- { table: "learning_run", row: { id: deps.newRunId(), ...(deps.gradeModel ? { model: deps.gradeModel } : {}) } },
149
+ { table: "learning_run", row: { id: deps.newRunId(), ...(deps.gradeModel ? { model: deps.gradeModel } : {}), ...(capUsd !== undefined ? { capUsd } : {}) } },
139
150
  ]);
140
151
  };
152
+ return async (input) => roundOf(await hook(input), round);
141
153
  }
@@ -1,8 +1,15 @@
1
1
  import { type Claim, type LoopEnd, type LoopFactory } from "./loop-contract.js";
2
2
  import { type RunnerStore } from "./store-port.js";
3
+ import { type RunState } from "../store/store.js";
3
4
  import { type Redact } from "./redact.js";
4
5
  import { type LiveTickerOptions } from "./live-ticker.js";
5
6
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
7
+ /** A final run's status as its end line says it: the store holds a cancel as state 'stopped' with outcome 'cancelled', so
8
+ * the outcome tells a cancel from a person's resumable stop. */
9
+ export declare const endedStatus: (run: {
10
+ state: RunState;
11
+ outcome?: string | null;
12
+ }) => RunState | "cancelled";
6
13
  export declare const RUNNER_LOOPS = 300;
7
14
  /** How long a claim lasts unless renewed, unless told (RunnerOptions.leaseMs). */
8
15
  export declare const RUNNER_LEASE_MS = 30000;
@@ -53,6 +60,10 @@ export interface RunnerOptions {
53
60
  /** The wait before a run whose loop ended interrupted on its own (no stop asked of it: its Session closed itself) is
54
61
  * claimable again; each such end of the run in a row waits twice the one before, up to 64 times this. */
55
62
  interruptBackoffMs?: number;
63
+ /** After a claim or release commit answered Unanswered (it may have landed), the wait before the first re-read of what
64
+ * this runner holds; each retry of that re-read waits twice the one before, up to UNKNOWN_READS tries, then the lease
65
+ * settles it. */
66
+ unknownBackoffMs?: number;
56
67
  /** How long a run's end waits for a command still with its loop before it writes its end; an answer after that is
57
68
  * dropped (nothing written, nothing said). */
58
69
  endWaitMs?: number;
@@ -100,6 +111,21 @@ export interface RunnerMemory {
100
111
  export type RunnerEvent = {
101
112
  type: "claimed";
102
113
  claim: Claim;
114
+ }
115
+ /** A run's start, once: its first claim (from queued). `agent` and `kind` are ids, never a secret. */
116
+ | {
117
+ type: "started";
118
+ runId: string;
119
+ agent: string;
120
+ kind: string;
121
+ }
122
+ /** A run's end, once it is final (ended, stopped, failed): its state and the cost its row holds. */
123
+ | {
124
+ type: "ended";
125
+ runId: string;
126
+ agent: string;
127
+ status: RunState | "cancelled";
128
+ costUsd: number | null;
103
129
  } | {
104
130
  type: "claim-lost";
105
131
  runId: string;