@parcha/agentrun-serve 0.1.0-beta.42 → 0.1.0-beta.44

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 (181) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +221 -31
  3. package/dist/cli.js +42 -8
  4. package/dist/composio-preset.d.ts +4 -3
  5. package/dist/composio-preset.js +12 -4
  6. package/dist/composio-triggers.d.ts +20 -2
  7. package/dist/composio-triggers.js +183 -17
  8. package/dist/computer-lost.d.ts +11 -0
  9. package/dist/computer-lost.js +19 -0
  10. package/dist/computer-record.d.ts +10 -2
  11. package/dist/computer-record.js +50 -18
  12. package/dist/computer-setting.d.ts +1 -0
  13. package/dist/computer-setting.js +2 -2
  14. package/dist/console/assets/index-BUktRvS-.css +1 -0
  15. package/dist/console/assets/index-nB9kTfIN.js +711 -0
  16. package/dist/console/index.html +2 -2
  17. package/dist/decisions.js +0 -4
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.js +3 -0
  20. package/dist/harness-table.d.ts +51 -3
  21. package/dist/harness-table.js +101 -13
  22. package/dist/harness.d.ts +18 -1
  23. package/dist/harness.js +21 -9
  24. package/dist/host.d.ts +12 -10
  25. package/dist/host.js +18 -16
  26. package/dist/import-sources.js +25 -5
  27. package/dist/import-worker.d.ts +3 -0
  28. package/dist/import-worker.js +7 -5
  29. package/dist/import.d.ts +22 -1
  30. package/dist/import.js +141 -28
  31. package/dist/learn/audit.d.ts +123 -0
  32. package/dist/learn/audit.js +159 -0
  33. package/dist/learn/check.d.ts +3 -0
  34. package/dist/learn/check.js +1 -1
  35. package/dist/learn/compile.d.ts +50 -74
  36. package/dist/learn/compile.js +90 -124
  37. package/dist/learn/delete.d.ts +17 -0
  38. package/dist/learn/delete.js +44 -0
  39. package/dist/learn/folder.d.ts +9 -0
  40. package/dist/learn/folder.js +13 -2
  41. package/dist/learn/promote.d.ts +92 -200
  42. package/dist/learn/promote.js +65 -187
  43. package/dist/learn/replay-calls.d.ts +5 -0
  44. package/dist/learn/replay-calls.js +12 -1
  45. package/dist/learn/secrets.d.ts +8 -0
  46. package/dist/learn/secrets.js +12 -0
  47. package/dist/learn/skills.d.ts +4 -0
  48. package/dist/learn/skills.js +19 -5
  49. package/dist/learn/workflow-nodes.d.ts +23 -3
  50. package/dist/learn/workflow-nodes.js +30 -12
  51. package/dist/learned-nodes.d.ts +9 -34
  52. package/dist/learned-nodes.js +11 -23
  53. package/dist/learned-workflow.d.ts +6 -8
  54. package/dist/learned-workflow.js +18 -57
  55. package/dist/learning-batch.d.ts +13 -5
  56. package/dist/learning-batch.js +34 -8
  57. package/dist/learning-cost.d.ts +111 -4
  58. package/dist/learning-cost.js +120 -3
  59. package/dist/learning-evals.d.ts +2 -0
  60. package/dist/learning-evals.js +4 -3
  61. package/dist/learning-routes.d.ts +8 -0
  62. package/dist/learning-routes.js +18 -1
  63. package/dist/learning-setting.d.ts +16 -1
  64. package/dist/learning-setting.js +34 -2
  65. package/dist/learning.d.ts +1 -1
  66. package/dist/listen-first.d.ts +30 -0
  67. package/dist/listen-first.js +115 -0
  68. package/dist/llms.txt +2 -1
  69. package/dist/mcp-servers-store.d.ts +12 -12
  70. package/dist/model.d.ts +8 -4
  71. package/dist/model.js +16 -8
  72. package/dist/openapi.js +203 -87
  73. package/dist/owner.d.ts +8 -0
  74. package/dist/owner.js +11 -0
  75. package/dist/paid-calls.d.ts +6 -0
  76. package/dist/paid-calls.js +11 -1
  77. package/dist/place.d.ts +8 -3
  78. package/dist/place.js +13 -9
  79. package/dist/provider.js +15 -1
  80. package/dist/run-launch.d.ts +6 -3
  81. package/dist/run-launch.js +2 -0
  82. package/dist/run-learning-served.d.ts +1 -1
  83. package/dist/run-model-key.d.ts +64 -0
  84. package/dist/run-model-key.js +147 -0
  85. package/dist/runner/adapter-loop.d.ts +10 -0
  86. package/dist/runner/adapter-loop.js +26 -4
  87. package/dist/runner/adapter-run-spec.d.ts +6 -3
  88. package/dist/runner/adapter-run-spec.js +83 -25
  89. package/dist/runner/adapters/index.d.ts +4 -2
  90. package/dist/runner/adapters/index.js +13 -4
  91. package/dist/runner/audit.d.ts +68 -0
  92. package/dist/runner/audit.js +349 -0
  93. package/dist/runner/beside.d.ts +2 -1
  94. package/dist/runner/beside.js +6 -3
  95. package/dist/runner/claim-secrets.d.ts +49 -0
  96. package/dist/runner/claim-secrets.js +110 -1
  97. package/dist/runner/cli-run-spec.d.ts +2 -1
  98. package/dist/runner/cli-run-spec.js +44 -15
  99. package/dist/runner/commands.d.ts +3 -6
  100. package/dist/runner/feedback-round.d.ts +3 -2
  101. package/dist/runner/feedback-round.js +8 -7
  102. package/dist/runner/harness-loops.js +31 -23
  103. package/dist/runner/journal-kinds.d.ts +5 -7
  104. package/dist/runner/journal-kinds.js +0 -7
  105. package/dist/runner/learning-dispatch.d.ts +0 -16
  106. package/dist/runner/learning-dispatch.js +4 -47
  107. package/dist/runner/learning-end.d.ts +55 -13
  108. package/dist/runner/learning-end.js +128 -44
  109. package/dist/runner/learning-factory.d.ts +1 -1
  110. package/dist/runner/learning-factory.js +1 -4
  111. package/dist/runner/learning-loop.d.ts +2 -38
  112. package/dist/runner/learning-loop.js +8 -116
  113. package/dist/runner/loop-contract.d.ts +6 -0
  114. package/dist/runner/loop-contract.js +4 -0
  115. package/dist/runner/loop.js +6 -2
  116. package/dist/runner/main.d.ts +1 -0
  117. package/dist/runner/main.js +25 -8
  118. package/dist/runner/memory-claim.d.ts +9 -6
  119. package/dist/runner/memory-claim.js +12 -9
  120. package/dist/runner/promotion.d.ts +55 -54
  121. package/dist/runner/promotion.js +232 -585
  122. package/dist/runner/reflect-hook.d.ts +14 -0
  123. package/dist/runner/reflect-hook.js +28 -3
  124. package/dist/runner/runner.js +57 -4
  125. package/dist/runner/store-secrets.js +9 -5
  126. package/dist/runner/workflow-first.d.ts +6 -5
  127. package/dist/runner/workflow-first.js +17 -12
  128. package/dist/runner/workflow-spec.js +10 -2
  129. package/dist/runs-over-store.d.ts +5 -4
  130. package/dist/runs-over-store.js +13 -3
  131. package/dist/sdk/workflows.d.ts +1 -1
  132. package/dist/server.d.ts +64 -50
  133. package/dist/server.js +516 -134
  134. package/dist/store/index.d.ts +2 -2
  135. package/dist/store/index.js +1 -1
  136. package/dist/store/seal.d.ts +20 -2
  137. package/dist/store/seal.js +24 -8
  138. package/dist/store/sqlite/run-launch.d.ts +4 -1
  139. package/dist/store/sqlite/run-launch.js +12 -0
  140. package/dist/store/sqlite/store.d.ts +3 -2
  141. package/dist/store/sqlite/store.js +119 -16
  142. package/dist/store/store.d.ts +41 -3
  143. package/dist/store-reads/analytics.js +11 -1
  144. package/dist/store-reads/learning.d.ts +57 -7
  145. package/dist/store-reads/learning.js +194 -28
  146. package/dist/store-reads/loop.d.ts +4 -39
  147. package/dist/store-reads/loop.js +10 -79
  148. package/dist/store-reads/stats.js +13 -3
  149. package/dist/store-view.d.ts +5 -1
  150. package/dist/store-view.js +12 -1
  151. package/dist/telemetry.d.ts +59 -0
  152. package/dist/telemetry.js +153 -0
  153. package/dist/tool-keys-store.d.ts +1 -1
  154. package/dist/tool-keys.d.ts +2 -2
  155. package/dist/tool-plane.d.ts +12 -12
  156. package/dist/tools.d.ts +11 -11
  157. package/dist/tools.js +18 -5
  158. package/dist/trigger-adapter.d.ts +3 -0
  159. package/dist/trigger-adapters.d.ts +4 -0
  160. package/dist/trigger-adapters.js +13 -0
  161. package/dist/trigger-composio.d.ts +58 -1
  162. package/dist/trigger-composio.js +160 -6
  163. package/dist/triggers.d.ts +4 -0
  164. package/dist/triggers.js +22 -3
  165. package/dist/validate.d.ts +11 -7
  166. package/dist/validate.js +8 -7
  167. package/dist/workspace/computer-for-claim.d.ts +15 -5
  168. package/dist/workspace/computer-for-claim.js +228 -32
  169. package/dist/workspace/resolve-computer.d.ts +8 -2
  170. package/dist/workspace/resolve-computer.js +1 -1
  171. package/dist/workspace/run-tools.d.ts +1 -1
  172. package/dist/workspace/run-tools.js +14 -3
  173. package/package.json +10 -9
  174. package/dist/console/assets/index-C3gNPz58.css +0 -1
  175. package/dist/console/assets/index-DYJ_wj27.js +0 -711
  176. package/dist/learn/general.d.ts +0 -69
  177. package/dist/learn/general.js +0 -75
  178. package/dist/learn/refit.d.ts +0 -48
  179. package/dist/learn/refit.js +0 -264
  180. package/dist/runner/step-guard.d.ts +0 -62
  181. package/dist/runner/step-guard.js +0 -93
