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

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 (372) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +260 -168
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-images.d.ts +15 -0
  15. package/dist/attach-images.js +59 -0
  16. package/dist/background.d.ts +0 -6
  17. package/dist/background.js +0 -28
  18. package/dist/box-image.d.ts +1 -97
  19. package/dist/box-image.js +4 -284
  20. package/dist/box-paths.d.ts +2 -7
  21. package/dist/box-paths.js +7 -13
  22. package/dist/box-settings.d.ts +0 -11
  23. package/dist/box-settings.js +4 -29
  24. package/dist/browser-commands.js +1 -1
  25. package/dist/browser-computer.d.ts +47 -3
  26. package/dist/browser-computer.js +286 -18
  27. package/dist/browser-person.d.ts +19 -2
  28. package/dist/browser-person.js +55 -6
  29. package/dist/browser-wait-ended.d.ts +23 -0
  30. package/dist/browser-wait-ended.js +42 -0
  31. package/dist/cap.d.ts +13 -41
  32. package/dist/cap.js +24 -73
  33. package/dist/cli.js +4 -22
  34. package/dist/computer-routes.d.ts +1 -4
  35. package/dist/computer-routes.js +3 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +38 -1
  38. package/dist/computer-view.d.ts +11 -2
  39. package/dist/computer-view.js +2 -1
  40. package/dist/computers.d.ts +48 -7
  41. package/dist/computers.js +100 -23
  42. package/dist/console/assets/index-BI4Byidu.js +550 -0
  43. package/dist/console/assets/index-C19gUF2n.css +1 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/docker-daemon.d.ts +2 -2
  46. package/dist/docker-daemon.js +2 -2
  47. package/dist/errors.js +5 -5
  48. package/dist/faux-computers.js +4 -0
  49. package/dist/files.d.ts +1 -9
  50. package/dist/files.js +1 -9
  51. package/dist/github.d.ts +22 -2
  52. package/dist/github.js +42 -8
  53. package/dist/gpu-words.d.ts +14 -0
  54. package/dist/gpu-words.js +21 -0
  55. package/dist/graph-view.d.ts +2 -0
  56. package/dist/graph-view.js +25 -1
  57. package/dist/handed-values.d.ts +1 -1
  58. package/dist/handed-values.js +1 -1
  59. package/dist/harness-install.d.ts +60 -3
  60. package/dist/harness-install.js +322 -34
  61. package/dist/harness.js +1 -1
  62. package/dist/host-tools.d.ts +8 -9
  63. package/dist/host-tools.js +7 -7
  64. package/dist/index.d.ts +1 -3
  65. package/dist/index.js +1 -2
  66. package/dist/key-refusal.d.ts +1 -1
  67. package/dist/key-refusal.js +2 -2
  68. package/dist/learn/check.d.ts +7 -1
  69. package/dist/learn/check.js +123 -5
  70. package/dist/learn/commit.d.ts +40 -6
  71. package/dist/learn/commit.js +164 -20
  72. package/dist/learn/folder.d.ts +5 -0
  73. package/dist/learn/folder.js +33 -0
  74. package/dist/learn/grade.d.ts +18 -1
  75. package/dist/learn/grade.js +86 -16
  76. package/dist/learn/index.d.ts +1 -1
  77. package/dist/learn/index.js +1 -1
  78. package/dist/learn/learning.sh +12 -1
  79. package/dist/learn/notes.d.ts +3 -0
  80. package/dist/learn/notes.js +3 -0
  81. package/dist/learn/reflect.d.ts +5 -2
  82. package/dist/learn/reflect.js +43 -29
  83. package/dist/learn/skills.d.ts +4 -0
  84. package/dist/learn/skills.js +7 -0
  85. package/dist/learned-nodes.d.ts +6 -2
  86. package/dist/learned-workflow.d.ts +19 -9
  87. package/dist/learned-workflow.js +62 -34
  88. package/dist/learning-cost.d.ts +79 -0
  89. package/dist/learning-cost.js +69 -0
  90. package/dist/learning-routes.d.ts +8 -3
  91. package/dist/learning-routes.js +9 -6
  92. package/dist/learning-words.d.ts +3 -0
  93. package/dist/learning-words.js +6 -2
  94. package/dist/learning.d.ts +13 -6
  95. package/dist/learning.js +4 -2
  96. package/dist/mcp-probe.d.ts +8 -1
  97. package/dist/mcp-probe.js +62 -20
  98. package/dist/mcp-secret-writes.js +4 -0
  99. package/dist/mcp-servers-store.js +8 -3
  100. package/dist/model.d.ts +5 -5
  101. package/dist/model.js +6 -6
  102. package/dist/openapi.d.ts +2 -0
  103. package/dist/openapi.js +204 -47
  104. package/dist/owner.d.ts +0 -1
  105. package/dist/owner.js +0 -2
  106. package/dist/paid-calls.js +1 -1
  107. package/dist/place-offers.d.ts +97 -0
  108. package/dist/place-offers.js +206 -0
  109. package/dist/place.d.ts +9 -13
  110. package/dist/place.js +22 -32
  111. package/dist/port-models.d.ts +2 -1
  112. package/dist/port-models.js +5 -3
  113. package/dist/print.d.ts +1 -8
  114. package/dist/print.js +1 -14
  115. package/dist/propose.d.ts +1 -0
  116. package/dist/propose.js +25 -10
  117. package/dist/run-cut.d.ts +5 -0
  118. package/dist/run-cut.js +19 -0
  119. package/dist/run-db.js +3 -3
  120. package/dist/run-launch.d.ts +14 -1
  121. package/dist/run-launch.js +7 -2
  122. package/dist/run-learning-served.d.ts +1 -1
  123. package/dist/run-manifest.d.ts +2 -2
  124. package/dist/run-manifest.js +2 -2
  125. package/dist/run-secrets.js +3 -3
  126. package/dist/run-timeline-served.js +56 -44
  127. package/dist/run-view.d.ts +5 -2
  128. package/dist/run-view.js +4 -3
  129. package/dist/runnable.d.ts +2 -2
  130. package/dist/runnable.js +6 -2
  131. package/dist/runner/adapter-loop.d.ts +16 -1
  132. package/dist/runner/adapter-loop.js +131 -30
  133. package/dist/runner/adapter-run-spec.d.ts +25 -4
  134. package/dist/runner/adapter-run-spec.js +103 -24
  135. package/dist/runner/adapters/pi.d.ts +11 -3
  136. package/dist/runner/adapters/pi.js +35 -12
  137. package/dist/runner/beside.js +6 -2
  138. package/dist/runner/cli-run-spec.d.ts +7 -0
  139. package/dist/runner/cli-run-spec.js +92 -38
  140. package/dist/runner/commands.d.ts +5 -1
  141. package/dist/runner/commands.js +3 -3
  142. package/dist/runner/conformance/harness.d.ts +0 -1
  143. package/dist/runner/conformance/harness.js +8 -5
  144. package/dist/runner/github-app.js +2 -2
  145. package/dist/runner/harness-loops.js +1 -1
  146. package/dist/runner/journal-kinds.d.ts +15 -5
  147. package/dist/runner/journal-kinds.js +6 -1
  148. package/dist/runner/learning-end.d.ts +15 -0
  149. package/dist/runner/learning-end.js +26 -5
  150. package/dist/runner/learning-factory.js +6 -2
  151. package/dist/runner/learning-loop.d.ts +73 -1
  152. package/dist/runner/learning-loop.js +203 -18
  153. package/dist/runner/learning-seed.d.ts +2 -0
  154. package/dist/runner/learning-seed.js +1 -1
  155. package/dist/runner/loop-contract.d.ts +8 -0
  156. package/dist/runner/loop-contract.js +6 -0
  157. package/dist/runner/loop.d.ts +5 -1
  158. package/dist/runner/loop.js +20 -0
  159. package/dist/runner/main.js +12 -2
  160. package/dist/runner/mcp-claim.d.ts +4 -0
  161. package/dist/runner/mcp-claim.js +29 -1
  162. package/dist/runner/mcp-github.d.ts +4 -2
  163. package/dist/runner/mcp-github.js +0 -7
  164. package/dist/runner/mcp-run.d.ts +2 -0
  165. package/dist/runner/mcp-run.js +1 -0
  166. package/dist/runner/metrics.d.ts +4 -0
  167. package/dist/runner/metrics.js +9 -0
  168. package/dist/runner/model-route.d.ts +3 -0
  169. package/dist/runner/model-route.js +5 -2
  170. package/dist/runner/pr-checkout.d.ts +59 -0
  171. package/dist/runner/pr-checkout.js +176 -0
  172. package/dist/runner/reflect-hook.d.ts +1 -0
  173. package/dist/runner/reflect-hook.js +3 -3
  174. package/dist/runner/runner.js +47 -12
  175. package/dist/runner/spec-holds.d.ts +8 -3
  176. package/dist/runner/spec-holds.js +12 -10
  177. package/dist/runner/store-port.d.ts +4 -1
  178. package/dist/runner/store-secrets.js +17 -1
  179. package/dist/runner/subagent.d.ts +44 -0
  180. package/dist/runner/subagent.js +188 -0
  181. package/dist/runner/workflow-host.d.ts +18 -2
  182. package/dist/runner/workflow-host.js +23 -3
  183. package/dist/runner/workflow-loop.d.ts +5 -2
  184. package/dist/runner/workflow-loop.js +9 -8
  185. package/dist/runner/workflow-spec.d.ts +26 -14
  186. package/dist/runner/workflow-spec.js +97 -30
  187. package/dist/runs-over-store.d.ts +11 -6
  188. package/dist/runs-over-store.js +111 -24
  189. package/dist/sealing.js +1 -2
  190. package/dist/secret-cut.d.ts +1 -1
  191. package/dist/secret-cut.js +1 -1
  192. package/dist/server.d.ts +32 -49
  193. package/dist/server.js +249 -199
  194. package/dist/store/agent-body.d.ts +9 -2
  195. package/dist/store/agent-body.js +16 -8
  196. package/dist/store/deadline.js +9 -5
  197. package/dist/store/index.d.ts +3 -3
  198. package/dist/store/index.js +2 -2
  199. package/dist/store/journal/storage.js +2 -1
  200. package/dist/store/postgres/connection.js +9 -4
  201. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  202. package/dist/store/schema.d.ts +2 -1
  203. package/dist/store/schema.js +11 -8
  204. package/dist/store/seal.d.ts +13 -0
  205. package/dist/store/seal.js +19 -0
  206. package/dist/store/sqlite/connection.d.ts +5 -0
  207. package/dist/store/sqlite/connection.js +88 -47
  208. package/dist/store/sqlite/run-patch.d.ts +18 -2
  209. package/dist/store/sqlite/run-patch.js +31 -2
  210. package/dist/store/sqlite/store.js +65 -11
  211. package/dist/store/store.d.ts +62 -12
  212. package/dist/store/store.js +22 -1
  213. package/dist/store-reads/analytics.js +3 -2
  214. package/dist/store-reads/cap.d.ts +1 -3
  215. package/dist/store-reads/cap.js +8 -6
  216. package/dist/store-reads/decisions.d.ts +2 -2
  217. package/dist/store-reads/decisions.js +3 -6
  218. package/dist/store-reads/journal.js +45 -12
  219. package/dist/store-reads/learning.d.ts +15 -1
  220. package/dist/store-reads/learning.js +68 -10
  221. package/dist/store-reads/runs.d.ts +6 -4
  222. package/dist/store-reads/runs.js +17 -10
  223. package/dist/store-reads/stats.js +5 -1
  224. package/dist/store-view.js +45 -19
  225. package/dist/template-eval.js +2 -1
  226. package/dist/templates.d.ts +64 -0
  227. package/dist/templates.js +101 -16
  228. package/dist/timeline/timeline.d.ts +3 -1
  229. package/dist/timeline/timeline.js +19 -4
  230. package/dist/tool-blurbs.js +1 -0
  231. package/dist/tool-budget.d.ts +8 -0
  232. package/dist/tool-budget.js +7 -1
  233. package/dist/tool-gate.d.ts +7 -1
  234. package/dist/tool-gate.js +7 -2
  235. package/dist/tool-plane.d.ts +33 -19
  236. package/dist/tool-plane.js +64 -27
  237. package/dist/tools.d.ts +18 -34
  238. package/dist/tools.js +104 -70
  239. package/dist/trigger-signatures.d.ts +1 -0
  240. package/dist/trigger-signatures.js +3 -1
  241. package/dist/triggers.d.ts +3 -3
  242. package/dist/triggers.js +2 -2
  243. package/dist/turn-end.d.ts +0 -3
  244. package/dist/turn-end.js +0 -3
  245. package/dist/usage-lines.d.ts +1 -1
  246. package/dist/validate.d.ts +6 -0
  247. package/dist/validate.js +30 -3
  248. package/dist/webhooks.d.ts +2 -1
  249. package/dist/webhooks.js +5 -2
  250. package/dist/workflow/decision-recovery.d.ts +23 -0
  251. package/dist/workflow/decision-recovery.js +80 -0
  252. package/dist/workflow/decisions.d.ts +134 -0
  253. package/dist/workflow/decisions.js +46 -0
  254. package/dist/workflow/host-session.d.ts +5 -0
  255. package/dist/workflow/host-session.js +85 -0
  256. package/dist/workflow/host-tools.d.ts +3 -0
  257. package/dist/workflow/host-tools.js +3 -0
  258. package/dist/workflow/node-runner.d.ts +112 -0
  259. package/dist/workflow/node-runner.js +270 -0
  260. package/dist/workflow/node.d.ts +88 -0
  261. package/dist/workflow/node.js +99 -0
  262. package/dist/workflow/operator-error.d.ts +4 -0
  263. package/dist/workflow/operator-error.js +4 -0
  264. package/dist/workflow/pi-versions.d.ts +9 -0
  265. package/dist/workflow/pi-versions.js +8 -0
  266. package/dist/workflow/readers.d.ts +36 -0
  267. package/dist/workflow/readers.js +145 -0
  268. package/dist/workflow/record-file.d.ts +10 -0
  269. package/dist/workflow/record-file.js +56 -0
  270. package/dist/workflow/record-tool.d.ts +76 -0
  271. package/dist/workflow/record-tool.js +126 -0
  272. package/dist/workflow/record.d.ts +151 -0
  273. package/dist/workflow/record.js +401 -0
  274. package/dist/workflow/run-error.d.ts +16 -0
  275. package/dist/workflow/run-error.js +26 -0
  276. package/dist/workflow/runner.d.ts +6 -0
  277. package/dist/workflow/runner.js +240 -0
  278. package/dist/workflow/store.d.ts +23 -0
  279. package/dist/workflow/store.js +242 -0
  280. package/dist/workflow/task.d.ts +133 -0
  281. package/dist/workflow/task.js +411 -0
  282. package/dist/workflow/thinking.d.ts +3 -0
  283. package/dist/workflow/thinking.js +7 -0
  284. package/dist/workflow/tool-context.d.ts +21 -0
  285. package/dist/workflow/tool-context.js +13 -0
  286. package/dist/workflow/types.d.ts +126 -0
  287. package/dist/workflow/types.js +1 -0
  288. package/dist/workflow/wal.d.ts +11 -0
  289. package/dist/workflow/wal.js +106 -0
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/agent-computer.d.ts +137 -0
  292. package/dist/workspace/agent-computer.js +292 -0
  293. package/dist/workspace/archil-claim.d.ts +11 -0
  294. package/dist/workspace/archil-claim.js +18 -10
  295. package/dist/workspace/archil-disks.d.ts +49 -0
  296. package/dist/workspace/archil-disks.js +185 -0
  297. package/dist/workspace/archil-exec.js +2 -3
  298. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  299. package/dist/workspace/archil-mount-credential.js +13 -4
  300. package/dist/workspace/computer-deps.d.ts +16 -8
  301. package/dist/workspace/computer-deps.js +18 -7
  302. package/dist/workspace/computer-for-claim.d.ts +42 -6
  303. package/dist/workspace/computer-for-claim.js +209 -9
  304. package/dist/workspace/computer-janitor.d.ts +3 -2
  305. package/dist/workspace/computer-janitor.js +43 -9
  306. package/dist/workspace/computer-ledger.d.ts +3 -1
  307. package/dist/workspace/computer-ledger.js +7 -0
  308. package/dist/workspace/index.d.ts +3 -2
  309. package/dist/workspace/index.js +1 -0
  310. package/dist/workspace/resolve-computer.d.ts +42 -11
  311. package/dist/workspace/resolve-computer.js +65 -13
  312. package/dist/workspace/run-disk.d.ts +34 -0
  313. package/dist/workspace/run-disk.js +91 -0
  314. package/dist/workspace/run-tools.d.ts +4 -4
  315. package/dist/workspace/run-tools.js +8 -6
  316. package/dist/workspace/server-run-workspace.d.ts +3 -2
  317. package/dist/workspace/server-run-workspace.js +17 -4
  318. package/dist/workspace.js +1 -1
  319. package/package.json +10 -15
  320. package/templates/README.md +9 -6
  321. package/templates/code-review/agent.md +27 -11
  322. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  323. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  324. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  325. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  326. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  327. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  328. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  329. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  330. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  331. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  332. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  333. package/templates/code-review/evals/re-review/prompt.md +1 -1
  334. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  335. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  336. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  337. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  338. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  339. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  340. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  341. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  342. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  343. package/templates/code-review/findings.schema.json +131 -27
  344. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  345. package/templates/code-review/skills/review/DEEP.md +130 -0
  346. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  347. package/templates/code-review/skills/review/SKILL.md +104 -154
  348. package/dist/box/record.d.ts +0 -6
  349. package/dist/box/record.js +0 -41
  350. package/dist/box/sweep.d.ts +0 -53
  351. package/dist/box/sweep.js +0 -193
  352. package/dist/box-egress-vm.d.ts +0 -118
  353. package/dist/box-egress-vm.js +0 -354
  354. package/dist/box-egress.d.ts +0 -105
  355. package/dist/box-egress.js +0 -256
  356. package/dist/box-relay-vm.d.ts +0 -84
  357. package/dist/box-relay-vm.js +0 -437
  358. package/dist/box-relay.d.ts +0 -36
  359. package/dist/box-relay.js +0 -207
  360. package/dist/boxes.d.ts +0 -109
  361. package/dist/boxes.js +0 -249
  362. package/dist/budget.d.ts +0 -71
  363. package/dist/budget.js +0 -199
  364. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  365. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  366. package/dist/daytona-api.d.ts +0 -10
  367. package/dist/daytona-api.js +0 -20
  368. package/dist/egress-proxy.d.ts +0 -45
  369. package/dist/egress-proxy.js +0 -416
  370. package/dist/egress-table.d.ts +0 -24
  371. package/dist/egress-table.js +0 -165
  372. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -16,6 +16,11 @@
