@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.47

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 (247) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/NOTICE +4 -0
  3. package/README.md +267 -40
  4. package/dist/acp-package.d.ts +35 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +5 -2
  7. package/dist/adapter-facts.js +6 -3
  8. package/dist/adapters.d.ts +7 -0
  9. package/dist/adapters.js +39 -0
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/api-only.d.ts +7 -10
  13. package/dist/api-only.js +7 -10
  14. package/dist/archil-routes.js +2 -1
  15. package/dist/cap.js +12 -2
  16. package/dist/chatgpt-plan.js +2 -1
  17. package/dist/cli.js +109 -41
  18. package/dist/composio-made.d.ts +19 -2
  19. package/dist/composio-made.js +17 -5
  20. package/dist/composio-preset.d.ts +42 -7
  21. package/dist/composio-preset.js +106 -70
  22. package/dist/composio-triggers.d.ts +9 -4
  23. package/dist/composio-triggers.js +20 -13
  24. package/dist/computer-attach.d.ts +11 -10
  25. package/dist/computer-attach.js +13 -14
  26. package/dist/computer-commands.d.ts +3 -0
  27. package/dist/computer-commands.js +3 -2
  28. package/dist/computer-lost.d.ts +4 -0
  29. package/dist/computer-lost.js +8 -3
  30. package/dist/computer-setting.d.ts +2 -0
  31. package/dist/computer-setting.js +2 -0
  32. package/dist/computers.d.ts +9 -75
  33. package/dist/computers.js +20 -66
  34. package/dist/console/assets/index-BBFzAxLB.js +715 -0
  35. package/dist/console/assets/index-BRi-Rgq6.css +1 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/cost-heal.d.ts +13 -0
  38. package/dist/cost-heal.js +27 -0
  39. package/dist/dial-relay.d.ts +6 -2
  40. package/dist/dial-relay.js +9 -12
  41. package/dist/email/routes.js +2 -1
  42. package/dist/errors.d.ts +2 -0
  43. package/dist/errors.js +5 -0
  44. package/dist/exa-keyless.d.ts +1 -1
  45. package/dist/exa-keyless.js +1 -1
  46. package/dist/faux-computers.d.ts +2 -3
  47. package/dist/faux-computers.js +9 -31
  48. package/dist/github-connection.js +2 -1
  49. package/dist/harness-archive.d.ts +19 -2
  50. package/dist/harness-archive.js +49 -15
  51. package/dist/harness-check.d.ts +73 -0
  52. package/dist/harness-check.js +489 -0
  53. package/dist/harness-cursor.d.ts +45 -0
  54. package/dist/harness-cursor.js +121 -0
  55. package/dist/harness-recipe.d.ts +127 -0
  56. package/dist/harness-recipe.js +357 -0
  57. package/dist/harness-table.d.ts +12 -0
  58. package/dist/harness-table.js +62 -2
  59. package/dist/harness.d.ts +2 -0
  60. package/dist/harness.js +3 -2
  61. package/dist/host-check.d.ts +6 -0
  62. package/dist/host-check.js +14 -0
  63. package/dist/host.d.ts +10 -3
  64. package/dist/host.js +17 -3
  65. package/dist/import-sources.d.ts +2 -0
  66. package/dist/import-sources.js +2 -0
  67. package/dist/import-summary.d.ts +15 -5
  68. package/dist/import-summary.js +24 -8
  69. package/dist/import.d.ts +24 -4
  70. package/dist/import.js +108 -26
  71. package/dist/key-refusal.d.ts +1 -0
  72. package/dist/key-refusal.js +8 -3
  73. package/dist/key-words.d.ts +1 -1
  74. package/dist/key-words.js +4 -4
  75. package/dist/learn/check.d.ts +3 -0
  76. package/dist/learn/check.js +31 -20
  77. package/dist/learn/compile.js +12 -5
  78. package/dist/learn/promote.d.ts +69 -2
  79. package/dist/learn/promote.js +95 -3
  80. package/dist/learned-nodes.d.ts +4 -3
  81. package/dist/learned-workflow.js +4 -1
  82. package/dist/learning-cost.d.ts +6 -16
  83. package/dist/learning-cost.js +6 -12
  84. package/dist/learning-words.d.ts +2 -0
  85. package/dist/learning-words.js +1 -1
  86. package/dist/listen-first.d.ts +10 -0
  87. package/dist/listen-first.js +25 -1
  88. package/dist/llms.txt +1 -1
  89. package/dist/mcp-gateway.d.ts +2 -1
  90. package/dist/mcp-gateway.js +31 -15
  91. package/dist/mcp-probe.d.ts +18 -6
  92. package/dist/mcp-probe.js +41 -8
  93. package/dist/mcp-secret-writes.d.ts +8 -0
  94. package/dist/mcp-secret-writes.js +104 -4
  95. package/dist/mcp-servers-store.d.ts +11 -5
  96. package/dist/mcp-servers-store.js +46 -20
  97. package/dist/model-form.d.ts +2 -1
  98. package/dist/model-form.js +22 -8
  99. package/dist/model-gateway.d.ts +113 -0
  100. package/dist/model-gateway.js +433 -0
  101. package/dist/model.d.ts +2 -1
  102. package/dist/model.js +9 -7
  103. package/dist/monid.js +1 -1
  104. package/dist/native/binding.d.ts +4 -0
  105. package/dist/native/binding.js +9 -0
  106. package/dist/native/cli.d.ts +3 -2
  107. package/dist/native/cli.js +6 -5
  108. package/dist/openapi.d.ts +2 -0
  109. package/dist/openapi.js +322 -39
  110. package/dist/owner.d.ts +4 -2
  111. package/dist/owner.js +10 -4
  112. package/dist/page.d.ts +8 -0
  113. package/dist/page.js +9 -1
  114. package/dist/port-models.js +17 -10
  115. package/dist/provider.d.ts +3 -3
  116. package/dist/provider.js +12 -3
  117. package/dist/public-address.d.ts +28 -0
  118. package/dist/public-address.js +62 -0
  119. package/dist/run-launch.d.ts +1 -1
  120. package/dist/run-launch.js +1 -1
  121. package/dist/run-secrets.d.ts +3 -2
  122. package/dist/run-secrets.js +6 -4
  123. package/dist/runner/adapter-loop.d.ts +10 -7
  124. package/dist/runner/adapter-loop.js +57 -22
  125. package/dist/runner/adapter-run-spec.d.ts +12 -0
  126. package/dist/runner/adapter-run-spec.js +40 -6
  127. package/dist/runner/adapters/index.js +16 -0
  128. package/dist/runner/adapters/pi.d.ts +5 -2
  129. package/dist/runner/adapters/pi.js +7 -4
  130. package/dist/runner/audit.d.ts +7 -0
  131. package/dist/runner/audit.js +15 -6
  132. package/dist/runner/claim-secrets.js +5 -1
  133. package/dist/runner/cli-run-spec.js +15 -7
  134. package/dist/runner/compare-end.d.ts +43 -0
  135. package/dist/runner/compare-end.js +95 -0
  136. package/dist/runner/computer-journal.d.ts +3 -0
  137. package/dist/runner/computer-journal.js +22 -2
  138. package/dist/runner/harness-loops.d.ts +6 -1
  139. package/dist/runner/harness-loops.js +94 -54
  140. package/dist/runner/held.d.ts +5 -4
  141. package/dist/runner/journal-kinds.d.ts +4 -1
  142. package/dist/runner/journal-kinds.js +3 -0
  143. package/dist/runner/loop-contract.d.ts +10 -0
  144. package/dist/runner/main.d.ts +5 -5
  145. package/dist/runner/main.js +62 -11
  146. package/dist/runner/mcp-claim.js +40 -12
  147. package/dist/runner/metrics.d.ts +26 -0
  148. package/dist/runner/metrics.js +44 -1
  149. package/dist/runner/presence.d.ts +41 -0
  150. package/dist/runner/presence.js +89 -0
  151. package/dist/runner/promotion.d.ts +9 -4
  152. package/dist/runner/promotion.js +33 -14
  153. package/dist/runner/run-child-host.js +40 -10
  154. package/dist/runner/runner.d.ts +5 -0
  155. package/dist/runner/runner.js +8 -0
  156. package/dist/runner/store-port.d.ts +3 -0
  157. package/dist/runner/store-secrets.js +19 -7
  158. package/dist/runner/workflow-first.d.ts +5 -2
  159. package/dist/runner/workflow-first.js +6 -3
  160. package/dist/runs-over-store.d.ts +6 -2
  161. package/dist/runs-over-store.js +14 -4
  162. package/dist/sdk/runs.d.ts +1 -1
  163. package/dist/sdk/runs.js +6 -1
  164. package/dist/sdk/schema.js +1 -1
  165. package/dist/secret-writes.d.ts +16 -3
  166. package/dist/secret-writes.js +28 -3
  167. package/dist/server-secrets-store.js +5 -0
  168. package/dist/server.d.ts +31 -2
  169. package/dist/server.js +322 -51
  170. package/dist/sign-ins-secrets.js +4 -1
  171. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  172. package/dist/slack-url.d.ts +5 -0
  173. package/dist/slack-url.js +11 -0
  174. package/dist/slack.d.ts +107 -0
  175. package/dist/slack.js +292 -0
  176. package/dist/start-switches.d.ts +28 -0
  177. package/dist/start-switches.js +37 -0
  178. package/dist/stats.d.ts +1 -1
  179. package/dist/stats.js +2 -1
  180. package/dist/stop-signals.d.ts +11 -0
  181. package/dist/stop-signals.js +22 -0
  182. package/dist/store/agent-body.d.ts +1 -1
  183. package/dist/store/agent-body.js +2 -2
  184. package/dist/store/index.d.ts +3 -3
  185. package/dist/store/index.js +1 -1
  186. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  187. package/dist/store/postgres/store.d.ts +1 -1
  188. package/dist/store/postgres/store.js +4 -2
  189. package/dist/store/schema.d.ts +13 -5
  190. package/dist/store/schema.js +20 -11
  191. package/dist/store/seal.d.ts +16 -4
  192. package/dist/store/sqlite/store.d.ts +1 -1
  193. package/dist/store/sqlite/store.js +106 -27
  194. package/dist/store/store.d.ts +75 -23
  195. package/dist/store/store.js +11 -0
  196. package/dist/store-reads/analytics.js +3 -2
  197. package/dist/store-reads/cap.d.ts +7 -0
  198. package/dist/store-reads/cap.js +11 -1
  199. package/dist/store-reads/journal.js +27 -1
  200. package/dist/store-reads/learning.d.ts +23 -2
  201. package/dist/store-reads/learning.js +29 -8
  202. package/dist/store-reads/runs.d.ts +9 -0
  203. package/dist/store-reads/runs.js +19 -6
  204. package/dist/store-reads/stats.d.ts +4 -1
  205. package/dist/store-reads/stats.js +15 -6
  206. package/dist/store-view.d.ts +123 -14
  207. package/dist/store-view.js +154 -21
  208. package/dist/telemetry.d.ts +7 -7
  209. package/dist/telemetry.js +38 -15
  210. package/dist/timeline/timeline.js +18 -0
  211. package/dist/tool-keys-store.js +2 -2
  212. package/dist/tool-keys.js +2 -1
  213. package/dist/tool-plane.js +2 -2
  214. package/dist/trigger-adapter.d.ts +3 -4
  215. package/dist/trigger-adapter.js +2 -2
  216. package/dist/trigger-composio.js +3 -3
  217. package/dist/trigger-email.js +0 -2
  218. package/dist/trigger-feed.js +0 -2
  219. package/dist/trigger-schedule.js +3 -0
  220. package/dist/trigger-secrets-shown.d.ts +6 -3
  221. package/dist/trigger-secrets-shown.js +22 -13
  222. package/dist/trigger-targets.d.ts +1 -1
  223. package/dist/trigger-targets.js +19 -8
  224. package/dist/triggers.d.ts +2 -2
  225. package/dist/webhooks.d.ts +82 -8
  226. package/dist/webhooks.js +128 -45
  227. package/dist/wires.d.ts +6 -1
  228. package/dist/wires.js +5 -0
  229. package/dist/workspace/attach.d.ts +3 -2
  230. package/dist/workspace/attach.js +2 -1
  231. package/dist/workspace/attached-computers.d.ts +6 -8
  232. package/dist/workspace/attached-computers.js +27 -24
  233. package/dist/workspace/computer-deps.d.ts +2 -3
  234. package/dist/workspace/computer-deps.js +3 -6
  235. package/dist/workspace/computer-for-claim.js +72 -96
  236. package/dist/workspace/computer-kept.d.ts +0 -7
  237. package/dist/workspace/computer-kept.js +0 -17
  238. package/dist/workspace/resolve-computer.d.ts +18 -14
  239. package/dist/workspace/resolve-computer.js +47 -60
  240. package/dist/workspace/synced-folder.d.ts +20 -15
  241. package/dist/workspace/synced-folder.js +33 -43
  242. package/launcher/agentrun-serve +4 -1
  243. package/package.json +10 -10
  244. package/skills/agentrun-serve/SKILL.md +11 -0
  245. package/templates/README.md +1 -1
  246. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  247. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -1,3 +1,7 @@
