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

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 (227) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +84 -16
  3. package/dist/adapters.d.ts +3 -0
  4. package/dist/adapters.js +7 -0
  5. package/dist/agent-rows.d.ts +1 -0
  6. package/dist/agents-store.js +17 -2
  7. package/dist/archil-settings.d.ts +11 -1
  8. package/dist/archil-settings.js +10 -0
  9. package/dist/bash-read-only.d.ts +13 -0
  10. package/dist/bash-read-only.js +77 -0
  11. package/dist/browser-cost.d.ts +2 -2
  12. package/dist/browser-cost.js +6 -4
  13. package/dist/budget.d.ts +0 -5
  14. package/dist/budget.js +0 -5
  15. package/dist/cap.d.ts +6 -3
  16. package/dist/cap.js +7 -4
  17. package/dist/cli.js +32 -5
  18. package/dist/computer-keys.d.ts +20 -10
  19. package/dist/computer-keys.js +36 -57
  20. package/dist/computer-setting.d.ts +6 -5
  21. package/dist/computer-setting.js +54 -26
  22. package/dist/computers.d.ts +9 -4
  23. package/dist/computers.js +4 -2
  24. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  25. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  26. package/dist/console/index.html +2 -2
  27. package/dist/content-filter.d.ts +7 -0
  28. package/dist/content-filter.js +23 -0
  29. package/dist/decision-cap.d.ts +7 -29
  30. package/dist/decision-cap.js +3 -94
  31. package/dist/errors.d.ts +1 -0
  32. package/dist/errors.js +3 -0
  33. package/dist/explain.js +3 -1
  34. package/dist/github-connection.js +25 -7
  35. package/dist/github-faux.d.ts +26 -0
  36. package/dist/github-faux.js +76 -0
  37. package/dist/github.d.ts +6 -2
  38. package/dist/github.js +5 -3
  39. package/dist/graph-served.d.ts +5 -3
  40. package/dist/graph-served.js +14 -6
  41. package/dist/graph-view.js +5 -2
  42. package/dist/harness-opencode/harness.js +0 -1
  43. package/dist/harness-opencode/host/policy.js +2 -2
  44. package/dist/index.d.ts +1 -0
  45. package/dist/index.js +1 -0
  46. package/dist/learn/check.d.ts +3 -1
  47. package/dist/learn/check.js +3 -3
  48. package/dist/learn/folder.d.ts +6 -3
  49. package/dist/learn/folder.js +7 -16
  50. package/dist/learn/grade.d.ts +4 -1
  51. package/dist/learn/grade.js +43 -5
  52. package/dist/learn/index.d.ts +2 -2
  53. package/dist/learn/index.js +2 -2
  54. package/dist/learn/learning.sh +1 -14
  55. package/dist/learn/notes.d.ts +14 -3
  56. package/dist/learn/notes.js +16 -6
  57. package/dist/learn/reflect.js +5 -3
  58. package/dist/learn/skills.d.ts +48 -5
  59. package/dist/learn/skills.js +97 -21
  60. package/dist/learned-nodes.d.ts +14 -0
  61. package/dist/learned-nodes.js +8 -0
  62. package/dist/learned-workflow.d.ts +9 -5
  63. package/dist/learned-workflow.js +53 -9
  64. package/dist/learning-routes.d.ts +41 -0
  65. package/dist/learning-routes.js +94 -26
  66. package/dist/learning-run.d.ts +7 -5
  67. package/dist/learning-run.js +9 -6
  68. package/dist/learning.d.ts +0 -22
  69. package/dist/learning.js +0 -16
  70. package/dist/llm.d.ts +4 -1
  71. package/dist/llm.js +4 -2
  72. package/dist/mcp-gateway.d.ts +6 -0
  73. package/dist/mcp-gateway.js +11 -1
  74. package/dist/mcp-servers-store.d.ts +12 -12
  75. package/dist/model.d.ts +3 -0
  76. package/dist/model.js +8 -0
  77. package/dist/openapi.js +37 -13
  78. package/dist/paid-calls.js +1 -1
  79. package/dist/pause.d.ts +2 -19
  80. package/dist/pause.js +5 -74
  81. package/dist/port-models.d.ts +10 -3
  82. package/dist/port-models.js +26 -6
  83. package/dist/propose.d.ts +2 -0
  84. package/dist/propose.js +1 -10
  85. package/dist/run-launch.d.ts +5 -3
  86. package/dist/run-launch.js +6 -5
  87. package/dist/run-learning-served.d.ts +11 -0
  88. package/dist/run-reads-over-store.d.ts +4 -2
  89. package/dist/run-reads-over-store.js +10 -8
  90. package/dist/run-timeline-served.js +12 -2
  91. package/dist/run-view.d.ts +30 -14
  92. package/dist/run-view.js +60 -32
  93. package/dist/runnable.d.ts +4 -1
  94. package/dist/runnable.js +14 -2
  95. package/dist/runner/adapter-loop.d.ts +30 -4
  96. package/dist/runner/adapter-loop.js +253 -29
  97. package/dist/runner/adapter-run-spec.d.ts +21 -0
  98. package/dist/runner/adapter-run-spec.js +104 -28
  99. package/dist/runner/adapters/pi.d.ts +29 -1
  100. package/dist/runner/adapters/pi.js +95 -23
  101. package/dist/runner/beside.d.ts +8 -0
  102. package/dist/runner/beside.js +18 -0
  103. package/dist/runner/claim-secrets.d.ts +6 -0
  104. package/dist/runner/claim-secrets.js +15 -1
  105. package/dist/runner/cli-run-spec.d.ts +3 -0
  106. package/dist/runner/cli-run-spec.js +123 -34
  107. package/dist/runner/conformance/harness.d.ts +1 -0
  108. package/dist/runner/conformance/harness.js +5 -5
  109. package/dist/runner/github-app.d.ts +7 -2
  110. package/dist/runner/github-app.js +46 -15
  111. package/dist/runner/harness-loops.d.ts +6 -1
  112. package/dist/runner/harness-loops.js +23 -0
  113. package/dist/runner/journal-kinds.d.ts +38 -2
  114. package/dist/runner/journal-kinds.js +23 -0
  115. package/dist/runner/learning-end.js +88 -16
  116. package/dist/runner/learning-loop.d.ts +2 -0
  117. package/dist/runner/learning-loop.js +13 -5
  118. package/dist/runner/learning-seed.d.ts +6 -0
  119. package/dist/runner/learning-seed.js +6 -0
  120. package/dist/runner/loop-contract.d.ts +4 -0
  121. package/dist/runner/main.d.ts +9 -4
  122. package/dist/runner/main.js +26 -11
  123. package/dist/runner/mcp-claim.d.ts +3 -0
  124. package/dist/runner/mcp-claim.js +6 -1
  125. package/dist/runner/mcp-github.d.ts +11 -2
  126. package/dist/runner/mcp-github.js +55 -4
  127. package/dist/runner/mcp-run.js +1 -0
  128. package/dist/runner/metrics.d.ts +14 -1
  129. package/dist/runner/metrics.js +72 -1
  130. package/dist/runner/model-route.d.ts +3 -0
  131. package/dist/runner/model-route.js +1 -1
  132. package/dist/runner/runner.js +90 -8
  133. package/dist/runner/spec-holds.d.ts +7 -2
  134. package/dist/runner/spec-holds.js +4 -3
  135. package/dist/runner/workflow-host.d.ts +7 -2
  136. package/dist/runner/workflow-host.js +3 -1
  137. package/dist/runner/workflow-loop.d.ts +4 -1
  138. package/dist/runner/workflow-loop.js +8 -2
  139. package/dist/runner/workflow-spec.d.ts +3 -0
  140. package/dist/runner/workflow-spec.js +156 -78
  141. package/dist/runs-over-store.d.ts +7 -1
  142. package/dist/runs-over-store.js +42 -11
  143. package/dist/seal-key.d.ts +0 -2
  144. package/dist/seal-key.js +0 -2
  145. package/dist/server-lock.js +4 -5
  146. package/dist/server.d.ts +21 -18
  147. package/dist/server.js +183 -34
  148. package/dist/stop-signals.d.ts +4 -2
  149. package/dist/stop-signals.js +5 -3
  150. package/dist/store/agent-body.d.ts +5 -1
  151. package/dist/store/agent-body.js +11 -5
  152. package/dist/store/deadline.d.ts +18 -0
  153. package/dist/store/deadline.js +45 -0
  154. package/dist/store/postgres/connection.d.ts +4 -0
  155. package/dist/store/postgres/connection.js +55 -9
  156. package/dist/store/sqlite/connection.js +3 -38
  157. package/dist/store-reads/journal.js +39 -4
  158. package/dist/store-reads/learning.d.ts +58 -2
  159. package/dist/store-reads/learning.js +172 -7
  160. package/dist/store-view.d.ts +15 -1
  161. package/dist/store-view.js +45 -12
  162. package/dist/templates.d.ts +9 -4
  163. package/dist/templates.js +14 -9
  164. package/dist/timeline/timeline.d.ts +8 -0
  165. package/dist/tool-budget.d.ts +18 -0
  166. package/dist/tool-budget.js +50 -0
  167. package/dist/tool-gate.d.ts +6 -2
  168. package/dist/tool-gate.js +8 -5
  169. package/dist/tool-plane.d.ts +9 -10
  170. package/dist/tools.d.ts +37 -7
  171. package/dist/tools.js +73 -12
  172. package/dist/uploads.d.ts +28 -5
  173. package/dist/uploads.js +82 -9
  174. package/dist/usage.d.ts +1 -47
  175. package/dist/usage.js +3 -82
  176. package/dist/validate.d.ts +2 -0
  177. package/dist/validate.js +11 -1
  178. package/dist/workspace/archil-claim.d.ts +2 -2
  179. package/dist/workspace/archil-claim.js +4 -3
  180. package/dist/workspace/archil-disk.d.ts +10 -1
  181. package/dist/workspace/archil-disk.js +4 -0
  182. package/dist/workspace/archil-exec.d.ts +12 -2
  183. package/dist/workspace/archil-exec.js +16 -0
  184. package/dist/workspace/archil.d.ts +2 -2
  185. package/dist/workspace/archil.js +25 -5
  186. package/dist/workspace/attach.js +2 -0
  187. package/dist/workspace/computer-deps.d.ts +9 -10
  188. package/dist/workspace/computer-deps.js +53 -40
  189. package/dist/workspace/computer-for-claim.d.ts +5 -3
  190. package/dist/workspace/computer-for-claim.js +28 -16
  191. package/dist/workspace/computer-ledger.d.ts +1 -8
  192. package/dist/workspace/computer-ledger.js +0 -3
  193. package/dist/workspace/computer-providers.d.ts +5 -3
  194. package/dist/workspace/computer-providers.js +11 -9
  195. package/dist/workspace/hands.d.ts +5 -2
  196. package/dist/workspace/hands.js +4 -3
  197. package/dist/workspace/index.d.ts +3 -3
  198. package/dist/workspace/index.js +1 -1
  199. package/dist/workspace/local.d.ts +3 -0
  200. package/dist/workspace/local.js +9 -0
  201. package/dist/workspace/paths.js +3 -2
  202. package/dist/workspace/pi-env.d.ts +4 -0
  203. package/dist/workspace/pi-env.js +3 -2
  204. package/dist/workspace/resolve-computer.d.ts +8 -3
  205. package/dist/workspace/resolve-computer.js +28 -11
  206. package/dist/workspace/run-tools.d.ts +2 -0
  207. package/dist/workspace/run-tools.js +9 -3
  208. package/dist/workspace/workspace.d.ts +5 -0
  209. package/dist/workspace.d.ts +0 -3
  210. package/dist/workspace.js +1 -14
  211. package/package.json +14 -14
  212. package/skills/agentrun-serve/SKILL.md +1 -1
  213. package/templates/README.md +2 -2
  214. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  215. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  216. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  217. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  218. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  219. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  220. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  221. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  222. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  223. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  224. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  225. package/templates/release-notes/agent.md +11 -0
  226. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  227. package/dist/console/assets/index-opTN5Naq.css +0 -1