16
16
  // (signedOut), a refresh that got no answer (silent), an address the check refuses (blocked). A runner never starts
17
17
  // without the seal key (seal-key.ts bootSealKey), so a claim always has one.
18
18
  //
19
+ // 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
+ // run's launch row for the run's life (store/seal.ts sealRunMcpAuth) and erased by the write that ends it. Each fresh()
21
+ // opens it again, so a message's new credential reaches the run's next model request; a run handed none gets its calls
22
+ // refused unsent (UNUSABLE.perRunMissing).
23
+ //
19
24
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
20
25
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
21
26
  // only when it provably never left: a refused or unmade connection, an address check out of time; one request that left
@@ -41,7 +46,7 @@ import { githubTokens } from "./mcp-github.js";
41
46
  import { ClaimRefused } from "./loop-contract.js";
42
47
  import { REFRESH_MARGIN_MS, UNKNOWN_EXPIRY_MS, UNUSABLE } from "../mcp-probe.js";
43
48
  import { tokenLeftOf } from "../mcp-probe.js";
44
- import { openMcpCredential, sealMcpCredential } from "../store/seal.js";
49
+ import { openMcpCredential, openRunMcpAuth, sealMcpCredential } from "../store/seal.js";
45
50
  import { Fenced, MCP_REFRESH_CALL_MS } from "../store/index.js";