1
+ import { envGatewayInForce, readSavedGateway, savedGatewayIn, savedGatewayMarked, SAVED_GATEWAY_ENV, withSavedGateway } from "../model-gateway.js";
2
+ import { GATEWAY_KEY_ENV } from "../model.js";
3
+ import { heldRedactor } from "./redact.js";
4
+ import { envValue } from "../key-meta.js";
1
5
  import { createSdkLoop } from "./sdk-loop.js";
2
6
  import { createNativeLoop } from "./native-loop.js";
3
7
  // The runner's dispatch switch (design 2.1: "the runner takes every run"): which loop a claimed run runs, by its revision
@@ -29,63 +33,86 @@ export class NeverFits extends ClaimRefused {
29
33
  }
30
34
  /** The dispatch's `resolve`, built from the runner's deps: it reads the run's revision (for a workflow revision) and
31
35
  * returns the loop the run runs on, or undefined when this runner does not run it (the dispatch fails it in words). */
32
- export function resolveRunnerLoop(deps) {
36
+ export function resolveRunnerLoop(given) {
33
37
  return async (harness, launch, runId) => {
34
- // A workflow revision runs on the workflow loop whatever the harness its body names (its default is pi): read the
35
- // revision to tell it apart from an agentic pi run.
36
- const run = await deps.store.runs.get(runId);
37
- const revision = run ? await deps.store.agents.revision(run.revisionId) : undefined;
38
- if (revision && isWorkflowRevision(revision)) {
39
- // A workflow run on the workflow loop: its claim-time spec (workflow-spec.ts) resolves each tier's model the one way
40
- // the runner resolves any (routeProviderOf over the route, the default when no providerOf is given).
41
- // The runner's seal key and data directory go with it: a claim's sealed secrets are read with them (claim-secrets.ts,
42
- // store-secrets.ts), and every one the server keeps is held by the run's one redactor.
43
- return createWorkflowLoop(workflowSpecOf({ store: deps.store, sealKey: deps.sealKey, data: deps.data, ...(deps.env ? { env: deps.env } : {}) }));
44
- }
45
- // A backend SDK run's compile turn is asked on the runner's one model route, on the agent's own model (its learning
46
- // start's), its key from the runner's environment, else the one saved in Settings → Model keys, read at each ask.
47
- if (launch.sdk)
48
- return createSdkLoop(launch, deps, async () => {
49
- const base = deps.env ?? process.env;
50
- const env = withModelKeys(base, await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: base }));
51
- // It runs after its backend reported the run complete, on no run's key: on a server that holds no gateway key it is
52
- // skipped in words (run-model-key.ts noServerKeyFor), nothing sent.
53
- const off = noServerKeyFor(env, "An SDK run's compile turn");
54
- if (off) {
55
- deps.log?.(off);
56
- throw new Error(off);
57
- }
58
- return askRouteOf(launch.learning.model, env, (model) => deps.routeOf(model, env, "default", PI_WIRES));
59
- });
60
- if (launch.native)
61
- return createNativeLoop(launch, deps);
62
- // The harness's own entry decides which spec builds the run, by what the entry gives and never the harness's name: an
63
- // entry with an adapter's facts and serve's own adapter for it (the CLI harnesses) runs the CLI spec (cli-run-spec.ts);
64
- // any other (pi, or a harness module's entry that gives only the required members) runs the run spec
65
- // (adapterRunSpecFromLaunch), whose adapter is its runner's (resolveHarness), with the record mode that runner names.
66
- // A harness with no entry is unknown here: the dispatch fails it in words.
67
- const env = deps.env ?? process.env;
68
- const runner = resolveHarness(harness, env);
69
- if (runner) {
70
- // A run this host's memory never holds (host.ts neverFits: one run of its harness is more than the host has for runs)
71
- // fails at its claim, in the words a start of it is refused in here (harness.ts harnessOffers): a run another host
72
- // started, or one left before this host's memory shrank. Claimed alone (runner.ts claimByMemory), it would run past
73
- // the host's memory and its OOM kill would take every run on it.
74
- const tooBig = neverFits(harness, hostMemory(), env);
75
- if (tooBig)
76
- throw new NeverFits(tooBig);
77
- const entry = harnessOf(env, harness);
78
- // A run that learns supplies its own end-of-run step (reflect + proposal over its store) from its spec builder now,
79
- // where the run's Archil claim is: a Mode 2 run's learning folder is on its claim's disk, not this machine's local
80
- // path (adapter-run-spec.ts / cli-run-spec.ts endOfRun). The loop prefers the spec's step over its deps' (stepOf); a
81
- // run that does not learn supplies none. The same for the pi and the CLI spec.
82
- return createAdapterLoop((claim, adapterRun) => entry?.facts && entry.adapter
83
- ? cliRunSpecFromLaunch(launch, adapterRun, deps, claim)
84
- : adapterRunSpecFromLaunch(launch, adapterRun, deps, claim, runner), deps.modelRetry ?? {});
85
- }
86
- return undefined;
38
+ // The model gateway saved in the console (model-gateway.ts), read from the store at each claim and laid over the run
39
+ // environment as its variables would be, so a gateway saved or removed since reaches the next run with no restart. A
40
+ // gateway the runner's environment names wins, and nothing saved is read over it.
41
+ const deps = await withSavedGatewayDeps(given);
42
+ const made = await loopOn(deps, harness, launch, runId);
43
+ return made && holdingGatewayKey(made, deps.env);
87
44
  };
