@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58

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 (312) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +246 -66
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +15 -5
  11. package/dist/api-only.js +32 -8
  12. package/dist/box-paths.d.ts +4 -3
  13. package/dist/box-paths.js +7 -4
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/chatgpt-plan.d.ts +18 -8
  19. package/dist/chatgpt-plan.js +91 -34
  20. package/dist/claude-login-token.d.ts +117 -0
  21. package/dist/claude-login-token.js +737 -0
  22. package/dist/claude-login.d.ts +120 -22
  23. package/dist/claude-login.js +347 -63
  24. package/dist/claude-sign-in.d.ts +17 -6
  25. package/dist/claude-sign-in.js +42 -39
  26. package/dist/cli.js +33 -10
  27. package/dist/composio-made.d.ts +4 -0
  28. package/dist/composio-made.js +4 -0
  29. package/dist/composio-preset.d.ts +43 -2
  30. package/dist/composio-preset.js +92 -4
  31. package/dist/computer-attach.d.ts +35 -17
  32. package/dist/computer-attach.js +301 -49
  33. package/dist/computer-held-routes.d.ts +5 -4
  34. package/dist/computer-held-routes.js +29 -8
  35. package/dist/computer-held.d.ts +6 -1
  36. package/dist/computer-held.js +14 -0
  37. package/dist/computer-record.js +4 -2
  38. package/dist/computer-viewer.js +4 -1
  39. package/dist/computers.d.ts +10 -10
  40. package/dist/computers.js +5 -5
  41. package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
  42. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  43. package/dist/console/assets/index-DPh29cyz.js +747 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/decisions.d.ts +1 -1
  46. package/dist/decisions.js +1 -1
  47. package/dist/dial-relay.d.ts +25 -4
  48. package/dist/dial-relay.js +129 -1
  49. package/dist/docker-host-addresses.d.ts +22 -11
  50. package/dist/docker-host-addresses.js +38 -26
  51. package/dist/env-switch.d.ts +8 -0
  52. package/dist/env-switch.js +31 -2
  53. package/dist/errors.d.ts +1 -0
  54. package/dist/errors.js +2 -0
  55. package/dist/fal-price.d.ts +56 -20
  56. package/dist/fal-price.js +400 -90
  57. package/dist/handed-values.d.ts +43 -1
  58. package/dist/handed-values.js +119 -2
  59. package/dist/harness-archive.d.ts +13 -10
  60. package/dist/harness-archive.js +60 -34
  61. package/dist/harness-check.d.ts +3 -1
  62. package/dist/harness-check.js +25 -46
  63. package/dist/harness-keys.d.ts +73 -27
  64. package/dist/harness-keys.js +194 -61
  65. package/dist/harness-recipe-entry.d.ts +8 -7
  66. package/dist/harness-recipe-entry.js +21 -32
  67. package/dist/harness-recipe.d.ts +38 -25
  68. package/dist/harness-recipe.js +49 -36
  69. package/dist/harness-sign-in.js +12 -23
  70. package/dist/harness-table.d.ts +10 -3
  71. package/dist/harness-table.js +26 -21
  72. package/dist/harness.d.ts +1 -0
  73. package/dist/harness.js +17 -5
  74. package/dist/hosted-search.d.ts +1 -1
  75. package/dist/hosted-search.js +1 -2
  76. package/dist/import-worker.d.ts +4 -2
  77. package/dist/import-worker.js +9 -2
  78. package/dist/in-flight.d.ts +26 -0
  79. package/dist/in-flight.js +52 -0
  80. package/dist/key-refusal.d.ts +9 -4
  81. package/dist/key-refusal.js +107 -25
  82. package/dist/learn/ledger.d.ts +170 -0
  83. package/dist/learn/ledger.js +218 -0
  84. package/dist/learn/promote.d.ts +3 -3
  85. package/dist/learn/promote.js +1 -1
  86. package/dist/learn/secrets.d.ts +13 -3
  87. package/dist/learn/secrets.js +118 -17
  88. package/dist/learning-cost.d.ts +28 -23
  89. package/dist/learning-cost.js +19 -23
  90. package/dist/link-check.js +1 -1
  91. package/dist/live-reach.d.ts +2 -0
  92. package/dist/live-reach.js +2 -0
  93. package/dist/llms.txt +1 -1
  94. package/dist/marketplace.d.ts +77 -0
  95. package/dist/marketplace.js +224 -0
  96. package/dist/mcp-api-only-origins.d.ts +35 -0
  97. package/dist/mcp-api-only-origins.js +57 -0
  98. package/dist/mcp-gateway.d.ts +7 -5
  99. package/dist/mcp-gateway.js +9 -12
  100. package/dist/mcp-secret-writes.js +5 -3
  101. package/dist/mcp-servers-store.d.ts +28 -6
  102. package/dist/mcp-servers-store.js +53 -4
  103. package/dist/media-duration.d.ts +3 -0
  104. package/dist/media-duration.js +90 -9
  105. package/dist/micro.d.ts +2 -0
  106. package/dist/micro.js +2 -0
  107. package/dist/model-form.d.ts +5 -4
  108. package/dist/model-form.js +11 -7
  109. package/dist/model.d.ts +10 -6
  110. package/dist/model.js +16 -11
  111. package/dist/monid.d.ts +14 -1
  112. package/dist/monid.js +103 -26
  113. package/dist/ollama-provider.d.ts +7 -1
  114. package/dist/ollama-provider.js +14 -2
  115. package/dist/openapi.js +210 -37
  116. package/dist/otel/genai.d.ts +65 -0
  117. package/dist/otel/genai.js +116 -0
  118. package/dist/otel/tracer.d.ts +55 -0
  119. package/dist/otel/tracer.js +308 -0
  120. package/dist/page.d.ts +2 -0
  121. package/dist/page.js +3 -1
  122. package/dist/paid-calls.d.ts +1 -32
  123. package/dist/paid-calls.js +4 -39
  124. package/dist/place-offers.d.ts +4 -0
  125. package/dist/place-offers.js +7 -4
  126. package/dist/provider.d.ts +11 -2
  127. package/dist/provider.js +59 -8
  128. package/dist/redact/match.d.ts +30 -3
  129. package/dist/redact/match.js +422 -41
  130. package/dist/refusal-words.d.ts +11 -0
  131. package/dist/refusal-words.js +11 -0
  132. package/dist/run-census.d.ts +67 -0
  133. package/dist/run-census.js +240 -0
  134. package/dist/run-computer.d.ts +6 -3
  135. package/dist/run-computer.js +4 -1
  136. package/dist/run-cut.d.ts +15 -6
  137. package/dist/run-cut.js +30 -9
  138. package/dist/run-files.d.ts +3 -0
  139. package/dist/run-files.js +3 -0
  140. package/dist/run-launch.d.ts +12 -1
  141. package/dist/run-launch.js +9 -10
  142. package/dist/run-learning-served.d.ts +4 -2
  143. package/dist/run-model-key.d.ts +8 -0
  144. package/dist/run-model-key.js +31 -1
  145. package/dist/run-reads-over-store.d.ts +24 -6
  146. package/dist/run-reads-over-store.js +67 -23
  147. package/dist/run-recordings.d.ts +5 -1
  148. package/dist/run-recordings.js +39 -14
  149. package/dist/run-timeline-served.d.ts +2 -0
  150. package/dist/run-timeline-served.js +2 -2
  151. package/dist/run-usage.d.ts +1 -0
  152. package/dist/run-view.d.ts +1 -2
  153. package/dist/run-view.js +2 -1
  154. package/dist/runnable.d.ts +10 -1
  155. package/dist/runnable.js +20 -8
  156. package/dist/runner/adapter-loop.d.ts +11 -0
  157. package/dist/runner/adapter-loop.js +58 -26
  158. package/dist/runner/adapter-run-spec.d.ts +55 -11
  159. package/dist/runner/adapter-run-spec.js +183 -52
  160. package/dist/runner/adapters/pi.js +25 -3
  161. package/dist/runner/beside.d.ts +9 -2
  162. package/dist/runner/beside.js +27 -9
  163. package/dist/runner/big-writes.js +1 -10
  164. package/dist/runner/claim-secrets.d.ts +27 -10
  165. package/dist/runner/claim-secrets.js +49 -22
  166. package/dist/runner/cli-run-spec.d.ts +6 -0
  167. package/dist/runner/cli-run-spec.js +97 -38
  168. package/dist/runner/computer-journal.d.ts +9 -1
  169. package/dist/runner/computer-journal.js +26 -0
  170. package/dist/runner/conformance/harness.js +1 -1
  171. package/dist/runner/feedback-round.js +3 -0
  172. package/dist/runner/harness-loops.d.ts +6 -5
  173. package/dist/runner/harness-loops.js +7 -7
  174. package/dist/runner/held.d.ts +24 -6
  175. package/dist/runner/journal-kinds.d.ts +5 -0
  176. package/dist/runner/journal-kinds.js +5 -0
  177. package/dist/runner/main.d.ts +11 -6
  178. package/dist/runner/main.js +19 -9
  179. package/dist/runner/mcp-claim.js +31 -3
  180. package/dist/runner/mcp-run.d.ts +9 -0
  181. package/dist/runner/mcp-run.js +11 -5
  182. package/dist/runner/model-route.d.ts +17 -0
  183. package/dist/runner/model-route.js +120 -2
  184. package/dist/runner/presence.d.ts +11 -1
  185. package/dist/runner/presence.js +7 -0
  186. package/dist/runner/reflect-hook.js +1 -1
  187. package/dist/runner/run-child-host.d.ts +22 -8
  188. package/dist/runner/run-child-host.js +128 -41
  189. package/dist/runner/run-child.js +5 -2
  190. package/dist/runner/runner.d.ts +17 -3
  191. package/dist/runner/runner.js +130 -34
  192. package/dist/runner/save-slots.js +2 -1
  193. package/dist/runner/store-port.d.ts +1 -1
  194. package/dist/runner/store-secrets.d.ts +6 -0
  195. package/dist/runner/store-secrets.js +49 -7
  196. package/dist/runner/subagent.d.ts +11 -0
  197. package/dist/runner/subagent.js +16 -38
  198. package/dist/runner/workflow-first.d.ts +35 -15
  199. package/dist/runner/workflow-first.js +38 -25
  200. package/dist/runner/workflow-spec.js +4 -3
  201. package/dist/runs-over-store.d.ts +15 -6
  202. package/dist/runs-over-store.js +33 -21
  203. package/dist/scrub-command.d.ts +73 -0
  204. package/dist/scrub-command.js +307 -0
  205. package/dist/secret-cut.d.ts +73 -0
  206. package/dist/secret-cut.js +291 -4
  207. package/dist/secret-rules.d.ts +143 -0
  208. package/dist/secret-rules.js +2564 -0
  209. package/dist/secrets.d.ts +7 -0
  210. package/dist/secrets.js +20 -0
  211. package/dist/server-keys.d.ts +20 -0
  212. package/dist/server-keys.js +25 -6
  213. package/dist/server.d.ts +65 -13
  214. package/dist/server.js +470 -157
  215. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  216. package/dist/slots.d.ts +9 -0
  217. package/dist/slots.js +45 -0
  218. package/dist/store/index.d.ts +1 -1
  219. package/dist/store/index.js +1 -1
  220. package/dist/store/journal/storage.js +1 -1
  221. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  222. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  223. package/dist/store/schema.d.ts +23 -0
  224. package/dist/store/schema.js +58 -2
  225. package/dist/store/seal.d.ts +6 -1
  226. package/dist/store/seal.js +5 -3
  227. package/dist/store/sqlite/run-launch.d.ts +9 -1
  228. package/dist/store/sqlite/run-launch.js +24 -13
  229. package/dist/store/sqlite/run-patch.d.ts +12 -2
  230. package/dist/store/sqlite/run-patch.js +42 -5
  231. package/dist/store/sqlite/store.js +105 -12
  232. package/dist/store/store.d.ts +57 -2
  233. package/dist/store/store.js +20 -0
  234. package/dist/store-reads/learning.d.ts +84 -124
  235. package/dist/store-reads/learning.js +210 -274
  236. package/dist/store-view.d.ts +3 -0
  237. package/dist/store-view.js +3 -3
  238. package/dist/suggestions.js +3 -2
  239. package/dist/template-eval.d.ts +39 -9
  240. package/dist/template-eval.js +191 -60
  241. package/dist/template-import.js +6 -2
  242. package/dist/templates.d.ts +10 -2
  243. package/dist/templates.js +28 -8
  244. package/dist/timeline/labels.d.ts +6 -4
  245. package/dist/timeline/labels.js +18 -6
  246. package/dist/timeline/timeline.d.ts +5 -0
  247. package/dist/timeline/timeline.js +14 -8
  248. package/dist/timeline/util.js +1 -1
  249. package/dist/timeline/web-calls.d.ts +22 -7
  250. package/dist/timeline/web-calls.js +106 -35
  251. package/dist/tool-gate.d.ts +42 -3
  252. package/dist/tool-gate.js +66 -5
  253. package/dist/tool-keys-store.d.ts +2 -4
  254. package/dist/tool-keys-store.js +5 -21
  255. package/dist/tool-keys.d.ts +2 -2
  256. package/dist/tool-keys.js +2 -2
  257. package/dist/tool-list.js +1 -1
  258. package/dist/tool-plane.d.ts +2 -2
  259. package/dist/tool-plane.js +35 -33
  260. package/dist/tools.js +13 -7
  261. package/dist/trigger-targets.d.ts +4 -0
  262. package/dist/trigger-targets.js +9 -2
  263. package/dist/triggers.d.ts +67 -4
  264. package/dist/triggers.js +171 -22
  265. package/dist/until.d.ts +3 -0
  266. package/dist/until.js +11 -0
  267. package/dist/web-fake.d.ts +1 -3
  268. package/dist/web-fake.js +7 -18
  269. package/dist/web-fetch.d.ts +6 -72
  270. package/dist/web-fetch.js +11 -265
  271. package/dist/web-run.d.ts +31 -0
  272. package/dist/web-run.js +90 -0
  273. package/dist/web-save.d.ts +10 -13
  274. package/dist/web-save.js +13 -55
  275. package/dist/web-search.d.ts +9 -127
  276. package/dist/web-search.js +23 -259
  277. package/dist/wires.d.ts +13 -0
  278. package/dist/wires.js +11 -0
  279. package/dist/workflow-run.d.ts +5 -4
  280. package/dist/workflow-run.js +5 -4
  281. package/dist/workspace/attached-computers.d.ts +32 -9
  282. package/dist/workspace/attached-computers.js +77 -13
  283. package/dist/workspace/computer-deps.d.ts +8 -2
  284. package/dist/workspace/computer-deps.js +10 -3
  285. package/dist/workspace/computer-for-claim.d.ts +12 -1
  286. package/dist/workspace/computer-for-claim.js +83 -11
  287. package/dist/workspace/computer-kept.d.ts +3 -0
  288. package/dist/workspace/computer-kept.js +11 -2
  289. package/dist/workspace/index.d.ts +1 -1
  290. package/dist/workspace/index.js +1 -1
  291. package/dist/workspace/kind-skills.d.ts +4 -0
  292. package/dist/workspace/kind-skills.js +9 -0
  293. package/dist/workspace/paired-route.d.ts +91 -0
  294. package/dist/workspace/paired-route.js +153 -0
  295. package/dist/workspace/synced-folder.js +3 -4
  296. package/dist/wrapped.d.ts +20 -6
  297. package/dist/wrapped.js +66 -25
  298. package/package.json +17 -11
  299. package/skills/agentrun-serve/SKILL.md +4 -0
  300. package/templates/README.md +32 -10
  301. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  302. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  303. package/dist/exa-keyless.d.ts +0 -34
  304. package/dist/exa-keyless.js +0 -118
  305. package/dist/firecrawl-keyless.d.ts +0 -41
  306. package/dist/firecrawl-keyless.js +0 -152
  307. package/dist/keyless-mcp.d.ts +0 -36
  308. package/dist/keyless-mcp.js +0 -127
  309. package/dist/text-urls.d.ts +0 -38
  310. package/dist/text-urls.js +0 -170
  311. package/dist/web-fetch-direct.d.ts +0 -119
  312. package/dist/web-fetch-direct.js +0 -190