46
51
  /** Whether two sealed credentials are the same bytes (none equals none). */
47
52
  const sameSealed = (a, b) => (a === null || b === null ? a === b : Buffer.from(a).equals(Buffer.from(b)));
@@ -170,6 +175,10 @@ export async function mcpClaim(options) {
170
175
  // after it), kept fresh mid-run, and never stored.
171
176
  if (row.auth === "github_app")
172
177
  return await github.open(name, entry), { awaited: true };
178
+ // A per_run server keeps none either: its credential is the one the run's caller handed it (mcp_auth), sealed in the
179
+ // run's launch, read again at every fresh() so a message's new one reaches the run's next request.
180
+ if (row.auth === "per_run")
181
+ return entry(await perRun(name, row.url)), { awaited: false };
173
182
  if (row.sealed === null)
174
183
  return entry({}), { awaited: false };
175
184
  // A seal problem first: no refresh is ever sent for a credential this runner cannot open.
@@ -287,9 +296,28 @@ export async function mcpClaim(options) {
287
296
  await settle(signal);
288
297
  return { awaited: true };
289
298
  };
299
+ /** The run's handed MCP credentials, opened from its launch: read once per fresh() (perRunRead), not once per server. */
300
+ let perRunRead;
301
+ /** A per_run server's headers for this run, from its launch; or why there are none. Only for the origin its url had
302
+ * when they were handed: a server moved since gets none. */
303
+ const perRun = async (name, url) => {
304
+ perRunRead ??= store.runs.launch(claim.runId).then((launch) => openRunMcpAuth(sealKey, claim.runId, launch.sealed));
305
+ const handed = await perRunRead;
306
+ if (handed === undefined)
307
+ return { unopened: UNUSABLE.damaged };
308
+ const given = Object.hasOwn(handed, name) ? handed[name] : undefined;
309
+ if (!given)
310
+ return { unopened: UNUSABLE.perRunMissing };
311
+ if (given.origin !== new URL(url).origin)
312
+ 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
+ return { headers: { ...given.headers } };
316
+ };
290
317
  const fresh = async () => {
291
318
  if (!pin || released)
292
319
  return;
320
+ perRunRead = undefined;
293
321
  let awaited = false;
294
322
  for (const [name, pinned] of Object.entries(pin))
295
323
  if ((await open(name, pinned.url)).awaited)
@@ -1,8 +1,10 @@
1
- /** The App's answer for one repository: a token and when it expires (ms), or why not. */
1
+ import type { GithubPermissions } from "../github.js";
2
+ /** The App's answer for one repository: a token and when it expires (ms), or why not. `permissions` narrows the token
3
+ * below the App's own (a checkout's: contents read alone). */
2
4
  export type GithubAppMint = (target: {
3
5
  installation?: number;
4
6
  repo: string;
5
- }) => Promise<{
7
+ }, permissions?: GithubPermissions) => Promise<{
6
8
  ok: true;
7
9
  token: string;
8
10
  expires_at: number;
@@ -1,10 +1,3 @@
1
- // A github_app MCP server's credential for one run (the runner's MCP claim step, runner/mcp-claim.ts): an installation
2
- // token the server's GitHub App mints (github.ts mintInstallationToken, given here as `mint`, its App id and key bound by
3
- // the runner), narrowed to the run's repository. It is minted at every launch (each claim), held in the step's memory
4
- // only (never sealed into mcp_servers, the journal or run_live: it lasts an hour and is minted again at will), joins the
5
- // redaction set, and is minted again with REFRESH_BEFORE_MS left, mid-run, so a long run's calls never carry an expired
6
- // token. A token that could not be renewed answers its calls in words once it expires, never a crash. One claim per run
7
- // mints for itself: there is no stored token to share, so no refresh lease.
8
1
  /** How long before its expiry a token is minted again: GitHub's tokens last an hour, so at 55 minutes. */
9
2
  export const REFRESH_BEFORE_MS = 5 * 60_000;
10
3
  /** Why a github_app server's calls are refused unsent, in the words the gateway gives the model. */
@@ -48,6 +48,8 @@ export interface McpForClaimOptions {
48
48
  connectMs?: number;
49
49
  };
50
50
  readonly githubTimer?: GithubTimer;
51
+ /** Each credential value the claim opens for a per_run server, for the run's redactors (mcp-claim.ts `hold`). */
52
+ readonly hold?: (values: string[]) => void;
51
53
  }
52
54
  /** A call as the loop's gate is asked about it: the tool by its catalog name. */
53
55
  export type McpGateCall = {
@@ -29,6 +29,7 @@ export async function mcpForClaim(options) {
29
29
  ...(githubApp ? { githubApp } : {}),
30
30
  ...(options.githubMcpOrigin ? { githubMcpOrigin: options.githubMcpOrigin } : {}),
31
31
  ...(options.githubTimer ? { githubTimer: options.githubTimer } : {}),
32
+ ...(options.hold ? { hold: options.hold } : {}),
32
33
  });
33
34
  }
