@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.47

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 (247) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/NOTICE +4 -0
  3. package/README.md +267 -40
  4. package/dist/acp-package.d.ts +35 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +5 -2
  7. package/dist/adapter-facts.js +6 -3
  8. package/dist/adapters.d.ts +7 -0
  9. package/dist/adapters.js +39 -0
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/api-only.d.ts +7 -10
  13. package/dist/api-only.js +7 -10
  14. package/dist/archil-routes.js +2 -1
  15. package/dist/cap.js +12 -2
  16. package/dist/chatgpt-plan.js +2 -1
  17. package/dist/cli.js +109 -41
  18. package/dist/composio-made.d.ts +19 -2
  19. package/dist/composio-made.js +17 -5
  20. package/dist/composio-preset.d.ts +42 -7
  21. package/dist/composio-preset.js +106 -70
  22. package/dist/composio-triggers.d.ts +9 -4
  23. package/dist/composio-triggers.js +20 -13
  24. package/dist/computer-attach.d.ts +11 -10
  25. package/dist/computer-attach.js +13 -14
  26. package/dist/computer-commands.d.ts +3 -0
  27. package/dist/computer-commands.js +3 -2
  28. package/dist/computer-lost.d.ts +4 -0
  29. package/dist/computer-lost.js +8 -3
  30. package/dist/computer-setting.d.ts +2 -0
  31. package/dist/computer-setting.js +2 -0
  32. package/dist/computers.d.ts +9 -75
  33. package/dist/computers.js +20 -66
  34. package/dist/console/assets/index-BBFzAxLB.js +715 -0
  35. package/dist/console/assets/index-BRi-Rgq6.css +1 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/cost-heal.d.ts +13 -0
  38. package/dist/cost-heal.js +27 -0
  39. package/dist/dial-relay.d.ts +6 -2
  40. package/dist/dial-relay.js +9 -12
  41. package/dist/email/routes.js +2 -1
  42. package/dist/errors.d.ts +2 -0
  43. package/dist/errors.js +5 -0
  44. package/dist/exa-keyless.d.ts +1 -1
  45. package/dist/exa-keyless.js +1 -1
  46. package/dist/faux-computers.d.ts +2 -3
  47. package/dist/faux-computers.js +9 -31
  48. package/dist/github-connection.js +2 -1
  49. package/dist/harness-archive.d.ts +19 -2
  50. package/dist/harness-archive.js +49 -15
  51. package/dist/harness-check.d.ts +73 -0
  52. package/dist/harness-check.js +489 -0
  53. package/dist/harness-cursor.d.ts +45 -0
  54. package/dist/harness-cursor.js +121 -0
  55. package/dist/harness-recipe.d.ts +127 -0
  56. package/dist/harness-recipe.js +357 -0
  57. package/dist/harness-table.d.ts +12 -0
  58. package/dist/harness-table.js +62 -2
  59. package/dist/harness.d.ts +2 -0
  60. package/dist/harness.js +3 -2
  61. package/dist/host-check.d.ts +6 -0
  62. package/dist/host-check.js +14 -0
  63. package/dist/host.d.ts +10 -3
  64. package/dist/host.js +17 -3
  65. package/dist/import-sources.d.ts +2 -0
  66. package/dist/import-sources.js +2 -0
  67. package/dist/import-summary.d.ts +15 -5
  68. package/dist/import-summary.js +24 -8
  69. package/dist/import.d.ts +24 -4
  70. package/dist/import.js +108 -26
  71. package/dist/key-refusal.d.ts +1 -0
  72. package/dist/key-refusal.js +8 -3
  73. package/dist/key-words.d.ts +1 -1
  74. package/dist/key-words.js +4 -4
  75. package/dist/learn/check.d.ts +3 -0
  76. package/dist/learn/check.js +31 -20
  77. package/dist/learn/compile.js +12 -5
  78. package/dist/learn/promote.d.ts +69 -2
  79. package/dist/learn/promote.js +95 -3
  80. package/dist/learned-nodes.d.ts +4 -3
  81. package/dist/learned-workflow.js +4 -1
  82. package/dist/learning-cost.d.ts +6 -16
  83. package/dist/learning-cost.js +6 -12
  84. package/dist/learning-words.d.ts +2 -0
  85. package/dist/learning-words.js +1 -1
  86. package/dist/listen-first.d.ts +10 -0
  87. package/dist/listen-first.js +25 -1
  88. package/dist/llms.txt +1 -1
  89. package/dist/mcp-gateway.d.ts +2 -1
  90. package/dist/mcp-gateway.js +31 -15
  91. package/dist/mcp-probe.d.ts +18 -6
  92. package/dist/mcp-probe.js +41 -8
  93. package/dist/mcp-secret-writes.d.ts +8 -0
  94. package/dist/mcp-secret-writes.js +104 -4
  95. package/dist/mcp-servers-store.d.ts +11 -5
  96. package/dist/mcp-servers-store.js +46 -20
  97. package/dist/model-form.d.ts +2 -1
  98. package/dist/model-form.js +22 -8
  99. package/dist/model-gateway.d.ts +113 -0
  100. package/dist/model-gateway.js +433 -0
  101. package/dist/model.d.ts +2 -1
  102. package/dist/model.js +9 -7
  103. package/dist/monid.js +1 -1
  104. package/dist/native/binding.d.ts +4 -0
  105. package/dist/native/binding.js +9 -0
  106. package/dist/native/cli.d.ts +3 -2
  107. package/dist/native/cli.js +6 -5
  108. package/dist/openapi.d.ts +2 -0
  109. package/dist/openapi.js +322 -39
  110. package/dist/owner.d.ts +4 -2
  111. package/dist/owner.js +10 -4
  112. package/dist/page.d.ts +8 -0
  113. package/dist/page.js +9 -1
  114. package/dist/port-models.js +17 -10
  115. package/dist/provider.d.ts +3 -3
  116. package/dist/provider.js +12 -3
  117. package/dist/public-address.d.ts +28 -0
  118. package/dist/public-address.js +62 -0
  119. package/dist/run-launch.d.ts +1 -1
  120. package/dist/run-launch.js +1 -1
  121. package/dist/run-secrets.d.ts +3 -2
  122. package/dist/run-secrets.js +6 -4
  123. package/dist/runner/adapter-loop.d.ts +10 -7
  124. package/dist/runner/adapter-loop.js +57 -22
  125. package/dist/runner/adapter-run-spec.d.ts +12 -0
  126. package/dist/runner/adapter-run-spec.js +40 -6
  127. package/dist/runner/adapters/index.js +16 -0
  128. package/dist/runner/adapters/pi.d.ts +5 -2
  129. package/dist/runner/adapters/pi.js +7 -4
  130. package/dist/runner/audit.d.ts +7 -0
  131. package/dist/runner/audit.js +15 -6
  132. package/dist/runner/claim-secrets.js +5 -1
  133. package/dist/runner/cli-run-spec.js +15 -7
  134. package/dist/runner/compare-end.d.ts +43 -0
  135. package/dist/runner/compare-end.js +95 -0
  136. package/dist/runner/computer-journal.d.ts +3 -0
  137. package/dist/runner/computer-journal.js +22 -2
  138. package/dist/runner/harness-loops.d.ts +6 -1
  139. package/dist/runner/harness-loops.js +94 -54
  140. package/dist/runner/held.d.ts +5 -4
  141. package/dist/runner/journal-kinds.d.ts +4 -1
  142. package/dist/runner/journal-kinds.js +3 -0
  143. package/dist/runner/loop-contract.d.ts +10 -0
  144. package/dist/runner/main.d.ts +5 -5
  145. package/dist/runner/main.js +62 -11
  146. package/dist/runner/mcp-claim.js +40 -12
  147. package/dist/runner/metrics.d.ts +26 -0
  148. package/dist/runner/metrics.js +44 -1
  149. package/dist/runner/presence.d.ts +41 -0
  150. package/dist/runner/presence.js +89 -0
  151. package/dist/runner/promotion.d.ts +9 -4
  152. package/dist/runner/promotion.js +33 -14
  153. package/dist/runner/run-child-host.js +40 -10
  154. package/dist/runner/runner.d.ts +5 -0
  155. package/dist/runner/runner.js +8 -0
  156. package/dist/runner/store-port.d.ts +3 -0
  157. package/dist/runner/store-secrets.js +19 -7
  158. package/dist/runner/workflow-first.d.ts +5 -2
  159. package/dist/runner/workflow-first.js +6 -3
  160. package/dist/runs-over-store.d.ts +6 -2
  161. package/dist/runs-over-store.js +14 -4
  162. package/dist/sdk/runs.d.ts +1 -1
  163. package/dist/sdk/runs.js +6 -1
  164. package/dist/sdk/schema.js +1 -1
  165. package/dist/secret-writes.d.ts +16 -3
  166. package/dist/secret-writes.js +28 -3
  167. package/dist/server-secrets-store.js +5 -0
  168. package/dist/server.d.ts +31 -2
  169. package/dist/server.js +322 -51
  170. package/dist/sign-ins-secrets.js +4 -1
  171. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  172. package/dist/slack-url.d.ts +5 -0
  173. package/dist/slack-url.js +11 -0
  174. package/dist/slack.d.ts +107 -0
  175. package/dist/slack.js +292 -0
  176. package/dist/start-switches.d.ts +28 -0
  177. package/dist/start-switches.js +37 -0
  178. package/dist/stats.d.ts +1 -1
  179. package/dist/stats.js +2 -1
  180. package/dist/stop-signals.d.ts +11 -0
  181. package/dist/stop-signals.js +22 -0
  182. package/dist/store/agent-body.d.ts +1 -1
  183. package/dist/store/agent-body.js +2 -2
  184. package/dist/store/index.d.ts +3 -3
  185. package/dist/store/index.js +1 -1
  186. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  187. package/dist/store/postgres/store.d.ts +1 -1
  188. package/dist/store/postgres/store.js +4 -2
  189. package/dist/store/schema.d.ts +13 -5
  190. package/dist/store/schema.js +20 -11
  191. package/dist/store/seal.d.ts +16 -4
  192. package/dist/store/sqlite/store.d.ts +1 -1
  193. package/dist/store/sqlite/store.js +106 -27
  194. package/dist/store/store.d.ts +75 -23
  195. package/dist/store/store.js +11 -0
  196. package/dist/store-reads/analytics.js +3 -2
  197. package/dist/store-reads/cap.d.ts +7 -0
  198. package/dist/store-reads/cap.js +11 -1
  199. package/dist/store-reads/journal.js +27 -1
  200. package/dist/store-reads/learning.d.ts +23 -2
  201. package/dist/store-reads/learning.js +29 -8
  202. package/dist/store-reads/runs.d.ts +9 -0
  203. package/dist/store-reads/runs.js +19 -6
  204. package/dist/store-reads/stats.d.ts +4 -1
  205. package/dist/store-reads/stats.js +15 -6
  206. package/dist/store-view.d.ts +123 -14
  207. package/dist/store-view.js +154 -21
  208. package/dist/telemetry.d.ts +7 -7
  209. package/dist/telemetry.js +38 -15
  210. package/dist/timeline/timeline.js +18 -0
  211. package/dist/tool-keys-store.js +2 -2
  212. package/dist/tool-keys.js +2 -1
  213. package/dist/tool-plane.js +2 -2
  214. package/dist/trigger-adapter.d.ts +3 -4
  215. package/dist/trigger-adapter.js +2 -2
  216. package/dist/trigger-composio.js +3 -3
  217. package/dist/trigger-email.js +0 -2
  218. package/dist/trigger-feed.js +0 -2
  219. package/dist/trigger-schedule.js +3 -0
  220. package/dist/trigger-secrets-shown.d.ts +6 -3
  221. package/dist/trigger-secrets-shown.js +22 -13
  222. package/dist/trigger-targets.d.ts +1 -1
  223. package/dist/trigger-targets.js +19 -8
  224. package/dist/triggers.d.ts +2 -2
  225. package/dist/webhooks.d.ts +82 -8
  226. package/dist/webhooks.js +128 -45
  227. package/dist/wires.d.ts +6 -1
  228. package/dist/wires.js +5 -0
  229. package/dist/workspace/attach.d.ts +3 -2
  230. package/dist/workspace/attach.js +2 -1
  231. package/dist/workspace/attached-computers.d.ts +6 -8
  232. package/dist/workspace/attached-computers.js +27 -24
  233. package/dist/workspace/computer-deps.d.ts +2 -3
  234. package/dist/workspace/computer-deps.js +3 -6
  235. package/dist/workspace/computer-for-claim.js +72 -96
  236. package/dist/workspace/computer-kept.d.ts +0 -7
  237. package/dist/workspace/computer-kept.js +0 -17
  238. package/dist/workspace/resolve-computer.d.ts +18 -14
  239. package/dist/workspace/resolve-computer.js +47 -60
  240. package/dist/workspace/synced-folder.d.ts +20 -15
  241. package/dist/workspace/synced-folder.js +33 -43
  242. package/launcher/agentrun-serve +4 -1
  243. package/package.json +10 -10
  244. package/skills/agentrun-serve/SKILL.md +11 -0
  245. package/templates/README.md +1 -1
  246. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  247. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -50,6 +50,8 @@ import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