@@ -1,4 +1,5 @@
1
1
  import { type HostedDial } from "@parcha/agentrun-computer";
2
+ import type { PairedRelay } from "../workspace/attached-computers.js";
2
3
  import { type Store } from "../store/index.js";
3
4
  import { type KeyEnv } from "../key-meta.js";
4
5
  import { type ComputerDeps, type ComputerDepsOptions } from "../workspace/computer-deps.js";
@@ -22,8 +23,9 @@ export interface RunnerProcessOptions {
22
23
  /** This runner's name in the runs it claims, its lines and its heartbeat. Default runner.ts runnerName(). */
23
24
  name?: string;
24
25
  /** Each claimed run's loop; default the runner's dispatch over the store (runnerLoop), with the computers it composed.
25
- * A factory of the store is given the runner's dial too, where it has a relay (dial-relay.ts). */
26
- createLoop?: LoopFactory | ((store: Store, sealKey: Buffer, dial?: HostedDial) => LoopFactory | RunnerParts);
26
+ * A factory of the store is given the runner's dial and its paired computers' relay too, where it has a relay
27
+ * (dial-relay.ts). */
28
+ createLoop?: LoopFactory | StoreFactory;
27
29
  /** Run the computer janitor (workspace/computer-janitor.ts) over the computers createLoop composed: at the start, then
28
30
  * on its interval. Only the runner subcommand asks for it; a test that does not ask runs none. */
29
31
  janitor?: boolean;
@@ -81,7 +83,7 @@ export declare function runEnv(env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
81
83
  * provider loader in place of the computer package's. Under --faux (the runs' environment names the faux model, as a
82
84
  * --faux server's and a `runner --faux` give it), --faux's computers are beside them, as the server's start check
83
85
  * reads them (server.ts computerReady): a run on the faux desktop is claimed, and its live view opened, the real way. */
84
- export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub" | "dial">) => {
86
+ export declare const runnerComputers: (store: Store, env: KeyEnv, sealKey: Buffer, own?: Pick<ComputerDepsOptions, "kinds" | "load" | "dockerPaths" | "hostAddresses" | "hostWhy" | "hub" | "dial" | "pairedRelay">) => {
85
87
  computerForClaim: typeof import("../workspace/computer-deps.js").claimComputer;
86
88
  computerDeps: ComputerDeps;
87
89
  factories: import("../computer-keys.js").ProviderFactories;
@@ -96,7 +98,7 @@ export declare function besideRunEnv(env: NodeJS.ProcessEnv, switches: NodeJS.Pr
96
98
  * its launch (harness-loops.ts resolveRunnerLoop), with the data directory, the run environment (runEnv), the store's
97
99
  * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
98
100
  * this process's, as it was handed or booted). Refused in words with no seal key. */
99
- export declare function runnerLoop(store: Store, dataDir: string, env?: NodeJS.ProcessEnv, booted?: Buffer, isolation?: RunIsolation, dial?: HostedDial): RunnerParts;
101
+ export declare function runnerLoop(store: Store, dataDir: string, env?: NodeJS.ProcessEnv, booted?: Buffer, isolation?: RunIsolation, dial?: HostedDial, paired?: PairedRelay): RunnerParts;
100
102
  /** What a runner in its own process may reach on loopback, from its own environment alone, as a server takes its opt-in
101
103
  * (cli.ts mcpLoopback): with AGENTRUN_MCP_ALLOW_LOOPBACK=1, an MCP server on this machine's loopback (the machine this
102
104
  * process runs on, its container's in a container), never at `own`: the port a server listens on unless --port says
@@ -129,8 +131,11 @@ export declare function checkRunner(options: {
129
131
  };
130
132
  /** Opens the store as a runner and starts claiming runs. */
131
133
  export declare function startRunnerProcess(options: RunnerProcessOptions): Promise<RunnerProcess>;
132
- /** Marks `make` as a function of the store (startRunnerProcess gives it the store it opens, and its relay's dial). */
133
- export declare function ofStore<Made extends LoopFactory | RunnerParts>(make: (store: Store, sealKey: Buffer, dial?: HostedDial) => Made): (store: Store, sealKey: Buffer, dial?: HostedDial) => Made;
134
+ /** A function of the store: startRunnerProcess gives it the store it opens, and its relay's dial and paired computers'
135
+ * relay where it has a relay. */
136
+ type StoreFactory = (store: Store, sealKey: Buffer, dial?: HostedDial, paired?: PairedRelay) => LoopFactory | RunnerParts;
137
+ /** Marks `make` as a function of the store (StoreFactory). */
138
+ export declare function ofStore<Made extends LoopFactory | RunnerParts>(make: (store: Store, sealKey: Buffer, dial?: HostedDial, paired?: PairedRelay) => Made): (store: Store, sealKey: Buffer, dial?: HostedDial, paired?: PairedRelay) => Made;
134
139
  /** How long a runner process lets each busy run finish its turn on SIGTERM, unless --drain-timeout or
135
140
  * AGENTRUN_DRAIN_TIMEOUT says: the image's server drain (its CMD's --drain-timeout 6s), so a runner beside a --no-runner
136
141
  * server drains as the server's own runner would.
@@ -50,12 +50,14 @@ import { computerDepsFrom } from "../workspace/computer-deps.js";
50
50
  import { startJanitor } from "../workspace/computer-janitor.js";
51
51
  import { projectRunEnded } from "../source-sync/checkpoints.js";
52
52
  import { runEndComputers } from "../workspace/run-end-computers.js";
53
+ import { sayLoginRunner } from "../claude-login-token.js";
53
54
  import { createDispatchLoop } from "./dispatch.js";
54
55
  import { resolveRunnerLoop } from "./harness-loops.js";
55
56
  import { routeOf } from "./model-route.js";
56
57
  import { RUN_PROCESS_MIB, runnerMemory } from "./memory-claim.js";
57
58
  import { childLoops, isolationLoops, RunIsolationRefused, runIsolationOf } from "./run-child-host.js";
58
59
  import { sweepEndedScratch } from "./scratch-sweep.js";
60
+ import { runCensus } from "../run-census.js";
59
61
  import { RUNNER_LOOPS, RUNNER_RENEW_EVERY_MS, runnerName, startRunner } from "./runner.js";
60
62
  import { keepPresence } from "./presence.js";
61
63
  import { diskFreeGate } from "./disk-free.js";
@@ -96,8 +98,10 @@ export async function openRunnerStore(dataDir, env, warn, url) {
96
98
  /** The runner's own secrets, which a run never gets, not even in the runner's in-process environment: the server's
97
99
  * 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
98
100
  * 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_");
101
+ * runner's claim alone reads (composio-made.ts composioEnvKey) and sends only as a granted Composio server's MCP header.
102
+ * And every OpenTelemetry setting (OTEL_*: OTEL_EXPORTER_OTLP_HEADERS holds a backend's key): a run's process is handed
103
+ * them on its pipe (secrets.ts OTEL_PAIR), never in an environment, so no harness, tool or computer of a run has them. */
104
+ 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_") || name.startsWith("OTEL_");
101
105
  /** A run's environment as the runner hands its loops (AdapterSpecDeps.env): this process's, less the runner's own
102
106
  * secrets, with every other secret the launcher's pipe handed it (a model key, a tool key, a box key) readable by name
103
107
  * but not enumerable, as secrets.ts withSecrets makes them: code that reads one by name (the model route) finds it, and
@@ -141,7 +145,7 @@ export function besideRunEnv(env, switches) {
141
145
  * its launch (harness-loops.ts resolveRunnerLoop), with the data directory, the run environment (runEnv), the store's
142
146
  * journal, the seal key and the model route. `booted`: the seal key startRunnerProcess booted against the store (else
143
147
  * this process's, as it was handed or booted). Refused in words with no seal key. */
144
- export function runnerLoop(store, dataDir, env = process.env, booted, isolation, dial) {
148
+ export function runnerLoop(store, dataDir, env = process.env, booted, isolation, dial, paired) {
145
149
  const sealKey = booted ?? sealKeyOf(secret(SEAL_KEY_ENV) ?? env[SEAL_KEY_ENV]);
146
150
  if (!sealKey)
147
151
  throw new RunnerRefused(`A runner needs the server's seal key (${SEAL_KEY_ENV}): start it through the server's launcher, which hands it over.`);
@@ -150,8 +154,9 @@ export function runnerLoop(store, dataDir, env = process.env, booted, isolation,
150
154
  // agent's setting, its keys read from the run environment first, then the store's sealed rows; a Docker computer's
151
155
  // mounts by where this process's Docker has the data directory (box-paths.ts), read once; a desktop's or a phone's live
152
156
  // view opened with it. A machine that dials goes to this runner's own hub, through the server's relay (`dial`, its
153
- // relay's: dial-relay.ts); with none, its provider refuses.
154
- const computers = runnerComputers(store, runs, sealKey, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(dial ? { dial } : {}) });
157
+ // relay's: dial-relay.ts); with none, its provider refuses. A paired computer is brought onto that same hub for the run
158
+ // (`paired`, the relay's); with none, it is refused in words.
159
+ const computers = runnerComputers(store, runs, sealKey, { dockerPaths: () => dockerPathsForRuns(runs, dataDir), hostAddresses: () => hostAddressesOnce(runs), hostWhy: hostCommandRefusals(PROVIDERS, process.env.PATH), ...(dial ? { dial } : {}), ...(paired ? { pairedRelay: paired } : {}) });
155
160
  const loopback = runnerLoopback(env);
156
161
  // The operator's bound on owner-allowed private hosts (mcp-private-hosts.ts), read by every dial this runner and its
157
162
  // runs' processes make (they inherit it, runEnv): said at the start when it narrows the owner's list.
@@ -262,9 +267,9 @@ export async function startRunnerProcess(options) {
262
267
  // Its relay (dial-relay.ts), where its environment names the server's public address: a machine that dials the
263
268
  // server lands in this runner's hub, through the server. Its log lines are the runner's warnings.
264
269
  relay = await startRunnerRelay({ store, sealKey: seal.key, runner: name, presence, env, log: warn });
265
- const made = options.createLoop ?? ofStore((opened, sealKey, dial) => runnerLoop(opened, options.dataDir, undefined, sealKey, undefined, dial));
270
+ const made = options.createLoop ?? ofStore((opened, sealKey, dial, paired) => runnerLoop(opened, options.dataDir, undefined, sealKey, undefined, dial, paired));
266
271
  // A factory of the store (marked by ofStore) is given the store; a loop factory is used as is.
267
- const parts = isStoreFactory(made) ? made(store, seal.key, relay?.dial) : made;
272
+ const parts = isStoreFactory(made) ? made(store, seal.key, relay?.dial, relay?.paired) : made;
268
273
  const createLoop = typeof parts === "function" ? parts : parts.createLoop;
269
274
  // The janitor sweeps with the computers the loop composed, never a second composition. Its lines are the runner's
270
275
  // warnings, said where the runner says its others (warn: stderr unless a test gives its own).
@@ -282,6 +287,8 @@ export async function startRunnerProcess(options) {
282
287
  createLoop,
283
288
  name,
284
289
  presence,
290
+ // Each end counts where in the run's files what its caller handed it sits, as the server reads them.
291
+ census: runCensus(store, { data: options.dataDir, sealKey: seal.key, env }),
285
292
  ...(options.loops ? { loops: options.loops } : {}),
286
293
  ...(options.drainMs ? { drainMs: options.drainMs } : {}),
287
294
  memory,
@@ -371,7 +378,7 @@ function watchFloor(store, known, everyMs) {
371
378
  };
372
379
  }
373
380
  const storeFactories = new WeakSet();
374
- /** Marks `make` as a function of the store (startRunnerProcess gives it the store it opens, and its relay's dial). */
381
+ /** Marks `make` as a function of the store (StoreFactory). */
375
382
  export function ofStore(make) {
376
383
  storeFactories.add(make);
377
384
  return make;
@@ -630,6 +637,9 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
630
637
  holds = { ...holds, loops: isolationLoops(isolation, holds.loops) };
631
638
  let started;
632
639
  const runnerOf = name ?? runnerName();
640
+ // Said on the data folder before it claims: whether its runs on Claude Code's login stay in this process, its CLI on
641
+ // the login's folder (claude-login-token.ts sayLoginRunner), for a runner whose runs are users of their own to read.
642
+ sayLoginRunner(args.dataDir, runnerOf, isolation.kind === "uid" ? "uid" : "process");
633
643
  // The last resort, in this process only (never the library, the server's CLI or the runner beside a server): an error
634
644
  // nothing handled is said with its stack, and the process exits 1 at once (lastResort: crashing is the safe failure).
635
645
  const fatal = lastResort(runnerOf);
@@ -656,7 +666,7 @@ export async function runnerMain(argv, given = process.env, hooks = {}) {
656
666
  drainMs: holds.drainMs,
657
667
  // Each run a process of its own (`isolation`); its computer, with this runner's relay's dial, held here in the
658
668
  // runner, which the run's process asks for it over its channel (run-child-host.ts, held.ts computer).
659
- createLoop: ofStore((store, sealKey, dial) => runnerLoop(store, args.dataDir, env, sealKey, isolation, dial)),
669
+ createLoop: ofStore((store, sealKey, dial, paired) => runnerLoop(store, args.dataDir, env, sealKey, isolation, dial, paired)),
660
670
  // Each run's own process weighed beside its harness's run (memory-claim.ts RUN_PROCESS_MIB).
661
671
  processMib: RUN_PROCESS_MIB,
662
672
  // The runner subcommand ends what a crashed runner of this server left (never under --faux).
@@ -31,6 +31,8 @@
31
31
  // as the runner was handed it at its start (secrets.ts secret, never its environment), for an address on Composio's origin
32
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
33
  // another address, the claim is refused before the loop starts (pinOf), in words naming it, and nothing is sent.
34
+ // A per_run server the API token saved at an origin off the API-only list (mcp-api-only-origins.ts) is refused at the
35
+ // claim (pinOf) and at each call after it (check): its entry holds only those words, so nothing goes to that origin.
34
36
  //
35
37
  // fresh(). After the pin check and before the loop, and again on a command-row resume: an OAuth access token past its
36
38
  // expiry is refreshed, bounded (the call within MCP_REFRESH_CALL_MS; a request not yet dialled within 4 s, and tried again
@@ -53,6 +55,7 @@
53
55
  // the next call sends the new one (or is refused for the move); and an OAuth access token within REFRESH_MARGIN_MS of its
54
56
  // end is refreshed through open's lease path: behind the call while the token is still valid (the call goes at once on
55
57
  // it), waited on only when it has run out. Concurrent calls to one server share one such open.
58
+ import { heldApiOnlyMcpOrigins, offApiOnlyMcpOrigins } from "../mcp-api-only-origins.js";
56
59
  import { randomUUID } from "node:crypto";
57
60
  import { EndpointRefused, REFRESH_REQUEST_MS, refreshed, refused, RequestUnsent, systemNetwork } from "../mcp-oauth.js";
58
61
  import { pinFirst } from "../mcp-pin-first.js";
@@ -103,6 +106,9 @@ export async function mcpClaim(options) {
103
106
  const stamps = new Map();
104
107
  /** The servers check() found removed: nothing (a github_app token's refresh among it) puts their entry back. */
105
108
  const gone = new Set();
109
+ /** The per_run servers the API-only origin list refused when last opened (offApiOnlyMcpOrigins): check() opens one
110
+ * again when the list says otherwise now. */
111
+ const offList = new Set();
106
112
  /** The opens check() started, by server: concurrent calls share one. */
107
113
  const reopening = new Map();
108
114
  // Servers whose refresh behind a still-valid token is going: one at a time per server from this claim.
@@ -218,8 +224,15 @@ export async function mcpClaim(options) {
218
224
  return await github.open(name, entry), { awaited: true };
219
225
  // A per_run server keeps none either: its credential is the one the run's caller handed it (mcp_auth), sealed in the
220
226
  // run's launch, read again at every fresh() so a message's new one reaches the run's next request.
221
- if (row.auth === "per_run")
222
- return entry(await perRun(name, row.url)), { awaited: false };
227
+ // One the API token saved at an origin no longer on the API-only list gets no entry but those words.
228
+ if (row.auth === "per_run") {
229
+ const off = await offApiOnlyMcpOrigins(store, name, row);
230
+ if (off)
231
+ offList.add(name);
232
+ else
233
+ offList.delete(name);
234
+ return entry(off ? { unopened: off } : await perRun(name, row.url)), { awaited: false };
235
+ }
223
236
  // A per-run Composio server: the run's account, or its calls refused unsent; its key is opened below as any server's.
224
237
  const account = row.auth === "headers" ? await composioAccount(name, row) : undefined;
225
238
  if (account && "unopened" in account)
@@ -425,8 +438,19 @@ export async function mcpClaim(options) {
425
438
  delete credentials[name];
426
439
  return;
427
440
  }
441
+ // A per_run server: the API-only origin list read at every call, not only at the claim, since a runner of its own
442
+ // holds its runs past a server's restart with the list changed. Refused or let in since its last open: opened again.
443
+ // The list is read first: with none held (a full server's store) the row is not read, and nothing is refused.
444
+ let listMoved = false;
445
+ if (stamp.auth === "per_run") {
446
+ const held = await heldApiOnlyMcpOrigins(store);
447
+ const row = held ? await getMcpServer(store, name) : undefined;
448
+ listMoved = (row !== undefined && (await offApiOnlyMcpOrigins(store, name, row, held)) !== undefined) !== offList.has(name);
449
+ if (released)
450
+ return;
451
+ }
428
452
  const was = stamps.get(name);
429
- const changed = !was || gone.has(name) || was.url !== stamp.url || was.auth !== stamp.auth || was.changedAt !== stamp.credentialChangedAt;
453
+ const changed = !was || gone.has(name) || listMoved || was.url !== stamp.url || was.auth !== stamp.auth || was.changedAt !== stamp.credentialChangedAt;
430
454
  // The token's end by the store's clock (tokenLeftMs), else as this claim opened it.
431
455
  const left = stamp.tokenLeftMs ?? (was?.end !== undefined ? was.end - now() : null);
432
456
  // And whether the row still holds the token this claim opened: another claim's refresh moves the row's token end (not
@@ -526,6 +550,10 @@ async function pinOf({ store, claim, grants, githubMcpOrigin = GITHUB_MCP_ORIGIN
526
550
  const got = row && keyEnv ? composioEnvKey(server, row.url, keyEnv, composioMcpOrigin) : undefined;
527
551
  if (got && "refused" in got)
528
552
  throw new McpClaimRefused(`${got.refused} Nothing was sent.`);
553
+ // A per_run server the API token saved at an origin no longer on the API-only list: the run never starts, nothing sent.
554
+ const off = row ? await offApiOnlyMcpOrigins(store, server, row) : undefined;
555
+ if (off)
556
+ throw new McpClaimRefused(off);
529
557
  }
530
558
  // As plain JSON, as the stored pin reads (the harnesses and the run's directory take it as such).
531
559
  return JSON.parse(JSON.stringify(pinned));
@@ -74,6 +74,15 @@ export interface McpForClaimOptions {
74
74
  /** Each credential value the claim opens, refreshes or mints, for the run's redactors (mcp-claim.ts `hold`). */
75
75
  readonly hold?: (values: string[]) => void;
76
76
  }
77
+ /** What a spec builder gives a claim's MCP for its metered jobs (`capped` and `media`), the same for every builder:
78
+ * whether its launch has a cap, and where a job's input media are read from: the run's eval web fake (`web`, as its
79
+ * builder read the run's fakes, once), else the builder's `env`, in web_save's slots. */
80
+ export declare function claimMetering(deps: {
81
+ readonly env: NodeJS.ProcessEnv;
82
+ readonly saveSlots?: SaveSlots;
83
+ }, web: WebFake | undefined, launch: {
84
+ readonly maxCostUsd?: number | undefined;
85
+ }): Pick<McpForClaimOptions, "capped" | "media">;
77
86
  /** A claim's MCP (AdapterRunSpec.mcp): what the loop reaches the gateway by, and the claim step's own hooks. */
78
87
  export interface ClaimMcp {
79
88
  /** One host tool per pinned tool, under its wire name, on every harness. Each reaches the gateway only as the loop
@@ -1,9 +1,9 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { wireName } from "../catalog.js";
3
3
  import { mcpGateway } from "../mcp-gateway.js";
4
- import { meterFor, publicMedia } from "../fal-price.js";
4
+ import { falBills, meterNamed, publicMedia } from "../fal-price.js";
5
5
  import { FAUX_ENV } from "../model.js";
6
- import { fetchOptions } from "../web-fetch-direct.js";
6
+ import { fetchOptions } from "../web-run.js";
7
7
  import { fakeSaveOptions } from "../web-fake.js";
8
8
  import { dialAt, mcpServerAt, systemNetwork } from "../mcp-oauth.js";
9
9
  import { privateOAuthHosts } from "../mcp-private-hosts.js";
@@ -13,6 +13,12 @@ import { mcpClaim } from "./mcp-claim.js";
13
13
  import { registryListing } from "../mcp-pin-first.js";
14
14
  import { heldOrThrow } from "./held.js";
15
15
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
16
+ /** What a spec builder gives a claim's MCP for its metered jobs (`capped` and `media`), the same for every builder:
17
+ * whether its launch has a cap, and where a job's input media are read from: the run's eval web fake (`web`, as its
18
+ * builder read the run's fakes, once), else the builder's `env`, in web_save's slots. */
19
+ export function claimMetering(deps, web, launch) {
20
+ return { capped: launch.maxCostUsd !== undefined, media: { env: deps.env, ...(web ? { web } : {}), ...(deps.saveSlots ? { slots: deps.saveSlots } : {}) } };
21
+ }
16
22
  /** The wire names a subagent's `grant` gives of the run's MCP and monid tools, by the gate's keys; else the grant's own. */
17
23
  export function catalogSessionNames(catalog, grant) {
18
24
  const given = (catalog?.tools ?? []).flatMap((tool) => (permissionKeys(catalog.catalogOf(tool.name) ?? "").includes(grant) ? [tool.name] : []));
@@ -80,7 +86,7 @@ export async function mcpForClaim(options) {
80
86
  commit: () => (change) => options.harness.commit(change, BACKGROUND_CONTEXT),
81
87
  ...(options.fetch ? { fetch: options.fetch } : {}),
82
88
  ...(options.callBounds ? { bounds: options.callBounds } : {}),
83
- capped: () => options.capped !== false,
89
+ capped: options.capped !== false,
84
90
  ...(media ? { media: publicMedia(async () => (media.web ? fakeSaveOptions(media.web) : fetchOptions(media.env, FAUX_ENV)), media.slots) } : {}),
85
91
  });
86
92
  const catalog = new Map();
@@ -118,8 +124,8 @@ export async function mcpForClaim(options) {
118
124
  return undefined;
119
125
  if (pinned.prices && Object.hasOwn(pinned.prices, parsed.tool))
120
126
  return pinned.prices[parsed.tool];
121
- // A metered server's job is priced from its input, when the call runs: no price to show before it.
122
- return meterFor(pinned)?.bills(parsed.tool) ? undefined : "not metered";
127
+ // fal's job is priced from its input when the call runs, after the person's allow.
128
+ return meterNamed(pinned.url, pinned.meter) && falBills(parsed.tool) ? "priced by usage" : "not metered";
123
129
  },
124
130
  effectOf: (name) => pinnedEffect(pin, name),
125
131
  fresh: () => step.fresh(),
@@ -66,6 +66,11 @@ export interface ModelRoute {
66
66
  readonly price?: (model: string, usage: RouteUsage) => number | null;
67
67
  /** The upstream fetch: the route's own, for a model that does not speak Messages. Absent: the network. */
68
68
  readonly fetch?: typeof fetch;
69
+ /** Where the route's own translation (`fetch`) sends the model's requests: the origin pi-ai's catalog entry gives it
70
+ * (OpenRouter's, Particle's, this machine's Ollama). A run's GenAI trace names its host, never `provider.origin`
71
+ * (ROUTE_ORIGIN, a name no request leaves for). Absent on a route with no translation, and under the faux model,
72
+ * whose requests go nowhere. */
73
+ readonly upstreamOrigin?: string;
69
74
  /** The catalog's cost of the model, tiers included: what the cap prices a request at before it leaves. */
70
75
  readonly cost?: RouteCost;
71
76
  /** True when serve has no price for the model (runModels' `unpriced`): `cost` is then a placeholder of zeros, which the
@@ -140,6 +145,18 @@ export declare function routeOf(model: string | PinnedModel | undefined, env?: N
140
145
  * sends to OpenRouter carries AgentRun's app attribution unless `env` turns it off (kernel openrouter-attribution.ts),
141
146
  * as one the model proxy sends there does; a request to any other provider carries none. */
142
147
  export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch, env?: NodeJS.ProcessEnv): typeof fetch;
148
+ /** `route` (a translated route's fetch, which streams every answer, as pi-ai asks) for any Messages client on the wire it
149
+ * translates onto, which asks two things pi-ai never does. Its token count (POST /v1/messages/count_tokens, free, asked
150
+ * beside its turns) is answered here and never run on the model, which has no count of its own: the body's bytes over
151
+ * four (COUNT_BYTES_PER_TOKEN), a bound for its context, not a price. A request with no `stream: true` (a side request)
152
+ * gets its answer whole, one JSON message as Messages writes it, joined from the stream (wholeOf). A tool_choice that
153
+ * forces a call is refused with a 400 before the model is asked (forcedChoice). */
154
+ export declare function forMessagesClients(route: typeof fetch): typeof fetch;
155
+ /** The route's translation onto each wire it translates a model onto (wires.ts TRANSLATED), by wire: what a harness's
156
+ * proxy on that wire forwards with for `model` (`provider/model-id`), made on `env`. Anthropic's Messages: the route's
157
+ * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). provider.ts routedProvider reads
158
+ * it; a wire with no entry has no translation, whatever TRANSLATED says. */
159
+ export declare const TRANSLATORS: Readonly<Partial<Record<Wire, (model: string, env: NodeJS.ProcessEnv) => Promise<typeof fetch>>>>;
143
160
  /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
144
161
  * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
145
162
  * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
@@ -16,7 +16,7 @@
16
16
  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
- import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
19
+ import { chooseModel, FAUX_PROVIDER, MODEL_PROVIDER, runModels } from "../model.js";
20
20
  import { OLLAMA_PROVIDER } from "../ollama-provider.js";
21
21
  import { gatewayHeadersAt, providerFor } from "../provider.js";
22
22
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
@@ -85,7 +85,9 @@ export async function routeOf(model, env = process.env, tier = "default", wires
85
85
  // before Ollama would cut the prompt.
86
86
  const local = target.provider === OLLAMA_PROVIDER;
87
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) };
88
+ // Where pi-ai sends the translated requests (its model's baseUrl), for the run's trace: none under the faux model.
89
+ const upstreamOrigin = target.provider !== FAUX_PROVIDER && target.baseUrl ? { upstreamOrigin: target.baseUrl } : {};
90
+ return { ...route, ...(like ? { like } : {}), ...(local ? { local: true } : {}), ...upstreamOrigin, provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream, env) };
89
91
  }
90
92
  /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
91
93
  const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
@@ -393,6 +395,122 @@ export function messagesFetch(models, target, redact = keepText, upstream, env =
393
395
  return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } });
394
396
  });
395
397
  }
398
+ /** The bytes of a request a token count answers per token (forMessagesClients' count_tokens). */
399
+ const COUNT_BYTES_PER_TOKEN = 4;
400
+ /** Whether a request asks Messages' token count (its path's last segment, any query after it). */
401
+ const countsTokens = (url) => /\/count_tokens(?:\?|$)/.test(String(url));
402
+ /** Why a Messages `tool_choice` that forces a call is refused (its 400's words), else undefined: the model behind the
403
+ * route (Ollama's chat) takes no tool choice, so a call forced by "any" or by a tool's name cannot be kept. "auto",
404
+ * "none" and none at all are taken; any other type is refused too. */
405
+ function forcedChoice(choice) {
406
+ if (choice === undefined || choice === null)
407
+ return undefined;
408
+ const plain = typeof choice === "object" && !Array.isArray(choice) ? choice : undefined;
409
+ const type = plain ? plain.type : choice;
410
+ if (type === "auto" || type === "none")
411
+ return undefined;
412
+ const unkept = 'is not taken on this model\'s route: the model here cannot be made to call a tool, so send "auto"';
413
+ if (type === "any")
414
+ return `tool_choice "any" ${unkept}`;
415
+ if (type === "tool")
416
+ return `tool_choice naming the tool ${String(plain?.name ?? "(none)")} ${unkept}`;
417
+ return `tool_choice ${JSON.stringify(type ?? "(no type)")} is not taken on this model's route: "auto" and "none" only`;
418
+ }
419
+ /** `route` (a translated route's fetch, which streams every answer, as pi-ai asks) for any Messages client on the wire it
420
+ * translates onto, which asks two things pi-ai never does. Its token count (POST /v1/messages/count_tokens, free, asked
421
+ * beside its turns) is answered here and never run on the model, which has no count of its own: the body's bytes over
422
+ * four (COUNT_BYTES_PER_TOKEN), a bound for its context, not a price. A request with no `stream: true` (a side request)
423
+ * gets its answer whole, one JSON message as Messages writes it, joined from the stream (wholeOf). A tool_choice that
424
+ * forces a call is refused with a 400 before the model is asked (forcedChoice). */
425
+ export function forMessagesClients(route) {
426
+ return (async (url, init = {}) => {
427
+ const body = String(init.body ?? "");
428
+ if (countsTokens(url))
429
+ return Response.json({ input_tokens: Math.ceil(new TextEncoder().encode(body).length / COUNT_BYTES_PER_TOKEN) });
430
+ const read = (() => {
431
+ try {
432
+ return JSON.parse(body || "{}");
433
+ }
434
+ catch {
435
+ return undefined;
436
+ }
437
+ })();
438
+ const refused = forcedChoice(read?.tool_choice);
439
+ if (refused)
440
+ return messagesError(refused, 400, "invalid_request_error");
441
+ const streamed = read === undefined || read.stream === true;
442
+ const answer = await route(url, init);
443
+ return streamed || answer.status !== 200 ? answer : wholeOf(await answer.text());
444
+ });
445
+ }
446
+ /** The route's translation onto each wire it translates a model onto (wires.ts TRANSLATED), by wire: what a harness's
447
+ * proxy on that wire forwards with for `model` (`provider/model-id`), made on `env`. Anthropic's Messages: the route's
448
+ * own Messages fetch (messagesFetch), as a Messages client asks it (forMessagesClients). provider.ts routedProvider reads
449
+ * it; a wire with no entry has no translation, whatever TRANSLATED says. */
450
+ export const TRANSLATORS = Object.freeze({
451
+ "anthropic-messages": async (model, env) => forMessagesClients((await routeOf(model, env)).fetch),
452
+ });
453
+ /** One Messages answer whole, from the events of its stream (`sse`): the message_start's message, each block joined from
454
+ * its deltas (a tool call's input parsed from its pieces), the last message_delta's stop and usage over the start's. An
455
+ * error event answers as Messages writes an error, at 500, with its words; so does a stream a part of which is not JSON. */
456
+ function wholeOf(sse) {
457
+ try {
458
+ return wholeRead(sse);
459
+ }
460
+ catch {
461
+ // A part that does not read (a data line not JSON, a tool call's input cut short) is said as an error event is.
462
+ return messagesError("The model's answer could not be read whole: a part of it is not JSON.");
463
+ }
464
+ }
465
+ /** A Messages error answer: `words` its message, 500 api_error unless said otherwise. */
466
+ const messagesError = (words, status = 500, type = "api_error") => Response.json({ type: "error", error: { type, message: words } }, { status });
467
+ /** wholeOf's reading, which throws on a part that is not JSON. */
468
+ function wholeRead(sse) {
469
+ let message = {};
470
+ const blocks = [];
471
+ const pieces = new Map();
472
+ for (const frame of sse.split(/\n\n/)) {
473
+ const lines = frame.split("\n");
474
+ const kind = lines.find((line) => line.startsWith("event: "))?.slice("event: ".length);
475
+ const data = lines.filter((line) => line.startsWith("data: ")).map((line) => line.slice("data: ".length)).join("\n");
476
+ if (!kind || !data)
477
+ continue;
478
+ if (kind === "error") {
479
+ let words = data;
480
+ try {
481
+ const said = JSON.parse(data);
482
+ words = String(said.error?.message ?? said.message ?? data);
483
+ }
484
+ catch {
485
+ // Its words alone (sendWords), not JSON.
486
+ }
487
+ return messagesError(words);
488
+ }
489
+ const event = JSON.parse(data);
490
+ const at = event.index ?? -1;
491
+ if (kind === "message_start")
492
+ message = { ...event.message };
493
+ else if (kind === "content_block_start" && event.content_block)
494
+ blocks[at] = { ...event.content_block };
495
+ else if (kind === "content_block_delta" && blocks[at] && event.delta) {
496
+ const { type, text, thinking, signature, partial_json: piece } = event.delta;
497
+ if (type === "text_delta")
498
+ blocks[at].text = (blocks[at].text ?? "") + (text ?? "");
499
+ else if (type === "thinking_delta")
500
+ blocks[at].thinking = (blocks[at].thinking ?? "") + (thinking ?? "");
501
+ else if (type === "signature_delta")
502
+ blocks[at].signature = signature ?? "";
503
+ else if (type === "input_json_delta")
504
+ pieces.set(at, (pieces.get(at) ?? "") + (piece ?? ""));
505
+ }
506
+ else if (kind === "message_delta")
507
+ message = { ...message, ...(event.delta ?? {}), usage: { ...(message.usage ?? {}), ...(event.usage ?? {}) } };
508
+ }
509
+ for (const [at, piece] of pieces)
510
+ if (blocks[at] && piece)
511
+ blocks[at].input = JSON.parse(piece);
512
+ return Response.json({ ...message, content: blocks.filter(Boolean) });
513
+ }
396
514
  /** pi-ai's stop reason as Messages says it. */
397
515
  const stopReasonOf = (reason) => (reason === "toolUse" ? "tool_use" : reason === "length" ? "max_tokens" : "end_turn");
398
516
  /** pi-ai's thinking levels past off, each asked by its own name. */
@@ -1,9 +1,19 @@
1
- import { type Runners } from "../store/store.js";
1
+ import { type RunnerRow, type Runners } from "../store/store.js";
2
2
  /** How often a runner says again that it is there. */
3
3
  export declare const PRESENCE_RENEW_MS = 10000;
4
4
  /** How old a runner's word can be and still count: three renewals missed. The store's (RUNNER_STALE_MS), which its claim
5
5
  * rule reads for a kept computer's pin. */
6
6
  export declare const PRESENCE_STALE_MS = 30000;
7
+ /** A runner's row that says where its relay answers. */
8
+ export type RelayRow = RunnerRow & {
9
+ readonly host: string;
10
+ readonly port: number;
11
+ };
12
+ /** The runners whose relay takes dials now: their rows seen within PRESENCE_STALE_MS on the store's clock (Runners.live,
13
+ * the database's on Postgres), never one process's, that say where their relay answers. The server relays a dial only
14
+ * to one of these (computer-attach.ts), says a dial provider is served while one answers at a host it dials (server.ts
15
+ * relayed), and a paired computer's route to a runner not among them is stale (workspace/paired-route.ts). */
16
+ export declare function liveRelays(runners: Pick<Runners, "live">): Promise<RelayRow[]>;
7
17
  /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
8
18
  * capacity read (GET /v2/capacity). */
9
19
  export declare const RUNNER_VERSION: string;
@@ -18,6 +18,13 @@ export const PRESENCE_RENEW_MS = 10_000;
18
18
  /** How old a runner's word can be and still count: three renewals missed. The store's (RUNNER_STALE_MS), which its claim
19
19
  * rule reads for a kept computer's pin. */
20
20
  export const PRESENCE_STALE_MS = RUNNER_STALE_MS;
21
+ /** The runners whose relay takes dials now: their rows seen within PRESENCE_STALE_MS on the store's clock (Runners.live,
22
+ * the database's on Postgres), never one process's, that say where their relay answers. The server relays a dial only
23
+ * to one of these (computer-attach.ts), says a dial provider is served while one answers at a host it dials (server.ts
24
+ * relayed), and a paired computer's route to a runner not among them is stale (workspace/paired-route.ts). */
25
+ export async function liveRelays(runners) {
26
+ return (await runners.live(PRESENCE_STALE_MS)).filter((row) => row.host !== null && row.port !== null);
27
+ }
21
28
  /** This build's version (the serve package's), which every runner says on its row (runners.version) for the server's
22
29
  * capacity read (GET /v2/capacity). */
23
30
  export const RUNNER_VERSION = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
@@ -47,7 +47,7 @@ export function createReflectHook(deps) {
47
47
  // What the step's model turns cost: the run's spend once it closed less the job's, unknown when either is. Kept with
48
48
  // every end once a compile turn was asked; 0 for an end that asked none. The step's only model turn is its compile
49
49
  // turn, so this is the compile's spend: it joins the revision it drafts, or the bill's unattributed when it kept no
50
- // draft (store-reads/learning.ts compilesOf, learning-cost.ts amortize), never the run's own.
50
+ // draft (learn/ledger.ts record and summarize), never the run's own.
51
51
  let asked = begun;
52
52
  const spent = async () => {
53
53
  if (!asked)
@@ -1,4 +1,5 @@
1
1
  import type { Duplex } from "node:stream";
2
+ import { type HeldRedact, type Redact } from "./redact.js";
2
3
  import type { Workspace } from "../workspace/workspace.js";
3
4
  import { type AdapterSpecDeps } from "./adapter-run-spec.js";
4
5
  import type { Held } from "./held.js";
@@ -120,12 +121,15 @@ interface ClaimReads {
120
121
  /** The runner's presence incarnation (LoopDeps.incarnation): with the claim's runner, who keeps a computer a park pins. */
121
122
  readonly incarnation?: string;
122
123
  }
124
+ /** The runner's redactor as the host side of a run's process holds it (LoopDeps.redact): its cut, and the carry of a
125
+ * value into what it cuts from the run's journal, which a token the runner hands the run needs (claudeLogin). */
126
+ export type RunnerCut = Redact & Partial<Pick<HeldRedact, "carry">>;
123
127
  /** Held (held.ts) for one claim, on the runner: each answer the claim's own, read with the runner's seal key from the
124
128
  * runner's own reads of the claim; every argument from the run's process is checked or ignored. `bigs`: the run's pieced
125
129
  * writes (big-writes.ts), let go at the claim's release and, by the caller, when the run's channel ends. */
126
130
  export declare function heldFor(deps: AdapterSpecDeps & {
127
131
  readonly sealKey: Buffer;
128
- }, reads: ClaimReads, cut: (text: string) => string, log: (line: string) => void, bigs?: RunBigWrites): {
132
+ }, reads: ClaimReads, cut: RunnerCut, log: (line: string) => void, bigs?: RunBigWrites): {
129
133
  held: Held;
130
134
  inputs(): Promise<void>;
131
135
  release(): Promise<void>;
@@ -158,23 +162,33 @@ export declare const childArgv: () => string[];
158
162
  * A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
159
163
  * connectors, whose rows are the server's. */
160
164
  export declare const runsInRunner: (harness: string, launch: Pick<RunLaunch, "sdk" | "native" | "cli_learning">) => boolean;
161
- /** The words a run on Claude Code's login on this machine is refused in where each run is a user of its own. */
162
- export declare const LOGIN_NEEDS_SERVER_USER = "A run on Claude Code's login on this machine needs runs under the server's own user, and this runner runs each run as a user of its own: set AGENTRUN_RUN_USER=same, or give the run a model_key.";
165
+ /** The words a run on this machine's own Claude Code login (the `machine` place: claude-login.ts machineFolder, ~/.claude
166
+ * or the server's CLAUDE_CONFIG_DIR) is refused in where each run is a user of its own: only AgentRun's own login folder
167
+ * is handed to such a run, as its access token. */
168
+ export declare const LOGIN_MACHINE_NEEDS_SERVER_USER = "A run on this machine's own Claude Code login (~/.claude, or the CLAUDE_CONFIG_DIR AgentRun was started with) needs runs under the server's own user, and this runner runs each run as a user of its own: switch to AgentRun's own login folder under Settings \u2192 Model keys, set AGENTRUN_RUN_USER=same, or give the run a model_key.";
169
+ /** The words a run on the login is refused in where each run is a user of its own while runner `other`, on the same data
170
+ * folder, runs its runs on the login in its own process, whose CLI renews the login in that folder itself. */
171
+ export declare const loginRunnerInProcessWords: (other: string) => string;
163
172
  /** The words a run on a harness recipe is refused in where each run is a user of its own (harness-table.ts recipeHarness). */
164
173
  export declare const RECIPE_NEEDS_SERVER_USER = "A run on a harness recipe needs runs under the server's own user, since its install, its check and its owner's sign-in are that user's alone, and this runner runs each run as a user of its own: set AGENTRUN_RUN_USER=same on this runner.";
165
174
  export { RECIPE_SIGN_IN_PERSON_ONLY } from "./harness-loops.js";
166
175
  /** Whether run `runId` stays in its runner's process: runsInRunner's, and a workflow run on a server with a documents
167
176
  * directory (launch.documents), whose reads and writes (a pdf_pages call's pages) are rooted in a folder the server's
168
177
  * user holds and no slot's user is given; its nodes run the server's own tools alone, no agent's code. A run on Claude
169
- * Code's login on this machine (claude-login.ts loginForRun) needs the login in the server's own folder, which its CLI
170
- * reads and refreshes: where runs are the runner's own user (`process`) it stays in the runner; where each run is a user
171
- * of its own (`uid`) it is refused at its claim (ClaimRefused, the run failed in words naming the setting), never run as
172
- * the server's user. A run its caller handed a model key (model_key) runs on that key and never on the login
173
- * (cli-run-spec.ts), so it is a process of its own like any other. */
178
+ * Code's login on this machine (claude-login.ts loginForRun), where runs are the runner's own user (`process`), stays in
179
+ * the runner, its CLI on the login's folder. Where each run is a user of its own (`uid`), a run on AgentRun's own login
180
+ * folder is a process of its own handed the login's access token alone (held.ts claudeLogin, claude-login-token.ts),
181
+ * never the folder; it is refused at its claim (ClaimRefused, in words) on this machine's own login (machineFolder), and
182
+ * while a `process` runner on the same data folder is live (its CLI renews the folder's login itself). A run its caller
183
+ * handed a model key (model_key) runs on that key and never on the login (cli-run-spec.ts), so it is a process of its
184
+ * own like any other. */
174
185
  export declare function staysInRunner(deps: Pick<AdapterSpecDeps, "store" | "data" | "env" | "sealKey">, harness: string, launch: RunLaunch, runId: string, isolation: RunIsolation): Promise<boolean>;
175
186
  /** The runner's loop factory where each run is a process of its own: a ChildLoop per claim, but for a run that stays in
176
187
  * the runner (staysInRunner). */
177
188
  export declare function childLoops(options: ChildLoopsOptions): LoopFactory;
189
+ /** The pair a run's process is handed this runner's OpenTelemetry settings in (secrets.ts OTEL_PAIR): none when it has
190
+ * none. */
191
+ export declare const otelPair: (env?: NodeJS.ProcessEnv) => (readonly [string, string])[];
178
192
  /** The runner's side of a run's channel over `socket`. Each call of the run's process runs inside the ledger of the tool
179
193
  * call it was made in (paid-calls.ts). web_save's slots are `gate`, this runner's one (save-slots.ts); the channel's end
180
194
  * (the run's end, or its process gone) gives back every slot the run held or waited for, and lets go of every pieced write