@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,459 @@
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 and claude-agent on @parcha/agentrun-harness-claude, each
4
+ // with serve's own model, price and endpoint, under the run's confinement, and claude-agent with its own web search
5
+ // where the run's web_search resolves native, and codex with its own; a package or a pinned CLI that is missing says
6
+ // so with the one line that installs it: an npm install beside serve, or, when serve runs from npx, the npx line that
7
+ // runs it with the missing package (claude-agent's SDK, Codex).
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { dirname, join, resolve, sep } from "node:path";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ import { DATA_ENV, defaultData } from "./files.js";
12
+ import { FAUX_HARNESS_ENV } from "./harness.js";
13
+ import { chooseModel, FAUX_ENV, hostModel, openRouterOnly } from "./model.js";
14
+ import { keyShaped } from "./secret-cut.js";
15
+ import { runKeyOf } from "./key-refusal.js";
16
+ import { planeOf } from "./tool-plane.js";
17
+ import { NATIVE_SEARCH_ALLOWANCE_TOKENS } from "./cap.js";
18
+ /** The one line that installs each harness beside serve. */
19
+ export const INSTALL = {
20
+ "claude-agent": "npm install @parcha/agentrun-harness-claude @anthropic-ai/claude-agent-sdk@0.3.286 zod",
21
+ codex: "npm install @parcha/agentrun-harness-codex @openai/codex@0.164.0",
22
+ };
23
+ /** This server's version: an npx line names it, so the server it runs is the one that said what was missing. */
24
+ const SERVE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
25
+ /** Whether this server runs from npx's cache (`npx @parcha/agentrun-serve`), where there is no project to install a
26
+ * package into: npm keeps what npx runs under `<npm cache>/_npx/<hash>/node_modules`. Read from where this file is, not
27
+ * from npm's environment (`npm_command=exec`), which every child of an npm command inherits and which npx sets too
28
+ * when it runs a copy a project installed, whose fix stays `npm install`. */
29
+ export const startedByNpx = (file = fileURLToPath(import.meta.url)) => file.split(sep).includes("_npx");
30
+ /** Set by `npx @parcha/agentrun` on the server it starts: that command's package at its version
31
+ * (`@parcha/agentrun@0.3.0`), so a hint names the command the person ran, not the server's own. */
32
+ export const NPX_PACKAGE_ENV = "AGENTRUN_NPX_PACKAGE";
33
+ /** The package each harness needs beside the server, as an npx line adds it. */
34
+ const HARNESS_PACKAGES = ["@anthropic-ai/claude-agent-sdk", "@openai/codex"];
35
+ /** The version of `name` installed where Node would look for it from `from`, or undefined. */
36
+ export function installedHere(name, from = fileURLToPath(import.meta.url)) {
37
+ for (let dir = dirname(from);; dir = dirname(dir)) {
38
+ const manifest = join(dir, "node_modules", name, "package.json");
39
+ if (existsSync(manifest)) {
40
+ try {
41
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
42
+ if (pkg.name === name && typeof pkg.version === "string")
43
+ return pkg.version;
44
+ }
45
+ catch { }
46
+ }
47
+ if (dirname(dir) === dir)
48
+ return undefined;
49
+ }
50
+ }
51
+ const shellWord = (word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`);
52
+ /**
53
+ * The one command that starts this same AgentRun again with `spec` beside it: the command the person ran
54
+ * (`npx @parcha/agentrun`, which NPX_PACKAGE_ENV names, or the server's own), this server's version, every other
55
+ * harness's package already here (so following one harness's hint never takes another away), and `--data` with this
56
+ * server's store, so the command opens this same store: always after `npx @parcha/agentrun`, whose own store
57
+ * (~/.agentrun) is not the server's default, and after the server's own command when the store is not its default.
58
+ */
59
+ export function npxLine(spec, env = {}, installed = installedHere) {
60
+ const door = env[NPX_PACKAGE_ENV];
61
+ const command = door !== undefined && /^@parcha\/agentrun@\d[\w.+-]*$/.test(door) ? door : undefined;
62
+ const own = spec.slice(0, spec.lastIndexOf("@"));
63
+ const kept = HARNESS_PACKAGES.filter((name) => name !== own).flatMap((name) => {
64
+ const version = installed(name);
65
+ return version ? [`${name}@${version}`] : [];
66
+ });
67
+ // Pinned even after a command that depends on this server: an older one (0.3.1) fetches the server on its own.
68
+ const packages = [...(command ? [command] : []), `@parcha/agentrun-serve@${SERVE_VERSION}`, ...kept, spec];
69
+ const data = env[DATA_ENV];
70
+ const named = data && (command || resolve(data) !== resolve(defaultData(env))) ? ` --data ${shellWord(resolve(data))}` : "";
71
+ return `npx ${packages.map((name) => `-p ${name}`).join(" ")} ${command ? "agentrun" : "agentrun-serve"}${named}`;
72
+ }
73
+ /** `message` with an adapter's own install line (`npmLine`, which installs `spec` into a project) as the npx line that
74
+ * starts this same AgentRun with `spec` beside it (npxLine), when the server runs from npx. Any other message is left
75
+ * as it is. */
76
+ export function installHint(message, npmLine, spec, npx = startedByNpx(), env = {}, installed) {
77
+ if (!npx || !message.includes(npmLine))
78
+ return message;
79
+ const line = `restart AgentRun with it: ${npxLine(spec, env, installed)}`;
80
+ return message.includes(`install it with: ${npmLine}`) ? message.replace(`install it with: ${npmLine}`, line) : message.replace(npmLine, line);
81
+ }
82
+ /** For tests: a JSON `{command, args?, env?}` that speaks Codex's app-server protocol in place of Codex. agentrun-harness-codex
83
+ * takes it only under its own guard (AGENTRUN_CODEX_STANDIN=1, under a test runner). */
84
+ export const CODEX_STANDIN_ENV = "AGENTRUN_SERVE_CODEX_STANDIN";
85
+ /** 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
86
+ * is never taken from one (runs.ts lastLogLine). */
87
+ export const HARNESS_LOG_EVENT = "harness";
88
+ /**
89
+ * 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
90
+ * line per call, as pi-durable-disk writes them (`{at, event, message, ...}`). A request's path loses its query string,
91
+ * and every value of the environment's key-shaped variables is cut out of the line, so a key a client sent in either
92
+ * place, or one serve holds, never reaches the log.
93
+ */
94
+ export function harnessLog(harness, env, write = (line) => void process.stderr.write(line)) {
95
+ // Every own name, enumerable or not: an environment object may hold a key it does not list.
96
+ const secrets = Object.getOwnPropertyNames(env)
97
+ .map((name) => [name, env[name]])
98
+ .filter(([name, value]) => keyShaped(name) && typeof value === "string" && value.length >= 8)
99
+ .map(([, value]) => value);
100
+ const cut = (text) => secrets.reduce((out, secret) => out.split(secret).join("[redacted]"), text);
101
+ // Every string is cut before it is serialized, field names included: JSON escapes a quote or a backslash, and a
102
+ // secret holding one would no longer match in the line. An object that serializes itself (toJSON) is cut as what it
103
+ // gives. The line is cut again after, as a backstop.
104
+ // toJSON is called once per value, as JSON.stringify does: what it returns is not asked again (one that returns
105
+ // `this` would never end), though the values inside it are.
106
+ const scrub = (value, asked = false) => {
107
+ if (typeof value === "string")
108
+ return cut(value);
109
+ if (!asked && value !== null && typeof value === "object" && typeof value.toJSON === "function")
110
+ return scrub(value.toJSON(), true);
111
+ if (Array.isArray(value))
112
+ return value.map((inner) => scrub(inner));
113
+ if (value !== null && typeof value === "object")
114
+ return Object.fromEntries(Object.entries(value).map(([name, inner]) => [cut(name), scrub(inner)]));
115
+ return value;
116
+ };
117
+ return (message, fields = {}) => {
118
+ const { path, ...rest } = fields;
119
+ const line = JSON.stringify(scrub({ at: new Date().toISOString(), event: HARNESS_LOG_EVENT, harness, message, ...rest, ...(typeof path === "string" ? { path: path.split("?")[0] } : {}) }));
120
+ write(`${cut(line)}\n`);
121
+ };
122
+ }
123
+ /** Why this server cannot run a harness here, in words a person can act on; `fix`, when installing is the fix; `keys`,
124
+ * 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). */
125
+ export class HarnessUnavailable extends Error {
126
+ fix;
127
+ keys;
128
+ constructor(message, fix, keys) {
129
+ super(message);
130
+ this.fix = fix;
131
+ this.keys = keys;
132
+ }
133
+ }
134
+ /** What an adapter's own setup error says installing fixes, by its typed code: none for any other error. */
135
+ function fixOf(error) {
136
+ const code = error?.code;
137
+ if (code === "CLAUDE_AGENT_NOT_INSTALLED" || code === "CODEX_NOT_INSTALLED")
138
+ return "install";
139
+ if (code === "CLAUDE_AGENT_PIN_MISMATCH" || code === "CODEX_PIN_MISMATCH")
140
+ return "pins";
141
+ return undefined;
142
+ }
143
+ /** How a reason found at the start's probe ends (harness.ts' harnessOffers), which is the only one: what is installed
144
+ * after it shows once AgentRun restarts. */
145
+ const RESTART = { install: "once it is installed, restart AgentRun to pick it up", pins: "once the pinned build is installed, restart AgentRun" };
146
+ /** The reason the start's probe gives for `error`: its message, ending with the restart (RESTART) where installing is
147
+ * the fix. A message whose install line is npx's has no `fix`: running that line is the restart. */
148
+ export function startReason(error) {
149
+ const message = error instanceof Error ? error.message : String(error);
150
+ const fix = error instanceof HarnessUnavailable ? error.fix : undefined;
151
+ return fix ? `${message.replace(/\.$/, "")}; ${RESTART[fix]}.` : message;
152
+ }
153
+ /** A HarnessUnavailable for an adapter's own setup `error`: its message, with the line that installs the harness when it
154
+ * names none, and with the adapter's own install line (`pinned`) made npx's where serve runs from npx (installHint):
155
+ * installing is its fix unless the line became npx's, which restarts AgentRun itself. */
156
+ function unavailable(harness, error, pinned, npx, env) {
157
+ const message = error.message;
158
+ const said = message.includes("npm install") ? message : `${message} (${INSTALL[harness]})`;
159
+ const hinted = pinned ? installHint(said, pinned.npmLine, pinned.spec, npx, env) : said;
160
+ return new HarnessUnavailable(hinted, hinted === said ? fixOf(error) : undefined);
161
+ }
162
+ /** The ConfineChild that starts a child under `prefix` (the argv pi's commands start under, ending in "--"); none when
163
+ * the run confines nothing, since an adapter refuses a confinement that adds nothing. */
164
+ export function confineOf(prefix) {
165
+ if (!prefix.length)
166
+ return undefined;
167
+ return (child) => ({ command: prefix[0], args: [...prefix.slice(1), child.command, ...child.args] });
168
+ }
169
+ /** Hosts a gateway may be reached at over plain http: this machine. */
170
+ 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
171
+ /**
172
+ * The base `setting` (a gateway's URL) gives the model proxy: its origin and its path, one trailing `/v1` taken off, since
173
+ * every route the proxy sends to begins with `/v1/`. So `https://openrouter.ai/api` and `https://openrouter.ai/api/v1` both
174
+ * send to `https://openrouter.ai/api/v1/...`. A provider's key goes wherever this points, so a value that could point
175
+ * somewhere other than it reads is refused, by the setting's name: userinfo, a query or a fragment, a "." or ".." path
176
+ * segment (raw or percent-encoded), a backslash, whitespace, or plain http to anything but this machine.
177
+ */
178
+ export function gatewayBase(setting, value) {
179
+ 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}.`);
180
+ if (/\s/.test(value))
181
+ throw wrong("holds whitespace");
182
+ // The URL parser reads a backslash as a path separator, so a ".." between backslashes would resolve where "/../" is refused.
183
+ if (value.includes("\\"))
184
+ throw wrong("holds a backslash");
185
+ let url;
186
+ try {
187
+ url = new URL(value);
188
+ }
189
+ catch {
190
+ throw wrong("is not a URL");
191
+ }
192
+ if (url.username || url.password)
193
+ throw wrong("names a user");
194
+ if (url.search || url.hash || /[?#]/.test(value))
195
+ throw wrong("has a query or a fragment");
196
+ // The URL parser resolves dot segments, so they are looked for in the text as given.
197
+ const path = value.slice(value.indexOf("//") + 2).replace(/^[^/]*/, "");
198
+ if (path.split("/").some((segment) => /^(\.|%2e){1,2}$/i.test(segment)))
199
+ throw wrong("has a . or .. path segment");
200
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
201
+ throw wrong(`is ${url.protocol.replace(/:$/, "")}, not https`);
202
+ return `${url.origin}${url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "")}`;
203
+ }
204
+ /** The model key a run on `harness` (claude-agent or codex) of `model` (the revision's; none, the host's default for the
205
+ * harness) takes: the one its requests carry on the route its provider below takes, as key-refusal.ts' runKeyOf names
206
+ * it. codex: the gateway's when AGENT_MODEL_BASE_URL is set, else OpenAI's, or OpenRouter's on OpenRouter's route;
207
+ * claude-agent: Anthropic's, for api.anthropic.com or ANTHROPIC_BASE_URL alike, or OpenRouter's on OpenRouter's route.
208
+ * None for pi, whose keys are its models' (model.ts' modelKeys). */
209
+ export function harnessModelKeys(harness, env, model) {
210
+ if (harness !== "codex" && harness !== "claude-agent")
211
+ return [];
212
+ const key = runKeyOf(env, harness, model);
213
+ return key ? [key.field] : [];
214
+ }
215
+ /** OpenRouter's API: its Anthropic Messages endpoint (`<base>/v1/messages`) and its Responses API (`<base>/v1/responses`)
216
+ * under one base, its key taken as a bearer token. The OpenRouter key goes nowhere else. */
217
+ export const OPENROUTER_BASE = "https://openrouter.ai/api";
218
+ export { openRouterOnly };
219
+ /** OpenRouter's key, read per request, refused by name where it is not set (a model named on OpenRouter, a host
220
+ * without its key). */
221
+ function openRouterKey(env, harness, named) {
222
+ if (!env.OPENROUTER_API_KEY)
223
+ throw new HarnessUnavailable(`${harness} runs ${named} through OpenRouter, which needs OPENROUTER_API_KEY.`, undefined, ["OPENROUTER_API_KEY"]);
224
+ return () => env.OPENROUTER_API_KEY ?? "";
225
+ }
226
+ export function codexProvider(env, model) {
227
+ if (env.AGENT_MODEL_BASE_URL)
228
+ return { origin: gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL), credential: () => env.AGENT_MODEL_API_KEY || "none", modelId: model.modelId };
229
+ const named = `${model.provider}/${model.modelId}`;
230
+ if (model.provider === "openrouter" && model.modelId.startsWith("openai/"))
231
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "codex", named), modelId: model.modelId };
232
+ if (model.provider !== "openai")
233
+ throw new HarnessUnavailable(`codex runs OpenAI models; the run's model is ${named}.`);
234
+ if (openRouterOnly("codex", env))
235
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "codex", named), modelId: named };
236
+ if (!env.OPENAI_API_KEY)
237
+ throw new HarnessUnavailable("codex 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"]);
238
+ return { origin: "https://api.openai.com", credential: () => env.OPENAI_API_KEY ?? "", modelId: model.modelId };
239
+ }
240
+ /** codex's model for `ref` (a revision's; none, the host's default for codex): as model.ts chooses it, except where
241
+ * codex reaches OpenAI only through OpenRouter (openRouterOnly), where an OpenAI model needs no OpenAI key, only a
242
+ * model pi-ai's catalog lists (it prices the run): OpenRouter's key is the one codexProvider sends. A save, a run and
243
+ * capabilities all ask this. */
244
+ export async function codexModel(env, ref) {
245
+ const named = ref ?? hostModel(env, "default", "codex");
246
+ if (env[FAUX_ENV] || env[FAUX_HARNESS_ENV] || !openRouterOnly("codex", env) || !named?.startsWith("openai/"))
247
+ return chooseModel(env, ref, "default", "codex");
248
+ const modelId = named.slice("openai/".length);
249
+ const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
250
+ if (!builtinModels().getModel("openai", modelId))
251
+ 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" };
252
+ return { model: { provider: "openai", modelId } };
253
+ }
254
+ /** A response's price in USD, from the same catalog that prices pi's runs; null when the model has no price. The
255
+ * usage's input is net of the cached tokens, which are priced at their own rate. */
256
+ export function priceOf(needs) {
257
+ return (_model, usage) => {
258
+ const cost = needs.models.getModel(needs.model.provider, needs.model.modelId)?.cost;
259
+ if (!cost || typeof cost.input !== "number" || typeof cost.output !== "number")
260
+ return null;
261
+ return (usage.input * cost.input + usage.output * cost.output + (usage.cacheRead ?? 0) * (cost.cacheRead ?? 0) + (usage.cacheWrite ?? 0) * (cost.cacheWrite ?? 0)) / 1e6;
262
+ };
263
+ }
264
+ /** Where claude-agent's requests go, Anthropic Messages only: at ANTHROPIC_BASE_URL's base (an Anthropic-compatible
265
+ * endpoint, with its path: <base>/v1/messages) or api.anthropic.com, with ANTHROPIC_API_KEY as `x-api-key`, priced as
266
+ * Anthropic's; or OpenRouter's Messages endpoint (openRouterOnly, or a model the run names on it,
267
+ * `openrouter/anthropic/<model-id>`), with OPENROUTER_API_KEY as a bearer token, priced as OpenRouter's (OpenRouter
268
+ * bills it). Either way the wire carries Anthropic's own id (`claude-sonnet-5-5`), the one the CLI knows the limits of
269
+ * and OpenRouter takes too. Its own settings only: AGENT_MODEL_BASE_URL is the other harnesses' gateway, and Claude's
270
+ * requests never go there. */
271
+ export function claudeProvider(env, model) {
272
+ const named = `${model.provider}/${model.modelId}`;
273
+ if (model.provider === "openrouter" && model.modelId.startsWith("anthropic/")) {
274
+ const own = claudeModelId({ provider: "anthropic", modelId: model.modelId.slice("anthropic/".length) });
275
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "claude-agent", named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", id: `anthropic/${openRouterName(own)}` } };
276
+ }
277
+ if (model.provider !== "anthropic")
278
+ throw new HarnessUnavailable(`claude-agent runs Anthropic models; the run's model is ${named}.`);
279
+ const own = claudeModelId(model);
280
+ if (openRouterOnly("claude-agent", env))
281
+ return { origin: OPENROUTER_BASE, credential: openRouterKey(env, "claude-agent", named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", id: `anthropic/${openRouterName(own)}` } };
282
+ // The endpoint first: one it refuses is the reason, and no key would fix it (no `keys`). An endpoint the host names
283
+ // takes Anthropic's key alone: OpenRouter's never goes there.
284
+ const origin = env.ANTHROPIC_BASE_URL ? gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL) : "https://api.anthropic.com";
285
+ if (!env.ANTHROPIC_API_KEY)
286
+ 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"]);
287
+ return { origin, credential: () => env.ANTHROPIC_API_KEY ?? "", auth: "x-api-key", modelId: own, priceModel: { provider: "anthropic", id: own } };
288
+ }
289
+ /** Anthropic's own model id, the model id with dots as dashes: Anthropic's ids hold no dot, and OpenRouter names the same
290
+ * models with dots (anthropic/claude-sonnet-5.5), so a revision may name either, and the catalog prices them by
291
+ * Anthropic's id. */
292
+ export function claudeModelId(model) {
293
+ return model.provider === "anthropic" ? model.modelId.replaceAll(".", "-") : model.modelId;
294
+ }
295
+ /** OpenRouter's name for Anthropic's model `id` (Anthropic's own), as its catalog and pi-ai's list it: the version's
296
+ * last two numbers joined by a dot (claude-sonnet-5-5 is claude-sonnet-5.5; claude-opus-5 stays). */
297
+ export const openRouterName = (id) => id.replace(/-(\d+)-(\d+)$/, "-$1.$2");
298
+ /** The catalog entry a claude-agent run on `model` is priced and capped by: claudeProvider's, or the model's own where
299
+ * claude-agent does not run here (its run is refused before any request). */
300
+ export function claudePriceModel(env, model) {
301
+ try {
302
+ const { priceModel } = claudeProvider(env, model);
303
+ return { provider: priceModel.provider, modelId: priceModel.id };
304
+ }
305
+ catch {
306
+ return { ...model, modelId: claudeModelId(model) };
307
+ }
308
+ }
309
+ /** claude-agent's model: the revision's (or the server's default for claude-agent, hostModel) as `provider/model-id`.
310
+ * Never the gateway's model, which serves the other harnesses. An Anthropic model (`anthropic/<id>`) is Anthropic's
311
+ * own id, dots as dashes, except where claude-agent reaches Anthropic only through OpenRouter (openRouterOnly), where it
312
+ * keeps the name it was given (OpenRouter's dotted one, as capabilities show it): claudeProvider names the id on the
313
+ * wire and the catalog entry that prices it. OpenRouter's name for an Anthropic model (pi's,
314
+ * `openrouter/anthropic/<id>`) runs through OpenRouter. Whether it is an Anthropic model is claudeProvider's to say. */
315
+ export function claudeModel(env, ref) {
316
+ const named = ref ?? hostModel(env, "default", "claude-agent");
317
+ if (!named)
318
+ 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 };
319
+ const slash = named.indexOf("/");
320
+ if (slash < 1)
321
+ return { why: `claude-agent runs a model named anthropic/<model-id>; the run's model is ${named}.`, host: ref === undefined };
322
+ const [provider, modelId] = [named.slice(0, slash), named.slice(slash + 1)];
323
+ // OpenRouter's name for a model is OpenRouter's provider, then the vendor's model; another vendor's is claudeProvider's
324
+ // to refuse.
325
+ const [vendor, id, ...more] = modelId.split("/");
326
+ if (provider === "openrouter" && id && !more.length)
327
+ return { model: { provider, modelId: vendor === "anthropic" ? `anthropic/${openRouterName(claudeModelId({ provider: vendor, modelId: id }))}` : modelId } };
328
+ // One provider, then the model's own id: a second segment (anthropic/anthropic/<model>, once a workaround) is refused
329
+ // by name, never sent on to fail at the provider.
330
+ if (modelId.includes("/"))
331
+ 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 };
332
+ if (provider === "anthropic" && openRouterOnly("claude-agent", env))
333
+ return { model: { provider, modelId } };
334
+ // Anthropic's own id from here on, so the cap's model lookup, the price and the wire all name one model the catalog
335
+ // knows: a dotted name (OpenRouter's) would find no model under anthropic, and a cap with no model would admit nothing
336
+ // it could price.
337
+ return { model: { provider, modelId: claudeModelId({ provider, modelId }) } };
338
+ }
339
+ /** The package that runs claude-agent, imported by a name the build does not resolve: it is installed beside serve
340
+ * only by the person who wants it (its SDK is an optional peer). */
341
+ const CLAUDE_PACKAGE = "@parcha/agentrun-harness-claude";
342
+ const loadClaude = () => import(CLAUDE_PACKAGE);
343
+ /** The installed claude-agent adapter's own check of the skills it would load (its skillProblems), from `load` (a test
344
+ * gives its own): what it refuses stays in the run's prompt (skills.ts), so claudeOf never hands it a skill it throws
345
+ * on. None where the package is not installed, or has no such check: every skill stays inlined, and claudeOf says
346
+ * what is missing. */
347
+ export async function claudeSkillCheck(load = loadClaude) {
348
+ const claude = (await load().catch(() => undefined));
349
+ return typeof claude?.skillProblems === "function" ? claude.skillProblems : undefined;
350
+ }
351
+ /** What a harness's adapter takes from the run's plane (tool-plane.ts) where web_search resolves native: claude-agent,
352
+ * Claude's own WebSearch with the input a search request may read in beyond its body (cap.ts), which its proxy adds to
353
+ * that request's bound; codex, Codex's own search, live (its adapter books each search); nothing otherwise. */
354
+ export function nativeOptions(harness, env) {
355
+ if (planeOf(env).web_search !== "native")
356
+ return {};
357
+ if (harness === "claude-agent")
358
+ return { webSearch: true, webSearchAllowance: NATIVE_SEARCH_ALLOWANCE_TOKENS };
359
+ if (harness === "codex")
360
+ return { webSearch: "live" };
361
+ return {};
362
+ }
363
+ /** claude-agent's adapter, from `load` (the installed package; a test gives its own). */
364
+ export async function claudeOf(env, needs, load = loadClaude, npx = startedByNpx()) {
365
+ const claude = (await load().catch(() => {
366
+ throw new HarnessUnavailable(`claude-agent is not installed here: ${INSTALL["claude-agent"]}`, "install");
367
+ }));
368
+ // What no key fixes is said first: the adapter is built before the provider's refusal is thrown, and its construction
369
+ // checks the SDK's version, zod and the pinned CLI (claude --version, once). The provider is read only when a session
370
+ // opens, so an adapter built with an unusable one is never returned.
371
+ let provider;
372
+ let refused;
373
+ try {
374
+ provider = claudeProvider(env, needs.model);
375
+ }
376
+ catch (error) {
377
+ refused = error;
378
+ }
379
+ let adapter;
380
+ try {
381
+ const native = { ...needs, model: { ...needs.model, modelId: claudeModelId(needs.model) } };
382
+ // The CLI runs Anthropic's own id, which it knows the limits and betas of, and sends it as it is, OpenRouter too
383
+ // (claudeProvider's modelId); the key goes as the endpoint takes it, and the run is priced by the catalog entry of
384
+ // whoever bills it (its priceModel).
385
+ const endpoint = provider ? { origin: provider.origin, credential: provider.credential, auth: provider.auth } : { origin: "", credential: () => "" };
386
+ const priced = provider ? { ...needs, model: { provider: provider.priceModel.provider, modelId: provider.priceModel.id } } : native;
387
+ // The skills only when there are some: with none, the adapter keeps its Skill tool off.
388
+ 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) });
389
+ }
390
+ catch (error) {
391
+ 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;
392
+ throw unavailable("claude-agent", error, pinned, npx, env);
393
+ }
394
+ if (refused !== undefined)
395
+ throw refused;
396
+ return adapter;
397
+ }
398
+ /** The run's thinking level as the harness takes it: serve's levels run to max; Codex's reasoning efforts stop at xhigh. */
399
+ export const thinkingFor = (harness, level) => (harness === "codex" && level === "max" ? "xhigh" : level);
400
+ /** The bare id Codex takes: serve's "openai/<id>" without its provider. */
401
+ /** codex's adapter, from `load` (the installed package; a test gives its own). */
402
+ export async function codexOf(env, needs, load = () => import("@parcha/agentrun-harness-codex"), npx = startedByNpx()) {
403
+ const codex = await load().catch(() => {
404
+ throw new HarnessUnavailable(`codex is not installed here: ${INSTALL.codex}`, "install");
405
+ });
406
+ const standIn = env[CODEX_STANDIN_ENV] ? JSON.parse(env[CODEX_STANDIN_ENV]) : undefined;
407
+ if (!standIn) {
408
+ try {
409
+ codex.verifyCodex();
410
+ }
411
+ catch (error) {
412
+ throw unavailable("codex", error, { npmLine: codex.CODEX_INSTALL, spec: `@openai/codex@${codex.CODEX_VERSION}` }, npx, env);
413
+ }
414
+ }
415
+ // The id as the provider's endpoint names it (codexProvider): a gateway's own name for the model as model.ts chose it,
416
+ // whole (AGENT_MODEL_GATEWAY_IDS says whether it is provider-qualified), OpenAI's model id, which chooseModel has
417
+ // already taken out of "openai/<id>", or OpenRouter's whole slug.
418
+ const provider = codexProvider(env, needs.model);
419
+ 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 } : {}) });
420
+ }
421
+ export async function adapterFor(harness, env, needs) {
422
+ const faux = env[FAUX_HARNESS_ENV];
423
+ if (faux) {
424
+ const [{ fauxAdapter }, module] = await Promise.all([import("@parcha/agentrun-kernel/testing"), import(pathToFileURL(faux).href)]);
425
+ if (typeof module.script !== "function")
426
+ throw new Error(`${FAUX_HARNESS_ENV} names ${faux}, which exports no script(spec)`);
427
+ // The options the harness's own adapter would be built with from the run (its web search), told to the module.
428
+ module.opened?.(harness, nativeOptions(harness, env));
429
+ return fauxAdapter({ script: module.script });
430
+ }
431
+ if (harness === "codex")
432
+ return codexOf(env, needs);
433
+ if (harness === "claude-agent")
434
+ return claudeOf(env, needs);
435
+ throw new HarnessUnavailable(`This server does not run ${harness} yet.`);
436
+ }
437
+ /** Why `harness` cannot run here, or undefined when it can: its package and pins, its provider, and the adapter's own
438
+ * check of the model `given` names (with none, a model of the harness's own provider: whether it runs here at all).
439
+ * `atStart`: asked by the start's probe, whose offers hold until a restart, so a reason installing fixes ends saying
440
+ * to restart AgentRun once it is installed (startReason). */
441
+ export async function harnessReason(harness, env, given, { atStart = false } = {}) {
442
+ return (await harnessRefusal(harness, env, given, { atStart }))?.reason;
443
+ }
444
+ /** harnessReason's reason, with the model keys any one of which lets the harness run when a key is all it lacks
445
+ * (HarnessUnavailable's `keys`): the start's probe keeps them on the offer, for the key rows (tool-keys.ts). */
446
+ export async function harnessRefusal(harness, env, given, { atStart = false } = {}) {
447
+ if (env[FAUX_HARNESS_ENV])
448
+ return undefined;
449
+ const needs = given ?? { model: { provider: harness === "claude-agent" ? "anthropic" : "openai", modelId: "default" }, models: { getModel: () => undefined } };
450
+ try {
451
+ const adapter = await adapterFor(harness, env, needs);
452
+ const problems = adapter.check({ key: "capabilities", label: "capabilities", system: [], tools: [], context: "fresh" });
453
+ return problems.length ? { reason: problems.join(" ") } : undefined;
454
+ }
455
+ catch (error) {
456
+ const keys = error instanceof HarnessUnavailable ? error.keys : undefined;
457
+ return { reason: atStart ? startReason(error) : error.message, ...(keys?.length ? { keys } : {}) };
458
+ }
459
+ }
@@ -0,0 +1,124 @@
1
+ import { type Agent, type AgentStore, type NewRevision, type Revision, type RevisionRow } from "@parcha/pi-durable-agent";
2
+ import { ApiError } from "./errors.js";
3
+ import { type DefinitionBody, type Json } from "./validate.js";
4
+ /** One agent as the routes show it: its row, its current revision and that revision's number (the oldest is 1). */
5
+ export type AgentEntry = {
6
+ agent: Agent;
7
+ revision: Revision | null;
8
+ version: number;
9
+ revisions: number;
10
+ runs: {
11
+ count: number;
12
+ live: number;
13
+ };
14
+ sizes: Map<string, number>;
15
+ };
16
+ /** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
17
+ export declare const sqliteBusy: (error: unknown) => boolean;
18
+ /** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
19
+ * milliseconds; about 2 s in all, then the request answers home_busy. */
20
+ export declare const REQUEST_BUSY_MS: readonly number[];
21
+ /** `act` again while another connection holds the store: after busy `attempt`, `onBusy` hears of it and the next of
22
+ * `delaysMs` is waited out without blocking the event loop. Past the last, the busy error is thrown. */
23
+ export declare function whenFree<T>(act: () => T | Promise<T>, delaysMs: readonly number[], onBusy?: (attempt: number, delayMs: number | undefined) => void): Promise<T>;
24
+ /** A store another writer holds: SQLite's busy or locked, or the agent home's own `busy` (a home held past its deadline, or a
25
+ * store a stopped writer left mid-write). Every answer of the server maps it the same way: home_busy. */
26
+ export declare const storeBusy: (error: unknown) => boolean;
27
+ /** The answer to a request the agent store stayed busy for. */
28
+ export declare const homeBusy: () => ApiError;
29
+ /** A store error as the request's answer: a busy store is retryable, a refusal names the field it refused. */
30
+ export declare function storeError(error: unknown, field?: string): never;
31
+ export declare class Agents {
32
+ readonly dir: string;
33
+ /** Never waits for another connection synchronously: what touches it goes through `request` or `whenFree`. */
34
+ readonly store: AgentStore;
35
+ /** Read-only, for the store's skill texts, which its reads do not return. */
36
+ private readonly skills;
37
+ constructor(dir: string);
38
+ /** A read or write of the store for a request: a busy store is waited for about 2 s (REQUEST_BUSY_MS). */
39
+ request<T>(act: () => T | Promise<T>): Promise<T>;
40
+ private closed;
41
+ close(): void;
42
+ /** Skill texts by their SHA-256. */
43
+ private texts;
44
+ /** The revision a checked definition makes; `files` are its skill files by path. */
45
+ private revisionOf;
46
+ /** `definition.version`, when given, is the number of the revision the request leaves current. */
47
+ private checkVersion;
48
+ /** A workflow revision is checked before anything is written, so a refusal makes no agent. */
49
+ private checked;
50
+ /** A new agent and its first revision, current. A definition id already here is `409 agent_exists`. `check` sees the
51
+ * revision before anything is written, and may refuse it. */
52
+ create({ definition, skills, note }: DefinitionBody, check?: (revision: NewRevision) => Promise<void>): Promise<AgentEntry>;
53
+ /** An edit: a new revision of the agent, its parent the current one, made current. Without `skills` the current
54
+ * revision's skill files carry over. An edit that is the current revision writes nothing, so a PUT sent twice makes
55
+ * one revision. The store keeps an agent's id, name and description from its creation. `ifCurrent` (from If-Match)
56
+ * is the current revision the caller read, null for none: the store compares it in the commit's own transaction.
57
+ * `check` sees the revision, the current one's included, before anything is written, and may refuse it. */
58
+ /** `contract`: the contract's edit, whose version the caller has checked is past the current one. It always makes a new
59
+ * revision, the same definition included, numbered as this store numbers them (the next), whatever version it named. */
60
+ commit(read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract }?: {
61
+ ifCurrent?: string | null;
62
+ check?: (revision: NewRevision) => Promise<void>;
63
+ contract?: boolean;
64
+ }): Promise<AgentEntry>;
65
+ /** Makes `revision`, one of the agent's own, its current one. */
66
+ setCurrent(entry: AgentEntry, revision: string): Promise<AgentEntry>;
67
+ /** Archives or unarchives an agent or a run. */
68
+ setArchived(kind: "agent" | "run", id: string, archived: boolean): Promise<void>;
69
+ /** The agent's revisions, newest first, each with its number. */
70
+ revisions(id: string): Promise<Array<RevisionRow & {
71
+ version: number;
72
+ }>>;
73
+ /** Revision `id` and its number, or null when it is not one of `agent`'s. */
74
+ revision(agent: string, id: string): Promise<{
75
+ revision: Revision;
76
+ version: number;
77
+ } | null>;
78
+ /** The agent `id`, or null. `runs` saves a read when the caller holds every run already. */
79
+ get(id: string): Promise<AgentEntry | null>;
80
+ private entry;
81
+ /** Every agent here, newest first. */
82
+ list(): Promise<AgentEntry[]>;
83
+ }
84
+ /** The agent's ETag: its current revision, which only an edit or `POST .../current` moves. */
85
+ export declare const etagOf: (entry: AgentEntry) => string;
86
+ /** A revision as a definition, as `POST /agents` takes one, numbered. */
87
+ export declare function definitionOf(agent: Agent, revision: Revision, version: number): Json;
88
+ /** `Agent` as the contract shows it, with its current revision. */
89
+ export declare function agentView(entry: AgentEntry): {
90
+ agent_id: string;
91
+ definition: Json | null;
92
+ kind: "workflow" | "agentic" | null;
93
+ revision: string | null;
94
+ revisions: number;
95
+ source: null;
96
+ skills: {
97
+ path: string;
98
+ sha256: string;
99
+ size_bytes: number | null;
100
+ }[];
101
+ sign_ins: never[];
102
+ runs: {
103
+ count: number;
104
+ live: number;
105
+ };
106
+ region: string;
107
+ home_etag: string;
108
+ archived_at: string | null;
109
+ created_at: string;
110
+ updated_at: string;
111
+ };
112
+ /** One revision as `GET .../revisions` lists it. */
113
+ export declare function revisionView(agent: Agent, row: RevisionRow & {
114
+ version: number;
115
+ }, revision: Revision): {
116
+ revision: string;
117
+ version: number;
118
+ parent: string | null;
119
+ kind: import("@parcha/pi-durable-agent").RevisionKind;
120
+ current: boolean;
121
+ note: string | null;
122
+ created_at: string;
123
+ definition: Json;
124
+ };