@parcha/agentrun-serve 0.1.0-beta.54 → 0.1.0-beta.55

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 (190) hide show
  1. package/CHANGELOG.md +110 -2
  2. package/README.md +266 -88
  3. package/dist/adapters.d.ts +10 -0
  4. package/dist/adapters.js +46 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +6 -13
  7. package/dist/agents-store.js +6 -5
  8. package/dist/api-only.d.ts +16 -4
  9. package/dist/api-only.js +21 -7
  10. package/dist/cli.js +5 -3
  11. package/dist/composio-made.d.ts +26 -1
  12. package/dist/composio-made.js +39 -2
  13. package/dist/composio-preset.d.ts +3 -2
  14. package/dist/composio-preset.js +46 -14
  15. package/dist/computer-held-routes.js +2 -3
  16. package/dist/computer-setting.d.ts +4 -2
  17. package/dist/computer-setting.js +0 -2
  18. package/dist/computers-running.d.ts +8 -0
  19. package/dist/computers-running.js +27 -0
  20. package/dist/console/assets/backend-D5EmB4N3.js +166 -0
  21. package/dist/console/assets/index-DUYLaqiR.js +746 -0
  22. package/dist/console/assets/index-DYhU4adm.css +1 -0
  23. package/dist/console/index.html +2 -2
  24. package/dist/docker-host-addresses.d.ts +23 -3
  25. package/dist/docker-host-addresses.js +90 -18
  26. package/dist/exa-keyless.d.ts +2 -3
  27. package/dist/exa-keyless.js +43 -127
  28. package/dist/firecrawl-keyless.d.ts +41 -0
  29. package/dist/firecrawl-keyless.js +152 -0
  30. package/dist/handed-secret.d.ts +3 -1
  31. package/dist/handed-secret.js +4 -2
  32. package/dist/harness-keys.d.ts +98 -0
  33. package/dist/harness-keys.js +247 -0
  34. package/dist/harness-recipe-entry.d.ts +14 -9
  35. package/dist/harness-recipe-entry.js +25 -14
  36. package/dist/harness-table.d.ts +16 -1
  37. package/dist/harness-table.js +19 -7
  38. package/dist/harness.d.ts +4 -0
  39. package/dist/harness.js +12 -1
  40. package/dist/host-check.d.ts +2 -0
  41. package/dist/host-check.js +6 -0
  42. package/dist/import-summary.d.ts +1 -1
  43. package/dist/import-summary.js +1 -1
  44. package/dist/import.d.ts +5 -5
  45. package/dist/import.js +54 -67
  46. package/dist/keyless-mcp.d.ts +36 -0
  47. package/dist/keyless-mcp.js +127 -0
  48. package/dist/learn/audit.d.ts +3 -3
  49. package/dist/learn/audit.js +3 -3
  50. package/dist/learn/commit.d.ts +8 -7
  51. package/dist/learn/commit.js +60 -20
  52. package/dist/learn/compile.d.ts +4 -3
  53. package/dist/learn/compile.js +7 -5
  54. package/dist/learn/folder.d.ts +16 -3
  55. package/dist/learn/folder.js +46 -13
  56. package/dist/learn/promote.d.ts +37 -13
  57. package/dist/learn/promote.js +112 -40
  58. package/dist/learn/secrets.js +10 -2
  59. package/dist/learning-routes.d.ts +22 -17
  60. package/dist/learning-routes.js +40 -39
  61. package/dist/learning.js +2 -2
  62. package/dist/manifest.d.ts +10 -0
  63. package/dist/manifest.js +30 -0
  64. package/dist/mcp-pin-first.d.ts +4 -2
  65. package/dist/mcp-pin-first.js +5 -2
  66. package/dist/mcp-secret-writes.d.ts +16 -7
  67. package/dist/mcp-secret-writes.js +35 -27
  68. package/dist/mcp-servers-store.d.ts +30 -6
  69. package/dist/mcp-servers-store.js +112 -28
  70. package/dist/mcp-sources.d.ts +10 -2
  71. package/dist/mcp-sources.js +9 -2
  72. package/dist/mcp-store.d.ts +13 -7
  73. package/dist/mcp-store.js +12 -9
  74. package/dist/model-form.d.ts +3 -2
  75. package/dist/model-form.js +11 -7
  76. package/dist/model.d.ts +20 -4
  77. package/dist/model.js +68 -9
  78. package/dist/native/history.d.ts +1 -1
  79. package/dist/native/history.js +2 -2
  80. package/dist/ollama-provider.d.ts +92 -0
  81. package/dist/ollama-provider.js +495 -0
  82. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  83. package/dist/openapi.js +127 -37
  84. package/dist/page.d.ts +11 -3
  85. package/dist/page.js +22 -7
  86. package/dist/place-offers.d.ts +17 -1
  87. package/dist/place-offers.js +46 -5
  88. package/dist/print.js +1 -1
  89. package/dist/purged-workflow.d.ts +35 -7
  90. package/dist/purged-workflow.js +73 -26
  91. package/dist/run-computer.d.ts +2 -0
  92. package/dist/run-computer.js +2 -0
  93. package/dist/run-files.d.ts +4 -0
  94. package/dist/run-files.js +4 -0
  95. package/dist/run-keys.d.ts +2 -4
  96. package/dist/run-keys.js +6 -7
  97. package/dist/run-launch.d.ts +4 -0
  98. package/dist/run-launch.js +4 -0
  99. package/dist/run-reads-over-store.d.ts +3 -2
  100. package/dist/run-reads-over-store.js +66 -2
  101. package/dist/run-secrets.js +5 -2
  102. package/dist/runner/adapter-loop.d.ts +6 -3
  103. package/dist/runner/adapter-loop.js +34 -15
  104. package/dist/runner/adapter-run-spec.d.ts +3 -0
  105. package/dist/runner/adapter-run-spec.js +5 -3
  106. package/dist/runner/audit.js +8 -4
  107. package/dist/runner/beside.d.ts +2 -1
  108. package/dist/runner/beside.js +6 -2
  109. package/dist/runner/claim-secrets.d.ts +5 -8
  110. package/dist/runner/claim-secrets.js +6 -0
  111. package/dist/runner/cli-run-spec.d.ts +1 -1
  112. package/dist/runner/cli-run-spec.js +38 -6
  113. package/dist/runner/harness-loops.d.ts +22 -9
  114. package/dist/runner/harness-loops.js +21 -11
  115. package/dist/runner/held.d.ts +3 -0
  116. package/dist/runner/learning-end.d.ts +1 -1
  117. package/dist/runner/learning-end.js +8 -3
  118. package/dist/runner/loop-contract.d.ts +5 -4
  119. package/dist/runner/main.js +4 -2
  120. package/dist/runner/mcp-claim.d.ts +3 -0
  121. package/dist/runner/mcp-claim.js +26 -2
  122. package/dist/runner/mcp-run.d.ts +3 -0
  123. package/dist/runner/mcp-run.js +2 -1
  124. package/dist/runner/metrics.d.ts +10 -10
  125. package/dist/runner/metrics.js +19 -38
  126. package/dist/runner/model-route.d.ts +3 -0
  127. package/dist/runner/model-route.js +6 -2
  128. package/dist/runner/promotion.d.ts +15 -9
  129. package/dist/runner/promotion.js +25 -15
  130. package/dist/runner/run-child-host.js +17 -7
  131. package/dist/runner/run-child.js +3 -1
  132. package/dist/runner/sdk-loop.js +2 -0
  133. package/dist/runner/workflow-loop.d.ts +2 -2
  134. package/dist/runner/workflow-loop.js +1 -2
  135. package/dist/runner/workflow-spec.d.ts +1 -1
  136. package/dist/runner/workflow-spec.js +6 -6
  137. package/dist/sdk/check.d.ts +4 -1
  138. package/dist/sdk/check.js +2 -1
  139. package/dist/sdk/runs.d.ts +2 -2
  140. package/dist/sdk/runs.js +8 -6
  141. package/dist/secret-cut.js +2 -1
  142. package/dist/secret-writes.d.ts +3 -2
  143. package/dist/secret-writes.js +1 -1
  144. package/dist/server.d.ts +44 -8
  145. package/dist/server.js +283 -108
  146. package/dist/standard-webhooks.d.ts +11 -0
  147. package/dist/standard-webhooks.js +20 -2
  148. package/dist/store/index.d.ts +1 -1
  149. package/dist/store/schema.js +5 -2
  150. package/dist/store/sqlite/store.js +90 -34
  151. package/dist/store/store.d.ts +54 -14
  152. package/dist/store-reads/journal.d.ts +7 -2
  153. package/dist/store-reads/journal.js +9 -6
  154. package/dist/store-reads/learning.d.ts +12 -9
  155. package/dist/store-reads/learning.js +18 -24
  156. package/dist/store-view.d.ts +0 -5
  157. package/dist/store-view.js +9 -8
  158. package/dist/template-eval.d.ts +49 -4
  159. package/dist/template-eval.js +168 -45
  160. package/dist/template-import.js +4 -2
  161. package/dist/templates.d.ts +5 -3
  162. package/dist/templates.js +19 -40
  163. package/dist/timeline/labels.d.ts +2 -2
  164. package/dist/timeline/labels.js +2 -2
  165. package/dist/timeline/timeline.d.ts +2 -2
  166. package/dist/timeline/timeline.js +1 -1
  167. package/dist/tool-plane.d.ts +17 -9
  168. package/dist/tool-plane.js +38 -17
  169. package/dist/tools.js +2 -2
  170. package/dist/trigger-launch-hook.d.ts +16 -8
  171. package/dist/trigger-launch-hook.js +32 -23
  172. package/dist/trigger-targets.d.ts +18 -8
  173. package/dist/trigger-targets.js +42 -19
  174. package/dist/triggers.d.ts +85 -23
  175. package/dist/triggers.js +303 -96
  176. package/dist/web-fake.js +3 -3
  177. package/dist/web-fetch-direct.d.ts +4 -0
  178. package/dist/web-fetch-direct.js +8 -1
  179. package/dist/web-fetch.d.ts +12 -3
  180. package/dist/web-fetch.js +47 -14
  181. package/dist/web-search.d.ts +33 -4
  182. package/dist/web-search.js +100 -41
  183. package/dist/webhooks.js +4 -5
  184. package/launcher/agentrun-serve +5 -1
  185. package/package.json +17 -13
  186. package/templates/README.md +2 -2
  187. package/dist/console/assets/index-B_85An2t.js +0 -745
  188. package/dist/console/assets/index-n1YsbnYh.css +0 -1
  189. package/dist/import-sources.d.ts +0 -116
  190. package/dist/import-sources.js +0 -693
