@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
@@ -7,7 +7,7 @@ import { llmTiers, nodeTiers, thinkingLevel, TIERS, tierModelOf, workflowNodes }
7
7
  import { firstMessage } from "../run-manifest.js";
8
8
  import { learningStartOf, seedFailed } from "../run-launch.js";
9
9
  import { isObject } from "../validate.js";
10
- import { deniedText, noApproverText, runGate } from "../tool-gate.js";
10
+ import { deniedText, mcpServersOf, noApproverText, runGate } from "../tool-gate.js";
11
11
  import { loadToolSettings, recheckPlane, TOOL_PLANE_ENV } from "../tool-plane.js";
12
12
  import { readApprovers } from "../server-approvers.js";
13
13
  import { ASK_TOOL, askPerson, toolOf } from "../tools.js";
@@ -30,19 +30,22 @@ import { runTools, withKindTools } from "../workspace/run-tools.js";
30
30
  import { copyRunFiles } from "../uploads.js";
31
31
  import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
32
32
  import { UNREADABLE_SIGN_IN } from "../run-view.js";
33
- import { claimSecrets, learnedDecisionKeys, tierModelKeys, withModelKeys } from "./claim-secrets.js";
33
+ import { claimSecrets, learnedDecisionKeys, savedModelKeys, tierModelKeys, withModelKeys } from "./claim-secrets.js";
34
34
  import { mcpForClaim } from "./mcp-run.js";
35
35
  import { hostLifecycle } from "./adapter-loop.js";
36
36
  import { piAdapter } from "./adapters/pi.js";
37
- import { entriesOf } from "./loop.js";
37
+ import { agentEntriesOf } from "./loop.js";
38
+ import { SUBAGENT_TIERS, SUBAGENT_TOOL, subagentTool } from "./subagent.js";
39
+ import { wireName } from "../catalog.js";
38
40
  import { ClaimRefused } from "./loop-contract.js";
39
41
  import { runMetrics } from "./metrics.js";
40
42
  import { specBuilt } from "./spec-holds.js";
41
43
  import { archilClaim, MOUNT_TTL_MS } from "../workspace/archil-claim.js";
42
44
  import { loadArchilSettings } from "../archil-settings.js";
43
- import { imageWaitWords } from "../workspace/computer-deps.js";
45
+ import { computerReadyWords, imageWaitWords } from "../workspace/computer-deps.js";
44
46
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
45
47
  import { githubAppAccess } from "./github-app.js";
48
+ import { prCheckoutForClaim } from "./pr-checkout.js";
46
49
  import { holdStored, storeSecrets } from "./store-secrets.js";
47
50
  import { bashPolicyOf } from "../bash-read-only.js";
48
51
  /** The wires pi speaks on the runner: main's pi's (provider.ts), Anthropic's Messages and OpenAI's Responses. */
@@ -60,7 +63,8 @@ export const browserListed = (host, granted) => BROWSER_ON_RUNNER && host.ledger
60
63
  * model's tier is held and booked at the tier, as main's calculateCost does). `api` is the proxy's shape, for the
61
64
  * overhead its provider adds; the output ceiling is the route's when it carries one, else none. */