34
35
  catch (error) {
@@ -27,6 +27,10 @@ export type BookedSpend = {
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
28
  * booking's. */
29
29
  export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions"): BookedSpend;
30
+ /** 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
+ * 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
+ * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
33
+ export declare function cliModelWorked(entries: readonly EntryLike[]): boolean;
30
34
  /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
31
35
  * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
32
36
  * booking (adapters/pi.ts afterResponse). */
@@ -86,6 +86,15 @@ export function bookedSpend(entries, which) {
86
86
  }
87
87
  return { usd: unpriced ? null : known, known, unpriced, requests, unmetered, models, tokens };
88
88
  }
89
+ /** 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
+ * 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
+ * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
92
+ export function cliModelWorked(entries) {
93
+ return entries.some((e) => {
94
+ const role = e.data?.role;
95
+ return e.kind === KINDS.callStart || ((e.kind === KINDS.message || e.kind === KINDS.endOfRunTurn) && role === "model");
96
+ });
97
+ }
89
98
  /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
90
99
  * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
91
100
  * booking (adapters/pi.ts afterResponse). */
@@ -55,6 +55,9 @@ export interface ModelRoute {
55
55
  readonly fetch?: typeof fetch;
56
56
  /** The catalog's cost of the model, tiers included: what the cap prices a request at before it leaves. */
57
57
  readonly cost?: RouteCost;
58
+ /** True when serve has no price for the model (runModels' `unpriced`): `cost` is then a placeholder of zeros, which the
59
+ * cap never reads as a price (capModelOf: price unknown, never $0). */
60
+ readonly unpriced?: boolean;
58
61
  /** The model's most output tokens (its catalog ceiling): the cap's output bound, null when the catalog names none. */
59
62
  readonly outputCeiling?: number | null;
60
63
  }
@@ -33,7 +33,10 @@ export async function routeOf(model, env = process.env, tier = "default", wires
33
33
  const chosen = await chooseModel(env, model, tier);
34
34
  if ("why" in chosen)
35
35
  throw new Error(chosen.why);
36
- const { models, unpriced } = await runModels(env, tier === "default" ? model : undefined, [tier]);
36
+ // A tier's own model, when one is named (a subagent's model_tiers), is the one registered, at the tier's price: a gateway
37
+ // lists only the models it is given, so the host's model for the tier in its place would leave this one unknown.
38
+ const named = tier !== "default" && typeof model === "string" ? { [tier]: model } : {};
39
+ const { models, unpriced } = await runModels(env, tier === "default" ? model : undefined, [tier], undefined, named);
37
40
  const target = models.getModel(chosen.model.provider, chosen.model.modelId);
38
41
  if (!target)
39
42
  throw new Error(`no model ${chosen.model.provider}/${chosen.model.modelId} here`);
@@ -43,7 +46,7 @@ export async function routeOf(model, env = process.env, tier = "default", wires
43
46
  // What the model takes as input and its input limits, on every wire: pi's session sends a model that takes no images
44
47
  // pi-ai's placeholder in place of one, and pi's read holds an image to the model's limits (port-models.ts sessionModel).
45
48
  const sees = { ...(target.input ? { input: target.input } : {}), ...(target.inputLimits ? { inputLimits: target.inputLimits } : {}) };
46
- const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, outputCeiling: target.maxTokens ?? null, like: sees };
49
+ const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, ...(unpriced.has(chosen.model.modelId) ? { unpriced: true } : {}), outputCeiling: target.maxTokens ?? null, like: sees };
47
50
  // An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
48
51
  if (chosen.model.provider === "anthropic") {
49
52
  return { ...route, provider: { api: "anthropic-messages", origin: target.baseUrl ?? "https://api.anthropic.com", credential: () => env.ANTHROPIC_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? "" } };
@@ -0,0 +1,59 @@
1
+ import type { Workspace } from "../workspace/workspace.js";
2
+ import type { GithubAppMint } from "./mcp-github.js";
3
+ import type { AdapterSpecDeps } from "./adapter-run-spec.js";
4
+ /** What an agent's revision keeps of its definition's `checkout` (validate.ts CHECKOUTS; `none` keeps nothing). */
5
+ export type Checkout = "pull_request";
6
+ /** The folder, in the run's own, the checkout lands in. */
7
+ export declare const CHECKOUT_DIR = "repo";
8
+ /** How long the whole checkout may take: inside Archil's exec bound, on either mode. */
9
+ export declare const CHECKOUT_MS = 295000;
10
+ /** What the checkout gives the run's claim: the line its system prompt carries, and its removal. */
11
+ export interface PrCheckout {
12
+ /** One line for the run's system prompt: where the checkout is and what it holds, or why there is none. */
13
+ readonly note: string;
14
+ /** The checkout removed from the run's folder: at the claim's release. A failure throws, for the release to log. */
15
+ end(): Promise<void>;
16
+ }
17
+ export interface PrCheckoutOptions {
18
+ /** The run's Workspace, whose exec runs the fetch. */
19
+ readonly workspace: Workspace;
20
+ /** The run's first input (its launch's): its payload tag names the pull request. */
21
+ readonly input: unknown;
22
+ /** Whether a github trigger started the run (its launch's inputOrigin): only then is its payload tag the server's own,
23
+ * and read. Anyone may write the tag's text into a run of their own. */
24
+ readonly fromGitHub?: boolean;
25
+ /** The server's GitHub App mint, when it has an App the runner can open: none, the fetch is anonymous. */
26
+ readonly mint?: GithubAppMint;
27
+ /** The token revoked at GitHub once the fetch is done: best effort, a failure leaves it to its hour. */
28
+ readonly revoke?: (token: string) => Promise<void>;
29
+ /** Each secret the checkout holds (the token, its header), handed to the run's redactor before it is used. */
30
+ readonly hold?: (secrets: readonly string[]) => void;
31
+ /** GitHub's site, where the repository is fetched from: a test's own (a folder of bare repositories, or a git server
32
+ * on loopback). Absent, https://github.com. */
33
+ readonly web?: string;
34
+ /** Ends the fetch at once: the claim's signal, aborted by a person's stop too. The checkout's removal is handed to
35
+ * `held` before the fetch starts, so a fetch cut short leaves its folder to the claim's release. */
36
+ readonly signal?: AbortSignal;
37
+ /** The checkout's removal, given the moment the fetch starts (the spec's holds), so whatever ends the claim removes it. */
38
+ readonly held?: (part: {
39
+ end(): Promise<void>;
40
+ }) => void;
41
+ readonly timeoutMs?: number;
42
+ }
43
+ /** The pull request `options.input` names, checked out in the run's folder at its head. Never throws for a checkout that
44
+ * could not be made: the run is told why, and reads the change some other way. */
45
+ export declare function prCheckout(options: PrCheckoutOptions): Promise<PrCheckout>;
46
+ /** The checkout a claim's spec makes (the pi and the CLI spec alike) for its launch: the server's GitHub App opened as the
47
+ * MCP step opens it (github-app.ts, its payload tag read only for a github trigger's run), its secrets held by the run's redactor `redact`, its removal by the spec's holds (`held`) from the
48
+ * moment the fetch starts, and `signal` (the claim's, a person's stop included) ending the fetch. */
49
+ export declare function prCheckoutForClaim(deps: Pick<AdapterSpecDeps, "store" | "sealKey" | "githubApi" | "githubWeb">, workspace: Workspace, launch: {
50
+ readonly input: unknown;
51
+ readonly inputOrigin?: {
52
+ readonly kind: string;
53
+ readonly source?: string;
54
+ } | undefined;
55
+ }, redact: {
56
+ hold(values: readonly string[]): void;
57
+ }, signal?: AbortSignal, held?: (part: {
58
+ end(): Promise<void>;
59
+ }) => void): Promise<PrCheckout>;
@@ -0,0 +1,176 @@
1
+ // A run's checkout of the pull request it was started for, made by the server before the first turn when the agent's
2
+ // definition says `checkout: pull_request` (a template's manifest sets it). The agent then starts with the repository at
3
+ // the pull request's head in `repo/` of its folder, its base and their merge base fetched beside it, and never holds a
4
+ // GitHub token: the fetch is the server's own, one exec on the run's Workspace (Mode 1 a process on this machine, Mode 2
5
+ // Archil's serverless exec over the run's folder), never a command of the agent's.
6
+ //
7
+ // What it reads of the run: its first message's payload tag alone (github.ts githubPullOf), which the server wrote from a
8
+ // signed GitHub delivery: the repository, the pull request's number, its head and its base. Nothing else names a
9
+ // repository to fetch.
10
+ //
11
+ // The credential: an installation token of the server's GitHub App, minted for that one repository with
12
+ // {contents: "read"} alone, handed to the exec on its stdin (Archil's: a spill file deleted on every path), turned there
13
+ // into an Authorization header in git's environment (GIT_CONFIG_COUNT), scoped to GitHub's site. It is never in argv,
14
+ // .git/config, the remote's URL, the run's folder, an env the agent's commands get, or the log (it joins the run's
15
+ // redactor). No App, or one not installed on the repository: the fetch is anonymous, which a public repository answers.
16
+ // The token is revoked once the fetch is done (GitHub's DELETE /installation/token), and is never kept.
17
+ //
18
+ // Git there reads no system or global config (no filter, textconv or fsmonitor a machine's config could attach), fetches
19
+ // no tags and no submodules, and checks out with the repository's own config alone, which this exec wrote.
20
+ //
21
+ // What the run is told: one line in its system prompt, the checkout's facts, or why there is none and that the GitHub
22
+ // tools can read the change instead. The checkout is removed when the claim lets go (spec-holds.ts), and made again by
23
+ // the next claim of the same run.
24
+ import { randomUUID } from "node:crypto";
25
+ import { GITHUB_WEB, githubPullOf } from "../github.js";
26
+ import { isObject } from "../validate.js";
27
+ import { COMMAND_MAX_MS } from "../workspace/archil-exec.js";
28
+ import { shellEnv } from "../workspace/hands.js";
29
+ import { githubAppAccess } from "./github-app.js";
30
+ /** The folder, in the run's own, the checkout lands in. */
31
+ export const CHECKOUT_DIR = "repo";
32
+ /** How long the whole checkout may take: inside Archil's exec bound, on either mode. */
33
+ export const CHECKOUT_MS = COMMAND_MAX_MS;
34
+ /** The commits each side is first fetched with, then deepened by (doubling) until the merge base is in: about 3,200
35
+ * commits back at most, past which the run is told there is no merge base and the base's diff is the two-dot one. A merge
36
+ * base found is taken only when no shallow edge lies outside its ancestry: a history cut short can show an older common
37
+ * commit (a long branch that merged an old side branch) while the path to the true merge base is cut off, so the fetch
38
+ * deepens until every edge is at or behind the merge base it found. Each fetch runs with git's auto maintenance off: a
39
+ * fetch otherwise starts a detached gc that writes into .git/objects while the checkout's removal deletes it. */
40
+ const DEPTH = 50;
41
+ const DEEPENS = 6;
42
+ /** The file in the checkout's .git naming the claim that made it: a removal takes only its own claim's checkout. */
43
+ const OWNER_FILE = "agentrun-claim";
44
+ /** The exec's script: $1 the remote's URL (no credential), $2 the head, $3 the base (or empty), $4 the folder, $5 the
45
+ * URL prefix the header is for, $6 this claim's checkout id (written to .git/${OWNER_FILE}). Its stdin's first line is
46
+ * an Authorization header, or empty for an anonymous fetch. Its exit codes name the step that failed (10 the folder, 11 the fetch, 12 the checkout); on success it prints the merge
47
+ * base, empty when none was found. */
48
+ const SCRIPT = `set -u
49
+ url=$1 head=$2 base=$3 dir=$4 scope=$5 claim=$6
50
+ IFS= read -r auth || true
51
+ export GIT_TERMINAL_PROMPT=0 GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null
52
+ if [ -n "\${auth:-}" ]; then export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.$scope.extraheader" GIT_CONFIG_VALUE_0="$auth"; fi
53
+ auth=
54
+ rm -rf "\${dir:?}"
55
+ git init -q "$dir" >/dev/null 2>&1 && cd "$dir" && printf '%s\\n' "$claim" > .git/${OWNER_FILE} && git remote add origin "$url" || exit 10
56
+ fetch() { git -c maintenance.auto=false -c gc.auto=0 fetch -q --no-tags --no-recurse-submodules origin "$@" "$head" \${base:+"$base"}; }
57
+ fetch --depth=${DEPTH} || exit 11
58
+ mb=
59
+ settled() {
60
+ [ -n "$mb" ] || return 1
61
+ [ -s .git/shallow ] || return 0
62
+ while IFS= read -r edge; do git merge-base --is-ancestor "$edge" "$mb" 2>/dev/null || return 1; done < .git/shallow
63
+ }
64
+ if [ -n "$base" ]; then
65
+ n=${DEPTH} i=0
66
+ while :; do
67
+ mb=$(git merge-base "$base" "$head" 2>/dev/null) || mb=
68
+ settled && break
69
+ [ "$i" -lt ${DEEPENS} ] || { mb=; break; }
70
+ fetch --deepen=$n || exit 11
71
+ n=$((n * 2)) i=$((i + 1))
72
+ done
73
+ fi
74
+ git update-ref refs/pr/head "$head" || exit 12
75
+ if [ -n "$base" ]; then git update-ref refs/pr/base "$base" || exit 12; fi
76
+ if [ -n "$mb" ]; then git update-ref refs/pr/merge-base "$mb" || exit 12; fi
77
+ git -c advice.detachedHead=false checkout -q --detach "$head" || exit 12
78
+ printf '%s\\n' "$mb"
79
+ `;
80
+ const noCheckout = (note) => ({ note, end: async () => { } });
81
+ /** The words of a failed exec, with the secrets cut and its last lines kept. */
82
+ const tail = (text, secrets) => {
83
+ let cut = text;
84
+ for (const secret of secrets)
85
+ cut = cut.split(secret).join("[redacted]");
86
+ const lines = cut.trim().split("\n").filter(Boolean);
87
+ return lines.slice(-3).join(" / ").slice(0, 400);
88
+ };
89
+ /** The pull request `options.input` names, checked out in the run's folder at its head. Never throws for a checkout that
90
+ * could not be made: the run is told why, and reads the change some other way. */
91
+ export async function prCheckout(options) {
92
+ const { workspace } = options;
93
+ const pull = githubPullOf(isObject(options.input) ? options.input.content : options.input, { payload: options.fromGitHub === true });
94
+ if (!pull)
95
+ return noCheckout("No checkout was made: this run was not started by a GitHub pull request event, so there is no repo/ folder. Read the change through the GitHub tools if you have them.");
96
+ const web = (options.web ?? GITHUB_WEB).replace(/\/+$/, "");
97
+ const name = `${pull.repo}#${pull.number}`;
98
+ // The token: the App's, for this repository alone, contents read alone. None (no App, not installed, GitHub said no):
99
+ // the fetch is anonymous, and the words say which, in case the repository turns out to be private.
100
+ let token;
101
+ let anonymous = "";
102
+ if (options.mint) {
103
+ try {
104
+ const got = await options.mint({ repo: pull.repo, ...(pull.installation !== undefined ? { installation: pull.installation } : {}) }, { contents: "read" });
105
+ if (got.ok)
106
+ token = got.token;
107
+ else
108
+ anonymous = got.reason === "not_installed" ? `the GitHub App is not installed on ${pull.repo}` : got.message;
109
+ }
110
+ catch (error) {
111
+ anonymous = `GitHub did not make a token (${error?.message ?? error})`;
112
+ }
113
+ }
114
+ else
115
+ anonymous = "this server has no GitHub App";
116
+ const header = token ? `Authorization: Basic ${Buffer.from(`x-access-token:${token}`, "utf8").toString("base64")}` : "";
117
+ const secrets = token ? [token, header, header.slice("Authorization: Basic ".length)] : [];
118
+ if (secrets.length)
119
+ options.hold?.(secrets);
120
+ // This claim's checkout, by an id of its own: a claim that lost its lease and lets go late removes only the folder it
121
+ // made, never the one a later claim of the run is fetching or reading (that claim's fetch replaces a stale one itself).
122
+ const claim = randomUUID();
123
+ const removal = async () => {
124
+ const result = await workspace.exec(["sh", "-c", `[ "$(cat "\${1:?}/.git/${OWNER_FILE}" 2>/dev/null)" = "$2" ] || exit 0; rm -rf -- "\${1:?}"`, "sh", CHECKOUT_DIR, claim], { env: shellEnv(), timeoutMs: CHECKOUT_MS });
125
+ if (result.code !== 0)
126
+ throw new Error(`the run's ${CHECKOUT_DIR}/ checkout could not be removed (exit ${result.code ?? result.signal}): ${tail(result.stderr, secrets)}`);
127
+ };
128
+ const failed = async (why) => {
129
+ // What a failed fetch left (a half folder) goes now: the run is told there is none.
130
+ await removal().catch(() => { });
131
+ return noCheckout(`The pull request ${name} could not be checked out (${why}), so there is no ${CHECKOUT_DIR}/ folder: read the change through the GitHub tools (its diff, and each file at the head sha ${pull.head}).`);
132
+ };
133
+ // From here a folder may exist: its removal is the claim's to run, whatever ends it.
134
+ options.held?.({ end: removal });
135
+ let result;
136
+ try {
137
+ result = await workspace.exec(["sh", "-c", SCRIPT, "sh", `${web}/${pull.repo}.git`, pull.head, pull.base ?? "", CHECKOUT_DIR, `${web}/`, claim], { env: shellEnv(), stdin: Buffer.from(`${header}\n`, "utf8"), timeoutMs: options.timeoutMs ?? CHECKOUT_MS, ...(options.signal ? { signal: options.signal } : {}) });
138
+ }
139
+ catch (error) {
140
+ // Cut short (a stop, a lost claim): the claim's release removes what the fetch made (`held`).
141
+ if (options.signal?.aborted)
142
+ throw error;
143
+ return failed(`the fetch could not run: ${tail(String(error?.message ?? error), secrets)}`);
144
+ }
145
+ finally {
146
+ // The fetch is the token's one use: it goes now, not in an hour.
147
+ if (token && options.revoke)
148
+ await options.revoke(token).catch(() => { });
149
+ }
150
+ if (result.timedOut)
151
+ return failed(`the fetch took more than ${Math.round((options.timeoutMs ?? CHECKOUT_MS) / 1000)} s`);
152
+ if (result.code !== 0) {
153
+ const step = result.code === 10 ? "its folder could not be made" : result.code === 11 ? `${web}/${pull.repo} did not give its commits${token ? "" : `, fetched with no token: ${anonymous}`}` : result.code === 12 ? "its head could not be checked out" : `git ended with ${result.code ?? result.signal}`;
154
+ const said = tail(result.stderr, secrets);
155
+ return failed(said ? `${step}: ${said}` : step);
156
+ }
157
+ const mergeBase = Buffer.from(result.stdout).toString("utf8").trim();
158
+ return { note: checkoutNote(pull, /^[0-9a-f]{40}$/.test(mergeBase) ? mergeBase : undefined), end: removal };
159
+ }
160
+ /** The line a run with a checkout is told. */
161
+ function checkoutNote(pull, mergeBase) {
162
+ const base = pull.base === undefined
163
+ ? "Its base was not named by the event, so only the head is there."
164
+ : mergeBase === undefined
165
+ ? `Its base ${pull.base} is fetched too (ref pr/base), but no merge base was found within ${DEPTH * 2 ** DEEPENS} commits: diff against pr/base.`
166
+ : `Its base ${pull.base} (ref pr/base) and their merge base ${mergeBase} (ref pr/merge-base) are fetched too: read the change with \`git diff pr/merge-base pr/head\`.`;
167
+ return `The pull request ${pull.repo}#${pull.number} is checked out in ${CHECKOUT_DIR}/, detached at its head ${pull.head} (ref pr/head), by the server before this run began. ${base} It is a shallow clone, and no credential is kept in it.`;
168
+ }
169
+ /** The checkout a claim's spec makes (the pi and the CLI spec alike) for its launch: the server's GitHub App opened as the
170
+ * MCP step opens it (github-app.ts, its payload tag read only for a github trigger's run), its secrets held by the run's redactor `redact`, its removal by the spec's holds (`held`) from the
171
+ * moment the fetch starts, and `signal` (the claim's, a person's stop included) ending the fetch. */
172
+ export async function prCheckoutForClaim(deps, workspace, launch, redact, signal, held) {
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) });
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
+ }
@@ -60,6 +60,7 @@ export interface ReflectDeps {
60
60
  readonly name: string;
61
61
  readonly does: string;
62
62
  }[];