@@ -1,4 +1,6 @@
1
- import type { RunLaunch } from "../run-launch.js";
1
+ import { RECIPE_SIGN_IN_PERSON_ONLY } from "../harness-keys.js";
2
+ import type { SealedKeys } from "../store/index.js";
3
+ import { type RunLaunch } from "../run-launch.js";
2
4
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
3
5
  import { ClaimRefused, type LoopFactory } from "./loop-contract.js";
4
6
  /** A claimed run whose harness this host's memory never holds: its message is the host's words (neverFits). A claim
@@ -6,15 +8,26 @@ import { ClaimRefused, type LoopFactory } from "./loop-contract.js";
6
8
  export declare class NeverFits extends ClaimRefused {
7
9
  name: string;
8
10
  }
9
- /** The words a scheduled or triggered run on a plan-billed harness recipe is refused in (harness-recipe-entry.ts
10
- * serverRoute): such a run takes keys saved for that harness, never its owner's own sign-in, and none are saved yet. */
11
- export declare const RECIPE_SIGN_IN_PERSON_ONLY = "A scheduled or triggered run on a harness recipe billed to its vendor's plan runs on keys saved for that harness, never on its owner's own sign-in, and this server saves no harness's keys yet: start this run yourself, or run the agent on a harness billed through this server's model proxy.";
12
- /** Refuses at its claim a run no person started (a schedule's, a trigger's: launch.trigger) on a plan-billed recipe's
13
- * harness (harness-table.ts recipeHarness), on every path a claim takes (run-child-host.ts staysInRunner, and here). */
14
- export declare function refuseRecipeTriggerRun(env: NodeJS.ProcessEnv, harness: string, launch: Pick<RunLaunch, "trigger">): void;
11
+ export { RECIPE_SIGN_IN_PERSON_ONLY };
12
+ /** Refuses at its claim a run no person started (a schedule's, a trigger's, a learned workflow's audit shadow or replay:
13
+ * personStarted) on a plan-billed recipe's harness (harness-table.ts recipeKeysOf) unless every key it runs on is saved for that harness (harness-keys.ts), on
14
+ * every path a claim takes (run-child-host.ts staysInRunner, and here): the early word, before a process is made. Rows
15
+ * are counted, never opened; the claim's spec opens them and refuses it again if not every one opened, since a row
16
+ * counted here can be gone or not open by then (cli-run-spec.ts). */
17
+ export declare function refuseRecipeTriggerRun(deps: {
18
+ readonly env?: NodeJS.ProcessEnv;
19
+ readonly store: {
20
+ readonly sealedKeys: Pick<SealedKeys, "all">;
21
+ };
22
+ }, harness: string, launch: Pick<RunLaunch, "trigger" | "audit" | "replay">): Promise<void>;
15
23
  /** The dispatch's `resolve`, built from the runner's deps: it reads the run's revision (for a workflow revision) and
16
- * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words). */
17
- export declare function resolveRunnerLoop(given: AdapterSpecDeps): (harness: string, launch: RunLaunch, runId: string) => Promise<LoopFactory | undefined>;
24
+ * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words).
25
+ * `keysCounted`: a run's own process (run-child.ts), whose runner counted its harness's key rows before it made the
26
+ * process (run-child-host.ts staysInRunner). The process's store lists no rows (STORE_CALLS has no sealedKeys.all), so
27
+ * it never counts them again; its claim's spec opens the claim's own keys and refuses the run if not every one opened. */
28
+ export declare function resolveRunnerLoop(given: AdapterSpecDeps, options?: {
29
+ readonly keysCounted?: boolean;
30
+ }): (harness: string, launch: RunLaunch, runId: string) => Promise<LoopFactory | undefined>;
18
31
  /** The loop factory the runner holds for every run (its createLoop), built from the runner's deps over the one store: the
19
32
  * dispatch (dispatch.ts) reads each run's launch and asks resolveRunnerLoop for its harness loop. The server
20
33
  * start and the test server pass this to startRunner. */
