@parcha/agentrun-serve 0.1.0-beta.43 → 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 (141) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +213 -24
  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/errors.d.ts +1 -0
  18. package/dist/errors.js +3 -0
  19. package/dist/harness-table.d.ts +51 -3
  20. package/dist/harness-table.js +101 -13
  21. package/dist/harness.d.ts +18 -1
  22. package/dist/harness.js +21 -9
  23. package/dist/host.d.ts +12 -10
  24. package/dist/host.js +18 -16
  25. package/dist/import-worker.d.ts +3 -0
  26. package/dist/import-worker.js +7 -5
  27. package/dist/import.d.ts +22 -1
  28. package/dist/import.js +141 -28
  29. package/dist/learn/check.d.ts +3 -0
  30. package/dist/learn/check.js +1 -1
  31. package/dist/learn/compile.js +1 -1
  32. package/dist/learn/delete.d.ts +17 -0
  33. package/dist/learn/delete.js +44 -0
  34. package/dist/learn/promote.d.ts +7 -1
  35. package/dist/learn/promote.js +8 -4
  36. package/dist/learn/skills.d.ts +4 -0
  37. package/dist/learn/skills.js +17 -1
  38. package/dist/learn/workflow-nodes.d.ts +22 -1
  39. package/dist/learn/workflow-nodes.js +28 -9
  40. package/dist/learning-cost.d.ts +100 -0
  41. package/dist/learning-cost.js +116 -1
  42. package/dist/learning-evals.d.ts +2 -0
  43. package/dist/learning-evals.js +4 -3
  44. package/dist/learning-routes.d.ts +8 -0
  45. package/dist/learning-routes.js +17 -0
  46. package/dist/learning.d.ts +1 -1
  47. package/dist/listen-first.d.ts +30 -0
  48. package/dist/listen-first.js +115 -0
  49. package/dist/llms.txt +2 -1
  50. package/dist/mcp-servers-store.d.ts +12 -12
  51. package/dist/model.d.ts +8 -4
  52. package/dist/model.js +16 -8
  53. package/dist/openapi.js +115 -39
  54. package/dist/owner.d.ts +8 -0
  55. package/dist/owner.js +11 -0
  56. package/dist/paid-calls.d.ts +6 -0
  57. package/dist/paid-calls.js +11 -1
  58. package/dist/place.d.ts +8 -3
  59. package/dist/place.js +13 -9
  60. package/dist/provider.js +15 -1
  61. package/dist/run-learning-served.d.ts +1 -1
  62. package/dist/run-model-key.d.ts +64 -0
  63. package/dist/run-model-key.js +147 -0
  64. package/dist/runner/adapter-loop.d.ts +6 -0
  65. package/dist/runner/adapter-loop.js +9 -2
  66. package/dist/runner/adapter-run-spec.d.ts +6 -3
  67. package/dist/runner/adapter-run-spec.js +70 -23
  68. package/dist/runner/adapters/index.d.ts +4 -2
  69. package/dist/runner/adapters/index.js +13 -4
  70. package/dist/runner/audit.d.ts +4 -0
  71. package/dist/runner/audit.js +15 -4
  72. package/dist/runner/beside.d.ts +2 -1
  73. package/dist/runner/beside.js +5 -2
  74. package/dist/runner/claim-secrets.d.ts +49 -0
  75. package/dist/runner/claim-secrets.js +110 -1
  76. package/dist/runner/cli-run-spec.d.ts +2 -1
  77. package/dist/runner/cli-run-spec.js +32 -13
  78. package/dist/runner/commands.d.ts +3 -6
  79. package/dist/runner/feedback-round.d.ts +3 -2
  80. package/dist/runner/feedback-round.js +7 -3
  81. package/dist/runner/harness-loops.js +30 -8
  82. package/dist/runner/journal-kinds.d.ts +5 -0
  83. package/dist/runner/learning-end.d.ts +3 -0
  84. package/dist/runner/learning-end.js +4 -0
  85. package/dist/runner/loop-contract.d.ts +6 -0
  86. package/dist/runner/loop-contract.js +4 -0
  87. package/dist/runner/loop.js +6 -2
  88. package/dist/runner/main.d.ts +1 -0
  89. package/dist/runner/main.js +24 -7
  90. package/dist/runner/memory-claim.d.ts +9 -6
  91. package/dist/runner/memory-claim.js +12 -9
  92. package/dist/runner/promotion.d.ts +5 -0
  93. package/dist/runner/promotion.js +46 -7
  94. package/dist/runner/reflect-hook.d.ts +4 -0
  95. package/dist/runner/reflect-hook.js +22 -3
  96. package/dist/runner/runner.js +57 -4
  97. package/dist/runner/store-secrets.js +9 -5
  98. package/dist/runner/workflow-spec.js +10 -2
  99. package/dist/runs-over-store.d.ts +5 -4
  100. package/dist/runs-over-store.js +13 -3
  101. package/dist/sdk/workflows.d.ts +1 -1
  102. package/dist/server.d.ts +64 -50
  103. package/dist/server.js +457 -120
  104. package/dist/store/index.d.ts +2 -2
  105. package/dist/store/index.js +1 -1
  106. package/dist/store/seal.d.ts +20 -2
  107. package/dist/store/seal.js +24 -8
  108. package/dist/store/sqlite/run-launch.d.ts +4 -1
  109. package/dist/store/sqlite/run-launch.js +12 -0
  110. package/dist/store/sqlite/store.d.ts +3 -2
  111. package/dist/store/sqlite/store.js +118 -16
  112. package/dist/store/store.d.ts +38 -3
  113. package/dist/store-reads/analytics.js +11 -1
  114. package/dist/store-reads/learning.d.ts +41 -2
  115. package/dist/store-reads/learning.js +158 -5
  116. package/dist/store-reads/stats.js +13 -3
  117. package/dist/store-view.d.ts +5 -1
  118. package/dist/store-view.js +12 -11
  119. package/dist/telemetry.d.ts +59 -0
  120. package/dist/telemetry.js +153 -0
  121. package/dist/tool-keys-store.d.ts +1 -1
  122. package/dist/tool-keys.d.ts +2 -2
  123. package/dist/tool-plane.d.ts +12 -12
  124. package/dist/tools.d.ts +11 -11
  125. package/dist/tools.js +18 -5
  126. package/dist/trigger-adapter.d.ts +3 -0
  127. package/dist/trigger-adapters.d.ts +4 -0
  128. package/dist/trigger-adapters.js +13 -0
  129. package/dist/trigger-composio.d.ts +58 -1
  130. package/dist/trigger-composio.js +160 -6
  131. package/dist/triggers.d.ts +4 -0
  132. package/dist/triggers.js +22 -3
  133. package/dist/validate.d.ts +11 -7
  134. package/dist/validate.js +8 -7
  135. package/dist/workspace/computer-for-claim.d.ts +15 -5
  136. package/dist/workspace/computer-for-claim.js +228 -32
  137. package/dist/workspace/resolve-computer.d.ts +8 -2
  138. package/dist/workspace/resolve-computer.js +1 -1
  139. package/package.json +10 -9
  140. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  141. package/dist/console/assets/index-Bz6IWncl.js +0 -711
