@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
package/dist/place.d.ts CHANGED
@@ -22,9 +22,14 @@ export declare function newAgentPlace(registry: readonly BoxOffer[]): {
22
22
  why: string;
23
23
  };
24
24
  /** The place a revision that names none resolves to, at its create and at each run alike: this server's default place
25
- * (newAgentPlace) for an agentic revision; the runner for a workflow, which is never given a box, and for one that names
26
- * a tool the box refuses (`refused`: the browser, runner-only for now). */
27
- export declare function defaultPlaceOf(kind: "agentic" | "workflow", tools: readonly unknown[], registry: readonly BoxOffer[], refused: (tool: string) => boolean): Place;
25
+ * (newAgentPlace) for an agentic revision with a tool that runs only in a box (`flags`, tools.ts: bash and the
26
+ * background tools); the runner for a workflow, which is never given a box, for one whose tools need no shell (none, or
27
+ * only read and write: a container would only hold up its start), and for one that names a tool the box refuses (the
28
+ * browser, runner-only for now). */
29
+ export declare function defaultPlaceOf(kind: "agentic" | "workflow", tools: readonly unknown[], registry: readonly BoxOffer[], flags: (tool: string) => {
30
+ readonly sandboxOnly?: true;
31
+ readonly runnerOnly?: true;
32
+ } | undefined): Place;
28
33
  /** The tools a new agent in the default box is given when its definition names none: a shell, and the background tools
29
34
  * that start, read, feed, signal and list commands that outlive one call (background.ts SHELL_TOOLS, which a test holds
30
35
  * this list to; written out here, since background.ts reads this module). A definition that names its tools, an empty
package/dist/place.js CHANGED
@@ -7,11 +7,12 @@
7
7
  // of that provider (computer-setting.ts computerOfPlace), which the run's claim starts: Docker, Daytona or Modal. A harness's own tools in the box, when they come, are an option of sandbox, never a third
8
8
  // mode.
9
9
  //
10
- // The box is a new agent's default machine: an agentic definition that names no place is saved, at its create, with the
11
- // Docker box as its place wherever this server has docker, and with bash when it names no tools
12
- // (newAgentPlace). A revision that names no place resolves the same way at each run (defaultPlaceOf): this server's
13
- // default_place, so where docker is there now it runs in the Docker box, and the runner where it is not. A workflow, and a
14
- // revision with a tool the box refuses, run on the runner.
10
+ // The box is a new agent's default machine for a shell: an agentic definition that names no place and no tools is saved,
11
+ // at its create, with the Docker box as its place wherever this server has docker, and with bash (newAgentPlace). One that
12
+ // names its tools gets the box only when one of them needs a shell; else it keeps no place and runs on the runner, with
13
+ // no container to wait for. A revision that names no place resolves the same way at each run (defaultPlaceOf): with a
14
+ // shell tool, this server's default_place, so where docker is there now it runs in the Docker box, and the runner where it
15
+ // is not. A workflow, a revision whose tools need no shell, and one with a tool the box refuses run on the runner.
15
16
  import { BOX_IDS, BOXES_ENV } from "./place-offers.js";
16
17
  import { sentence } from "./errors.js";
17
18
  export const PLACE_MODES = ["runner", "sandbox"];
@@ -39,10 +40,13 @@ export function newAgentPlace(registry) {
39
40
  return { reason: `new agents run on the runner, because the docker box is unavailable here: ${why}`, why };
40
41
  }
41
42
  /** The place a revision that names none resolves to, at its create and at each run alike: this server's default place
42
- * (newAgentPlace) for an agentic revision; the runner for a workflow, which is never given a box, and for one that names
43
- * a tool the box refuses (`refused`: the browser, runner-only for now). */
44
- export function defaultPlaceOf(kind, tools, registry, refused) {
45
- if (kind === "workflow" || tools.some((tool) => typeof tool === "string" && refused(tool)))
43
+ * (newAgentPlace) for an agentic revision with a tool that runs only in a box (`flags`, tools.ts: bash and the
44
+ * background tools); the runner for a workflow, which is never given a box, for one whose tools need no shell (none, or
45
+ * only read and write: a container would only hold up its start), and for one that names a tool the box refuses (the
46
+ * browser, runner-only for now). */
47
+ export function defaultPlaceOf(kind, tools, registry, flags) {
48
+ const named = tools.flatMap((tool) => (typeof tool === "string" ? [flags(tool)] : []));
49
+ if (kind === "workflow" || named.some((tool) => tool?.runnerOnly) || !named.some((tool) => tool?.sandboxOnly))
46
50
  return { mode: "runner" };
47
51
  const fresh = newAgentPlace(registry);
48
52
  return "place" in fresh ? fresh.place : { mode: "runner" };
package/dist/provider.js CHANGED
@@ -59,6 +59,18 @@ export function gatewayBase(setting, value) {
59
59
  throw wrong(`is ${url.protocol.replace(/:$/, "")}, not https`);
60
60
  return `${url.origin}${url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "")}`;
61
61
  }
62
+ /** Whether `base` (a gatewayBase answer) is on the origin of serve's own gateway (AGENT_MODEL_BASE_URL): there a run's own
63
+ * model key (run-model-key.ts) is sent, so the endpoint needs no standing key of the server's. */
64
+ function onServeGateway(env, base) {
65
+ if (!env.AGENT_MODEL_BASE_URL)
66
+ return false;
67
+ try {
68
+ return new URL(gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL)).origin === new URL(base).origin;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
62
74
  /**
63
75
  * Whether `wire` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
64
76
  * wire's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names (ANTHROPIC_BASE_URL
@@ -114,7 +126,9 @@ export function providerFor(wire, env, model, who) {
114
126
  // The endpoint first: one it refuses is the reason, and no key would fix it (no `keys`). An endpoint the host names
115
127
  // takes Anthropic's key alone: OpenRouter's never goes there.
116
128
  const origin = env.ANTHROPIC_BASE_URL ? gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL) : ANTHROPIC_ORIGIN;
117
- if (!env.ANTHROPIC_API_KEY)
129
+ // An endpoint on serve's own gateway's origin takes each run's own key where the server holds none (run-model-key.ts):
130
+ // the harness runs here with no standing key, and a run with no key to spend is refused at its start.
131
+ if (!env.ANTHROPIC_API_KEY && !onServeGateway(env, origin))
118
132
  throw env.ANTHROPIC_BASE_URL ? new HarnessUnavailable(`${who} needs ANTHROPIC_API_KEY.`, undefined, ["ANTHROPIC_API_KEY"]) : new HarnessUnavailable(`${who} needs ANTHROPIC_API_KEY or OPENROUTER_API_KEY.`, undefined, ["ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"]);
119
133
  return { origin, credential: () => env.ANTHROPIC_API_KEY ?? "", auth: "x-api-key", modelId: own, priceModel: { provider: "anthropic", modelId: own } };
120
134
  }
@@ -74,7 +74,7 @@ export declare function servedRunLearning(deps: {
74
74
  feedback_status: "running" | "ended" | "not_run" | null;
75
75
  source: "feedback" | "eval";
76
76
  graded_at: string;
77
- path: "agent" | "workflow" | "handed_back" | "replay" | "audit";
77
+ path: "agent" | "workflow" | "replay" | "handed_back" | "audit";
78
78
  workflow_digest: string | null;
79
79
  feedback: "look_back" | null;
80
80
  run_id: string;
@@ -0,0 +1,64 @@
1
+ import { ApiError, type InputIssue } from "./errors.js";
2
+ /** The longest model key a run takes: a header value, never a document. */
3
+ export declare const MAX_MODEL_KEY_CHARS = 4096;
4
+ /** The origin of the model gateway a run's model key goes to (AGENT_MODEL_BASE_URL's, by the one base rule), or undefined
5
+ * when the server names none or one a key may not go to. */
6
+ export declare function runModelOrigin(env: NodeJS.ProcessEnv): string | undefined;
7
+ /** The variables a run's model key fills in a model route's env, for a gateway at `origin`: the gateway's key, and
8
+ * ANTHROPIC_API_KEY where ANTHROPIC_BASE_URL is that same gateway. */
9
+ export declare function runKeyNames(env: NodeJS.ProcessEnv, origin: string): string[];
10
+ /** A model key `body` hands, checked: text of 1 to MAX_MODEL_KEY_CHARS characters with no whitespace or control character
11
+ * (it goes in a header). Issues are pushed at `model_key`. */
12
+ export declare function modelKeyOf(value: unknown, issues: InputIssue[]): string | undefined;
13
+ /** 422 model_key_required: a run start, or a message that would start a turn, with no model key to spend: none handed,
14
+ * none the run holds, and none the server holds for its route. */
15
+ export declare const modelKeyRequired: (message: boolean) => ApiError;
16
+ /** What of a run says where its model requests go: its kind and its launch's pinned model. */
17
+ export type ModelKeyTarget = {
18
+ readonly kind: "agentic" | "workflow" | string;
19
+ readonly model?: {
20
+ readonly provider: string;
21
+ readonly modelId: string;
22
+ } | undefined;
23
+ readonly native?: boolean;
24
+ };
25
+ /** The variables a run's model route reads its key from when that route goes to the model gateway (a workflow's model
26
+ * nodes, pi's and codex's models, a CLI harness on Anthropic's wire where ANTHROPIC_BASE_URL is the gateway's origin);
27
+ * undefined for a route that goes elsewhere (a provider's own, the ChatGPT plan, the faux model) or a native run. */
28
+ export declare function gatewayKeyNames(env: NodeJS.ProcessEnv, run: ModelKeyTarget): string[] | undefined;
29
+ /** Whether a run of `run` with no key of its own has none to spend: its route goes to the gateway, and `env` (the
30
+ * server's, with the keys saved in Settings) holds no key it reads. */
31
+ export declare function serverKeyMissing(env: NodeJS.ProcessEnv, run: ModelKeyTarget): boolean;
32
+ /** Words for model spend tied to no run's key (`what`, a noun phrase) on a server that holds no gateway key (`env`, its
33
+ * keys saved in Settings among them): skipped or refused, never sent with no key. Undefined where the server holds one. */
34
+ export declare function noServerKeyFor(env: NodeJS.ProcessEnv, what: string): string | undefined;
35
+ /** The words of noServerKeyFor for `what`. */
36
+ export declare const noServerKeyWords: (what: string) => string;
37
+ /** Words for spend after the turn of a run that held its own model key (`what`): skipped, since that key is erased with
38
+ * the turn's end and revoked by its caller, and the server's key never pays for a run that brought its own. */
39
+ export declare const runKeyEndedFor: (what: string) => string;
40
+ /** Why a run's model key would never be used, so it is refused rather than kept unused; undefined where it applies: a
41
+ * workflow run (its model nodes go to the gateway), or an agentic run whose model goes to the gateway (pi's and codex's,
42
+ * MODEL_PROVIDER) or to Anthropic's endpoint on the gateway's origin (a CLI harness on Anthropic's wire). */
43
+ export declare function modelKeyMisfit(env: NodeJS.ProcessEnv, run: ModelKeyTarget): string | undefined;
44
+ /** A run's model key as a claim holds it: the gateway origin it was handed for, and the key now (a message's replaces it
45
+ * at the next command; none before the run's first key, and none once its launch no longer holds one). */
46
+ export interface HeldModelKey {
47
+ readonly origin: string;
48
+ key(): string | undefined;
49
+ }
50
+ /**
51
+ * `env` for a run's model routes when the run holds its own key: every property of `env` but each model key (the runner's
52
+ * own and any saved one never go), with the run's key read at each request (`held.key()`) in each variable it fills
53
+ * (runKeyNames). Those are getters, never enumerable: a spread of the result, a spawn given it or a tool's env made from
54
+ * it carries none of them. No ChatGPT sign-in either (a symbol, not copied): every model call tied to the run carries
55
+ * the run's key.
56
+ */
57
+ export declare function withRunModelKey(env: NodeJS.ProcessEnv, held: HeldModelKey): NodeJS.ProcessEnv;
58
+ /**
59
+ * `env` (a claim's model env on the server's keys, withModelKeys) for a run that holds no key of its own yet: each
60
+ * variable a run's key fills (runKeyNames) reads the run's key once a message hands one, and the server's value until
61
+ * then, at each request; every other variable as it is. So a run that started on the server's key spends a message's
62
+ * key from the request after that message on. Getters, never enumerable, as withRunModelKey's.
63
+ */
64
+ export declare function withRunModelKeyLater(env: NodeJS.ProcessEnv, held: HeldModelKey): NodeJS.ProcessEnv;
@@ -0,0 +1,147 @@
1
+ // A run's own model key: a key its caller hands with the run (`model_key` on POST /runs, POST /agents/{id}/runs and
2
+ // POST /runs/{id}/messages), such as a LiteLLM virtual key minted for that run, which every model request the run makes
3
+ // carries in place of the server's own key. AgentRun never mints, lists or revokes it: the caller owns its life.
4
+ //
5
+ // Where it goes: the model gateway at AGENT_MODEL_BASE_URL, which every pi model and every workflow model node is sent to,
6
+ // and Anthropic's Messages endpoint when ANTHROPIC_BASE_URL names that same gateway origin (a CLI harness on Anthropic's
7
+ // wire). It is sealed with the run, bound to that origin when handed (store/seal.ts RunModelKey), so a gateway moved since
8
+ // never receives it; it fills the gateway's key variable (and ANTHROPIC_API_KEY on that origin) in the model routes' env
9
+ // alone, read at each request, never enumerable and never on the env a tool, a harness or a sandbox runs under.
10
+ //
11
+ // No setting: what the server holds decides. A run with a model_key spends on it alone, outside its turn too (its
12
+ // subagents, learned nodes, end-of-run look-back), never on the server's key. A run without one spends on the server's
13
+ // key for its route, as before. A server that holds no key for a run's route (no AGENT_MODEL_API_KEY, nothing saved in
14
+ // Settings) is an operator saying "callers bring their own": a start or a message that would start a turn with no key
15
+ // to spend is 422 model_key_required, never a failure at the first model call. Spend after a run's turn ended (its key
16
+ // erased with that end, and revoked by its caller) or tied to no run, with no key to spend, is skipped or refused in words.
17
+ import { ApiError } from "./errors.js";
18
+ import { FAUX_ENV, GATEWAY_KEY_ENV, MODEL_PROVIDER, PROVIDER_KEYS } from "./model.js";
19
+ import { gatewayBase } from "./provider.js";
20
+ /** The longest model key a run takes: a header value, never a document. */
21
+ export const MAX_MODEL_KEY_CHARS = 4096;
22
+ /** The origin of the model gateway a run's model key goes to (AGENT_MODEL_BASE_URL's, by the one base rule), or undefined
23
+ * when the server names none or one a key may not go to. */
24
+ export function runModelOrigin(env) {
25
+ if (!env.AGENT_MODEL_BASE_URL)
26
+ return undefined;
27
+ try {
28
+ return new URL(gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL)).origin;
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ /** Whether ANTHROPIC_BASE_URL names the gateway at `origin`: there a CLI harness on Anthropic's wire sends ANTHROPIC_API_KEY,
35
+ * which a run's key then fills. */
36
+ function anthropicOnGateway(env, origin) {
37
+ if (!env.ANTHROPIC_BASE_URL)
38
+ return false;
39
+ try {
40
+ return new URL(gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL)).origin === origin;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ /** The variables a run's model key fills in a model route's env, for a gateway at `origin`: the gateway's key, and
47
+ * ANTHROPIC_API_KEY where ANTHROPIC_BASE_URL is that same gateway. */
48
+ export function runKeyNames(env, origin) {
49
+ return [GATEWAY_KEY_ENV, ...(anthropicOnGateway(env, origin) ? ["ANTHROPIC_API_KEY"] : [])];
50
+ }
51
+ /** Every model key a model route reads by name: each of pi-ai's providers' and the gateway's. */
52
+ const MODEL_KEY_NAMES = new Set([...Object.values(PROVIDER_KEYS).flat(), GATEWAY_KEY_ENV]);
53
+ /** A model key `body` hands, checked: text of 1 to MAX_MODEL_KEY_CHARS characters with no whitespace or control character
54
+ * (it goes in a header). Issues are pushed at `model_key`. */
55
+ export function modelKeyOf(value, issues) {
56
+ if (typeof value !== "string")
57
+ return void issues.push({ field: "model_key", reason: "wrong_type", message: "model_key is the run's model key as text, such as a LiteLLM virtual key minted for this run." });
58
+ if (!value.length || value.length > MAX_MODEL_KEY_CHARS || /[\s\x00-\x1f\x7f]/.test(value))
59
+ return void issues.push({ field: "model_key", reason: "invalid", message: `model_key is 1 to ${MAX_MODEL_KEY_CHARS} characters with no space or control character.` });
60
+ return value;
61
+ }
62
+ /** 422 model_key_required: a run start, or a message that would start a turn, with no model key to spend: none handed,
63
+ * none the run holds, and none the server holds for its route. */
64
+ export const modelKeyRequired = (message) => new ApiError("model_key_required", `This server holds no model key for this run's model (AGENT_MODEL_API_KEY is not set and none is saved in Settings → Model keys), so each run's caller brings its own: send model_key with ${message ? "a message that starts a turn" : "the run"}, a key for the model gateway at AGENT_MODEL_BASE_URL (such as a LiteLLM virtual key) minted for ${message ? "that turn" : "this run"}.`, { fields: [{ field: "model_key", reason: "missing", message: "model_key is required here: the server holds no model key for this run's model." }] });
65
+ /** The variables a run's model route reads its key from when that route goes to the model gateway (a workflow's model
66
+ * nodes, pi's and codex's models, a CLI harness on Anthropic's wire where ANTHROPIC_BASE_URL is the gateway's origin);
67
+ * undefined for a route that goes elsewhere (a provider's own, the ChatGPT plan, the faux model) or a native run. */
68
+ export function gatewayKeyNames(env, run) {
69
+ const origin = runModelOrigin(env);
70
+ if (!origin || run.native || env[FAUX_ENV])
71
+ return undefined;
72
+ if (run.kind === "workflow" || run.model?.provider === MODEL_PROVIDER)
73
+ return [GATEWAY_KEY_ENV];
74
+ if (run.model?.provider === "anthropic" && anthropicOnGateway(env, origin))
75
+ return ["ANTHROPIC_API_KEY"];
76
+ return undefined;
77
+ }
78
+ /** Whether a run of `run` with no key of its own has none to spend: its route goes to the gateway, and `env` (the
79
+ * server's, with the keys saved in Settings) holds no key it reads. */
80
+ export function serverKeyMissing(env, run) {
81
+ const names = gatewayKeyNames(env, run);
82
+ return names !== undefined && !names.some((name) => env[name]);
83
+ }
84
+ /** Words for model spend tied to no run's key (`what`, a noun phrase) on a server that holds no gateway key (`env`, its
85
+ * keys saved in Settings among them): skipped or refused, never sent with no key. Undefined where the server holds one. */
86
+ export function noServerKeyFor(env, what) {
87
+ return runModelOrigin(env) && !env[GATEWAY_KEY_ENV] ? noServerKeyWords(what) : undefined;
88
+ }
89
+ /** The words of noServerKeyFor for `what`. */
90
+ export const noServerKeyWords = (what) => `${what} is skipped: it is tied to no run's model key, and this server holds none of its own (AGENT_MODEL_API_KEY is not set and none is saved in Settings → Model keys).`;
91
+ /** Words for spend after the turn of a run that held its own model key (`what`): skipped, since that key is erased with
92
+ * the turn's end and revoked by its caller, and the server's key never pays for a run that brought its own. */
93
+ export const runKeyEndedFor = (what) => `${what} is skipped: this run spent on its own model key, which is erased when its turn ends; the server's key never pays for a run that brought its own.`;
94
+ /** Why a run's model key would never be used, so it is refused rather than kept unused; undefined where it applies: a
95
+ * workflow run (its model nodes go to the gateway), or an agentic run whose model goes to the gateway (pi's and codex's,
96
+ * MODEL_PROVIDER) or to Anthropic's endpoint on the gateway's origin (a CLI harness on Anthropic's wire). */
97
+ export function modelKeyMisfit(env, run) {
98
+ const origin = runModelOrigin(env);
99
+ if (!origin)
100
+ return "This server sends no model through a gateway (AGENT_MODEL_BASE_URL is not set), so a run's model key has nowhere to go.";
101
+ if (run.native)
102
+ return "A native run's model runs on its own machine, never through this server's gateway, so a model key would never be used.";
103
+ if (run.kind === "workflow")
104
+ return undefined;
105
+ if (run.model?.provider === MODEL_PROVIDER)
106
+ return undefined;
107
+ if (run.model?.provider === "anthropic" && anthropicOnGateway(env, origin))
108
+ return undefined;
109
+ const named = run.model ? `${run.model.provider}/${run.model.modelId}` : "its harness's own model";
110
+ return `This run's model (${named}) is not sent through the gateway at AGENT_MODEL_BASE_URL, so its model key would never be used.`;
111
+ }
112
+ /**
113
+ * `env` for a run's model routes when the run holds its own key: every property of `env` but each model key (the runner's
114
+ * own and any saved one never go), with the run's key read at each request (`held.key()`) in each variable it fills
115
+ * (runKeyNames). Those are getters, never enumerable: a spread of the result, a spawn given it or a tool's env made from
116
+ * it carries none of them. No ChatGPT sign-in either (a symbol, not copied): every model call tied to the run carries
117
+ * the run's key.
118
+ */
119
+ export function withRunModelKey(env, held) {
120
+ const out = {};
121
+ for (const name of Object.getOwnPropertyNames(env)) {
122
+ if (!MODEL_KEY_NAMES.has(name))
123
+ Object.defineProperty(out, name, Object.getOwnPropertyDescriptor(env, name));
124
+ }
125
+ for (const name of runKeyNames(env, held.origin))
126
+ Object.defineProperty(out, name, { get: () => held.key(), enumerable: false, configurable: false });
127
+ return out;
128
+ }
129
+ /**
130
+ * `env` (a claim's model env on the server's keys, withModelKeys) for a run that holds no key of its own yet: each
131
+ * variable a run's key fills (runKeyNames) reads the run's key once a message hands one, and the server's value until
132
+ * then, at each request; every other variable as it is. So a run that started on the server's key spends a message's
133
+ * key from the request after that message on. Getters, never enumerable, as withRunModelKey's.
134
+ */
135
+ export function withRunModelKeyLater(env, held) {
136
+ const names = new Set(runKeyNames(env, held.origin));
137
+ const out = {};
138
+ for (const name of Object.getOwnPropertyNames(env)) {
139
+ if (!names.has(name))
140
+ Object.defineProperty(out, name, Object.getOwnPropertyDescriptor(env, name));
141
+ }
142
+ for (const name of names) {
143
+ const server = env[name];
144
+ Object.defineProperty(out, name, { get: () => held.key() ?? server, enumerable: false, configurable: false });
145
+ }
146
+ return out;
147
+ }
@@ -220,6 +220,12 @@ export interface AdapterRunSpec {
220
220
  * the session through the loop's gate, a command row makes them fresh again, and the pass's end lets them go. Absent:
221
221
  * the run grants no MCP tool. */
222
222
  readonly mcp?: ClaimMcp;
223
+ /** The run's model key holder (claim-secrets.ts claimModelKey), which its model routes read at each request: a command
224
+ * row opens it from the run's launch again before the command reaches the session, so a message's key (a replacement,
225
+ * or a run's first) is the one its next request carries. Absent: no gateway here, and the routes read the server's keys. */
226
+ readonly modelKey?: {
227
+ fresh(): Promise<void>;
228
+ };
223
229
  /** The JSON Schema the run's final answer's last json block meets (its revision's definition.output_schema). An answer
224
230
  * that misses it is asked again once, in the same session under the same cap (the output contract's retry); absent:
225
231
  * the run's answer is never checked here. */
@@ -350,7 +350,7 @@ async function openCliRecord(harness, journal, context, now, cwd, endsItsCalls =
350
350
  flushedAtRequest = atRequest;
351
351
  if (joined)
352
352
  return;
353
- const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }) } : {};
353
+ const length = cut?.stopReason === "length" ? { stopReason: "length", ...(cut.outputTokens === undefined ? {} : { outputTokens: cut.outputTokens }), ...(cut.capCut === undefined ? {} : { capCut: { capUsd: cut.capCut.capUsd, raiseToUsd: cut.capCut.raiseToUsd } }) } : {};
354
354
  await append(KINDS.message, { role: "model", text: said, ...length });
355
355
  });
356
356
  };
@@ -3948,8 +3948,15 @@ function adapterLoop(specOf, options, deps) {
3948
3948
  async command(command) {
3949
3949
  // A command row resumes a loop that may have sat past a token's life: its MCP credentials are made fresh again
3950
3950
  // before its next model request.
3951
- if (command.kind === "steer" || command.kind === "approve" || command.kind === "deny" || command.kind === "raise")
3951
+ if (command.kind === "steer" || command.kind === "approve" || command.kind === "deny" || command.kind === "raise") {
3952
3952
  mcpStale = true;
3953
+ // The run's own model key, read again from its launch before the command reaches the session: the message's key
3954
+ // was written with its command row, so the next request's credential (which the model proxy reads before its
3955
+ // beforeRequest hook) is the message's, a first key or a replacement. Fail-closed: a read that keeps failing
3956
+ // throws here, before the command is taken, so the runner delivers it again at its next poll and the session
3957
+ // never runs the message on the key held before it.
3958
+ await specNow?.modelKey?.fresh();
3959
+ }
3953
3960
  if (command.kind === "steer")
3954
3961
  return steer(command);
3955
3962
  if (command.kind === "approve" || command.kind === "deny") {
@@ -16,6 +16,7 @@ import { type LearnedWorkflow } from "../learning.js";
16
16
  import { type ToolResults } from "../workspace/run-tools.js";
17
17
  import { type ClaimMcp } from "./mcp-run.js";
18
18
  import { type AdapterLoopOptions, type AdapterRun, type AdapterRunSpec, hostLifecycle } from "./adapter-loop.js";
19
+ import { type RunnerHarness } from "./adapters/index.js";
19
20
  import { type Claim, type Journal } from "./loop-contract.js";
20
21
  import type { ReplayCalls } from "../learn/replay-calls.js";
21
22
  import type { ModelRoute } from "./model-route.js";
@@ -221,9 +222,11 @@ export declare function adapterRunGate(store: Pick<Store, "settings">, claim: Pi
221
222
  /** The server's tool settings from the store now; a read that throws is unread (no value of it said). A workflow's call
222
223
  * and model nodes read theirs through it too (workflow-spec.ts callPolicyOf), so both gates fail closed alike. */
223
224
  export declare function storeSettings(store: Pick<Store, "settings">): Promise<Awaited<ReturnType<typeof loadToolSettings>>>;
224
- /** pi's spec for a claimed run. What it makes for the run (its Archil mount credential, its Workspace, its computer, its
225
- * tools) is held until the spec's release; a build that throws part-way lets go what it made by then (spec-holds.ts). */
226
- export declare function adapterRunSpecFromLaunch(launch: RunLaunch, run: AdapterRun, deps: AdapterSpecDeps, claim: Claim): Promise<AdapterRunSpec>;
225
+ /** pi's spec for a claimed run, on `runner`'s adapter (pi's when none is given; a harness module's runner for a harness it
226
+ * adds with no adapter facts), its visible record kept as that runner says (RunnerHarness.record). What it makes for the
227
+ * run (its Archil mount credential, its Workspace, its computer, its tools) is held until the spec's release; a build
228
+ * that throws part-way lets go what it made by then (spec-holds.ts). */
229
+ export declare function adapterRunSpecFromLaunch(launch: RunLaunch, run: AdapterRun, deps: AdapterSpecDeps, claim: Claim, runner?: RunnerHarness): Promise<AdapterRunSpec>;
227
230
  /** The host-tool ctx a non-hand tool is wrapped with (host-tools.ts hostToolOf): the run's own Harness (its commit,
228
231
  * snapshot and task reads), the results map, and the run's folder as the api env's cwd (a tool reads no
229
232
  * file environment, so an error names a path relative to it). Shared by the pi spec's bindNonHandTools and the CLI spec's
@@ -1,3 +1,17 @@
1
+ // The runner's pi spec (design 2.1: "the runner takes every run"). What app.ts built for a run it launched — the run's
2
+ // workspace, its computer, its tools, its model route, its spend cap and its end metrics — built here instead, from the
3
+ // run's launch record and its revision, and handed to the kernel's adapter loop (adapter-loop.ts) as one AdapterRunSpec.
4
+ // The dispatch switch (dispatch.ts resolve) runs a pi run on `createAdapterLoop((claim, run) =>
5
+ // adapterRunSpecFromLaunch(launch, run, deps, claim, runner))`, and so does a harness a module adds with no adapter facts
6
+ // of its own: the session's adapter is the run's runner's (RunnerHarness.adapter), pi's for a pi run.
7
+ //
8
+ // The one ledger (B2c): pi's model requests go through the session's proxy, booked by the runner's booking under the
9
+ // run's cap; the cap prices a request as main's calculateCost does (tiers included), on the hold and the booking. The
10
+ // tools are the kernel registry's hands on the run's Workspace (runTools), and — once built through the ToolHost below —
11
+ // tools.ts's full set (browser, web, MCP, decisions, monid) by their own names. The gate before a call's intent is the
12
+ // run's revision's tool settings, read through runGate (approvals "never" among them), the adapter loop asking it.
13
+ import { dirname, join } from "node:path";
14
+ import { stopRunWith } from "../paid-calls.js";
1
15
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
16
  import { defineExtension, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
3
17
  import { checkRaise, followUpOf, freeModelRequestsOf, parkOf, planCapModel } from "@parcha/agentrun-kernel/kernel/cap";
@@ -29,16 +43,17 @@ import { PORT_PROVIDER, tieredModels, tierProvider } from "../port-models.js";
29
43
  import { promptOf, readsFiles } from "../skills.js";
30
44
  import { openRunWorkspace } from "../workspace/run-workspace.js";
31
45
  import { layOwnSkills } from "../workspace/revision-skills.js";
32
- import { COMPUTER_ROOT, recordingsFolder, runFolder } from "../workspace/paths.js";
46
+ import { COMPUTER_ROOT, recordingsFolder, runFolder, scratchFolder } from "../workspace/paths.js";
33
47
  import { runTools, withKindTools } from "../workspace/run-tools.js";
34
48
  import { placeRunInputs } from "../uploads.js";
35
49
  import { handedSignInReadsBack, signInReads } from "../sign-ins-store.js";
36
50
  import { UNREADABLE_SIGN_IN } from "../run-view.js";
37
51
  import { durableWait } from "../workflow/pi-versions.js";
38
- import { claimSecrets, hostDecisionKeys, learnedDecisionKeys, savedModelKeys, tierModelKeys, withModelKeys } from "./claim-secrets.js";
52
+ import { claimModelEnv, claimModelKey, claimSecrets, claimSpendOff, holdRunKey, keyedAtClaim, hostDecisionKeys, learnedDecisionKeys, savedModelKeys, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
39
53
  import { catalogSessionNames, mcpForClaim } from "./mcp-run.js";
40
54
  import { hostLifecycle } from "./adapter-loop.js";
41
- import { piAdapter } from "./adapters/pi.js";
55
+ import { RUNNER_HARNESSES } from "./adapters/index.js";
56
+ import { DEFAULT_HARNESS } from "../harness.js";
42
57
  import { agentEntriesOf } from "./loop.js";
43
58
  import { SUBAGENT_TIERS, SUBAGENT_TOOL, subagentTool } from "./subagent.js";
44
59
  import { ClaimRefused } from "./loop-contract.js";
@@ -203,12 +218,14 @@ export async function storeSettings(store) {
203
218
  return { settings: {}, problems: ["the stored tool settings could not be read"], unreadable: true };
204
219
  }
205
220
  }
206
- /** pi's spec for a claimed run. What it makes for the run (its Archil mount credential, its Workspace, its computer, its
207
- * tools) is held until the spec's release; a build that throws part-way lets go what it made by then (spec-holds.ts). */
208
- export function adapterRunSpecFromLaunch(launch, run, deps, claim) {
209
- return specBuilt((holds) => adapterSpec(launch, run, deps, claim, holds));
221
+ /** pi's spec for a claimed run, on `runner`'s adapter (pi's when none is given; a harness module's runner for a harness it
222
+ * adds with no adapter facts), its visible record kept as that runner says (RunnerHarness.record). What it makes for the
223
+ * run (its Archil mount credential, its Workspace, its computer, its tools) is held until the spec's release; a build
224
+ * that throws part-way lets go what it made by then (spec-holds.ts). */
225
+ export function adapterRunSpecFromLaunch(launch, run, deps, claim, runner = RUNNER_HARNESSES[DEFAULT_HARNESS]) {
226
+ return specBuilt((holds) => adapterSpec(launch, run, deps, claim, holds, runner));
210
227
  }
211
- async function adapterSpec(launch, run, deps, claim, holds) {
228
+ async function adapterSpec(launch, run, deps, claim, holds, runner) {
212
229
  const context = BACKGROUND_CONTEXT;
213
230
  // What this claim may reach on loopback, read once for its MCP servers and its calendar_events alike (mcpReachOf).
214
231
  const reach = await mcpReachOf(deps);
@@ -317,7 +334,7 @@ async function adapterSpec(launch, run, deps, claim, holds) {
317
334
  // claim's is a new one whatever ended the earlier claim (a lost runner, a server's stop, a park past its keep). The
318
335
  // computer a park kept, attached again, brings its mount credential with it (inheritMount): none is minted. A
319
336
  // recording of its screen (computer.record) goes in the run's recordings folder, beside its folder, said on its timeline.
320
- { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, 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) } : {}) });
337
+ { ...deps.computerDeps, mode, workspace: ws.workspace, sealKey: deps.sealKey, 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) } : {}) });
321
338
  // The run's shell is its computer's (600 s) where one mounts its folder; with none, Archil's serverless exec in Mode 2
322
339
  // (295 s), and in Mode 1 none at all: no bash family, its folder being one of this server's own (run-tools.ts).
323
340
  // A desktop's or a phone's hold (the person's take-over) wraps its ports: a call made while the person holds it waits,
@@ -341,11 +358,20 @@ async function adapterSpec(launch, run, deps, claim, holds) {
341
358
  // tools unlock and its model needs, scoped to the run as the old per-run environment was, so one run's keys never reach
342
359
  // another's on this runner (claim-secrets.ts). MCP credentials are the other per-claim secret and come through mcp-claim.
343
360
  const toolEnv = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, launch);
361
+ // The run's own model key, when its caller handed one (model_key, sealed in its launch): opened at every claim, a reclaim
362
+ // after a crash among them, and held by the run's one redactor. Its model routes read it alone; its tools never do.
363
+ // 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.
364
+ const runKey = await claimModelKey({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, claim.runId);
365
+ const keyed = keyedAtClaim(runKey);
366
+ if (keyed)
367
+ withoutModelKeys(toolEnv);
368
+ if (runKey)
369
+ holdRunKey(cut, runKey);
344
370
  // The keys it opened join the run's one redactor before any tool or model request can echo one.
345
371
  holdClaimed(cut, toolEnv);
346
372
  // The route reads its model's key from the runner's environment, else the one the claim opened from the store: a key
347
- // saved in Settings → Model keys runs the next run with no restart (withModelKeys).
348
- const modelEnv = withModelKeys(deps.env, toolEnv);
373
+ // saved in Settings → Model keys runs the next run with no restart (withModelKeys). A run with its own key: that key.
374
+ const modelEnv = claimModelEnv(deps.env, toolEnv, runKey);
349
375
  const route = await deps.routeOf(modelAskOf(launch.model, body.model), modelEnv, "default", PI_WIRES, undefined, cut);
350
376
  await planBeforeRun(modelEnv, route.provider.plan ? { provider: PLAN_PROVIDER } : undefined);
351
377
  // The run's models of other tiers, for its learned workflows' nodes of a tier (learnedTierRoutes, filled once the seed's
@@ -374,9 +400,10 @@ async function adapterSpec(launch, run, deps, claim, holds) {
374
400
  // requests as that route books them.
375
401
  const tierWhy = new Map();
376
402
  if (revision.kind === "agentic" && granted.includes(SUBAGENT_TOOL)) {
377
- const savedKeys = await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
403
+ // A run with its own model key: its subagents' models carry that key too, and no saved key is read.
404
+ const savedKeys = keyed ? {} : await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env });
378
405
  holdClaimed(cut, savedKeys);
379
- const tierEnv = withModelKeys(deps.env, { ...savedKeys, ...toolEnv });
406
+ const tierEnv = claimModelEnv(deps.env, { ...savedKeys, ...toolEnv }, runKey);
380
407
  for (const tier of SUBAGENT_TIERS) {
381
408
  if (body.modelTiers?.[tier] === undefined && tierModelOf(tierEnv, tier) === undefined)
382
409
  continue;
@@ -388,17 +415,28 @@ async function adapterSpec(launch, run, deps, claim, holds) {
388
415
  }
389
416
  }
390
417
  }
391
- const adapter = piAdapter({
418
+ // The run's adapter is its runner's (runner/adapters/index.ts RunnerHarness: pi's, or the one a harness module's entry
419
+ // brings), made from the run's launch on its route. Its private files, where it keeps any, go in this claim's folder of
420
+ // the run's scratch (the CLI spec's layout), swept at the claim's end with the earlier claims' and any parent left empty.
421
+ // pi's own options (its extensions, tools, redactor, the model's catalog entry, hosted search, tiers, and the route's
422
+ // whole provider) are the harness's own options (`extra`), passed on as given.
423
+ const scratch = scratchFolder(deps.data, runRow.agentId, claim.runId);
424
+ const harnesses = join(scratch, "harness");
425
+ holds.hold({ scratch: { sweep: async () => (await import("./cli-run-spec.js")).sweepScratch(harnesses, claim.epoch, [harnesses, scratch, dirname(scratch)]) } });
426
+ const adapter = await runner.adapter({
392
427
  run,
428
+ model: route.model,
429
+ provider: route.provider,
430
+ ...(route.price ? { price: route.price } : {}),
431
+ sessionsDir: join(harnesses, String(claim.epoch)),
432
+ ...(route.fetch ? { fetch: route.fetch } : {}),
433
+ }, {
393
434
  // Read when the session opens (pi.ts), so the browser's extension pushed by bindNonHandTools below is in it.
394
435
  extensions: native,
395
436
  tools: piTools,
396
- model: route.model,
397
437
  provider: route.provider,
398
438
  redact: cut,
399
439
  ...(route.like ? { like: route.like } : {}),
400
- ...(route.price ? { price: route.price } : {}),
401
- ...(route.fetch ? { fetch: route.fetch } : {}),
402
440
  // The run's web_search is its provider's hosted search (the launch's plane, as its start resolved it): the session's
403
441
  // proxy admits that search's one request (it goes through the session's port: buildToolHost's `search`) and books it
404
442
  // with each search it ran.
@@ -467,11 +505,14 @@ async function adapterSpec(launch, run, deps, claim, holds) {
467
505
  // five); while the folder's revision replays or is held, the champion (the digest promoted last) serves in its place
468
506
  // (laidFor). Or the one the money rule stopped, over the agent's past runs (costLineOf): the agent takes the run.
469
507
  // The audits that finished since are written first (runner/audit.ts settleAudits): a hold they make decides this claim.
470
- const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey };
508
+ // Model spend beside the run that its caller's key does not pay for (claimSpendOff): a shadow audit, a replay check and
509
+ // the learning run's grade are skipped, in words, where the run brought its own key or the server holds none.
510
+ const spendOff = await claimSpendOff({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, runKey);
511
+ const audits = { store: deps.store, agentId: runRow.agentId, revisionId: runRow.revisionId, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff };
471
512
  if (launch.learning && !launch.replay && !launch.audit)
472
513
  await settleAudits(audits);
473
514
  const promotion = claimPromotion({
474
- store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey,
515
+ store: deps.store, agentId: runRow.agentId, runId: claim.runId, revisionId: runRow.revisionId, launch, context, log, folder: learningFolder, shown, sealKey: deps.sealKey, spendOff,
475
516
  });
476
517
  const firstChoice = learnsWorkflows(revision.kind, laidFlows) ? await workflowFirstOf(revision.kind, laidFlows, launch, log, () => pastRunsOverStore(deps.store, runRow.agentId), promotionGate(promotion), revision.body.outputSchema) : {};
477
518
  // A replay run runs only its revision, while it still replays: else its claim is refused (the run ends failed, no agent).
@@ -489,9 +530,10 @@ async function adapterSpec(launch, run, deps, claim, holds) {
489
530
  // The keys those tiers' models need (tierModelKeys: a key saved in Settings too, which claimSecrets opened only for the
490
531
  // run's own model), held by the run's one redactor, on the tiers' route env alone (withModelKeys, never enumerable),
491
532
  // never on the tools' (toolEnv).
492
- const tierKeys = await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
533
+ // A run with its own model key: its learned nodes' tiers carry that key too, and no saved key is read.
534
+ const tierKeys = keyed ? {} : await tierModelKeys({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, learnedTiers(workflows));
493
535
  holdClaimed(cut, tierKeys);
494
- const tierEnv = withModelKeys(deps.env, { ...toolEnv, ...tierKeys });
536
+ const tierEnv = claimModelEnv(deps.env, { ...toolEnv, ...tierKeys }, runKey);
495
537
  for (const [tier, routed] of await learnedTierRoutes(workflows, tierEnv, (tier) => deps.routeOf(undefined, tierEnv, tier, PI_WIRES, undefined, cut))) {
496
538
  if ("why" in routed)
497
539
  tierUnreachable.set(tier, routed.why);
@@ -588,11 +630,12 @@ async function adapterSpec(launch, run, deps, claim, holds) {
588
630
  // agent's folder on THIS claim's Archil disk (the proposal is checked against the seed on the disk, never this machine's
589
631
  // local path) — so the end-of-run step reads the run's own Workspace, the one the run worked in.
590
632
  // 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.
591
- // A run the promoted workflow served first starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
633
+ // A run the promoted workflow answered (path `workflow`) starts its shadow audit after the step, drawn at 1 in k (runner/audit.ts
592
634
  // withAudit): at its end, so the shadow's cap is what the run's own left.
593
635
  const endOfRun = launch.replay || launch.audit ? undefined : withAudit(learningEndOfRun(launch, {
594
636
  store: deps.store,
595
637
  data: deps.data,
638
+ spendOff,
596
639
  ...(deps.env ? { env: deps.env } : {}),
597
640
  // What the run must never learn beside the runner's secrets: the keys its claim handed it, every secret the server
598
641
  // keeps sealed (storeSecrets: the run's redactor holds the same list), and its sign-in's pointers, read back from the
@@ -606,9 +649,11 @@ async function adapterSpec(launch, run, deps, claim, holds) {
606
649
  learningFolder: archil === undefined
607
650
  ? (agentId) => learningFolderOf(deps.data, agentId)
608
651
  : (agentId) => learningWorkspace({ mode: "archil", agentId, archil }),
609
- }), { ...audits, launch });
652
+ }), { ...audits, launch, ...(run.redact ? { redact: run.redact } : {}) });
610
653
  return {
611
654
  adapter,
655
+ // Who keeps the run's visible record: its runner says (none: the adapter, as pi keeps its own).
656
+ ...(runner.record ? { record: runner.record } : {}),
612
657
  session,
613
658
  input,
614
659
  // A trigger's first input is its origin's, the launch's own owner flag kept (run-launch.ts keepInputOrigin).
@@ -623,6 +668,8 @@ async function adapterSpec(launch, run, deps, claim, holds) {
623
668
  // The run's MCP for a harness with its own client (mcp-run.ts), with its monid endpoints beside it (monid-run.ts):
624
669
  // the catalog tools the session mounts; absent when none.
625
670
  ...(catalog ? { mcp: catalog } : {}),
671
+ // The run's own model key: a command row opens it again before the next model request (a message's new key).
672
+ ...(runKey ? { modelKey: runKey } : {}),
626
673
  // The run's end-of-run step, when it learns (the spec's, which the loop prefers over its deps': adapter-loop.ts stepOf).
627
674
  ...(endOfRun ? { endOfRun } : {}),
628
675
  ...(start ? { learningLaid: laidOf(seedLaid) } : {}),
@@ -33,5 +33,7 @@ export interface RunnerHarness {
33
33
  }
34
34
  /** Every harness the runner runs, by name. */
35
35
  export declare const RUNNER_HARNESSES: Readonly<Record<string, RunnerHarness>>;
36
- /** The harness the launch names, or undefined when the runner runs none by that name. */
37
- export declare function resolveHarness(harness: string): RunnerHarness | undefined;
36
+ /** The harness the launch names, as `env`'s harness table has it (harness-table.ts harnessOf): a built-in one's runner is
37
+ * the runner's own (RUNNER_HARNESSES), one a harness module adds brings its own (HarnessEntry.runner). Undefined when
38
+ * the table has none by that name. `env`: the run's environment (this process's when not given). */
39
+ export declare function resolveHarness(harness: string, env?: NodeJS.ProcessEnv): RunnerHarness | undefined;