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

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -4,7 +4,7 @@ import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
5
  import { type Recorded, type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
- import { type CheckBar, type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
7
+ import { type CheckBar, type Compared, type PromotionRecord, recordPromotion, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
8
  import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
9
9
  import type { LearningFolder } from "../learn/folder.js";
10
10
  import type { Shown } from "../learning.js";
@@ -50,6 +50,9 @@ export interface PromotionDeps {
50
50
  * they are shortened (decideCheck). */
51
51
  readonly shown: () => Promise<Shown>;
52
52
  }
53
+ /** What deciding a check needs (decideCheck, stopUnchecked): a claim's ports, or those of a connected agent's start or
54
+ * run end, whose record names its commit (no claimed launch to read a seed from). */
55
+ type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now">>;
53
56
  /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
54
57
  * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
55
58
  * claim of this run served (`kept`, from its journal: none on a first claim). */
@@ -71,9 +74,17 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
71
74
  * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
72
75
  * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
73
76
  * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
74
- * in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
77
+ * in its place. One the records never named is an unchecked draft and is not offered. A replay run's as
75
78
  * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
76
79
  export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
80
+ /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
81
+ * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
82
+ * promoted, or its text cannot be read. The one champion lookup a claim's gate (servingNow), the learned_workflow tool
83
+ * (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
84
+ export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>): Promise<{
85
+ champion?: PromotionRecord;
86
+ text?: LearnedWorkflow;
87
+ }>;
77
88
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
78
89
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
79
90
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its check moved on (decide:
@@ -83,10 +94,19 @@ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentI
83
94
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
84
95
  /** The words a hold of a serving revision this release's workflow DSL refuses starts with (holdRefused). */
85
96
  export declare const DSL_REFUSES = "this release's workflow DSL refuses it";
97
+ /** Which check of a compile a new revision's is: 2 when the workflow's newest record of another revision is a first
98
+ * check's hold, an audit's hold or a hold by its reason alone (holdRefused: the DSL refuses a serving revision), or a
99
+ * first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
100
+ * (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
101
+ * whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
102
+ export declare function attemptOf(records: readonly PromotionRecord[], name: string, digest: string): 1 | 2;
86
103
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
87
104
  export declare const NOTHING_TO_CHECK = "nothing to check it on";
88
- /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none. */
89
- export declare const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word; name the fields that carry the decision (learning.agree_on)";
105
+ /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none: only a
106
+ * check no grader compared (no agree_on, and no fast model to read the answers). */
107
+ export declare const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word, and no fast model compared their decisions (a learning agent with no agree_on wants one: AGENT_MODEL_FAST, or its model_tiers.fast); name the fields that carry the decision (learning.agree_on)";
108
+ /** What a held check the grader compared says of the inputs it disagreed on: k of n, with one of the decisions. */
109
+ export declare const differentDecisionWords: (k: number, n: number, example: string | undefined) => string;
90
110
  /** One input a check ran its draft on: the agent's run (`of`) and its input, the agent's recorded answer, and what the
91
111
  * draft did: its answer when it answered alone, why it handed the input back, or failed (or skipped a write). A
92
112
  * reserved input whose replay run was never created, or never ended, by the check's deadline failed (`unstarted` for
@@ -100,19 +120,62 @@ type CheckRow = {
100
120
  readonly escalated?: string;
101
121
  readonly skipped?: Skipped;
102
122
  readonly unstarted?: true;
123
+ readonly compared?: Compared;
103
124
  };
104
125
  /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
105
- * with the agent's recorded answer (learn/promote.ts sameAnswer, on the bar's agree_on when it names fields), alone
126
+ * with the agent's recorded answer (learn/promote.ts compareAnswers, the audit's one comparison: on the bar's agree_on
127
+ * when it names fields, else equal, or the same decision by the grader's verdict its replay run kept), alone
106
128
  * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
107
129
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
108
130
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
109
131
  * (the one write: of two claims at once, one decides). */
110
- export declare function decideCheck(deps: PromotionDeps, name: string, digest: string, bar: CheckBar, read: {
132
+ export declare function decideCheck(deps: DecideDeps, name: string, digest: string, bar: CheckBar, read: {
111
133
  rows: readonly CheckRow[];
112
134
  cost: number | null;
113
135
  outcomes: ReplayOutcomes;
114
136
  unstarted: number;
115
- }, still: (was: PromotionRecord | undefined) => boolean, extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
137
+ exactMismatchReason?: string;
138
+ fresh_reads?: number;
139
+ }, still: Parameters<typeof recordPromotion>[3], extra: Partial<PromotionRecord>): Promise<import("../learn/promote.js").Recorded>;
140
+ /** How many of a connected agent's reserved native turns its check gives back before it stops. A turn is given back
141
+ * when it cannot be the check's baseline: cancelled or failed, a learned workflow or nested call in it, redacted
142
+ * evidence, no shadow report, or a shadow that did not answer. One or two are ordinary (a person cancels a task, an
143
+ * input carries a secret); five say the integration cannot give one (a client with no shadow check, inputs it never
144
+ * resolves, a draft whose shadow always refuses), and each reserved turn runs without the champion. The fifth stops it
145
+ * with nothing checked (stopUnchecked), which asks no recompile: a revision would have no baseline either. */
146
+ export declare const SDK_CHECK_RELEASES = 5;
147
+ /** A connected agent's draft reserved on one native turn: what its start hands the caller (sdk/runs.ts receipt). */
148
+ export type SdkWorkflowCheck = {
149
+ id: string;
150
+ revision: string;
151
+ digest: string;
152
+ workflow: LearnedWorkflow;
153
+ };
154
+ /** A connected agent's run input as a check row quotes it: the task text its start was given. */
155
+ export declare const sdkInputText: (launch: RunLaunch | undefined) => string;
156
+ /** Reserves one of `flows` (a connected agent's start's candidates, each its folder's newest revision) for a shadow
157
+ * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
158
+ * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
159
+ * concurrent starts. First each SDK check of a candidate's workflow is moved on: one whose turn is past
160
+ * REPLAY_DEADLINE_MS is decided as one failed row (sdkCheckDeadline), and one waiting at a revision the folder moved
161
+ * past is set aside. A managed replay's record (no `via`) is never touched here. */
162
+ export declare function reserveSdkCheck(deps: DecideDeps, turn: {
163
+ readonly runId: string;
164
+ readonly revision: string | null;
165
+ readonly learning: unknown;
166
+ readonly flows: readonly LearnedWorkflow[];
167
+ readonly takes: (flow: LearnedWorkflow) => boolean;
168
+ }): Promise<SdkWorkflowCheck | undefined>;
169
+ /** A connected agent's check whose native turn did not settle it by REPLAY_DEADLINE_MS (the backend never completed the
170
+ * turn, or the server stopped before the run's end): decided as every check is (decideCheck), on one failed row. Its
171
+ * hold asks the one recompile, and a recompile's check that ends here stops (`stopped`): an abandoned check never
172
+ * restarts its budget. */
173
+ export declare function sdkCheckDeadline(deps: DecideDeps, pending: PromotionRecord): Promise<import("../learn/promote.js").Recorded | undefined>;
174
+ /** Gives back a connected agent's reserved native turn that cannot be its check's baseline (`cause`): the check waits for
175
+ * the next turn the draft takes, nothing decided or promoted, and the turn counts toward SDK_CHECK_RELEASES, whose last
176
+ * stops it with nothing checked (stopUnchecked: no recompile). `counted` false: no turn ran (its start was not
177
+ * admitted). Kept only while the record is still this reservation. */
178
+ export declare function releaseSdkCheck(deps: DecideDeps, record: PromotionRecord, cause: string, counted?: boolean): Promise<import("../learn/promote.js").Recorded | undefined>;
116
179
  /** A run's final answer row, its text whole (its last final answer row that is not its end-of-run turn's), or null: none,
117
180
  * or its record could not be read. `turn`: the row of that id instead (the answer an audit is of, runner/audit.ts), so an
118
181
  * answer a follow-up gave since is never read for it. */
@@ -7,9 +7,10 @@ import { FINAL_STATES, RunFinal, StoreConstraint } from "../store/store.js";
7
7
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
8
8
  import { isCliRecord, piShaped, runEntries, runTimeline } from "../store-reads/journal.js";
9
9
  import { pinAnnotations, recordedCalls, replayCalls, SKIPPED_WRITE, toolClassOf, toolWord, unmarkedWords } from "../learn/replay-calls.js";
10
+ import { listed } from "../learning-words.js";
10
11
  import { isObject } from "../validate.js";
11
12
  import { agentRun, lastOwnRuns, newCompileAttempt } from "../learn/compile.js";
12
- import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, fieldsWords, promotionOf, promotionsOf, recordPromotion, replayingOf, sameAnswer, skippedToolsOf } from "../learn/promote.js";
13
+ import { checkPasses, checkShares, CHECK_TEXT_MAX, championOf, compareAnswers, comparedOf, promotionOf, promotionsOf, recordPromotion, replayingOf, skippedToolsOf } from "../learn/promote.js";
13
14
  import { sendCommand } from "./commands.js";
14
15
  import { ClaimRefused } from "./loop-contract.js";
15
16
  import { readSnapshot } from "../learn/folder.js";
@@ -77,7 +78,7 @@ export function replayLaid(launch, laid) {
77
78
  * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
78
79
  * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
79
80
  * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
80
- * in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A replay run's as
81
+ * in its place. One the records never named is an unchecked draft and is not offered. A replay run's as
81
82
  * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
82
83
  export async function toolFlowsFor(deps, launch, laid, choice) {
83
84
  const chosen = laidFor(laid, choice);
@@ -94,18 +95,15 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
94
95
  }
95
96
  const out = [];
96
97
  for (const one of chosen) {
97
- if (one.name === name || !records.some((record) => record.workflow === one.name)) {
98
+ if (one.name === name) {
98
99
  out.push(one);
99
100
  continue;
100
101
  }
101
102
  const digest = workflowDigest(one);
102
- const champion = championOf(records, one.name);
103
- if (champion?.digest === digest) {
103
+ const { champion, text } = await championTextOf(records, one, deps.champion);
104
+ if (text === one)
104
105
  out.push(one);
105
- continue;
106
- }
107
- const text = champion?.commit && deps.champion ? await deps.champion(one.name, champion.commit).catch(() => undefined) : undefined;
108
- if (text && workflowDigest(text) === champion.digest) {
106
+ else if (text) {
109
107
  deps.log(`workflow-first: the learned_workflow tool runs ${one.name}'s champion at ${champion.digest}, not ${digest}, which is not promoted`);
110
108
  out.push(text);
111
109
  }
@@ -114,9 +112,22 @@ export async function toolFlowsFor(deps, launch, laid, choice) {
114
112
  }
115
113
  return out;
116
114
  }
115
+ /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
116
+ * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
117
+ * promoted, or its text cannot be read. The one champion lookup a claim's gate (servingNow), the learned_workflow tool
118
+ * (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
119
+ export async function championTextOf(records, flow, read) {
120
+ const champion = championOf(records, flow.name);
121
+ if (!champion)
122
+ return {};
123
+ if (champion.digest === workflowDigest(flow))
124
+ return { champion, text: flow };
125
+ const text = champion.commit && read ? await read(flow.name, champion.commit).catch(() => undefined) : undefined;
126
+ return text && workflowDigest(text) === champion.digest ? { champion, text } : { champion };
127
+ }
117
128
  const iso = (ms) => new Date(ms).toISOString();
118
129
  /** The claim's seed as a record's `commit`: the learning commit the laid workflow's text was read from. */
119
- const seedOf = (deps) => (deps.launch.learning?.seed ? { commit: deps.launch.learning.seed } : {});
130
+ const seedOf = (deps) => (deps.launch?.learning?.seed ? { commit: deps.launch.learning.seed } : {});
120
131
  const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
121
132
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
122
133
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
@@ -161,7 +172,7 @@ export const promotionGate = (deps) => {
161
172
  * serves: none promoted, the champion held, or its text cannot be read (the agent takes the run). */
162
173
  async function servingNow(deps, workflow, digest, laid) {
163
174
  const records = await promotionsOf(deps.store.settings, deps.agentId);
164
- const champion = championOf(records, workflow.name);
175
+ const { champion, text } = await championTextOf(records, workflow, deps.champion);
165
176
  const own = promotionOf(records, workflow.name, digest);
166
177
  if (!champion) {
167
178
  if (own?.decided === "promote")
@@ -172,8 +183,7 @@ async function servingNow(deps, workflow, digest, laid) {
172
183
  return laid ? { workflow } : undefined;
173
184
  if (!deps.champion)
174
185
  return undefined;
175
- const text = champion.commit ? await deps.champion(workflow.name, champion.commit).catch(() => undefined) : undefined;
176
- if (!text || workflowDigest(text) !== champion.digest) {
186
+ if (!text) {
177
187
  deps.log(`workflow-first: ${workflow.name}'s champion at ${champion.digest} could not be read from its learning commit; the agent takes this run`);
178
188
  return undefined;
179
189
  }
@@ -262,7 +272,7 @@ async function loopOfRevision(deps) {
262
272
  * first compile's failed draft (this revision is its one recompile), else 1. A stop with nothing checked
263
273
  * (stopUnchecked) is no first check's hold: it spends no recompile. A workflow's first revision after a first compile
264
274
  * whose drafts failed under another name (learn/compile.ts newCompileAttempt) is that compile's recompile too. */
265
- function attemptOf(records, name, digest) {
275
+ export function attemptOf(records, name, digest) {
266
276
  const before = records.findLast((one) => one.workflow === name && one.digest !== digest);
267
277
  if (!before)
268
278
  return newCompileAttempt(records.filter((one) => one.digest !== digest));
@@ -365,8 +375,11 @@ async function startCheck(deps, workflow, digest) {
365
375
  }
366
376
  /** The words a stopped check's record starts with when it had nothing to check its draft on. */
367
377
  export const NOTHING_TO_CHECK = "nothing to check it on";
368
- /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none. */
369
- export const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word; name the fields that carry the decision (learning.agree_on)";
378
+ /** What a held check compared on the whole answer says when it answered some inputs alone and agreed on none: only a
379
+ * check no grader compared (no agree_on, and no fast model to read the answers). */
380
+ export const NEVER_WORD_FOR_WORD = "its answers never matched the agent's word for word, and no fast model compared their decisions (a learning agent with no agree_on wants one: AGENT_MODEL_FAST, or its model_tiers.fast); name the fields that carry the decision (learning.agree_on)";
381
+ /** What a held check the grader compared says of the inputs it disagreed on: k of n, with one of the decisions. */
382
+ export const differentDecisionWords = (k, n, example) => `its answers reached a different decision from the agent's on ${k} of ${n}${example ? ` (for example: ${example})` : ""}`;
370
383
  /** Stops a draft its check had nothing to run on (`why`: no input of the agent's it takes, or every input skipped at a
371
384
  * write): held, never promoted unchecked, its record `stopped` (nothing compiles again until a hold or its owner acts)
372
385
  * and naming the cause, which the compile's draft errors show (store-reads/loop.ts). It asks no recompile: a revision
@@ -418,7 +431,10 @@ async function checkRows(deps, record) {
418
431
  }
419
432
  const outcome = outcomeOf(run);
420
433
  const stoppedAt = outcome === "skipped_write" ? metricsOf(run).replay?.skipped : undefined;
434
+ // The grader's verdict on this pair, asked at the replay run's end (runner/compare-end.ts).
435
+ const compared = outcome === "answered" ? comparedOf(metricsOf(run).replay?.compared) : undefined;
421
436
  rows.push({
437
+ ...(compared ? { compared } : {}),
422
438
  of: replayed, input: inputText(launch.input), agent: await answerOf(store, replayed, context), outcome,
423
439
  answer: outcome === "answered" ? await answerOf(store, run.id, context) : null,
424
440
  ...(outcome === "handed_back" ? { escalated: (await handedBackOf(store, run.id, context)) ?? "" } : {}),
@@ -459,7 +475,8 @@ async function settleCheck(deps, workflow, digest, record) {
459
475
  return decided.record?.decided === "replaying" ? undefined : decided.record;
460
476
  }
461
477
  /** Decides a check on its rows: each input it ran on (a skipped write is none) agreed when the draft answered it alone
462
- * with the agent's recorded answer (learn/promote.ts sameAnswer, on the bar's agree_on when it names fields), alone
478
+ * with the agent's recorded answer (learn/promote.ts compareAnswers, the audit's one comparison: on the bar's agree_on
479
+ * when it names fields, else equal, or the same decision by the grader's verdict its replay run kept), alone
463
480
  * when it answered it with no escalate and no failed step. Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
464
481
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
465
482
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
@@ -468,17 +485,25 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
468
485
  const now = deps.now ?? Date.now;
469
486
  const ran = read.rows.filter((row) => row.outcome !== "skipped_write");
470
487
  const alone = (row) => row.outcome === "answered";
471
- // Compared on the bar's agree_on when it names paths (the definition's), else the whole answer.
472
- const agrees = (row) => alone(row) && sameAnswer(row.answer, row.agent, bar.agree_on);
488
+ // Compared on the bar's agree_on when it names paths (the definition's), else equal answers agree and the grader's
489
+ // verdict decides the rest; with no grader (no fast model), the whole answer.
490
+ const compared = new Map(ran.map((row) => [row, compareAnswers(row.answer, row.agent, bar.agree_on, row.compared)]));
491
+ const agrees = (row) => alone(row) && compared.get(row).same;
473
492
  const score = { n: ran.length, agreed: ran.filter(agrees).length, alone: ran.filter(alone).length };
474
493
  const ok = checkPasses(score, bar);
494
+ // The fast model that compared, when it read any input's answers.
495
+ const grader = [...compared.values()].find((one) => one.grader !== undefined)?.grader;
475
496
  // Each text is cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown).
476
497
  const shown = await deps.shown();
477
498
  const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
478
- const disagreements = ran.filter((row) => !agrees(row)).map((row) => ({
479
- run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
480
- ...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
481
- }));
499
+ const disagreements = ran.filter((row) => !agrees(row)).map((row) => {
500
+ const differs = row.outcome === "answered" ? compared.get(row).differs_on : undefined;
501
+ return {
502
+ run: row.of, input: cut(row.input), agent: row.agent === null ? null : cut(row.agent),
503
+ ...(row.outcome === "answered" ? { draft: cut(row.answer ?? "") } : row.outcome === "handed_back" ? { escalated: cut(row.escalated ?? "") } : { failed: true }),
504
+ ...(differs ? { differs_on: cut(differs) } : {}),
505
+ };
506
+ });
482
507
  const stopped = !ok && bar.attempt === 2;
483
508
  const pct = (value) => `${(value * 100).toFixed(1)}%`;
484
509
  const shares = checkShares(score);
@@ -487,7 +512,7 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
487
512
  const tools = skippedToolsOf(read.rows);
488
513
  const { skipped_write: skipped, failed } = read.outcomes;
489
514
  const { hint, why: skipWhy } = skipWordsOf(tools, skipped);
490
- const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}) };
515
+ const numbers = { of: read.rows.map((row) => row.of), cost_usd: read.cost, outcomes: read.outcomes, ...(read.unstarted ? { unstarted: read.unstarted } : {}), ...(tools.length ? { skipped_tools: tools } : {}), ...(read.fresh_reads ? { fresh_reads: read.fresh_reads } : {}) };
491
516
  // Every input skipped at a write (each reserved input counts: one never created or never ended failed, so this is the
492
517
  // only way to none): nothing to check it on, so it stops, never promoted unchecked, and asks no recompile.
493
518
  if (!score.n) {
@@ -501,11 +526,14 @@ export async function decideCheck(deps, name, digest, bar, read, still, extra) {
501
526
  // and the words say none ran.
502
527
  const said = read.unstarted === score.n
503
528
  ? `none of its ${plural(score.n, "check run")} started by the check's deadline (its launch was interrupted: the server stopped after reserving it, say): nothing was checked`
504
- : `checked on ${score.n} of the agent's inputs: answered ${score.alone} alone (${pct(shares.alone)}, the bar ${pct(bar.alone_min)}), and ${score.agreed} of those said what the agent said${bar.agree_on?.length ? ` on ${fieldsWords(bar.agree_on)}` : ""} (${pct(shares.agreement)}, the bar ${pct(bar.agree_min)})${aside ? ` (${aside})` : ""}`;
505
- // Compared whole and never once the same: free text two runs never repeat, most likely, so the owner is told what to set.
506
- const verbatim = !ok && !bar.agree_on?.length && score.alone > 0 && score.agreed === 0 ? `; ${NEVER_WORD_FOR_WORD}` : "";
529
+ : `checked on ${score.n} of the agent's inputs: answered ${score.alone} alone (${pct(shares.alone)}, the bar ${pct(bar.alone_min)}), and ${score.agreed} of those said what the agent said${bar.agree_on?.length ? ` on ${listed(bar.agree_on)}` : grader ? `, compared by the fast model (${grader})` : ""} (${pct(shares.agreement)}, the bar ${pct(bar.agree_min)})${aside ? ` (${aside})` : ""}`;
530
+ // The grader compared: how many answered alone reached another decision, with one it named. Compared whole and never
531
+ // once the same (no grader): free text two runs never repeat, most likely, so the owner is told what to set.
532
+ const differed = score.alone - score.agreed;
533
+ const example = disagreements.find((one) => one.differs_on !== undefined)?.differs_on;
534
+ const verbatim = ok || bar.agree_on?.length ? "" : grader ? (differed > 0 ? `; ${differentDecisionWords(differed, score.alone, example)}` : "") : score.alone > 0 && score.agreed === 0 ? `; ${read.exactMismatchReason ?? NEVER_WORD_FOR_WORD}` : "";
507
535
  const reason = ok ? `${said}: promoted` : stopped ? `${said}: held${verbatim}, and this was the recompile's check, so it stops: nothing compiles again until a hold or its owner acts` : `${said}: held${verbatim}; the agent's next run recompiles it once with the inputs it did not agree on`;
508
- const check = { ...bar, ...score, ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}) };
536
+ const check = { ...bar, ...score, ...numbers, ...(disagreements.length ? { disagreements } : {}), ...(stopped ? { stopped: true } : {}), ...(grader ? { grader } : {}) };
509
537
  const decided = await recordPromotion(deps.store.settings, deps.agentId, { workflow: name, digest, at: iso(now()), decided: ok ? "promote" : "hold", reason, check, ...seedOf(deps), ...extra }, still);
510
538
  if (decided.won)
511
539
  deps.log(`workflow-first: ${name} at ${digest} ${ok ? "promoted" : "held"}: ${reason}`);
@@ -526,6 +554,128 @@ async function reserve(deps, workflow, digest, inputs, reason, still, check) {
526
554
  await startReplay(deps, workflow, digest, one.run, one.launch, ids[i], launch);
527
555
  return reserved;
528
556
  }
557
+ /** How many of a connected agent's reserved native turns its check gives back before it stops. A turn is given back
558
+ * when it cannot be the check's baseline: cancelled or failed, a learned workflow or nested call in it, redacted
559
+ * evidence, no shadow report, or a shadow that did not answer. One or two are ordinary (a person cancels a task, an
560
+ * input carries a secret); five say the integration cannot give one (a client with no shadow check, inputs it never
561
+ * resolves, a draft whose shadow always refuses), and each reserved turn runs without the champion. The fifth stops it
562
+ * with nothing checked (stopUnchecked), which asks no recompile: a revision would have no baseline either. */
563
+ export const SDK_CHECK_RELEASES = 5;
564
+ /** A connected agent's check waiting for a native turn (`via` sdk, replaying, no turn reserved). */
565
+ const waitingSdk = (record) => record?.decided === "replaying" && record.via === "sdk" && !record.runs?.length;
566
+ /** Whether a connected agent's check was overtaken: a record of another revision of its workflow came after its own
567
+ * newest (a newer revision reserved, held by its owner, or promoted). An overtaken check is given no record of its own
568
+ * on a release, a deadline or a set-aside, so it never hides that newer record from the compile (learn/compile.ts
569
+ * heldNamesOf reads the workflow's newest), and it blocks no newer revision's reservation. A report that reached it
570
+ * still decides it (decideCheck), as an older check's verdict stands. */
571
+ const overtaken = (records, record) => {
572
+ const own = promotionOf(records, record.workflow, record.digest);
573
+ const at = own ? records.lastIndexOf(own) : -1;
574
+ return at >= 0 && records.slice(at + 1).some((one) => one.workflow === record.workflow && one.digest !== record.digest);
575
+ };
576
+ /** The checks of `name` other than at `digest` that block reserving it: every replaying one but an overtaken SDK one. */
577
+ const blocking = (records, name, digest) => replayingOf(records, name, digest).filter((one) => one.via !== "sdk" || !overtaken(records, one));
578
+ /** What every record of a connected agent's check carries on from its reservation. */
579
+ const sdkExtra = (record) => ({ via: "sdk", ...(record.runs ? { runs: record.runs } : {}), ...(record.replay_id ? { replay_id: record.replay_id } : {}), ...(record.commit ? { commit: record.commit } : {}) });
580
+ /** A connected agent's run input as a check row quotes it: the task text its start was given. */
581
+ export const sdkInputText = (launch) => {
582
+ const input = launch?.input;
583
+ return isObject(input) && typeof input.content === "string" ? input.content : inputText(input);
584
+ };
585
+ /** Reserves one of `flows` (a connected agent's start's candidates, each its folder's newest revision) for a shadow
586
+ * check on the native turn `runId`: the first the turn takes (`takes`) with no decision yet, or one waiting for a turn,
587
+ * while no other revision of its workflow is checked; the guarded write keeps one reservation per workflow across
588
+ * concurrent starts. First each SDK check of a candidate's workflow is moved on: one whose turn is past
589
+ * REPLAY_DEADLINE_MS is decided as one failed row (sdkCheckDeadline), and one waiting at a revision the folder moved
590
+ * past is set aside. A managed replay's record (no `via`) is never touched here. */
591
+ export async function reserveSdkCheck(deps, turn) {
592
+ const { revision } = turn;
593
+ if (!revision)
594
+ return;
595
+ const now = deps.now ?? Date.now;
596
+ for (const flow of turn.flows) {
597
+ const digest = workflowDigest(flow);
598
+ const before = await promotionsOf(deps.store.settings, deps.agentId);
599
+ for (const pending of replayingOf(before, flow.name, null)) {
600
+ if (pending.via !== "sdk" || overtaken(before, pending))
601
+ continue;
602
+ if (pending.runs?.length) {
603
+ if (now() - Date.parse(pending.at) > REPLAY_DEADLINE_MS)
604
+ await sdkCheckDeadline(deps, pending);
605
+ }
606
+ else if (pending.digest !== digest)
607
+ await setAside(deps, pending);
608
+ }
609
+ if (!turn.takes(flow))
610
+ continue;
611
+ const records = await promotionsOf(deps.store.settings, deps.agentId);
612
+ const own = promotionOf(records, flow.name, digest);
613
+ if ((own && !waitingSdk(own)) || blocking(records, flow.name, digest).length)
614
+ continue;
615
+ const id = uuidv7();
616
+ const reserved = await recordPromotion(deps.store.settings, deps.agentId, {
617
+ workflow: flow.name, digest, at: iso(now()), decided: "replaying", via: "sdk",
618
+ reason: "Checking it in the connected agent against one independent native turn before it can be reused.",
619
+ replay_id: id, runs: [turn.runId], inputs: [turn.runId], commit: revision,
620
+ check: own?.check ?? { ...loopOf(turn.learning), attempt: attemptOf(records, flow.name, digest) },
621
+ }, (was, current) => (own ? waitingSdk(was) && was.replay_id === own.replay_id : was === undefined) && blocking(current, flow.name, digest).length === 0);
622
+ if (reserved.won)
623
+ return { id, revision, digest, workflow: flow };
624
+ }
625
+ }
626
+ /** A connected agent's check whose native turn did not settle it by REPLAY_DEADLINE_MS (the backend never completed the
627
+ * turn, or the server stopped before the run's end): decided as every check is (decideCheck), on one failed row. Its
628
+ * hold asks the one recompile, and a recompile's check that ends here stops (`stopped`): an abandoned check never
629
+ * restarts its budget. */
630
+ export async function sdkCheckDeadline(deps, pending) {
631
+ const runId = pending.runs?.[0];
632
+ if (!runId || !pending.check || overtaken(await promotionsOf(deps.store.settings, deps.agentId), pending))
633
+ return;
634
+ const launch = await deps.store.runs.launch(runId).then((one) => readLaunchBody(one.body), () => undefined);
635
+ return decideCheck(deps, pending.workflow, pending.digest, pending.check, {
636
+ rows: [{ of: runId, input: sdkInputText(launch), agent: null, outcome: "failed", answer: null }],
637
+ cost: null, outcomes: { ...NO_OUTCOMES, failed: 1 }, unstarted: 0,
638
+ }, (was, current) => sameReplay(was, pending) && !overtaken(current, was), sdkExtra(pending));
639
+ }
640
+ /** Gives back a connected agent's reserved native turn that cannot be its check's baseline (`cause`): the check waits for
641
+ * the next turn the draft takes, nothing decided or promoted, and the turn counts toward SDK_CHECK_RELEASES, whose last
642
+ * stops it with nothing checked (stopUnchecked: no recompile). `counted` false: no turn ran (its start was not
643
+ * admitted). Kept only while the record is still this reservation. */
644
+ export async function releaseSdkCheck(deps, record, cause, counted = true) {
645
+ if (!record.check)
646
+ return;
647
+ if (overtaken(await promotionsOf(deps.store.settings, deps.agentId), record)) {
648
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} gave back its native turn (${cause}); a newer revision has a record since, so it is left as it is`);
649
+ return;
650
+ }
651
+ const released = (record.check.released ?? 0) + (counted ? 1 : 0);
652
+ const why = excerptShown(cause, await deps.shown(), CHECK_TEXT_MAX);
653
+ // Overtaken is read again inside the write: a newer revision's record can land while the cause is being cut.
654
+ const still = (was, current) => sameReplay(was, record) && !overtaken(current, was);
655
+ const bar = { ...record.check, ...(released ? { released } : {}) };
656
+ if (released >= SDK_CHECK_RELEASES)
657
+ return stopUnchecked(deps, record.workflow, record.digest, bar, `the connected agent gave back ${plural(released, "reserved native turn")} with no answer to check it against (the last: ${why})`, still, {}, sdkExtra(record));
658
+ const { runs: _runs, inputs: _inputs, ...rest } = record;
659
+ const kept = await recordPromotion(deps.store.settings, deps.agentId, {
660
+ ...rest, at: iso((deps.now ?? Date.now)()), check: bar,
661
+ reason: `Waiting for a native turn of the connected agent that it takes: ${why}, so that turn was given back${counted ? ` (${released} of ${SDK_CHECK_RELEASES} before the check stops)` : ""}. Nothing was promoted.`,
662
+ }, still);
663
+ if (kept.won)
664
+ deps.log(`workflow-first: ${record.workflow} at ${record.digest} waits for another native turn: ${why}`);
665
+ return kept;
666
+ }
667
+ /** A connected agent's check waiting at a revision the folder moved past (an owner's edit landed a newer one): set aside
668
+ * with nothing checked, never promoted, and `stopped` as any stop with nothing checked, so it spends no recompile
669
+ * (attemptOf): the newer revision is the one checked next. */
670
+ async function setAside(deps, pending) {
671
+ if (!pending.check)
672
+ return;
673
+ await recordPromotion(deps.store.settings, deps.agentId, {
674
+ ...pending, at: iso((deps.now ?? Date.now)()), decided: "hold",
675
+ reason: `${NOTHING_TO_CHECK}: a newer revision of it landed before a native turn of the connected agent checked it. It is not promoted; the newer revision is checked instead`,
676
+ check: { ...pending.check, n: 0, agreed: 0, alone: 0, of: [], stopped: true },
677
+ }, (was, current) => waitingSdk(was) && was.replay_id === pending.replay_id && !overtaken(current, was));
678
+ }
529
679
  /** The launch a replay's runs all run with (PromotionRecord.launch), chosen once by the claim or person reserving it:
530
680
  * `deps.launch` as a replay run takes it (a claim's claimed run's; a person's ask makes one now), the revision it runs,
531
681
  * and the claimed run as the one whose per_run MCP credentials its runs are handed, when the server can seal them. A
@@ -31,7 +31,8 @@ import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
31
31
  import { learningEndOfRun } from "./learning-end.js";
32
32
  import { runnerSecrets } from "./redact.js";
33
33
  import { storeSecrets } from "./store-secrets.js";
34
- import { FAUX_ENV } from "../model.js";
34
+ import { FAUX_ENV, GATEWAY_KEY_ENV } from "../model.js";
35
+ import { SAVED_GATEWAY_ENV, savedGatewayIn } from "../model-gateway.js";
35
36
  import { FAUX_VENDOR_API_ENV } from "../tools.js";
36
37
  import { withinCarried } from "../paid-calls.js";
37
38
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
@@ -52,14 +53,16 @@ import { learningStartOf, seedFailed } from "../run-launch.js";
52
53
  import { messageText } from "../run-manifest.js";
53
54
  import { placeRunInputs } from "../uploads.js";
54
55
  import { withAudit } from "./audit.js";
56
+ import { compareEndOfRun } from "./compare-end.js";
55
57
  import { learnedFirst } from "./learned-first.js";
56
58
  import { workflowsAt } from "./learning-seed.js";
57
59
  import { heldMcpOf, mcpForClaim } from "./mcp-run.js";
58
60
  import { learnedTiers, learnsWorkflows, mcpReachOf } from "./adapter-run-spec.js";
59
61
  import { createDispatchLoop } from "./dispatch.js";
60
- import { resolveRunnerLoop } from "./harness-loops.js";
62
+ import { resolveRunnerLoop, withSavedGatewayDeps } from "./harness-loops.js";
61
63
  import { isWorkflowRevision } from "./workflow-loop.js";
62
64
  import { loginForRun } from "../claude-login.js";
65
+ import { heardComputerHold } from "./computer-journal.js";
63
66
  import { ClaimRefused } from "./loop-contract.js";
64
67
  import { Channel, ChannelClosed } from "./run-channel.js";
65
68
  import { registerRunErrors } from "./run-errors.js";
@@ -738,6 +741,8 @@ export function heldFor(deps, reads, cut, log) {
738
741
  runZone: () => runZone(store, launch.inputOrigin),
739
742
  liveViewerPut: (handover) => putLiveViewer(store, sealKey, claim, handover),
740
743
  liveViewerDrop: (tag) => dropLiveViewer(store, claim, tag),
744
+ // The claim's own run, whatever the process names: its view on this runner hears the change.
745
+ computerHold: async (change) => heardComputerHold(claim.runId, change, cut),
741
746
  handOn: async (from, id) => {
742
747
  if (from !== claim.runId || typeof id !== "string")
743
748
  return undefined;
@@ -799,9 +804,17 @@ export function heldFor(deps, reads, cut, log) {
799
804
  // The step as the run's spec builds it in a runner (adapter-run-spec.ts), over the runner's reads of the claim: what
800
805
  // the run must never learn is every secret this runner holds, the keys its claim handed it, every secret the server
801
806
  // keeps sealed and its sign-in's pointers, none of which the run's process is given.
802
- // A replay run or an audit's shadow run asks nothing at its end, as the run's spec says (adapter-run-spec.ts).
803
- if (launch.replay || launch.audit)
804
- return undefined;
807
+ // A replay run or an audit's shadow run learns nothing at its end, as the run's spec says (adapter-run-spec.ts): it
808
+ // compares its answer with the other one through its grader, handed in by the run's process (runner/compare-end.ts).
809
+ // This runner reads both answers and the learning ledger, which no run's process may.
810
+ if (launch.replay || launch.audit) {
811
+ const compare = compareEndOfRun(launch, { store, folder: await folderNow(), log, redact: cut });
812
+ const grade = input.grade;
813
+ const rows = compare && grade && typeof input.grader === "string"
814
+ ? await compare({ runId: claim.runId, agentId: run.agentId, claim, outcome: input.outcome === "failed" ? "failed" : "completed", ...(input.cut === undefined ? {} : { cut: "faulted" }), grader: input.grader, grade: (request) => grade(request), ask: input.ask, signal: input.signal })
815
+ : undefined;
816
+ return rows?.compared ? { also: [], compared: dataOnly(rows.compared) } : undefined;
817
+ }
805
818
  const made = await archilOf();
806
819
  // The audit's spend, skipped as the run's spec skips it (claim-secrets.ts claimSpendOff): over the claim's own key.
807
820
  const spendOff = await claimSpendOff(keys, await claimModelKey(keys, claim.runId));
@@ -977,6 +990,13 @@ export function childLoops(options) {
977
990
  });
978
991
  }
979
992
  registerRunErrors();
993
+ /** `claimed` with the saved gateway's key beside its own (the runner's reads of what the run must never keep, heldFor):
994
+ * a copy, every property as it is (its non-enumerable keys and the sign-in's reader too), the key non-enumerable. */
995
+ function withGatewayKey(claimed, key) {
996
+ const out = Object.defineProperties({}, Object.getOwnPropertyDescriptors(claimed));
997
+ Object.defineProperty(out, GATEWAY_KEY_ENV, { value: key, enumerable: false, writable: false, configurable: false });
998
+ return out;
999
+ }
980
1000
  /** The environment a run's process starts with: the runner's run environment's plain values (runEnv: its secrets are
981
1001
  * not enumerable, so none is here), no key-shaped name, and where its keys come from. */
982
1002
  function childEnv(base, keys, extra) {
@@ -1057,17 +1077,26 @@ function childLoop(options, slots, loopDeps) {
1057
1077
  if (!revisionRow)
1058
1078
  throw new Error(`run ${claim.runId}: its revision ${runRow.revisionId} is gone from the store`);
1059
1079
  const revision = { kind: revisionRow.kind, body: (revisionRow.body ?? {}) };
1080
+ // The model gateway saved in the console, read from the store now and laid over this claim's environment, as a run
1081
+ // in this process has it laid (harness-loops.ts): the run's process reads no store row of it and holds no seal key.
1082
+ const claimDeps = await withSavedGatewayDeps(deps);
1083
+ const claimEnv = claimDeps.env ?? {};
1084
+ const savedGateway = savedGatewayIn(claimEnv);
1060
1085
  // The run's own keys: those its claim opens (claim-secrets.ts), the one list its loop in this process read.
1061
- const claimed = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, launch);
1086
+ const claimed = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: claimEnv }, revisionRow, launch);
1062
1087
  // With them, its revision's own model's (a launch pinned at its start to another model, a --faux start's, is still
1063
1088
  // handed its agent's model's key, as a run's own process was handed it before: run-secrets.ts secretsFor).
1064
- const ofRevision = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, { ...(launch.plane ? { plane: launch.plane } : {}) });
1089
+ const ofRevision = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: claimEnv }, revisionRow, { ...(launch.plane ? { plane: launch.plane } : {}) });
1065
1090
  // A run that holds a model key of its own (model_key, its launch's) spends that key alone: its process is handed
1066
1091
  // none of the server's model keys, as its spec drops them from its tools' (claim-secrets.ts withoutModelKeys).
1067
1092
  // Copies: the runner's own reads (heldFor's `claimed`: what the run's learning must never keep) stay whole.
1068
1093
  const keyed = (await openRunModelKey({ store: deps.store, sealKey: deps.sealKey }, claim.runId)) !== undefined;
1069
1094
  const toProcess = keyed ? [withoutModelKeys({ ...claimed }), withoutModelKeys({ ...ofRevision })] : [claimed, ofRevision];
1070
- const handed = (name) => toProcess.map((from) => from[name]).find((value) => typeof value === "string" && value !== "");
1095
+ // The saved gateway's key, kept off the claim's tool keys (claimSecrets), is handed for the run's model routes alone,
1096
+ // read as the server's model keys are (savedModelKeys, over the claim's environment the gateway was laid over), as a
1097
+ // run in this process reads it from its environment by name; none to a run that brings its own key.
1098
+ const gatewayKey = savedGateway ? (keyed ? {} : await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: claimEnv }))[GATEWAY_KEY_ENV] || undefined : undefined;
1099
+ const handed = (name) => (name === GATEWAY_KEY_ENV && savedGateway ? gatewayKey : toProcess.map((from) => from[name]).find((value) => typeof value === "string" && value !== ""));
1071
1100
  const keys = encode(SECRET_NAMES.flatMap((name) => {
1072
1101
  const value = handed(name);
1073
1102
  return value === undefined ? [] : [[name, value]];
@@ -1091,7 +1120,7 @@ function childLoop(options, slots, loopDeps) {
1091
1120
  if (isolation.kind === "uid" && slot !== undefined)
1092
1121
  hold = new SlotHold(slot, isolation.helper, log);
1093
1122
  const tops = runTops(deps.data, runRow.agentId, claim.runId);
1094
- const heldSide = heldFor(deps, { claim, run: runRow, launch, revision, claimed }, cut, log);
1123
+ const heldSide = heldFor({ ...deps, env: claimEnv }, { claim, run: runRow, launch, revision, claimed: gatewayKey ? withGatewayKey(claimed, gatewayKey) : claimed }, cut, log);
1095
1124
  try {
1096
1125
  let extra = {};
1097
1126
  let argv = [...(options.argv ?? childArgv())];
@@ -1105,7 +1134,8 @@ function childLoop(options, slots, loopDeps) {
1105
1134
  extra = { TMPDIR: tmp, HOME: scratch };
1106
1135
  argv = [isolation.helper, "run", String(slot), "--keep-fd", "3", "--keep-fd", "4", "--", ...argv];
1107
1136
  }
1108
- const env = childEnv(deps.env, keys, extra);
1137
+ // The saved gateway's address and models go as plain variables (childEnv), and its mark says they are the saved one.
1138
+ const env = childEnv(claimEnv, keys, savedGateway ? { ...extra, [SAVED_GATEWAY_ENV]: "1" } : extra);
1109
1139
  const [program, ...rest] = argv;
1110
1140
  child = spawn(program, rest, { stdio: ["ignore", "inherit", "inherit", "pipe", "pipe"], env, detached: true });
1111
1141
  exited = new Promise((resolve) => {
@@ -3,6 +3,7 @@ import { type RunnerStore } from "./store-port.js";
3
3
  import { type RunState } from "../store/store.js";
4
4
  import { type Redact } from "./redact.js";
5
5
  import { type LiveTickerOptions } from "./live-ticker.js";
6
+ import { type Presence } from "./presence.js";
6
7
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
7
8
  /** A final run's status as its end line says it: the store holds a cancel as state 'stopped' with outcome 'cancelled', so
8
9
  * the outcome tells a cancel from a person's resumable stop. */
@@ -42,6 +43,10 @@ export interface RunnerOptions {
42
43
  live?: false | LiveTickerOptions;
43
44
  /** This runner's name in the runs it claims (runs.runner). Default: host, pid and a random part. */
44
45
  name?: string;
46
+ /** Its word in the store that it is there (presence.ts), kept by its caller (runner/main.ts, whose relay says where it
47
+ * answers on the same row, under the same incarnation): used as is, never closed here. Default: one of its own,
48
+ * removed at its close. */
49
+ presence?: Presence;
45
50
  /** Most runs held at once. */
46
51
  loops?: number;
47
52
  /** How long a claim lasts unless renewed. */