@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41

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 (173) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +129 -16
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/index-C3gNPz58.css +1 -0
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/email/account.d.ts +0 -1
  25. package/dist/email/account.js +3 -3
  26. package/dist/email/answer.d.ts +5 -0
  27. package/dist/email/answer.js +35 -0
  28. package/dist/email/mail.js +19 -26
  29. package/dist/email/names.d.ts +30 -0
  30. package/dist/email/names.js +34 -0
  31. package/dist/email/routes.d.ts +1 -0
  32. package/dist/email/routes.js +1 -1
  33. package/dist/email/tools.d.ts +11 -4
  34. package/dist/email/tools.js +91 -46
  35. package/dist/eval-feed.d.ts +26 -0
  36. package/dist/eval-feed.js +68 -0
  37. package/dist/eval-mailbox.d.ts +5 -2
  38. package/dist/eval-mailbox.js +14 -6
  39. package/dist/exa-keyless.d.ts +1 -1
  40. package/dist/exa-keyless.js +1 -1
  41. package/dist/feed/feed-faux.d.ts +62 -0
  42. package/dist/feed/feed-faux.js +123 -0
  43. package/dist/feed/fetch.d.ts +41 -0
  44. package/dist/feed/fetch.js +128 -0
  45. package/dist/feed/parse.d.ts +41 -0
  46. package/dist/feed/parse.js +300 -0
  47. package/dist/learn/check.d.ts +3 -1
  48. package/dist/learn/check.js +57 -2
  49. package/dist/learn/compile.d.ts +3 -2
  50. package/dist/learn/compile.js +7 -6
  51. package/dist/learn/promote.d.ts +25 -14
  52. package/dist/learn/promote.js +32 -14
  53. package/dist/learned-nodes.d.ts +21 -4
  54. package/dist/learned-nodes.js +21 -8
  55. package/dist/learned-workflow.d.ts +3 -3
  56. package/dist/learned-workflow.js +14 -5
  57. package/dist/learning-cost.d.ts +17 -8
  58. package/dist/learning-cost.js +12 -4
  59. package/dist/local-models.d.ts +7 -1
  60. package/dist/local-models.js +11 -5
  61. package/dist/mcp-oauth.d.ts +15 -1
  62. package/dist/mcp-oauth.js +39 -5
  63. package/dist/mcp-pin-first.d.ts +4 -2
  64. package/dist/mcp-pin-first.js +4 -3
  65. package/dist/mcp-servers-store.d.ts +58 -5
  66. package/dist/mcp-servers-store.js +136 -17
  67. package/dist/mcp.d.ts +2 -2
  68. package/dist/mcp.js +2 -2
  69. package/dist/observation/http.d.ts +4 -1
  70. package/dist/observation/http.js +5 -4
  71. package/dist/openapi.d.ts +1 -1
  72. package/dist/openapi.js +63 -27
  73. package/dist/port-models.d.ts +4 -1
  74. package/dist/port-models.js +1 -0
  75. package/dist/print.d.ts +6 -3
  76. package/dist/print.js +4 -2
  77. package/dist/refusal-words.d.ts +3 -0
  78. package/dist/refusal-words.js +3 -0
  79. package/dist/run-labels.d.ts +23 -0
  80. package/dist/run-labels.js +79 -0
  81. package/dist/run-launch.d.ts +2 -0
  82. package/dist/run-launch.js +2 -0
  83. package/dist/run-secrets.js +12 -4
  84. package/dist/run-view.d.ts +3 -4
  85. package/dist/run-view.js +26 -24
  86. package/dist/runner/adapter-loop.d.ts +6 -2
  87. package/dist/runner/adapter-loop.js +136 -22
  88. package/dist/runner/adapter-run-spec.d.ts +5 -0
  89. package/dist/runner/adapter-run-spec.js +75 -32
  90. package/dist/runner/beside.d.ts +6 -3
  91. package/dist/runner/beside.js +9 -7
  92. package/dist/runner/cli-run-spec.js +33 -26
  93. package/dist/runner/conformance/harness.js +69 -14
  94. package/dist/runner/conformance/subject.d.ts +4 -1
  95. package/dist/runner/journal-kinds.d.ts +22 -0
  96. package/dist/runner/journal-kinds.js +39 -0
  97. package/dist/runner/main.d.ts +1 -1
  98. package/dist/runner/main.js +2 -2
  99. package/dist/runner/mcp-claim.d.ts +3 -0
  100. package/dist/runner/mcp-claim.js +1 -1
  101. package/dist/runner/mcp-run.d.ts +4 -0
  102. package/dist/runner/mcp-run.js +5 -3
  103. package/dist/runner/model-route.d.ts +7 -3
  104. package/dist/runner/model-route.js +24 -9
  105. package/dist/runner/promotion.d.ts +16 -8
  106. package/dist/runner/promotion.js +178 -55
  107. package/dist/runner/workflow-first.d.ts +6 -5
  108. package/dist/runner/workflow-first.js +9 -7
  109. package/dist/runs-over-store.js +5 -2
  110. package/dist/sdk/runs.d.ts +7 -1
  111. package/dist/sdk/runs.js +19 -6
  112. package/dist/secret-cut.js +3 -1
  113. package/dist/secrets.js +3 -1
  114. package/dist/server.d.ts +27 -2
  115. package/dist/server.js +181 -56
  116. package/dist/store/dialect.d.ts +6 -0
  117. package/dist/store/dialect.js +2 -0
  118. package/dist/store/index.d.ts +1 -1
  119. package/dist/store/postgres/connection.d.ts +11 -5
  120. package/dist/store/postgres/connection.js +44 -17
  121. package/dist/store/postgres/dialect.js +6 -0
  122. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  123. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  124. package/dist/store/postgres/store.d.ts +7 -3
  125. package/dist/store/postgres/store.js +1 -0
  126. package/dist/store/schema.d.ts +9 -0
  127. package/dist/store/schema.js +26 -2
  128. package/dist/store/sqlite/connection.js +80 -8
  129. package/dist/store/sqlite/run-launch.d.ts +11 -0
  130. package/dist/store/sqlite/run-launch.js +8 -0
  131. package/dist/store/sqlite/run-patch.d.ts +2 -1
  132. package/dist/store/sqlite/run-patch.js +3 -2
  133. package/dist/store/sqlite/store.js +101 -26
  134. package/dist/store/sqlite/worker.d.ts +2 -0
  135. package/dist/store/sqlite/worker.js +13 -10
  136. package/dist/store/store.d.ts +53 -1
  137. package/dist/store-reads/journal.js +2 -1
  138. package/dist/store-reads/learning.d.ts +30 -13
  139. package/dist/store-reads/learning.js +130 -51
  140. package/dist/store-reads/runs.d.ts +4 -3
  141. package/dist/store-reads/runs.js +3 -2
  142. package/dist/store-view.js +4 -2
  143. package/dist/template-eval.d.ts +4 -0
  144. package/dist/template-eval.js +127 -50
  145. package/dist/templates.d.ts +24 -1
  146. package/dist/templates.js +129 -21
  147. package/dist/timeline/origin.d.ts +1 -1
  148. package/dist/timeline/origin.js +2 -2
  149. package/dist/tool-gate.d.ts +5 -3
  150. package/dist/tool-gate.js +5 -2
  151. package/dist/tools.d.ts +13 -0
  152. package/dist/tools.js +15 -10
  153. package/dist/trigger-adapter.d.ts +12 -36
  154. package/dist/trigger-adapters.js +2 -1
  155. package/dist/trigger-email.js +30 -77
  156. package/dist/trigger-feed.d.ts +12 -0
  157. package/dist/trigger-feed.js +371 -0
  158. package/dist/triggers.d.ts +27 -14
  159. package/dist/triggers.js +121 -80
  160. package/dist/webhooks.js +9 -5
  161. package/dist/workflow/decision-recovery.js +5 -2
  162. package/dist/workflow/decisions.d.ts +7 -0
  163. package/dist/workspace/computer-deps.d.ts +5 -1
  164. package/dist/workspace/computer-deps.js +2 -2
  165. package/dist/workspace/index.d.ts +1 -0
  166. package/dist/workspace/index.js +2 -0
  167. package/dist/workspace/resolve-computer.d.ts +32 -3
  168. package/dist/workspace/resolve-computer.js +47 -9
  169. package/launcher/agentrun-serve +6 -1
  170. package/package.json +10 -9
  171. package/templates/README.md +27 -2
  172. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  173. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -147,6 +147,45 @@ export function endedAnswer(tool, end) {
147
147
  const text = typeof end.output === "string" ? end.output : end.status === "interrupted" ? INTERRUPTED_TEXT : `The ${tool} call ended ${end.status}.`;
148
148
  return { text, isError: end.status !== "done" };
149
149
  }
