@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/model.js ADDED
@@ -0,0 +1,485 @@
1
+ // Where a run's model comes from. An agentic revision names one as "provider/model-id", or names none and runs on this
2
+ // host's default (`AGENT_MODEL`). A workflow's model node names a tier, and the host maps it: fast to
3
+ // `AGENT_MODEL_FAST`, strong to `AGENT_MODEL_STRONG`, each falling back to the default. With `--faux` every model is the
4
+ // faux module's (no key, no network); with `AGENT_MODEL_BASE_URL` every model id goes to that one OpenAI Responses
5
+ // gateway; otherwise pi-ai's providers serve it, each with its keys from the server's secrets (PROVIDER_KEYS): the
6
+ // launcher hands the server every one, and a run's process those of its model's provider, never in an environment.
7
+ import { pathToFileURL } from "node:url";
8
+ import { DEFAULT_HARNESS, FAUX_HARNESS_ENV } from "./harness.js";
9
+ import { authContextOf } from "./secrets.js";
10
+ /** The child's environment names the faux module by absolute path. */
11
+ export const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
12
+ /** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_HARNESS, AGENTRUN_SERVE_FAUX_WEB, ...). */
13
+ export const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
14
+ /** `env` without a test hook's name: serve sets those from startServe's options alone, so a name the server's own
15
+ * environment holds (an operator's export, a leftover) never gives its runs fake answers or loads a module. */
16
+ export const withoutFaux = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith(FAUX_PREFIX)));
17
+ /** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
18
+ * tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
19
+ * request to the provider the revision's model names (web_search's, hosted-search.ts); the run's turns stay faux. */
20
+ export const FAUX_UPSTREAM_ENV = "AGENTRUN_SERVE_FAUX_UPSTREAM";
21
+ /** A run's `effort`, passed to its child. */
22
+ export const EFFORT_ENV = "AGENTRUN_SERVE_EFFORT";
23
+ /** The model the server's keys give a run that names none (hostModel at the run's launch, from every key the server
24
+ * holds), passed to its child as its effort is: behind a gateway the run holds the gateway's key alone, never the key
25
+ * that names its default (runs.ts). A model id, never a secret, so its name has no secret's segment (pi-durable-disk's
26
+ * secret-name rule): a harness's log keeps it (adapters.ts harnessLog). */
27
+ export const DEFAULT_MODEL_ENV = "AGENTRUN_SERVE_DEFAULT_MODEL";
28
+ export const MODEL_PROVIDER = "agent-model";
29
+ export const EFFORTS = ["low", "medium", "high"];
30
+ /** The thinking levels a revision or the host may name. Never off. */
31
+ export const THINKING_LEVELS = ["low", "medium", "high", "xhigh", "max"];
32
+ export const TIERS = ["fast", "default", "strong"];
33
+ const TIER_ENV = { fast: "AGENT_MODEL_FAST", default: "AGENT_MODEL", strong: "AGENT_MODEL_STRONG" };
34
+ /** The workflow node kinds that run on a model. */
35
+ export const MODEL_NODES = ["agent", "decide", "extract", "report"];
36
+ /** The model providers whose key a person may save here (tool-keys.ts' `model` rows), in the order a default is taken
37
+ * from, each with the model a run gets on its key when neither its revision nor the host names one: the provider's
38
+ * capable everyday model, not its dearest (Claude Sonnet 5.5 and GPT-6.1 Sol, each $2 in and $10 out per million
39
+ * tokens). `harnesses`: those that run on the key, pi on any model of it and the harnesses that talk to that
40
+ * provider's own API (OpenAI's: codex and opencode); OpenRouter's runs them all. `models`: a harness's own default on the
41
+ * key where it is not `model`. On OpenRouter:
42
+ * pi's is GPT-6 Sol on pi-ai's openrouter provider (/chat/completions, the key as a bearer token, as OpenRouter's docs
43
+ * name it; its Anthropic models go to /v1/messages with the key in x-api-key, which the docs do not), claude-agent's
44
+ * Claude Sonnet 5.5 and codex's and opencode's GPT-6 Sol, each through OpenRouter's own endpoint for the harness (adapters.ts), the ids
45
+ * a live run took through OpenRouter on 2026-10-29. The row order is the order a default is taken in: a direct
46
+ * provider's key wins over OpenRouter's. */
47
+ export const MODEL_KEYS = [
48
+ { id: "anthropic", label: "Anthropic", field: "ANTHROPIC_API_KEY", model: "anthropic/claude-sonnet-5-5", harnesses: [DEFAULT_HARNESS, "claude-agent"] },
49
+ { id: "openai", label: "OpenAI", field: "OPENAI_API_KEY", model: "openai/gpt-6.1-sol", harnesses: [DEFAULT_HARNESS, "codex", "opencode"] },
50
+ { id: "openrouter", label: "OpenRouter", field: "OPENROUTER_API_KEY", model: "openrouter/openai/gpt-6-sol", harnesses: [DEFAULT_HARNESS, "claude-agent", "codex", "opencode"], models: { "claude-agent": "anthropic/claude-sonnet-5.5", codex: "openai/gpt-6-sol", opencode: "openai/gpt-6-sol" } },
51
+ ];
52
+ /** `row`'s default for `harness`: its own (`models`), else the row's. */
53
+ const rowModel = (row, harness) => row.models?.[harness] ?? row.model;
54
+ /**
55
+ * Whether `harness` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
56
+ * harness's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names
57
+ * (ANTHROPIC_BASE_URL for claude-agent, which needs ANTHROPIC_API_KEY; serve's gateway AGENT_MODEL_BASE_URL for codex
58
+ * and opencode, which take the same route, with AGENT_MODEL_API_KEY or none), then the vendor's own key (ANTHROPIC_API_KEY, OPENAI_API_KEY), then OpenRouter. An
59
+ * endpoint the host names never gets the OpenRouter key.
60
+ */
61
+ export function openRouterOnly(harness, env) {
62
+ if (!env.OPENROUTER_API_KEY)
63
+ return false;
64
+ return harness === "claude-agent" ? !env.ANTHROPIC_BASE_URL && !env.ANTHROPIC_API_KEY : !env.AGENT_MODEL_BASE_URL && !env.OPENAI_API_KEY;
65
+ }
66
+ /** Whether `harness`'s model requests for `model` (as named, `provider/model-id`; none, the host's for the harness) go
67
+ * through OpenRouter: a model named on it (`openrouter/<vendor>/...`), or the harness's vendor reached only through it
68
+ * (openRouterOnly). The route claudeProvider and codexProvider take (adapters.ts); a gateway (AGENT_MODEL_BASE_URL)
69
+ * comes first for codex. On it a harness's own search does not run: OpenRouter runs no OpenAI hosted web_search for
70
+ * Codex and no Anthropic server search for Claude, and its answers carry no count of searches to price. */
71
+ export function viaOpenRouter(env, harness, model) {
72
+ if (harness === "codex")
73
+ return !env.AGENT_MODEL_BASE_URL && (Boolean(model?.startsWith("openrouter/openai/")) || openRouterOnly("codex", env));
74
+ if (harness === "claude-agent")
75
+ return Boolean(model?.startsWith("openrouter/anthropic/")) || openRouterOnly("claude-agent", env);
76
+ return false;
77
+ }
78
+ /** What a person does when no model runs here: add a model provider's key in the console, or set one where AgentRun
79
+ * starts (MODEL_KEYS' fields), OpenRouter's named first, as its one key runs every harness. The order a default is
80
+ * taken in is MODEL_KEYS' own. */
81
+ export const ADD_A_KEY = `add a model key in Settings → Model keys, or set ${[...MODEL_KEYS].sort((a, b) => Number(b.id === "openrouter") - Number(a.id === "openrouter")).map((row) => row.field).join(", ").replace(/, ([^,]+)$/, " or $1")} where AgentRun starts.`;
82
+ /** Whether `id` names `vendor`'s model on OpenRouter (`openrouter/<vendor>/<model-id>`), as pi names it and claude-agent
83
+ * and codex take it (adapters.ts' claudeModel and codexProvider). */
84
+ const onOpenRouter = (id, vendor) => new RegExp(`^openrouter/${vendor}/[^/]+$`).test(id);
85
+ /** Whether `harness` runs the model `id`: pi any; claude-agent an Anthropic model (`anthropic/...`, or Anthropic's on
86
+ * OpenRouter, `openrouter/anthropic/...`), as it talks to an Anthropic Messages endpoint only; codex and opencode, behind a gateway
87
+ * (AGENT_MODEL_BASE_URL), any id, which is the gateway's own string and names no provider here (team/model included),
88
+ * as each takes that gateway for its OpenAI-compatible endpoint; without one, an OpenAI model (`openai/...`, or OpenAI's
89
+ * on OpenRouter). On the faux harness every harness runs the run's model. */
90
+ export function harnessRuns(env, id, harness) {
91
+ if (harness === DEFAULT_HARNESS || env[FAUX_HARNESS_ENV])
92
+ return true;
93
+ const slash = id.indexOf("/");
94
+ const provider = slash > 0 ? id.slice(0, slash) : undefined;
95
+ if (harness === "claude-agent")
96
+ return provider === "anthropic" || onOpenRouter(id, "anthropic");
97
+ if (harness === "codex" || harness === "opencode")
98
+ return Boolean(env.AGENT_MODEL_BASE_URL) || provider === "openai" || onOpenRouter(id, "openai");
99
+ return true;
100
+ }
101
+ /** The model a revision that names none runs on with `harness`, for `tier`: the tier's own variable, else AGENT_MODEL,
102
+ * each only when `harness` runs it (harnessRuns; one it can't is skipped, never an error), else that of the first of
103
+ * MODEL_KEYS whose key is here (a placeholder behind a base URL counts) and that `harness` runs on, else, in a run's
104
+ * process that holds none of those keys, the one the server's keys gave it (DEFAULT_MODEL_ENV). Undefined when none is:
105
+ * the harness has no default here. */
106
+ export function hostModel(env, tier = "default", harness = DEFAULT_HARNESS) {
107
+ for (const id of [env[TIER_ENV[tier]], env.AGENT_MODEL])
108
+ if (id && harnessRuns(env, id, harness))
109
+ return id;
110
+ const row = MODEL_KEYS.find((row) => env[row.field] && row.harnesses.includes(harness));
111
+ return row ? rowModel(row, harness) : env[DEFAULT_MODEL_ENV] || undefined;
112
+ }
113
+ /** A faux model id per tier: `faux-1`, or the id a tier's variable names. */
114
+ const fauxModel = (env, tier) => (tier === "default" ? undefined : env[TIER_ENV[tier]]) || "faux-1";
115
+ /** `route_prefix`: the routing prefix this server puts before a gateway's model ids (MODEL_PROVIDER), which a reader takes off
116
+ * to show the gateway's own id; null with any other source. */
117
+ /** The values `models.source` takes here: a faux module, a gateway, or each provider with its own key. */
118
+ export const MODEL_SOURCES = ["faux", "gateway", "providers"];
119
+ /** What capabilities say about models here: where they come from, and the model of each tier (`default` is also what a
120
+ * revision that names none runs on). */
121
+ export function modelSource(env) {
122
+ const each = (name) => Object.fromEntries(TIERS.map((tier) => [tier, name(tier)]));
123
+ if (env[FAUX_ENV])
124
+ return { source: "faux", route_prefix: null, ...each((tier) => `faux/${fauxModel(env, tier)}`) };
125
+ if (env.AGENT_MODEL_BASE_URL)
126
+ return { source: "gateway", route_prefix: MODEL_PROVIDER, ...each((tier) => (hostModel(env, tier) ? `${MODEL_PROVIDER}/${hostModel(env, tier)}` : null)) };
127
+ return { source: "providers", route_prefix: null, ...each((tier) => hostModel(env, tier) ?? null) };
128
+ }
129
+ /** A workflow's nodes as the DSL's inspection lists them, each read from the document at its path: only what the
130
+ * workflow's structure makes a node, never data shaped like one (a node's `state` may hold an example node). */
131
+ export function workflowNodes(workflow, inspection) {
132
+ const at = (path) => path.split("/").slice(1).reduce((value, part) => value[part.replace(/~1/g, "/").replace(/~0/g, "~")], workflow);
133
+ return inspection.nodes.map(({ path }) => at(path));
134
+ }
135
+ /** The tiers a workflow's model nodes name (`nodes` from workflowNodes); a node that names none is `default`. */
136
+ export function nodeTiers(nodes) {
137
+ const tiers = new Set();
138
+ for (const node of nodes) {
139
+ const model = MODEL_NODES.includes(node.node) || (node.node === "artifact" && ["markdown", "report"].includes(String(node.type)));
140
+ if (model)
141
+ tiers.add(TIERS.includes(node.tier) ? node.tier : "default");
142
+ }
143
+ return TIERS.filter((tier) => tiers.has(tier));
144
+ }
145
+ /** A `{dot.path}` the DSL fills in from the state when the node runs. */
146
+ const TEMPLATE = /\{[a-zA-Z0-9_.$]+\}/;
147
+ /** `tiers` with those a workflow's `llm` calls name (`args.tier`, else default) added: an `llm` call completes on the
148
+ * model of its tier, as a model node does. A tier the state fills in when the call runs (`"{requestedTier}"`, or args
149
+ * filled in whole) may be any of the three, so it adds all three. */
150
+ export function llmTiers(nodes, tiers) {
151
+ const all = new Set(tiers);
152
+ for (const node of nodes) {
153
+ if (node.node !== "call" || node.via !== "tool" || node.tool !== "llm")
154
+ continue;
155
+ const tier = typeof node.args === "string" ? node.args : node.args?.tier;
156
+ if (typeof tier === "string" && TEMPLATE.test(tier))
157
+ TIERS.forEach((each) => all.add(each));
158
+ else
159
+ all.add(TIERS.includes(tier) ? tier : "default");
160
+ }
161
+ return TIERS.filter((tier) => all.has(tier));
162
+ }
163
+ /**
164
+ * The model a revision runs on here, or why it cannot: `ref` is an agentic revision's "provider/model-id", absent for
165
+ * the host's model of `tier`. Through the gateway the ref goes whole, as a gateway such as OpenRouter names its models
166
+ * `vendor/model` (with `AGENT_MODEL_GATEWAY_IDS=bare`, only the part after the provider), and `namedProvider` is that
167
+ * provider, whose catalog entry prices the model. `host` says a setting of this host (a key, a default model) could
168
+ * make it reachable; a model the revision names that pi-ai does not know is not. `needs`: what would: a provider's key
169
+ * (none names a model, or the model's provider has no key here), or another model. `harness` picks the host's model
170
+ * when `ref` is absent (hostModel).
171
+ */
172
+ export async function chooseModel(env, ref, tier = "default", harness = DEFAULT_HARNESS) {
173
+ if (env[FAUX_ENV])
174
+ return { model: { provider: "faux", modelId: fauxModel(env, tier) } };
175
+ const named = ref ?? hostModel(env, tier, harness);
176
+ // In a person's words (a first run from npx sees them): what to add and where. Operator detail is the README's.
177
+ const none = tier === "default" ? "No model yet" : `No model yet for this workflow's ${tier} tier`;
178
+ if (env.AGENT_MODEL_BASE_URL) {
179
+ if (!named)
180
+ return { why: `${none}: name the gateway's model in AGENT_MODEL where AgentRun starts, or add a model key in Settings → Model keys.`, host: true, needs: "key" };
181
+ // A revision's model, and a key's default (MODEL_KEYS: "provider/model"), go as the gateway takes its ids (bare: the
182
+ // part after the provider), that provider pricing them; the host's own AGENT_MODEL or tier id goes as configured.
183
+ const id = ref ?? ([env[TIER_ENV[tier]], env.AGENT_MODEL].includes(named) ? undefined : named);
184
+ const slash = id?.indexOf("/") ?? -1;
185
+ const sent = id && env.AGENT_MODEL_GATEWAY_IDS === "bare" ? id.slice(slash + 1) : named;
186
+ return { model: { provider: MODEL_PROVIDER, modelId: sent }, ...(id && slash > 0 ? { namedProvider: id.slice(0, slash) } : {}) };
187
+ }
188
+ if (!named)
189
+ return { why: `${none}: ${ADD_A_KEY}`, host: true, needs: "key" };
190
+ const slash = named.indexOf("/");
191
+ if (slash < 1)
192
+ return { why: `The host's default model ${named} is not a provider/model-id.`, host: true, needs: "model" };
193
+ const [provider, modelId] = [named.slice(0, slash), named.slice(slash + 1)];
194
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
195
+ const models = builtinModels({ authContext: authContextOf(env) });
196
+ const model = models.getModel(provider, modelId);
197
+ if (!model)
198
+ return { why: `pi-ai knows no model ${modelId} of ${provider}. Name one of its models, or route every model through a gateway with AGENT_MODEL_BASE_URL.`, host: ref === undefined, needs: "model" };
199
+ if (!(await models.getAuth(model))) {
200
+ const row = MODEL_KEYS.find((r) => r.id === provider);
201
+ const field = row?.field ?? models.getProvider(provider)?.auth.apiKey?.name ?? "its API key";
202
+ return { why: `No ${row?.label ?? provider} key here for ${named}: ${row ? `add one in Settings → Model keys, or set ${field}` : `set ${field}`} where AgentRun starts.`, host: true, needs: "key" };
203
+ }
204
+ return { model: { provider, modelId } };
205
+ }
206
+ /**
207
+ * The keys each of pi-ai's providers reads, by its id: pi-ai's own table (env-api-keys' findEnvKeys), and Amazon
208
+ * Bedrock's AWS keys, which that table leaves out as ambient. Every one is on the launcher's list (secrets.ts'
209
+ * SECRET_NAMES), so the server holds it and no environment does, and a run's process is handed a provider's keys over
210
+ * its pipe only when a model it runs is that provider's (runs.ts' secretsFor), as its model's provider reads them from
211
+ * the run's auth context. The custody test checks this against the pi-ai installed, so one that reads another key fails
212
+ * there.
213
+ */
214
+ export const PROVIDER_KEYS = {
215
+ "amazon-bedrock": ["AWS_BEARER_TOKEN_BEDROCK", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"],
216
+ "ant-ling": ["ANT_LING_API_KEY"],
217
+ anthropic: ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
218
+ azure: ["AZURE_OPENAI_API_KEY"],
219
+ baseten: ["BASETEN_API_KEY"],
220
+ cerebras: ["CEREBRAS_API_KEY"],
221
+ "cloudflare-ai-gateway": ["CLOUDFLARE_API_KEY"],
222
+ "cloudflare-workers-ai": ["CLOUDFLARE_API_KEY"],
223
+ deepseek: ["DEEPSEEK_API_KEY"],
224
+ fireworks: ["FIREWORKS_API_KEY"],
225
+ "github-copilot": ["COPILOT_GITHUB_TOKEN"],
226
+ google: ["GEMINI_API_KEY"],
227
+ "google-vertex": ["GOOGLE_CLOUD_API_KEY"],
228
+ groq: ["GROQ_API_KEY"],
229
+ huggingface: ["HF_TOKEN"],
230
+ "kimi-coding": ["KIMI_API_KEY"],
231
+ meta: ["META_API_KEY"],
232
+ minimax: ["MINIMAX_API_KEY"],
233
+ "minimax-cn": ["MINIMAX_CN_API_KEY"],
234
+ mistral: ["MISTRAL_API_KEY"],
235
+ moonshotai: ["MOONSHOT_API_KEY"],
236
+ "moonshotai-cn": ["MOONSHOT_API_KEY"],
237
+ nvidia: ["NVIDIA_API_KEY"],
238
+ openai: ["OPENAI_API_KEY"],
239
+ opencode: ["OPENCODE_API_KEY"],
240
+ "opencode-go": ["OPENCODE_API_KEY"],
241
+ openrouter: ["OPENROUTER_API_KEY"],
242
+ "qwen-token-plan": ["QWEN_TOKEN_PLAN_API_KEY"],
243
+ "qwen-token-plan-cn": ["QWEN_TOKEN_PLAN_CN_API_KEY"],
244
+ "qwen-token-plan-individual": ["QWEN_TOKEN_PLAN_API_KEY"],
245
+ radius: ["RADIUS_API_KEY"],
246
+ together: ["TOGETHER_API_KEY"],
247
+ typesafe: ["TYPESAFE_API_KEY"],
248
+ "vercel-ai-gateway": ["AI_GATEWAY_API_KEY"],
249
+ xai: ["XAI_API_KEY"],
250
+ xiaomi: ["XIAOMI_API_KEY"],
251
+ "xiaomi-token-plan-ams": ["XIAOMI_TOKEN_PLAN_AMS_API_KEY"],
252
+ "xiaomi-token-plan-cn": ["XIAOMI_TOKEN_PLAN_CN_API_KEY"],
253
+ "xiaomi-token-plan-sgp": ["XIAOMI_TOKEN_PLAN_SGP_API_KEY"],
254
+ zai: ["ZAI_API_KEY"],
255
+ "zai-coding-cn": ["ZAI_CODING_CN_API_KEY"],
256
+ };
257
+ /** The keys pi-ai reads at a request, from the request's `env` option (else the process's environment), past the auth
258
+ * context: Bedrock's, whose request builds its AWS credentials itself. */
259
+ const REQUEST_KEYS = PROVIDER_KEYS["amazon-bedrock"];
260
+ /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
261
+ export const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
262
+ /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
263
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
264
+ * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
265
+ * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
266
+ export function modelKeys(env, ref, tiers = ["default"]) {
267
+ if (env.AGENT_MODEL_BASE_URL)
268
+ return [GATEWAY_KEY_ENV];
269
+ const named = tiers.map((tier) => (tier === "default" ? ref : undefined) ?? hostModel(env, tier));
270
+ const providers = named.flatMap((name) => (name && name.indexOf("/") > 0 ? [name.slice(0, name.indexOf("/"))] : []));
271
+ return [...new Set(providers.flatMap((provider) => PROVIDER_KEYS[provider] ?? []))];
272
+ }
273
+ /** A run's thinking level: its `effort`, else its revision's `thinking`, else the host's `AGENT_THINKING`, else medium.
274
+ * Never off. */
275
+ export function thinkingOf(env, revision) {
276
+ const level = [env[EFFORT_ENV], revision, env.AGENT_THINKING].find((name) => THINKING_LEVELS.includes(name));
277
+ return (level ?? "medium");
278
+ }
279
+ /** The models for a run, and its model of each tier it uses and of no other: an agentic revision's `ref` (or the
280
+ * default) is its `default`, and a workflow's tiers are the ones its nodes name. The faux module's replies, the gateway
281
+ * in the environment, or pi-ai's providers. `unpriced`: the ids of its models serve has no price for (a gateway model the
282
+ * catalog does not list, with no price set), which a cap cannot be kept on. */
283
+ export async function runModels(env, ref, tiers = ["default"], harness = DEFAULT_HARNESS) {
284
+ const ai = await import("@earendil-works/pi-ai");
285
+ const { createModels, createProvider } = await import("@earendil-works/pi-ai/models");
286
+ const faux = env[FAUX_ENV];
287
+ const byTier = new Map();
288
+ const namedBy = new Map();
289
+ for (const tier of new Set(tiers)) {
290
+ const chosen = await chooseModel(env, tier === "default" ? ref : undefined, tier, harness);
291
+ if ("why" in chosen)
292
+ throw new Error(chosen.why);
293
+ byTier.set(tier, chosen.model);
294
+ if (chosen.namedProvider)
295
+ namedBy.set(tier, chosen.namedProvider);
296
+ }
297
+ const model = byTier.get("default");
298
+ if (!faux && !env.AGENT_MODEL_BASE_URL) {
299
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
300
+ // Each provider's key from `env`, which holds this process's secrets, never from process.env (secrets.ts).
301
+ return { models: withRequestKeys(builtinModels({ authContext: authContextOf(env) }), env), model, byTier, unpriced: new Set() };
302
+ }
303
+ const ids = [...new Set([...byTier.values()].map((m) => m.modelId))];
304
+ const models = createModels({ authContext: authContextOf(env) });
305
+ const unpriced = new Set();
306
+ if (!ids.length)
307
+ return { models, model, byTier, unpriced };
308
+ if (faux) {
309
+ const mod = (await import(pathToFileURL(faux).href));
310
+ const price = typeof mod.cost === "object" ? mod.cost : undefined;
311
+ if (typeof mod.default !== "function")
312
+ throw new Error(`the faux module ${faux} has no default export function`);
313
+ const reply = mod.default;
314
+ const helpers = { message: ai.fauxAssistantMessage, text: ai.fauxText, thinking: ai.fauxThinking, toolCall: ai.fauxToolCall };
315
+ // `contextWindow` sizes the faux model's window, so a test can make a run long enough to compact.
316
+ const core = ai.createFauxCore({ models: ids.map((id) => ({ id, ...(price ? { cost: price } : {}), ...(typeof mod.contextWindow === "number" ? { contextWindow: mod.contextWindow } : {}) })) });
317
+ const step = (async (context, options, _state, model) => reply(context, { ...helpers, ...(options?.signal ? { signal: options.signal } : {}), ...(model?.id ? { model: model.id } : {}) }));
318
+ core.setResponses(Array.from({ length: 10_000 }, () => step));
319
+ // `cost` (USD per million tokens) prices the faux model's usage, which the faux core leaves at $0, so a run's
320
+ // estimate and its cap can be tested; "unknown" leaves its usage with no cost, as a provider that does not price it.
321
+ const priced = (model, context, options) => {
322
+ const inner = core.stream(model, context, options);
323
+ if (!mod.cost)
324
+ return inner;
325
+ const outer = ai.createAssistantMessageEventStream();
326
+ void (async () => {
327
+ let last;
328
+ for await (const event of inner) {
329
+ const message = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
330
+ if (message) {
331
+ if (price)
332
+ message.usage.cost = ai.calculateCost(model, message.usage);
333
+ else
334
+ delete message.usage.cost;
335
+ last = message;
336
+ }
337
+ outer.push(event);
338
+ }
339
+ outer.end(last ?? (await inner.result()));
340
+ })();
341
+ return outer;
342
+ };
343
+ models.setProvider(createProvider({
344
+ id: core.provider,
345
+ auth: { apiKey: { name: "Faux", resolve: async () => ({ auth: {} }) } },
346
+ models: core.models,
347
+ api: { stream: priced, streamSimple: priced, fetchDeferred: core.fetchDeferred, cancelDeferred: core.cancelDeferred },
348
+ }));
349
+ if (env[FAUX_UPSTREAM_ENV]) {
350
+ const send = (await import(pathToFileURL(env[FAUX_UPSTREAM_ENV]).href)).default;
351
+ const [{ anthropicProvider }, { openaiProvider }] = await Promise.all([import("@earendil-works/pi-ai/providers/anthropic"), import("@earendil-works/pi-ai/providers/openai")]);
352
+ for (const provider of [anthropicProvider(), openaiProvider()]) {
353
+ const via = (stream) => ((model, context, options) => stream(model, context, { ...options, fetch: send }));
354
+ models.setProvider(Object.assign(Object.create(provider), { stream: via(provider.stream.bind(provider)), streamSimple: via(provider.streamSimple.bind(provider)) }));
355
+ }
356
+ }
357
+ return { models, model, byTier, unpriced };
358
+ }
359
+ // One base rule for every harness (adapters.ts' gatewayBase): one trailing /v1 off, then the API under <base>/v1, so
360
+ // <gw>/api and <gw>/api/v1 both reach <gw>/api/v1/responses, as OpenRouter serves it.
361
+ const baseUrl = `${env.AGENT_MODEL_BASE_URL.replace(/\/+$/, "").replace(/\/v1$/, "")}/v1`;
362
+ const { openAIResponsesApi } = await import("@earendil-works/pi-ai/api/openai-responses.lazy");
363
+ // USD per million input, output, cache-read and cache-write tokens, so the run's usage has a price. A tier's own price
364
+ // (`AGENT_MODEL_FAST_PRICE`, `AGENT_MODEL_STRONG_PRICE`) goes with its model, else the default's; a model two tiers
365
+ // share takes the default's. With none set, pi-ai's catalog prices it (listedPrice), a $0 entry included; an id it does
366
+ // not list is unpriced: its answers carry no total (unpricedApi), so the run's cost reads unknown, never $0, and a cap
367
+ // refuses it.
368
+ const prices = new Map();
369
+ for (const tier of ["default", "fast", "strong"]) {
370
+ const id = byTier.get(tier)?.modelId;
371
+ if (id !== undefined && !prices.has(id))
372
+ prices.set(id, { given: (tier !== "default" && env[`${TIER_ENV[tier]}_PRICE`]) || env.AGENT_MODEL_PRICE || undefined, named: namedBy.get(tier) });
373
+ }
374
+ const catalog = [...prices.values()].some((price) => price.given === undefined) ? await catalogPrices() : new Map();
375
+ const listedOf = (id, named) => {
376
+ // A revision's ref names its provider: priced as that provider's entry for the model, whether it went whole or bare.
377
+ if (named !== undefined)
378
+ return listedPrice(catalog.get(id.startsWith(`${named}/`) ? id.slice(named.length + 1) : id) ?? [], named);
379
+ // A host model set whole (`vendor/model`) the catalog does not list as it is: priced as its model, the vendor named.
380
+ const slash = id.indexOf("/");
381
+ if (catalog.has(id) || slash < 1)
382
+ return listedPrice(catalog.get(id) ?? [], undefined);
383
+ return listedPrice(catalog.get(id.slice(slash + 1)) ?? [], id.slice(0, slash));
384
+ };
385
+ const priceOf = (id) => {
386
+ const { given, named } = prices.get(id);
387
+ if (given === undefined) {
388
+ const listed = listedOf(id, named);
389
+ if (listed)
390
+ return listed;
391
+ unpriced.add(id);
392
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
393
+ }
394
+ const [input = 0, output = 0, cacheRead = 0, cacheWrite = input] = given.split(",").map(Number);
395
+ return { input, output, cacheRead, cacheWrite };
396
+ };
397
+ // `models` is priced first, which fills `unpriced`, and `api` is chosen by it.
398
+ models.setProvider(createProvider({
399
+ id: MODEL_PROVIDER,
400
+ baseUrl,
401
+ auth: { apiKey: { name: GATEWAY_KEY_ENV, resolve: async () => ({ auth: { apiKey: env[GATEWAY_KEY_ENV] || "none" }, source: GATEWAY_KEY_ENV }) } },
402
+ models: ids.map((id) => ({
403
+ id, name: id, api: "openai-responses", provider: MODEL_PROVIDER, baseUrl, reasoning: true, input: ["text", "image"],
404
+ cost: priceOf(id), contextWindow: 128_000, maxTokens: 32_000, compat: { supportsDeveloperRole: false },
405
+ })),
406
+ api: unpriced.size ? unpricedApi(openAIResponsesApi(), unpriced, ai) : openAIResponsesApi(),
407
+ }));
408
+ return { models, model, byTier, unpriced };
409
+ }
410
+ /** The requests a Models object sends, each with its options third. */
411
+ const REQUESTS = new Set(["stream", "streamSimple", "complete", "completeSimple"]);
412
+ /** `models` with each request's `env` option carrying the REQUEST_KEYS that `env` holds (a run's process holds only
413
+ * those of its model's provider), so Bedrock's request finds its AWS keys there: in no environment, which would hand
414
+ * them to every program the run starts. A request's own `env` wins. With none held, `models` as it is. */
415
+ function withRequestKeys(models, env) {
416
+ const keys = Object.fromEntries(REQUEST_KEYS.flatMap((name) => (env[name] ? [[name, env[name]]] : [])));
417
+ if (!Object.keys(keys).length)
418
+ return models;
419
+ return new Proxy(models, {
420
+ get: (target, key) => {
421
+ const value = Reflect.get(target, key, target);
422
+ if (typeof value !== "function")
423
+ return value;
424
+ if (!REQUESTS.has(key))
425
+ return value.bind(target);
426
+ return (model, context, options) => value.call(target, model, context, { ...options, env: { ...keys, ...options?.env } });
427
+ },
428
+ });
429
+ }
430
+ /** `api`, with each answer of a model in `unpriced` written as an unpriced one: its usage's cost has no total, as
431
+ * harness-app writes a harness's, so the timeline, the run's cost and /v2 read it unknown rather than $0. Every pi request
432
+ * passes through it, a compaction's summary (`completeSimple`) included. */
433
+ function unpricedApi(api, unpriced, ai) {
434
+ const strip = (message) => void (message?.usage?.cost && delete message.usage.cost.total);
435
+ const unpricedOf = (stream) => ((model, context, options) => {
436
+ const inner = stream(model, context, options);
437
+ if (!unpriced.has(model.id))
438
+ return inner;
439
+ const outer = ai.createAssistantMessageEventStream();
440
+ void (async () => {
441
+ let last;
442
+ for await (const event of inner) {
443
+ const message = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
444
+ if (message) {
445
+ strip(message);
446
+ last = message;
447
+ }
448
+ outer.push(event);
449
+ }
450
+ const result = last ?? (await inner.result());
451
+ strip(result);
452
+ outer.end(result);
453
+ })().catch((error) => {
454
+ const message = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }, errorMessage: `the model request failed: ${String(error?.message ?? error).slice(0, 200)}` };
455
+ outer.push({ type: "error", reason: "error", error: message });
456
+ outer.end(message);
457
+ });
458
+ return outer;
459
+ });
460
+ return { ...api, stream: unpricedOf(api.stream.bind(api)), streamSimple: unpricedOf(api.streamSimple.bind(api)) };
461
+ }
462
+ /** pi-ai's catalog list prices by model id: every provider's entry for it, in the catalog's order. */
463
+ export async function catalogPrices() {
464
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
465
+ const out = new Map();
466
+ for (const model of builtinModels().getModels()) {
467
+ const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, tiers } = model.cost ?? {};
468
+ const listed = out.get(model.id) ?? out.set(model.id, []).get(model.id);
469
+ listed.push({ provider: model.provider, cost: { input, output, cacheRead, cacheWrite, ...(tiers ? { tiers } : {}) } });
470
+ }
471
+ return out;
472
+ }
473
+ /** A gateway model's catalog price: the paid entry of the provider its ref names, when the catalog lists one. Else, as
474
+ * the gateway does not say whose model answers (a named provider is a hint), the highest any provider lists, so the
475
+ * estimate and a cap on it err high: one entry's whole price, the one with the most input plus output (the first of
476
+ * equals), so a $0 entry never wins over a paid one, a named provider's included. An id the catalog lists at $0 is a
477
+ * known $0; one it does not list has no price (undefined). */
478
+ function listedPrice(entries, named) {
479
+ if (!entries.length)
480
+ return undefined;
481
+ const own = named === undefined ? undefined : entries.find((entry) => entry.provider === named);
482
+ if (own && own.cost.input + own.cost.output > 0)
483
+ return own.cost;
484
+ return entries.reduce((top, { cost }) => (cost.input + cost.output > top.input + top.output ? cost : top), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
485
+ }
@@ -0,0 +1,74 @@
1
+ import { type ToolRegistration } from "@earendil-works/pi-durable";
2
+ import type { ToolEntry } from "./tools.js";
3
+ import { type Json } from "./validate.js";
4
+ export declare const MONID_KEY_ENV = "MONID_API_KEY";
5
+ /** Under `faux` only (startServe's `fauxMonid`): a module whose default export is the fetch monid's calls go through, in
6
+ * place of monid's API (the tests' fake). */
7
+ export declare const FAUX_MONID_ENV = "AGENTRUN_SERVE_FAUX_MONID";
8
+ export declare const MONID_API = "https://api.monid.ai";
9
+ /** The most characters of one answer the model reads. */
10
+ export declare const CLIP = 60000;
11
+ /** monid's answer, or `error` saying why there is none, with the HTTP `status` when one came. */
12
+ export type MonidAnswer = Json & {
13
+ error?: string;
14
+ };
15
+ export type MonidOptions = {
16
+ key: string;
17
+ fetch?: typeof fetch;
18
+ /** Each request's own limit (30 s), but a run's first, which gets the whole wait: a sync provider answers in it. */
19
+ requestMs?: number;
20
+ /** Between two reads of an async run (2 s). */
21
+ pollMs?: number;
22
+ /** The most a run is waited for, its first request and every read together (150 s: monid's runs take 1 to 120 s). */
23
+ waitMs?: number;
24
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
25
+ };
26
+ /** What a run cost: `cost` on a run read back, else a sync answer's settled `billing.reportedCost`. */
27
+ export declare const costOf: (record: Json) => {
28
+ value: number;
29
+ currency: string;
30
+ } | undefined;
31
+ /** What a run's answer says monid charged, in USD: its cost; else undefined when monid charged nothing (UNCHARGED), and
32
+ * null for every other answer, which may have been charged (one with no cost, FAILED, TIMED_OUT, a run stopped by its
33
+ * caller or the wait, a run whose sending failed): never $0 for a charge no one knows, and counted by the cap at what
34
+ * the run was held at (paidCall). A cost in another currency is unknown too. */
35
+ export declare function chargeOf(answer: MonidAnswer): number | null | undefined;
36
+ /** monid's three calls on `key`, each answering what the model reads, never throwing. */
37
+ export declare function monidClient(options: MonidOptions): {
38
+ discover: (args: {
39
+ query: string;
40
+ limit?: number;
41
+ minScore?: number;
42
+ }, signal?: AbortSignal) => Promise<MonidAnswer>;
43
+ inspect: (args: {
44
+ provider: string;
45
+ endpoint: string;
46
+ }, signal?: AbortSignal) => Promise<MonidAnswer>;
47
+ run(args: {
48
+ provider: string;
49
+ endpoint: string;
50
+ input?: Json;
51
+ }, signal?: AbortSignal): Promise<MonidAnswer>;
52
+ };
53
+ /** `answer` as the model reads it: JSON, cut at CLIP characters, the whole then filed under `work`'s evidence/monid/
54
+ * (by run id, else by `label` and the time) and the cut saying where. A copy that cannot be filed (a full disk) still
55
+ * answers, cut and saying so: the answer may have been paid for. */
56
+ export declare function monidText(answer: MonidAnswer, work: string, label: string): Promise<string>;
57
+ declare const KINDS: readonly ["discover", "inspect", "run"];
58
+ type Kind = (typeof KINDS)[number];
59
+ /** What a run is held at when no inspect in this run's process quoted its price: an allowance, not a price, set high on
60
+ * purpose. A crash between sending a run and recording its charge leaves the cap counting it, so a cap errs toward
61
+ * refusing sooner, never toward passing unseen. */
62
+ export declare const MONID_RUN_ALLOWANCE_USD = 1;
63
+ /** monid's tool `kind` for a run, under its wire name: the key and the faux hook read from `env` (the run's process's,
64
+ * with its secrets) at each call, an answer too long for the model filed under `work()`, read at the call. A run goes
65
+ * through the run's cap (paidCall), is marked before it is sent (TOOL_STARTED, held at its quoted price or the
66
+ * allowance) and settled by its charge (TOOL_COST): a crash between the two leaves the cap counting the held figure
67
+ * and the run's cost unknown, never $0. pi binds it (monidTool); another harness runs it as a host tool
68
+ * (host-tools.ts), whose `api` commits to the run's store as pi's does. */
69
+ export declare function monidRegistration(kind: Kind, env: NodeJS.ProcessEnv, work: () => string): ToolRegistration;
70
+ /** The three, as another harness's host tools. */
71
+ export declare const monidTools: (env: NodeJS.ProcessEnv, work: () => string) => ToolRegistration[];
72
+ /** The table's entry for `monid.<kind>`: it needs MONID_API_KEY, and no workflow node names it yet. */
73
+ export declare const monidTool: (kind: Kind) => ToolEntry;
74
+ export {};