@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
@@ -2,10 +2,13 @@ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/conte
2
2
  import { createModels } from "@earendil-works/pi-ai/models";
3
3
  import { createRegistry, defineDoc, Harness, LiveDoc, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
4
4
  import { answeredUnpriced, modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
5
- import { ASK_PERSON_WAITING, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
- import { endedOnTurnEndingTool, HOST_PHASE, originOf, RUN_RESUMED } from "../timeline/index.js";
5
+ import { ASK_PERSON_WAITING, capNowOf, endedAnswer, KINDS, MESSAGE_SENT_AGAIN, withdrawnAnswers } from "./journal-kinds.js";
6
+ import { endedOnTurnEndingTool, HOST_PHASE, MESSAGE_ORIGIN, originOf, RUN_RESUMED } from "../timeline/index.js";
7
+ import { raiseFollowUpId } from "../run-view.js";
8
+ /** A raised run's follow-up is the server's message (the kernel cap's followUpOf), never the person's. */
9
+ const CAP_RAISED_ORIGIN = { kind: "server", reason: "cap_raised" };
7
10
  import { ClaimRefused, deniedText, endedBy, noteOf } from "./loop-contract.js";
8
- import { deniedText as setToDenyText, ENDED_WHILE_WAITING, STOPPED_WHILE_WAITING } from "../refusal-words.js";
11
+ import { deniedText as setToDenyText, ENDED_WHILE_WAITING, refusedText, STOPPED_WHILE_WAITING } from "../refusal-words.js";
9
12
  import { ADAPTER_API } from "../turn-end.js";
10
13
  import { answerText, REFLECT_NOTE_ONLY, reflectRequestId, underLearning, WRITES } from "./end-of-run.js";
11
14
  import { approvalOf, CLOSE_MS, CUT_STEP_MS, STOP_SETTLE_MS, commandRequest, cutLast, DEFAULT_RESTART_LIMIT, entriesOf, findData, Gate, heldReporter, Interrupted, KernelFault, Parked, quiet, restartLimited, writesEntry, writesSubmission } from "./loop.js";
@@ -13,14 +16,15 @@ import { answerOnce, HAND_BACK, handBackOf } from "./hand-back.js";
13
16
  import { isComputerCommand, journalHold } from "./computer-journal.js";
14
17
  import { COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND } from "../computer-commands.js";
15
18
  import { journalSessions } from "./sessions.js";
16
- import { DECISION_SESSION, overCapOf, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
17
- import { portModels } from "../port-models.js";
19
+ import { DECISION_SESSION, FIT_TOLERANCE, overCapOf, paidRefusal, runCap, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
20
+ import { PORT_PROVIDER, portModels, tierProvider } from "../port-models.js";
18
21
  import { bookedIn } from "../paid-calls.js";
19
22
  import { withHostCalls } from "../host-calls.js";
20
23
  import { sideEffect } from "./side-effects.js";
21
24
  import { McpClaimRefused } from "./mcp-claim.js";
22
25
  import { Fenced } from "../store/index.js";
23
26
  import { parkedFollowUp } from "./mcp-run.js";
27
+ import { TOOL_BUDGET_TEXT, WRAP_UP_TEXT, wrappingUp } from "../tool-budget.js";
24
28
  /** A pause or resume row on an agentic run, refused in main's words (runs.ts pause): only a workflow run pauses. */
25
29
  export const AGENTIC_PAUSE_REFUSED = "Only a workflow run pauses here: an agentic run's turn is stopped with POST /runs/{id}/stop.";
26
30
  /** The request ids of the person's messages placed as turns (loop.ts commandRequest). */
@@ -53,6 +57,23 @@ export function agentConversation(record) {
53
57
  const RootWritesOwed = defineDoc({ kind: "agentrun.root-writes-owed", version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ owed: false }), checkpointWhen: () => false });
54
58
  /** The most of a harness's own turn error a failed run's summary keeps. */
55
59
  const TURN_ERROR_MAX = 500;
60
+ /** A paid call's refusal an earlier claim kept (KINDS.pausePending) whose pause never landed: the newest one with no
61
+ * pause (KINDS.budget), no end and no park on a person's question (KINDS.personAsked: the turn ended on the ask with no
62
+ * next request, so the refusal is spent, and the person's answer is no retry of the call) after it. Undefined when there
63
+ * is none. */
64
+ export function pendingPauseOf(entries) {
65
+ for (let at = entries.length - 1; at >= 0; at--) {
66
+ const entry = entries[at];
67
+ if (entry.kind === KINDS.budget || entry.kind === KINDS.end || entry.kind === KINDS.personAsked)
68
+ return undefined;
69
+ // A kept refusal, or none: a drop kept as null (the call would since fit, or the turn ended on a question).
70
+ if (entry.kind === KINDS.pausePending)
71
+ return (entry.data ?? undefined);
72
+ }
73
+ return undefined;
74
+ }
75
+ /** How long a turn's end waits for the runner to hand on the rows it has not yet (LoopDeps.deliverNow). */
76
+ const DELIVER_NOW_MS = 5_000;
56
77
  /** `text` cut to at most `max` UTF-16 units, never inside a character: a high surrogate the cut leaves alone goes too. */
57
78
  const cutWhole = (text, max) => {
58
79
  const cut = text.slice(0, max);
@@ -122,7 +143,7 @@ const refusalOf = (refusal) => ({ message: refusal.refuse, forGood: refusal.forG
122
143
  * fault left with a start and no end ended interrupted (the CLI never runs it again: its own resume says so). Each entry
123
144
  * it writes carries when it was written (`at`, ms, from the loop's clock `now`), as pi's own entries carry their
124
145
  * message's timestamp: the Timeline dates its rows by them. */
125
- async function openCliRecord(harness, journal, context, now) {
146
+ async function openCliRecord(harness, journal, context, now, cwd) {
126
147
  const root = await harness.root(context);
127
148
  const append = async (kind, data) => {
128
149
  await harness.commit((tx) => tx.appendEntry(root.id, { kind, data: { ...data, at: now() } }), context);
@@ -239,16 +260,16 @@ async function openCliRecord(harness, journal, context, now) {
239
260
  }
240
261
  return;
241
262
  }
242
- await append(KINDS.callStart, { callId, tool, input, replaySafe });
263
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, ...(cwd ? { cwd } : {}) });
243
264
  started.set(callId, false);
244
265
  });
245
266
  },
246
- async park(callId, tool, input, replaySafe) {
267
+ async park(callId, tool, input, replaySafe, bridge) {
247
268
  await flushText();
248
269
  await inTurn(async () => {
249
270
  if (started.has(callId))
250
271
  return;
251
- await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true });
272
+ await append(KINDS.callStart, { callId, tool, input, replaySafe, parked: true, ...(bridge ? { bridge } : {}), ...(cwd ? { cwd } : {}) });
252
273
  started.set(callId, false);
253
274
  parked.add(callId);
254
275
  });
@@ -404,6 +425,11 @@ function adapterLoop(specOf, options, deps) {
404
425
  * it (sendAfterTurn) (#2174: refused here, a message the API had accepted was lost). Kept across a pass's restart; a row still here
405
426
  * when the claim ends is untaken, so the run's next claim takes it again, or the run's end refuses it in the end's words. */
406
427
  const afterTurn = [];
428
+ /** The request ids of the messages placed as steers into a turn in flight (a harness that steers: pi), in order. pi
429
+ * answers one in the turn it steered, or, placed as that turn answered, in a run of its own right after it: the turn's
430
+ * end waits on each one's submission (turnOfRequest) before the run may end, so the run never reads completed with a
431
+ * message it took still unanswered, and its session is never closed under that answer. */
432
+ const steeredIn = [];
407
433
  /** Set once the claim's last turn has ended and nothing more is sent: a message after it waits for the run's end, as one
408
434
  * during the end-of-run turn does. */
409
435
  let turnsOver = false;
@@ -453,6 +479,20 @@ function adapterLoop(specOf, options, deps) {
453
479
  /** An MCP tool of the run as the claim's pass wrapped it, by its catalog name (set once its tools are wrapped). */
454
480
  let mcpHosted = () => undefined;
455
481
  let mcpStale = false;
482
+ /** Marks the raise's follow-up the server's (MESSAGE_ORIGIN, timeline/origin.ts) before it is sent: its own commit, the
483
+ * input's user entry left as pi writes it (its submission, which a re-claim answers from, unchanged), so the Timeline
484
+ * shows the next user entry with exactly this text as "AgentRun: …". Once per follow-up: the marker names its request
485
+ * id, and a re-claim that finds one under it writes none (a second would stay open, and could take a person's later
486
+ * message of the same words for the server's). A CLI's run records its follow-up through its own record, which carries
487
+ * the origin itself. */
488
+ const markServerFollowUp = async (theHarness, theRoot, text, requestId) => {
489
+ if (cliRecord)
490
+ return;
491
+ const marked = (await entriesOf(gate.journal, theRoot.id, context)).some((entry) => entry.kind === MESSAGE_ORIGIN && entry.data?.requestId === requestId);
492
+ if (marked)
493
+ return;
494
+ await theHarness.commit((tx) => tx.appendEntry(theRoot.id, { kind: MESSAGE_ORIGIN, data: { origin: CAP_RAISED_ORIGIN, text, requestId } }), context);
495
+ };
456
496
  /** The run's raise state, read from its root: the newest budget entry with no raise entry after it is the pause it
457
497
  * waits at (its pending cap is the cap a raise is checked against); the newest raise entry is its last raise. */
458
498
  async function raiseStateOf() {
@@ -649,6 +689,10 @@ function adapterLoop(specOf, options, deps) {
649
689
  afterTurn.push({ commandId: command.id, text, requestId, ...(origin ? { origin } : {}) });
650
690
  return { taken: true };
651
691
  }
692
+ // The claim's last turn has ended and nothing more is sent (turnsOver): a steer placed now would start a turn the run's
693
+ // end then cuts, so it waits for the run's end, as a CLI's message does.
694
+ if (turnsOver && !askedLast)
695
+ return { later: "the run has answered and is ending: the message waits for the run's end" };
652
696
  // A person's answer to the question the last turn ended on (a parked ask's, its run claimed again by it): the row's
653
697
  // waiting summary goes in its commit, as an in-claim wait's answer clears it. Left until the end commit, the answer's
654
698
  // turn reads running, held and "Waiting for your reply", and the server tells run.needs_input for that ask again.
@@ -671,6 +715,9 @@ function adapterLoop(specOf, options, deps) {
671
715
  return { later: "the run is parking: the steer waits for its resume" };
672
716
  return { refused: `the steer was not placed: ${error.message}` };
673
717
  }
718
+ // Placed in the turn in flight: the turn's end waits for it to be answered (steeredIn), never ending the run first.
719
+ if (!askedLast)
720
+ steeredIn.push(requestId);
674
721
  await taken.catch(() => { });
675
722
  return { taken: true };
676
723
  };
@@ -787,7 +834,7 @@ function adapterLoop(specOf, options, deps) {
787
834
  },
788
835
  // Lazy, as main's process takes them (portModels(() => sessionPort?.(...))): a spec takes them at its build, and
789
836
  // each request reads the session's port then, there once the session is open.
790
- models: (label) => portModels(() => session?.port?.(label)),
837
+ models: (label, tier) => portModels(() => session?.port?.(label, tier), undefined, tier === undefined ? PORT_PROVIDER : tierProvider(tier)),
791
838
  pause: async (refusal) => {
792
839
  await pauseFor?.(refusal);
793
840
  },
@@ -916,10 +963,38 @@ function adapterLoop(specOf, options, deps) {
916
963
  // bound, and that bound kept, so a possible cache miss pauses the run, never fails it).
917
964
  return overCapOf(await sessions.read(spec.session.key), others, cap);
918
965
  };
966
+ /** A paid call's pending pause as it lands, at the model's next request: said again with the run's spend as it is
967
+ * now (every session's booked spend; the turn's calls have all ended, so nothing else is held), so the budget card
968
+ * counts what parallel calls settled since the refusal. Undefined when the call would now fit (one of them settled
969
+ * for less than it held): no pause, and the request goes to the cap as any does. A refusal with no call named on
970
+ * it, or a spend unknown, lands as it was. */
971
+ const landing = async (pending) => {
972
+ const step = pending.figures?.step;
973
+ const cap = capNow();
974
+ if (!step || cap === undefined)
975
+ return pending;
976
+ let spent = 0;
977
+ for (const key of await sessions.keys()) {
978
+ const spend = sessionSpendOf(await sessions.read(key)).spentUsd;
979
+ if (spend === null)
980
+ return pending;
981
+ spent += spend;
982
+ }
983
+ if (spent + step.holdUsd <= cap + FIT_TOLERANCE)
984
+ return undefined;
985
+ const { text, figures } = paidRefusal(cap, spent, 0, step.name, step.holdUsd, step.basis);
986
+ return { ...pending, refuse: text, figures };
987
+ };
919
988
  const beforeRequest = async (request) => {
920
989
  // A run whose booked spend passed its cap sends nothing more: it ends in the cap's words (overCap), never paused,
921
990
  // whatever else would pause it (a paid call's refusal, pendingPause).
922
991
  const over = await overCap();
992
+ if (!over && pendingPause) {
993
+ pendingPause = await landing(pendingPause);
994
+ // Fits now: dropped for good, on the root too, so a later claim never revives the old refusal.
995
+ if (pendingPause === undefined)
996
+ await keepPending(null);
997
+ }
923
998
  const answer = over ? { refuse: over, forGood: true } : (pendingPause ?? (await theCap().before(request)));
924
999
  if (answer && "refuse" in answer) {
925
1000
  refused = answer;
@@ -927,10 +1002,29 @@ function adapterLoop(specOf, options, deps) {
927
1002
  }
928
1003
  return answer;
929
1004
  };
1005
+ // A paid call's refusal is the call's result first: its pause is journaled at the model's next request (beforeRequest,
1006
+ // pendingPause), once the harness has stored that result, so the run never reads waiting on a raise before its
1007
+ // Timeline says why. The refusal is kept on the root at once (KINDS.pausePending, no run patch, nothing a person
1008
+ // reads), so a claim lost in between restores it (pendingPauseOf) and the next claim's request parks the run.
930
1009
  pauseFor = async (refusal) => {
931
1010
  pendingPause = refusal;
932
- await pauseAt(refusal);
1011
+ await keepPending(refusal);
933
1012
  };
1013
+ /** The pending pause kept on the root (KINDS.pausePending): a refusal, or null once it is dropped for good (the call
1014
+ * would now fit, or the turn ended on a question), which pendingPauseOf reads as none. */
1015
+ async function keepPending(refusal) {
1016
+ if (!harness || !gate || gate.sealed)
1017
+ return;
1018
+ const on = harness;
1019
+ try {
1020
+ const conversation = root ?? (await on.root(context));
1021
+ await on.commit(async (tx) => void (await tx.appendEntry(conversation.id, { kind: KINDS.pausePending, data: refusal })), context);
1022
+ }
1023
+ catch {
1024
+ // Not kept (the journal sealed: the claim lost or the run parking): a refusal still parks this claim's own
1025
+ // request; a drop leaves the next claim to judge the old refusal again when it lands (landing).
1026
+ }
1027
+ }
934
1028
  async function pauseAt(answer) {
935
1029
  {
936
1030
  // A refusal a raise could fix (the cap's rule, parkOf) journals its pause, the run parked, before the refusal
@@ -975,9 +1069,28 @@ function adapterLoop(specOf, options, deps) {
975
1069
  const toolsAtOpen = sessionSpendOf(await sessions.read(TOOL_SESSION));
976
1070
  if (spec.runCap && toolsAtOpen.turns.some((turn) => !toolsAtOpen.answered.has(turn)))
977
1071
  await paidOf();
978
- const gateOf = preIntentGate(spec, hooks);
1072
+ // The cap's wrap-up (tool-budget.ts wrappingUp): what every session of the run has taken as the cap counts it, its
1073
+ // spend and each request or paid step still out at its hold and bound, read from the run's records at each call. A
1074
+ // hold-only step still open (a browser session's reserve) is no spend in its records, but the cap holds it in
1075
+ // flight: it counts at its hold too. One a lost claim left open was given back at this claim's open (bookCut).
1076
+ const wrapUp = async () => {
1077
+ // A run whose spec gives no cap (no runCap) has none to wrap up at, as overCap reads it.
1078
+ if (!spec.runCap)
1079
+ return false;
1080
+ const capUsd = capNow();
1081
+ if (capUsd === undefined)
1082
+ return false;
1083
+ let taken = 0;
1084
+ for (const key of await sessions.keys()) {
1085
+ const read = sessionSpendOf(await sessions.read(key));
1086
+ const reserved = [...read.openHolds].reduce((sum, turn) => sum + (read.held.get(turn) ?? 0), 0);
1087
+ taken = taken === null || read.spentUsd === null ? null : taken + read.spentUsd + reserved;
1088
+ }
1089
+ return wrappingUp(capUsd, taken);
1090
+ };
1091
+ const gateOf = preIntentGate(spec, hooks, wrapUp);
979
1092
  // A CLI's run: the loop keeps its visible record (record: "loop"), every call a crash or a fault left open ended.
980
- const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now) : undefined;
1093
+ const record = spec.record === "loop" ? await openCliRecord(harness, gate.journal, context, now, spec.cwd) : undefined;
981
1094
  cliRecord = record;
982
1095
  // Each tool the session runs on the host, the host's own and any its adapter adds (SessionIO.hostTool: a CLI's
983
1096
  // read_skill_file), the same way: a CLI's call on its record, so the run's Timeline shows it and its result.
@@ -995,6 +1108,34 @@ function adapterLoop(specOf, options, deps) {
995
1108
  const ended = record?.endOf(toolContext.callId);
996
1109
  if (ended)
997
1110
  return endedAnswer(tool.name, ended);
1111
+ // A call run again after an earlier attempt (the harness's rerun of a replay-safe call after a crash: its
1112
+ // attempt above 0) never passed the gate before its intent this time: the gate is asked again here, so a deny
1113
+ // set since the first attempt refuses the rerun, in words saying the earlier attempt may have taken effect.
1114
+ if ((toolContext.attempt ?? 0) > 0 && spec.gate) {
1115
+ // By the name the gate before the intent asks it by: an MCP tool by its catalog name.
1116
+ const name = mcp?.catalogOf(tool.name) ?? tool.name;
1117
+ const asked = spec.gate.askedAs?.(name) ?? name;
1118
+ const now = await spec.gate({ callId: toolContext.callId, tool: name, args: (args ?? {}) }, { replayed: true });
1119
+ if (now === "deny")
1120
+ return { text: setToDenyText(asked, undefined, "server", "unknown"), isError: true };
1121
+ if (typeof now === "object")
1122
+ return { text: now.deny, isError: true };
1123
+ // Set to ask since (or asked, and answered before the crash): asked as any call is, as main's gate parked a
1124
+ // replayed call as a request of its own. Its answer stands; else the run parks on it, the call held unrun until
1125
+ // the claim lets it go; a deny says the earlier attempt may have taken effect.
1126
+ if (now === "ask") {
1127
+ const call = { callId: toolContext.callId, tool: name, args: (args ?? {}) };
1128
+ const answer = await answerOf(call, mcp?.priceOf(name) ?? spec.approvalPrice?.({ ...call, tool: name }) ?? null, asked);
1129
+ if (answer === "park")
1130
+ return await heldUntilAborted(toolContext.signal);
1131
+ if (!answer.approved)
1132
+ return { text: refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown"), isError: true };
1133
+ }
1134
+ // pi let this call start before it was asked here: a stop while the gate or a person was asked wins over the
1135
+ // permission that came after it, and the call is never started.
1136
+ if (stopAbort.signal.aborted || toolContext.signal?.aborted)
1137
+ return { text: STOPPED_WHILE_WAITING, isError: true };
1138
+ }
998
1139
  if (record)
999
1140
  await record.start(toolContext.callId, tool.name, args ?? {}, tool.replay === "safe");
1000
1141
  try {
@@ -1083,14 +1224,24 @@ function adapterLoop(specOf, options, deps) {
1083
1224
  };
1084
1225
  // The gate a CLI's tool bridge asks before anything of a call: a call it refuses never reaches its host tool, so its
1085
1226
  // start and its end, refused in the gate's words, go on the record here, as pi writes a refused call and its error
1086
- // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it).
1227
+ // result (a deny set, no one to approve, or a person's deny of its ask on the claim that resumes it). A call it asks
1228
+ // about goes on the record first, its start marked parked (once per call id), as an MCP call parked at its door does,
1229
+ // and marked the bridge's: the bridge hands the CLI nothing while it waits, so no waiting result shows, as on pi. Its
1230
+ // row shows while it waits, before its approval; the claim that runs it once allowed writes its sent mark on that
1231
+ // one start (start()), and a stop withdraws it never sent (unsentParked). A start refused because another call of the
1232
+ // round parked the run first (the journal sealed) leaves this call held as that one is.
1233
+ const replaySafe = (name) => tools.find((one) => one.name === name)?.replay === "safe";
1234
+ const askingGate = record
1235
+ ? preIntentGate(spec, hooks, wrapUp, (call) => record.park(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), true).catch((error) => {
1236
+ if (!gate?.sealed)
1237
+ throw error;
1238
+ }))
1239
+ : gateOf;
1087
1240
  const bridgeGate = record
1088
1241
  ? async (call, hookContext) => {
1089
- const answer = await gateOf(call, hookContext);
1090
- if (answer !== "allow" && "deny" in answer) {
1091
- const tool = tools.find((one) => one.name === call.tool);
1092
- await record.refused(call.callId, call.tool, call.args ?? {}, tool?.replay === "safe", answer.deny);
1093
- }
1242
+ const answer = await askingGate(call, hookContext);
1243
+ if (answer !== "allow" && "deny" in answer)
1244
+ await record.refused(call.callId, call.tool, call.args ?? {}, replaySafe(call.tool), answer.deny);
1094
1245
  return answer;
1095
1246
  }
1096
1247
  : gateOf;
@@ -1133,10 +1284,16 @@ function adapterLoop(specOf, options, deps) {
1133
1284
  // The run's journal so far: a take an earlier claim's computer left in force ends released here (computer-journal.ts).
1134
1285
  await computerNow.up(await entriesOf(gate.journal, root.id, context));
1135
1286
  }
1136
- // The cap a raise left the run at, from its root (the newest raise entry), before any request of this claim: a
1137
- // claim that takes over a raised run (a resume, another runner's) holds it to the raise, never the launch's cap.
1287
+ // The cap a raise left the run at, before any request of this claim, through the one reader the run view and its
1288
+ // budget card read too (capNowOf: the newest raise entry, else the launch's cap): a claim that takes over a raised
1289
+ // run (a resume, another runner's, a restarted server's) holds it to the raise, never the launch's cap.
1138
1290
  if (spec.cap)
1139
- raisedCapUsd = (await raiseStateOf()).lastRaise?.to ?? raisedCapUsd;
1291
+ raisedCapUsd = capNowOf(spec.cap.capUsd, await entriesOf(gate.journal, root.id, context)) ?? raisedCapUsd;
1292
+ // A paid call an earlier claim refused for room whose pause never landed (the claim lost between the call's stored
1293
+ // result and the model's next request): its pending pause, restored, so that request is refused in its words and
1294
+ // the run parks for the raise the call needs.
1295
+ if (spec.cap && pendingPause === undefined)
1296
+ pendingPause = pendingPauseOf(await entriesOf(gate.journal, root.id, context)) ?? pendingPause;
1140
1297
  // A run brought back from a park: the raises its claim has are taken together, once its delivery is done. So is a
1141
1298
  // run whose journal still holds an unanswered budget pause, whatever its row said at the claim: a resumed claim lost
1142
1299
  // before its raise entry landed leaves the run running, its pause unanswered and its raises untaken.
@@ -1147,6 +1304,11 @@ function adapterLoop(specOf, options, deps) {
1147
1304
  // Taken over from a runner whose lease ran out mid-run: said on the run's timeline once, at this claim's first pass.
1148
1305
  if (restarts === 0 && claim.lost)
1149
1306
  await noteTakenOver(harness, root, claim.lost.runner);
1307
+ // What this claim laid of the run's learning seed, once per claim: the newest is what the run was given.
1308
+ if (restarts === 0 && spec.learningLaid) {
1309
+ const [journalOf, rootOf, laid] = [harness, root, spec.learningLaid];
1310
+ await journalOf.commit((tx) => tx.appendEntry(rootOf.id, { kind: KINDS.learningLaid, data: { skills: [...laid.skills], workflows: [...laid.workflows] } }), context);
1311
+ }
1150
1312
  // Reopened by a person's follow-up (runs.reopen): its journal holds an end and its session opens idle. Set before the
1151
1313
  // session is ready, so the follow-up's steer, handed over once it is, is sent as this claim's turn.
1152
1314
  if (restarts === 0 && session.state === "idle" && (await entriesOf(gate.journal, root.id, context)).some((entry) => entry.kind === KINDS.end))
@@ -1177,7 +1339,11 @@ function adapterLoop(specOf, options, deps) {
1177
1339
  if (paused) {
1178
1340
  if (!resumes || raising.capUsd === undefined || !spec.cap?.followUpOf)
1179
1341
  return await parkAtCap(harness, root, gate, paused);
1180
- await session.send(spec.cap.followUpOf(raising.capUsd).text, { id: `agentrun:raise:${raising.state?.lastRaise?.pause ?? "follow-up"}` });
1342
+ // The server's words, shown as its row ("AgentRun: …"), never as the person's; under the id a raise's answer named.
1343
+ const followUp = spec.cap.followUpOf(raising.capUsd).text;
1344
+ const followUpId = raiseFollowUpId(raising.state?.lastRaise?.pause ?? "follow-up");
1345
+ await markServerFollowUp(harness, root, followUp, followUpId);
1346
+ await session.send(followUp, { id: followUpId });
1181
1347
  followedUp = true;
1182
1348
  }
1183
1349
  }
@@ -1188,7 +1354,10 @@ function adapterLoop(specOf, options, deps) {
1188
1354
  // the run's, is the follow-up's, never the first input's.
1189
1355
  const state = await raiseStateOf();
1190
1356
  if (state.pause === undefined && state.lastRaise?.pause !== undefined) {
1191
- await session.send(spec.cap.followUpOf(state.lastRaise.to).text, { id: `agentrun:raise:${state.lastRaise.pause}` });
1357
+ const followUp = spec.cap.followUpOf(state.lastRaise.to).text;
1358
+ const followUpId = raiseFollowUpId(state.lastRaise.pause);
1359
+ await markServerFollowUp(harness, root, followUp, followUpId);
1360
+ await session.send(followUp, { id: followUpId });
1192
1361
  followedUp = true;
1193
1362
  }
1194
1363
  }
@@ -1349,6 +1518,12 @@ function adapterLoop(specOf, options, deps) {
1349
1518
  // its claim, as the browser's hand-over does, the person's time held under its cap (waitInClaim); their answer is
1350
1519
  // its next turn, on the same session. With nothing open, it parks (parkOnAsk).
1351
1520
  const callId = endedOnTurnEndingTool(settledEntries);
1521
+ // Ended on the question with no next request: a paid call's pending pause from this turn is spent, so the
1522
+ // person's answer is never refused in that call's words (pendingPauseOf stops at the ask's park too).
1523
+ if (pendingPause) {
1524
+ pendingPause = undefined;
1525
+ await keepPending(null);
1526
+ }
1352
1527
  const waited = await waitInClaim(harness, callId);
1353
1528
  if (waited) {
1354
1529
  turn = waited.next;
@@ -1361,12 +1536,34 @@ function adapterLoop(specOf, options, deps) {
1361
1536
  // An answer cut at the model's output limit is unfinished: the run fails, saying so, never ended (loop.ts cutLast,
1362
1537
  // the direct loop's rule: the words are loop-contract's cutAtLimit).
1363
1538
  const cut = cutLast(settledEntries);
1539
+ // The rows the runner has not handed on yet (its next poll may be half a second away): handed on now, so a
1540
+ // message sent while the turn worked is one of the run's turns below, never refused by its end. Bounded: a
1541
+ // command that waits on this loop cannot hold its end.
1542
+ if (!cut && afterTurn.length === 0 && steeredIn.length === 0 && deps.deliverNow) {
1543
+ let bound;
1544
+ await Promise.race([deps.deliverNow().catch(() => undefined), new Promise((resolve) => (bound = setTimeout(resolve, DELIVER_NOW_MS)))]);
1545
+ clearTimeout(bound);
1546
+ // A stop or cancel among them: the run ends stopped in its words, its row taken, never completed. Its turn
1547
+ // has ended, so there is nothing to settle. Read past the narrowing TypeScript did before the delivery.
1548
+ const cutBy = stopReason;
1549
+ if (cutBy?.kind === "command")
1550
+ return await writeEnd(harness, root, gate, { state: "stopped", summary: endedBy(cutBy.cancel) }, [cutBy.commandId], await cutRows(claim, spec, "stopped"));
1551
+ if (cutBy || deps.signal.aborted)
1552
+ return await interrupted(cutBy?.kind ?? "its claim's signal aborted");
1553
+ }
1364
1554
  // A message taken while the turn ran (afterTurn): the run's next turn, on the same session, before its end.
1365
1555
  const next = cut ? undefined : afterTurn.shift();
1366
1556
  if (next) {
1367
1557
  turn = sendAfterTurn(gate, next);
1368
1558
  continue;
1369
1559
  }
1560
+ // A message steered into the turn (steeredIn): its answer, in that turn or a run of its own after it, before
1561
+ // the run's end. One already answered settles at once.
1562
+ const steered = cut ? undefined : steeredIn.shift();
1563
+ if (steered !== undefined) {
1564
+ turn = turnOfRequest(harness, root, steered);
1565
+ continue;
1566
+ }
1370
1567
  data = cut ? { state: "failed", summary: cut } : { state: "ended" };
1371
1568
  }
1372
1569
  break;
@@ -1438,8 +1635,11 @@ function adapterLoop(specOf, options, deps) {
1438
1635
  await closeSession();
1439
1636
  }
1440
1637
  }
1441
- /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park). */
1442
- function preIntentGate(spec, hooks) {
1638
+ /** The gate before a call's intent: the kernel's beforeIntent point, then allow, deny, or ask (answered, or park).
1639
+ * `wrapUp`: whether the run has taken its share of the cap, so every call the model makes is refused in its fixed words.
1640
+ * `beforeAsk`: what goes on the record of a call the gate asks about, before its ask is written or read (a CLI's call
1641
+ * through its tool bridge: its start, marked parked, so its row shows while it waits and reads before its approval). */
1642
+ function preIntentGate(spec, hooks, wrapUp, beforeAsk) {
1443
1643
  return async (call, _hookContext) => {
1444
1644
  // An MCP tool is asked about by its catalog name (`mcp:<server>/<tool>`), as its settings and its card name it.
1445
1645
  const tool = mcp?.catalogOf(call.tool) ?? call.tool;
@@ -1448,7 +1648,18 @@ function adapterLoop(specOf, options, deps) {
1448
1648
  if (reflecting && WRITES.has(call.tool) && underLearning(spec.workRoot, call.args))
1449
1649
  return { deny: REFLECT_NOTE_ONLY };
1450
1650
  await hooks.beforeIntent(kernelCall);
1451
- const decision = (await spec.gate?.(kernelCall)) ?? "allow";
1651
+ // The tool-call budget, before the gate's settings: a call past it is refused in its fixed words, never parked or
1652
+ // asked about.
1653
+ const budget = spec.gate?.toolCalls;
1654
+ if (budget !== undefined && call.callsBefore && (await call.callsBefore(budget)) >= budget)
1655
+ return { deny: TOOL_BUDGET_TEXT };
1656
+ // The cap's wrap-up, the same way: once the run has taken its share of the cap, every call the model makes is refused
1657
+ // in its fixed words, and the model answers from what it has. A call a running tool makes is that tool's, let through.
1658
+ if (call.nested !== true && (await wrapUp()))
1659
+ return { deny: WRAP_UP_TEXT };
1660
+ // A CLI bridge's call run again after an attempt that may have been sent: its refusals say so (RAN_UNKNOWN).
1661
+ const replayed = call.replayed === true;
1662
+ const decision = (await spec.gate?.(kernelCall, replayed ? { replayed } : {})) ?? "allow";
1452
1663
  if (typeof decision === "object")
1453
1664
  return { deny: decision.deny };
1454
1665
  // Asked about by the name the gate gives (its settings key, as main's pending approval is named), else the call's own;
@@ -1456,7 +1667,7 @@ function adapterLoop(specOf, options, deps) {
1456
1667
  const asked = spec.gate?.askedAs?.(tool) ?? tool;
1457
1668
  // Main's words for a tool set to deny (tool-gate's deniedText, from its one copy in refusal-words.ts).
1458
1669
  if (decision === "deny")
1459
- return { deny: setToDenyText(asked) };
1670
+ return { deny: setToDenyText(asked, undefined, "server", replayed ? "unknown" : "no") };
1460
1671
  if (decision === "allow")
1461
1672
  return "allow";
1462
1673
  // The card shows the call's input, and beside it what the gate says the call would do that the person approves too
@@ -1465,6 +1676,8 @@ function adapterLoop(specOf, options, deps) {
1465
1676
  // Shown first, so a card cut at its preview's bound (ARGS_PREVIEW_BYTES) still names them whatever the input's size.
1466
1677
  // The gate's own fields win over any of the same name in the call's input, which the model wrote.
1467
1678
  const args = shown ? { ...shown, ...Object.fromEntries(Object.entries((call.args ?? {})).filter(([key]) => !Object.hasOwn(shown, key))) } : call.args;
1679
+ // The call on the record before its ask (beforeAsk), with the input its model gave it.
1680
+ await beforeAsk?.(call);
1468
1681
  const answer = await answerOf({ ...call, tool, args }, mcp?.priceOf(tool) ?? spec.approvalPrice?.(kernelCall) ?? null, asked);
1469
1682
  if (answer === "park")
1470
1683
  return { park: true };
@@ -1475,7 +1688,9 @@ function adapterLoop(specOf, options, deps) {
1475
1688
  const seen = askedArgs.get(call.callId);
1476
1689
  approvedCalls.set(call.callId, seen && typeof seen === "object" && !Array.isArray(seen) ? seen : {});
1477
1690
  }
1478
- return answer.approved ? "allow" : { deny: deniedText(asked, answer.note) };
1691
+ if (answer.approved)
1692
+ return "allow";
1693
+ return { deny: replayed ? refusedText(asked, answer.note?.trim() ? answer.note : undefined, "unknown") : deniedText(asked, answer.note) };
1479
1694
  };
1480
1695
  }
1481
1696
  /** An ask's answer: one in the journal stands; else the approve or deny the runner hands over on a resume; else ask and
@@ -1540,6 +1755,15 @@ function adapterLoop(specOf, options, deps) {
1540
1755
  await new Promise((resolve) => (wakeInbox = resolve));
1541
1756
  }
1542
1757
  }
1758
+ /** A call parked from inside its run (a rerun asked again): held unrun until its signal aborts (the pass ends on the
1759
+ * park), then thrown, so nothing of it is answered in this pass. */
1760
+ function heldUntilAborted(signal) {
1761
+ return new Promise((_, reject) => {
1762
+ if (signal.aborted)
1763
+ return reject(new Error("parked"));
1764
+ signal.addEventListener("abort", () => reject(new Error("parked")), { once: true });
1765
+ });
1766
+ }
1543
1767
  /** Whether a call of this run waits for the answer `approval` names: asked, and not answered yet. `later` when this
1544
1768
  * claim can no longer say: its Harness never opened, or its pass is parking, ending or stopping (the journal sealed,
1545
1769
  * closeSession closing the Harness behind the seal). The row is left untaken and the run's next claim checks it, as a
@@ -155,6 +155,7 @@ export declare function adapterRunGate(store: Pick<Store, "settings">, claim: Pi
155
155
  toolSettings?: unknown;
156
156
  harness?: string;
157
157
  approvals?: Approvals;
158
+ maxToolCalls?: number;
158
159
  };
159
160
  }, root: RunFiles, shell?: ShellPlace): Promise<NonNullable<AdapterRunSpec["gate"]> & {
160
161
  readonly permissions: RunPermissions;
@@ -175,6 +176,22 @@ export declare function hostToolCtxOf(run: AdapterRun, context: Context, results
175
176
  * a workflow it may run (`workflows`: the claim's seed lay chose them, runner/learning-seed.ts). A revision never names
176
177
  * the tool among its own: the run has it beside them, so the harness is told of it as of theirs. */
177
178
  export declare const learnsWorkflows: (kind: string, workflows: readonly LearnedWorkflow[]) => boolean;
179
+ /** A tier a learned workflow's node names, as the run has it: its model's id, or why it could not be reached. */
180
+ export type LearnedTier = {
181
+ readonly model: string;
182
+ } | {
183
+ readonly why: string;
184
+ };
185
+ /** The tiers other than the default that `workflows`' model nodes and `llm` calls name (model.ts nodeTiers, llmTiers),
186
+ * in TIERS order. A workflow that does not parse names none: its call refuses it. */
187
+ export declare function learnedTiers(workflows: readonly LearnedWorkflow[]): Tier[];
188
+ /** The route of each tier `workflows` name (learnedTiers) that `env` names a model of its own for (tierModelOf:
189
+ * AGENT_MODEL_FAST, AGENT_MODEL_STRONG), through `routeOf` (the run's one route, as its own model's): the model a node
190
+ * 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
191
+ * run's model); one whose route is refused is `why`, so its nodes fail in those words and never run on another model. */
192
+ export declare function learnedTierRoutes(workflows: readonly LearnedWorkflow[], env: NodeJS.ProcessEnv, routeOf: (tier: Tier) => Promise<ModelRoute>): Promise<Map<Tier, ModelRoute | {
193
+ why: string;
194
+ }>>;
178
195
  /** The run's learned_workflow tool as a HostTool, listed when the run has it (learnsWorkflows: an agentic revision whose
179
196
  * agent learned workflows, by learning.ts chooseWorkflows as main's start chooses them, so the tool set the model sees
180
197
  * 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
@@ -193,6 +210,10 @@ export declare function learnedWorkflowHostTool(opts: {
193
210
  /** The run's gate's permissions (adapterRunGate): each call node's tool is held to them, as main holds it. */
194
211
  readonly permissions: RunPermissions;
195
212
  readonly ctx: HostToolCtx;
213
+ /** The run's models of other tiers (pi's: learnedTierRoutes), by tier: a node of one runs on that model, through the
214
+ * session's port of the tier (AdapterSession.port's `tier`); one with `why` fails in those words. A tier not here runs
215
+ * on the session's model. */
216
+ readonly tiers?: ReadonlyMap<string, LearnedTier>;
196
217
  /** The claim's MCP (mcp-run.ts mcpForClaim), when its revision grants an MCP tool: its call nodes may name its tools by
197
218
  * catalog name, each run through the run's own MCP as the loop wraps it. */
198
219
  readonly mcp?: Pick<ClaimMcp, "tools" | "catalogOf">;