150
+ /** The calls of `tool` `entries` show: a CLI's (agentrun.call.start and its end) and pi's (a pi.tool-result of it), each
151
+ * call id once, however many records say it. Run to a good end: a CLI's end done, a pi result that is no error. */
152
+ export function toolCalls(entries, tool) {
153
+ const started = new Set();
154
+ const ran = new Set();
155
+ const ended = new Set();
156
+ let unnamed = 0;
157
+ for (const entry of entries) {
158
+ if (entry.kind === KINDS.callStart && entry.data.tool === tool)
159
+ started.add(entry.data.callId);
160
+ else if (entry.kind === KINDS.callEnd && started.has(entry.data.callId)) {
161
+ ended.add(entry.data.callId);
162
+ if (entry.data.status === "done")
163
+ ran.add(entry.data.callId);
164
+ }
165
+ else if (entry.kind === "pi.tool-result") {
166
+ const result = entry.model?.[0];
167
+ if (result?.toolName !== tool)
168
+ continue;
169
+ const id = typeof result.toolCallId === "string" && result.toolCallId ? result.toolCallId : undefined;
170
+ if (id)
171
+ ended.add(id);
172
+ if (result.isError === true)
173
+ continue;
174
+ if (id)
175
+ ran.add(id);
176
+ else
177
+ unnamed++;
178
+ }
179
+ }
180
+ return { ran, unnamed, ended };
181
+ }
182
+ /** How many calls of `tool` `entries` show run to a good end (toolCalls): a call refused, denied, failed or not ended is
183
+ * not counted. What a tool's own ask counts (tools.ts AskContext.ran), with the calls its gate let through and that
184
+ * have no result yet (adapterRunGate). */
185
+ export function ranCalls(entries, tool) {
186
+ const calls = toolCalls(entries, tool);
187
+ return calls.ran.size + calls.unnamed;
188
+ }
150
189
  /** Whether `entries` hold a call's finished result: an agentrun.call.end not cut (a CLI's call), or a pi.tool-result
151
190
  * for it that pi did not write for an abort (pi's diagnostics code `aborted`). */