50
50
  import { UNREADABLE_SIGN_IN } from "../run-view.js";
51
51
  import { durableWait } from "../workflow/pi-versions.js";
52
52
  import { claimModelEnv, claimModelKey, claimSecrets, claimSpendOff, holdRunKey, keyedAtClaim, hostDecisionKeys, learnedDecisionKeys, savedModelKeys, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
53
+ import { compareEndOfRun, GRADER, withGrader } from "./compare-end.js";
54
+ import { agreeOnOf } from "../learning-setting.js";
53
55
  import { catalogSessionNames, mcpWhereHeld } from "./mcp-run.js";
54
56
  import { held as runnerSeam, heldOrThrow, heldSignInReads } from "./held.js";
55
57
  import { hostLifecycle } from "./adapter-loop.js";
@@ -58,7 +60,7 @@ import { DEFAULT_HARNESS } from "../harness.js";
58
60
  import { agentEntriesOf } from "./loop.js";
59
61
  import { SUBAGENT_TIERS, SUBAGENT_TOOL, subagentTool } from "./subagent.js";
60
62
  import { ClaimRefused } from "./loop-contract.js";
61
- import { bookedSpend, cliRunMetrics, endCostOf, runCostOf, runMetrics } from "./metrics.js";
63
+ import { bookedSpend, cliRunMetrics, costBasisOf, endCostOf, runCostOf, runMetrics } from "./metrics.js";
62
64
  import { journalEntries } from "./journal-reader.js";
63
65
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
64
66
  import { replayCallsOver } from "./promotion.js";
@@ -123,6 +125,29 @@ export function modelRetryOf(routes) {
123
125
  const SUBAGENT_ROUTE = "subagent-";
124
126
  const subagentRoute = (tier) => `${SUBAGENT_ROUTE}${tier}`;
125
127
  const isSubagentRoute = (key) => key.startsWith(SUBAGENT_ROUTE);
128
+ /** A replay run's or an audit shadow's grader route (runner/compare-end.ts): its fast model (the revision's
129
+ * modelTiers.fast, else AGENT_MODEL_FAST) when its revision names no agree_on, on pi's wires. A fast model may be another
130
+ * provider's than the run's own, whose key claimSecrets never opened: so its route reads every model key the server
131
+ * holds (savedModelKeys) as a subagent's tier does, held by the run's redactor, on the route's env alone. A run with its
132
+ * own model key carries that key, and no saved key is read. Undefined when there is no fast model, the revision names
133
+ * agree_on, or no route can be made (logged: the pair is then compared whole). */
134
+ export async function graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, holds = [cut]) {
135
+ if (agreeOnOf(body.learning)?.length)
136
+ return undefined;
137
+ const savedKeys = keyed ? {} : await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
138
+ for (const redact of new Set(holds))
139
+ holdClaimed(redact, savedKeys);
140
+ const env = claimModelEnv(deps.env, { ...savedKeys, ...claimed }, runKey);
141
+ if (body.modelTiers?.fast === undefined && tierModelOf(env, "fast") === undefined)
142
+ return undefined;
143
+ try {
144
+ return await deps.routeOf(body.modelTiers?.fast, env, "fast", PI_WIRES, undefined, cut);
145
+ }
146
+ catch (error) {
147
+ log(`learning: no grader route (${error instanceof Error ? error.message : String(error)}): the answers are compared whole`);
148
+ return undefined;
149
+ }
150
+ }
126
151
  /** What the runner routes a claimed run on: the launch's model as its start pinned it, sent as pinned, with the
127
152
  * revision's own ref beside it (main prices a gateway's id by the provider that ref names); the revision's ref alone
128
153
  * when the start pinned none. Never the pin's provider and id joined into a ref: a gateway refuses the joined id, and
@@ -536,6 +561,11 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
536
561
  holdClaimed(cut, learnedKeys);
537
562
  Object.assign(toolEnv, learnedKeys);
538
563
  }
564
+ // A replay run's or a shadow's grader (runner/compare-end.ts), on a route of its own beside the session's, on the
565
+ // session's booking under the run's one cap. None: the pair is compared whole, in words saying so.
566
+ const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, toolEnv, cut, log, deps) : undefined;
567
+ if (graderRoute)
568
+ tierRoutes.set(GRADER, graderRoute);
539
569
  // The tool host's install lifecycle: what a binding registers to run in each conversation's creating commit, once the
540
570
  // Harness is open before the session, and at the run's end (the browser tool's reconcile and release hang off these). The
541
571
  // adapter loop runs them from the spec's `lifecycle` (adapter-loop.ts hostLifecycle).
@@ -554,7 +584,7 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
554
584
  const handTools = tools.hostTools(withKindTools(granted, tools), results);
555
585
  // 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
556
586
  // words, pass the run's one redactor before the harness, the model or the record has them.
557
- const tiers = new Map([...[...tierRoutes].filter(([tier]) => !isSubagentRoute(tier)).map(([tier, { model }]) => [tier, { model }]), ...[...tierUnreachable].map(([tier, why]) => [tier, { why }])]);
587
+ const tiers = new Map([...[...tierRoutes].filter(([tier]) => !isSubagentRoute(tier) && tier !== GRADER).map(([tier, { model }]) => [tier, { model }]), ...[...tierUnreachable].map(([tier, why]) => [tier, { why }])]);
558
588
  // The gate asks a learned_workflow call about its workflow's MCP nodes (adapterRunGate).
559
589
  gate.learn(workflows);
560
590
  // The run's monid endpoints (monid-run.ts), one host tool each from its revision's pin, on the claim's keys and beside
@@ -624,10 +654,11 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
624
654
  // (adapter-loop.ts stepOf). Its learning folder is where the run's place keeps it — Mode 1 the agent's folder under the
625
655
  // data directory, Mode 2 the agent's folder on THIS claim's Archil disk (the draft is checked against the seed on the disk, never this machine's
626
656
  // local path) — so the end-of-run step reads the run's own Workspace, the one the run worked in.
627
- // A replay run or an audit's shadow run asks nothing at its end: it is the promotion's, never the agent's to learn from.
657
+ // A replay run or an audit's shadow run learns nothing at its end: it is the promotion's, never the agent's to learn
658
+ // from. With a grader it compares its answer with the other one (runner/compare-end.ts), on its own cap.
628
659
  // A run the promoted workflow answered (path `workflow`) starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
629
660
  // withAudit): at its end, so the shadow's cap is what the run's own left.
630
- const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
661
+ const endOfRun = launch.replay || launch.audit ? withGrader(compareEndOfRun(launch, { store: deps.store, folder: learningFolder, log, ...(run.redact ? { redact: run.redact } : {}) }), graderRoute ? { model: graderRoute.model, models: () => run.ledger.models(GRADER, GRADER) } : undefined) : withAudit(learningEndOfRun(launch, {
631
662
  store: deps.store,
632
663
  data: deps.data,
633
664
  ...(deps.env ? { env: deps.env } : {}),
@@ -704,12 +735,15 @@ async function adapterSpec(launch, run, deps, claim, holds, runner) {
704
735
  // metrics are its booking's, as a CLI harness's run reads them: the workflow's nodes and the agent's own after a handback.
705
736
  // An MCP tool called by a hashed wire name is counted under its catalog name, as its timeline names it.
706
737
  const catalog = await hashedMcpOf(deps.store, claim.runId);
738
+ // Its model requests as every session of its journal booked them: how they were priced (costBasis, which the sums
739
+ // over runs read), and, for a run its learned workflow served, its tokens.
740
+ const booked = bookedSpend((await journalEntries(deps.journal(claim), context)), "model");
707
741
  const { metrics } = servedOf(entries)
708
- ? { metrics: cliRunMetrics(piShaped(entries), bookedSpend((await journalEntries(deps.journal(claim), context)), "model"), { ...(launch.effort !== undefined ? { effort: launch.effort } : {}), model: launch.model ? `${launch.model.provider}/${launch.model.modelId}` : route.model, catalog }) }
742
+ ? { metrics: cliRunMetrics(piShaped(entries), booked, { ...(launch.effort !== undefined ? { effort: launch.effort } : {}), model: launch.model ? `${launch.model.provider}/${launch.model.modelId}` : route.model, catalog }) }
709
743
  : runMetrics(entries, { ...(launch.effort !== undefined ? { effort: launch.effort } : {}), catalog });
710
744
  // Its cost is endCost's, read apart (an unknown one written as null, never left out: a follow-up's end clears the
711
745
  // cost an earlier end stored).
712
- return { metrics: { ...metrics, ...path } };
746
+ return { metrics: { ...metrics, ...path, costBasis: costBasisOf(booked) } };
713
747
  },
714
748
  // A run started with hold: true holds its computer for its owner (computer-held.ts): the loop waits for their start
715
749
  // and release, and runs their calls on it.
@@ -4,6 +4,7 @@ import { facts as openCodeFacts } from "../../harness-opencode/facts.js";
4
4
  import { harnessOf } from "../../harness-table.js";
5
5
  import { acpPackage } from "../../acp-package.js";
6
6
  import { GOOSE_ID } from "../../harness-goose.js";
7
+ import { CURSOR_ID } from "../../harness-cursor.js";
7
8
  import { piAdapter } from "./pi.js";
8
9
  const CLAUDE_PACKAGE = "@parcha/agentrun-harness-claude";
9
10
  const CODEX_PACKAGE = "@parcha/agentrun-harness-codex";
@@ -95,6 +96,21 @@ export const RUNNER_HARNESSES = {
95
96
  });
96
97
  },
97
98
  },
99
+ // Cursor, where the same package is beside serve: on the launcher `extra.binary` names, which its owner installed
100
+ // (harness-cursor.ts), and its owner's key read by name from `extra.env`; billed to the owner's Cursor plan, so the
101
+ // launch's provider and price are never its. A run on serve's table builds its adapter from its entry (adapters.ts
102
+ // cursorOf).
103
+ [CURSOR_ID]: {
104
+ record: "loop",
105
+ adapter: async (launch, extra = {}) => {
106
+ const acp = acpPackage();
107
+ if (!acp)
108
+ throw new Error("Cursor's adapter (@parcha/agentrun-harness-acp) is not installed beside this runner");
109
+ if (typeof extra.binary !== "string")
110
+ throw new Error("Cursor's runner adapter needs the installed launcher's path (extra.binary)");
111
+ return acp.cursorAdapter({ sessionsDir: launch.sessionsDir, ...extra });
112
+ },
113
+ },
98
114
  };
99
115
  /** The harness the launch names, as `env`'s harness table has it (harness-table.ts harnessOf): a built-in one's runner is
100
116
  * the runner's own (RUNNER_HARNESSES), one a harness module adds brings its own (HarnessEntry.runner). Undefined when
@@ -36,8 +36,11 @@ export type PreIntentAnswer = "allow" | {
36
36
  export type PiSessionIO = SessionIO & {
37
37
  gate?: (call: PreIntentCall, context: Context) => Promise<PreIntentAnswer>;
38
38
  /** What the request that just answered cost, as the runner's booking wrote it (the session's ledger): its figure, null
39
- * when unknown, undefined when none was booked. pi's own price for the model is none (the adapter does not know it). */
40
- bookedCost?: () => Promise<number | null | undefined>;
39
+ * when unknown, undefined when none was booked. pi's own price for the model is none (the adapter does not know it).
40
+ * `conversation`: the answer's conversation, as each of its requests named it to the session's proxy (pi's own id for
41
+ * it: port-models.ts sessionApi), so an answer reads its own conversation's bookings, never those of a conversation
42
+ * asking beside it (a subagent's child). */
43
+ bookedCost?: (conversation?: string) => Promise<number | null | undefined>;
41
44
  /** Keeps a tool call's computer calls beside it on the run's root, by the call's id (the loop's, as its host tools'
42
45
  * are kept): each run's pi-native tool (code mode's script among them) runs inside recordingCalls with it, so its row
43
46
  * carries the calls it made as a host tool's does. */
@@ -1,9 +1,9 @@
1
1
  import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
2
2
  import { clampThinkingLevel, createModels, getSupportedThinkingLevels } from "@earendil-works/pi-ai/models";
3
- import { defineExtension, defineTool, GenerationTask, hook, ToolTask } from "@earendil-works/pi-durable";
3
+ import { defineExtension, defineTool, GenerationTask, hook, ProviderDoc, ToolTask } from "@earendil-works/pi-durable";
4
4
  import { anthropicPolicy, withWebSearches } from "@parcha/agentrun-harness-claude";
5
5
  import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
6
- import { NATIVE_SEARCH_USD, startModelProxy } from "@parcha/agentrun-kernel/host";
6
+ import { conversationLabel, NATIVE_SEARCH_USD, startModelProxy } from "@parcha/agentrun-kernel/host";
7
7
  import { INTERRUPTED_TEXT } from "@parcha/agentrun-kernel/kernel";
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { DEFAULT_HARNESS } from "../../harness.js";
@@ -309,10 +309,13 @@ async function sessionOn(proxy, options, spec, io, context, tiers) {
309
309
  // An answer's cost is the runner's booking of its request, never pi's $0 for a model it has no price for: set on
310
310
  // the answer before pi stores it, so the answer, pi.usage and the live timeline carry it; unknown stays unknown.
311
311
  hook(GenerationTask, {
312
- afterResponse: async (message) => {
312
+ afterResponse: async (message, api, hookContext) => {
313
313
  if (!io.bookedCost)
314
314
  return;
315
- const usd = await io.bookedCost();
315
+ // The conversation that asked, by the id pi sends with each of its requests (its pi.provider document's), as
316
+ // the session's client names it to the proxy (port-models.ts sessionApi).
317
+ const asked = await api.snapshot(ProviderDoc, api.conversationId, hookContext);
318
+ const usd = await io.bookedCost(conversationLabel(asked?.sessionId));
316
319
  if (usd === undefined)
317
320
  return;
318
321
  const cost = message.usage?.cost;
@@ -28,6 +28,13 @@ export type AuditDeps = {
28
28
  export declare const STOPPED_TWICE = "stopped: the workflow disagreed with the agent twice";
29
29
  /** The audit numbers of revision `revisionId`'s definition (each one it leaves out at its default). */
30
30
  export declare function auditLoopOfRevision(store: Pick<Store, "agents">, revisionId: string): Promise<AuditLoop>;
31
+ /** The answer paths an audit of a run of revision `revisionId` compares on, as its check does (learning-setting.ts
32
+ * agreeOnOf: its agree_on); undefined, the whole answer. A read that fails throws: settleAudits leaves the row to a
33
+ * later claim, never comparing on the whole answer an agent that named its fields (#3182 review). */
34
+ export declare function agreeOnOfRevision(store: Pick<Store, "agents">, revisionId: string): Promise<readonly string[] | undefined>;
35
+ /** The served answer shadow run `shadowRun` audits: its open line's `turn`'s answer, read from the served run by that row's
36
+ * id (what settleAudits compares the shadow's answer with); null when no open line names it, or it names no turn. */
37
+ export declare function auditedAnswerOf(deps: Pick<AuditDeps, "store" | "context" | "folder">, shadowRun: string): Promise<string | null>;
31
38
  /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
32
39
  * started them): what the promotions read counts beside the audit line. */
33
40
  export declare function notAuditableOf(store: Pick<Store, "runs">, agentId: string, workflow: string, digest: string, loop: Pick<AuditLoop, "stop_window">): Promise<number>;
@@ -12,8 +12,9 @@
12
12
  // shadow) of an agent every tool of which only reads (learn/audit.ts auditWriterOf, the replay's readOnlyHint rule): a
13
13
  // shadow never writes again.
14
14
  // settleAudits: each open started line (no result row yet) whose two runs, read by id, ended writes its row (agreed:
15
- // the audited answer, its `turn`'s, and the shadow's say the same, learn/promote.ts sameAnswer, on the served run's
16
- // revision's agree_on as the check compares, learning-setting.ts agreeOnOf; a follow-up's answer since is never
15
+ // the audited answer, its `turn`'s, and the shadow's say the same, learn/promote.ts compareAnswers, the check's one
16
+ // comparison: on the served run's revision's agree_on, learning-setting.ts agreeOnOf, else the grader's verdict the
17
+ // shadow kept at its end, runner/compare-end.ts; a follow-up's answer since is never
17
18
  // read), oldest served run first; then, rows added or not, the hold rule reads the serving revisions'
18
19
  // rows: a hold is a function of the ledger alone.
19
20
  // applyHold: at least hold_disagree disagreements in the newest hold_window rows of the digest's current promotion
@@ -35,7 +36,7 @@ import { isObject } from "../validate.js";
35
36
  import { auditableLaunch, auditChange, auditEveryOf, auditDrawn, auditsOffWords, auditWriterOf, holdOf, ledgerOf, lineKey, openAudits, rowsOf, shadowRunId } from "../learn/audit.js";
36
37
  import { lastRunsOf } from "../learn/compile.js";
37
38
  import { readLearning, writeLearning } from "../learn/folder.js";
38
- import { CHECK_TEXT_MAX, promotionOf, promotionsOf, promotionStartOf, recordPromotion, sameAnswer, servingOf } from "../learn/promote.js";
39
+ import { CHECK_TEXT_MAX, compareAnswers, comparedOf, promotionOf, promotionsOf, promotionStartOf, recordPromotion, servingOf } from "../learn/promote.js";
39
40
  import { excerptShown } from "../learn/secrets.js";
40
41
  import { auditRoomOf } from "./learning-end.js";
41
42
  import { answerOf, answerRowOf } from "./promotion.js";
@@ -69,9 +70,15 @@ export async function auditLoopOfRevision(store, revisionId) {
69
70
  /** The answer paths an audit of a run of revision `revisionId` compares on, as its check does (learning-setting.ts
70
71
  * agreeOnOf: its agree_on); undefined, the whole answer. A read that fails throws: settleAudits leaves the row to a
71
72
  * later claim, never comparing on the whole answer an agent that named its fields (#3182 review). */
72
- async function agreeOnOfRevision(store, revisionId) {
73
+ export async function agreeOnOfRevision(store, revisionId) {
73
74
  return agreeOnOf((await store.agents.revision(revisionId))?.body?.learning);
74
75
  }
76
+ /** The served answer shadow run `shadowRun` audits: its open line's `turn`'s answer, read from the served run by that row's
77
+ * id (what settleAudits compares the shadow's answer with); null when no open line names it, or it names no turn. */
78
+ export async function auditedAnswerOf(deps, shadowRun) {
79
+ const open = openAudits(await readLedger(deps)).find((line) => line.shadow_run === shadowRun);
80
+ return open ? auditedAnswer(deps, open) : null;
81
+ }
75
82
  /** The served runs of `workflow` (at `digest` when given) that `keep` keeps too, the newest `n` of them (lastRunsOf: the
76
83
  * shadows and the agent's own runs among them never push one out of the read). */
77
84
  const servedRuns = (store, agentId, n, workflow, digest, keep = () => true) => lastRunsOf(store, agentId, n, (row) => served(row) && metricsOf(row).workflow === workflow && (digest === undefined || metricsOf(row).workflow_digest === digest) && keep(row));
@@ -245,8 +252,10 @@ export async function settleAudits(deps) {
245
252
  return null;
246
253
  // The audited answer (the row's turn), never the run's newest: a follow-up since may have answered again.
247
254
  const [a, b] = [await auditedAnswer(deps, row), await answerOf(store, row.shadow_run, deps.context)];
248
- // Compared on the fields the served run's revision says carry the decision, as its check compared.
249
- return a === null || b === null ? null : sameAnswer(a, b, await agreeOnOfRevision(store, served.revisionId));
255
+ // The check's one comparison (compareAnswers): on the fields the served run's revision says carry the decision, else
256
+ // equal, else the grader's verdict its shadow kept at its end (runner/compare-end.ts), else the whole answer.
257
+ const verdict = comparedOf(isObject(shadow.metrics) ? shadow.metrics.audit?.compared : undefined);
258
+ return a === null || b === null ? null : compareAnswers(a, b, await agreeOnOfRevision(store, served.revisionId), verdict).same;
250
259
  }) : { all: lines, added: [] };
251
260
  const written = rowsOf(added);
252
261
  if (written.length)
@@ -14,6 +14,7 @@ import { getSealedKey } from "../server-keys.js";
14
14
  import { PLAN_PROVIDER, planOf, planReaderOf, withPlan } from "../chatgpt-plan.js";
15
15
  import { handsParallel } from "../tool-plane.js";
16
16
  import { held, held as runnerSeam } from "./held.js";
17
+ import { savedGatewayIn } from "../model-gateway.js";
17
18
  import { noServerKeyWords, runKeyEndedFor, runModelOrigin, withRunModelKey, withRunModelKeyLater } from "../run-model-key.js";
18
19
  import { openRunLaunch } from "../store/seal.js";
19
20
  import { StoreLaunchMissing } from "../store/store.js";
@@ -32,8 +33,11 @@ export async function claimSecrets(deps, revision, launch) {
32
33
  // in its place, and the run would hold a key its model never sends and lack the one it does.
33
34
  const scoped = launch.model && !needs.tiers ? { ...needs, model: `${launch.model.provider}/${launch.model.modelId}` } : needs;
34
35
  const env = { ...base };
36
+ // The key of a gateway saved in the console (model-gateway.ts) stays on the run environment its model routes read, never
37
+ // on the tools': it is read there by name alone (claimModelEnv), as a run's own model key is.
38
+ const savedGateway = savedGatewayIn(deps.env ?? {});
35
39
  for (const name of keysFor(scoped, working))
36
- if (working[name] !== undefined)
40
+ if (working[name] !== undefined && !(savedGateway && name === GATEWAY_KEY_ENV))
37
41
  env[name] = working[name];
38
42
  const decision = decisionKeysFor(working, { providers: needs.decisionProviders, parallelWeb: launch.plane ? handsParallel(launch.plane) : false });
39
43
  for (const [name, value] of Object.entries(decision))
@@ -48,7 +48,7 @@ import { settingOfDefinition } from "../computer-setting.js";
48
48
  import { computerKeptWords, computerReadyWords, computerReplacedNote, computerStartingWords, imageWaitWords } from "../workspace/computer-deps.js";
49
49
  import { hadComputer } from "./computer-journal.js";
50
50
  import { hostLifecycle } from "./adapter-loop.js";
51
- import { adapterRunGate, answersCut, buildToolHost, capModelOf as capModelOfRoute, claimLiveAt, hostToolCtxOf, learnedTierRoutes, learnedTiers, learnedWorkflowHostTool, learnsWorkflows, mcpReachOf, modelAskOf, PI_WIRES, webHostTools } from "./adapter-run-spec.js";
51
+ import { adapterRunGate, answersCut, buildToolHost, capModelOf as capModelOfRoute, claimLiveAt, graderRouteOf, hostToolCtxOf, learnedTierRoutes, learnedTiers, learnedWorkflowHostTool, learnsWorkflows, mcpReachOf, modelAskOf, PI_WIRES, webHostTools } from "./adapter-run-spec.js";
52
52
  import { openTierProxies } from "./adapters/pi.js";
53
53
  import { signInReads } from "../sign-ins-store.js";
54
54
  import { isWebHostTool } from "../tool-list.js";
@@ -62,13 +62,14 @@ import { DECISION_PROVIDER_KEYS, TOOL_PLANE_ENV } from "../tool-plane.js";
62
62
  import { decisionProvidersIn } from "../decisions.js";
63
63
  import { resolveHarness } from "./adapters/index.js";
64
64
  import { entriesOf } from "./loop.js";
65
- import { bookedSpend, cliModelWorked, cliRunMetrics, endCostOf, runCostOf } from "./metrics.js";
65
+ import { bookedSpend, cliModelWorked, cliRunMetrics, costBasisOf, endCostOf, runCostOf } from "./metrics.js";
66
66
  import { journalEntries } from "./journal-reader.js";
67
67
  import { hashedMcpOf, piShaped } from "../store-reads/journal.js";
68
68
  import { replayCallsOver } from "./promotion.js";
69
69
  import { learnedFirstWhereHeld } from "./learned-first.js";
70
70
  import { pathMetrics } from "./workflow-first.js";
71
71
  import { AUDIT_PARKED, withAudit } from "./audit.js";
72
+ import { compareEndOfRun, GRADER, withGrader } from "./compare-end.js";
72
73
  import { runPathOverStore } from "../store-reads/learning.js";
73
74
  import { specBuilt } from "./spec-holds.js";
74
75
  import { heldRedactor, holdClaimed, runnerSecrets, secretRedactor } from "./redact.js";
@@ -120,11 +121,12 @@ export function capModelOf(id, wire, listed, unpriced, plan = false) {
120
121
  return { id, api: wire, price, outputCeiling: typeof listed?.maxTokens === "number" ? listed.maxTokens : null };
121
122
  }
122
123
  /** The model a CLI run of `entry` on `chosen` (modelsOf) is capped at, on its `wire`: the catalog entry that bills it
123
- * (its entry's priceModel), priced by capModelOf. */
124
+ * (its entry's priceModel), priced by capModelOf. A harness its vendor bills to its owner's plan (its promises' billing,
125
+ * Cursor's) is the plan rule's, as a ChatGPT plan's model is. */
124
126
  function chosenCapModel(entry, env, chosen, wire) {
125
127
  const priced = entry.priceModel(env, chosen.model);
126
128
  const listed = chosen.models.getModel(priced.provider, priced.modelId);
127
- return capModelOf(priced.modelId, wire, listed, chosen.unpriced.has(priced.modelId) || listed === undefined, priced.provider === PLAN_PROVIDER || priced.provider === CLAUDE_LOGIN_PROVIDER);
129
+ return capModelOf(priced.modelId, wire, listed, chosen.unpriced.has(priced.modelId) || listed === undefined, priced.provider === PLAN_PROVIDER || priced.provider === CLAUDE_LOGIN_PROVIDER || entry.promises?.billing === "plan");
128
130
  }
129
131
  /** The model a run of the CLI harness `entry` on `ref` (a revision's model; none, this host's default for it) is capped
130
132
  * at here, as its run's spec prices it (modelsOf, chosenCapModel), before any run: a save's cap warning (cap-short.ts)
@@ -581,6 +583,11 @@ async function cliSpec(launch, run, deps, claim, holds) {
581
583
  // are skipped, in words, where the run brought its own key or the server holds none.
582
584
  const spendOff = await claimSpendOff({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, runKey);
583
585
  const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff };
586
+ // A replay run's or a shadow's grader (runner/compare-end.ts), on a proxy of its own beside the CLI session's, as pi's
587
+ // is (adapter-run-spec.ts graderRouteOf), reached through the session's port while it is up. None: compared whole.
588
+ const graderRoute = launch.replay || launch.audit ? await graderRouteOf(body, keyed, runKey, claimed, cut, log, deps, [held, cut]) : undefined;
589
+ if (graderRoute)
590
+ tierRoutes.set(GRADER, graderRoute);
584
591
  // Each step writes the store or reads another run (runner/learned-first.ts): in a run's own process its runner takes
585
592
  // them (held.ts learnedFirst), over the workflows it reads at the claim's seed itself.
586
593
  const learned = await learnedFirstWhereHeld(deps, { agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, kind: revision.kind, outputSchema: revision.body.outputSchema, launch, context, log, folder: learningFolder, shown, spendOff }, seedLaid?.workflows ?? []);
@@ -660,10 +667,11 @@ async function cliSpec(launch, run, deps, claim, holds) {
660
667
  // The run's end-of-run step, when it learns, the same as the pi spec's: the compile turn and the owner's correction over
661
668
  // the run's store, its learning folder where the run's place keeps it — Mode 1 under the data directory, Mode 2 on this
662
669
  // claim's Archil disk — so the draft is checked against the seed in the run's own Workspace, never this machine's local path.
663
- // A replay run or an audit's shadow run asks nothing at its end: it is the promotion's, never the agent's to learn from.
670
+ // A replay run or an audit's shadow run learns nothing at its end: it is the promotion's, never the agent's to learn
671
+ // from. With a grader it compares its answer with the other one (runner/compare-end.ts), on its own cap.
664
672
  // A run the promoted workflow answered (path `workflow`) starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
665
673
  // withAudit): at its end, so the shadow's cap is what the run's own left.
666
- const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
674
+ const endOfRun = launch.replay || launch.audit ? withGrader(compareEndOfRun(launch, { store: deps.store, folder: learningFolder, log, ...(run.redact ? { redact: run.redact } : {}) }), graderRoute ? { model: graderRoute.model, models: () => run.ledger.models(GRADER, GRADER) } : undefined) : withAudit(learningEndOfRun(launch, {
667
675
  store: deps.store,
668
676
  data: deps.data,
669
677
  ...(deps.env ? { env: deps.env } : {}),
@@ -740,7 +748,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
740
748
  const metrics = cliRunMetrics(piShaped(entries), booked, { ...(thinking ? { effort: thinking } : {}), model: `${chosen.model.provider}/${chosen.model.modelId}`, catalog: await hashedMcpOf(deps.store, claim.runId) });
741
749
  // Its cost is endCost's, read apart (an unknown one written as null, never left out: a follow-up's end clears the
742
750
  // cost an earlier end stored).
743
- return { metrics: { ...metrics, ...pathMetrics(launch, launch.learning ? await runPathOverStore(deps.store, claim.runId, launch.learning, run.redact) : undefined, entries) } };
751
+ return { metrics: { ...metrics, ...pathMetrics(launch, launch.learning ? await runPathOverStore(deps.store, claim.runId, launch.learning, run.redact) : undefined, entries), costBasis: costBasisOf(booked) } };
744
752
  },
745
753
  // A run started with hold: true holds its computer for its owner (computer-held.ts), as the pi spec's.
746
754
  ...(heldComputer ? { held: heldComputer } : {}),
@@ -0,0 +1,43 @@
1
+ import type { LearningFolder } from "../learn/folder.js";
2
+ import { type GraderReply } from "../learn/promote.js";
3
+ import type { PortModels } from "../port-models.js";
4
+ import type { RunLaunch } from "../run-launch.js";
5
+ import type { Store } from "../store/store.js";
6
+ import type { EndOfRunTurn } from "./loop-contract.js";
7
+ /** The grader's route among a run's tier routes (never a learned workflow's tier, nor a subagent's), which is also the
8
+ * label its requests carry on the run's record. */
9
+ export declare const GRADER = "grader";
10
+ export type CompareEndDeps = {
11
+ readonly store: Store;
12
+ readonly folder: () => LearningFolder;
13
+ readonly log: (line: string) => void;
14
+ readonly redact?: (text: string) => string;
15
+ };
16
+ /** The end-of-run step of a replay run or an audit's shadow (its callers pass no other run): its comparison (above),
17
+ * asked only when the run completed, was not cut, has a grader (its route exists only for a revision that names no
18
+ * agree_on, graderRouteOf), and the two answers are not already the same. In a run's own process the step is its runner's (held.ts endOfRun): it reads other runs and the
19
+ * learning ledger, which no run's process may. A comparison that fails keeps no verdict: the pair then differs, compared
20
+ * whole (compareAnswers), in the log's words. */
21
+ export declare function compareEndOfRun(launch: RunLaunch, deps: CompareEndDeps): EndOfRunTurn | undefined;
22
+ /** How long one grader request may take before it is cut: a verdict is a few words, so a request this late is stuck. */
23
+ export declare const GRADER_DEADLINE_MS = 60000;
24
+ /** One request to the grader's model over `models` (the run's port on the grader's route): its reply's text, the run's
25
+ * cap refusing it (`refused`: the proxy sent nothing and booked nothing), or a failure on its way (`failed`). pi-ai
26
+ * retries nothing of its own: the one retry is gradeAnswers'. Bounded by `signal` (the run's stop, its lost claim, its
27
+ * session closing) and `deadlineMs`, one combined abort signal: either one aborts the request and answers `cut`, and
28
+ * gradeAnswers asks it no more. Whatever it spent before it was cut is booked as any cut request is (the run's cap at its
29
+ * worst case). */
30
+ export declare function graderAsk(models: PortModels, request: {
31
+ readonly system: string;
32
+ readonly user: string;
33
+ }, given?: {
34
+ readonly signal?: AbortSignal;
35
+ readonly deadlineMs?: number;
36
+ }): Promise<GraderReply>;
37
+ /** `step` with the run's grader handed in: its fast model's name and one request to it, over `models` (the run's port on
38
+ * GRADER), cut by the step's `signal` (the loop aborts it on a person's stop or cancel, a lost claim or the session
39
+ * closing) or at GRADER_DEADLINE_MS. No grader: no step at all, so the run ends as it did before there was one. */
40
+ export declare function withGrader(step: EndOfRunTurn | undefined, grader: {
41
+ readonly model: string;
42
+ readonly models: () => Promise<PortModels>;
43
+ } | undefined): EndOfRunTurn | undefined;
@@ -0,0 +1,95 @@
1
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { gradeAnswers, sameAnswer } from "../learn/promote.js";
3
+ import { runPathOverStore } from "../store-reads/learning.js";
4
+ import { auditedAnswerOf } from "./audit.js";
5
+ import { held, heldEndOfRun } from "./held.js";
6
+ import { answerOf } from "./promotion.js";
7
+ /** The grader's route among a run's tier routes (never a learned workflow's tier, nor a subagent's), which is also the
8
+ * label its requests carry on the run's record. */
9
+ export const GRADER = "grader";
10
+ /** The most tokens the grader's verdict may take: a JSON object of a few words. */
11
+ const GRADER_MAX_TOKENS = 1_000;
12
+ /** The job input as the grader reads it: the launch's text, or its typed input as JSON. */
13
+ const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input ?? null));
14
+ /** The two answers a replay run or a shadow compares at its end: the agent's and the workflow's. A replay's workflow
15
+ * answer is its own, when the workflow it replays answered it; the agent's is its graded run's. A shadow's agent answer
16
+ * is its own; the workflow's is the served run's answer it audits (its open ledger line's turn). Null: nothing to
17
+ * compare. */
18
+ async function pairOf(launch, deps, runId) {
19
+ if (launch.replay) {
20
+ const path = await runPathOverStore(deps.store, runId, launch.learning, deps.redact);
21
+ if (path.path !== "workflow" || path.workflow !== launch.replay.workflow)
22
+ return null;
23
+ const [workflow, agent] = [await answerOf(deps.store, runId, BACKGROUND_CONTEXT), await answerOf(deps.store, launch.replay.of, BACKGROUND_CONTEXT)];
24
+ return workflow === null || agent === null ? null : { agent, workflow };
25
+ }
26
+ if (launch.audit) {
27
+ const [agent, workflow] = [await answerOf(deps.store, runId, BACKGROUND_CONTEXT), await auditedAnswerOf({ store: deps.store, context: BACKGROUND_CONTEXT, folder: deps.folder }, runId)];
28
+ return workflow === null || agent === null ? null : { agent, workflow };
29
+ }
30
+ return null;
31
+ }
32
+ /** The end-of-run step of a replay run or an audit's shadow (its callers pass no other run): its comparison (above),
33
+ * asked only when the run completed, was not cut, has a grader (its route exists only for a revision that names no
34
+ * agree_on, graderRouteOf), and the two answers are not already the same. In a run's own process the step is its runner's (held.ts endOfRun): it reads other runs and the
35
+ * learning ledger, which no run's process may. A comparison that fails keeps no verdict: the pair then differs, compared
36
+ * whole (compareAnswers), in the log's words. */
37
+ export function compareEndOfRun(launch, deps) {
38
+ if (held())
39
+ return heldEndOfRun();
40
+ return async (input) => {
41
+ if (input.cut !== undefined || input.outcome !== "completed" || !input.grade || input.grader === undefined)
42
+ return undefined;
43
+ try {
44
+ const pair = await pairOf(launch, deps, input.runId);
45
+ if (!pair || sameAnswer(pair.agent, pair.workflow))
46
+ return undefined;
47
+ const grade = input.grade;
48
+ const compared = await gradeAnswers(inputText(launch.input), pair.agent, pair.workflow, { model: input.grader, ask: (request) => grade(request) });
49
+ return { also: [], compared };
50
+ }
51
+ catch (error) {
52
+ deps.log(`learning: run ${input.runId}'s comparison was not asked (${error?.message ?? error})`);
53
+ return undefined;
54
+ }
55
+ };
56
+ }
57
+ /** How long one grader request may take before it is cut: a verdict is a few words, so a request this late is stuck. */
58
+ export const GRADER_DEADLINE_MS = 60_000;
59
+ /** One request to the grader's model over `models` (the run's port on the grader's route): its reply's text, the run's
60
+ * cap refusing it (`refused`: the proxy sent nothing and booked nothing), or a failure on its way (`failed`). pi-ai
61
+ * retries nothing of its own: the one retry is gradeAnswers'. Bounded by `signal` (the run's stop, its lost claim, its
62
+ * session closing) and `deadlineMs`, one combined abort signal: either one aborts the request and answers `cut`, and
63
+ * gradeAnswers asks it no more. Whatever it spent before it was cut is booked as any cut request is (the run's cap at its
64
+ * worst case). */
65
+ export async function graderAsk(models, request, given = {}) {
66
+ const failure = (words) => (/spend_cap_reached/.test(words) ? { refused: words } : { failed: words });
67
+ const deadlineMs = given.deadlineMs ?? GRADER_DEADLINE_MS;
68
+ const stopped = { cut: "its request was stopped with the run" };
69
+ if (given.signal?.aborted)
70
+ return stopped;
71
+ const limit = AbortSignal.timeout(deadlineMs);
72
+ const signal = given.signal ? AbortSignal.any([given.signal, limit]) : limit;
73
+ // An aborted request answers by whichever signal aborted it: the run's stop, else the deadline.
74
+ const cutOf = () => (given.signal?.aborted ? stopped : { cut: `its request gave no answer within ${deadlineMs / 1000} s` });
75
+ try {
76
+ const model = models.getModels()[0];
77
+ if (!model)
78
+ return { failed: "the grader's route is not up" };
79
+ const message = await models.completeSimple(model, { systemPrompt: request.system, messages: [{ role: "user", content: request.user, timestamp: Date.now() }] }, { maxTokens: GRADER_MAX_TOKENS, maxRetries: 0, signal });
80
+ if (message.stopReason === "error" || message.stopReason === "aborted")
81
+ return signal.aborted ? cutOf() : failure(message.errorMessage ?? message.stopReason);
82
+ return { text: message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("") };
83
+ }
84
+ catch (error) {
85
+ return signal.aborted ? cutOf() : failure(error?.message ?? String(error));
86
+ }
87
+ }
88
+ /** `step` with the run's grader handed in: its fast model's name and one request to it, over `models` (the run's port on
89
+ * GRADER), cut by the step's `signal` (the loop aborts it on a person's stop or cancel, a lost claim or the session
90
+ * closing) or at GRADER_DEADLINE_MS. No grader: no step at all, so the run ends as it did before there was one. */
91
+ export function withGrader(step, grader) {
92
+ if (!step || !grader)
93
+ return undefined;
94
+ return (input) => step({ ...input, grader: grader.model, grade: async (request) => graderAsk(await grader.models(), request, { signal: input.signal }) });
95
+ }
@@ -24,6 +24,9 @@ export type ComputerHoldChange = {
24
24
  /** Calls `listener` after each change of run `runId`'s hold is committed to its journal, in order, in this process.
25
25
  * Returns the unsubscribe. */
26
26
  export declare function onComputerHold(runId: string, listener: (change: ComputerHoldChange) => void): () => void;
27
+ /** A change run `runId`'s own process committed (Held.computerHold), signalled in its runner's process: its state, end and
28
+ * words as data, the words cut by the runner's redactor (`cut`); anything else is no change and is dropped. */
29
+ export declare function heardComputerHold(runId: string, change: unknown, cut: (text: string) => string): void;
27
30
  /** Whether a command row is the person's turn with the run's computer. */
28
31
  export declare const isComputerCommand: (command: Pick<Command, "kind">) => boolean;
29
32
  /** The journal's side of run `runId`'s hold, for the pass whose Harness `commit` writes root entries (in one commit, in
@@ -1,5 +1,6 @@
1
1
  import { HOST_PHASE } from "../timeline/index.js";
2
- import { COMPUTER_HAND_BACK, COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND, COMPUTER_TAKE_OVER, holdIn, holdWords, takeEndedWords, } from "../computer-commands.js";
2
+ import { COMPUTER_HAND_BACK, COMPUTER_HANDOVER_KIND, COMPUTER_HOLD_KIND, COMPUTER_TAKE_OVER, ENDS, holdIn, holdWords, STATES, takeEndedWords, } from "../computer-commands.js";
3
+ import { held } from "./held.js";
3
4
  import { KINDS } from "./journal-kinds.js";
4
5
  import { journalEntries } from "./journal-reader.js";
5
6
  /** Whether the run's journal says an earlier claim made the run a computer of its own (KINDS.computerMade, which only a
@@ -28,6 +29,25 @@ const signal = (runId, change) => {
28
29
  catch { /* a listener's error is not the hold's */ }
29
30
  }
30
31
  };
32
+ /** A committed change, signalled where the run's viewer listens: in this process, or, in a run's own process
33
+ * (run-child.ts), in its runner's, which holds the run's computer and its view (Held.computerHold). */
34
+ const committed = (runId, change) => {
35
+ const runner = held();
36
+ if (runner)
37
+ void runner.computerHold(change).catch(() => undefined);
38
+ else
39
+ signal(runId, change);
40
+ };
41
+ /** A change run `runId`'s own process committed (Held.computerHold), signalled in its runner's process: its state, end and
42
+ * words as data, the words cut by the runner's redactor (`cut`); anything else is no change and is dropped. */
43
+ export function heardComputerHold(runId, change, cut) {
44
+ if (!change || typeof change !== "object")
45
+ return;
46
+ const { state, ended, message } = change;
47
+ if (!STATES.includes(state) || (ended !== undefined && !ENDS.includes(ended)) || (message !== undefined && typeof message !== "string"))
48
+ return;
49
+ signal(runId, { state: state, ...(ended !== undefined ? { ended: ended } : {}), ...(typeof message === "string" ? { message: cut(message) } : {}) });
50
+ }
31
51
  /** Whether a command row is the person's turn with the run's computer. */
32
52
  export const isComputerCommand = (command) => command.kind === COMPUTER_TAKE_OVER || command.kind === COMPUTER_HAND_BACK;
33
53
  /** The journal's side of run `runId`'s hold, for the pass whose Harness `commit` writes root entries (in one commit, in
@@ -79,7 +99,7 @@ export function journalHold(runId, computer, commit, now = Date.now) {
79
99
  const off = hold.on((event) => {
80
100
  const entries = entriesOf(event);
81
101
  const change = changeOf(event, entries);
82
- void write(entries).then(() => change && signal(runId, change), () => undefined);
102
+ void write(entries).then(() => change && committed(runId, change), () => undefined);
83
103
  });
84
104
  return {
85
105
  /** The run's computer is up for this pass: the server shows it live, the agent driving. `prior`, the run's root
@@ -8,8 +8,13 @@ export declare class NeverFits extends ClaimRefused {
8
8
  }
9
9
  /** The dispatch's `resolve`, built from the runner's deps: it reads the run's revision (for a workflow revision) and
10
10
  * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words). */
11
- export declare function resolveRunnerLoop(deps: AdapterSpecDeps): (harness: string, launch: RunLaunch, runId: string) => Promise<LoopFactory | undefined>;
11
+ export declare function resolveRunnerLoop(given: AdapterSpecDeps): (harness: string, launch: RunLaunch, runId: string) => Promise<LoopFactory | undefined>;
12
12
  /** The loop factory the runner holds for every run (its createLoop), built from the runner's deps over the one store: the
13
13
  * dispatch (dispatch.ts) reads each run's launch and asks resolveRunnerLoop for its harness loop. The server
14
14
  * start and the test server pass this to startRunner. */
15
15
  export declare function dispatchRunner(deps: AdapterSpecDeps): LoopFactory;
16
+ /** `deps` with the model gateway saved in the console laid over its run environment (model-gateway.ts withSavedGateway),
17
+ * read from the store now; `deps` itself where none is saved or the runner's environment names its own. A run's own
18
+ * process (no seal key) reads nothing of it: its runner laid it over the claim (run-child-host.ts) and marked it
19
+ * (SAVED_GATEWAY_ENV), and only that mark is read here. */
20
+ export declare function withSavedGatewayDeps(deps: AdapterSpecDeps): Promise<AdapterSpecDeps>;