@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
@@ -0,0 +1,585 @@
1
+ // The adapter a harness id runs on, and whether this server can run it. With a faux harness module (FAUX_HARNESS_ENV)
2
+ // every id runs on run-adapters' faux harness, scripted by the module's `script(spec)`, as `--faux` runs pi on the
3
+ // faux model. Otherwise codex runs on @parcha/agentrun-harness-codex, opencode on this server's own OpenCode adapter
4
+ // (src/harness-opencode) and claude-agent on @parcha/agentrun-harness-claude, each with serve's own model, price and
5
+ // endpoint, under the run's confinement, and claude-agent with its own web search where the run's web_search resolves
6
+ // native, and codex with its own; a package or a pinned CLI that is missing says so with the one line that installs it:
7
+ // an npm install beside serve, or, when serve runs from npx, the npx line that runs it with the missing package
8
+ // (claude-agent's SDK, Codex, OpenCode).
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { dirname, join, resolve, sep } from "node:path";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
12
+ import { DATA_ENV, defaultData } from "./files.js";
13
+ import { FAUX_HARNESS_ENV } from "./harness.js";
14
+ import { chooseModel, FAUX_ENV, hostModel, openRouterOnly } from "./model.js";
15
+ import { keyShaped } from "./secret-cut.js";
16
+ import { runKeyOf } from "./key-refusal.js";
17
+ import { planeOf } from "./tool-plane.js";
18
+ import { NATIVE_SEARCH_ALLOWANCE_TOKENS } from "./cap.js";
19
+ /** The one line that installs each harness beside serve. */
20
+ export const INSTALL = {
21
+ "claude-agent": "npm install @parcha/agentrun-harness-claude @anthropic-ai/claude-agent-sdk@0.3.286 zod",
22
+ codex: "npm install @parcha/agentrun-harness-codex @openai/codex@0.164.0",
23
+ // The server is named first, as the other lines name a package beside it: OpenCode's CLI is an optional peer of the
24
+ // server's own.
25
+ opencode: "npm install @parcha/agentrun-serve opencode-ai@1.19.5",
26
+ };
27
+ /** This server's version: an npx line names it, so the server it runs is the one that said what was missing. */
28
+ const SERVE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
29
+ /** Whether this server runs from npx's cache (`npx @parcha/agentrun-serve`), where there is no project to install a
30
+ * package into: npm keeps what npx runs under `<npm cache>/_npx/<hash>/node_modules`. Read from where this file is, not
31
+ * from npm's environment (`npm_command=exec`), which every child of an npm command inherits and which npx sets too
32
+ * when it runs a copy a project installed, whose fix stays `npm install`. */
33
+ export const startedByNpx = (file = fileURLToPath(import.meta.url)) => file.split(sep).includes("_npx");
34
+ /** Set by `npx @parcha/agentrun` on the server it starts: that command's package at its version
35
+ * (`@parcha/agentrun@0.3.0`), so a hint names the command the person ran, not the server's own. */
36
+ export const NPX_PACKAGE_ENV = "AGENTRUN_NPX_PACKAGE";
37
+ /** The package each harness needs beside the server, as an npx line adds it. */
38
+ const HARNESS_PACKAGES = ["@anthropic-ai/claude-agent-sdk", "@openai/codex", "opencode-ai"];
39
+ /** The version of `name` installed where Node would look for it from `from`, or undefined. */
40
+ export function installedHere(name, from = fileURLToPath(import.meta.url)) {
41
+ for (let dir = dirname(from);; dir = dirname(dir)) {
42
+ const manifest = join(dir, "node_modules", name, "package.json");
43
+ if (existsSync(manifest)) {
44
+ try {
45
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
46
+ if (pkg.name === name && typeof pkg.version === "string")
47
+ return pkg.version;
48
+ }
49
+ catch { }
50
+ }
51
+ if (dirname(dir) === dir)
52
+ return undefined;
53
+ }
54
+ }
55
+ const shellWord = (word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`);
56
+ /**
57
+ * The one command that starts this same AgentRun again with `spec` beside it: the command the person ran
58
+ * (`npx @parcha/agentrun`, which NPX_PACKAGE_ENV names, or the server's own), this server's version, every other
59
+ * harness's package already here (so following one harness's hint never takes another away), and `--data` with this
60
+ * server's store, so the command opens this same store: always after `npx @parcha/agentrun`, whose own store
61
+ * (~/.agentrun) is not the server's default, and after the server's own command when the store is not its default.
62
+ */
63
+ export function npxLine(spec, env = {}, installed = installedHere) {
64
+ const door = env[NPX_PACKAGE_ENV];
65
+ const command = door !== undefined && /^@parcha\/agentrun@\d[\w.+-]*$/.test(door) ? door : undefined;
66
+ const own = spec.slice(0, spec.lastIndexOf("@"));
67
+ const kept = HARNESS_PACKAGES.filter((name) => name !== own).flatMap((name) => {
68
+ const version = installed(name);
69
+ return version ? [`${name}@${version}`] : [];
70
+ });
71
+ // Pinned even after a command that depends on this server: an older one (0.3.1) fetches the server on its own.
72
+ const packages = [...(command ? [command] : []), `@parcha/agentrun-serve@${SERVE_VERSION}`, ...kept, spec];
73
+ const data = env[DATA_ENV];
74
+ const named = data && (command || resolve(data) !== resolve(defaultData(env))) ? ` --data ${shellWord(resolve(data))}` : "";
75
+ return `npx ${packages.map((name) => `-p ${name}`).join(" ")} ${command ? "agentrun" : "agentrun-serve"}${named}`;
76
+ }
77
+ /** `message` with an adapter's own install line (`npmLine`, which installs `spec` into a project) as the npx line that
78
+ * starts this same AgentRun with `spec` beside it (npxLine), when the server runs from npx. Any other message is left
79
+ * as it is. */
80
+ export function installHint(message, npmLine, spec, npx = startedByNpx(), env = {}, installed) {
81
+ if (!npx || !message.includes(npmLine))
82
+ return message;
83
+ const line = `restart AgentRun with it: ${npxLine(spec, env, installed)}`;
84
+ return message.includes(`install it with: ${npmLine}`) ? message.replace(`install it with: ${npmLine}`, line) : message.replace(npmLine, line);
85
+ }
86
+ /** For tests: a JSON `{command, args?, env?}` that speaks Codex's app-server protocol in place of Codex. agentrun-harness-codex
87
+ * takes it only under its own guard (AGENTRUN_CODEX_STANDIN=1, under a test runner). */
88
+ export const CODEX_STANDIN_ENV = "AGENTRUN_SERVE_CODEX_STANDIN";
89
+ /** For tests: a JSON `{command, args?, env?}` that speaks `opencode serve`'s HTTP API in place of OpenCode. The OpenCode
90
+ * adapter (src/harness-opencode) takes it only under its own guard (AGENTRUN_OPENCODE_STANDIN=1, under a test runner). */
91
+ export const OPENCODE_STANDIN_ENV = "AGENTRUN_SERVE_OPENCODE_STANDIN";
92
+ /** The event of a harness's own lines in the run's log (its model proxy's refusals and failures): a failed run's message
93
+ * is never taken from one (runs.ts lastLogLine). */
94
+ export const HARNESS_LOG_EVENT = "harness";
95
+ /**
96
+ * A harness's log, into the run's log: the run process's stderr, which serve opens on the run's process.log. One JSON
97
+ * line per call, as pi-durable-disk writes them (`{at, event, message, ...}`). A request's path loses its query string,
98
+ * and every value of the environment's key-shaped variables is cut out of the line, so a key a client sent in either
99
+ * place, or one serve holds, never reaches the log.
100
+ */
101
+ export function harnessLog(harness, env, write = (line) => void process.stderr.write(line)) {
102
+ // Every own name, enumerable or not: an environment object may hold a key it does not list.
103
+ const secrets = Object.getOwnPropertyNames(env)
104
+ .map((name) => [name, env[name]])
105
+ .filter(([name, value]) => keyShaped(name) && typeof value === "string" && value.length >= 8)
106
+ .map(([, value]) => value);
107
+ const cut = (text) => secrets.reduce((out, secret) => out.split(secret).join("[redacted]"), text);
108
+ // Every string is cut before it is serialized, field names included: JSON escapes a quote or a backslash, and a
109
+ // secret holding one would no longer match in the line. An object that serializes itself (toJSON) is cut as what it
110
+ // gives. The line is cut again after, as a backstop.
111
+ // toJSON is called once per value, as JSON.stringify does: what it returns is not asked again (one that returns
112
+ // `this` would never end), though the values inside it are.
113
+ const scrub = (value, asked = false) => {
114
+ if (typeof value === "string")
115
+ return cut(value);
116
+ if (!asked && value !== null && typeof value === "object" && typeof value.toJSON === "function")
117
+ return scrub(value.toJSON(), true);
118
+ if (Array.isArray(value))
119
+ return value.map((inner) => scrub(inner));
120
+ if (value !== null && typeof value === "object")
121
+ return Object.fromEntries(Object.entries(value).map(([name, inner]) => [cut(name), scrub(inner)]));
122
+ return value;
123
+ };
124
+ return (message, fields = {}) => {
125
+ const { path, ...rest } = fields;
126
+ const line = JSON.stringify(scrub({ at: new Date().toISOString(), event: HARNESS_LOG_EVENT, harness, message, ...rest, ...(typeof path === "string" ? { path: path.split("?")[0] } : {}) }));
127
+ write(`${cut(line)}\n`);
128
+ };
129
+ }
130
+ /** Why this server cannot run a harness here, in words a person can act on; `fix`, when installing is the fix; `keys`,
131
+ * when a model key is all it lacks: the keys, any one of which, set, lets it run (a key row names it: tool-keys.ts). */
132
+ export class HarnessUnavailable extends Error {
133
+ fix;
134
+ keys;
135
+ constructor(message, fix, keys) {
136
+ super(message);
137
+ this.fix = fix;
138
+ this.keys = keys;
139
+ }
140
+ }
141
+ /** What an adapter's own setup error says installing fixes, by its typed code: none for any other error. */
142
+ function fixOf(error) {
143
+ const code = error?.code;
144
+ if (code === "CLAUDE_AGENT_NOT_INSTALLED" || code === "CODEX_NOT_INSTALLED" || code === "OPENCODE_NOT_INSTALLED")
145
+ return "install";
146
+ if (code === "CLAUDE_AGENT_PIN_MISMATCH" || code === "CODEX_PIN_MISMATCH" || code === "OPENCODE_PIN_MISMATCH")
147
+ return "pins";
148
+ return undefined;
149
+ }
150
+ /** How a reason found at the start's probe ends (harness.ts' harnessOffers), which is the only one: what is installed
151
+ * after it shows once AgentRun restarts. */
152
+ const RESTART = { install: "once it is installed, restart AgentRun to pick it up", pins: "once the pinned build is installed, restart AgentRun" };
153
+ /** The reason the start's probe gives for `error`: its message, ending with the restart (RESTART) where installing is
154
+ * the fix. A message whose install line is npx's has no `fix`: running that line is the restart. */
155
+ export function startReason(error) {
156
+ const message = error instanceof Error ? error.message : String(error);
157
+ const fix = error instanceof HarnessUnavailable ? error.fix : undefined;
158
+ return fix ? `${message.replace(/\.$/, "")}; ${RESTART[fix]}.` : message;
159
+ }
160
+ /** A HarnessUnavailable for an adapter's own setup `error`: its message, with the line that installs the harness when it
161
+ * names none, and with the adapter's own install line (`pinned`) made npx's where serve runs from npx (installHint):
162
+ * installing is its fix unless the line became npx's, which restarts AgentRun itself. */
163
+ function unavailable(harness, error, pinned, npx, env) {
164
+ const message = error.message;
165
+ const said = message.includes("npm install") ? message : `${message} (${INSTALL[harness]})`;
166
+ const hinted = pinned ? installHint(said, pinned.npmLine, pinned.spec, npx, env) : said;
167
+ return new HarnessUnavailable(hinted, hinted === said ? fixOf(error) : undefined);
168
+ }
169
+ /** The ConfineChild that starts a child under `prefix` (the argv pi's commands start under, ending in "--"); none when
170
+ * the run confines nothing, since an adapter refuses a confinement that adds nothing. */
171
+ export function confineOf(prefix) {
172
+ if (!prefix.length)
173
+ return undefined;
174
+ return (child) => ({ command: prefix[0], args: [...prefix.slice(1), child.command, ...child.args] });
175
+ }
176
+ /** Hosts a gateway may be reached at over plain http: this machine. */
177
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]); // key-gate: loopback-rule names this machine only, the hosts a gateway may use plain http on; an allow-list, the line dials nothing
178
+ /**
179
+ * The base `setting` (a gateway's URL) gives the model proxy: its origin and its path, one trailing `/v1` taken off, since
180
+ * every route the proxy sends to begins with `/v1/`. So `https://openrouter.ai/api` and `https://openrouter.ai/api/v1` both
181
+ * send to `https://openrouter.ai/api/v1/...`. A provider's key goes wherever this points, so a value that could point
182
+ * somewhere other than it reads is refused, by the setting's name: userinfo, a query or a fragment, a "." or ".." path
183
+ * segment (raw or percent-encoded), a backslash, whitespace, or plain http to anything but this machine.
184
+ */
185
+ export function gatewayBase(setting, value) {
186
+ const wrong = (why) => new HarnessUnavailable(`${setting} must be an https URL of a gateway, with a path if it serves the API under one; it ${why}.`);
187
+ if (/\s/.test(value))
188
+ throw wrong("holds whitespace");
189
+ // The URL parser reads a backslash as a path separator, so a ".." between backslashes would resolve where "/../" is refused.
190
+ if (value.includes("\\"))
191
+ throw wrong("holds a backslash");
192
+ let url;
193
+ try {
194
+ url = new URL(value);
195
+ }
196
+ catch {
197
+ throw wrong("is not a URL");
198
+ }
199
+ if (url.username || url.password)
200
+ throw wrong("names a user");
201
+ if (url.search || url.hash || /[?#]/.test(value))
202
+ throw wrong("has a query or a fragment");
203
+ // The URL parser resolves dot segments, so they are looked for in the text as given.
204
+ const path = value.slice(value.indexOf("//") + 2).replace(/^[^/]*/, "");
205
+ if (path.split("/").some((segment) => /^(\.|%2e){1,2}$/i.test(segment)))
206
+ throw wrong("has a . or .. path segment");
207
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
208
+ throw wrong(`is ${url.protocol.replace(/:$/, "")}, not https`);
209
+ return `${url.origin}${url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "")}`;
210
+ }
211
+ /** The model key a run on `harness` (claude-agent, codex, or opencode, which takes codex's route) of `model` (the revision's; none, the host's default for the
212
+ * harness) takes: the one its requests carry on the route its provider below takes, as key-refusal.ts' runKeyOf names
213
+ * it. codex: the gateway's when AGENT_MODEL_BASE_URL is set, else OpenAI's, or OpenRouter's on OpenRouter's route;
214
+ * claude-agent: Anthropic's, for api.anthropic.com or ANTHROPIC_BASE_URL alike, or OpenRouter's on OpenRouter's route.
215
+ * None for pi, whose keys are its models' (model.ts' modelKeys). */
216
+ export function harnessModelKeys(harness, env, model) {
217
+ if (harness !== "codex" && harness !== "claude-agent" && harness !== "opencode")
218
+ return [];
219
+ const key = runKeyOf(env, harness, model);
220
+ return key ? [key.field] : [];
221
+ }
222
+ /** OpenRouter's API: its Anthropic Messages endpoint (`<base>/v1/messages`) and its Responses API (`<base>/v1/responses`)
223
+ * under one base, its key taken as a bearer token. The OpenRouter key goes nowhere else. */
224
+ export const OPENROUTER_BASE = "https://openrouter.ai/api";
225
+ /** Anthropic's own origin, where pi-ai's Anthropic provider sends (a gateway is not it). */
226
+ export const ANTHROPIC_ORIGIN = "https://api.anthropic.com";
227
+ /** OpenAI's own origin, where pi-ai's OpenAI provider sends. */
228
+ export const OPENAI_ORIGIN = "https://api.openai.com";
229
+ export { openRouterOnly };
230
+ /** OpenRouter's key, read per request, refused by name where it is not set (a model named on OpenRouter, a host
231
+ * without its key). */
232
+ function openRouterKey(env, harness, named) {
233
+ if (!env.OPENROUTER_API_KEY)
234
+ throw new HarnessUnavailable(`${harness} runs ${named} through OpenRouter, which needs OPENROUTER_API_KEY.`, undefined, ["OPENROUTER_API_KEY"]);
235
+ return () => env.OPENROUTER_API_KEY ?? "";
236
+ }
237
+ export function codexProvider(env, model, harness = "codex") {
238
+ if (env.AGENT_MODEL_BASE_URL)
239
+ return { origin: gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL), credential: () => env.AGENT_MODEL_API_KEY || "none", modelId: model.modelId };
240
+ const named = `${model.provider}/${model.modelId}`;
241
+ if (model.provider === "openrouter" && model.modelId.startsWith("openai/"))
242
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, harness, named), modelId: model.modelId };
243
+ if (model.provider !== "openai")
244
+ throw new HarnessUnavailable(`${harness} runs OpenAI models; the run's model is ${named}.`);
245
+ if (openRouterOnly(harness, env))
246
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, harness, named), modelId: named };
247
+ if (!env.OPENAI_API_KEY)
248
+ throw new HarnessUnavailable(`${harness} needs OPENAI_API_KEY, OPENROUTER_API_KEY (OpenAI's models through OpenRouter), or a gateway in AGENT_MODEL_BASE_URL.`, undefined, ["OPENAI_API_KEY", "OPENROUTER_API_KEY"]);
249
+ return { origin: OPENAI_ORIGIN, credential: () => env.OPENAI_API_KEY ?? "", modelId: model.modelId };
250
+ }
251
+ /** codex's model for `ref` (a revision's; none, the host's default for codex), or opencode's (`harness`), which takes
252
+ * codex's route: as model.ts chooses it, except where it reaches OpenAI only through OpenRouter (openRouterOnly), where an OpenAI model needs no OpenAI key, only a
253
+ * model pi-ai's catalog lists (it prices the run): OpenRouter's key is the one codexProvider sends. A save, a run and
254
+ * capabilities all ask this. */
255
+ export async function codexModel(env, ref, harness = "codex") {
256
+ const named = ref ?? hostModel(env, "default", harness);
257
+ if (env[FAUX_ENV] || env[FAUX_HARNESS_ENV] || !openRouterOnly(harness, env) || !named?.startsWith("openai/"))
258
+ return chooseModel(env, ref, "default", harness);
259
+ const modelId = named.slice("openai/".length);
260
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
261
+ if (!builtinModels().getModel("openai", modelId))
262
+ return { why: `pi-ai knows no model ${modelId} of openai. Name one of its models, or route every model through a gateway with AGENT_MODEL_BASE_URL.`, host: ref === undefined, needs: "model" };
263
+ return { model: { provider: "openai", modelId } };
264
+ }
265
+ /** A response's price in USD, from the same catalog that prices pi's runs; null when the model has no price. The
266
+ * usage's input is net of the cached tokens, which are priced at their own rate. */
267
+ export function priceOf(needs) {
268
+ return (_model, usage) => {
269
+ const cost = needs.models.getModel(needs.model.provider, needs.model.modelId)?.cost;
270
+ if (!cost || typeof cost.input !== "number" || typeof cost.output !== "number")
271
+ return null;
272
+ return (usage.input * cost.input + usage.output * cost.output + (usage.cacheRead ?? 0) * (cost.cacheRead ?? 0) + (usage.cacheWrite ?? 0) * (cost.cacheWrite ?? 0)) / 1e6;
273
+ };
274
+ }
275
+ /** Where claude-agent's requests go, Anthropic Messages only: at ANTHROPIC_BASE_URL's base (an Anthropic-compatible
276
+ * endpoint, with its path: <base>/v1/messages) or api.anthropic.com, with ANTHROPIC_API_KEY as `x-api-key`, priced as
277
+ * Anthropic's; or OpenRouter's Messages endpoint (openRouterOnly, or a model the run names on it,
278
+ * `openrouter/anthropic/<model-id>`), with OPENROUTER_API_KEY as a bearer token, priced as OpenRouter's (OpenRouter
279
+ * bills it). Either way the wire carries Anthropic's own id (`claude-sonnet-5-5`), the one the CLI knows the limits of
280
+ * and OpenRouter takes too. Its own settings only: AGENT_MODEL_BASE_URL is the other harnesses' gateway, and Claude's
281
+ * requests never go there. */
282
+ export function claudeProvider(env, model) {
283
+ const named = `${model.provider}/${model.modelId}`;
284
+ if (model.provider === "openrouter" && model.modelId.startsWith("anthropic/")) {
285
+ const own = claudeModelId({ provider: "anthropic", modelId: model.modelId.slice("anthropic/".length) });
286
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "claude-agent", named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", id: `anthropic/${openRouterName(own)}` } };
287
+ }
288
+ if (model.provider !== "anthropic")
289
+ throw new HarnessUnavailable(`claude-agent runs Anthropic models; the run's model is ${named}.`);
290
+ const own = claudeModelId(model);
291
+ if (openRouterOnly("claude-agent", env))
292
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "claude-agent", named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", id: `anthropic/${openRouterName(own)}` } };
293
+ // The endpoint first: one it refuses is the reason, and no key would fix it (no `keys`). An endpoint the host names
294
+ // takes Anthropic's key alone: OpenRouter's never goes there.
295
+ const origin = env.ANTHROPIC_BASE_URL ? gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL) : ANTHROPIC_ORIGIN;
296
+ if (!env.ANTHROPIC_API_KEY)
297
+ throw env.ANTHROPIC_BASE_URL ? new HarnessUnavailable("claude-agent needs ANTHROPIC_API_KEY.", undefined, ["ANTHROPIC_API_KEY"]) : new HarnessUnavailable("claude-agent needs ANTHROPIC_API_KEY or OPENROUTER_API_KEY.", undefined, ["ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"]);
298
+ return { origin, credential: () => env.ANTHROPIC_API_KEY ?? "", auth: "x-api-key", modelId: own, priceModel: { provider: "anthropic", id: own } };
299
+ }
300
+ /** Anthropic's own model id, the model id with dots as dashes: Anthropic's ids hold no dot, and OpenRouter names the same
301
+ * models with dots (anthropic/claude-sonnet-5.5), so a revision may name either, and the catalog prices them by
302
+ * Anthropic's id. */
303
+ export function claudeModelId(model) {
304
+ return model.provider === "anthropic" ? model.modelId.replaceAll(".", "-") : model.modelId;
305
+ }
306
+ /** OpenRouter's name for Anthropic's model `id` (Anthropic's own), as its catalog and pi-ai's list it: the version's
307
+ * last two numbers joined by a dot (claude-sonnet-5-5 is claude-sonnet-5.5; claude-opus-5 stays). */
308
+ export const openRouterName = (id) => id.replace(/-(\d+)-(\d+)$/, "-$1.$2");
309
+ /** The catalog entry a claude-agent run on `model` is priced and capped by: claudeProvider's, or the model's own where
310
+ * claude-agent does not run here (its run is refused before any request). */
311
+ export function claudePriceModel(env, model) {
312
+ try {
313
+ const { priceModel } = claudeProvider(env, model);
314
+ return { provider: priceModel.provider, modelId: priceModel.id };
315
+ }
316
+ catch {
317
+ return { ...model, modelId: claudeModelId(model) };
318
+ }
319
+ }
320
+ /** The model a learned workflow's requests on `harness` name in the run's models (pi-ai's catalog, app.ts): the route
321
+ * the harness's own requests take (claudeProvider, codexProvider). Through OpenRouter, OpenRouter's name for the run's
322
+ * model, whose key the run holds and whose entry prices it; the vendor's provider would need the vendor's key, which a
323
+ * run on OpenRouter alone does not have. Otherwise the run's model as it is (Anthropic's own id for claude-agent); under
324
+ * a faux harness, through codex's gateway (AGENT_MODEL_BASE_URL), or where the harness refuses the run (before any
325
+ * request), `model` itself. */
326
+ export function learnedRoute(harness, env, model) {
327
+ if (env[FAUX_ENV] || env[FAUX_HARNESS_ENV])
328
+ return model;
329
+ try {
330
+ if (harness === "claude-agent") {
331
+ const { origin, auth, priceModel } = claudeProvider(env, model);
332
+ // OpenRouter's own route only (its key, as a bearer token): a gateway named by ANTHROPIC_BASE_URL, even at
333
+ // OpenRouter's URL, takes Anthropic's key (x-api-key), and learnedWorkflowsOff withholds learned workflows there.
334
+ return origin === OPENROUTER_BASE && auth === "bearer" ? { provider: "openrouter", modelId: priceModel.id } : { ...model, modelId: claudeModelId(model) };
335
+ }
336
+ if (harness === "codex" || harness === "opencode") {
337
+ // Through a gateway (AGENT_MODEL_BASE_URL), even one at OpenRouter's URL, the run's models hold the gateway's
338
+ // provider (runModels), not OpenRouter's: its model is the one prepared. opencode takes codex's route.
339
+ if (env.AGENT_MODEL_BASE_URL)
340
+ return model;
341
+ const { origin, modelId } = codexProvider(env, model, harness);
342
+ return origin === OPENROUTER_BASE ? { provider: "openrouter", modelId } : model;
343
+ }
344
+ }
345
+ catch {
346
+ // The harness refuses this run before any request: nothing is sent on this model.
347
+ }
348
+ return model;
349
+ }
350
+ /** Why a run on `harness` is offered no learned workflow, or undefined when it is. A learned workflow's model requests go
351
+ * through the run's models (pi-ai's catalog, learnedRoute), whose Anthropic provider reaches api.anthropic.com alone:
352
+ * claude-agent through the operator's own gateway (ANTHROPIC_BASE_URL) would have them go around it, with its key. So
353
+ * that run gets none (fail closed), and its pin says why. codex and opencode (codex's route) the same, at any origin
354
+ * learnedOriginOk does not name; their gateway is the run's models' own (runModels), and pi runs on them. A run its
355
+ * harness refuses sends nothing, so it is not this one's to say. */
356
+ export async function learnedWorkflowsOff(harness, env, ref) {
357
+ if (env[FAUX_ENV] || env[FAUX_HARNESS_ENV])
358
+ return undefined;
359
+ let origin;
360
+ if (harness === "claude-agent") {
361
+ const choice = claudeModel(env, ref);
362
+ if ("why" in choice)
363
+ return undefined;
364
+ let chosen;
365
+ try {
366
+ chosen = claudeProvider(env, choice.model);
367
+ }
368
+ catch {
369
+ return undefined;
370
+ }
371
+ // On the route the run chose: the operator's gateway (ANTHROPIC_BASE_URL with Anthropic's key, x-api-key), at any
372
+ // URL, OpenRouter's too, is one a learned node's provider could not follow. OpenRouter's own route (its key, bearer)
373
+ // never goes there, whatever ANTHROPIC_BASE_URL says.
374
+ if (chosen.auth === "x-api-key" && env.ANTHROPIC_BASE_URL)
375
+ return "claude-agent sends this run's model requests to the gateway at ANTHROPIC_BASE_URL, and a learned workflow's requests could not go through it";
376
+ origin = chosen.origin;
377
+ }
378
+ else if (harness === "codex" || harness === "opencode") {
379
+ const choice = await codexModel(env, ref, harness);
380
+ if ("why" in choice)
381
+ return undefined;
382
+ try {
383
+ origin = codexProvider(env, choice.model, harness).origin;
384
+ }
385
+ catch {
386
+ return undefined;
387
+ }
388
+ }
389
+ else
390
+ return undefined;
391
+ if (learnedOriginOk(harness, origin, env))
392
+ return undefined;
393
+ return harness === "claude-agent"
394
+ ? "claude-agent sends this run's model requests to the gateway at ANTHROPIC_BASE_URL, and a learned workflow's requests could not go through it"
395
+ : `${harness} sends this run's model requests to ${origin}, where a learned workflow's requests could not follow`;
396
+ }
397
+ /** Whether a learned workflow's requests reach `origin`, where `harness` sends the run's own (learnedWorkflowsOff): the
398
+ * run's models hold Anthropic's, OpenAI's and OpenRouter's providers, and, for codex and opencode (runModels), the
399
+ * gateway at AGENT_MODEL_BASE_URL. Any other origin is not one they can follow. */
400
+ export function learnedOriginOk(harness, origin, env) {
401
+ if (origin === OPENROUTER_BASE)
402
+ return true;
403
+ if (harness === "claude-agent")
404
+ return origin === ANTHROPIC_ORIGIN;
405
+ if (harness === "codex" || harness === "opencode")
406
+ return origin === OPENAI_ORIGIN || Boolean(env.AGENT_MODEL_BASE_URL);
407
+ return true;
408
+ }
409
+ /** claude-agent's model: the revision's (or the server's default for claude-agent, hostModel) as `provider/model-id`.
410
+ * Never the gateway's model, which serves the other harnesses. An Anthropic model (`anthropic/<id>`) is Anthropic's
411
+ * own id, dots as dashes, except where claude-agent reaches Anthropic only through OpenRouter (openRouterOnly), where it
412
+ * keeps the name it was given (OpenRouter's dotted one, as capabilities show it): claudeProvider names the id on the
413
+ * wire and the catalog entry that prices it. OpenRouter's name for an Anthropic model (pi's,
414
+ * `openrouter/anthropic/<id>`) runs through OpenRouter. Whether it is an Anthropic model is claudeProvider's to say. */
415
+ export function claudeModel(env, ref) {
416
+ const named = ref ?? hostModel(env, "default", "claude-agent");
417
+ if (!named)
418
+ return { why: "No model yet for claude-agent: add an OpenRouter or Anthropic key in Settings → Model keys, or set OPENROUTER_API_KEY or ANTHROPIC_API_KEY where AgentRun starts.", host: true };
419
+ const slash = named.indexOf("/");
420
+ if (slash < 1)
421
+ return { why: `claude-agent runs a model named anthropic/<model-id>; the run's model is ${named}.`, host: ref === undefined };
422
+ const [provider, modelId] = [named.slice(0, slash), named.slice(slash + 1)];
423
+ // OpenRouter's name for a model is OpenRouter's provider, then the vendor's model; another vendor's is claudeProvider's
424
+ // to refuse.
425
+ const [vendor, id, ...more] = modelId.split("/");
426
+ if (provider === "openrouter" && id && !more.length)
427
+ return { model: { provider, modelId: vendor === "anthropic" ? `anthropic/${openRouterName(claudeModelId({ provider: vendor, modelId: id }))}` : modelId } };
428
+ // One provider, then the model's own id: a second segment (anthropic/anthropic/<model>, once a workaround) is refused
429
+ // by name, never sent on to fail at the provider.
430
+ if (modelId.includes("/"))
431
+ return { why: `claude-agent runs a model named ${provider}/<model-id>; ${named} names more than one segment: name it ${provider}/${modelId.slice(modelId.lastIndexOf("/") + 1)}.`, host: ref === undefined };
432
+ if (provider === "anthropic" && openRouterOnly("claude-agent", env))
433
+ return { model: { provider, modelId } };
434
+ // Anthropic's own id from here on, so the cap's model lookup, the price and the wire all name one model the catalog
435
+ // knows: a dotted name (OpenRouter's) would find no model under anthropic, and a cap with no model would admit nothing
436
+ // it could price.
437
+ return { model: { provider, modelId: claudeModelId({ provider, modelId }) } };
438
+ }
439
+ /** The package that runs claude-agent, imported by a name the build does not resolve: it is installed beside serve
440
+ * only by the person who wants it (its SDK is an optional peer). */
441
+ const CLAUDE_PACKAGE = "@parcha/agentrun-harness-claude";
442
+ const loadClaude = () => import(CLAUDE_PACKAGE);
443
+ /** The installed claude-agent adapter's own check of the skills it would load (its skillProblems), from `load` (a test
444
+ * gives its own): what it refuses stays in the run's prompt (skills.ts), so claudeOf never hands it a skill it throws
445
+ * on. None where the package is not installed, or has no such check: every skill stays inlined, and claudeOf says
446
+ * what is missing. */
447
+ export async function claudeSkillCheck(load = loadClaude) {
448
+ const claude = (await load().catch(() => undefined));
449
+ return typeof claude?.skillProblems === "function" ? claude.skillProblems : undefined;
450
+ }
451
+ /** What a harness's adapter takes from the run's plane (tool-plane.ts) where web_search resolves native: claude-agent,
452
+ * Claude's own WebSearch with the input a search request may read in beyond its body (cap.ts), which its proxy adds to
453
+ * that request's bound; codex, Codex's own search, live (its adapter books each search); nothing otherwise. */
454
+ export function nativeOptions(harness, env) {
455
+ if (planeOf(env).web_search !== "native")
456
+ return {};
457
+ if (harness === "claude-agent")
458
+ return { webSearch: true, webSearchAllowance: NATIVE_SEARCH_ALLOWANCE_TOKENS };
459
+ if (harness === "codex")
460
+ return { webSearch: "live" };
461
+ return {};
462
+ }
463
+ /** claude-agent's adapter, from `load` (the installed package; a test gives its own). */
464
+ export async function claudeOf(env, needs, load = loadClaude, npx = startedByNpx()) {
465
+ const claude = (await load().catch(() => {
466
+ throw new HarnessUnavailable(`claude-agent is not installed here: ${INSTALL["claude-agent"]}`, "install");
467
+ }));
468
+ // What no key fixes is said first: the adapter is built before the provider's refusal is thrown, and its construction
469
+ // checks the SDK's version, zod and the pinned CLI (claude --version, once). The provider is read only when a session
470
+ // opens, so an adapter built with an unusable one is never returned.
471
+ let provider;
472
+ let refused;
473
+ try {
474
+ provider = claudeProvider(env, needs.model);
475
+ }
476
+ catch (error) {
477
+ refused = error;
478
+ }
479
+ let adapter;
480
+ try {
481
+ const native = { ...needs, model: { ...needs.model, modelId: claudeModelId(needs.model) } };
482
+ // The CLI runs Anthropic's own id, which it knows the limits and betas of, and sends it as it is, OpenRouter too
483
+ // (claudeProvider's modelId); the key goes as the endpoint takes it, and the run is priced by the catalog entry of
484
+ // whoever bills it (its priceModel).
485
+ const endpoint = provider ? { origin: provider.origin, credential: provider.credential, auth: provider.auth } : { origin: "", credential: () => "" };
486
+ const priced = provider ? { ...needs, model: { provider: provider.priceModel.provider, modelId: provider.priceModel.id } } : native;
487
+ // The skills only when there are some: with none, the adapter keeps its Skill tool off.
488
+ adapter = claude.claudeAgentAdapter({ model: { default: provider?.modelId ?? native.model.modelId }, provider: endpoint, price: priceOf(priced), log: harnessLog("claude-agent", env), ...(needs.confine ? { confine: needs.confine } : {}), ...(needs.skills?.length ? { skills: needs.skills } : {}), ...nativeOptions("claude-agent", env) });
489
+ }
490
+ catch (error) {
491
+ const pinned = claude.CLAUDE_AGENT_SDK_INSTALL && claude.CLAUDE_AGENT_SDK_VERSION ? { npmLine: claude.CLAUDE_AGENT_SDK_INSTALL, spec: `@anthropic-ai/claude-agent-sdk@${claude.CLAUDE_AGENT_SDK_VERSION}` } : undefined;
492
+ throw unavailable("claude-agent", error, pinned, npx, env);
493
+ }
494
+ if (refused !== undefined)
495
+ throw refused;
496
+ return adapter;
497
+ }
498
+ /** The run's thinking level as the harness takes it: serve's levels run to max; Codex's and OpenCode's reasoning efforts
499
+ * (OpenAI's) stop at xhigh. */
500
+ export const thinkingFor = (harness, level) => ((harness === "codex" || harness === "opencode") && level === "max" ? "xhigh" : level);
501
+ /** The bare id Codex takes: serve's "openai/<id>" without its provider. */
502
+ /** codex's adapter, from `load` (the installed package; a test gives its own). */
503
+ export async function codexOf(env, needs, load = () => import("@parcha/agentrun-harness-codex"), npx = startedByNpx()) {
504
+ const codex = await load().catch(() => {
505
+ throw new HarnessUnavailable(`codex is not installed here: ${INSTALL.codex}`, "install");
506
+ });
507
+ const standIn = env[CODEX_STANDIN_ENV] ? JSON.parse(env[CODEX_STANDIN_ENV]) : undefined;
508
+ if (!standIn) {
509
+ try {
510
+ codex.verifyCodex();
511
+ }
512
+ catch (error) {
513
+ throw unavailable("codex", error, { npmLine: codex.CODEX_INSTALL, spec: `@openai/codex@${codex.CODEX_VERSION}` }, npx, env);
514
+ }
515
+ }
516
+ // The id as the provider's endpoint names it (codexProvider): a gateway's own name for the model as model.ts chose it,
517
+ // whole (AGENT_MODEL_GATEWAY_IDS says whether it is provider-qualified), OpenAI's model id, which chooseModel has
518
+ // already taken out of "openai/<id>", or OpenRouter's whole slug.
519
+ const provider = codexProvider(env, needs.model);
520
+ return codex.codexAdapter({ model: provider.modelId, provider: { origin: provider.origin, credential: provider.credential }, price: priceOf(needs), log: harnessLog("codex", env), ...(nativeOptions("codex", env).webSearch === "live" ? { webSearch: "live" } : {}), ...(needs.confine ? { confine: needs.confine } : {}), ...(standIn ? { standIn } : {}) });
521
+ }
522
+ /** opencode's adapter, from `load` (the installed package; a test gives its own). Its model goes where codex's does: serve's
523
+ * gateway (AGENT_MODEL_BASE_URL) or OpenAI, on the Responses API, through the adapter's proxy. */
524
+ export async function opencodeOf(env, needs, load = () => import("./harness-opencode/index.js"), npx = startedByNpx()) {
525
+ const opencode = await load().catch(() => {
526
+ throw new HarnessUnavailable(`opencode is not installed here: ${INSTALL.opencode}`, "install");
527
+ });
528
+ const standIn = env[OPENCODE_STANDIN_ENV] ? JSON.parse(env[OPENCODE_STANDIN_ENV]) : undefined;
529
+ if (!standIn) {
530
+ try {
531
+ opencode.verifyOpenCode();
532
+ }
533
+ catch (error) {
534
+ // serve's own line, which installs the adapter with its pinned CLI, in place of the adapter's (the CLI alone).
535
+ const message = error.message.replace(opencode.OPENCODE_INSTALL, INSTALL.opencode);
536
+ throw unavailable("opencode", Object.assign(new Error(message), { code: error?.code }), { npmLine: INSTALL.opencode, spec: `opencode-ai@${opencode.OPENCODE_VERSION}` }, npx, env);
537
+ }
538
+ }
539
+ // The shared date line (environment.ts) reaches OpenCode in the session's system prompt (app.ts), as it reaches every
540
+ // harness.
541
+ // The id as the provider's endpoint names it (codexProvider, as codexOf takes it): OpenRouter's is the whole slug.
542
+ const provider = codexProvider(env, needs.model, "opencode");
543
+ return opencode.openCodeAdapter({ model: provider.modelId, provider: { origin: provider.origin, credential: provider.credential }, price: priceOf(needs), log: harnessLog("opencode", env), ...(needs.confine ? { confine: needs.confine } : {}), ...(standIn ? { standIn } : {}) });
544
+ }
545
+ export async function adapterFor(harness, env, needs) {
546
+ const faux = env[FAUX_HARNESS_ENV];
547
+ if (faux) {
548
+ const [{ fauxAdapter }, module] = await Promise.all([import("@parcha/agentrun-kernel/testing"), import(pathToFileURL(faux).href)]);
549
+ if (typeof module.script !== "function")
550
+ throw new Error(`${FAUX_HARNESS_ENV} names ${faux}, which exports no script(spec)`);
551
+ // The options the harness's own adapter would be built with from the run (its web search), told to the module.
552
+ module.opened?.(harness, nativeOptions(harness, env));
553
+ return fauxAdapter({ script: module.script });
554
+ }
555
+ if (harness === "codex")
556
+ return codexOf(env, needs);
557
+ if (harness === "opencode")
558
+ return opencodeOf(env, needs);
559
+ if (harness === "claude-agent")
560
+ return claudeOf(env, needs);
561
+ throw new HarnessUnavailable(`This server does not run ${harness} yet.`);
562
+ }
563
+ /** Why `harness` cannot run here, or undefined when it can: its package and pins, its provider, and the adapter's own
564
+ * check of the model `given` names (with none, a model of the harness's own provider: whether it runs here at all).
565
+ * `atStart`: asked by the start's probe, whose offers hold until a restart, so a reason installing fixes ends saying
566
+ * to restart AgentRun once it is installed (startReason). */
567
+ export async function harnessReason(harness, env, given, { atStart = false } = {}) {
568
+ return (await harnessRefusal(harness, env, given, { atStart }))?.reason;
569
+ }
570
+ /** harnessReason's reason, with the model keys any one of which lets the harness run when a key is all it lacks
571
+ * (HarnessUnavailable's `keys`): the start's probe keeps them on the offer, for the key rows (tool-keys.ts). */
572
+ export async function harnessRefusal(harness, env, given, { atStart = false } = {}) {
573
+ if (env[FAUX_HARNESS_ENV])
574
+ return undefined;
575
+ const needs = given ?? { model: { provider: harness === "claude-agent" ? "anthropic" : "openai", modelId: "default" }, models: { getModel: () => undefined } };
576
+ try {
577
+ const adapter = await adapterFor(harness, env, needs);
578
+ const problems = adapter.check({ key: "capabilities", label: "capabilities", system: [], tools: [], context: "fresh" });
579
+ return problems.length ? { reason: problems.join(" ") } : undefined;
580
+ }
581
+ catch (error) {
582
+ const keys = error instanceof HarnessUnavailable ? error.keys : undefined;
583
+ return { reason: atStart ? startReason(error) : error.message, ...(keys?.length ? { keys } : {}) };
584
+ }
585
+ }