152
191
  function finished(entries, callId) {
@@ -68,7 +68,7 @@ export declare function runEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
68
68
  * provider loader in place of the computer package's. Under --faux (the runs' environment names the faux model, as a
69
69
  * --faux server's and a `runner --faux` give it), --faux's computers are beside them, as the server's start check
70
70
  * reads them (server.ts computerReady): a run on the faux desktop is claimed, and its live view opened, the real way. */
71
- export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub">) => {
71
+ export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub" | "dial">) => {
72
72
  computerForClaim: typeof import("../workspace/computer-deps.js").claimComputer;
73
73
  computerDeps: ComputerDeps;
74
74
  factories: import("../computer-keys.js").ProviderFactories;
@@ -70,9 +70,9 @@ export async function openRunnerStore(dataDir, env, warn, url) {
70
70
  }
71
71
  }
72
72
  /** The runner's own secrets, which a run never gets, not even in the runner's in-process environment: the server's
73
- * token and API key, the seal key (the runner holds it as its sealKey), and the store's connection (its URL holds a
73
+ * tokens (the token and the token list) and API key, the seal key (the runner holds it as its sealKey), and the store's connection (its URL holds a
74
74
  * database password). */
75
- const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name.startsWith("AGENTRUN_STORE_");
75
+ const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_TOKENS" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name.startsWith("AGENTRUN_STORE_");
76
76
  /** A run's environment as the runner hands its loops (AdapterSpecDeps.env): this process's, less the runner's own
77
77
  * secrets, with every other secret the launcher's pipe handed it (a model key, a tool key, a box key) readable by name
78
78
  * but not enumerable, as secrets.ts withSecrets makes them: code that reads one by name (the model route) finds it, and
@@ -34,6 +34,9 @@ export interface McpClaimOptions {
34
34
  /** Whether this runner may reach a loopback address (McpForClaimOptions.loopback): a refresh's request to a loopback
35
35
  * authorization server is sent only then. Absent, never. */
36
36
  loopback?: boolean;