@@ -0,0 +1,349 @@
1
+ // The shadow audit of a serving learned workflow, at a run's claim and its end (learn/audit.ts keeps the ledger).
2
+ // startAudit (withAudit: at the served run's end, before the end commits): a run the promoted workflow answered (path
3
+ // `workflow`; a run it handed back is never drawn and never counts as served) is drawn at 1 in k (auditDrawn, from its id), and a drawn one appends a `started` line to audits.jsonl (with the
4
+ // promotion serving it and the answer it audits, `turn`: the id of the run's newest answer row now), then starts its
5
+ // shadow run: the same agent and revision on the same input with learning off (no seed, no look-back), marked as the
6
+ // audit of the served run (launch.audit), no row of the run list, billed to the agent as learning cost. Its cap is
7
+ // what the served run's cap left (the two together never pass it; the served run's later gates count it beside them,
8
+ // learning-end.ts besideOf); none left, no shadow (`skipped: "no allowance"`). A shadow never waits on a person: where
9
+ // it would park (an approval its owner's setting asks, a raise of that cap, a question) it ends at once in
10
+ // AUDIT_PARKED's words (AdapterRunSpec.neverWaits, the gate untouched: nothing is let through, no one is asked to
11
+ // answer), and its row is `parked`. Only a run started over the API (no trigger: its context is never rebuilt for a
12
+ // shadow) of an agent every tool of which only reads (learn/audit.ts auditWriterOf, the replay's readOnlyHint rule): a
13
+ // shadow never writes again.
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; a follow-up's answer
16
+ // since is never read), oldest served run first; then, rows added or not, the hold rule reads the serving revisions'
17
+ // rows: a hold is a function of the ledger alone.
18
+ // applyHold: at least hold_disagree disagreements in the newest hold_window rows of the digest's current promotion
19
+ // hold the workflow (a promotion hold carrying `audit`, with those rows, each text cut of the host's secrets before
20
+ // it is shortened, learn/secrets.ts excerptShown): the agent's next run asks one recompile with them as data
21
+ // (runner/learning-end.ts compileAskOf), which S3a's check decides on its inputs plus the disagreeing ones. A second
22
+ // hold within stop_window served runs of the first stops it: no compile, the stop said on the record.
23
+ // gradeRow: an owner's grade on a run the workflow answered alone is a row too (source grade, agreed = the grade).
24
+ // Every number is the agent definition's (learning-setting.ts auditLoopOf). Nothing here fails a claim: a failure is logged.
25
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
26
+ import { overCapMessage } from "@parcha/agentrun-kernel/kernel/cap";
27
+ import { auditLoopOf } from "../learning-setting.js";
28
+ import { RUN_CAP_MIN_USD } from "../learning-batch.js";
29
+ import { launchBody, readLaunchBody } from "../run-launch.js";
30
+ import { runEntries } from "../store-reads/journal.js";
31
+ import { runPathOverStore } from "../store-reads/learning.js";
32
+ import { FINAL_STATES, StoreConstraint } from "../store/store.js";
33
+ import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
34
+ import { isObject } from "../validate.js";
35
+ import { auditableLaunch, auditChange, auditEveryOf, auditDrawn, auditsOffWords, auditWriterOf, holdOf, ledgerOf, lineKey, openAudits, rowsOf, shadowRunId } from "../learn/audit.js";
36
+ import { lastRunsOf } from "../learn/compile.js";
37
+ import { readLearning, writeLearning } from "../learn/folder.js";
38
+ import { CHECK_TEXT_MAX, promotionOf, promotionsOf, promotionStartOf, recordPromotion, sameAnswer, servingOf } from "../learn/promote.js";
39
+ import { excerptShown } from "../learn/secrets.js";
40
+ import { auditRoomOf } from "./learning-end.js";
41
+ import { answerOf, answerRowOf } from "./promotion.js";
42
+ import { servedOf } from "./workflow-first.js";
43
+ /** The words a second hold within stop_window leaves on its record: what the owner reads. */
44
+ export const STOPPED_TWICE = "stopped: the workflow disagreed with the agent twice";
45
+ const iso = (ms) => new Date(ms).toISOString();
46
+ const ended = (row) => row !== undefined && FINAL_STATES.includes(row.state) && row.runner === null;
47
+ const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input) ?? "");
48
+ const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
49
+ /** A run the audit counts as served: one its learned workflow answered (path `workflow`). One it handed back (path
50
+ * `handed_back`) is the agent's answer: never drawn, never counted. */
51
+ const served = (row) => metricsOf(row).path === "workflow";
52
+ /** A line's `turn` (AuditRow.turn): the answer row's id, none when the run had no answer. */
53
+ const turnOf = (id) => (id === undefined ? {} : { turn: id });
54
+ /** The answer an audit row is of: its `turn`'s, read from the run by that row's id; none when it names none. */
55
+ const auditedAnswer = (deps, row) => (row.turn === undefined ? Promise.resolve(null) : answerOf(deps.store, row.run, deps.context, row.turn));
56
+ /** The audit numbers of revision `revisionId`'s definition (each one it leaves out at its default). */
57
+ export async function auditLoopOfRevision(store, revisionId) {
58
+ try {
59
+ return auditLoopOf((await store.agents.revision(revisionId))?.body?.learning);
60
+ }
61
+ catch {
62
+ return auditLoopOf(undefined);
63
+ }
64
+ }
65
+ /** The served runs of `workflow` (at `digest` when given) that `keep` keeps too, the newest `n` of them (lastRunsOf: the
66
+ * shadows and the agent's own runs among them never push one out of the read). */
67
+ 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));
68
+ /** How many of the newest stop_window runs `workflow` at `digest` served were not auditable (auditableLaunch: a trigger
69
+ * started them): what the promotions read counts beside the audit line. */
70
+ export async function notAuditableOf(store, agentId, workflow, digest, loop) {
71
+ return (await servedRuns(store, agentId, loop.stop_window, workflow, digest)).filter((row) => metricsOf(row).not_auditable === true).length;
72
+ }
73
+ /** The words a shadow run ends failed with where it would wait on a person (AdapterRunSpec.neverWaits: an approval, a
74
+ * raise of its cap, which is what its served run's cap left, a question), what it would wait on after them: its row is
75
+ * `parked`, with no verdict. */
76
+ export const AUDIT_PARKED = "the audit ended where it would wait on a person";
77
+ /** The served run's end-of-run step `step` (none for a run that only uses what its agent learned), its audit started
78
+ * after it (startAudit) on an end the run reached on its own (a cut run starts none): the learned workflow that served
79
+ * it, read from its journal whatever claim it served on (servedOf), and, for a capped run, what its cap leaves once this
80
+ * end is counted (auditRoomOf: its job, its look-back, the grades beside it and the one this end queues). A run that
81
+ * could never be audited (no learning start, or not auditableLaunch) keeps `step` as it is. */
82
+ export function withAudit(step, deps) {
83
+ if (!deps.launch.learning || !auditableLaunch(deps.launch))
84
+ return step;
85
+ return async (input) => {
86
+ const rows = step ? await step(input) : undefined;
87
+ if (input.cut === undefined)
88
+ await auditAtEnd(deps, input.runId, rows?.also ?? []);
89
+ return rows;
90
+ };
91
+ }
92
+ /** Only a run the workflow answered is drawn: its path `workflow` by the one classifier its record keeps
93
+ * (store-reads/learning.ts runPathOverStore, with the run's `redact`), never one it handed back. */
94
+ async function auditAtEnd(deps, runId, queued) {
95
+ try {
96
+ const entries = await runEntries(deps.store, runId, BACKGROUND_CONTEXT);
97
+ const served = servedOf(entries);
98
+ if (!served?.digest)
99
+ return;
100
+ if ((await runPathOverStore(deps.store, runId, deps.launch.learning, deps.redact)).path !== "workflow")
101
+ return;
102
+ const capUsd = deps.launch.maxCostUsd;
103
+ await startAudit({ ...deps, runId, ...(capUsd !== undefined ? { room: () => auditRoomOf(deps.store, runId, capUsd, entries, queued) } : {}) }, { name: served.workflow, digest: served.digest });
104
+ }
105
+ catch (error) {
106
+ deps.log(`workflow-first: the audit of this run did not start (${error?.message ?? error})`);
107
+ }
108
+ }
109
+ /** Starts the shadow of run `runId`, at its end, when the learned workflow `serve` served it first and its id is drawn:
110
+ * never for a replay or a shadow, a run that does not learn, one not auditable (auditableLaunch: a trigger started it,
111
+ * or it was handed files), nor a run of an agent that can call a tool that writes (auditWriterOf). A capped run's shadow
112
+ * is capped at what its cap leaves (`room`, read now: the served run spent all it will under it), so the two never
113
+ * spend past the served run's cap; with less than a run's smallest cap left (or a spend not known), no shadow is started
114
+ * and its row says `skipped: "no allowance"`. Its started line is appended first: a shadow is created only once the
115
+ * ledger names it (settlement finds it there, never in a window of runs), and one whose line could not be written is
116
+ * never created. Idempotent: one line and one shadow per run. */
117
+ export async function startAudit(deps, serve) {
118
+ const { store, agentId, runId, launch, log } = deps;
119
+ if (!serve || serve.replay || launch.replay || launch.audit || !launch.learning || !auditableLaunch(launch))
120
+ return;
121
+ // A shadow is a run of its own the runner starts, on no caller's key: skipped where the served run brought its own key
122
+ // or the server holds none (claimSpendOff).
123
+ const off = deps.spendOff?.("A shadow audit");
124
+ if (off)
125
+ return void log(`workflow-first: ${off}`);
126
+ try {
127
+ // Read after the claim pinned the revision's MCP tools (mcp-claim.ts pinFirst): the pin a revision saved without one
128
+ // takes at its first run is what its tools are classed by.
129
+ const revision = await store.agents.revision(deps.revisionId);
130
+ const writer = auditWriterOf(revision);
131
+ if (writer !== undefined) {
132
+ log(`workflow-first: ${serve.name} at ${serve.digest} serves this run, never audited: ${auditsOffWords(writer)}`);
133
+ return;
134
+ }
135
+ const loop = auditLoopOf(revision?.body?.learning);
136
+ const before = (await servedRuns(store, agentId, loop.audit_later_after, serve.name, serve.digest, (row) => row.id !== runId)).length;
137
+ const k = auditEveryOf(loop, before);
138
+ if (!auditDrawn(runId, k))
139
+ return;
140
+ const id = shadowRunId(runId);
141
+ // Once per run: an end after a follow-up finds its shadow made, or its row written (skipped, or settled). A started
142
+ // line with no shadow (a crash between the two) is made now.
143
+ if (await store.runs.get(id))
144
+ return;
145
+ if ((await readLedger(deps)).some((line) => line.run === runId && line.source === "shadow"))
146
+ return;
147
+ const promoted = promotionStartOf(await promotionsOf(store.settings, agentId), serve.name, serve.digest);
148
+ // The answer audited: the run's newest answer now, at the end that drew it, kept by its row's id so a follow-up's
149
+ // answer since is never the one compared.
150
+ const turn = turnOf((await answerRowOf(store, runId, deps.context))?.id);
151
+ // What the served run's cap leaves its shadow (none for an uncapped run), to a millionth, never above it.
152
+ const room = deps.room ? await deps.room() : undefined;
153
+ const allowance = room === undefined || room === null ? room : Math.floor(room * 1e6 + 1e-6) / 1e6;
154
+ if (allowance === null || (allowance !== undefined && allowance < RUN_CAP_MIN_USD)) {
155
+ const skipped = { run: runId, shadow_run: null, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, source: "shadow", agreed: null, served_cost: null, shadow_cost: null, ...turn, skipped: "no allowance", at: iso((deps.now ?? Date.now)()) };
156
+ await addLines(deps, [skipped]);
157
+ log(`workflow-first: ${serve.name} at ${serve.digest} served this run, drawn for its audit (1 in ${k}); no shadow: ${allowance === null ? "what it spent under its cap is not known" : `its cap leaves $${allowance}, under a run's smallest cap`} (no allowance)`);
158
+ return;
159
+ }
160
+ const shadow = {
161
+ input: launch.input,
162
+ title: `Audit of ${launch.title}`.slice(0, 200),
163
+ place: launch.place,
164
+ ...(launch.repo !== undefined ? { repo: launch.repo } : {}),
165
+ ...(launch.harness !== undefined ? { harness: launch.harness } : {}),
166
+ ...(launch.model ? { model: launch.model } : {}),
167
+ ...(launch.effort !== undefined ? { effort: launch.effort } : {}),
168
+ ...(allowance !== undefined ? { maxCostUsd: allowance } : {}),
169
+ ...(launch.plane ? { plane: launch.plane } : {}),
170
+ ...(launch.approvers !== undefined ? { approvers: launch.approvers } : {}),
171
+ ...(launch.documents !== undefined ? { documents: launch.documents } : {}),
172
+ ...(launch.boxAllow !== undefined ? { boxAllow: launch.boxAllow } : {}),
173
+ ...(launch.boxAllowSet ? { boxAllowSet: true } : {}),
174
+ ...(launch.archilDisk ? { archilDisk: launch.archilDisk } : {}),
175
+ audit: { of: runId, workflow: serve.name, digest: serve.digest },
176
+ };
177
+ const started = { source: "started", run: runId, shadow_run: id, workflow: serve.name, digest: serve.digest, promoted_at: promoted?.at ?? null, ...turn, at: iso((deps.now ?? Date.now)()) };
178
+ await addLines(deps, [started]);
179
+ const sealed = await handedTo(deps, runId, id);
180
+ try {
181
+ await store.runs.create({ id, agentId, revisionId: deps.revisionId }, { body: launchBody(shadow), ...(sealed ? { sealed } : {}) });
182
+ }
183
+ catch (error) {
184
+ if (error instanceof StoreConstraint && (await store.runs.get(id)))
185
+ return;
186
+ throw error;
187
+ }
188
+ log(`workflow-first: ${serve.name} at ${serve.digest} serves this run; drawn for its audit (1 in ${k}): its shadow run ${id} runs the agent on the same input`);
189
+ }
190
+ catch (error) {
191
+ log(`workflow-first: the audit of this run did not start (${error?.message ?? error})`);
192
+ }
193
+ }
194
+ /** The per_run MCP credentials run `from` was handed, sealed for shadow run `id` alone (as a replay run's are). */
195
+ async function handedTo(deps, from, id) {
196
+ if (!deps.sealKey)
197
+ return undefined;
198
+ const sealed = await deps.store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
199
+ const handed = sealed === null ? undefined : openRunMcpAuth(deps.sealKey, from, sealed);
200
+ return handed && Object.keys(handed).length ? sealRunMcpAuth(deps.sealKey, id, handed) : undefined;
201
+ }
202
+ /** Writes the row of each open audit (a started line with no row yet) whose two runs, read by id, ended, the batch
203
+ * oldest served run first (the ledger's tail is its newest); a run that is gone (its shadow never created, say) ends it
204
+ * with no verdict. Then applies the hold rule over the ledger as it is now, rows added or not: the hold is a function of
205
+ * the ledger, so one a crash or a failed write lost after the rows were committed is made at the next claim. */
206
+ export async function settleAudits(deps) {
207
+ const { store, log } = deps;
208
+ try {
209
+ // An agent with no promotion record never served a learned workflow: it has no ledger to read.
210
+ if (!(await promotionsOf(store.settings, deps.agentId)).length)
211
+ return;
212
+ const lines = await readLedger(deps);
213
+ const now = (deps.now ?? Date.now)();
214
+ const rows = [];
215
+ for (const open of openAudits(lines)) {
216
+ const [servedRow, shadow] = [await store.runs.get(open.run), await store.runs.get(open.shadow_run)];
217
+ // Its shadow is created after its line, at the served run's claim: one missing once the served run ended never ran.
218
+ if ((servedRow && !ended(servedRow)) || (shadow && !ended(shadow)))
219
+ continue;
220
+ // One that ended where it would wait on a person (AUDIT_PARKED: an approval, a raise of its cap, a question), or
221
+ // once its cost passed its cap (the kernel's overCapEnd: it would wait on a raise), has no answer: `parked`.
222
+ const parked = shadow?.state === "failed" && ((shadow.summary ?? "").startsWith(AUDIT_PARKED) || overCapMessage(shadow.summary) !== undefined);
223
+ rows.push({ at: servedRow?.startedAt ?? 0, row: { run: open.run, shadow_run: open.shadow_run, workflow: open.workflow, digest: open.digest, promoted_at: open.promoted_at, source: "shadow", agreed: null, served_cost: servedRow?.costUsd ?? null, shadow_cost: shadow?.costUsd ?? null, ...turnOf(open.turn), ...(parked ? { parked: true } : {}), at: iso(now) } });
224
+ }
225
+ rows.sort((a, b) => a.at - b.at || (a.row.run < b.row.run ? -1 : a.row.run > b.row.run ? 1 : 0));
226
+ const { all, added } = rows.length ? await addLines(deps, rows.map(({ row }) => row), async (row) => {
227
+ const shadow = await store.runs.get(row.shadow_run);
228
+ if (shadow?.state !== "ended" || !(await store.runs.get(row.run)))
229
+ return null;
230
+ // The audited answer (the row's turn), never the run's newest: a follow-up since may have answered again.
231
+ const [a, b] = [await auditedAnswer(deps, row), await answerOf(store, row.shadow_run, deps.context)];
232
+ return a === null || b === null ? null : sameAnswer(a, b);
233
+ }) : { all: lines, added: [] };
234
+ const written = rowsOf(added);
235
+ if (written.length)
236
+ log(`workflow-first: ${written.length} audit row${written.length === 1 ? "" : "s"} written (${written.filter((row) => row.agreed === false).length} disagreeing)`);
237
+ await holdByLedger(deps, rowsOf(all));
238
+ }
239
+ catch (error) {
240
+ log(`workflow-first: the audits were not settled (${error?.message ?? error}); a later claim settles them`);
241
+ }
242
+ }
243
+ /** The row an owner's grade of served run `run` writes (source grade, agreed = the grade, counted for the digest's
244
+ * promotion now), then the hold rule: only for a run the workflow answered alone (its answer is the workflow's).
245
+ * Nothing else: no round, no compile by itself. */
246
+ export async function gradeRow(deps, run, correct) {
247
+ const m = metricsOf(run);
248
+ if (m.path !== "workflow" || typeof m.workflow !== "string" || typeof m.workflow_digest !== "string")
249
+ return;
250
+ const promoted = promotionStartOf(await promotionsOf(deps.store.settings, deps.agentId), m.workflow, m.workflow_digest);
251
+ // The answer graded: the run's newest now, kept by its row's id (as a shadow's audit keeps its turn).
252
+ const turn = turnOf((await answerRowOf(deps.store, run.id, deps.context))?.id);
253
+ const row = { run: run.id, shadow_run: null, workflow: m.workflow, digest: m.workflow_digest, promoted_at: promoted?.at ?? null, source: "grade", agreed: correct, served_cost: run.costUsd, shadow_cost: null, ...turn, at: iso((deps.now ?? Date.now)()) };
254
+ const { all } = await addLines(deps, [row], async () => correct, true);
255
+ await holdByLedger(deps, rowsOf(all));
256
+ }
257
+ /** The ledger's lines on the agent's learning folder's main. */
258
+ async function readLedger(deps) {
259
+ const folder = deps.folder();
260
+ try {
261
+ return await readLearning(folder.workspace, ledgerOf);
262
+ }
263
+ finally {
264
+ await folder.end().catch(() => undefined);
265
+ }
266
+ }
267
+ /** Appends `lines` (each not in the ledger yet, lineKey; a row's verdict read by `agreed` once it is known to be new) in
268
+ * their order, and answers the ledger after (`all`) with the lines it appended. A grade's row (`again`) replaces an
269
+ * earlier grade of the same run. */
270
+ async function addLines(deps, lines, agreed, again = false) {
271
+ const folder = deps.folder();
272
+ try {
273
+ const verdicts = new Map();
274
+ const done = await writeLearning(folder.workspace, async (read) => {
275
+ const before = (await ledgerOf(read)).filter((one) => !again || !lines.some((line) => lineKey(line) === lineKey(one)));
276
+ const known = new Set(before.map(lineKey));
277
+ const fresh = [];
278
+ for (const line of lines) {
279
+ const key = lineKey(line);
280
+ if (known.has(key))
281
+ continue;
282
+ if (line.source === "started" || !agreed) {
283
+ fresh.push(line);
284
+ continue;
285
+ }
286
+ if (!verdicts.has(key))
287
+ verdicts.set(key, await agreed(line));
288
+ fresh.push({ ...line, agreed: verdicts.get(key) });
289
+ }
290
+ const change = auditChange(before, fresh);
291
+ return { result: { all: [...before, ...change.added], added: change.added }, ...(change.change ? { change: change.change } : {}) };
292
+ });
293
+ return done.result;
294
+ }
295
+ finally {
296
+ await folder.end().catch(() => undefined);
297
+ }
298
+ }
299
+ /** The hold rule over the ledger's rows `all` for each workflow that serves now (its champion's digest), whether or not
300
+ * a row was just added: idempotent (applyHold holds only a digest whose newest record still promotes it). */
301
+ async function holdByLedger(deps, all) {
302
+ if (!all.length)
303
+ return;
304
+ const loop = await auditLoopOfRevision(deps.store, deps.revisionId);
305
+ for (const { workflow, digest } of servingOf(await promotionsOf(deps.store.settings, deps.agentId))) {
306
+ if (digest !== null)
307
+ await applyHold(deps, all, loop, workflow, digest);
308
+ }
309
+ }
310
+ /** The hold rule on `workflow` at `digest` over the ledger `rows`, when it serves now (its newest record promotes it),
311
+ * on the rows of its current promotion alone (promotionStartOf: a digest its owner's replay promoted again after a hold
312
+ * starts on none): a hold carrying `audit` with the disagreeing rows, or a stop when an earlier audit hold of the
313
+ * workflow is within stop_window served runs. Kept only while the record it read is still the digest's (of two claims,
314
+ * one holds). */
315
+ async function applyHold(deps, rows, loop, workflow, digest) {
316
+ const { store, agentId, log } = deps;
317
+ const records = await promotionsOf(store.settings, agentId);
318
+ const current = promotionOf(records, workflow, digest);
319
+ if (current?.decided !== "promote")
320
+ return;
321
+ const hold = holdOf(rows, workflow, digest, promotionStartOf(records, workflow, digest)?.at ?? null, loop);
322
+ if (!hold)
323
+ return;
324
+ const first = records.findLast((one) => one.workflow === workflow && one.decided === "hold" && one.audit !== undefined);
325
+ const since = first ? Date.parse(first.at) : undefined;
326
+ const servedSince = since === undefined ? 0 : (await servedRuns(store, agentId, loop.stop_window, workflow, undefined, (row) => row.startedAt >= since)).length;
327
+ const stopped = first !== undefined && servedSince < loop.stop_window;
328
+ // Each text cut of the host's secrets whole, then shortened (learn/secrets.ts excerptShown), as a check's are.
329
+ const shown = await deps.shown();
330
+ const cut = (text) => excerptShown(text, shown, CHECK_TEXT_MAX);
331
+ const disagreements = [];
332
+ for (const row of hold.disagreed) {
333
+ const input = await store.runs.launch(row.run).then((one) => inputText(readLaunchBody(one.body)?.input ?? null), () => "");
334
+ // The answer the row compared (its turn's), as the verdict read it: never a follow-up's since.
335
+ const draft = await auditedAnswer(deps, row);
336
+ const agent = row.shadow_run ? await answerOf(store, row.shadow_run, deps.context) : null;
337
+ disagreements.push({ run: row.shadow_run ?? row.run, served: row.run, input: cut(input), agent: agent === null ? null : cut(agent), draft: draft === null ? null : cut(draft), ...(row.source === "grade" ? { graded: true } : {}) });
338
+ }
339
+ const said = `it disagreed with the agent's own answer on ${hold.disagreed.length} of its last ${hold.rows.length} audited runs (the bar: ${loop.hold_disagree} of ${loop.hold_window})`;
340
+ const reason = stopped ? STOPPED_TWICE : `held: ${said}; the agent's next run recompiles it once with them`;
341
+ const record = {
342
+ workflow, digest, at: iso((deps.now ?? Date.now)()), decided: "hold", reason,
343
+ audit: { window: loop.hold_window, disagree: loop.hold_disagree, rows: hold.rows.length, disagreements, ...(stopped ? { stopped: true } : {}) },
344
+ ...(current.commit ? { commit: current.commit } : {}),
345
+ };
346
+ const kept = await recordPromotion(store.settings, agentId, record, (was) => was?.decided === "promote" && was.at === current.at);
347
+ if (kept.won)
348
+ log(`workflow-first: ${workflow} at ${digest} ${stopped ? `stopped (${said}, a second hold within ${loop.stop_window} served runs)` : reason}`);
349
+ }
@@ -30,7 +30,7 @@ export declare function besideStopping(server: {
30
30
  * holds each paired computer's socket in this process, so a run here takes one. `dial`: the server's (Serve.dial), which
31
31
  * a remote provider's create takes, so a machine that dials the server lands in this process's hub. Returns the runner
32
32
  * and a close() that stops both and closes its store. */
33
- export declare function runnerBeside(dataDir: string, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine }?: {
33
+ export declare function runnerBeside(dataDir: string, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine, onRunEnded }?: {
34
34
  loops?: number;
35
35
  drainMs?: number;
36
36
  env?: NodeJS.ProcessEnv;
@@ -42,6 +42,7 @@ export declare function runnerBeside(dataDir: string, { loops, drainMs, env, jan
42
42
  evalFakes?: (agentId: string) => import("./adapter-run-spec.js").EvalFakes | undefined;
43
43
  harnessInstall?: import("../harness-install.js").HarnessInstaller;
44
44
  onLine?: (line: string) => void;
45
+ onRunEnded?: (status: string) => void;
45
46
  }): Promise<{
46
47
  runner: Awaited<ReturnType<typeof import("./runner.js")["startRunner"]>>;
47
48
  close: () => Promise<void>;
@@ -31,7 +31,7 @@ export function besideStopping(server, held, drainMs) {
31
31
  * holds each paired computer's socket in this process, so a run here takes one. `dial`: the server's (Serve.dial), which
32
32
  * a remote provider's create takes, so a machine that dials the server lands in this process's hub. Returns the runner
33
33
  * and a close() that stops both and closes its store. */
34
- export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine } = {}) {
34
+ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub, dial, mcpLoopback, mcpOwn, evalFakes, harnessInstall, onLine, onRunEnded } = {}) {
35
35
  const { runnerName, startRunner } = await import("./runner.js");
36
36
  const { dispatchRunner } = await import("./harness-loops.js");
37
37
  const { routeOf } = await import("./model-route.js");
@@ -64,7 +64,7 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub,
64
64
  const computers = runnerComputers(store, runs, seal.key, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(hub ? { hub } : {}), ...(dial ? { dial } : {}) });
65
65
  // `mcpLoopback`: the server beside it is a local install (Serve.localInstall), so its runs may reach an MCP server on
66
66
  // loopback; a runner in its own process does only as its own environment says (main.ts runnerLoopback). `mcpOwn`: that server's own addresses (Serve.own), whose ports a run's
67
- // loopback read never goes to. A run's log lines (a learning run's skipped generality check) go to
67
+ // loopback read never goes to. A run's log lines (a sweep that failed) go to
68
68
  // stderr with the runner's other lines. `evalFakes`: the template eval's fakes (EvalFakes: a case's web, now, monid and
69
69
  // email), by the agent each of its runs is of; only the eval, in its own process, hands them. `harnessInstall`: what a
70
70
  // claim's first-use install installs with (the eval's sharedInstaller, which the server beside it takes too).
@@ -88,11 +88,14 @@ export async function runnerBeside(dataDir, { loops, drainMs, env, janitor, hub,
88
88
  const line = runLine(event);
89
89
  if (line)
90
90
  (onLine ?? console.log)(line);
91
+ // The server's anonymous counts (telemetry.ts) hear a run's end: its state alone, never which run or agent.
92
+ if (event.type === "ended")
93
+ onRunEnded?.(event.status);
91
94
  };
92
95
  // A run's end lets go of what its earlier claims' computers left, with the same computers (run-end-computers.ts).
93
96
  const { runEndComputers } = await import("../workspace/run-end-computers.js");
94
97
  const runEnded = runEndComputers({ store, computers: computers.computerDeps, log: (line) => console.error(`agentrun-serve runner: ${line}`) });
95
- const runner = startRunner({ store, name, createLoop, memory: runnerMemory(store), onEvent: said, runEnded, ...(loops !== undefined ? { loops } : {}), ...(drainMs !== undefined ? { drainMs } : {}) });
98
+ const runner = startRunner({ store, name, createLoop, memory: runnerMemory(store, undefined, runs), onEvent: said, runEnded, ...(loops !== undefined ? { loops } : {}), ...(drainMs !== undefined ? { drainMs } : {}) });
96
99
  // The computer janitor over the same computers, when the start asks for it: never under --faux. Its lines are the
97
100
  // runner's, on stderr (a stderr whose reader closed loses them, never the process: cli.ts).
98
101
  const { startJanitor } = await import("../workspace/computer-janitor.js");
@@ -3,6 +3,8 @@ import { type Tier } from "../model.js";
3
3
  import type { RunLaunch } from "../run-launch.js";
4
4
  import type { SealedKeys } from "../store/store.js";
5
5
  import type { Revision } from "../agent-rows.js";
6
+ import type { HeldRedact } from "./redact.js";
7
+ import { type HeldModelKey } from "../run-model-key.js";
6
8
  /** What claimSecrets reads the keys from: the one store (its sealed keys) and the runner's seal key, and the runner's base
7
9
  * environment (its own, with no server secret in it: those are the store's). */
8
10
  export interface ClaimSecretsDeps {
@@ -49,3 +51,50 @@ export declare function withModelKeys(env: NodeJS.ProcessEnv, opened: NodeJS.Pro
49
51
  /** Every model key the server holds, for a model route with no revision to scope it by (a learning run's grade): each
50
52
  * by its name from `deps.env` first, then the store's sealed value, as claimSecrets reads them. */
51
53
  export declare function savedModelKeys(deps: ClaimSecretsDeps): Promise<NodeJS.ProcessEnv>;
54
+ /** A run's own model key, held by its claim (run-model-key.ts): `fresh()` opens it from the run's launch again (a message's
55
+ * new key replaces it, or a run that started on the server's key takes its first); `everHeld()`, whether the claim ever
56
+ * held one, so spend after the turn never falls to the server's key for a run that brought its own. */
57
+ export interface ClaimModelKey extends HeldModelKey {
58
+ fresh(): Promise<void>;
59
+ everHeld(): boolean;
60
+ /** Calls `listener` with the key now and with each new one fresh() opens: the run's redactors hold every key it held. */
61
+ watch(listener: (key: string) => void): void;
62
+ }
63
+ /**
64
+ * The run's own model key for claim `runId`, opened from its launch's sealed column under the runner's seal key (the
65
+ * server sealed it there with mcp_auth, store/seal.ts). Undefined only where the server has no gateway and the run holds
66
+ * no key: a claim on a gateway server holds one even before the run's first key, so a message that hands it one reaches
67
+ * the next request (fresh()). Read at every claim, a reclaim after a runner's crash among them, so a run's key outlives no
68
+ * process but its own launch row. Throws, in words, when its launch does not open, or when the key was handed for another
69
+ * gateway than AGENT_MODEL_BASE_URL's now: it is never sent where it was not handed for.
70
+ */
71
+ export declare function claimModelKey(deps: {
72
+ readonly store: {
73
+ readonly runs: {
74
+ launch(runId: string): Promise<{
75
+ readonly sealed: Uint8Array | null;
76
+ }>;
77
+ };
78
+ };
79
+ readonly sealKey: Buffer | undefined;
80
+ readonly env?: NodeJS.ProcessEnv;
81
+ }, runId: string): Promise<ClaimModelKey | undefined>;
82
+ /** The run's own model key held by `redact` (one of the run's redactors), the key now and each one a message hands it. */
83
+ export declare function holdRunKey(redact: HeldRedact, runKey: ClaimModelKey): void;
84
+ /** Whether the claim opened a key of the run's own at its start: its routes then carry that key alone, its tools hold no
85
+ * model key, and no saved key is read for it. */
86
+ export declare const keyedAtClaim: (runKey: ClaimModelKey | undefined) => boolean;
87
+ /** Why the claim's model spend after the run's turn, or beside it on runs the runner starts (a shadow audit, a replay
88
+ * check, the learning run's grade), is skipped: `what` the work, asked when that spend would start. A run that brought
89
+ * its own key, at its start or with a message since (everHeld): that key is erased with its turn's end and the server's
90
+ * never pays for it (runKeyEndedFor). Else, a server that holds no gateway key (the runner's environment or
91
+ * Settings → Model keys) has none to spend (noServerKeyWords). Undefined where it runs. */
92
+ export declare function claimSpendOff(deps: ClaimSecretsDeps, runKey: ClaimModelKey | undefined): Promise<(what: string) => string | undefined>;
93
+ /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
94
+ * the runner's environment with the keys `opened` for it (withModelKeys), whose gateway variables read the run's key
95
+ * once a message hands it one (withRunModelKeyLater). */
96
+ export declare function claimModelEnv(env: NodeJS.ProcessEnv, opened: NodeJS.ProcessEnv, runKey: ClaimModelKey | undefined): NodeJS.ProcessEnv;
97
+ /** `toolEnv` with no model key in it, for a run that holds its own: a tool's environment never carries a model key the
98
+ * run's model routes do not send. The decision providers' keys stay (DECISION_KEY_NAMES): a keyed workflow's judge,
99
+ * pick, sift, route and ask nodes run on them as any run's do. */
100
+ export declare function withoutModelKeys(toolEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -6,13 +6,16 @@
6
6
  // providers they name, read once the claim's seed lay chose them (learnedDecisionKeys). So a run that names no monid never gets the monid key, and two runs on
7
7
  // one runner never see each other's keys: each claim reads its own, into its own environment. (MCP credentials are the
8
8
  // other per-claim secret; they come through mcp-claim.ts, which already opens them from the store under the claim.)
9
- import { decisionKeysFor, providersNamed } from "../decisions.js";
9
+ import { decisionKeysFor, JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV, providersNamed } from "../decisions.js";
10
10
  import { GATEWAY_KEY_ENV, hostModel, modelKeys, PROVIDER_KEYS, tierModelOf, TIERS, workflowNodes } from "../model.js";
11
11
  import { keysFor, needsOf, RUN_SECRETS } from "../run-secrets.js";
12
12
  import { DECISION_KEYS, withoutSecrets } from "../secrets.js";
13
13
  import { getSealedKey } from "../server-keys.js";
14
14
  import { PLAN_PROVIDER, planOf, planReaderOf, withPlan } from "../chatgpt-plan.js";
15
15
  import { handsParallel } from "../tool-plane.js";
16
+ import { noServerKeyWords, runKeyEndedFor, runModelOrigin, withRunModelKey, withRunModelKeyLater } from "../run-model-key.js";
17
+ import { openRunLaunch } from "../store/seal.js";
18
+ import { StoreLaunchMissing } from "../store/store.js";
16
19
  /** Every server secret a run might be handed (runs.ts RUN_SECRETS is the tool and model keys; the decision keys go beside
17
20
  * them). Read from the store into a working environment, then scoped to the run below. */
18
21
  const CANDIDATES = [...new Set([...RUN_SECRETS, ...DECISION_KEYS])];
@@ -165,3 +168,109 @@ export async function savedModelKeys(deps) {
165
168
  }
166
169
  return out;
167
170
  }
171
+ /** How many times fresh() reads a run's launch before it gives up, and the first wait between reads (doubled each time). */
172
+ const FRESH_TRIES = 3;
173
+ const FRESH_WAIT_MS = 50;
174
+ /**
175
+ * The run's own model key for claim `runId`, opened from its launch's sealed column under the runner's seal key (the
176
+ * server sealed it there with mcp_auth, store/seal.ts). Undefined only where the server has no gateway and the run holds
177
+ * no key: a claim on a gateway server holds one even before the run's first key, so a message that hands it one reaches
178
+ * the next request (fresh()). Read at every claim, a reclaim after a runner's crash among them, so a run's key outlives no
179
+ * process but its own launch row. Throws, in words, when its launch does not open, or when the key was handed for another
180
+ * gateway than AGENT_MODEL_BASE_URL's now: it is never sent where it was not handed for.
181
+ */
182
+ export async function claimModelKey(deps, runId) {
183
+ const origin = runModelOrigin(deps.env ?? {});
184
+ const open = async () => {
185
+ // A run with no launch row (one no start wrote: a test's, an import's) holds no key of its own.
186
+ const sealed = await deps.store.runs.launch(runId).then((launch) => launch.sealed, (error) => {
187
+ if (error instanceof StoreLaunchMissing)
188
+ return null;
189
+ throw error;
190
+ });
191
+ if (sealed === null)
192
+ return undefined;
193
+ const opened = deps.sealKey ? openRunLaunch(deps.sealKey, runId, sealed) : undefined;
194
+ if (!opened)
195
+ throw new Error("This run's launch secrets do not open with this runner's seal key: its model key is not sent.");
196
+ return opened.model;
197
+ };
198
+ let held = await open();
199
+ if (held && held.origin !== origin)
200
+ throw new Error(`This run's model key was handed for the gateway at ${held.origin}, and AGENT_MODEL_BASE_URL names ${origin ?? "none"} here now: the key is never sent anywhere else.`);
201
+ if (!origin)
202
+ return undefined;
203
+ let ever = held !== undefined;
204
+ const listeners = [];
205
+ return {
206
+ origin,
207
+ key: () => held?.key,
208
+ everHeld: () => ever,
209
+ // A message that hands no key keeps the run's (the server's write keeps it), so none here is a run whose launch holds
210
+ // none (yet, or no longer). A key for another origin is never taken. Fail-closed: a launch that cannot be read is read
211
+ // again, FRESH_TRIES in all with a growing wait, and then fresh() throws, so the command that asked is not handed to
212
+ // the session (the runner leaves its row untaken and delivers it again at its next poll). A message's key is never
213
+ // replaced by the key the claim held before it, nor by the server's.
214
+ fresh: async () => {
215
+ let now;
216
+ for (let attempt = 1;; attempt++) {
217
+ try {
218
+ now = await open();
219
+ break;
220
+ }
221
+ catch (error) {
222
+ if (attempt >= FRESH_TRIES)
223
+ throw new Error(`the run's model key could not be read from its launch (${FRESH_TRIES} tries): the message is held until it can be, never sent on another key: ${error?.message ?? error}`);
224
+ await new Promise((resolve) => setTimeout(resolve, FRESH_WAIT_MS * 2 ** (attempt - 1)));
225
+ }
226
+ }
227
+ held = now && now.origin === origin ? now : undefined;
228
+ if (held) {
229
+ ever = true;
230
+ for (const listener of listeners)
231
+ listener(held.key);
232
+ }
233
+ },
234
+ watch: (listener) => {
235
+ listeners.push(listener);
236
+ if (held)
237
+ listener(held.key);
238
+ },
239
+ };
240
+ }
241
+ /** The run's own model key held by `redact` (one of the run's redactors), the key now and each one a message hands it. */
242
+ export function holdRunKey(redact, runKey) {
243
+ runKey.watch((key) => redact.hold([key]));
244
+ }
245
+ /** Whether the claim opened a key of the run's own at its start: its routes then carry that key alone, its tools hold no
246
+ * model key, and no saved key is read for it. */
247
+ export const keyedAtClaim = (runKey) => runKey?.key() !== undefined;
248
+ /** Why the claim's model spend after the run's turn, or beside it on runs the runner starts (a shadow audit, a replay
249
+ * check, the learning run's grade), is skipped: `what` the work, asked when that spend would start. A run that brought
250
+ * its own key, at its start or with a message since (everHeld): that key is erased with its turn's end and the server's
251
+ * never pays for it (runKeyEndedFor). Else, a server that holds no gateway key (the runner's environment or
252
+ * Settings → Model keys) has none to spend (noServerKeyWords). Undefined where it runs. */
253
+ export async function claimSpendOff(deps, runKey) {
254
+ const keyless = runModelOrigin(deps.env ?? {}) !== undefined && !(await savedModelKeys(deps))[GATEWAY_KEY_ENV];
255
+ return (what) => (runKey?.everHeld() ? runKeyEndedFor(what) : keyless ? noServerKeyWords(what) : undefined);
256
+ }
257
+ /** The env a claimed run's model routes read: the run's own key alone where the claim opened one (withRunModelKey); else
258
+ * the runner's environment with the keys `opened` for it (withModelKeys), whose gateway variables read the run's key
259
+ * once a message hands it one (withRunModelKeyLater). */
260
+ export function claimModelEnv(env, opened, runKey) {
261
+ if (!runKey)
262
+ return withModelKeys(env, opened);
263
+ return keyedAtClaim(runKey) ? withRunModelKey(env, runKey) : withRunModelKeyLater(withModelKeys(env, opened), runKey);
264
+ }
265
+ /** The decision providers' own keys (decisions.ts: Jev's TypeSafe key, OpenRouter's, Parallel's): some are also pi-ai
266
+ * provider names, but a run's model key never replaces them, so withoutModelKeys keeps them. */
267
+ const DECISION_KEY_NAMES = new Set([JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV]);
268
+ /** `toolEnv` with no model key in it, for a run that holds its own: a tool's environment never carries a model key the
269
+ * run's model routes do not send. The decision providers' keys stay (DECISION_KEY_NAMES): a keyed workflow's judge,
270
+ * pick, sift, route and ask nodes run on them as any run's do. */
271
+ export function withoutModelKeys(toolEnv) {
272
+ for (const name of MODEL_KEY_NAMES)
273
+ if (!DECISION_KEY_NAMES.has(name))
274
+ delete toolEnv[name];
275
+ return toolEnv;
276
+ }
@@ -4,6 +4,7 @@ import { type HarnessEntry } from "../harness-table.js";
4
4
  import { type RunLaunch } from "../run-launch.js";
5
5
  import { type AdapterRun, type AdapterRunSpec } from "./adapter-loop.js";
6
6
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
7
+ import { type ClaimModelKey } from "./claim-secrets.js";
7
8
  import type { Claim } from "./loop-contract.js";
8
9
  /** The shared claim-time computer types live on the base spec (adapter-run-spec.ts), re-exported for this module's API. */
9
10
  export type { ClaimComputer, ClaimDeps, ClaimLaunch, ComputerForClaim } from "./adapter-run-spec.js";
@@ -50,7 +51,7 @@ export declare function cliCapModel(entry: HarnessEntry & {
50
51
  * run whose plane resolves it to native gets the harness's own search (#2458), this run's alone; whatever the runner's
51
52
  * own environment says of a plane is never the run's. Whether each search runs is the tool's setting at that search
52
53
  * (SessionIO.permission, the gate), never this plane, which is frozen when the run is made. */
53
- export declare function cliRunEnv(env: NodeJS.ProcessEnv | undefined, data: string, claimed?: NodeJS.ProcessEnv, plane?: RunLaunch["plane"]): NodeJS.ProcessEnv;
54
+ export declare function cliRunEnv(env: NodeJS.ProcessEnv | undefined, data: string, claimed?: NodeJS.ProcessEnv, plane?: RunLaunch["plane"], runKey?: ClaimModelKey): NodeJS.ProcessEnv;
54
55
  /** `tools` in the order the agent grants them (`granted`, catalog names; a tool is listed by its catalog name's wire
55
56
  * name), as main listed a CLI run's tools to its harness: each granted tool where its grant is, and a tool the grant
56
57
  * does not name (one a granted tool or the run's computer brings beside it) right after the tool listed before it. Ties