@@ -13,8 +13,10 @@ import { createNativeLoop } from "./native-loop.js";
13
13
  // module adds with no adapter facts of its own, on its runner's adapter;
14
14
  // - a CLI harness (claude-agent, codex, opencode) runs on the adapter loop with its own adapter;
15
15
  // - anything else fails the run in words (the dispatch's UnknownHarness).
16
- import { harnessOf, recipeHarness } from "../harness-table.js";
16
+ import { harnessOf, recipeKeysOf } from "../harness-table.js";
17
+ import { harnessKeysSaved, RECIPE_SIGN_IN_PERSON_ONLY } from "../harness-keys.js";
17
18
  import { hostMemory, neverFits } from "../host.js";
19
+ import { personStarted } from "../run-launch.js";
18
20
  import { resolveHarness } from "./adapters/index.js";
19
21
  import { adapterRunSpecFromLaunch, PI_WIRES } from "./adapter-run-spec.js";
20
22
  import { createAdapterLoop } from "./adapter-loop.js";
@@ -32,20 +34,28 @@ import { workflowSpecOf } from "./workflow-spec.js";
32
34
  export class NeverFits extends ClaimRefused {
33
35
  name = "NeverFits";
34
36
  }
35
- /** The words a scheduled or triggered run on a plan-billed harness recipe is refused in (harness-recipe-entry.ts
36
- * serverRoute): such a run takes keys saved for that harness, never its owner's own sign-in, and none are saved yet. */
37
- export const RECIPE_SIGN_IN_PERSON_ONLY = "A scheduled or triggered run on a harness recipe billed to its vendor's plan runs on keys saved for that harness, never on its owner's own sign-in, and this server saves no harness's keys yet: start this run yourself, or run the agent on a harness billed through this server's model proxy.";
38
- /** Refuses at its claim a run no person started (a schedule's, a trigger's: launch.trigger) on a plan-billed recipe's
39
- * harness (harness-table.ts recipeHarness), on every path a claim takes (run-child-host.ts staysInRunner, and here). */
40
- export function refuseRecipeTriggerRun(env, harness, launch) {
41
- if (launch.trigger !== undefined && recipeHarness(env, harness) === "plan")
37
+ export { RECIPE_SIGN_IN_PERSON_ONLY };
38
+ /** Refuses at its claim a run no person started (a schedule's, a trigger's, a learned workflow's audit shadow or replay:
39
+ * personStarted) on a plan-billed recipe's harness (harness-table.ts recipeKeysOf) unless every key it runs on is saved for that harness (harness-keys.ts), on
40
+ * every path a claim takes (run-child-host.ts staysInRunner, and here): the early word, before a process is made. Rows
41
+ * are counted, never opened; the claim's spec opens them and refuses it again if not every one opened, since a row
42
+ * counted here can be gone or not open by then (cli-run-spec.ts). */
43
+ export async function refuseRecipeTriggerRun(deps, harness, launch) {
44
+ if (personStarted(launch))
45
+ return;
46
+ const keys = recipeKeysOf(deps.env ?? {}, harness);
47
+ if (keys !== undefined && !(await harnessKeysSaved(deps.store, harness, keys)))
42
48
  throw new ClaimRefused(RECIPE_SIGN_IN_PERSON_ONLY);
43
49
  }
44
50
  /** The dispatch's `resolve`, built from the runner's deps: it reads the run's revision (for a workflow revision) and
45
- * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words). */
46
- export function resolveRunnerLoop(given) {
51
+ * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words).
52
+ * `keysCounted`: a run's own process (run-child.ts), whose runner counted its harness's key rows before it made the
53
+ * process (run-child-host.ts staysInRunner). The process's store lists no rows (STORE_CALLS has no sealedKeys.all), so
54
+ * it never counts them again; its claim's spec opens the claim's own keys and refuses the run if not every one opened. */
55
+ export function resolveRunnerLoop(given, options = {}) {
47
56
  return async (harness, launch, runId) => {
48
- refuseRecipeTriggerRun(given.env ?? {}, harness, launch);
57
+ if (!options.keysCounted)
58
+ await refuseRecipeTriggerRun(given, harness, launch);
49
59
  // The model gateway saved in the console (model-gateway.ts), read from the store at each claim and laid over the run
50
60
  // environment as its variables would be, so a gateway saved or removed since reaches the next run with no restart. A
51
61
  // gateway the runner's environment names wins, and nothing saved is read over it.
@@ -89,6 +89,9 @@ export interface Held {
89
89
  /** The zone the claim's run's day is told in (environment.ts runZone): its trigger's, read by the runner from the
90
90
  * claim's own launch, else the server's. A zone's name, never the trigger's row. */
91
91
  runZone(): Promise<string>;
92
+ /** The keys saved for the claim's own harness alone (harness-keys.ts openHarnessKeys), by name, opened by the runner:
93
+ * none unless that harness is a plan-billed recipe. The process lays them on its adapter's environment alone. */
94
+ harnessKeys(): Promise<Record<string, string>>;
92
95
  /** The host's keys of the decision providers `providers` (claim-secrets.ts hostDecisionKeys): of the providers the
93
96
  * claim's learned workflows' questions name, as the runner chose them (learnedFirst), alone. */
94
97
  decisionKeys(providers: readonly string[]): Promise<Record<string, string>>;
@@ -141,7 +141,7 @@ export declare const draftFailedDigest: (runId: string) => string;
141
141
  * compiles it again. A revision of a connected agent's hold on give-backs is no recompile (runner/promotion.ts
142
142
  * reviseAttemptOf). One record per run (its digest is the run's), written once: a claim that ends the run again
143
143
  * writes none. */
144
- export declare function recordDraftFailed(deps: Pick<LearningEndDeps, "store" | "log">, input: {
144
+ export declare function recordDraftFailed(deps: Pick<LearningEndDeps, "store" | "log" | "learningFolder">, input: {
145
145
  runId: string;
146
146
  agentId: string;
147
147
  compile: CompileAsk;
@@ -44,6 +44,7 @@ import { learningStartOf, readLaunchBody, seedFailed } from "../run-launch.js";
44
44
  import { FINAL_STATES } from "../store/store.js";
45
45
  import { shadowRunId } from "../learn/audit.js";
46
46
  import { getMcpServer } from "../mcp-store.js";
47
+ import { purgeGate, refusedIn } from "../purged-workflow.js";
47
48
  import { readApprovers } from "../server-approvers.js";
48
49
  import { isCliRecord, runEntries, runTimeline, withoutFeedbackRounds } from "../store-reads/journal.js";
49
50
  import { capNowOf, KINDS } from "./journal-kinds.js";
@@ -498,7 +499,7 @@ export async function recordDraftFailed(deps, input) {
498
499
  const failed = input.errors.join("; ").slice(0, CHECK_TEXT_MAX) || "no draft passed";
499
500
  const reason = `${DRAFT_FAILED}: ${failed}. ${attempt === 2 ? "It was the recompile, so it stops: nothing compiles again until its owner acts" : "It is not promoted; the next due run compiles it once more"}`;
500
501
  const check = { compile_after, agree_min, alone_min, attempt, n: 0, agreed: 0, alone: 0, of: [], ...(attempt === 2 ? { stopped: true } : {}) };
501
- const kept = await recordPromotion(deps.store.settings, input.agentId, { workflow, digest, at: new Date().toISOString(), decided: "hold", reason, check }, (was) => was === undefined);
502
+ const kept = await recordPromotion(deps.store.settings, input.agentId, { workflow, digest, at: new Date().toISOString(), decided: "hold", reason, check }, (was) => was === undefined, refusedIn(() => deps.learningFolder(input.agentId), deps.store, deps.log));
502
503
  if (kept.won)
503
504
  deps.log?.(`learning: run ${input.runId}: the compile of ${workflow} failed its checks (attempt ${attempt}${attempt === 2 ? ", stopped" : ""})`);
504
505
  }
@@ -552,8 +553,10 @@ export async function compileAskOf(deps, input) {
552
553
  const { agentId } = input;
553
554
  // A revision is asked only of a workflow its promotion holds, once per hold. The workflows whose newest revision other
554
555
  // than their champion (learn/promote.ts championOf: it serves while that one is held) is held: the run's own may be one.
556
+ // A record the purge gate refuses is skipped as the champion's readers skip it (purged-workflow.ts refusedOf); a gate
557
+ // that can't be asked skips none, and the text read below is gated again.
555
558
  const records = await promotionsOf(deps.store.settings, agentId).catch(() => []);
556
- const heldNames = heldNamesOf(records);
559
+ const heldNames = heldNamesOf(records, records.length ? await refusedIn(() => deps.learningFolder(agentId), deps.store, deps.log)(records).catch(() => undefined) : undefined);
557
560
  // The loop's numbers on the agent's definition (the revision this run runs): the first compile waits for compile_after
558
561
  // completed agent runs, the ending one counted.
559
562
  const { compile_after: compileAfter } = await loopOfRun(deps.store, input.runId);
@@ -587,8 +590,10 @@ export async function compileAskOf(deps, input) {
587
590
  // `main`: the commit the snapshot read is main's at, which `current` was read from.
588
591
  let read;
589
592
  try {
593
+ // A workflow a purged run wrote is neither counted nor told (purgeGate), on main or at a replayed round's parent.
590
594
  const readFrom = async ({ snapshot, body }) => {
591
- const workflows = (snapshot?.workflows ?? []).filter(({ status }) => status === "active" || status === "pending");
595
+ const purged = (await purgeGate(snapshot, deps.store)).workflows;
596
+ const workflows = (snapshot?.workflows ?? []).filter(({ name, status }) => (status === "active" || status === "pending") && !purged.has(name));
592
597
  const textOf = async (name) => {
593
598
  const file = workflows.find((one) => one.name === name)?.files.find(({ path }) => path.endsWith("/workflow.json"));
594
599
  const text = file ? await body(file.path, file.oid) : undefined;
@@ -1,5 +1,5 @@
1
1
  import type { AlsoRow, Claim, Command, Journal } from "../store/store.js";
2
- import type { Redact } from "./redact.js";
2
+ import type { HeldRedact } from "./redact.js";
3
3
  import type { Compared, GraderReply } from "../learn/promote.js";
4
4
  export type { AlsoRow, Claim, Command, Journal };
5
5
  /** Why a run ends failed when the answer it would end on was cut at the model's output limit (stopReason "length"): the
@@ -187,9 +187,10 @@ export interface LoopDeps {
187
187
  * The ticker writes it to the run's run_live row, one store transaction per tick for all its loops, never into the
188
188
  * journal. Absent: not reported. */
189
189
  live?: (read: () => HeldState | undefined) => void;
190
- /** The runner's one redactor (redact.ts): an error's text the loop writes to its run's end goes through it, so no
191
- * secret the runner holds is stored, and its values cut the run's live view (live-ticker.ts). Absent: none cut. */
192
- redact?: Redact;
190
+ /** The runner's one redactor (redact.ts), the same instance for every loop: an error's text the loop writes to its run's
191
+ * end goes through it, so no secret the runner holds is stored, its values cut the run's live view (live-ticker.ts),
192
+ * and a claim carries the run's own tool keys into it (claim-secrets.ts). */
193
+ redact: HeldRedact;
193
194
  }
194
195
  /** A run's held state: what pi shows before it stores it. The live view (live/stream.ts) streams it beside the stored
195
196
  * commits' events, in the door's vocabulary (a running tool's tool_execution_start, a partial's message_update). */
@@ -23,6 +23,7 @@ import { startRunnerRelay } from "../dial-relay.js";
23
23
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
24
24
  import { ArchilSettingsEnvInvalid, archilSettingsFromEnv } from "../archil-settings.js";
25
25
  import { dockerPathsForRuns } from "../box-paths.js";
26
+ import { COMPOSIO_KEY_ENV } from "../composio-made.js";
26
27
  import { hostCommandRefusals } from "../computers.js";
27
28
  import { hostAddressesOnce } from "../docker-host-addresses.js";
28
29
  import { claimInstallsStopped } from "../harness-install.js";
@@ -94,8 +95,9 @@ export async function openRunnerStore(dataDir, env, warn, url) {
94
95
  }
95
96
  /** The runner's own secrets, which a run never gets, not even in the runner's in-process environment: the server's
96
97
  * tokens (the token and the token list) and API key, the seal key (the runner holds it as its sealKey), the store's connection (its URL holds a
97
- * database password), and the launch hook's signing secret (the server's alone). */
98
- const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_TOKENS" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name === LAUNCH_HOOK_SECRET_ENV || name.startsWith("AGENTRUN_STORE_");
98
+ * database password), the launch hook's signing secret (the server's alone), and the Composio account key, which the
99
+ * runner's claim alone reads (composio-made.ts composioEnvKey) and sends only as a granted Composio server's MCP header. */
100
+ const RUNNER_ONLY = (name) => name === "AGENTRUN_TOKEN" || name === "AGENTRUN_TOKENS" || name === "AGENTRUN_API_KEY" || name === SEAL_KEY_ENV || name === LAUNCH_HOOK_SECRET_ENV || name === COMPOSIO_KEY_ENV || name.startsWith("AGENTRUN_STORE_");
99
101
  /** A run's environment as the runner hands its loops (AdapterSpecDeps.env): this process's, less the runner's own
100
102
  * secrets, with every other secret the launcher's pipe handed it (a model key, a tool key, a box key) readable by name
101
103
  * but not enumerable, as secrets.ts withSecrets makes them: code that reads one by name (the model route) finds it, and
@@ -43,6 +43,9 @@ export interface McpClaimOptions {
43
43
  /** For tests only (no environment or CLI flag maps onto it): the one origin a github_app server may have, a fake for
44
44
  * GitHub's hosted MCP (GITHUB_MCP_ORIGIN). */
45
45
  githubMcpOrigin?: string;
46
+ /** For tests only (no environment or CLI flag maps onto it): the one origin a key read from the environment is sent to,
47
+ * a fake for Composio's (COMPOSIO_ORIGIN; composioEnvKey). */
48
+ composioMcpOrigin?: string;
46
49
  /** The run's redactors (runner/redact.ts, the spec's `cut`): every credential value this step hands the gateway (each
47
50
  * header's value and a Bearer's bare token: a saved one, a refreshed OAuth token, a minted GitHub App token, a per_run
48
51
  * server's handed one at the claim and at each fresh()) is held by them as it is handed over, before any call carries
@@ -27,6 +27,10 @@
27
27
  //
28
28
  // A per-run Composio server (composio-made.ts composioPerRun) is bound by each run's caller ({composio_user_id,
29
29
  // connected_account_id?} in mcp_auth, sealed in its launch): its entry carries them as `query` (mcp-gateway.ts).
30
+ // A Composio server saved with api_key_env (composio-made.ts key_env) seals no key: each open reads the variable's value
31
+ // as the runner was handed it at its start (secrets.ts secret, never its environment), for an address on Composio's origin
32
+ // alone (composioEnvKey), and only for a server the run is granted: the run's process never holds it. Unset, or a row at
33
+ // another address, the claim is refused before the loop starts (pinOf), in words naming it, and nothing is sent.
30
34
  //
31
35
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
32
36
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
@@ -53,7 +57,7 @@ import { randomUUID } from "node:crypto";
53
57
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
54
58
  import { pinFirst } from "../mcp-pin-first.js";
55
59
  import { mcpNameOf } from "../tool-names.js";
56
- import { composioMadeKey, composioPerRun } from "../composio-made.js";
60
+ import { composioEnvKey, composioMadeKey, composioPerRun, recordedMade } from "../composio-made.js";
57
61
  import { composioRunQuery } from "../composio-preset.js";
58
62
  import { META_REASON, metaToolOf } from "../mcp-meta.js";
59
63
  import { resourceToolProblem } from "../mcp-resources.js";
@@ -221,6 +225,13 @@ export async function mcpClaim(options) {
221
225
  if (account && "unopened" in account)
222
226
  return entry({ unopened: account.unopened }), { awaited: false };
223
227
  const query = account?.query;
228
+ // Its key named by api_key_env: the value the runner was handed at its start, for an address on Composio's origin
229
+ // alone; else its calls refused unsent, naming why (composioEnvKey).
230
+ const keyEnv = await keyEnvOf(store, name, row);
231
+ if (keyEnv) {
232
+ const got = composioEnvKey(name, row.url, keyEnv, options.composioMcpOrigin);
233
+ return entry("key" in got ? { headers: { "x-api-key": got.key }, ...(query ? { query } : {}) } : { unopened: got.refused }), { awaited: false };
234
+ }
224
235
  if (row.sealed === null)
225
236
  return entry({ ...(query ? { query } : {}) }), { awaited: false };
226
237
  // A seal problem first: no refresh is ever sent for a credential this runner cannot open.
@@ -451,7 +462,7 @@ export async function mcpClaim(options) {
451
462
  }
452
463
  /** The run's pin: its revision's, as its save made it, held to the run's grants and checked against the meta tools known
453
464
  * now; undefined when it grants no MCP tool. A granted tool the pin does not hold refuses the claim in words. */
454
- async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN, pinListing, signal }) {
465
+ async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN, composioMcpOrigin, pinListing, signal }) {
455
466
  // A github_app server anywhere but GitHub's hosted MCP ends the run here, before any token is minted or anything sent:
456
467
  // the App's tokens go to GitHub alone (github.ts githubMcpUrl, the one check).
457
468
  const offGithub = (server, url, auth) => {
@@ -509,10 +520,23 @@ async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN
509
520
  if (row && metaToolOf(row.url, tool.name))
510
521
  throw new McpClaimRefused(`mcp:${server}/${tool.name} can't be granted: ${META_REASON}`);
511
522
  offGithub(server, url, row?.auth);
523
+ // A Composio server whose key variable is unset, or whose address is off Composio's origin: the run never starts
524
+ // without its tools, and nothing is sent.
525
+ const keyEnv = row ? await keyEnvOf(store, server, row) : undefined;
526
+ const got = row && keyEnv ? composioEnvKey(server, row.url, keyEnv, composioMcpOrigin) : undefined;
527
+ if (got && "refused" in got)
528
+ throw new McpClaimRefused(`${got.refused} Nothing was sent.`);
512
529
  }
513
530
  // As plain JSON, as the stored pin reads (the harnesses and the run's directory take it as such).
514
531
  return JSON.parse(JSON.stringify(pinned));
515
532
  }
533
+ /** The variable a Composio server saved with api_key_env reads its key from (its record's key_env): a headers row that
534
+ * seals none. None for every other row. */
535
+ async function keyEnvOf(store, name, row) {
536
+ if (row.auth !== "headers" || row.sealed !== null)
537
+ return undefined;
538
+ return recordedMade(await store.settings.get(composioMadeKey(name)), row.createdAt)?.key_env;
539
+ }
516
540
  /** The claim still the run's: its epoch unchanged, else Fenced. */
517
541
  async function confirm(store, claim) {
518
542
  const run = await store.runs.get(claim.runId);
@@ -38,6 +38,9 @@ export interface McpForClaimOptions {
38
38
  /** A test's fake GitHub MCP origin, handed to the claim step (mcpClaim's githubMcpOrigin): for tests only: no environment variable, flag or setting maps onto it; absent, GitHub's hosted MCP
39
39
  * (github.ts GITHUB_MCP_ORIGIN). */
40
40
  readonly githubMcpOrigin?: string;
41
+ /** A test's fake Composio MCP origin, handed to the claim step and the pin's listing (mcpClaim's composioMcpOrigin): for
42
+ * tests only: no environment variable, flag or setting maps onto it; absent, Composio's (composio-made.ts COMPOSIO_ORIGIN). */
43
+ readonly composioMcpOrigin?: string;
41
44
  /** Whether this runner may reach an MCP server whose URL is on loopback (AdapterSpecDeps.mcpLoopback): the runner
42
45
  * beside a local-install server, or a runner in its own process whose own environment opts in. Absent, never. */
43
46
  readonly loopback?: boolean;
@@ -36,13 +36,14 @@ export async function mcpForClaim(options) {
36
36
  sealKey: options.sealKey,
37
37
  signal: held.signal,
38
38
  // A run whose revision has no pin (one made before the upgrade) pins it here, listing as a save does.
39
- 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 } : {}) }),
39
+ 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 } : {}), ...(options.composioMcpOrigin ? { composioOrigin: options.composioMcpOrigin } : {}) }),
40
40
  ...(options.bounds ? { bounds: options.bounds } : {}),
41
41
  ...(options.network ? { network: options.network } : {}),
42
42
  ...(options.loopback ? { loopback: true } : {}),
43
43
  ...(options.own ? { own: options.own } : {}),
44
44
  ...(githubApp ? { githubApp } : {}),
45
45
  ...(options.githubMcpOrigin ? { githubMcpOrigin: options.githubMcpOrigin } : {}),
46
+ ...(options.composioMcpOrigin ? { composioMcpOrigin: options.composioMcpOrigin } : {}),
46
47
  ...(options.githubTimer ? { githubTimer: options.githubTimer } : {}),
47
48
  ...(options.hold ? { hold: options.hold } : {}),
48
49
  });