88
45
  }
46
+ /** `made` with the saved gateway's key, as this claim read it, held by the run's one redactor before the loop starts: the
47
+ * key stays off the claim's tool keys (claimSecrets), and a later scan of the store (holdStored) would find only a key
48
+ * saved since, so a gateway reply that echoes this one is cut in the run's records and logs all the same. `made` itself
49
+ * where the gateway is not the saved one. */
50
+ function holdingGatewayKey(made, env) {
51
+ const key = env && savedGatewayIn(env) ? env[GATEWAY_KEY_ENV] : undefined;
52
+ if (!key)
53
+ return made;
54
+ return (loopDeps) => {
55
+ if (loopDeps.redact)
56
+ heldRedactor(loopDeps.redact).hold([key]);
57
+ return made(loopDeps);
58
+ };
59
+ }
60
+ /** The loop a claimed run runs on, over `deps` (the saved gateway laid over its environment). */
61
+ async function loopOn(deps, harness, launch, runId) {
62
+ // A workflow revision runs on the workflow loop whatever the harness its body names (its default is pi): read the
63
+ // revision to tell it apart from an agentic pi run.
64
+ const run = await deps.store.runs.get(runId);
65
+ const revision = run ? await deps.store.agents.revision(run.revisionId) : undefined;
66
+ if (revision && isWorkflowRevision(revision)) {
67
+ // A workflow run on the workflow loop: its claim-time spec (workflow-spec.ts) resolves each tier's model the one way
68
+ // the runner resolves any (routeProviderOf over the route, the default when no providerOf is given).
69
+ // The runner's seal key and data directory go with it: a claim's sealed secrets are read with them (claim-secrets.ts,
70
+ // store-secrets.ts), and every one the server keeps is held by the run's one redactor.
71
+ return createWorkflowLoop(workflowSpecOf({ store: deps.store, sealKey: deps.sealKey, data: deps.data, ...(deps.env ? { env: deps.env } : {}) }));
72
+ }
73
+ // A backend SDK run's compile turn is asked on the runner's one model route, on the agent's own model (its learning
74
+ // start's), its key from the runner's environment, else the one saved in Settings → Model keys, read at each ask.
75
+ if (launch.sdk)
76
+ return createSdkLoop(launch, deps, async () => {
77
+ const base = deps.env ?? process.env;
78
+ const env = withModelKeys(base, await savedModelKeys({ store: deps.store, sealKey: deps.sealKey, env: base }));
79
+ // It runs after its backend reported the run complete, on no run's key: on a server that holds no gateway key it is
80
+ // skipped in words (run-model-key.ts noServerKeyFor), nothing sent.
81
+ const off = noServerKeyFor(env, "An SDK run's compile turn");
82
+ if (off) {
83
+ deps.log?.(off);
84
+ throw new Error(off);
85
+ }
86
+ return askRouteOf(launch.learning.model, env, (model) => deps.routeOf(model, env, "default", PI_WIRES));
87
+ });
88
+ if (launch.native)
89
+ return createNativeLoop(launch, deps);
90
+ // The harness's own entry decides which spec builds the run, by what the entry gives and never the harness's name: an
91
+ // entry with an adapter's facts and serve's own adapter for it (the CLI harnesses) runs the CLI spec (cli-run-spec.ts);
92
+ // any other (pi, or a harness module's entry that gives only the required members) runs the run spec
93
+ // (adapterRunSpecFromLaunch), whose adapter is its runner's (resolveHarness), with the record mode that runner names.
94
+ // A harness with no entry is unknown here: the dispatch fails it in words.
95
+ const env = deps.env ?? process.env;
96
+ const runner = resolveHarness(harness, env);
97
+ if (runner) {
98
+ // A run this host's memory never holds (host.ts neverFits: one run of its harness is more than the host has for runs)
99
+ // fails at its claim, in the words a start of it is refused in here (harness.ts harnessOffers): a run another host
100
+ // started, or one left before this host's memory shrank. Claimed alone (runner.ts claimByMemory), it would run past
101
+ // the host's memory and its OOM kill would take every run on it.
102
+ const tooBig = neverFits(harness, hostMemory(), env);
103
+ if (tooBig)
104
+ throw new NeverFits(tooBig);
105
+ const entry = harnessOf(env, harness);
106
+ // A run that learns supplies its own end-of-run step (reflect + proposal over its store) from its spec builder now,
107
+ // where the run's Archil claim is: a Mode 2 run's learning folder is on its claim's disk, not this machine's local
108
+ // path (adapter-run-spec.ts / cli-run-spec.ts endOfRun). The loop prefers the spec's step over its deps' (stepOf); a
109
+ // run that does not learn supplies none. The same for the pi and the CLI spec.
110
+ return createAdapterLoop((claim, adapterRun) => entry?.facts && entry.adapter
111
+ ? cliRunSpecFromLaunch(launch, adapterRun, deps, claim)
112
+ : adapterRunSpecFromLaunch(launch, adapterRun, deps, claim, runner), deps.modelRetry ?? {});
113
+ }
114
+ return undefined;
115
+ }
89
116
  /** The loop factory the runner holds for every run (its createLoop), built from the runner's deps over the one store: the
90
117
  * dispatch (dispatch.ts) reads each run's launch and asks resolveRunnerLoop for its harness loop. The server
91
118
  * start and the test server pass this to startRunner. */