@@ -1,8 +1,9 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { defineExtension, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
3
3
  import { checkRaise, followUpOf, parkOf } from "@parcha/agentrun-kernel/kernel/cap";
4
+ import { inspectWorkflow } from "@parcha/agentrun-dsl";
4
5
  import { dropLiveViewer, putLiveViewer } from "../browser-live.js";
5
- import { thinkingLevel } from "../model.js";
6
+ import { llmTiers, nodeTiers, thinkingLevel, TIERS, tierModelOf, workflowNodes } from "../model.js";
6
7
  import { firstMessage } from "../run-manifest.js";
7
8
  import { learningStartOf, seedFailed } from "../run-launch.js";
8
9
  import { isObject } from "../validate.js";
@@ -16,22 +17,21 @@ import { WEB_SEARCH_TOOL } from "../web-search.js";
16
17
  import { environmentLine } from "../environment.js";
17
18
  import { effortGuidance } from "../effort-guidance.js";
18
19
  import { laidLearned, learningFolderOf, secretsShown } from "../learning.js";
19
- import { layLearningSeed } from "./learning-seed.js";
20
+ import { laidOf, layLearningSeed } from "./learning-seed.js";
20
21
  import { learningWorkspace } from "../learn/folder.js";
21
22
  import { learningEndOfRun } from "./learning-end.js";
22
23
  import { learnedAskFits, learnedAskShown, LEARNED_WORKFLOW_TOOL, learnedMcpTools, learnedWorkflowTool } from "../learned-workflow.js";
23
- import { PORT_PROVIDER } from "../port-models.js";
24
+ import { PORT_PROVIDER, tieredModels, tierProvider } from "../port-models.js";
24
25
  import { promptOf, readsFiles } from "../skills.js";
25
26
  import { openRunWorkspace } from "../workspace/run-workspace.js";
26
27
  import { layOwnSkills } from "../workspace/revision-skills.js";
27
28
  import { COMPUTER_ROOT, runFolder } from "../workspace/paths.js";
28
29
  import { runTools, withKindTools } from "../workspace/run-tools.js";
29
- import { INPUTS_DIR, UPLOADS_DIR, Uploads } from "../uploads.js";
30
+ import { copyRunFiles } from "../uploads.js";
30
31
  import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
31
32
  import { UNREADABLE_SIGN_IN } from "../run-view.js";
32
- import { claimSecrets, learnedDecisionKeys, withModelKeys } from "./claim-secrets.js";
33
+ import { claimSecrets, learnedDecisionKeys, tierModelKeys, withModelKeys } from "./claim-secrets.js";
33
34
  import { mcpForClaim } from "./mcp-run.js";
34
- import { join } from "node:path";
35
35
  import { hostLifecycle } from "./adapter-loop.js";
36
36
  import { piAdapter } from "./adapters/pi.js";
37
37
  import { entriesOf } from "./loop.js";
@@ -44,6 +44,7 @@ import { imageWaitWords } from "../workspace/computer-deps.js";
44
44
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
45
45
  import { githubAppAccess } from "./github-app.js";
46
46
  import { holdStored, storeSecrets } from "./store-secrets.js";
47
+ import { bashPolicyOf } from "../bash-read-only.js";
47
48
  /** The wires pi speaks on the runner: main's pi's (provider.ts), Anthropic's Messages and OpenAI's Responses. */
48
49
  export const PI_WIRES = Object.freeze(["anthropic-messages", "openai-responses"]);
49
50
  /** The browser's catalog name (tools.ts TOOLS.browser). */
@@ -89,9 +90,9 @@ export async function adapterRunGate(store, claim, revision, root, shell) {
89
90
  const gate = runGate({ root: folder, work: folder, ...(shell === undefined ? {} : { computer: shell === "computer" }) }, claim.runId, revision, () => current, approvers);
90
91
  // The run's learned workflows, once its spec has read them (learn): a learned_workflow call is asked about its MCP nodes.
91
92
  let learned = [];
92
- const decide = async (call) => {
93
+ const decide = async (call, options = {}) => {
93
94
  current = await storeSettings(store);
94
- const decision = await gate.decide(call.tool, call.args);
95
+ const decision = await gate.decide(call.tool, call.args, options);
95
96
  // A learned workflow's MCP nodes are the run's own MCP calls, held to the same settings, decided for the whole call
96
97
  // before any node runs, never mid-run: one set to deny refuses the call in the gate's words, nothing sent; one set to
97
98
  // ask asks for the call, up front, on the run's one card (a running workflow can't park mid-call: it is never run
@@ -131,7 +132,9 @@ export async function adapterRunGate(store, claim, revision, root, shell) {
131
132
  const asks = (await mcpOf(args)).filter((one) => gate.policy(one) === "ask");
132
133
  return asks.length ? learnedAskShown(asks) : undefined;
133
134
  };
134
- return Object.assign(decide, { askedAs: (tool) => gate.askedAs(tool), askedFor, permissions, learn: (flows) => void (learned = flows) });
135
+ // The revision's tool-call budget (tool-budget.ts), which the adapter loop holds each conversation's calls to.
136
+ const toolCalls = revision.body.maxToolCalls;
137
+ return Object.assign(decide, { askedAs: (tool) => gate.askedAs(tool), askedFor, permissions, learn: (flows) => void (learned = flows), ...(toolCalls === undefined ? {} : { toolCalls }) });
135
138
  }
136
139
  /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
137
140
  * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
@@ -192,21 +195,15 @@ async function adapterSpec(launch, run, deps, claim, holds) {
192
195
  ? await openRunWorkspace({ mode: 1, agentId: runRow.agentId, runId: claim.runId, data: deps.data, log })
193
196
  : await openRunWorkspace({ mode: 2, agentId: runRow.agentId, runId: claim.runId, archil, log });
194
197
  holds.hold({ ws });
195
- // The run's uploaded files, copied into its work/inputs/ before the first turn, as the server's start copied them before
196
- // the per-run process ran (uploads.copyInto). Once per run: a fresh run has no inputs/ yet; a resumed claim finds them
197
- // copied and skips, so the copy's name-collision suffixes never duplicate a file across claims.
198
- if (launch.files?.length) {
199
- const copied = await ws.workspace.list(INPUTS_DIR).then(() => true, () => false);
200
- if (!copied) {
201
- const uploads = new Uploads(join(deps.data, UPLOADS_DIR));
202
- await uploads.copyInto(ws.workspace, await uploads.readyFiles(launch.files));
203
- }
204
- }
198
+ // The run's uploaded files, copied into its work/inputs/ before the first turn, from what its start held for it, once
199
+ // per run (uploads.ts copyRunFiles); a copy that fails ends the run failed, saying why.
200
+ if (launch.files?.length)
201
+ await copyRunFiles(deps.data, claim.runId, ws.workspace, launch.files);
205
202
  // The run's MCP for this claim (mcp-run.ts mcpForClaim): its pin made at the first claim or read as written, its
206
203
  // credentials opened under the server's seal key into this claim's memory, one gateway for the claim. First, before
207
204
  // 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
208
205
  // words before the session opens. The seal key is the runner's own (deps.sealKey), not re-read from the environment.
209
- 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 } : {}), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}) });
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 } : {}) });
210
207
  // The claim's MCP goes to the loop, which lets it go; a build that throws lets it go itself.