@@ -1,18 +1,22 @@
1
1
  import { facts as claudeFacts } from "@parcha/agentrun-harness-claude/facts";
2
2
  import { facts as codexFacts } from "@parcha/agentrun-harness-codex/facts";
3
3
  import { facts as openCodeFacts } from "../../harness-opencode/facts.js";
4
+ import { harnessOf } from "../../harness-table.js";
4
5
  import { piAdapter } from "./pi.js";
5
6
  const CLAUDE_PACKAGE = "@parcha/agentrun-harness-claude";
6
7
  const CODEX_PACKAGE = "@parcha/agentrun-harness-codex";
7
8
  /** Every harness the runner runs, by name. */
8
9
  export const RUNNER_HARNESSES = {
9
10
  pi: {
10
- adapter: async (launch) => piAdapter({
11
+ // `extra`: pi's own options (PiAdapterOptions), as the run's spec gives them (adapter-run-spec.ts): its extensions,
12
+ // tools, redactor, tiers, and the route's whole provider over the launch's.
13
+ adapter: async (launch, extra = {}) => piAdapter({
11
14
  run: launch.run,
12
15
  model: launch.model,
13
16
  provider: { api: launch.provider.api ?? "anthropic-messages", origin: launch.provider.origin, credential: launch.provider.credential, ...(launch.provider.headers ? { headers: launch.provider.headers } : {}), ...(launch.provider.auth ? { auth: launch.provider.auth } : {}) },
14
17
  ...(launch.price ? { price: launch.price } : {}),
15
18
  ...(launch.fetch ? { fetch: launch.fetch } : {}),
19
+ ...extra,
16
20
  }),
17
21
  },
18
22
  [claudeFacts.id]: {
@@ -70,7 +74,12 @@ export const RUNNER_HARNESSES = {
70
74
  },
71
75
  },
72
76
  };
73
- /** The harness the launch names, or undefined when the runner runs none by that name. */
74
- export function resolveHarness(harness) {
75
- return Object.prototype.hasOwnProperty.call(RUNNER_HARNESSES, harness) ? RUNNER_HARNESSES[harness] : undefined;
77
+ /** The harness the launch names, as `env`'s harness table has it (harness-table.ts harnessOf): a built-in one's runner is
78
+ * the runner's own (RUNNER_HARNESSES), one a harness module adds brings its own (HarnessEntry.runner). Undefined when
79
+ * the table has none by that name. `env`: the run's environment (this process's when not given). */
80
+ export function resolveHarness(harness, env = process.env) {
81
+ const entry = harnessOf(env, harness);
82
+ if (!entry)
83
+ return undefined;
84
+ return entry.runner ?? (Object.prototype.hasOwnProperty.call(RUNNER_HARNESSES, harness) ? RUNNER_HARNESSES[harness] : undefined);
76
85
  }
@@ -20,6 +20,9 @@ export type AuditDeps = {
20
20
  readonly log: (line: string) => void;
21
21
  readonly sealKey?: Buffer;
22
22
  readonly now?: () => number;
23
+ /** Why model spend beside the claimed run is skipped (claim-secrets.ts claimSpendOff): a shadow is a run the runner
24
+ * starts with no caller's key. Absent: it runs. */
25
+ readonly spendOff?: (what: string) => string | undefined;
23
26
  };
24
27
  /** The words a second hold within stop_window leaves on its record: what the owner reads. */
25
28
  export declare const STOPPED_TWICE = "stopped: the workflow disagreed with the agent twice";
@@ -39,6 +42,7 @@ export declare const AUDIT_PARKED = "the audit ended where it would wait on a pe
39
42
  * could never be audited (no learning start, or not auditableLaunch) keeps `step` as it is. */
40
43
  export declare function withAudit(step: EndOfRunTurn | undefined, deps: AuditDeps & {
41
44
  readonly launch: RunLaunch;
45
+ readonly redact?: (text: string) => string;
42
46
  }): EndOfRunTurn | undefined;
43
47
  /** Starts the shadow of run `runId`, at its end, when the learned workflow `serve` served it first and its id is drawn:
44
48
  * never for a replay or a shadow, a run that does not learn, one not auditable (auditableLaunch: a trigger started it,
@@ -1,6 +1,6 @@
1
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 served first is
3
- // drawn at 1 in k (auditDrawn, from its id), and a drawn one appends a `started` line to audits.jsonl (with the
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
4
  // promotion serving it and the answer it audits, `turn`: the id of the run's newest answer row now), then starts its
5
5
  // shadow run: the same agent and revision on the same input with learning off (no seed, no look-back), marked as the
6
6
  // audit of the served run (launch.audit), no row of the run list, billed to the agent as learning cost. Its cap is
@@ -26,9 +26,9 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
26
26
  import { overCapMessage } from "@parcha/agentrun-kernel/kernel/cap";
27
27
  import { auditLoopOf } from "../learning-setting.js";
28
28
  import { RUN_CAP_MIN_USD } from "../learning-batch.js";
29
- import { SERVED_PATHS } from "../learning-cost.js";
30
29
  import { launchBody, readLaunchBody } from "../run-launch.js";
31
30
  import { runEntries } from "../store-reads/journal.js";
31
+ import { runPathOverStore } from "../store-reads/learning.js";
32
32
  import { FINAL_STATES, StoreConstraint } from "../store/store.js";
33
33
  import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
34
34
  import { isObject } from "../validate.js";
@@ -46,7 +46,9 @@ const iso = (ms) => new Date(ms).toISOString();
46
46
  const ended = (row) => row !== undefined && FINAL_STATES.includes(row.state) && row.runner === null;
47
47
  const inputText = (input) => (typeof input === "string" ? input : JSON.stringify(input) ?? "");
48
48
  const metricsOf = (row) => (isObject(row?.metrics) ? row.metrics : {});
49
- const served = (row) => SERVED_PATHS.includes(metricsOf(row).path);
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";
50
52
  /** A line's `turn` (AuditRow.turn): the answer row's id, none when the run had no answer. */
51
53
  const turnOf = (id) => (id === undefined ? {} : { turn: id });
52
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. */
@@ -87,12 +89,16 @@ export function withAudit(step, deps) {
87
89
  return rows;
88
90
  };
89
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. */
90
94
  async function auditAtEnd(deps, runId, queued) {
91
95
  try {
92
96
  const entries = await runEntries(deps.store, runId, BACKGROUND_CONTEXT);
93
97
  const served = servedOf(entries);
94
98
  if (!served?.digest)
95
99
  return;
100
+ if ((await runPathOverStore(deps.store, runId, deps.launch.learning, deps.redact)).path !== "workflow")
101
+ return;
96
102
  const capUsd = deps.launch.maxCostUsd;
97
103
  await startAudit({ ...deps, runId, ...(capUsd !== undefined ? { room: () => auditRoomOf(deps.store, runId, capUsd, entries, queued) } : {}) }, { name: served.workflow, digest: served.digest });
98
104
  }
@@ -112,6 +118,11 @@ export async function startAudit(deps, serve) {
112
118
  const { store, agentId, runId, launch, log } = deps;
113
119
  if (!serve || serve.replay || launch.replay || launch.audit || !launch.learning || !auditableLaunch(launch))
114
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}`);
115
126
  try {
116
127
  // Read after the claim pinned the revision's MCP tools (mcp-claim.ts pinFirst): the pin a revision saved without one
117
128
  // takes at its first run is what its tools are classed by.
@@ -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");
@@ -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
@@ -14,6 +14,7 @@
14
14
  // hands on them (runTools), the gate from the store's tool settings, the system prompt (environment line, instructions
15
15
  // with what the agent learned and its skills, effort guidance), the first message, the end's metrics and the release.
16
16
  import { mkdir, readdir, rm, rmdir } from "node:fs/promises";
17
+ import { stopRunWith } from "../paid-calls.js";
17
18
  import { dirname, join } from "node:path";
18
19
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
19
20
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
@@ -54,7 +55,7 @@ import { isWebHostTool } from "../tool-list.js";
54
55
  import { hostToolOf } from "../host-tools.js";
55
56
  import { ASK_TOOL, askPerson } from "../tools.js";
56
57
  import { fakedPlane } from "../web-fake.js";
57
- import { claimSecrets, hostDecisionKeys, learnedDecisionKeys, tierModelKeys, withModelKeys } from "./claim-secrets.js";
58
+ import { claimModelEnv, claimModelKey, claimSecrets, claimSpendOff, holdRunKey, keyedAtClaim, hostDecisionKeys, learnedDecisionKeys, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
58
59
  import { mcpForClaim } from "./mcp-run.js";
59
60
  import { DECISION_PROVIDER_KEYS, TOOL_PLANE_ENV } from "../tool-plane.js";
60
61
  import { decisionProvidersIn } from "../decisions.js";
@@ -139,8 +140,9 @@ export async function cliCapModel(entry, env, ref) {
139
140
  * run whose plane resolves it to native gets the harness's own search (#2458), this run's alone; whatever the runner's
140
141
  * own environment says of a plane is never the run's. Whether each search runs is the tool's setting at that search
141
142
  * (SessionIO.permission, the gate), never this plane, which is frozen when the run is made. */
142
- export function cliRunEnv(env, data, claimed = {}, plane) {
143
- const out = withModelKeys(env ?? {}, claimed);
143
+ export function cliRunEnv(env, data, claimed = {}, plane, runKey) {
144
+ // A run with its own model key: that key alone, in the variables its route sends (claimModelEnv, never enumerable).
145
+ const out = claimModelEnv(env ?? {}, claimed, runKey);
144
146
  Object.defineProperty(out, DATA_ENV, { value: data, enumerable: true, writable: true, configurable: true });
145
147
  delete out[TOOL_PLANE_ENV];
146
148
  if (plane && Object.keys(plane).length)
@@ -270,7 +272,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
270
272
  // test runner; anywhere else it is the built-ins), and the runner's record mode for it.
271
273
  const name = launch.harness ?? body.harness;
272
274
  const entry = harnessOf(deps.env, name);
273
- const runner = name === undefined ? undefined : resolveHarness(name);
275
+ const runner = name === undefined ? undefined : resolveHarness(name, deps.env);
274
276
  if (!name || !entry?.facts || !entry.adapter || !runner)
275
277
  throw new Error(`run ${claim.runId}: ${JSON.stringify(name)} is not a CLI harness this runner runs`);
276
278
  const facts = entry.facts;
@@ -383,7 +385,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
383
385
  // Whether an earlier claim made the run a computer of its own is the run's journal's to say (hadComputer), as the pi
384
386
  // spec asks it. The computer a park kept, attached again, brings its mount credential with it (inheritMount). Its
385
387
  // screen's recording (computer.record) goes in the run's recordings folder, as the pi spec's does.
386
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
388
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, refuseKind: cliRefusesKind, recordings: { folder: recordingsFolder(deps.data, runRow.agentId, claim.runId), say: (words) => run.phase?.(words) }, hadComputer: () => hadComputer(deps.journal(claim), context), stopRun: stopRunWith((refusal) => run.ledger.pause(refusal)), ...(claimSignal ? { signal: claimSignal } : {}), ...(archil ? { revokeMount: () => archil.revoke(), inheritMount: () => archil.inherit() } : {}), ...(run.phase ? { onImageWait: (making, image) => run.phase?.(imageWaitWords(making, image)), onStarting: (said) => run.phase?.(computerStartingWords(said)), onConnected: (said) => run.phase?.(computerReadyWords(said)), onComputerNote: (words) => run.phase?.(words) } : {}) });
387
389
  holds.hold({ computer });
388
390
  const loopComputer = loopComputerOf(computer.computer, computer.held, computer.made);
389
391
  const heldComputer = heldSpecOf(launch, loopComputer);
@@ -429,9 +431,19 @@ async function cliSpec(launch, run, deps, claim, holds) {
429
431
  // to the model choice and the adapter's provider (withModelKeys, never enumerable), so a key saved in
430
432
  // Settings → Model keys runs the next run with no restart, as one set where AgentRun starts does.
431
433
  const claimed = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, launch);
432
- for (const redact of [...(run.redact ? [heldRedactor(run.redact)] : []), cut])
434
+ // The run's own model key, when its caller handed one (model_key): opened at every claim, held by the redactors, read by
435
+ // its model route alone; the CLI's process and its tools never carry it, nor any other model key then.
436
+ // A run that starts on the server's key holds the claim's key holder too: a message's first key reaches its next request.
437
+ const runKey = await claimModelKey({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, claim.runId);
438
+ const keyed = keyedAtClaim(runKey);
439
+ if (keyed)
440
+ withoutModelKeys(claimed);
441
+ for (const redact of [...(run.redact ? [heldRedactor(run.redact)] : []), cut]) {
433
442
  holdClaimed(redact, claimed);
434
- const env = cliRunEnv(deps.env, deps.data, claimed, launch.plane);
443
+ if (runKey)
444
+ holdRunKey(redact, runKey);
445
+ }
446
+ const env = cliRunEnv(deps.env, deps.data, claimed, launch.plane, runKey);
435
447
  const chosen = await modelsOf(entry, env, modelAskOf(launch.model, body.model));
436
448
  await planBeforeRun(env, chosen.model);
437
449
  // The CLI's own process (the Claude CLI, Codex, OpenCode) starts under the no_new_privs pi's commands start under
@@ -557,11 +569,14 @@ async function cliSpec(launch, run, deps, claim, holds) {
557
569
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
558
570
  // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the agent takes the run.
559
571
  // The audits that finished since are written first (runner/audit.ts settleAudits): a hold they make decides this claim.
560
- const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey };
572
+ // Model spend beside the run that its caller's key does not pay for (claimSpendOff): a shadow audit, a replay check and
573
+ // the learning run's grade are skipped, in words, where the run brought its own key or the server holds none.
574
+ const spendOff = await claimSpendOff({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, runKey);
575
+ const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff };
561
576
  if (launch.learning && !launch.replay && !launch.audit)
562
577
  await settleAudits(audits);
563
578
  const promotion = claimPromotion({
564
- store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
579
+ store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff,
565
580
  });
566
581
  const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(promotion), revision.body.outputSchema) : {};
567
582
  // A replay run runs only its revision, while it still replays: else its claim is refused (the run ends failed, no agent).
@@ -601,10 +616,11 @@ async function cliSpec(launch, run, deps, claim, holds) {
601
616
  // keys, pi's wires, since pi-ai's client sends these, never the CLI); one refused fails its node in its words.
602
617
  // Their models' keys (tierModelKeys: a saved one too, which claimSecrets opened only for the run's own model), held by
603
618
  // the redactors, on the tiers' route env alone (withModelKeys, never enumerable), never on the tools' (toolEnv).
604
- const tierKeys = await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
619
+ // A run with its own model key: these tiers carry that key too, and no saved key is read.
620
+ const tierKeys = keyed ? {} : await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
605
621
  for (const redact of new Set([held, cut]))
606
622
  holdClaimed(redact, tierKeys);
607
- const modelEnv = withModelKeys(deps.env, { ...claimed, ...tierKeys });
623
+ const modelEnv = claimModelEnv(deps.env, { ...claimed, ...tierKeys }, runKey);
608
624
  const tiers = new Map();
609
625
  for (const [tier, routed] of await learnedTierRoutes(workflows, modelEnv, (tier) => deps.routeOf(undefined, modelEnv, tier, PI_WIRES, undefined, cut))) {
610
626
  if ("why" in routed)
@@ -640,11 +656,12 @@ async function cliSpec(launch, run, deps, claim, holds) {
640
656
  // store, its learning folder where the run's place keeps it — Mode 1 under the data directory, Mode 2 on this claim's
641
657
  // Archil disk — so the proposal is checked against the seed in the run's own Workspace, never this machine's local path.
642
658
  // A replay run or an audit's shadow run asks nothing at its end: it is the promotion's, never the agent's to learn from.
643
- // A run the promoted workflow served first starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
659
+ // A run the promoted workflow answered (path `workflow`) starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
644
660
  // withAudit): at its end, so the shadow's cap is what the run's own left.
645
661
  const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
646
662
  store: deps.store,
647
663
  data: deps.data,
664
+ spendOff,
648
665
  ...(deps.env ? { env: deps.env } : {}),
649
666
  // What the run must never learn beside the runner's secrets: the keys its claim handed it, every secret the server
650
667
  // keeps sealed (storeSecrets: the run's redactor holds the same list), and its sign-in's pointers, read back from the
@@ -658,7 +675,7 @@ async function cliSpec(launch, run, deps, claim, holds) {
658
675
  learningFolder: archil === undefined
659
676
  ? (agentId) => learningFolderOf(deps.data, agentId)
660
677
  : (agentId) => learningWorkspace({ mode: "archil", agentId, archil }),
661
- }), { ...audits, launch });
678
+ }), { ...audits, launch, ...(run.redact ? { redact: run.redact } : {}) });
662
679
  return {
663
680
  adapter,
664
681
  session,
@@ -674,6 +691,8 @@ async function cliSpec(launch, run, deps, claim, holds) {
674
691
  // The run's MCP for a harness with its own client (mcp-run.ts), with its monid endpoints beside it (monid-run.ts):
675
692
  // the catalog tools the session mounts; absent when none.
676
693
  ...(catalog ? { mcp: catalog } : {}),
694
+ // The run's own model key: a command row opens it again before the next model request (a message's new key).
695
+ ...(runKey ? { modelKey: runKey } : {}),
677
696
  // The run's end-of-run step, when it learns (the spec's, preferred over the loop's deps': adapter-loop.ts stepOf).
678
697
  ...(endOfRun ? { endOfRun } : {}),
679
698
  ...(start ? { learningLaid: laidOf(seedLaid) } : {}),
@@ -1,4 +1,5 @@
1
1
  import type { Command } from "./loop-contract.js";
2
+ import type { LaunchSealedWrite } from "../store/store.js";
2
3
  /** stop and cancel both end the run, stopped: a cancel's end says it was cancelled, as main's cancel ends a run for good.
3
4
  * browser_hand_back is a person's answer to the agent's browser hand-over (runner/hand-back.ts). computer_take_over and
4
5
  * computer_hand_back are a person's turn with the run's desktop or phone (computer-commands.ts, runner/computer-journal.ts).
@@ -15,15 +16,11 @@ export interface CommandSink {
15
16
  command(runId: string, command: {
16
17
  kind: string;
17
18
  body: Record<string, unknown>;
18
- }, options?: {
19
- launchSealed?: Uint8Array;
20
- }): Promise<Command>;
19
+ }, options?: LaunchSealedWrite): Promise<Command>;
21
20
  }
22
21
  /** Inserts a command row for a run, after checking its kind and body. Rejects RunFinal (from the store) when the run is
23
22
  * final, and a TypeError for a kind or body no runner would take. */
24
- export declare function sendCommand(store: CommandSink, runId: string, input: CommandInput, options?: {
25
- launchSealed?: Uint8Array;
26
- }): Promise<Command>;
23
+ export declare function sendCommand(store: CommandSink, runId: string, input: CommandInput, options?: LaunchSealedWrite): Promise<Command>;
27
24
  /** The reason a command still untaken when its run ended is refused with: the store's own words (the write that makes a
28
25
  * run final refuses such rows itself). */
29
26
  export { endedReason } from "../store/store.js";
@@ -1,5 +1,6 @@
1
1
  import { type Grade } from "../learn/promote.js";
2
2
  import type { RunPath } from "../learning-cost.js";
3
+ import { type RunLaunch } from "../run-launch.js";
3
4
  import { type Command, type Store } from "../store/store.js";
4
5
  export declare const FEEDBACK_ROUNDS: readonly ["look_back"];
5
6
  export type FeedbackRound = (typeof FEEDBACK_ROUNDS)[number];
@@ -55,9 +56,9 @@ export interface OpenedRound {
55
56
  * agent (closed history: a grade of it starts no paid work), and one the store opens again (an agentic run that answered
56
57
  * or that a person stopped). Null when the grade asks for nothing more, or the run can't be opened again (the grade is
57
58
  * kept either way). */
58
- export declare function openFeedbackRound(store: Pick<Store, "runs" | "agents">, grade: Grade, label: string | undefined): Promise<OpenedRound | null>;
59
+ export declare function openFeedbackRound(store: Pick<Store, "runs" | "agents">, grade: Grade, label: string | undefined, canTurn?: (launch: RunLaunch) => boolean): Promise<OpenedRound | null>;
59
60
  /** A grade's write (PUT /runs/{id}/grade): keeps `grade` for agent `agentId` naming no round, opens its run again on the
60
61
  * round it asks for (openFeedbackRound), and only then marks the kept grade with that round and its steer. The grade is
61
62
  * kept first, so the round's end reads it; the round is named last, so a reopen that fails (thrown, or a run that can't
62
63
  * be opened again) leaves a grade naming none, never one claiming a round that didn't open. The grade as kept. */
63
- export declare function keepGrade(store: Pick<Store, "runs" | "agents" | "settings">, agentId: string, grade: Grade, label: string | undefined): Promise<Grade>;
64
+ export declare function keepGrade(store: Pick<Store, "runs" | "agents" | "settings">, agentId: string, grade: Grade, label: string | undefined, canTurn?: (launch: RunLaunch) => boolean): Promise<Grade>;
@@ -68,7 +68,7 @@ export function feedbackStatus(entries, command) {
68
68
  * agent (closed history: a grade of it starts no paid work), and one the store opens again (an agentic run that answered
69
69
  * or that a person stopped). Null when the grade asks for nothing more, or the run can't be opened again (the grade is
70
70
  * kept either way). */
71
- export async function openFeedbackRound(store, grade, label) {
71
+ export async function openFeedbackRound(store, grade, label, canTurn = () => true) {
72
72
  const words = label?.trim() ? label.trim() : undefined;
73
73
  const round = feedbackRoundOf(grade, words);
74
74
  if (!round || !words)
@@ -84,6 +84,10 @@ export async function openFeedbackRound(store, grade, label) {
84
84
  const learning = launch?.learning;
85
85
  if (!learning || learning.use)
86
86
  return null;
87
+ // The round is a turn of the run with no caller's model key (a grade hands none): where the server holds no key for the
88
+ // run's route (`canTurn` false), the grade is kept and the run is not opened again, never left to fail with no key.
89
+ if (launch && !canTurn(launch))
90
+ return null;
87
91
  const feedback = { round, correct: grade.correct };
88
92
  try {
89
93
  const steer = await store.runs.reopen(grade.run, { kind: "steer", body: { text: words, feedback } });
@@ -99,8 +103,8 @@ export async function openFeedbackRound(store, grade, label) {
99
103
  * round it asks for (openFeedbackRound), and only then marks the kept grade with that round and its steer. The grade is
100
104
  * kept first, so the round's end reads it; the round is named last, so a reopen that fails (thrown, or a run that can't
101
105
  * be opened again) leaves a grade naming none, never one claiming a round that didn't open. The grade as kept. */
102
- export async function keepGrade(store, agentId, grade, label) {
106
+ export async function keepGrade(store, agentId, grade, label, canTurn) {
103
107
  const kept = await putGrade(store.settings, agentId, { ...grade, feedback: null });
104
- const opened = await openFeedbackRound(store, kept, label);
108
+ const opened = await openFeedbackRound(store, kept, label, canTurn);
105
109
  return opened ? markGradeRound(store.settings, agentId, kept, opened) : kept;
106
110
  }