@@ -12,7 +12,12 @@ import { type CostParts } from "@parcha/agentrun-kernel";
12
12
  * gateway priced (`reported`: the proxy's reportedCostOf or usageCostOf, its runner.turn keeping the table's figure beside
13
13
  * it as `tableUsd`) and how many a price table did (`estimated`: its runner.turn's `estimated`, or a cut request's hold,
14
14
  * or a native or SDK task's `aggregate` booking, its harness's own figure).
15
- * A figure that is neither ($0 for a request refused or never sent, a charge settled through the cap) counts in neither. */
15
+ * A figure that is neither ($0 for a request refused or never sent, a charge settled through the cap) counts in neither.
16
+ * `plan`: of its requests, those billed to a person's plan (a ChatGPT plan's, chatgpt-plan.ts, or Claude Code's login's:
17
+ * its runner.turn's `billing` "plan", or, still in flight, its runner.request's `plan`), how many and their tokens (input,
18
+ * output and cache, as each booking reported them; none yet for one in flight). Each is $0 to the run by the kernel's one
19
+ * rule (turnCostOf), however it ended: the plan pays for it, so no reader counts it unpriced. Counted as `requests` is:
20
+ * a request booked twice is one. */
16
21
  export type BookedSpend = {
17
22
  readonly usd: number | null;
18
23
  readonly known: number;
@@ -32,6 +37,10 @@ export type BookedSpend = {
32
37
  readonly reported: number;
33
38
  readonly estimated: number;
34
39
  };
40
+ readonly plan: {
41
+ readonly requests: number;
42
+ readonly tokens: number;
43
+ };
35
44
  readonly free?: true;
36
45
  };