63
+ workflows?: false;
63
64
  }>;
64
65
  /** What the person said in the run, and a trigger's input, as the checks and the grader read them. */
65
66
  readonly asked: (runId: string) => Promise<{
@@ -76,10 +76,10 @@ export function createReflectHook(deps) {
76
76
  const close = async (rows) => ({ also: (await looked({ also: rows })).also.map((row) => cutRow(row, refuse)) });
77
77
  if (read === "unreadable")
78
78
  return close([droppedRow(null, "propose_failed", said.stopped(STOPPED.refuseUnread))]);
79
- const { active, tools, draftFor, described } = await deps.promptFacts(input.runId, input.agentId);
79
+ const { active, tools, draftFor, described, workflows } = await deps.promptFacts(input.runId, input.agentId);
80
80
  const deadlineMs = deps.deadlineMs ?? REFLECT_TIMEOUT_MS;
81
81
  const started = now();
82
- const end = await input.ask(reflectPrompt({ dir: LEARNED_DIR, active, tools, ...(draftFor?.length ? { draftFor, ...(described?.length ? { described } : {}) } : {}) }), { origin: "reflect", deadlineMs });
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 });
83
83
  // closeLearning: how the turn ended.
84
84
  if ("timedOut" in end)
85
85
  return close([droppedRow(null, "reflect_timeout", said.stopped(STOPPED.timedOut))]);