37
+ /** The own addresses of the local-install server beside this runner (McpForClaimOptions.own): a loopback authorization
38
+ * server on one of their ports is refused, as the server refuses it. */
39
+ own?: readonly string[];
37
40
  /** For a github_app server (auth github_app, nothing sealed): the server's GitHub App mint and the run's repository
38
41
  * (runner/mcp-github.ts). None: such a server's calls are refused in words. */
39
42
  githubApp?: GithubAppAccess;
@@ -117,7 +117,7 @@ export async function mcpClaim(options) {
117
117
  if (!set.tokens.refresh_token)
118
118
  return { refused: true };
119
119
  const call = AbortSignal.timeout(callMs);
120
- const reach = { allowed: await privateOAuthHosts(store), loopback: options.loopback === true };
120
+ const reach = { allowed: await privateOAuthHosts(store), loopback: options.loopback === true, own: options.own ?? [] };
121
121
  for (let tried = 0; tried < tries && !call.aborted; tried++) {
122
122
  // Every try before this one provably never left: nothing is spent.
123
123
  if (stop.aborted)
@@ -38,6 +38,10 @@ export interface McpForClaimOptions {
38
38
  /** Whether this runner may reach an MCP server whose URL is on loopback (AdapterSpecDeps.mcpLoopback): only a runner
39
39
  * beside a local-install server is. Absent, never. */
40
40
  readonly loopback?: boolean;
41
+ /** The own addresses of the local-install server beside this runner (AdapterSpecDeps.mcpOwn, Serve.own): a loopback
42
+ * URL on one of their ports is refused, as the server refuses it, so a run never reaches that server through an MCP
43
+ * server's address, its authorization server's or a pin's listing. */
44
+ readonly own?: readonly string[];
41
45
  /** For tests: the authorization servers' network, a refresh's bound, the gateway's upstream fetch and bounds, and the
42
46
  * timer a github_app token's refresh is armed on. */
43
47
  readonly network?: OAuthNetwork;
@@ -30,10 +30,11 @@ export async function mcpForClaim(options) {
30
30
  sealKey: options.sealKey,
31
31
  signal: held.signal,
32
32
  // A run whose revision has no pin (one made before the upgrade) pins it here, listing as a save does.
33
- pinListing: registryListing(options.store, options.sealKey, { loopback: options.loopback === true, ...(options.network ? { network: options.network } : {}), ...(githubApp ? { githubApp } : {}), ...(options.githubMcpOrigin ? { appOrigin: options.githubMcpOrigin } : {}) }),
33
+ pinListing: registryListing(options.store, options.sealKey, { loopback: options.loopback === true, own: options.own ?? [], ...(options.network ? { network: options.network } : {}), ...(githubApp ? { githubApp } : {}), ...(options.githubMcpOrigin ? { appOrigin: options.githubMcpOrigin } : {}) }),
34
34
  ...(options.bounds ? { bounds: options.bounds } : {}),
35
35
  ...(options.network ? { network: options.network } : {}),
36
36
  ...(options.loopback ? { loopback: true } : {}),
37
+ ...(options.own ? { own: options.own } : {}),
37
38
  ...(githubApp ? { githubApp } : {}),
38
39
  ...(options.githubMcpOrigin ? { githubMcpOrigin: options.githubMcpOrigin } : {}),
39
40
  ...(options.githubTimer ? { githubTimer: options.githubTimer } : {}),
@@ -57,9 +58,10 @@ export async function mcpForClaim(options) {
57
58
  // private-network hosts read now, and dialled at the address checked: a name that resolves somewhere private since the
58
59
  // save, or a host the owner no longer allows, is refused unsent. A URL on loopback is reached only by a runner told
59
60
  // so by the local-install server beside it, in its own process (options.loopback): never by what a store says, so
60
- // one host's local install never opens loopback for another host's runner on a shared store.
61
+ // one host's local install never opens loopback for another host's runner on a shared store; and never at that
62
+ // server's own ports (options.own).
61
63
  reach: async (url, signal) => {
62
- const at = await mcpServerAt(new URL(url), signal, network, { allowed: await privateOAuthHosts(options.store), loopback: options.loopback === true });
64
+ const at = await mcpServerAt(new URL(url), signal, network, { allowed: await privateOAuthHosts(options.store), loopback: options.loopback === true, own: options.own ?? [] });
63
65
  return "refused" in at ? { refused: at.refused } : { send: dialAt(network, at.address, options.fetch ?? fetch) };
64
66
  },
65
67
  beforeCall: step.beforeCall,
@@ -49,7 +49,8 @@ export interface ModelRoute {
49
49
  * takes images) and its input limits (an image's most size), which pi's session and its read size an image by; on a
50
50
  * wire that carries its reasoning (Responses), also whether it reasons, its window, its output ceiling, and the effort
51
51
  * each thinking level asks for (`thinkingLevelMap`: a level mapped to null sends no effort, so pi's thinking off asks
52
- * a model that takes no "none" for none, gpt-6.1-sol's case). */
52
+ * a model that takes no "none" for none, gpt-6.1-sol's case). On the route's own translation, a model that reasons
53
+ * asks its level by name (LEVELS_BY_NAME: `adaptiveThinking`), so the run's effort reaches it. */
53
54
  readonly like?: {
54
55
  readonly reasoning?: boolean;
55
56
  readonly contextWindow?: number;
@@ -57,6 +58,7 @@ export interface ModelRoute {
57
58
  readonly input?: readonly string[];
58
59
  readonly inputLimits?: unknown;
59
60
  readonly developerRole?: boolean;
61
+ readonly adaptiveThinking?: boolean;
60
62
  readonly thinkingLevelMap?: ThinkingLevelMap;
61
63
  };
62
64
  /** A request's price from its usage (the proxy's booking reads it): pi-ai's calculateCost, tiers included. */
@@ -128,8 +130,10 @@ type PiMessage = {
128
130
  export declare function routeOf(model: string | PinnedModel | undefined, env?: NodeJS.ProcessEnv, tier?: Tier, wires?: readonly Wire[], upstream?: typeof fetch, redact?: Redact): Promise<ModelRoute>;
129
131
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
130
132
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
131
- * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
132
- export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch): typeof fetch;
133
+ * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). A request pi-ai
134
+ * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
135
+ * as one the model proxy sends there does; a request to any other provider carries none. */
136
+ export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch, env?: NodeJS.ProcessEnv): typeof fetch;
133
137
  /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
134
138
  * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
135
139
  * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
@@ -15,7 +15,7 @@
15
15
  // the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
- import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
18
+ import { onOpenRouter, openRouterAttribution, ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
19
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
20
20
  import { providerFor } from "../provider.js";
21
21
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
@@ -73,12 +73,11 @@ export async function routeOf(model, env = process.env, tier = "default", wires
73
73
  };
74
74
  }
75
75
  // The translation writes an answer's cost in its usage only where pi-ai read the provider's own (OpenRouter's): the
76
- // proxy reads it on ROUTE_ORIGIN (statesUsageCost).
77
- return { ...route, provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
76
+ // proxy reads it on ROUTE_ORIGIN (statesUsageCost). A model that reasons is given to pi's session as one that asks its
77
+ // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
78
+ // model, mapped and clamped by its own catalog entry.
79
+ return { ...route, ...(target.reasoning ? { like: { ...sees, ...LEVELS_BY_NAME } } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
78
80
  }
79
- /** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
80
- const OPENROUTER_HOST = "openrouter.ai";
81
- const onOpenRouter = (origin) => URL.canParse(origin) && new URL(origin).hostname === OPENROUTER_HOST;
82
81
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
83
82
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
84
83
  /** How much of an answer's text the error tap keeps: its end, where a stream's error event is. */
@@ -107,8 +106,11 @@ function tapped(upstream) {
107
106
  }
108
107
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
109
108
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
110
- * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
111
- export function messagesFetch(models, target, redact = keepText, upstream) {
109
+ * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). A request pi-ai
110
+ * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
111
+ * as one the model proxy sends there does; a request to any other provider carries none. */
112
+ export function messagesFetch(models, target, redact = keepText, upstream, env = process.env) {
113
+ const attribution = piOnOpenRouter(target) ? openRouterAttribution(env) : {};
112
114
  // A tool call's id as Messages carries it (letters, digits, _ and -), and back to the provider's own on its result.
113
115
  const providerIds = new Map();
114
116
  const messagesId = (id) => {
@@ -126,7 +128,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
126
128
  // On OpenRouter, each answer's end is kept as it streams by, for a rate limit it ends in (limitedWords).
127
129
  const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
128
130
  const sendWith = tap?.fetch ?? upstream;
129
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
131
+ const level = levelOf(body);
132
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(level ? { reasoning: level } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}), ...(Object.keys(attribution).length ? { headers: attribution } : {}) };
130
133
  const events = models.streamSimple(target, context, streamOptions);
131
134
  const encoder = new TextEncoder();
132
135
  const stream = new ReadableStream({
@@ -377,6 +380,18 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
377
380
  }
378
381
  /** pi-ai's stop reason as Messages says it. */
379
382
  const stopReasonOf = (reason) => (reason === "toolUse" ? "tool_use" : reason === "length" ? "max_tokens" : "end_turn");
383
+ /** pi-ai's thinking levels past off, each asked by its own name. */
384
+ const NAMED_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"];
385
+ /** How the route's translation has pi's session register a model that reasons: on Messages, with adaptive thinking whose
386
+ * effort is the level's own name (a thinkingLevelMap of each level to itself), so a request carries the session's level
387
+ * as it is, `output_config.effort`, and no budget the translation would have to read a level back from. Off maps to
388
+ * nothing: a session at off sends thinking disabled, and no level reaches the model. */
389
+ const LEVELS_BY_NAME = { reasoning: true, adaptiveThinking: true, thinkingLevelMap: Object.fromEntries(NAMED_LEVELS.map((level) => [level, level])) };
390
+ /** The thinking level a Messages request from pi's session asks (LEVELS_BY_NAME), else undefined: none asked, or off. */
391
+ function levelOf(body) {
392
+ const effort = body.output_config?.effort;
393
+ return body.thinking?.type === "adaptive" && NAMED_LEVELS.includes(effort) ? effort : undefined;
394
+ }
380
395
  const textOf = (content) => (typeof content === "string" ? content : (content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n"));
381
396
  /** A Messages block as pi-ai's part: a text as text, a base64 image as an image; anything else none. */
382
397
  const partOf = (block) => block.type === "text" ? [{ type: "text", text: block.text ?? "" }] : block.type === "image" && block.source?.data ? [{ type: "image", data: block.source.data, mimeType: block.source.media_type ?? "image/png" }] : [];
@@ -4,7 +4,7 @@ import { type RunLaunch } from "../run-launch.js";
4
4
  import { type Store } from "../store/store.js";
5
5
  import { type ReplayCalls } from "../learn/replay-calls.js";
6
6
  import { type Json } from "../validate.js";
7
- import { type PromotionRecord, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
7
+ import { type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
8
  import { type FirstChoice, type Promoted } from "./workflow-first.js";
9
9
  import type { LearningFolder } from "../learn/folder.js";
10
10
  import type { Shown } from "../learning.js";
@@ -36,7 +36,7 @@ export interface PromotionDeps {
36
36
  * it held none by that name. Absent: no champion serves. */
37
37
  readonly champion?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>;
38
38
  /** The digest of the learned workflow `name` the learning folder's main holds now (the newest revision), or undefined
39
- * when it holds none by that name. Absent: no revision supersedes another. */
39
+ * when it holds none by that name. Absent: no revision queues behind another's replay. */
40
40
  readonly newest?: (name: string) => Promise<string | undefined>;
41
41
  /** The learned workflow an earlier claim of this run served first (its WORKFLOW_FIRST entry, answered or handed back:
42
42
  * workflow-first.ts servedOf), or undefined for a run no claim served yet: a run already executing keeps its revision
@@ -61,7 +61,7 @@ export declare function claimPromotion(deps: Omit<PromotionDeps, "commit" | "cha
61
61
  /** A replay run's claim (launch.replay) of run `runId`, once its first choice is made: refused (ClaimRefused: the run ends
62
62
  * failed, no agent turn, nothing sent) unless its revision's record still says replaying and names it among its runs (it
63
63
  * is reserved before its runs are created), or has none (trimmed), and the claim laid that revision to serve it. A
64
- * superseded, promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
64
+ * promoted or held revision's replay run never runs (a cancel that never reached it included), nor an older
65
65
  * replay's leftover once its revision replays again; one whose workflow is not laid at its digest (the seed could not be
66
66
  * read, the folder moved on) never falls to the agent's path. Any other run: nothing to check. */
67
67
  export declare function replayClaimed(store: Pick<Store, "settings">, agentId: string, runId: string, launch: RunLaunch, choice: FirstChoice): Promise<void>;
@@ -70,10 +70,18 @@ export declare function replayClaimed(store: Pick<Store, "settings">, agentId: s
70
70
  * the laid one is not the digest it replays (the replay then fails, never scoring another revision). Any other run's,
71
71
  * as laid. */
72
72
  export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWorkflow[]): LearnedWorkflow[];
73
+ /** The learned workflows a run's learned_workflow tool runs, once its first choice is made: what serves, never a
74
+ * revision its promotion has not promoted. The one its first choice served or the money rule stopped (laidFor: its
75
+ * champion in place of the laid revision) as chosen; any other the records name, its champion (championOf: the laid
76
+ * text when that is the champion, else its text at its record's commit), and none while nothing of it serves (none
77
+ * promoted yet, or the champion held): a revision replaying, queued, held or never decided is never handed to the
78
+ * agent to run in its place. One the records never named (no run's input fit it, so no claim asked) runs as laid. A
79
+ * replay run's as laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
80
+ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
73
81
  /** The gate workflowFirstOf asks (its `promoted`), at every run's claim, a queued run's included: the workflow that serves
74
82
  * this run first. A run already executing keeps the revision an earlier claim of it served (keptFor). Else the laid
75
83
  * revision (`workflow` at `digest`, the folder's revision as the run's seed holds it) has its promotion moved on (decide:
76
- * a replay started, settled or superseded, a dry-run promote), and then servingNow alone says who serves: the champion
84
+ * a replay started, queued or settled, a dry-run promote), and then servingNow alone says who serves: the champion
77
85
  * (championOf), the laid text when it is the champion, its own text read from its record's commit when not; undefined
78
86
  * when none serves (the agent takes the run). A digest's own record never says it serves. */
79
87
  export declare const promotionGate: (deps: PromotionDeps) => Promoted;
@@ -105,7 +113,7 @@ export interface ReplayAsk {
105
113
  * held on (heldOn), which it promotes only once it answered on: the claim's picker (inputsFor). Its runs end as a claim's
106
114
  * do, and it is decided by the claim path's settle: at a claim that lays the revision, or at its read (replayView).
107
115
  * Refused (ReplayRefused): no such workflow or revision; one replaying already, or another revision of it replaying (one
108
- * at a time); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
116
+ * at a time, never queued by a person: a queued revision is one a run's claim found newest); a promoted one (it serves already); fewer than REPLAY_MIN graded inputs it fits (a replay on fewer could
109
117
  * only hold it: settle scores none of it), refused before anything is reserved; an agent that does not learn here. The
110
118
  * replay's id and its inputs. */
111
119
  export declare function askReplay(ask: ReplayAsk, name: string, digest: string, inputs: "held" | number): Promise<{
@@ -113,8 +121,8 @@ export declare function askReplay(ask: ReplayAsk, name: string, digest: string,
113
121
  inputs: number;
114
122
  }>;
115
123
  /** A replay as its read answers it (GET .../replays/{replay_id}). `status`: `running` while its record says replaying,
116
- * `done` once promoted or held, `failed` when superseded (its runs cancelled) or when none of its runs started by its
117
- * deadline (nothing was replayed; held, its `reason` says so). `outcomes`: what its own runs did (outcomesOf), so far
124
+ * `done` once promoted or held, `failed` when none of its runs started by its deadline (nothing was replayed; held, its
125
+ * `reason` says so). A replay is never cancelled for a newer revision: that one queues behind it. `outcomes`: what its own runs did (outcomesOf), so far
118
126
  * while it runs, and once decided as its record kept them, whatever the agent's grades kept now; never the thresholds'
119
127
  * reading (a run answered under its guard's threshold stays answered: `score` hands it back). `score` and `cost_usd`
120
128
  * the decided record's, else the runs ended so far at the revision's serving thresholds, and null while a run's cost
@@ -128,7 +136,7 @@ type ReplayView = {
128
136
  readonly outcomes: ReplayOutcomes;
129
137
  readonly score: ReplayScore;
130
138
  readonly cost_usd: number | null;
131
- readonly decided?: PromotionRecord["decided"];
139
+ readonly decided?: "promote" | "hold";
132
140
  readonly reason?: string;
133
141
  };
134
142
  /** Reads replay `id` of `name` at `digest`, settling it first as a claim of its revision would (the claim path's settle)