62
65
  export function capModelOf(route) {
63
- const cost = route.cost;
66
+ // A model serve has no price for carries placeholder zeros: the cap reads it as unknown (null), never as $0.
67
+ const cost = route.unpriced ? undefined : route.cost;
64
68
  const price = cost
65
69
  ? {
66
70
  input: cost.input,
@@ -73,6 +77,11 @@ export function capModelOf(route) {
73
77
  // The cap reads a request's provider overhead by the route's own wire (providerInputOverhead).
74
78
  return { id: route.model, api: route.provider.api, price, outputCeiling: route.outputCeiling ?? null };
75
79
  }
80
+ /** The key of a subagent tier's route in a run's tier routes and proxies (a key of its own, never a learned workflow's
81
+ * tier: those nodes keep their own route and fallback). */
82
+ const SUBAGENT_ROUTE = "subagent-";
83
+ const subagentRoute = (tier) => `${SUBAGENT_ROUTE}${tier}`;
84
+ const isSubagentRoute = (key) => key.startsWith(SUBAGENT_ROUTE);
76
85
  /** What the runner routes a claimed run on: the launch's model as its start pinned it, sent as pinned, with the
77
86
  * revision's own ref beside it (main prices a gateway's id by the provider that ref names); the revision's ref alone
78
87
  * when the start pinned none. Never the pin's provider and id joined into a ref: a gateway refuses the joined id, and
@@ -80,14 +89,16 @@ export function capModelOf(route) {
80
89
  export function modelAskOf(pinned, ref) {
81
90
  return pinned ? { pinned, ...(ref ? { ref } : {}) } : ref;
82
91
  }
83
- export async function adapterRunGate(store, claim, revision, root, shell) {
92
+ export async function adapterRunGate(store, claim, revision, root, shell, mcpServers = []) {
84
93
  let current = await storeSettings(store);
85
94
  const approvers = await readApprovers(store.settings);
86
95
  // A Workspace's paths are in the run's folder: its folder named as a computer names it, for the gate's path checks.
87
96
  const folder = typeof root === "string" ? root : COMPUTER_ROOT;
88
97
  // Where the run's shell is (run-tools.ts shell): with no computer, a tool no setting names takes the kernel's ruled
89
- // default (tool-gate.ts defaultPermission): bash asks first, the background tools are refused.
90
- const gate = runGate({ root: folder, work: folder, ...(shell === undefined ? {} : { computer: shell === "computer" }) }, claim.runId, revision, () => current, approvers);
98
+ // default (tool-gate.ts defaultPermission): bash asks first, the background tools are refused. The run's MCP servers
99
+ // (mcpServersOf its grants), so a harness naming an MCP tool its own way (OpenCode's `<server>_<tool>`) is held to that
100
+ // tool's settings, never to a table tool's of the same shape.
101
+ const gate = runGate({ root: folder, work: folder, ...(shell === undefined ? {} : { computer: shell === "computer" }), mcpServers }, claim.runId, revision, () => current, approvers);
91
102
  // The run's learned workflows, once its spec has read them (learn): a learned_workflow call is asked about its MCP nodes.
92
103
  let learned = [];
93
104
  const decide = async (call, options = {}) => {
@@ -175,7 +186,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
175
186
  // The run's mode is the server's: Mode 2 where its Archil settings are saved (archil-settings.ts), the run's folder then
176
187
  // on the claim's Archil disk (archil-claim.ts: its keys from the store's sealed rows, under the runner's seal key, in this
177
188
  // claim's memory only); else Mode 1, the run's local folder. The same for the pi and the CLI spec.
178
- const archilSettings = await loadArchilSettings(deps.store);
189
+ const archilSettings = await loadArchilSettings(deps.store, deps.env);
179
190
  const mode = archilSettings === undefined ? 1 : 2;
180
191
  const archil = archilSettings === undefined
181
192
  ? undefined
@@ -186,7 +197,8 @@ async function adapterSpec(launch, run, deps, claim, holds) {
186
197
  // The mint is lazy (archil-claim.ts token(), k2's run-tools.ts): only a mounting computer asks for it, so a Mode 2 run
187
198
  // with no computer makes no control-plane call. mountControl (a test's loopback control-plane fake) is spread into the
188
199
  // mount, so no test reaches the real control plane. MOUNT_TTL_MS is the credential's safety net (its computer's 24 h bound), not its lifetime.
189
- : await archilClaim({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
200
+ // The disk is the run's (run-disk.ts): its launch record's, else its agent's, made on its first run that needs one.
201
+ : await archilClaim({ settings: archilSettings, keys: deps.store.sealedKeys, sealKey: deps.sealKey, signal: run.signal ?? new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: runRow.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store: deps.store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
190
202
  // Each resource is held the moment it exists (spec-holds.ts): a throw after it lets it go.
191
203
  holds.hold({ archil });
192
204
  // The run's Workspace at the claim: Mode 1 the run's local folder (made here, the server's start made it before); Mode 2
@@ -199,20 +211,29 @@ async function adapterSpec(launch, run, deps, claim, holds) {
199
211
  // per run (uploads.ts copyRunFiles); a copy that fails ends the run failed, saying why.
200
212
  if (launch.files?.length)
201
213
  await copyRunFiles(deps.data, claim.runId, ws.workspace, launch.files);
214
+ // The pull request's checkout, when the revision asks for one (pr-checkout.ts): the server's own fetch before the first
215
+ // turn, with the GitHub App's read-only token for that one repository (or none); the run is told what it holds, or why
216
+ // there is none. Held from the fetch's start, so the release (after the tools' end) removes it however the claim ends; a
217
+ // person's stop ends the fetch at once (run.stopped).
218
+ const checkout = body.checkout === "pull_request" ? await prCheckoutForClaim(deps, ws.workspace, launch, cut, run.stopped ?? run.signal, (part) => holds.hold({ checkout: part })) : undefined;
219
+ holds.hold({ checkout });
202
220
  // The run's MCP for this claim (mcp-run.ts mcpForClaim): its pin made at the first claim or read as written, its
203
221
  // credentials opened under the server's seal key into this claim's memory, one gateway for the claim. First, before
204
222
  // anything the spec would have to let go: a refusal (a pin that cannot be made, a pinned meta tool) ends the run in its
205
223
  // words before the session opens. The seal key is the runner's own (deps.sealKey), not re-read from the environment.
206
- const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold: (values) => cut.hold(values) }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}) });
224
+ // A credential the claim opens mid-run (a GitHub App token, a per_run server's handed one) joins the run's redactor.
225
+ const hold = (values) => cut.hold(values);
226
+ const mcp = await mcpForClaim({ claim, store: deps.store, sealKey: deps.sealKey, grants: granted, harness: run.harness, work: () => ws.workspace, launchInput: launch.input, hold, githubAppAccess: (store, key, input) => githubAppAccess(store, key, input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub: launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github", hold }), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}) });
207
227
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
208
228
  holds.hold({ passed: mcp });
209
229
  // The run's computer, from the one shared claim-time function (the CLI spec takes the same): none for a runner place, a
210
230
  // Docker container for a sandbox, under the claim's epoch (the one fence). It throws computer_unavailable (nothing made)
211
231
  // when the computer cannot be had: the run fails in its words.
212
- const computer = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, revisionId: runRow.revisionId, place: launch.place, ...(launch.computer !== undefined ? { computer: launch.computer } : {}) }, deps.store,
232
+ const computer = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, agentId: runRow.agentId, revisionId: runRow.revisionId, place: launch.place, ...(launch.computer !== undefined ? { computer: launch.computer } : {}) }, deps.store,
213
233
  // revokeMount removes the run's Archil mount credential when the computer is released (and if a start fails after a mint);
214
- // the run's end revokes it too (below), so it goes on every outcome even when no computer is made. Idempotent.
215
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, ...(archil ? { revokeMount: () => archil.revoke() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)) } : {}) });
234
+ // the run's end revokes it too (below), so it goes on every outcome even when no computer is made. Idempotent. What
235
+ // became of the agent's own computer (a persistent setting) is said on the run's timeline.
236
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, ...(archil ? { revokeMount: () => archil.revoke() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
216
237
  // The run's shell is its computer's (600 s) where one mounts its folder; with none, Archil's serverless exec in Mode 2
217
238
  // (295 s), and in Mode 1 none at all: no bash family, its folder being one of this server's own (run-tools.ts).
218
239
  // A desktop's or a phone's hold (the person's take-over) wraps its ports: a call made while the person holds it waits,
@@ -249,10 +270,39 @@ async function adapterSpec(launch, run, deps, claim, holds) {
249
270
  // refuses it (runnable.ts). pi only.
250
271
  // - the browser's durable extension, when the run gets one (bindNonHandTools, below, before the session opens).
251
272
  const native = granted.includes(ASK_TOOL) ? [defineExtension({ name: "ask_person", tools: [askPerson] })] : [];
273
+ // pi-native tools in the session's own extension (PiAdapterOptions.tools): the subagent tool, pushed below.
274
+ const piTools = [];
275
+ // A run granted subagent (runner/subagent.ts): the model of each of its tiers, the revision's own (modelTiers) else the
276
+ // host's for the tier (AGENT_MODEL_FAST, AGENT_MODEL_STRONG), each on a route of its own (its proxy on the session's
277
+ // booking, adapters/pi.ts tiers). A tier with neither is the agent's own model, as a learned workflow's node of it runs
278
+ // on the run's. A tier no route can be made for here is no failure of the run: a call on it answers why. A tier's model may be another
279
+ // provider's than the run's own, whose key claimSecrets never opened (it scopes the claim's keys to the run's model): so
280
+ // its route reads every model key the server holds (savedModelKeys). Those reach the tier's proxy alone, as its
281
+ // credential, never the run's tools (toolEnv).
282
+ // Each is in tierRoutes under its own key (subagentRoute: never a learned workflow's tier, whose nodes keep their own
283
+ // routes and fallback), on a proxy of its own that names that key on each request, so the cap prices a child's
284
+ // requests as that route books them.
285
+ const tierWhy = new Map();
286
+ if (revision.kind === "agentic" && granted.includes(SUBAGENT_TOOL)) {
287
+ const savedKeys = await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
288
+ holdClaimed(cut, savedKeys);
289
+ const tierEnv = withModelKeys(deps.env, { ...savedKeys, ...toolEnv });
290
+ for (const tier of SUBAGENT_TIERS) {
291
+ if (body.modelTiers?.[tier] === undefined && tierModelOf(tierEnv, tier) === undefined)
292
+ continue;
293
+ try {
294
+ tierRoutes.set(subagentRoute(tier), await deps.routeOf(body.modelTiers?.[tier], tierEnv, tier, PI_WIRES, undefined, cut));
295
+ }
296
+ catch (error) {
297
+ tierWhy.set(tier, cut(error instanceof Error ? error.message : String(error)));
298
+ }
299
+ }
300
+ }
252
301
  const adapter = piAdapter({
253
302
  run,
254
303
  // Read when the session opens (pi.ts), so the browser's extension pushed by bindNonHandTools below is in it.
255
304
  extensions: native,
305
+ tools: piTools,
256
306
  model: route.model,
257
307
  provider: route.provider,
258
308
  redact: cut,
@@ -267,7 +317,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
267
317
  const root = runFolder(deps.data, runRow.agentId, claim.runId);
268
318
  // The gate names the run's folder by its Workspace (Mode 2: its folder on the run's disk, never this machine's folder at
269
319
  // the same path), for its path checks; it reads nothing in it.
270
- const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace, tools.shell);
320
+ const gate = await adapterRunGate(deps.store, claim, revision, ws.workspace, tools.shell, mcpServersOf(granted));
271
321
  // The run's one cap, as the loop's runCap reads it (adapter-loop.ts RunCapConfig): the launch's cap figure (undefined
272
322
  // uncapped — every paid request still books through the one cap), the run's model priced WITH tiers, strict where the
273
323
  // launch says. The loop builds the kernel runCap from these over the run's own sessions (its model requests, its paid
@@ -323,6 +373,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
323
373
  own: Object.keys(revisionRow.skills ?? {}),
324
374
  shown: async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(deps.store, deps.sealKey, deps.data)), { local: true }),
325
375
  log,
376
+ ...(start.notesOnly ? { workflows: false } : {}),
326
377
  })
327
378
  : undefined;
328
379
  // The decision keys its learned workflows' typed questions need (claim-secrets.ts learnedDecisionKeys), read once the lay
@@ -365,10 +416,10 @@ async function adapterSpec(launch, run, deps, claim, holds) {
365
416
  const handTools = tools.hostTools(withKindTools(granted, tools), results);
366
417
  // The non-hand tools run on the claim's keys (host.env), so a vendor's error may echo one: each answer, and a throw's
367
418
  // words, pass the run's one redactor before the harness, the model or the record has them.
368
- const tiers = new Map([...[...tierRoutes].map(([tier, { model }]) => [tier, { model }]), ...[...tierUnreachable].map(([tier, why]) => [tier, { why }])]);
419
+ const tiers = new Map([...[...tierRoutes].filter(([tier]) => !isSubagentRoute(tier)).map(([tier, { model }]) => [tier, { model }]), ...[...tierUnreachable].map(([tier, why]) => [tier, { why }])]);
369
420
  // The gate asks a learned_workflow call about its workflow's MCP nodes (adapterRunGate).
370
421
  gate.learn(workflows);
371
- const nonHandTools = (await bindNonHandTools(host, revision.kind, granted, run, context, results, root, launch.plane, workflows, native, gate.permissions, tiers, mcp)).map((tool) => answersCut(tool, cut));
422
+ const nonHandTools = (await bindNonHandTools(host, revision.kind, granted, run, context, results, root, launch.plane, workflows, native, gate.permissions, tiers, mcp, () => route.model)).map((tool) => answersCut(tool, cut));
372
423
  const sessionTools = [...handTools, ...nonHandTools];
373
424
  // The run's system prompt, as main's per-run process builds it (app.ts): the environment line first (environment.ts, as
374
425
  // pi installs it before every other section), then the revision's instructions with what the agent learned laid in
@@ -379,7 +430,32 @@ async function adapterSpec(launch, run, deps, claim, holds) {
379
430
  const laid = start && !seedFailed(start) ? laidLearned(body.instructions ?? "", start.section) : (body.instructions ?? "");
380
431
  const instructions = await promptOf(laid, [...Object.keys(body.skills ?? {}), ...(seedLaid?.skills ?? [])], ws.workspace, { onDemand: readsFiles(granted) });
381
432
  const guidance = effortGuidance(launch.effort);
382
- const system = [environmentLine(), instructions, guidance].filter((line) => Boolean(line));
433
+ const system = [environmentLine(), checkout?.note, instructions, guidance].filter((line) => Boolean(line));
434
+ // The subagent tool, one of the session's own tools (no extension of its own): a child's tools are a subset of the
435
+ // revision's grants (each by its session name: an MCP tool's wire name, the browser's registrations), its model the
436
+ // agent's own or one of the tiers resolved above.
437
+ if (revision.kind === "agentic" && granted.includes(SUBAGENT_TOOL)) {
438
+ const browserNames = native.filter((extension) => extension.name !== "ask_person").flatMap((extension) => (extension.tools ?? []).map((tool) => tool.name));
439
+ piTools.push(subagentTool({
440
+ granted,
441
+ sessionNames: (catalog) => (catalog === BROWSER_TOOL ? browserNames : [wireName(catalog)]),
442
+ tier: (tier) => {
443
+ const why = tierWhy.get(tier);
444
+ if (why !== undefined)
445
+ return { why };
446
+ // A tier with no model of its own (no model_tiers, no AGENT_MODEL_<TIER>): the agent's own model.
447
+ const at = tierRoutes.get(subagentRoute(tier));
448
+ if (!at)
449
+ return { ref: { provider: PORT_PROVIDER, modelId: route.model } };
450
+ // A capped run never sends a request it cannot price: an unpriced tier refuses the call, and the run goes on.
451
+ if (at.unpriced && launch.maxCostUsd !== undefined)
452
+ return { why: `${at.model} has no known price here, so this run's cost cap cannot hold its requests.` };
453
+ return { ref: { provider: tierProvider(subagentRoute(tier)), modelId: at.model } };
454
+ },
455
+ preamble: environmentLine(),
456
+ ...(revision.body.maxToolCalls !== undefined ? { toolCalls: revision.body.maxToolCalls } : {}),
457
+ }));
458
+ }
383
459
  // The level pi thinks at: the launch's effort (the run's own, else its revision's, else the host's), every level pi's
384
460
  // agent takes; none, pi's default.
385
461
  const thinking = thinkingLevel(launch.effort);
@@ -433,11 +509,15 @@ async function adapterSpec(launch, run, deps, claim, holds) {
433
509
  // The tool host's install lifecycle (its bindings' onConversation/beforeResume/beforeRelease), run by the adapter loop.
434
510
  lifecycle: life,
435
511
  agentId: runRow.agentId,
512
+ // The run's desktop or phone and the person's hold on it, as the claim made them: the loop shows it up and applies a
513
+ // take-over and a hand-back to it.
514
+ ...(computer.held ? { computer: computer.held } : {}),
436
515
  workRoot: root,
437
516
  // The end's metrics and cost, from the run's journal, as the old per-run end path read them (metrics.ts runMetrics =
438
517
  // runs.ts storedMetrics/costOf). A pi run adds its effort, no model (metrics.ts).
439
518
  endPatch: async () => {
440
- const entries = await entriesOf(deps.journal(claim), ROOT_CONVERSATION_ID, context);
519
+ // The root's entries and every conversation a task of the run owns (a subagent's): a child's requests are the run's.
520
+ const entries = await agentEntriesOf(deps.journal(claim), context);
441
521
  const { metrics, costUsd } = runMetrics(entries, { ...(launch.effort !== undefined ? { effort: launch.effort } : {}) });
442
522
  // Its paid tool calls (a Parallel search's, a monid call's, a person's browser time), booked on the run's one ledger
443
523
  // (the paid tool calls on its cap, in their own session, not on the root), are the run's cost too.
@@ -453,7 +533,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
453
533
  };
454
534
  }
455
535
  /** The host-tool ctx a non-hand tool is wrapped with (host-tools.ts hostToolOf): the run's own Harness (its commit,
456
- * snapshot, conversation and task reads), the results map, and the run's folder as the api env's cwd (a tool reads no
536
+ * snapshot and task reads), the results map, and the run's folder as the api env's cwd (a tool reads no
457
537
  * file environment, so an error names a path relative to it). Shared by the pi spec's bindNonHandTools and the CLI spec's
458
538
  * learned_workflow. */
459
539
  export function hostToolCtxOf(run, context, results, root) {
@@ -463,7 +543,6 @@ export function hostToolCtxOf(run, context, results, root) {
463
543
  env: async () => ({ cwd: root }),
464
544
  commit: (change, at, options) => run.harness.commit(change, at, options),
465
545
  snapshot: ((...args) => Reflect.apply(run.harness.snapshot, run.harness, args)),
466
- conversation: ((id, at) => run.harness.conversation(id, at)),
467
546
  waitForTask: (id, at) => run.harness.waitForTask(id, at),
468
547
  agent: async (at) => {
469
548
  const conversation = await run.harness.conversation(ROOT_CONVERSATION_ID, at);
@@ -537,7 +616,7 @@ export async function learnedWorkflowHostTool(opts) {
537
616
  throw new Error(`the run's ${tier} model could not be reached: ${model.why}`);
538
617
  return { provider: tierProvider(tier), modelId: model.model };
539
618
  };
540
- const tool = learnedWorkflowTool({ workflows: flows, granted: opts.granted, ...(opts.plane ? { plane: opts.plane } : {}), env: opts.env, work: opts.work, models: tieredModels(byProvider), modelOf, policy: opts.permissions.policy, denyFrom: opts.permissions.denyFrom, refresh: opts.permissions.refresh, decide: opts.permissions.decide, mcpTools });
619
+ const tool = learnedWorkflowTool({ workflows: flows, granted: opts.granted, ...(opts.plane ? { plane: opts.plane } : {}), env: opts.env, work: opts.work, models: tieredModels(byProvider), modelOf, policy: opts.permissions.policy, denyFrom: opts.permissions.denyFrom, refresh: opts.permissions.refresh, decide: opts.permissions.decide, mcpTools, ...(opts.modelName ? { modelName: opts.modelName } : {}) });
541
620
  return hostToolOf(LEARNED_WORKFLOW_TOOL, tool, opts.ctx) ?? undefined;
542
621
  }
543
622
  /** The run's non-hand tools as HostTool[], bound through the ToolHost seam and wrapped as the hands are (host-tools.ts
@@ -634,7 +713,7 @@ export async function webHostTools(host, granted, ctx) {
634
713
  }
635
714
  return tools;
636
715
  }
637
- async function bindNonHandTools(host, kind, granted, run, context, results, root, plane, workflows, native, permissions, tiers, mcp) {
716
+ async function bindNonHandTools(host, kind, granted, run, context, results, root, plane, workflows, native, permissions, tiers, mcp, modelName) {
638
717
  // Fail closed (browserListed): the browser binds only on the native route (BROWSER_ON_RUNNER) and with the claim's
639
718
  // one-ledger booking on its ToolHost (host.ledger.paid); otherwise its extension is not installed. learned_workflow
640
719
  // binds below with no web tool, so a learned run with no web tool still lists it.
@@ -647,7 +726,7 @@ async function bindNonHandTools(host, kind, granted, run, context, results, root
647
726
  // the session's tools the harness is told of: its model nodes run on the session's proxied models (run.ledger.models),
648
727
  // each a request on the run's one route labelled learned_workflow. The agent's scoped keys (host.env) are its call
649
728
  // nodes'.
650
- const learned = await learnedWorkflowHostTool({ run, kind, granted, plane, env: host.env, work: root, workflows, permissions, ctx, tiers, ...(mcp ? { mcp } : {}) });
729
+ const learned = await learnedWorkflowHostTool({ run, kind, granted, plane, env: host.env, work: root, workflows, permissions, ctx, tiers, ...(mcp ? { mcp } : {}), ...(modelName ? { modelName } : {}) });
651
730
  if (learned)
652
731
  tools.push(learned);
653
732
  // The browser (tl-browser), on pi's native route: tools.ts's own binding on this run's ToolHost (its store, claim and seal
@@ -1,8 +1,8 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import type { Models } from "@earendil-works/pi-ai";
3
- import { type Extension, type Harness, type Registry } from "@earendil-works/pi-durable";
3
+ import { type Extension, type Harness, type Registry, type ToolRegistration } from "@earendil-works/pi-durable";
4
4
  import { type AgentAdapter, type SessionIO, type SessionPort, type Wire } from "@parcha/agentrun-kernel";
5
- import { type ProviderPolicy } from "@parcha/agentrun-kernel/host";
5
+ import { type ModelProxy, type ProviderPolicy } from "@parcha/agentrun-kernel/host";
6
6
  import { CALL_REFUSED } from "../../timeline/index.js";
7
7
  /** What the adapter loop lends pi for one claim: the run's Harness, its registry, and where pi's models go. */
8
8
  export interface PiRun {
@@ -22,6 +22,8 @@ export interface PreIntentCall {
22
22
  /** The tool calls the call's conversation made before it, at most `upTo`, read from its committed entries (tool-budget.ts
23
23
  * countCalls), for the gate's tool-call budget: pi's model-issued calls only, never a nested call or a CLI's. */
24
24
  readonly callsBefore?: (upTo: number) => Promise<number>;
25
+ /** The call's conversation's own tool-call budget (tool-budget.ts ConversationToolBudget, a subagent's), if it has one. */
26
+ readonly ownBudget?: () => Promise<number | undefined>;
25
27
  /** A call a running tool made (pi's nested call), part of a call already let through: the cap's wrap-up never refuses
26
28
  * one (tool-budget.ts), so a tool in flight is never cut short. */
27
29
  readonly nested?: true;
@@ -75,6 +77,10 @@ export interface PiAdapterOptions {
75
77
  * claim's Harness. Their tools pass the session's gate (its beforeTool hook), and every conversation they open takes
76
78
  * its model from the root's agent, through this session's proxy and its booking. */
77
79
  readonly extensions?: readonly Extension[];
80
+ /** pi-native tools the session's own extension carries beside its host tools (the subagent tool: runner/subagent.ts):
81
+ * pi's own tool tasks, under the session's gate like every call. Read when the session opens. A conversation one of
82
+ * them opens keeps the session's extension, so its calls pass the same gate; its own `tools` say which it is offered. */
83
+ readonly tools?: readonly ToolRegistration[];
78
84
  /** The run's models of other tiers than its own (a learned workflow's node of a tier: AGENT_MODEL_FAST,
79
85
  * AGENT_MODEL_STRONG), by tier, each a model route as the session's is: read when the session opens, each on a proxy of
80
86
  * its own beside the session's (its origin, credential, price and fetch), on the session's booking (io.models), so its
@@ -88,6 +94,8 @@ export type TierModel = Pick<PiAdapterOptions, "provider" | "model" | "like" | "
88
94
  /** The tier proxies a session holds (openTierProxies): each tier's port for a side request under `label`, and their close. */
89
95
  export interface TierProxies {
90
96
  port(label: string, tier: string): SessionPort | undefined;
97
+ /** Each tier, its route and its proxy: a subagent's child on the tier is sent there on the proxy's own key. */
98
+ readonly each: readonly (readonly [string, TierModel, ModelProxy])[];
91
99
  close(): Promise<void>;
92
100
  }
93
101
  /** A run's models of other tiers than its own (a learned workflow's node of a tier: AGENT_MODEL_FAST, AGENT_MODEL_STRONG),
@@ -96,7 +104,7 @@ export interface TierProxies {
96
104
  * keys, AdapterSession.port's `tier`), sent by pi-ai's client of the tier model's own wire (port-models.ts), so a tier
97
105
  * proxy speaks its model's route (model-route.ts routeOf, its translation fetch for a model of neither wire), never the
98
106
  * harness's. One that fails to start closes those started. */
99
- export declare function openTierProxies(tiers: ReadonlyMap<string, TierModel>, hooks: SessionIO["models"], redact?: (text: string) => string): Promise<TierProxies>;
107
+ export declare function openTierProxies(tiers: ReadonlyMap<string, TierModel>, hooks: SessionIO["models"], redact?: (text: string) => string, tools?: readonly string[]): Promise<TierProxies>;
100
108
  /** The session proxy's policy on Messages: claude-agent's (no fork), with pi's tools, the host's own names (`tools`), as
101
109
  * the names its client offers by themselves (its builtins). The CLI's own `mcp__hands__` prefix is not pi's: under it
102
110
  * every one of pi's tool definitions would be dropped and the model offered none. Every other tool definition is
@@ -6,10 +6,10 @@ import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
6
6
  import { startModelProxy } from "@parcha/agentrun-kernel/host";
7
7
  import { randomBytes } from "node:crypto";
8
8
  import { DEFAULT_HARNESS } from "../../harness.js";
9
- import { sessionProvider } from "../../port-models.js";
9
+ import { sessionProvider, tierProvider } from "../../port-models.js";
10
10
  import { KINDS } from "../journal-kinds.js";
11
11
  import { CALL_REFUSED } from "../../timeline/index.js";
12
- import { countCalls } from "../../tool-budget.js";
12
+ import { ConversationToolBudget, countCalls } from "../../tool-budget.js";
13
13
  const PROVIDER = "agentrun-session";
14
14
  const INPUT_REQUEST = "agentrun:input";
15
15
  /** pi as an AgentAdapter for one claim's run. */
@@ -22,12 +22,11 @@ export function piAdapter(options) {
22
22
  open: (spec, io) => openPi(options, spec, io),
23
23
  };
24
24
  }
25
- /** The names of the run's pi-native extensions' tools (options.extensions): the model is offered them beside the session's
25
+ /** The names of the run's pi-native tools (options.extensions' and options.tools): the model is offered them beside the session's
26
26
  * own (so it may call one), and pi runs it. Offered and run by one mechanism; sessionOn never also piTool-wraps a session
27
27
  * tool a native extension already owns, so the name is in the request's tools exactly once. */
28
- const nativeToolNames = (options) => (options.extensions ?? []).flatMap((extension) => extension.tools ?? []).map((tool) => tool.name);
28
+ const nativeToolNames = (options) => [...(options.extensions ?? []).flatMap((extension) => extension.tools ?? []), ...(options.tools ?? [])].map((tool) => tool.name);
29
29
  async function openPi(options, spec, io) {
30
- const { model } = options;
31
30
  const context = withAbortSignal(io.signal, BACKGROUND_CONTEXT);
32
31
  // The session's route: pi-ai's requests reach the provider only through this proxy, which admits and books each one
33
32
  // through the runner's booking (io.models).
@@ -36,7 +35,8 @@ async function openPi(options, spec, io) {
36
35
  // the runner's process open.
37
36
  let tiers;
38
37
  try {
39
- tiers = await openTierProxies(options.tiers ?? new Map(), io.models, options.redact);
38
+ // A tier's proxy admits the session's tools too: a subagent's child on the tier offers them (runner/subagent.ts).
39
+ tiers = await openTierProxies(options.tiers ?? new Map(), io.models, options.redact, [...spec.tools.map((tool) => tool.name), ...nativeToolNames(options)]);
40
40
  return await sessionOn(proxy, options, spec, io, context, tiers);
41
41
  }
42
42
  catch (error) {
@@ -69,7 +69,7 @@ async function routeProxy(route, hooks, tools, redact, tier) {
69
69
  * keys, AdapterSession.port's `tier`), sent by pi-ai's client of the tier model's own wire (port-models.ts), so a tier
70
70
  * proxy speaks its model's route (model-route.ts routeOf, its translation fetch for a model of neither wire), never the
71
71
  * harness's. One that fails to start closes those started. */
72
- export async function openTierProxies(tiers, hooks, redact) {
72
+ export async function openTierProxies(tiers, hooks, redact, tools = []) {
73
73
  const open = new Map();
74
74
  const close = async () => {
75
75
  for (const { proxy } of open.values())
@@ -77,7 +77,7 @@ export async function openTierProxies(tiers, hooks, redact) {
77
77
  };
78
78
  try {
79
79
  for (const [tier, route] of tiers)
80
- open.set(tier, { proxy: await routeProxy(route, hooks, [], redact, tier), route });
80
+ open.set(tier, { proxy: await routeProxy(route, hooks, tools, redact, tier), route });
81
81
  }
82
82
  catch (error) {
83
83
  await close();
@@ -88,6 +88,7 @@ export async function openTierProxies(tiers, hooks, redact) {
88
88
  const at = open.get(tier);
89
89
  return at ? { url: at.proxy.url, key: at.proxy.sideKey(label), model: at.route.model, api: at.route.provider.api } : undefined;
90
90
  },
91
+ each: [...open].map(([tier, { proxy, route }]) => [tier, route, proxy]),
91
92
  close,
92
93
  };
93
94
  }
@@ -119,7 +120,22 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
119
120
  // proxy's booking does), so the model's cost stays $0. Image input on either wire (sessionModel): a host tool's images
120
121
  // (a screenshot) reach the model in its tool result.
121
122
  models.setProvider(sessionProvider(api, proxy, model, { provider: PROVIDER, keyName: "AGENTRUN_SESSION_KEY", ...(like ? { like } : {}), reasoning: false }));
122
- run.setModels(models);
123
+ // Each tier's model at its own proxy, under its own provider id (tierProvider): a conversation whose agent names it
124
+ // (a subagent's) is sent there, and booked as the session's own requests are.
125
+ for (const [tier, route, at] of tiers.each)
126
+ models.setProvider(sessionProvider(route.provider.api, at, route.model, { provider: tierProvider(tier), keyName: "AGENTRUN_SESSION_KEY", ...(route.like ? { like: route.like } : {}), reasoning: false }));
127
+ // A child made on an earlier claim keeps the tier's model it was made on; when the tier's model has changed since (the
128
+ // server's AGENT_MODEL_STRONG, say), that one is not here, and the child resumes on the tier's model now, as a new call
129
+ // on the tier would run.
130
+ const tierModel = new Map(tiers.each.map(([tier, route]) => [tierProvider(tier), route.model]));
131
+ run.setModels(tierModel.size === 0 ? models : new Proxy(models, {
132
+ get(target, key) {
133
+ if (key === "getModel")
134
+ return (provider, id) => target.getModel(provider, id) ?? (tierModel.has(provider) ? target.getModel(provider, tierModel.get(provider)) : undefined);
135
+ const value = Reflect.get(target, key, target);
136
+ return typeof value === "function" ? value.bind(target) : value;
137
+ },
138
+ }));
123
139
  // A session tool whose name a native extension already owns is run by that extension (pi's own tool task), so it is not
124
140
  // piTool-wrapped here too: one tool by that name on the agent, offered once.
125
141
  const owned = new Set(nativeToolNames(options));
@@ -127,7 +143,7 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
127
143
  // intent: a call it runs with no pass here is one it reruns after a crash (a replay-safe call whose intent an earlier
128
144
  // attempt stored), told to the host tool as an attempt above 0, so the loop asks the gate about it again.
129
145
  const passed = new Set();
130
- const tools = spec.tools.filter((tool) => !owned.has(tool.name)).map((tool) => piTool(tool, io, (callId) => (io.gate ? (passed.has(callId) ? 0 : 1) : undefined)));
146
+ const tools = [...spec.tools.filter((tool) => !owned.has(tool.name)).map((tool) => piTool(tool, io, (callId) => (io.gate ? (passed.has(callId) ? 0 : 1) : undefined))), ...(options.tools ?? [])];
131
147
  // A refused call's words (the gate's deny, main's), by call: its result is those words alone, as main gives them.
132
148
  const refusals = refusalWords();
133
149
  const extension = defineExtension({
@@ -140,7 +156,7 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
140
156
  return undefined;
141
157
  // A model-issued call's count, read only when the gate holds a budget: a nested call (one a tool made) is its
142
158
  // parent's part, and is marked so (the cap's wrap-up lets it through).
143
- const counted = call.parent === undefined ? { callsBefore: (upTo) => callsBefore(api, call.id, upTo, hookContext) } : { nested: true };
159
+ const counted = call.parent === undefined ? { callsBefore: (upTo) => callsBefore(api, call.id, upTo, hookContext), ownBudget: async () => (await api.snapshot(ConversationToolBudget, api.conversationId, hookContext))?.toolCalls } : { nested: true };
144
160
  const answer = await io.gate({ callId: call.id, tool: call.name, args: (call.arguments ?? {}), ...counted }, hookContext);
145
161
  if (answer === "allow") {
146
162
  passed.add(call.id);
@@ -201,7 +217,14 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
201
217
  const existing = await run.harness.commit((tx) => tx.submissionByRequest(root.id, INPUT_REQUEST), context);
202
218
  if (existing)
203
219
  input = await run.harness.submission(existing.id, context);
204
- let state = existing === undefined ? "new" : existing.status === "done" ? "idle" : "open_turn";
220
+ // Once that first input is settled, a later input of the root still in flight (a follow-up a reopen sent, its turn cut by
221
+ // a lost claim or a drain) is the turn the session is in: its end is the one recover() reads, never the first input's.
222
+ const later = existing && (existing.status === "done" || existing.status === "unanswered")
223
+ ? (await run.harness.inspect(context)).submissions.filter((one) => one.conversationId === root.id && one.type === "input").at(-1)
224
+ : undefined;
225
+ if (later)
226
+ input = await run.harness.submission(later.id, context);
227
+ let state = existing === undefined ? "new" : later ? "open_turn" : existing.status === "done" ? "idle" : "open_turn";
205
228
  let running;
206
229
  const watch = (submission) => {
207
230
  running = submission.wait(context).then((record) => {
@@ -58,7 +58,9 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor } = {
58
58
  const runs = env ?? runEnv(process.env);
59
59
  const { dockerPathsForRuns } = await import("../box-paths.js");
60
60
  const { hostAddressesOnce } = await import("../docker-host-addresses.js");
61
- const computers = computerDepsFrom({ env: runs, store, sealKey: seal.key, dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs) });
61
+ const { PROVIDERS } = await import("@parcha/agentrun-computer");
62
+ const { hostCommandRefusals } = await import("../computers.js");
63
+ const computers = computerDepsFrom({ env: runs, store, sealKey: seal.key, dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH) });
62
64
  const createLoop = dispatchRunner({ env: runs, data: dataDir, journal: (claim) => store.journal(claim), store, sealKey: seal.key, routeOf, computerForClaim: computers.computerForClaim, computerDeps: computers.computerDeps });
63
65
  // It claims by the host's memory as well as by --max-runs (memory-claim.ts): a heavy harness's run waits queued for room.
64
66
  const { runnerMemory } = await import("./memory-claim.js");
@@ -67,8 +69,10 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor } = {
67
69
  // runner's, on stderr (a stderr whose reader closed loses them, never the process: cli.ts).
68
70
  const { startJanitor } = await import("../workspace/computer-janitor.js");
69
71
  const swept = janitor ? startJanitor({ store, computers: computers.computerDeps, env: runs, log: (line) => console.error(`agentrun-serve runner: ${line}`) }) : undefined;
72
+ // Its close waits for any first-use install its claims let go of to stop (its npm ended) before it lets go of the data.
73
+ const { claimInstallsStopped } = await import("../harness-install.js");
70
74
  // The janitor's sweep is cut and waited for on a bound of its own, beside the runner's close, never before it.
71
- return { runner, close: async () => { await Promise.all([swept?.close(), runner.close()]); await store.close(); seal.release(); } };
75
+ return { runner, close: async () => { await Promise.all([swept?.close(), runner.close()]); await claimInstallsStopped(); await store.close(); seal.release(); } };
72
76
  }
73
77
  /** A server and one runner beside it, both in this process, as the CLI's start composes them (cli.ts): the runner holds
74
78
  * what the server's options say (besideRunnerOptions) and sees the server's test switches (fauxEnvOf), so a --faux
@@ -9,6 +9,13 @@ export type { ClaimComputer, ClaimDeps, ClaimLaunch, ComputerForClaim } from "./
9
9
  export type CliSpecDeps = AdapterSpecDeps;
10
10
  /** What a CLI harness refuses of an agent's computer, in words: a browser, which only pi's browser tool drives. */
11
11
  export declare const cliRefusesKind: (kind: string) => string | undefined;
12
+ /** `tools` in the order the agent grants them (`granted`, catalog names; a tool is listed by its catalog name's wire
13
+ * name), as main listed a CLI run's tools to its harness: each granted tool where its grant is, and a tool the grant
14
+ * does not name (one a granted tool or the run's computer brings beside it) right after the tool listed before it. Ties
15
+ * keep the order given. */
16
+ export declare function inGrantOrder<T extends {
17
+ readonly name: string;
18
+ }>(tools: readonly T[], granted: readonly string[]): T[];
12
19
  /** A claim's private folder removed, then each of `parents` in order while it is empty: one another claim of the run has
13
20
  * laid things in since (a follow-up's) stays, with what is in it. */
14
21
  export declare function sweepScratch(dir: string, parents: readonly string[]): Promise<void>;