@@ -104,7 +104,7 @@ export function createReflectHook(deps) {
104
104
  // within the turn's own deadline; a re-ask that times out or fails leaves the first answer's drop.
105
105
  if (checked.state === "dropped" && checked.reason === "unparsed") {
106
106
  const left = deadlineMs - (now() - started);
107
- const again = left > 0 ? await input.ask(reflectAgain(checked.detail), { origin: "reflect", deadlineMs: left, again: true }) : undefined;
107
+ const again = left > 0 ? await input.ask(reflectAgain(checked.detail, ...(workflows === false ? [false] : [])), { origin: "reflect", deadlineMs: left, again: true }) : undefined;
108
108
  if (again && "ended" in again) {
109
109
  turn = turnOf(again.answer);
110
110
  checked = await checkOf(turn);
@@ -12,8 +12,9 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
12
12
  import { COMMAND_KINDS, endedReason } from "./commands.js";
13
13
  import { KINDS, withdrawnAnswers } from "./journal-kinds.js";
14
14
  import { journalEntries } from "./journal-reader.js";
15
- import { ClaimRefused, endedBy } from "./loop-contract.js";
15
+ import { ClaimRefused, stopEnd } from "./loop-contract.js";
16
16
  import { isFenced } from "./store-port.js";
17
+ import { clearWaitEnded } from "../browser-wait-ended.js";
17
18
  import { heldRedactor, processSecretRedactor } from "./redact.js";
18
19
  import { withLiveTicker } from "./live-ticker.js";
19
20
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
@@ -294,18 +295,23 @@ export function startRunner(options) {
294
295
  * the run row alone (runs.update, the same take in its one transaction), unless the end is a stop that may withdraw a
295
296
  * call (one waits, or the journal could not be read to say none does): that end is never written without its withdrawal,
296
297
  * so it throws EndNotWithdrawn and the run is left as it stands, not final, its stop untaken (endRefused retries it). A
297
- * lost claim (Fenced) writes neither.
298
+ * lost claim (Fenced) writes neither. A person's stop written on the row alone keeps no outcome 'stopped': with no end
299
+ * in its journal, a reopen would find no turn to follow (its next claim would read the run as never started), so it
300
+ * reads as a stop that is over (cancelled), as it read before a stop and a cancel were told apart.
298
301
  */
299
302
  const endRun = async (claim, given, take, withdrawnAs = "withdrawn") => {
300
303
  // Why the run ended, as its end and its row say it: cut of every secret the runner holds (an error's text may echo one).
301
304
  const data = { ...given, summary: redact(given.summary) };
302
305
  // Unknown means it may withdraw: false only once the journal was read and no call of it waits.
303
306
  let mayWithdraw = data.state === "stopped";
307
+ // A run whose journal holds no conversation never sent a request: its end carries a cost of $0, as a loop's end does.
308
+ let neverSent = false;
304
309
  try {
305
310
  const journal = store.journal(claim);
306
311
  const [root] = (await journal.scanConversations({}, 1, undefined, BACKGROUND_CONTEXT)).items;
307
312
  if (!root)
308
313
  mayWithdraw = false;
314
+ neverSent = !root;
309
315
  const writes = [];
310
316
  let conversationId = root?.id;
311
317
  if (conversationId === undefined) {
@@ -324,7 +330,7 @@ export function startRunner(options) {
324
330
  }
325
331
  const id = (await journal.mintId());
326
332
  writes.push({ type: "entry", value: { id, conversationId, kind: KINDS.end, data: data } });
327
- journal.stage({ run: { state: data.state, summary: data.summary }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
333
+ journal.stage({ run: { state: data.state, summary: data.summary, ...(data.outcome ? { outcome: data.outcome } : {}), ...(neverSent ? { costUsd: 0 } : {}) }, effect: id, ...(take.length ? { take: take.map((command) => ({ command, effect: id })) } : {}) });
328
334
  const result = await journal.commit([writes], () => { }, BACKGROUND_CONTEXT);
329
335
  if (result.stored !== 1)
330
336
  throw result.refused ?? new Error("the run's end was not stored");
@@ -334,14 +340,22 @@ export function startRunner(options) {
334
340
  throw error;
335
341
  if (mayWithdraw)
336
342
  throw new EndNotWithdrawn(claim.runId, error);
337
- await store.runs.update(claim, { state: data.state, summary: data.summary }, take.length ? { take } : undefined);
343
+ await store.runs.update(claim, { state: data.state, summary: data.summary, ...(data.outcome === "cancelled" ? { outcome: data.outcome } : {}) }, take.length ? { take } : undefined);
338
344
  }
345
+ // An ended run's Screen has no ended-while-waiting state to keep (browser-wait-ended.ts): its row goes with the end.
346
+ if (store.settings)
347
+ await clearWaitEnded(store.settings, claim.runId, claim.epoch).catch(() => undefined);
339
348
  };
340
349
  /** Ends the run under `claim` stopped on its untaken `stop` (or cancel) row (endRun). False when that end may withdraw a
341
350
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
342
351
  const endStopped = async (claim, stop) => {
343
352
  try {
344
- await endRun(claim, { state: "stopped", summary: endedBy(stop.kind === "cancel") }, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
353
+ // A learning run is never reopened (reopenableWhere), so its person's stop keeps no outcome 'stopped' (which would
354
+ // read it waiting on a message for good): it reads stopped, as the learning loop's own stop end leaves it.
355
+ const end = stopEnd(stop.kind === "cancel");
356
+ const launch = end.outcome === "stopped" ? await store.runs.launch?.(claim.runId).catch(() => undefined) : undefined;
357
+ const learning = launch?.body?.harness === "learning";
358
+ await endRun(claim, learning ? { state: end.state, summary: end.summary } : end, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
345
359
  return true;
346
360
  }
347
361
  catch (error) {
@@ -378,7 +392,9 @@ export function startRunner(options) {
378
392
  const why = message(refused.cause);
379
393
  if (tries >= endRetryCapFrom + endRetryAtCap) {
380
394
  emit({ type: "error", runId: claim.runId, step: "end", message: `run ${claim.runId} ended without withdrawing: journal unreadable or refusing (after ${tries} tries; the last: ${why})` });
381
- await store.runs.update(claim, { state: "stopped", summary: redact(endedBy(stop.kind === "cancel")) }, { take: [stop.id] });
395
+ // On its row alone, so no outcome 'stopped' (endRun): a run whose journal never took its end is never reopened.
396
+ const end = stopEnd(stop.kind === "cancel");
397
+ await store.runs.update(claim, { state: end.state, summary: redact(end.summary), ...(end.outcome === "cancelled" ? { outcome: end.outcome } : {}) }, { take: [stop.id] });
382
398
  await releaseStopped(claim, stop);
383
399
  return;
384
400
  }
@@ -388,6 +404,16 @@ export function startRunner(options) {
388
404
  await store.release(claim, { backoffUntil: now() + wait });
389
405
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "interrupted" });
390
406
  };
407
+ /** Whether the run under `claim` never started: its journal has no conversation yet, so no input of it went out. A
408
+ * journal that cannot be read says no (the claim's loop applies the stop as it would). */
409
+ const neverStarted = async (claim) => {
410
+ try {
411
+ return (await store.journal(claim).scanConversations({}, 1, undefined, BACKGROUND_CONTEXT)).items.length === 0;
412
+ }
413
+ catch {
414
+ return false;
415
+ }
416
+ };
391
417
  /** A claim of a run whose stopped end was refused (its untaken stop row has tries): it only ends the run, with no loop,
392
418
  * so no turn, model request or tool runs on a run that is stopping. */
393
419
  const endRetried = async (claim, stop) => {
@@ -451,6 +477,9 @@ export function startRunner(options) {
451
477
  if (row.refused === reason)
452
478
  emit({ type: "refused", runId: claim.runId, commandId: row.id, reason });
453
479
  }
480
+ // The run's end (a normal completion among them) leaves no browser-released message behind for a follow-up (browser-wait-ended.ts).
481
+ if (store.settings)
482
+ await clearWaitEnded(store.settings, claim.runId, claim.epoch).catch(() => undefined);
454
483
  }
455
484
  await store.flush();
456
485
  // A loop that ended interrupted with no stop asked of it (its Session closed itself) is released with a backoff that
@@ -575,14 +604,20 @@ export function startRunner(options) {
575
604
  const sentAt = clock.now();
576
605
  const weights = new Map();
577
606
  const claims = memory ? await claimByMemory(memory, free, weights) : await store.runs.claimMany(name, free, { leaseMs });
578
- // A run whose untaken stop row has tries failed to apply that stop before: its claim only ends it (endRetried). Either
579
- // source of tries counts: a refused stopped end (endRefused, released running) or a failed resume (resumeFailed's
580
- // store.retry, released parked). One read of those claims' rows, made only when the batch has a released run.
581
- const released = claims.filter((claim) => claim.from === "running" || claim.from === "parked");
582
- const rows = released.length ? await store.commandsOf(released.map((claim) => ({ runId: claim.runId, after: 0 }))) : new Map();
607
+ // A claim whose run must only end, with no loop (endRetried), so no turn, model request or tool runs on it:
608
+ // - a run stopped or cancelled while it had not started: claimed from queued, or claimed from running when an earlier
609
+ // claim was lost before the run's journal had anything (its runner gone before it wrote a word). Nothing of it
610
+ // starts now, not even its first input: a loop started first would send that input before the stop reached it;
611
+ // - a run whose untaken stop row has tries, which failed to apply that stop before. Either source of tries counts: a
612
+ // refused stopped end (endRefused, released running) or a failed resume (resumeFailed's store.retry, released
613
+ // parked).
614
+ // One read of those claims' rows, made only when the batch has a queued or a released run.
615
+ const reread = claims.filter((claim) => claim.from === "queued" || claim.from === "running" || claim.from === "parked");
616
+ const rows = reread.length ? await store.commandsOf(reread.map((claim) => ({ runId: claim.runId, after: 0 }))) : new Map();
583
617
  for (const claim of claims) {
584
618
  const stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
585
- if (stop && stop.tries > 0 && !closed && !killed && !runs.has(claim.runId)) {
619
+ const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))));
620
+ if (stop && endsOnly && !closed && !killed && !runs.has(claim.runId)) {
586
621
  const ending = endRetried(claim, stop);
587
622
  endings.add(ending);
588
623
  void ending.finally(() => endings.delete(ending));
@@ -3,6 +3,10 @@ type Held = {
3
3
  readonly tools?: {
4
4
  end(): Promise<void>;
5
5
  };
6
+ /** The run's checkout of its pull request (pr-checkout.ts), removed from its folder while the Workspace still answers. */
7
+ readonly checkout?: {
8
+ end(): Promise<void>;
9
+ } | undefined;
6
10
  readonly computer?: {
7
11
  release(): Promise<void>;
8
12
  };
@@ -33,9 +37,10 @@ export declare class SpecHolds {
33
37
  logTo(log: (line: string) => void): void;
34
38
  /** `parts`, held from now until the release. */
35
39
  hold(parts: Held): void;
36
- /** Everything held let go, once: the tools' end (background processes ended, scratch swept), the computer, the Archil
37
- * mount credential (idempotent: the computer's release revokes it too), the Workspace's end, the CLI's scratch, then
38
- * the claim's keys where they are held. A second call waits for the first and does nothing more. */
40
+ /** Everything held let go, once: the tools' end (background processes ended, scratch swept), the pull request's
41
+ * checkout removed, the computer, the Archil mount credential (idempotent: the computer's release revokes it too), the
42
+ * Workspace's end, the CLI's scratch, then the claim's keys where they are held. A second call waits for the first and
43
+ * does nothing more. */
39
44
  release(): Promise<void>;
40
45
  /** What the spec would have handed the loop, let go: only a build that throws calls it. */
41
46
  releasePassed(): void;