211
208
  holds.hold({ passed: mcp });
212
209
  // The run's computer, from the one shared claim-time function (the CLI spec takes the same): none for a runner place, a
@@ -221,7 +218,9 @@ async function adapterSpec(launch, run, deps, claim, holds) {
221
218
  // 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,
222
219
  // and the agent's hand-over (computer_request_handoff) asks the person through it.
223
220
  holds.hold({ computer });
224
- const tools = await runTools(ws.workspace, computer.computer, { mode, context, ...(computer.hold ? { hold: computer.hold } : {}) });
221
+ // Under the agent's bash policy, its shell's environment is the policy's too (bash-read-only.ts policyEnv).
222
+ const bashPolicy = bashPolicyOf(body.toolSettings);
223
+ const tools = await runTools(ws.workspace, computer.computer, { mode, context, ...(computer.hold ? { hold: computer.hold } : {}), ...(bashPolicy === undefined ? {} : { bashPolicy }) });
225
224
  holds.hold({ tools });
226
225
  // The run's model route: its model through routeOf (NEVER re-resolved — the launch's model, pinned at start), the catalog
227
226
  // price with tiers for the cap, and the proxy's price (pi-ai calculateCost, tiered).
@@ -236,7 +235,11 @@ async function adapterSpec(launch, run, deps, claim, holds) {
236
235
  holdClaimed(cut, toolEnv);
237
236
  // The route reads its model's key from the runner's environment, else the one the claim opened from the store: a key
238
237
  // saved in Settings → Model keys runs the next run with no restart (withModelKeys).
239
- const route = await deps.routeOf(modelAskOf(launch.model, body.model), withModelKeys(deps.env, toolEnv), "default", PI_WIRES, undefined, cut);
238
+ const modelEnv = withModelKeys(deps.env, toolEnv);
239
+ const route = await deps.routeOf(modelAskOf(launch.model, body.model), modelEnv, "default", PI_WIRES, undefined, cut);
240
+ // The run's models of other tiers, for its learned workflows' nodes of a tier (learnedTierRoutes, filled once the seed's
241
+ // lay chose the workflows, below): read when the session opens (pi.ts options.tiers), each on a proxy of its own.
242
+ const tierRoutes = new Map();
240
243
  // The run's pi-native extensions, in the root agent through the pi adapter (PiAdapterOptions.extensions), which installs
241
244
  // them in the claim's registry and offers each tool once:
242
245
  // - ask_person is pi's own tool (tools.ts): a run granted it carries its native extension, so pi runs it as its own tool
@@ -256,6 +259,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
256
259
  ...(route.like ? { like: route.like } : {}),
257
260
  ...(route.price ? { price: route.price } : {}),
258
261
  ...(route.fetch ? { fetch: route.fetch } : {}),
262
+ tiers: tierRoutes,
259
263
  });