37
46
  /** How a run's cost was reached, by how its model requests were priced: `reported` when every request priced had the
@@ -115,15 +124,6 @@ export type EndCost = {
115
124
  readonly costUpperBound: boolean;
116
125
  };
117
126
  export declare const endCostOf: (cost: RunCost) => EndCost;
118
- /** The run's model requests billed to a person's plan (runner.turn `billing` "plan", booked at no price: a ChatGPT plan's,
119
- * chatgpt-plan.ts, or Claude Code's login's):
120
- * how many and their tokens (input, output and cache, as each booking reported them). Each is $0 to the run by the
121
- * kernel's one rule (turnCostOf), however it ended: the plan pays for it, so no reader counts it unpriced. One still in
122
- * flight (its runner.request marked `plan`, no runner.turn yet) is one of them, with no tokens yet. */
123
- export declare function planSpend(entries: readonly EntryLike[]): {
124
- readonly requests: number;
125
- readonly tokens: number;
126
- };
127
127
  /** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
128
128
  * its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
129
129
  * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
@@ -8,11 +8,13 @@
8
8
  // passes its decisions. `effort` is the level the run ran at and `model`, on a harness other than pi, the model its
9
9
  // revision named — both as storedMetrics added them, resolved by the caller from the run's launch and harness.
10
10
  import { runMetricsWithDecisions, timelineOf } from "../timeline/index.js";
11
- import { costOfParts, rebooked, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
11
+ import { billedToPlan, costOfParts, rebooked, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
12
12
  import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
13
13
  import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
14
14
  import { anthropicModelId } from "../provider.js";
15
15
  import { WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
16
+ /** A booking record's request, as every reader of a booking names it: its conversation and its turn. */
17
+ const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
16
18
  /** How a run's cost was reached, by how its model requests were priced: `reported` when every request priced had the
17
19
  * provider's or its gateway's own figure (LiteLLM's `x-litellm-response-cost`, OpenRouter's usage `cost`); `estimate`
18
20
  * when any was priced from a price table (the catalog, AGENT_MODEL_PRICE, a cut request's hold); `unpriced` when no
@@ -71,7 +73,6 @@ export function bookedSpend(entries, which) {
71
73
  const paidConv = keyed.get(TOOL_SESSION);
72
74
  const decisionsConv = keyed.get(DECISION_SESSION);
73
75
  const conv = (e) => Number(e.conversationId);
74
- const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
75
76
  const model = (e) => conv(e) !== paidConv && conv(e) !== decisionsConv;
76
77
  // The side calls among the model requests: each request that says so, by its conversation and turn.
77
78
  const sides = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request && model(e) && (e.data?.side === true || typeof e.data?.host === "string")).map(turnOf));
@@ -95,6 +96,7 @@ export function bookedSpend(entries, which) {
95
96
  let reported = 0;
96
97
  let estimated = 0;
97
98
  const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
99
+ const plan = { requests: 0, tokens: 0 };
98
100
  // Each request is booked once, as the kernel's sessionSpendOf reads it: a second runner.turn of a turn already booked
99
101
  // (two bookings of one session that each read it open, a cut written twice) counts no money and no request again.
100
102
  const booked = new Set();
@@ -104,9 +106,11 @@ export function bookedSpend(entries, which) {
104
106
  if (e.kind === RUNNER_RECORDS.request && !answered.has(turnOf(e))) {
105
107
  requests += 1;
106
108
  count(e);
107
- // One billed to a person's plan (its record's `plan`, Admitted.plan) is $0 to the run however it ends, as the cap's
108
- // reader (the kernel's sessionSpendOf) holds it: in flight it is a known $0, never unpriced.
109
- if (e.data?.plan !== true)
109
+ // One billed to a person's plan (its record's `plan`, Admitted.plan) is $0 to the run however it ends, as the
110
+ // kernel's sessionSpendOf holds it: in flight it is a known $0 and one of the plan's requests, never unpriced.
111
+ if (billedToPlan(e.data))
112
+ plan.requests += 1;
113
+ else
110
114
  unpriced += 1;
111
115
  unmetered += 1;
112
116
  continue;
@@ -145,17 +149,22 @@ export function bookedSpend(entries, which) {
145
149
  // The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
146
150
  if (d.usage === undefined)
147
151
  unmetered += 1;
148
- for (const key of Object.keys(tokens))
149
- if (typeof d.usage?.[key] === "number")
150
- tokens[key] += d.usage[key];
152
+ if (d.billing === "plan")
153
+ plan.requests += 1;
154
+ for (const key of Object.keys(tokens)) {
155
+ if (typeof d.usage?.[key] !== "number")
156
+ continue;
157
+ tokens[key] += d.usage[key];
158
+ if (d.billing === "plan")
159
+ plan.tokens += d.usage[key];
160
+ }
151
161
  }
152
- return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, priced: { reported, estimated }, ...(requests > 0 && free === requests ? { free: true } : {}) };
162
+ return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, priced: { reported, estimated }, plan, ...(requests > 0 && free === requests ? { free: true } : {}) };
153
163
  }
154
164
  /** The run's decisions whose ids are in `ids` (each booked as `decision:<id>`), as bookedSpend reads its decisions, with
155
165
  * every other decision left out: the ones a vendor charged as a paid call (store-reads/decisions.ts
156
166
  * parallelChargedDecisions), which the run's tools figures count beside its paid tool calls. */