@@ -95,3 +122,16 @@ export function dispatchRunner(deps) {
95
122
  resolve: resolveRunnerLoop(deps),
96
123
  });
97
124
  }
125
+ /** `deps` with the model gateway saved in the console laid over its run environment (model-gateway.ts withSavedGateway),
126
+ * read from the store now; `deps` itself where none is saved or the runner's environment names its own. A run's own
127
+ * process (no seal key) reads nothing of it: its runner laid it over the claim (run-child-host.ts) and marked it
128
+ * (SAVED_GATEWAY_ENV), and only that mark is read here. */
129
+ export async function withSavedGatewayDeps(deps) {
130
+ const base = deps.env ?? process.env;
131
+ if (envValue(base, SAVED_GATEWAY_ENV) === "1")
132
+ return { ...deps, env: savedGatewayMarked(base) };
133
+ if (envGatewayInForce(base) || !deps.sealKey)
134
+ return deps;
135
+ const saved = await readSavedGateway(deps.store, deps.sealKey);
136
+ return saved ? { ...deps, env: withSavedGateway(base, saved) } : deps;
137
+ }
@@ -2,13 +2,13 @@ import type { PlanReader } from "../chatgpt-plan.js";
2
2
  import type { Tier } from "../model.js";
3
3
  import type { RunSignIn } from "../sign-ins-store.js";
4
4
  import type { LiveHandover } from "../browser-live.js";
5
+ import type { ComputerHoldChange } from "./computer-journal.js";
5
6
  import type { ApprovalPrice, ToolEffect } from "../tool-gate.js";
6
7
  import type { OpenedAccount } from "../email/account.js";
7
8
  import type { SavedCalendar } from "../calendar/address.js";
8
9
  import type { Workspace } from "../workspace/workspace.js";
9
10
  import type { GithubAppAccessAt } from "./github-app.js";
10
11
  import type { HarnessInstallEntry, HarnessPins } from "../harness-install.js";
11
- import type { AlsoRow } from "../store/store.js";
12
12
  import type { RunModelKey } from "../store/seal.js";
13
13
  import type { EndOfRunKept, EndOfRunTurn } from "./loop-contract.js";
14
14
  import type { LearnedFirst } from "./learned-first.js";