260
264
  // The gate before a call's intent: the run's revision's tool settings through runGate (approvals "never" turns the one
261
265
  // ask it leaves into an allow). The adapter loop asks `gate` and handles the ask/park/answer on the journal itself, so
@@ -270,9 +274,16 @@ async function adapterSpec(launch, run, deps, claim, holds) {
270
274
  // tool calls and its decisions all on one rule and one booking), so the spec carries no beforeRequest of its own.
271
275
  const capUsd = launch.maxCostUsd;
272
276
  const capModel = capModelOf(route);
277
+ // And each tier's model (tierRoutes, filled below), by the route its request names (its tier's proxy, ModelRequest.route),
278
+ // priced as that route books it: one id the run's model and a tier share is priced apart, never at the other's price.
273
279
  const runCap = {
274
280
  capUsd: () => launch.maxCostUsd,
275
- modelOf: (id) => (id === route.model ? capModel : undefined),
281
+ modelOf: (id, by) => {
282
+ if (by === undefined)
283
+ return id === route.model ? capModel : undefined;
284
+ const tierRoute = tierRoutes.get(by);
285
+ return tierRoute && tierRoute.model === id ? capModelOf(tierRoute) : undefined;
286
+ },
276
287
  ...(launch.capMode === "strict" ? { mode: "strict" } : {}),
277
288
  };
278
289
  // The run's cap figure and what a refusal does to it (parkOf, with the kernel's raise rule): present only when the run
@@ -319,7 +330,22 @@ async function adapterSpec(launch, run, deps, claim, holds) {
319
330
  // onto the tools' environment alone. The model's route was built on the revision's keys above, so a decision key never
320
331
  // becomes its model's.
321
332
  const workflows = seedLaid?.workflows ?? [];
333
+ // A tier a learned workflow's node names and the host has a model of: none can't be reached is left as `why`, and its
334
+ // node fails in those words (learnedWorkflowHostTool), never on another model.
335
+ const tierUnreachable = new Map();
322
336
  if (learnsWorkflows(revision.kind, workflows)) {
337
+ // The keys those tiers' models need (tierModelKeys: a key saved in Settings too, which claimSecrets opened only for the
338
+ // run's own model), held by the run's one redactor, on the tiers' route env alone (withModelKeys, never enumerable),
339
+ // never on the tools' (toolEnv).
340
+ const tierKeys = await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
341
+ holdClaimed(cut, tierKeys);
342
+ const tierEnv = withModelKeys(deps.env, { ...toolEnv, ...tierKeys });
343
+ for (const [tier, routed] of await learnedTierRoutes(workflows, tierEnv, (tier) => deps.routeOf(undefined, tierEnv, tier, PI_WIRES, undefined, cut))) {
344
+ if ("why" in routed)
345
+ tierUnreachable.set(tier, routed.why);
346
+ else
347
+ tierRoutes.set(tier, routed);
348
+ }
323
349
  const learnedKeys = await learnedDecisionKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, workflows, (provider) => gate.permissions.policy(provider) !== "deny");
324
350
  holdClaimed(cut, learnedKeys);
325
351
  Object.assign(toolEnv, learnedKeys);
@@ -339,9 +365,10 @@ async function adapterSpec(launch, run, deps, claim, holds) {
339
365
  const handTools = tools.hostTools(withKindTools(granted, tools), results);
340
366
  // 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
341
367
  // 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 }])]);
342
369
  // The gate asks a learned_workflow call about its workflow's MCP nodes (adapterRunGate).
343
370
  gate.learn(workflows);
344
- const nonHandTools = (await bindNonHandTools(host, revision.kind, granted, run, context, results, root, launch.plane, workflows, native, gate.permissions, mcp)).map((tool) => answersCut(tool, cut));
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));
345
372
  const sessionTools = [...handTools, ...nonHandTools];
346
373
  // The run's system prompt, as main's per-run process builds it (app.ts): the environment line first (environment.ts, as
347
374
  // pi installs it before every other section), then the revision's instructions with what the agent learned laid in
@@ -402,6 +429,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
402
429
  ...(mcp ? { mcp } : {}),
403
430
  // The run's end-of-run step, when it learns (the spec's, which the loop prefers over its deps': adapter-loop.ts stepOf).
404
431
  ...(endOfRun ? { endOfRun } : {}),
432
+ ...(start ? { learningLaid: laidOf(seedLaid) } : {}),
405
433
  // The tool host's install lifecycle (its bindings' onConversation/beforeResume/beforeRelease), run by the adapter loop.
406
434
  lifecycle: life,
407
435
  agentId: runRow.agentId,
@@ -449,6 +477,42 @@ export function hostToolCtxOf(run, context, results, root) {
449
477
  * a workflow it may run (`workflows`: the claim's seed lay chose them, runner/learning-seed.ts). A revision never names
450
478
  * the tool among its own: the run has it beside them, so the harness is told of it as of theirs. */
451
479
  export const learnsWorkflows = (kind, workflows) => kind === "agentic" && workflows.length > 0;
480
+ /** The tiers other than the default that `workflows`' model nodes and `llm` calls name (model.ts nodeTiers, llmTiers),
481
+ * in TIERS order. A workflow that does not parse names none: its call refuses it. */
482
+ export function learnedTiers(workflows) {
483
+ const named = new Set();
484
+ for (const flow of workflows) {
485
+ let doc;
486
+ try {
487
+ doc = JSON.parse(flow.workflow);
488
+ const nodes = workflowNodes(doc, inspectWorkflow(doc));
489
+ for (const tier of llmTiers(nodes, nodeTiers(nodes)))
490
+ named.add(tier);
491
+ }
492
+ catch {
493
+ continue;
494
+ }
495
+ }
496
+ return TIERS.filter((tier) => tier !== "default" && named.has(tier));
497
+ }
498
+ /** The route of each tier `workflows` name (learnedTiers) that `env` names a model of its own for (tierModelOf:
499
+ * AGENT_MODEL_FAST, AGENT_MODEL_STRONG), through `routeOf` (the run's one route, as its own model's): the model a node
500
+ * of that tier runs on, priced at its own price. A tier with no model of its own is left out (its nodes run on the
501
+ * run's model); one whose route is refused is `why`, so its nodes fail in those words and never run on another model. */
502
+ export async function learnedTierRoutes(workflows, env, routeOf) {
503
+ const routes = new Map();
504
+ for (const tier of learnedTiers(workflows)) {
505
+ if (tierModelOf(env, tier) === undefined)
506
+ continue;
507
+ try {
508
+ routes.set(tier, await routeOf(tier));
509
+ }
510
+ catch (error) {
511
+ routes.set(tier, { why: String(error?.message ?? error).slice(0, 300) });
512
+ }
513
+ }
514
+ return routes;
515
+ }
452
516
  /** The run's learned_workflow tool as a HostTool, listed when the run has it (learnsWorkflows: an agentic revision whose
453
517
  * agent learned workflows, by learning.ts chooseWorkflows as main's start chooses them, so the tool set the model sees
454
518
  * matches main). `granted`, the revision's own tools, are the ones its workflows' call nodes may call. Every run's session — pi's and every CLI harness's — has a model
@@ -459,9 +523,21 @@ export async function learnedWorkflowHostTool(opts) {
459
523
  if (!learnsWorkflows(opts.kind, opts.workflows))
460
524
  return undefined;
461
525
  const flows = opts.workflows;
462
- const models = await opts.run.ledger.models(LEARNED_WORKFLOW_TOOL);
526
+ const tiers = opts.tiers ?? new Map();
463
527
  const mcpTools = (opts.mcp?.tools ?? []).map((one) => opts.mcp.catalogOf(one.name)).filter((name) => typeof name === "string");
464
- const tool = learnedWorkflowTool({ workflows: flows, granted: opts.granted, ...(opts.plane ? { plane: opts.plane } : {}), env: opts.env, work: opts.work, models: models, modelOf: () => ({ provider: PORT_PROVIDER, modelId: "session" }), policy: opts.permissions.policy, denyFrom: opts.permissions.denyFrom, refresh: opts.permissions.refresh, decide: opts.permissions.decide, mcpTools });
528
+ const byProvider = new Map([[PORT_PROVIDER, await opts.run.ledger.models(LEARNED_WORKFLOW_TOOL)]]);
529
+ for (const [tier, model] of tiers)
530
+ if ("model" in model)
531
+ byProvider.set(tierProvider(tier), await opts.run.ledger.models(LEARNED_WORKFLOW_TOOL, tier));
532
+ const modelOf = (tier) => {
533
+ const model = tier === undefined ? undefined : tiers.get(tier);
534
+ if (model === undefined)
535
+ return { provider: PORT_PROVIDER, modelId: "session" };
536
+ if ("why" in model)
537
+ throw new Error(`the run's ${tier} model could not be reached: ${model.why}`);
538
+ return { provider: tierProvider(tier), modelId: model.model };
539
+ };
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 });
465
541
  return hostToolOf(LEARNED_WORKFLOW_TOOL, tool, opts.ctx) ?? undefined;
466
542
  }
467
543
  /** The run's non-hand tools as HostTool[], bound through the ToolHost seam and wrapped as the hands are (host-tools.ts
@@ -558,7 +634,7 @@ export async function webHostTools(host, granted, ctx) {
558
634
  }
559
635
  return tools;
560
636
  }
561
- async function bindNonHandTools(host, kind, granted, run, context, results, root, plane, workflows, native, permissions, mcp) {
637
+ async function bindNonHandTools(host, kind, granted, run, context, results, root, plane, workflows, native, permissions, tiers, mcp) {
562
638
  // Fail closed (browserListed): the browser binds only on the native route (BROWSER_ON_RUNNER) and with the claim's
563
639
  // one-ledger booking on its ToolHost (host.ledger.paid); otherwise its extension is not installed. learned_workflow
564
640
  // binds below with no web tool, so a learned run with no web tool still lists it.
@@ -571,7 +647,7 @@ async function bindNonHandTools(host, kind, granted, run, context, results, root
571
647
  // the session's tools the harness is told of: its model nodes run on the session's proxied models (run.ledger.models),
572
648
  // each a request on the run's one route labelled learned_workflow. The agent's scoped keys (host.env) are its call
573
649
  // nodes'.
574
- const learned = await learnedWorkflowHostTool({ run, kind, granted, plane, env: host.env, work: root, workflows, permissions, ctx, ...(mcp ? { mcp } : {}) });
650
+ const learned = await learnedWorkflowHostTool({ run, kind, granted, plane, env: host.env, work: root, workflows, permissions, ctx, tiers, ...(mcp ? { mcp } : {}) });
575
651
  if (learned)
576
652
  tools.push(learned);
577
653
  // 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,7 +1,7 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import type { Models } from "@earendil-works/pi-ai";
3
3
  import { type Extension, type Harness, type Registry } from "@earendil-works/pi-durable";
4
- import { type AgentAdapter, type SessionIO, type Wire } from "@parcha/agentrun-kernel";
4
+ import { type AgentAdapter, type SessionIO, type SessionPort, type Wire } from "@parcha/agentrun-kernel";
5
5
  import { 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. */
@@ -16,6 +16,15 @@ export interface PreIntentCall {
16
16
  readonly callId: string;
17
17
  readonly tool: string;
18
18
  readonly args: Record<string, unknown>;
19
+ /** An earlier attempt of the call may have been sent (a CLI's kernel bridge, asking about a replay-safe call a crash
20
+ * cut: GateCall's `replayed`), so a refusal never says nothing was. */
21
+ readonly replayed?: true;
22
+ /** The tool calls the call's conversation made before it, at most `upTo`, read from its committed entries (tool-budget.ts
23
+ * countCalls), for the gate's tool-call budget: pi's model-issued calls only, never a nested call or a CLI's. */
24
+ readonly callsBefore?: (upTo: number) => Promise<number>;
25
+ /** 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
+ * one (tool-budget.ts), so a tool in flight is never cut short. */
27
+ readonly nested?: true;
19
28
  }
20
29
  /** The host's answer before a call's intent: run it, refuse it, or park the run on it (the call never moves on here). */
21
30
  export type PreIntentAnswer = "allow" | {
@@ -66,9 +75,28 @@ export interface PiAdapterOptions {
66
75
  * claim's Harness. Their tools pass the session's gate (its beforeTool hook), and every conversation they open takes
67
76
  * its model from the root's agent, through this session's proxy and its booking. */
68
77
  readonly extensions?: readonly Extension[];
78
+ /** The run's models of other tiers than its own (a learned workflow's node of a tier: AGENT_MODEL_FAST,
79
+ * 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
+ * its own beside the session's (its origin, credential, price and fetch), on the session's booking (io.models), so its
81
+ * requests are the run's, under its one cap, each priced at its own model. Reached through `port(label, tier)`. */
82
+ readonly tiers?: ReadonlyMap<string, TierModel>;
69
83
  }
70
84
  /** pi as an AgentAdapter for one claim's run. */
71
85
  export declare function piAdapter(options: PiAdapterOptions): AgentAdapter;
86
+ /** A tier's model as its proxy takes it: its route's provider, model, catalog entry, price and fetch (model-route.ts). */
87
+ export type TierModel = Pick<PiAdapterOptions, "provider" | "model" | "like" | "price" | "fetch">;
88
+ /** The tier proxies a session holds (openTierProxies): each tier's port for a side request under `label`, and their close. */
89
+ export interface TierProxies {
90
+ port(label: string, tier: string): SessionPort | undefined;
91
+ close(): Promise<void>;
92
+ }
93
+ /** A run's models of other tiers than its own (a learned workflow's node of a tier: AGENT_MODEL_FAST, AGENT_MODEL_STRONG),
94
+ * each on a proxy of its own beside the session's, on the session's booking (`hooks`, io.models): the one way every
95
+ * harness serves them, pi's session and a CLI harness's (cli-run-spec.ts). Only the host's own requests reach them (side
96
+ * 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
+ * proxy speaks its model's route (model-route.ts routeOf, its translation fetch for a model of neither wire), never the
98
+ * 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>;
72
100
  /** The session proxy's policy on Messages: claude-agent's (no fork), with pi's tools, the host's own names (`tools`), as
73
101
  * the names its client offers by themselves (its builtins). The CLI's own `mcp__hands__` prefix is not pi's: under it
74
102
  * every one of pi's tool definitions would be dropped and the model offered none. Every other tool definition is
@@ -9,6 +9,7 @@ import { DEFAULT_HARNESS } from "../../harness.js";
9
9
  import { sessionProvider } 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
13
  const PROVIDER = "agentrun-session";
13
14
  const INPUT_REQUEST = "agentrun:input";
14
15
  /** pi as an AgentAdapter for one claim's run. */
@@ -30,27 +31,66 @@ async function openPi(options, spec, io) {
30
31
  const context = withAbortSignal(io.signal, BACKGROUND_CONTEXT);
31
32
  // The session's route: pi-ai's requests reach the provider only through this proxy, which admits and books each one
32
33
  // through the runner's booking (io.models).
33
- const proxy = await startModelProxy({
34
- policy: await policyFor(options.provider, model, [...spec.tools.map((tool) => tool.name), ...nativeToolNames(options)]),
35
- hooks: io.models,
36
- model,
37
- origin: options.provider.origin,
38
- credential: async () => (await options.provider.credential()) ?? "",
39
- ...(options.price ? { price: options.price } : {}),
40
- ...(options.provider.headers ? { headers: options.provider.headers } : {}),
41
- ...(options.fetch ? { fetch: options.fetch } : {}),
42
- ...(options.redact ? { redact: options.redact } : {}),
43
- }, randomBytes(32).toString("base64url"));
44
- // An open that fails from here (the claim lost while the session opened) closes the proxy: its server would hold the
45
- // runner's process open.
34
+ const proxy = await routeProxy(options, io.models, [...spec.tools.map((tool) => tool.name), ...nativeToolNames(options)], options.redact);
35
+ // An open that fails from here (the claim lost while the session opened) closes the proxies: their servers would hold
36
+ // the runner's process open.
37
+ let tiers;
46
38
  try {
47
- return await sessionOn(proxy, options, spec, io, context);
39
+ tiers = await openTierProxies(options.tiers ?? new Map(), io.models, options.redact);
40
+ return await sessionOn(proxy, options, spec, io, context, tiers);
48
41
  }
49
42
  catch (error) {
50
43
  await proxy.close().catch(() => undefined);
44
+ await tiers?.close();
51
45
  throw error;
52
46
  }
53
47
  }
48
+ /** A proxy on `hooks` (the session's booking: its requests are the run's, under its one cap) for `route`'s model, with its
49
+ * origin, credential, price and fetch, its provider's errors through `redact`. `tools`: the tool names its policy admits
50
+ * by name on a request of the session's own key (none for a tier's: only side keys reach it). */
51
+ async function routeProxy(route, hooks, tools, redact, tier) {
52
+ return startModelProxy({
53
+ // A tier's proxy names its tier on each request (ModelRequest.route), so the run's cap prices it as this route books it.
54
+ ...(tier === undefined ? {} : { route: tier }),
55
+ policy: await policyFor(route.provider, route.model, tools),
56
+ hooks,
57
+ model: route.model,
58
+ origin: route.provider.origin,
59
+ credential: async () => (await route.provider.credential()) ?? "",
60
+ ...(route.price ? { price: route.price } : {}),
61
+ ...(route.provider.headers ? { headers: route.provider.headers } : {}),
62
+ ...(route.fetch ? { fetch: route.fetch } : {}),
63
+ ...(redact ? { redact } : {}),
64
+ }, randomBytes(32).toString("base64url"));
65
+ }
66
+ /** A run's models of other tiers than its own (a learned workflow's node of a tier: AGENT_MODEL_FAST, AGENT_MODEL_STRONG),
67
+ * each on a proxy of its own beside the session's, on the session's booking (`hooks`, io.models): the one way every
68
+ * harness serves them, pi's session and a CLI harness's (cli-run-spec.ts). Only the host's own requests reach them (side
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
+ * proxy speaks its model's route (model-route.ts routeOf, its translation fetch for a model of neither wire), never the
71
+ * harness's. One that fails to start closes those started. */
72
+ export async function openTierProxies(tiers, hooks, redact) {
73
+ const open = new Map();
74
+ const close = async () => {
75
+ for (const { proxy } of open.values())
76
+ await proxy.close().catch(() => undefined);
77
+ };
78
+ try {
79
+ for (const [tier, route] of tiers)
80
+ open.set(tier, { proxy: await routeProxy(route, hooks, [], redact, tier), route });
81
+ }
82
+ catch (error) {
83
+ await close();
84
+ throw error;
85
+ }
86
+ return {
87
+ port: (label, tier) => {
88
+ const at = open.get(tier);
89
+ return at ? { url: at.proxy.url, key: at.proxy.sideKey(label), model: at.route.model, api: at.route.provider.api } : undefined;
90
+ },
91
+ close,
92
+ };
93
+ }
54
94
  /** The session proxy's policy on Messages: claude-agent's (no fork), with pi's tools, the host's own names (`tools`), as
55
95
  * the names its client offers by themselves (its builtins). The CLI's own `mcp__hands__` prefix is not pi's: under it
56
96
  * every one of pi's tool definitions would be dropped and the model offered none. Every other tool definition is
@@ -71,7 +111,7 @@ export async function policyFor(provider, model, tools) {
71
111
  return codexPolicy({ model, tools });
72
112
  }
73
113
  /** The session on its proxy: pi's models through it, the host's tools and the gate as pi's extension, the root's state. */
74
- async function sessionOn(proxy, options, spec, io, context) {
114
+ async function sessionOn(proxy, options, spec, io, context, tiers) {
75
115
  const { run, model, like } = options;
76
116
  const { api } = options.provider;
77
117
  const models = createModels();
@@ -83,7 +123,11 @@ async function sessionOn(proxy, options, spec, io, context) {
83
123
  // A session tool whose name a native extension already owns is run by that extension (pi's own tool task), so it is not
84
124
  // piTool-wrapped here too: one tool by that name on the agent, offered once.
85
125
  const owned = new Set(nativeToolNames(options));
86
- const tools = spec.tools.filter((tool) => !owned.has(tool.name)).map((tool) => piTool(tool, io));
126
+ // The calls the gate let through in this session, before their intent. pi runs a call's beforeTool only before its
127
+ // 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
+ // attempt stored), told to the host tool as an attempt above 0, so the loop asks the gate about it again.
129
+ 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)));
87
131
  // A refused call's words (the gate's deny, main's), by call: its result is those words alone, as main gives them.
88
132
  const refusals = refusalWords();
89
133
  const extension = defineExtension({
@@ -91,12 +135,17 @@ async function sessionOn(proxy, options, spec, io, context) {
91
135
  tools,
92
136
  hooks: [
93
137
  hook(ToolTask, {
94
- beforeTool: async (call, _api, hookContext) => {
138
+ beforeTool: async (call, api, hookContext) => {
95
139
  if (!io.gate)
96
140
  return undefined;
97
- const answer = await io.gate({ callId: call.id, tool: call.name, args: (call.arguments ?? {}) }, hookContext);
98
- if (answer === "allow")
141
+ // A model-issued call's count, read only when the gate holds a budget: a nested call (one a tool made) is its
142
+ // 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 };
144
+ const answer = await io.gate({ callId: call.id, tool: call.name, args: (call.arguments ?? {}), ...counted }, hookContext);
145
+ if (answer === "allow") {
146
+ passed.add(call.id);
99
147
  return undefined;
148
+ }
100
149
  if ("deny" in answer) {
101
150
  refusals.refuse(call.id, answer.deny);
102
151
  return { block: answer.deny };
@@ -200,11 +249,17 @@ async function sessionOn(proxy, options, spec, io, context) {
200
249
  async close() {
201
250
  closed = true;
202
251
  await proxy.close().catch(() => undefined);
252
+ await tiers.close();
203
253
  },
204
254
  // The session's own model route for a request the host sends beside pi's (a learned workflow's model node): its proxy
205
255
  // with a side key minted for `label`, pi's model and the provider's wire (never a literal), so the request goes through
206
- // the same policy, origin, credential, price and booking as pi's own, labelled. None once the session is closed.
207
- port: (label) => (closed ? undefined : { url: proxy.url, key: proxy.sideKey(label), model, api }),
256
+ // the same policy, origin, credential, price and booking as pi's own, labelled. `tier`: that tier's proxy and model
257
+ // instead (options.tiers), on the same booking; none for a tier the session has no proxy of. None once closed.
258
+ port: (label, tier) => {
259
+ if (closed)
260
+ return undefined;
261
+ return tier === undefined ? { url: proxy.url, key: proxy.sideKey(label), model, api } : tiers.port(label, tier);
262
+ },
208
263
  // A steer: pi places it in the turn in flight, at its next boundary. `id`: its request id (the command's), so the
209
264
  // commit that places it is the one that takes its row. `origin` (a trigger's message): its input is the host's user
210
265
  // entry (KINDS.input) with that origin, in the same submission, so the attribution lands with the message or not at all.
@@ -239,6 +294,20 @@ export function refusalWords() {
239
294
  },
240
295
  };
241
296
  }
297
+ /** The tool calls a hook's conversation made before `callId`, at most `upTo`: its committed entries read oldest first, a
298
+ * page at a time, only as far as the count needs (tool-budget.ts countCalls). */
299
+ async function callsBefore(api, callId, upTo, context) {
300
+ let counted = { count: 0, done: upTo <= 0 };
301
+ let cursor;
302
+ while (!counted.done) {
303
+ const page = await api.entries({ order: "ascending" }, 100, cursor, context);
304
+ counted = countCalls(page.items, callId, upTo, counted.count);
305
+ cursor = page.next;
306
+ if (cursor === undefined)
307
+ break;
308
+ }
309
+ return counted.count;
310
+ }
242
311
  /** pi's output limits for a host tool, from the host's result bound: a result within it holds at most that many
243
312
  * characters (UTF-16 units), so at most that many lines plus one, and three bytes of UTF-8 to a character. pi's own
244
313
  * default (50 KB or 2,000 lines, its head kept) would cut the end off a host tool's answer, where the answer says how to
@@ -249,8 +318,9 @@ export const HOST_TOOL_OUTPUT = Object.freeze({ maxLines: HOST_RESULT_MAX_CHARS
249
318
  /** A host tool as a pi tool: replay-safe or at most once, its answer the host's text and any images it shows, passed
250
319
  * whole within the host's bound (HOST_TOOL_OUTPUT). Each call gets what pi's own tool task gives a tool: the calling
251
320
  * agent's model, resolved in the session's models (its input and input limits, which a file read sizes an image by),
252
- * and pi's output stream (the running tool's live slot). */
253
- function piTool(tool, io) {
321
+ * and pi's output stream (the running tool's live slot); and its attempt (`attemptOf`: above 0 for a call the gate did
322
+ * not pass in this session, pi's rerun after a crash). */
323
+ function piTool(tool, io, attemptOf = () => undefined) {
254
324
  return defineTool({
255
325
  name: tool.name,
256
326
  description: tool.description,
@@ -259,12 +329,14 @@ function piTool(tool, io) {
259
329
  outputLimits: HOST_TOOL_OUTPUT,
260
330
  execute: async (args, api, toolContext) => {
261
331
  io.onEvent({ type: "tool_start", callId: api.callId, name: tool.name, args });
332
+ const attempt = attemptOf(api.callId);
262
333
  const ref = (await api.agent(toolContext)).model;
263
334
  const model = ref === undefined ? undefined : api.models.getModel(ref.provider, ref.modelId);
264
335
  const answer = await tool.call(args ?? {}, {
265
336
  callId: api.callId, signal: toolContext.abortSignal ?? io.signal,
266
337
  ...(model ? { model } : {}),
267
338
  output: (chunk) => api.output(chunk),
339
+ ...(attempt === undefined ? {} : { attempt }),
268
340
  });
269
341
  io.onEvent({ type: "tool_end", callId: api.callId, name: tool.name, isError: Boolean(answer.isError), result: answer.text });
270
342
  const images = (answer.images ?? []).map((image) => ({ type: "image", data: image.data, mimeType: image.mimeType }));
@@ -37,3 +37,11 @@ export declare function runnerBeside(dataDir: string, { loops, drainMs, env, jan
37
37
  runner: Awaited<ReturnType<typeof import("./runner.js")["startRunner"]>>;
38
38
  close: () => Promise<void>;
39
39
  }>;
40
+ /** A server and one runner beside it, both in this process, as the CLI's start composes them (cli.ts): the runner holds
41
+ * what the server's options say (besideRunnerOptions) and sees the server's test switches (fauxEnvOf), so a --faux
42
+ * server's runs reach its fakes. For a launcher that starts serve in-process (a demo, a smoke): a server alone leaves
43
+ * every run queued. close() stops both. */
44
+ export declare function serveWithRunner(options: import("../server.js").ServeOptions): Promise<{
45
+ serve: import("../server.js").Serve;
46
+ close(): Promise<void>;
47
+ }>;
@@ -70,3 +70,21 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor } = {
70
70
  // The janitor's sweep is cut and waited for on a bound of its own, beside the runner's close, never before it.
71
71
  return { runner, close: async () => { await Promise.all([swept?.close(), runner.close()]); await store.close(); seal.release(); } };
72
72
  }
73
+ /** A server and one runner beside it, both in this process, as the CLI's start composes them (cli.ts): the runner holds
74
+ * what the server's options say (besideRunnerOptions) and sees the server's test switches (fauxEnvOf), so a --faux
75
+ * server's runs reach its fakes. For a launcher that starts serve in-process (a demo, a smoke): a server alone leaves
76
+ * every run queued. close() stops both. */
77
+ export async function serveWithRunner(options) {
78
+ const { fauxEnvOf, startServe } = await import("../server.js");
79
+ const { besideRunEnv } = await import("./main.js");
80
+ const { loops, drainMs } = besideRunnerOptions(options, process.env);
81
+ const serve = await startServe(options);
82
+ const beside = await runnerBeside(options.data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(options)) }).catch(async (error) => {
83
+ await serve.close();
84
+ throw error;
85
+ });
86
+ // Once: a second call (a SIGTERM and a SIGINT both) is the first one's promise, so the runner's store is never closed
87
+ // under a run still finishing.
88
+ let closing;
89
+ return { serve, close: () => (closing ??= Promise.all([beside.close(), serve.close()]).then(() => undefined)) };
90
+ }
@@ -1,4 +1,5 @@
1
1
  import type { LearnedWorkflow } from "../learning.js";
2
+ import { type Tier } from "../model.js";
2
3
  import type { RunLaunch } from "../run-launch.js";
3
4
  import type { SealedKeys } from "../store/store.js";
4
5
  import type { Revision } from "../agent-rows.js";
@@ -24,6 +25,11 @@ export declare function claimSecrets(deps: ClaimSecretsDeps, revision: Revision,
24
25
  * workflow that does not parse or inspect names no provider: the tool refuses it before any node runs. No workflow, or
25
26
  * no provider left, reads nothing. A fresh object per call, so no run's keys reach another's. */
26
27
  export declare function learnedDecisionKeys(deps: ClaimSecretsDeps, workflows: readonly Pick<LearnedWorkflow, "workflow">[], allowed: (provider: string) => boolean): Promise<Record<string, string>>;
28
+ /** The model keys the host's models of `tiers` need (model.ts modelKeys: each one's provider's, or the gateway's), read as
29
+ * claimSecrets reads a run's (the runner's environment first, then the key saved in Settings → Model keys), for a run's
30
+ * learned workflow nodes of those tiers (adapter-run-spec.ts learnedTierRoutes): claimSecrets opens only the run's own
31
+ * model's. For the tiers' routes alone, through withModelKeys (never enumerable), never onto a tool's environment. */
32
+ export declare function tierModelKeys(deps: ClaimSecretsDeps, tiers: readonly Tier[]): Promise<NodeJS.ProcessEnv>;
27
33
  /** Every model key a model route reads by name: each of pi-ai's providers' (model.ts PROVIDER_KEYS) and the gateway's. */
28
34
  export declare const MODEL_KEY_NAMES: readonly string[];
29
35
  /** `env` for a model route (model-route.ts routeOf, a CLI's providerFor): the runner's own environment, its secrets kept
@@ -7,7 +7,7 @@
7
7
  // one runner never see each other's keys: each claim reads its own, into its own environment. (MCP credentials are the
8
8
  // other per-claim secret; they come through mcp-claim.ts, which already opens them from the store under the claim.)
9
9
  import { decisionKeysFor, providersNamed } from "../decisions.js";
10
- import { GATEWAY_KEY_ENV, PROVIDER_KEYS, workflowNodes } from "../model.js";
10
+ import { GATEWAY_KEY_ENV, modelKeys, PROVIDER_KEYS, workflowNodes } from "../model.js";
11
11
  import { keysFor, needsOf, RUN_SECRETS } from "../run-secrets.js";
12
12
  import { DECISION_KEYS, withoutSecrets } from "../secrets.js";
13
13
  import { getSealedKey } from "../server-keys.js";
@@ -78,6 +78,20 @@ export async function learnedDecisionKeys(deps, workflows, allowed) {
78
78
  return {};
79
79
  return decisionKeysFor(await workingEnv(deps), { providers, parallelWeb: false });
80
80
  }
81
+ /** The model keys the host's models of `tiers` need (model.ts modelKeys: each one's provider's, or the gateway's), read as
82
+ * claimSecrets reads a run's (the runner's environment first, then the key saved in Settings → Model keys), for a run's
83
+ * learned workflow nodes of those tiers (adapter-run-spec.ts learnedTierRoutes): claimSecrets opens only the run's own
84
+ * model's. For the tiers' routes alone, through withModelKeys (never enumerable), never onto a tool's environment. */
85
+ export async function tierModelKeys(deps, tiers) {
86
+ if (!tiers.length)
87
+ return {};
88
+ const working = await workingEnv(deps);
89
+ const out = {};
90
+ for (const name of modelKeys(working, undefined, tiers))
91
+ if (working[name] !== undefined)
92
+ out[name] = working[name];
93
+ return out;
94
+ }
81
95
  /** Every model key a model route reads by name: each of pi-ai's providers' (model.ts PROVIDER_KEYS) and the gateway's. */
82
96
  export const MODEL_KEY_NAMES = [...new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV])];
83
97
  /** `env` for a model route (model-route.ts routeOf, a CLI's providerFor): the runner's own environment, its secrets kept
@@ -9,6 +9,9 @@ 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
+ /** A claim's private folder removed, then each of `parents` in order while it is empty: one another claim of the run has
13
+ * laid things in since (a follow-up's) stays, with what is in it. */
14
+ export declare function sweepScratch(dir: string, parents: readonly string[]): Promise<void>;
12
15
  /**
13
16
  * One claimed CLI run's AdapterRunSpec, built from its launch record and its revision.
14
17
  *