157
167
  export function bookedDecisionsOf(entries, ids) {
158
- const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
159
168
  const named = (e) => e.data?.model;
160
169
  const kept = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request && typeof named(e) === "string" && named(e).startsWith("decision:") && ids.has(named(e).slice("decision:".length))).map(turnOf));
161
170
  return bookedSpend(entries.filter((e) => !(e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn) || kept.has(turnOf(e))), "decisions");
@@ -202,34 +211,6 @@ export function runCostOf(entries, { unbooked = false } = {}) {
202
211
  return { usd, known, bounded: usd === null ? 0 : Math.max(0, round(usd - known)), unpriced: cost.unpriced, atMost: cost.atMost ?? 0, requests: parts.reduce((sum, part) => sum + part.requests, 0) };
203
212
  }
204
213
  export const endCostOf = (cost) => ({ costUsd: cost.usd, costUpperBound: cost.usd !== null && cost.atMost > 0 });
205
- /** The run's model requests billed to a person's plan (runner.turn `billing` "plan", booked at no price: a ChatGPT plan's,
206
- * chatgpt-plan.ts, or Claude Code's login's):
207
- * how many and their tokens (input, output and cache, as each booking reported them). Each is $0 to the run by the
208
- * kernel's one rule (turnCostOf), however it ended: the plan pays for it, so no reader counts it unpriced. One still in
209
- * flight (its runner.request marked `plan`, no runner.turn yet) is one of them, with no tokens yet. */
210
- export function planSpend(entries) {
211
- const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
212
- const answered = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.turn).map(turnOf));
213
- let requests = 0;
214
- let tokens = 0;
215
- for (const e of entries) {
216
- if (e.kind === RUNNER_RECORDS.request) {
217
- if (e.data?.plan === true && !answered.has(turnOf(e)))
218
- requests += 1;
219
- continue;
220
- }
221
- if (e.kind !== RUNNER_RECORDS.turn)
222
- continue;
223
- const d = (e.data ?? {});
224
- if (d.billing !== "plan" || d.givenBack === true || d.unsent === true)
225
- continue;
226
- requests += 1;
227
- for (const key of ["input", "output", "cacheRead", "cacheWrite"])
228
- if (typeof d.usage?.[key] === "number")
229
- tokens += d.usage[key];
230
- }
231
- return { requests, tokens };
232
- }
233
214
  /** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
234
215
  * its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
235
216
  * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
@@ -73,6 +73,9 @@ export interface ModelRoute {
73
73
  readonly unpriced?: boolean;
74
74
  /** The model's most output tokens (its catalog ceiling): the cap's output bound, null when the catalog names none. */