@@ -90,6 +90,9 @@ export interface Held {
90
90
  /** A browser session's viewer handed over, and taken back (browser-live.ts). */
91
91
  liveViewerPut(handover: LiveHandover): Promise<boolean>;
92
92
  liveViewerDrop(tag?: string): Promise<void>;
93
+ /** A change of the claim's computer's hold, committed to the run's journal here: signalled on the runner, whose live
94
+ * view of the computer tells its open viewer (computer-journal.ts heardComputerHold). */
95
+ computerHold(change: ComputerHoldChange): Promise<void>;
93
96
  /** The MCP credentials run `from` was handed, sealed again for run `id`, a run this one starts (promotion.ts,
94
97
  * audit.ts): none unless `from` is the claim's own run. */
95
98
  handOn(from: string, id: string): Promise<Uint8Array | undefined>;
@@ -119,9 +122,7 @@ export interface Held {
119
122
  * what the run's learning must never keep is every secret the runner holds, which no run's process is given. Its
120
123
  * turns are asked through `input.ask`, the run's own session; `input.keptOf` is read once, for the round the runner
121
124
  * reads. */
122
- endOfRun(input: HeldEndOfRunInput): Promise<{
123
- readonly also: readonly AlsoRow[];
124
- } | undefined>;
125
+ endOfRun(input: HeldEndOfRunInput): Promise<Awaited<ReturnType<EndOfRunTurn>>>;
125
126
  /** The claim's learned first choice (learned-first.ts learnedFirst), run by the runner over the workflows it reads at the
126
127
  * claim's seed: `laid` says only whether the process's seed lay laid any (false: none is laid). Its audits, promotion
127
128
  * and replay reads are the runner's. */
@@ -74,6 +74,9 @@ export declare const KINDS: {
74
74
  * later claim that asks the same turn again reads the first ask's (the commit of main a compile turn was asked at among
75
75
  * them), never its own. Neither a call nor a message: the reader passes over it. */
76
76
  readonly endOfRunKept: "agentrun.end-of-run.kept";
77
+ /** A replay run's or an audit shadow's grader verdict (learn/promote.ts Compared), from its end-of-run step, written on
78
+ * the root before its end: its metrics carry it (`replay.compared`, `audit.compared`). Neither a call nor a message. */
79
+ readonly compared: "agentrun.learning.compared";
77
80
  /** How the run's job's own turn ended (JobEndData: the end it gives the run, a CLI's error answer), as the claim that
78
81
  * read it decided, written on the root before the end-of-run step asks its first turn. A claim that finds that turn
79
82
  * open ends the run on the newest one, never working the job's end out again. Neither a call nor a message. */
@@ -208,7 +211,7 @@ export interface CallEndData {
208
211
  readonly callId: string;
209
212
  readonly status: CallStatus;
210
213
  readonly output?: unknown;
211
- /** On an `interrupted` end the run's own end wrote (a call that only nests calls, still open: adapter-loop.ts openNests):
214
+ /** On an `interrupted` end the run's own end wrote (a CLI's call still open: adapter-loop.ts openCalls):
212
215
  * nothing ended it, so it has no outcome. Its row reads interrupted, never failed (CALL_ENDED_WITH_RUN). */
213
216
  readonly withRun?: true;
214
217
  /** When it was written (ms, the loop's clock): the Timeline dates the result's row by it. */
@@ -74,6 +74,9 @@ export const KINDS = {
74
74
  * later claim that asks the same turn again reads the first ask's (the commit of main a compile turn was asked at among
75
75
  * them), never its own. Neither a call nor a message: the reader passes over it. */
76
76
  endOfRunKept: "agentrun.end-of-run.kept",
77
+ /** A replay run's or an audit shadow's grader verdict (learn/promote.ts Compared), from its end-of-run step, written on
78
+ * the root before its end: its metrics carry it (`replay.compared`, `audit.compared`). Neither a call nor a message. */
79
+ compared: "agentrun.learning.compared",
77
80
  /** How the run's job's own turn ended (JobEndData: the end it gives the run, a CLI's error answer), as the claim that
78
81
  * read it decided, written on the root before the end-of-run step asks its first turn. A claim that finds that turn
79
82
  * open ends the run on the newest one, never working the job's end out again. Neither a call nor a message. */
@@ -1,5 +1,6 @@
1
1
  import type { AlsoRow, Claim, Command, Journal } from "../store/store.js";
2
2
  import type { Redact } from "./redact.js";
3
+ import type { Compared, GraderReply } from "../learn/promote.js";
3
4
  export type { AlsoRow, Claim, Command, Journal };
4
5
  /** Why a run ends failed when the answer it would end on was cut at the model's output limit (stopReason "length"): the
5
6
  * answer is unfinished, so the run never reads ended. `tokens`: what the cut answer used, when its harness says. */
@@ -64,9 +65,18 @@ export type EndOfRunTurn = (input: {
64
65
  * earlier claim (or this one) started, readable before `ask`, so a step that skips or is cut never asks, and still
65
66
  * closes that look-back with its first ask's figures. Undefined when none asked it, or the loop keeps no record (pi's). */
66
67
  keptOf?(round: number): EndOfRunKept | undefined;
68
+ /** A replay run's or an audit shadow's grader (learn/promote.ts): its fast model's name (`grader`), and one request to
69
+ * it (`grade`), sent through the run's own session on its one cap, booked as the run's spend; a refusal of that cap
70
+ * never parks the run (`refused`). Absent when the run has no grader route (no fast model, or agree_on named). */
71
+ readonly grader?: string;
72
+ grade?(request: {
73
+ readonly system: string;
74
+ readonly user: string;
75
+ }): Promise<GraderReply>;
67
76
  readonly signal: AbortSignal;
68
77
  }) => Promise<{
69
78
  readonly also: readonly AlsoRow[];
79
+ readonly compared?: Compared;
70
80
  } | undefined>;
71
81
  /** How a loop's start() ended. The run's own outcome (state, cost) is already in the journal's last commit. */
72
82
  export type LoopEnd = {
@@ -56,8 +56,8 @@ export declare class RunnerRefused extends Error {
56
56
  name: string;
57
57
  }
58
58
  /** The store, opened as a runner, its kind and its schema version: refused when its schema is one this build does not
59
- * know, or not set up yet. The one place the runner opens its store (store/open.ts: Postgres when AGENTRUN_STORE_URL
60
- * names one, else SQLite in the data directory). */
59
+ * know, not set up yet, or not yet upgraded by its server. The one place the runner opens its store (store/open.ts:
60
+ * Postgres when AGENTRUN_STORE_URL names one, else SQLite in the data directory). */
61
61
  export declare function openRunnerStore(dataDir: string, env: NodeJS.ProcessEnv, warn: (message: string) => void, url: string | undefined): Promise<{
62
62
  store: Store;
63
63
  kind: string;
@@ -174,9 +174,9 @@ export declare function lastResort(name: string, write?: (line: string) => void,
174
174
  * goes to stderr. Undefined for any other event. The runner beside a server says them the same way (beside.ts), so a
175
175
  * lapse of every claim at once shows its cause. */
176
176
  export declare function troubleLine(name: string, event: RunnerEvent): string | undefined;
177
- /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
178
- * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
179
- * it when --name does not. */
177
+ /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store this runner cannot open (a schema it does not
178
+ * know, none set up yet, or one its server has yet to upgrade); 1: anything else; 0: closed on a signal, or --check found
179
+ * a fresh heartbeat. AGENTRUN_RUNNER_NAME names it when --name does not. */
180
180
  export declare function runnerMain(argv: readonly string[], given?: NodeJS.ProcessEnv, hooks?: RunnerMainHooks): Promise<number>;
181
181
  /** A test's hooks into runnerMain: `started`, awaited once the runner has started claiming and before its stop handlers
182
182
  * take over from the ones its start listened on (the window a stop must not fall through). */
@@ -8,11 +8,13 @@
8
8
  // memory holds: the server's --max-runs default, host.ts maxRunsOf). SIGTERM or SIGINT closes it: each busy run finishes
9
9
  // its turn for up to --drain-timeout (default AGENTRUN_DRAIN_TIMEOUT, else RUNNER_DRAIN_TIMEOUT), then every loop left is stopped where it can resume
10
10
  // and its run handed back for another runner (a loop that never stops is given up when its claim would run out, and its
11
- // run is claimable when its lease lapses); then 0. Bad arguments exit 2, a store schema it does not know 3, anything else 1.
11
+ // run is claimable when its lease lapses); then 0. Bad arguments exit 2, a store it cannot open (yet) 3, anything else 1.
12
12
  // A run isolation it cannot give (run-child-host.ts runIsolationOf) is said, and it stays up claiming nothing until a stop: 0.
13
13
  // An error nothing handles exits 1 at once, said with its stack (lastResort).
14
+ import { randomUUID } from "node:crypto";
14
15
  import { mkdirSync, statSync, utimesSync, writeFileSync, writeSync } from "node:fs";
15
16
  import { join, resolve } from "node:path";
17
+ import { setTimeout as sleep } from "node:timers/promises";
16
18
  import { PROVIDERS } from "@parcha/agentrun-computer";
17
19
  import { startRunnerRelay } from "../dial-relay.js";
18
20
  import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
@@ -27,7 +29,7 @@ import { FAUX_ENV, FAUX_PREFIX, withoutFaux } from "../model.js";
27
29
  import { durationMs, runLine } from "../print.js";
28
30
  import { bootSealKey } from "../seal-key.js";
29
31
  import { handedSecret, SECRET_NAMES, secret } from "../secrets.js";
30
- import { migrationsIn, openStore, SchemaVersionUnknown, storePlace, storeTarget } from "../store/index.js";
32
+ import { migrationsIn, openStore, SchemaVersionUnknown, StoreAwaitsServer, storePlace, storeTarget } from "../store/index.js";
31
33
  import { SCHEMA_VERSION } from "../store/schema.js";
32
34
  import { SEAL_KEY_ENV, sealKeyOf } from "../tool-keys.js";
33
35
  import { FAUX_BROWSER_ENV } from "../tools.js";
@@ -48,14 +50,15 @@ import { RUN_PROCESS_MIB, runnerMemory } from "./memory-claim.js";
48
50
  import { childLoops, isolationLoops, RunIsolationRefused, runIsolationOf } from "./run-child-host.js";
49
51
  import { sweepEndedScratch } from "./scratch-sweep.js";
50
52
  import { RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
53
+ import { keepPresence } from "./presence.js";
51
54
  export { RUNNER_RENEW_EVERY_MS } from "./runner.js";
52
55
  /** A store this runner cannot use, or arguments it cannot take, in words a person starting it can act on. */
53
56
  export class RunnerRefused extends Error {
54
57
  name = "RunnerRefused";
55
58
  }
56
59
  /** The store, opened as a runner, its kind and its schema version: refused when its schema is one this build does not
57
- * know, or not set up yet. The one place the runner opens its store (store/open.ts: Postgres when AGENTRUN_STORE_URL
58
- * names one, else SQLite in the data directory). */
60
+ * know, not set up yet, or not yet upgraded by its server. The one place the runner opens its store (store/open.ts:
61
+ * Postgres when AGENTRUN_STORE_URL names one, else SQLite in the data directory). */
59
62
  export async function openRunnerStore(dataDir, env, warn, url) {
60
63
  // The store module owns where the store is (design: only the store adapter knows a file or a schema). The URL is this
61
64
  // process's secret (as the launcher handed it over), unless a test hands one.
@@ -68,6 +71,8 @@ export async function openRunnerStore(dataDir, env, warn, url) {
68
71
  return { store, kind: target.kind, schema: target.kind === "sqlite" ? SCHEMA_VERSION : migrationsIn().at(-1).version };
69
72
  }
70
73
  catch (error) {
74
+ if (error instanceof StoreAwaitsServer)
75
+ throw new RunnerRefused(`The store in ${where} is behind this runner: start the server first, which upgrades the store in place, then the runner.`, { cause: error });
71
76
  if (!(error instanceof SchemaVersionUnknown))
72
77
  throw error;
73
78
  const { found, known } = error;
@@ -218,6 +223,7 @@ export async function startRunnerProcess(options) {
218
223
  let seal;
219
224
  let janitor;
220
225
  let relay;
226
+ let presence;
221
227
  try {
222
228
  // The server's seal key, booted the one way the server boots it (seal-key.ts): the one handed over, else the one in
223
229
  // this data directory, checked against what the store records. A runner on a store whose secrets another key sealed
@@ -225,9 +231,13 @@ export async function startRunnerProcess(options) {
225
231
  // or records a key.
226
232
  seal = await bootSealKey(store, options.dataDir, { given: handedSecret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV], role: "runner" });
227
233
  const name = options.name ?? runnerName();
234
+ // One incarnation for this process: its word in the store that it is there (presence.ts) and its relay's minted
235
+ // tokens and proofs name the same one, so the server's "restarted since" and the runner's row speak of one process.
236
+ // The presence first, then the relay says where it answers on the presence's row.
237
+ presence = keepPresence(store.runners, name, null, { warn, incarnation: randomUUID() });
228
238
  // Its relay (dial-relay.ts), where its environment names the server's public address: a machine that dials the
229
239
  // server lands in this runner's hub, through the server. Its log lines are the runner's warnings.
230
- relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, env, log: warn });
240
+ relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, presence, env, log: warn });
231
241
  const made = options.createLoop ?? ofStore((opened, sealKey, dial) => runnerLoop(opened, options.dataDir, undefined, sealKey, undefined, dial));
232
242
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
233
243
  const parts = isStoreFactory(made) ? made(store, seal.key, relay?.dial) : made;
@@ -244,6 +254,7 @@ export async function startRunnerProcess(options) {
244
254
  store,
245
255
  createLoop,
246
256
  name,
257
+ presence,
247
258
  ...(options.loops ? { loops: options.loops } : {}),
248
259
  ...(options.drainMs ? { drainMs: options.drainMs } : {}),
249
260
  memory,
@@ -255,6 +266,7 @@ export async function startRunnerProcess(options) {
255
266
  catch (error) {
256
267
  await janitor?.close();
257
268
  await relay?.close();
269
+ await presence?.close();
258
270
  seal?.release();
259
271
  await store.close();
260
272
  throw error;
@@ -262,6 +274,7 @@ export async function startRunnerProcess(options) {
262
274
  let closing;
263
275
  const held = seal;
264
276
  const relayed = relay;
277
+ const kept = presence;
265
278
  return {
266
279
  runner,
267
280
  store: { kind, schema },
@@ -269,8 +282,10 @@ export async function startRunnerProcess(options) {
269
282
  close: () => (closing ??= (async () => {
270
283
  // The janitor's sweep is cut and waited for on its own bound, beside the runner's close, never before it.
271
284
  await Promise.all([janitor?.close(), runner.close()]);
272
- // Its relay after its runs: a run's release revokes its machine's token through it.
285
+ // Its relay after its runs: a run's release revokes its machine's token through it. Then its word that it is
286
+ // there: it claims no more.
273
287
  await relayed?.close();
288
+ await kept.close();
274
289
  // A first-use install its claims started, stopped as they let go: its npm ends before this process can.
275
290
  await claimInstallsStopped();
276
291
  await store.close();
@@ -431,9 +446,9 @@ export function troubleLine(name, event) {
431
446
  return `Runner ${name}: ${event.step}${event.runId ? ` ${event.runId}` : ""}: ${event.message}`;
432
447
  return undefined;
433
448
  }
434
- /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store schema this runner does not know (or none
435
- * set up yet); 1: anything else; 0: closed on a signal, or --check found a fresh heartbeat. AGENTRUN_RUNNER_NAME names
436
- * it when --name does not. */
449
+ /** `agentrun-serve runner ...`: the exit code. 2: bad arguments; 3: a store this runner cannot open (a schema it does not
450
+ * know, none set up yet, or one its server has yet to upgrade); 1: anything else; 0: closed on a signal, or --check found
451
+ * a fresh heartbeat. AGENTRUN_RUNNER_NAME names it when --name does not. */
437
452
  export async function runnerMain(argv, given = process.env, hooks = {}) {
438
453
  let args;
439
454
  try {
@@ -506,7 +521,10 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
506
521
  // Said, then up and claiming nothing until a stop: in the image's server-and-runner either process's exit stops the
507
522
  // container, which a platform that restarts it (Render, Railway) would loop on, the refusal lost in the restarts.
508
523
  console.error(`agentrun-serve runner: ${error.message}`);
509
- await untilSignalled(RUNNER_SIGNALS);
524
+ // And said in the store until the stop (presence.ts), so the server, in its own process or on another host, refuses a
525
+ // launch in these words and fails the runs left queued while no runner that claims is there.
526
+ const stop = untilSignalled(RUNNER_SIGNALS);
527
+ await refusedInStore(args.dataDir, env, name ?? runnerName(), error.message, stop);
510
528
  return 0;
511
529
  }
512
530
  if (isolation.kind === "uid" && holds.loops > isolation.slots)
@@ -557,7 +575,7 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
557
575
  catch (error) {
558
576
  unlisten();
559
577
  console.error(`agentrun-serve runner: ${error?.message ?? String(error)}`);
560
- return error instanceof RunnerRefused && error.cause instanceof SchemaVersionUnknown ? 3 : 1;
578
+ return error instanceof RunnerRefused && (error.cause instanceof SchemaVersionUnknown || error.cause instanceof StoreAwaitsServer) ? 3 : 1;
561
579
  }
562
580
  await hooks.started?.(started);
563
581
  // From here the handlers below take the stop, with nothing awaited between: no signal falls in a gap.
@@ -578,6 +596,39 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
578
596
  }
579
597
  /** The signals that stop a runner process. */
580
598
  const RUNNER_SIGNALS = ["SIGTERM", "SIGINT"];
599
+ /** How long a refusing runner waits before it tries its store again (refusedInStore). */
600
+ const REFUSED_STORE_RETRY_MS = 5_000;
601
+ /** A runner whose run isolation was refused: its `words` kept in its store (presence.ts) until `stopped`, then its row
602
+ * removed and the store closed. A store that does not open (not set up yet, one its server has yet to upgrade, a
603
+ * connection down) is said, once for each reason, and tried again every REFUSED_STORE_RETRY_MS until it opens or the
604
+ * stop: a runner that starts before its server still tells that server, once it is there. */
605
+ async function refusedInStore(dataDir, env, name, words, stopped) {
606
+ const warn = (line) => void console.error(`agentrun-serve runner: ${line}`);
607
+ let stop = false;
608
+ void stopped.then(() => void (stop = true));
609
+ let said;
610
+ while (!stop) {
611
+ let store;
612
+ try {
613
+ ({ store } = await openRunnerStore(dataDir, env, warn, undefined));
614
+ }
615
+ catch (error) {
616
+ const why = error?.message ?? String(error);
617
+ if (why !== said)
618
+ warn(`the server is not told yet that this runner claims nothing, since its store did not open (tried again every ${REFUSED_STORE_RETRY_MS / 1000} s): ${why}`);
619
+ said = why;
620
+ await Promise.race([sleep(REFUSED_STORE_RETRY_MS, undefined, { ref: false }), stopped]);
621
+ continue;
622
+ }
623
+ if (said !== undefined)
624
+ warn("its store opened: the server is told that this runner claims nothing");
625
+ const presence = keepPresence(store.runners, name, words, { warn });
626
+ await stopped;
627
+ await presence.close();
628
+ await store.close();
629
+ return;
630
+ }
631
+ }
581
632
  /** Holds the process up, with nothing else to do, until one of `signals`. */
582
633
  function untilSignalled(signals) {
583
634
  return new Promise((resolve) => {
@@ -25,6 +25,9 @@
25
25
  // opens it again, so a message's new credential reaches the run's next model request; a run handed none gets its calls
26
26
  // refused unsent (UNUSABLE.perRunMissing).
27
27
  //
28
+ // A per-run Composio server (composio-made.ts composioPerRun) is bound by each run's caller ({composio_user_id,
29
+ // connected_account_id?} in mcp_auth, sealed in its launch): its entry carries them as `query` (mcp-gateway.ts).
30
+ //
28
31
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
29
32
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
30
33
  // only when it provably never left: a refused or unmade connection, an address check out of time; one request that left
@@ -50,6 +53,8 @@ import { randomUUID } from "node:crypto";
50
53
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
51
54
  import { pinFirst } from "../mcp-pin-first.js";
52
55
  import { mcpNameOf } from "../tool-names.js";
56
+ import { composioMadeKey, composioPerRun } from "../composio-made.js";
57
+ import { composioRunQuery } from "../composio-preset.js";
53
58
  import { META_REASON, metaToolOf } from "../mcp-meta.js";
54
59
  import { credentialInQuery, credentialInQueryWords, shownUrl } from "../mcp-probe.js";
55
60
  import { privateOAuthHosts } from "../mcp-private-hosts.js";
@@ -193,10 +198,14 @@ export async function mcpClaim(options) {
193
198
  // Held by the run's redactor before anything else: a value opened is a value to cut, sent or not.
194
199
  if (extra.headers)
195
200
  options.hold?.(credentialValues(extra.headers));
201
+ if (extra.query)
202
+ options.hold?.(Object.values(extra.query));
196
203
  if (released || gone.has(name))
197
204
  return;
198
- // Headers go only to the URL the run was pinned to: a server moved since is refused per call by the gateway.
199
- credentials[name] = { url: row.url, ...(extra.unopened ? { unopened: extra.unopened } : extra.headers && row.url === pinnedUrl ? { headers: extra.headers } : {}) };
205
+ // Headers and a run's account go only to the URL the run was pinned to: a server moved since is refused per call by
206
+ // the gateway.
207
+ const pinned = row.url === pinnedUrl;
208
+ credentials[name] = { url: row.url, ...(extra.unopened ? { unopened: extra.unopened } : { ...(extra.headers && pinned ? { headers: extra.headers } : {}), ...(extra.query && pinned ? { query: extra.query } : {}) }) };
200
209
  };
201
210
  // A GitHub App's server keeps no credential: its token is minted for this run (awaited, so the claim is confirmed
202
211
  // after it), kept fresh mid-run, and never stored.
@@ -206,15 +215,20 @@ export async function mcpClaim(options) {
206
215
  // run's launch, read again at every fresh() so a message's new one reaches the run's next request.
207
216
  if (row.auth === "per_run")
208
217
  return entry(await perRun(name, row.url)), { awaited: false };
218
+ // A per-run Composio server: the run's account, or its calls refused unsent; its key is opened below as any server's.
219
+ const account = row.auth === "headers" ? await composioAccount(name, row) : undefined;
220
+ if (account && "unopened" in account)
221
+ return entry({ unopened: account.unopened }), { awaited: false };
222
+ const query = account?.query;
209
223
  if (row.sealed === null)
210
- return entry({}), { awaited: false };
224
+ return entry({ ...(query ? { query } : {}) }), { awaited: false };
211
225
  // A seal problem first: no refresh is ever sent for a credential this runner cannot open.
212
226
  const opened = openMcpRow(sealKey, row);
213
227
  if (!("credential" in opened))
214
228
  return entry(opened.unusable === "none" ? {} : { unopened: UNUSABLE.damaged }), { awaited: false };
215
229
  const credential = opened.credential;
216
230
  if (credential.type === "headers")
217
- return entry({ headers: { ...credential.headers } }), { awaited: false };
231
+ return entry({ headers: { ...credential.headers }, ...(query ? { query } : {}) }), { awaited: false };
218
232
  const oauth = credential;
219
233
  if (oauth.expired)
220
234
  return entry({ unopened: UNUSABLE.signedOut }), { awaited: false };
@@ -346,19 +360,33 @@ export async function mcpClaim(options) {
346
360
  };
347
361
  /** The run's handed MCP credentials, opened from its launch: read once per fresh() (perRunRead), not once per server. */
348
362
  let perRunRead;
349
- /** A per_run server's headers for this run, from its launch; or why there are none. Only for the origin its url had
350
- * when they were handed: a server moved since gets none. */
351
- const perRun = async (name, url) => {
363
+ /** What the run's caller handed `name` (mcp_auth, opened from its launch) when it is of `shape`; or why there is none.
364
+ * Only for the origin its url had when it was handed: a server moved since gets none. */
365
+ const handed = async (name, url, shape) => {
352
366
  perRunRead ??= store.runs.launch(claim.runId).then((launch) => openRunMcpAuth(sealKey, claim.runId, launch.sealed));
353
- const handed = await perRunRead;
354
- if (handed === undefined)
367
+ const all = await perRunRead;
368
+ if (all === undefined)
355
369
  return { unopened: UNUSABLE.damaged };
356
- const given = Object.hasOwn(handed, name) ? handed[name] : undefined;
357
- if (!given)
370
+ const given = Object.hasOwn(all, name) ? all[name] : undefined;
371
+ if (!given || !(shape in given))
358
372
  return { unopened: UNUSABLE.perRunMissing };
359
373
  if (given.origin !== new URL(url).origin)
360
374
  return { unopened: UNUSABLE.damaged };
361
- return { headers: { ...given.headers } };
375
+ return given;
376
+ };
377
+ /** A per_run server's headers for this run; or why there are none. */
378
+ const perRun = async (name, url) => {
379
+ const given = await handed(name, url, "headers");
380
+ return "unopened" in given ? given : { headers: { ...given.headers } };
381
+ };
382
+ /** A per-run Composio server's account for this run, as the query its requests add (composio-preset.ts
383
+ * composioRunQuery); or why there is none. Undefined: `row` is no per-run Composio server (its own record says so:
384
+ * composioPerRun). */
385
+ const composioAccount = async (name, row) => {
386
+ if (!composioPerRun(row, await store.settings.get(composioMadeKey(name))))
387
+ return undefined;
388
+ const given = await handed(name, row.url, "composio");
389
+ return "unopened" in given ? given : { query: composioRunQuery(given.composio) };
362
390
  };
363
391
  const fresh = async () => {
364
392
  if (!pin || released)
@@ -8,6 +8,11 @@ import { type CostParts } from "@parcha/agentrun-kernel";
8
8
  * its runner.request's model, "" for one that names none). `free`: it booked requests, every one on a free model (its
9
9
  * runner.turn's `free`: its known price $0 for every token), so its $0 says why. A reader that joins sessions, or says
10
10
  * what is known of an unknown cost, takes the parts through costOfParts, never `usd` and `known` alone. */
11
+ /** `priced`: of its requests with a known figure (a plan's aside, which cost no dollars), how many the provider or its
12
+ * gateway priced (`reported`: the proxy's reportedCostOf or usageCostOf, its runner.turn keeping the table's figure beside
13
+ * it as `tableUsd`) and how many a price table did (`estimated`: its runner.turn's `estimated`, or a cut request's hold,
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. */
11
16
  export type BookedSpend = {
12
17
  readonly usd: number | null;
13
18
  readonly known: number;
@@ -23,8 +28,28 @@ export type BookedSpend = {
23
28
  cacheRead: number;
24
29
  cacheWrite: number;
25
30
  };
31
+ readonly priced: {
32
+ readonly reported: number;
33
+ readonly estimated: number;
34
+ };
26
35
  readonly free?: true;
27
36
  };
37
+ /** How a run's cost was reached, by how its model requests were priced: `reported` when every request priced had the
38
+ * provider's or its gateway's own figure (LiteLLM's `x-litellm-response-cost`, OpenRouter's usage `cost`); `estimate`
39
+ * when any was priced from a price table (the catalog, AGENT_MODEL_PRICE, a cut request's hold); `unpriced` when no
40
+ * request was priced (none was sent, or none had a figure). The run's cost block (`cost.basis`), its stored metrics
41
+ * (`costBasis`) and the sums over runs (GET /stats, GET /usage) say it in these words. */
42
+ export declare const COST_BASES: readonly ["reported", "estimate", "unpriced"];
43
+ export type CostBasis = (typeof COST_BASES)[number];
44
+ /** The basis of a booking's model requests (bookedSpend "model"): COST_BASES. */
45
+ export declare const costBasisOf: (spend: Pick<BookedSpend, "priced">) => CostBasis;
46
+ /** The basis of a sum of costs: `estimate` when any is, else `reported` when any is, else `unpriced`. */
47
+ export declare function joinedBasis(bases: Iterable<CostBasis>): CostBasis;
48
+ /** A run's basis as its end stored it (its metrics' `costBasis`); an imported run's catalog estimate (import.ts stores
49
+ * `costBasis: "catalog"` beside `costUsdEst`, the figure store-reads/runs.ts costOfRun reads) is an `estimate`, at $0 too;
50
+ * a run that stored none (one that ended before the end stored it, a workflow's, a native, SDK or imported run's: their
51
+ * figures are the harness's) is an `estimate` when it cost anything, else `unpriced`. */
52
+ export declare function storedBasisOf(metrics: unknown, usd: number | null | undefined): CostBasis;
28
53
  /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
29
54
  * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
30
55
  * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
@@ -114,6 +139,7 @@ export declare function bookedListSpend(entries: readonly EntryLike[]): number |
114
139
  export type RunMetricsStored = RunMetrics & {
115
140
  effort?: string;
116
141
  model?: string;
142
+ costBasis?: CostBasis;
117
143
  };
118
144
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
119
145
  * `effort`/`model`: the enrichment the old storedMetrics added. `catalog`: the run's MCP tools called by a hashed wire