75
75
  readonly outputCeiling?: number | null;
76
+ /** A model on this machine's own Ollama (ollama-provider.ts): $0, and its requests never count toward the run's
77
+ * free-model limit (the cap's CapModel.local), which guards a provider's shared quota this model has none of. */
78
+ readonly local?: boolean;
76
79
  }
77
80
  type PiModel = {
78
81
  id: string;
@@ -17,6 +17,7 @@ import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
18
  import { onOpenRouter, openRouterAttribution, ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
19
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
20
+ import { OLLAMA_PROVIDER } from "../ollama-provider.js";
20
21
  import { gatewayHeadersAt, providerFor } from "../provider.js";
21
22
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
22
23
  import { callsOfText, toolsAsText } from "./text-tools.js";
@@ -80,8 +81,11 @@ export async function routeOf(model, env = process.env, tier = "default", wires
80
81
  // thinking level by name (LEVELS_BY_NAME), which the translation hands to pi-ai (levelOf): the run's effort reaches the
81
82
  // model, mapped and clamped by its own catalog entry. Direct Particle states no cost (its usage is priced from the
82
83
  // catalog), and its session also takes the model's window and ceiling and replays unsigned reasoning.
83
- const like = target.provider === "particle" ? { ...settings, ...LEVELS_BY_NAME, translatedChatCompletions: true } : target.reasoning ? { ...sees, ...LEVELS_BY_NAME } : undefined;
84
- return { ...route, ...(like ? { like } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
84
+ // An Ollama model's session also takes its window, the context every request asks Ollama for (num_ctx), so pi compacts
85
+ // before Ollama would cut the prompt.
86
+ const local = target.provider === OLLAMA_PROVIDER;
87
+ const like = target.provider === "particle" ? { ...settings, ...LEVELS_BY_NAME, translatedChatCompletions: true } : local ? { ...settings, ...(target.reasoning ? LEVELS_BY_NAME : {}) } : target.reasoning ? { ...sees, ...LEVELS_BY_NAME } : undefined;
88
+ return { ...route, ...(like ? { like } : {}), ...(local ? { local: true } : {}), provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
85
89
  }
86
90
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
87
91
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
@@ -5,7 +5,7 @@ import { type RunLaunch } from "../run-launch.js";
5
5
  import { type Store } from "../store/store.js";
6
6
  import { type Recorded, type ReplayCalls, type Skipped } from "../learn/replay-calls.js";
7
7
  import { type Json } from "../validate.js";
8
- import { type CheckBar, type CheckRecord, type CheckTurns, type Compared, type PromotionRecord, recordPromotion, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
8
+ import { type CheckBar, type CheckRecord, type CheckTurns, type Compared, type PromotionRecord, recordPromotion, type Refused, type ReplayOutcomes, type ReplayScore } from "../learn/promote.js";
9
9
  import { type FirstChoice, type Promoted, type ReplayOutcome } from "./workflow-first.js";
10
10
  import type { LearningFolder } from "../learn/folder.js";
11
11
  import type { Shown } from "../learning.js";
@@ -32,9 +32,13 @@ export interface PromotionDeps {
32
32
  readonly context: Context;
33
33
  readonly log: (line: string) => void;
34
34
  /** The learned workflow `name` as the learning folder held it active at `commit` (a champion's text), or undefined when
35
- * it held none by that name, or a purged run wrote it (learning.ts seedAt): a purged champion is no champion's text,
36
- * and the agent takes the run. Absent: no champion serves. */
35
+ * it held none by that name, or a purged run wrote it (learning.ts seedAt): a purged run's text is never served (the
36
+ * champion skips it first, `refused`). Absent: no champion serves. */
37
37
  readonly champion?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>;
38
+ /** The records of `workflows` (all, when absent) championOf skips (purged-workflow.ts refusedIn over the learning
39
+ * folder): a champion the purge gate refuses at its commit, so the newest promotion it lets through serves, and the
40
+ * promotions trim keeps that one (recordPromotion). Absent: none skipped. */
41
+ readonly refused?: (records: readonly PromotionRecord[], workflows?: Iterable<string>) => Promise<Refused>;
38
42
  /** The digest of the learned workflow `name` the learning folder's main holds now (the newest revision), or undefined
39
43
  * when it holds none by that name. Absent: every revision is the newest. */
40
44
  readonly newest?: (name: string) => Promise<string | undefined>;
@@ -55,7 +59,7 @@ export interface PromotionDeps {
55
59
  }
56
60
  /** What deciding a check needs (decideCheck, stopUnchecked): a claim's ports, or those of a connected agent's start or
57
61
  * run end, whose record names its commit (no claimed launch to read a seed from). */
58
- type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now">>;
62
+ type DecideDeps = Pick<PromotionDeps, "store" | "agentId" | "log" | "shown"> & Partial<Pick<PromotionDeps, "launch" | "now" | "refused">>;
59
63
  /** The claim's promotion ports: `folder`, the agent's learning folder where the run's place keeps it, a champion read
60
64
  * from it at its record's commit, cut of the server's secrets (`shown`) as the claim's lay is; and the workflow an earlier
61
65
  * claim of this run served (`kept`, from its journal: none on a first claim). */
@@ -79,12 +83,13 @@ export declare function replayLaid(launch: RunLaunch, laid: readonly LearnedWork
79
83
  * promoted yet, or the champion held): a revision replaying, held or never decided is never handed to the agent to run
80
84
  * in its place. One the records never named is an unchecked draft and is not offered. A replay run's as
81
85
  * laid (replayLaid). The records unread: only the chosen one, as the gate leaves a run to its agent. */
82
- export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
86
+ export declare function toolFlowsFor(deps: Pick<PromotionDeps, "store" | "agentId" | "champion" | "refused" | "log">, launch: RunLaunch, laid: readonly LearnedWorkflow[], choice: FirstChoice): Promise<LearnedWorkflow[]>;
83
87
  /** `flow`'s champion (championOf) and the text it serves from: `flow` itself when it is the champion, else the
84
88
  * champion's text read at its record's commit (`read`), kept only when its digest is the champion's. No text: none is
85
- * promoted, or its text cannot be read. The one champion lookup a claim's gate (servingNow), the learned_workflow tool
86
- * (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
87
- export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>): Promise<{
89
+ * promoted, or its text cannot be read. The champion skips what `refused` says the purge gate refuses (PromotionDeps
90
+ * refused), so after a purge of its run the newest promotion the gate lets through serves. The one champion lookup a
91
+ * claim's gate (servingNow), the learned_workflow tool (toolFlowsFor) and a connected agent's start (sdk/runs.ts) share. */
92
+ export declare function championTextOf(records: readonly PromotionRecord[], flow: LearnedWorkflow, read?: (name: string, commit: string) => Promise<LearnedWorkflow | undefined>, refused?: PromotionDeps["refused"]): Promise<{
88
93
  champion?: PromotionRecord;
89
94
  text?: LearnedWorkflow;
90
95
  }>;
@@ -127,7 +132,8 @@ export type CheckRow = {
127
132
  readonly compared?: Compared;
128
133
  };
129
134
  /** Decides a check on its rows, with a connected agent's turns checked before them (`before`), scored on its bar
130
- * (scoreRows). Promoted when it clears the bar (checkPasses); else held with the inputs it did not agree on, which the
135
+ * (scoreRows). Promoted when it clears the bar (checkPasses) and the purge gate lets its revision through at its commit
136
+ * (`refused`: else held, a purged run's text); else held with the inputs it did not agree on, which the
131
137
  * agent's next run's compile turn reads as data (its one recompile); a recompile's check that holds it too stops:
132
138
  * nothing compiles again. No grade, refit, queue or second replay. Kept only while `still` holds of the digest's record
133
139
  * (the one write: of two claims at once, one decides). */