@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
package/dist/mcp.js ADDED
@@ -0,0 +1,392 @@
1
+ // The MCP endpoint, POST /v2/mcp: the Model Context Protocol over Streamable HTTP in its simplest form, one JSON-RPC
2
+ // message per POST, answered as JSON, stateless (no stream, no session). Its tools run the /v2 routes themselves: a tool
3
+ // calls the route that serves it in process, with the caller's token, so it checks and answers exactly as that route
4
+ // does, and a route's refusal is the tool's error. A run is started, then polled: no tool holds its call open for a run.
5
+ // The endpoint takes the Bearer token only, never the page's cookie, and refuses a browser Origin other than this
6
+ // server's own (the transport's rule against DNS rebinding; on loopback the Host check comes first, in server.ts).
7
+ import { readFile } from "node:fs/promises";
8
+ import { Readable, Writable } from "node:stream";
9
+ import { homeBusy, storeBusy } from "./agents.js";
10
+ import { ApiError, invalid } from "./errors.js";
11
+ import { isJson, ownOrigin } from "./page.js";
12
+ import { isObject } from "./validate.js";
13
+ export const MCP_PATH = "/v2/mcp";
14
+ /** The protocol versions this endpoint speaks, newest first. `initialize` answers the client's when it is one of them,
15
+ * else the newest, as the protocol's negotiation says. */
16
+ export const PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
17
+ const MAX_BODY = 1 << 20;
18
+ /** The most a route's answer may hold here; a file is read up to MAX_TEXT. */
19
+ const MAX_ANSWER = 4 << 20;
20
+ /** The most of a file `runs_files` returns as text: a client's tool output is short (Claude Code's is about 25k tokens). */
21
+ export const MAX_TEXT = 64 << 10;
22
+ /** `runs_events`' page when the caller names no limit: small enough for a client's tool output. */
23
+ const EVENTS_LIMIT = 100;
24
+ /** An argument the tool cannot take: answered as the routes answer a body they refuse (422, by field). */
25
+ class ArgumentError extends Error {
26
+ field;
27
+ reason;
28
+ constructor(field, reason, message) {
29
+ super(message);
30
+ this.field = field;
31
+ this.reason = reason;
32
+ }
33
+ }
34
+ const text = (args, name) => {
35
+ const value = args[name];
36
+ if (typeof value !== "string" || !value)
37
+ throw new ArgumentError(name, value === undefined ? "missing" : "wrong_type", `${name} is a non-empty string`);
38
+ return value;
39
+ };
40
+ const optionalText = (args, name) => (args[name] === undefined ? undefined : text(args, name));
41
+ const id = encodeURIComponent;
42
+ const pick = (args, keys) => Object.fromEntries(keys.filter((k) => args[k] !== undefined).map((k) => [k, args[k]]));
43
+ const without = (args, keys) => Object.fromEntries(Object.entries(args).filter(([k]) => !keys.includes(k)));
44
+ const runLink = (origin, run) => `${origin}/#/runs/${id(run)}`;
45
+ /** A route's JSON answer as a tool's result: the body as structured content and, for a client without it, as text; a
46
+ * refusal (4xx, 5xx) as an error result holding the route's error envelope. `extra` is added to a body that is no
47
+ * refusal. */
48
+ function resultOf(answer, extra = {}) {
49
+ if (answer.tooBig)
50
+ return { content: [{ type: "text", text: `The answer is over ${MAX_ANSWER >> 20} MiB.` }], isError: true };
51
+ const refused = answer.status >= 400;
52
+ const parsed = answer.bytes.length ? JSON.parse(answer.bytes.toString("utf8")) : {};
53
+ const body = isObject(parsed) ? { ...parsed, ...(refused ? {} : extra) } : { value: parsed };
54
+ return { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body, ...(refused ? { isError: true } : {}) };
55
+ }
56
+ const json = (answer) => JSON.parse(answer.bytes.toString("utf8"));
57
+ /** A tool that is one route: its answer is the tool's. */
58
+ const routed = (build) => async (args, context) => resultOf(await context.call(build(args)));
59
+ const READ = { readOnlyHint: true, openWorldHint: false };
60
+ const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
61
+ const AGENT_ID = { type: "string", description: "The agent's id." };
62
+ const RUN_ID = { type: "string", description: "The run's id." };
63
+ const DEFINITION = {
64
+ instructions: { type: "string", description: "What the agent does and how: its system prompt." },
65
+ harness: { type: "string", enum: ["pi", "claude-agent", "codex"], description: "What runs it (default pi). whoami says which this server runs." },
66
+ model: { type: ["string", "null"], description: "provider/model-id. Absent, this server's default (whoami names it)." },
67
+ thinking: { type: ["string", "null"], description: "How hard the model thinks: one of whoami's thinking levels. Absent, the model's own." },
68
+ tools: { type: "array", items: { type: "string" }, description: "The tools it may use, by name (whoami lists them); [] for none. It writes files only with a tool like write." },
69
+ definition: { type: "object", description: "Optional: any other definition field, as POST /v2/agents takes it (place, say), which the route checks as it checks every field. A field named outright here wins over the same one inside definition." },
70
+ };
71
+ /** A tool's definition: `definition`'s fields, passed through as they are for the route's own checks (so a field the
72
+ * server takes later needs no change here), then the fields named outright over them. `skip` are the tool's own. */
73
+ function definitionOf(args, skip) {
74
+ const extra = args.definition;
75
+ if (extra !== undefined && !isObject(extra))
76
+ throw new ArgumentError("definition", "wrong_type", "definition is an object of definition fields");
77
+ return { ...(extra ?? {}), ...without(args, ["definition", ...skip]) };
78
+ }
79
+ /** Each tool, by the /v2 routes it calls. Field names are the routes'. */
80
+ export const TOOLS = [
81
+ {
82
+ name: "whoami", title: "Check the connection", annotations: READ,
83
+ description: "Checks the connection and the token, and says what this server runs: its version, its address and console, the harnesses, tools, efforts, thinking levels and default model it has (GET /v2/capabilities). Call it first.",
84
+ inputSchema: { type: "object", properties: {} },
85
+ run: async (_args, context) => {
86
+ const answer = await context.call({ method: "GET", path: "/capabilities" });
87
+ if (answer.status >= 400)
88
+ return resultOf(answer);
89
+ const caps = json(answer);
90
+ const me = {
91
+ authenticated: true, credential: "token", server: "agentrun-serve", version: context.version,
92
+ base_url: `${context.origin}/v2`, console_url: `${context.origin}/`,
93
+ harnesses: (caps.harnesses ?? []).filter((h) => h.available).map((h) => h.id),
94
+ tools: (caps.tools ?? []).filter((t) => t.available).map((t) => t.name),
95
+ efforts: caps.features?.efforts ?? [], thinking: caps.features?.thinking ?? [], models: caps.models ?? {},
96
+ };
97
+ return resultOf({ ...answer, bytes: Buffer.from(JSON.stringify(me)) });
98
+ },
99
+ },
100
+ {
101
+ name: "agents_list", title: "List agents", annotations: READ,
102
+ description: "The agents on this server, 20 at a time (GET /v2/agents): each one's id, name, kind, current definition and run counts. next_cursor, when not null, is the next page's cursor.",
103
+ inputSchema: { type: "object", properties: { cursor: { type: "string", description: "next_cursor from the page before." } } },
104
+ run: routed((args) => ({ method: "GET", path: "/agents", query: pick(args, ["cursor"]) })),
105
+ },
106
+ {
107
+ name: "agents_create", title: "Create an agent", annotations: WRITE,
108
+ description: "Creates an agent (POST /v2/agents with these fields, and any other in definition, as its definition), checked as that route checks it: a refusal names each field. Ask the person before you create one. warnings in the answer is what this server still lacks to run it.",
109
+ inputSchema: {
110
+ type: "object", required: ["name", "instructions"],
111
+ properties: {
112
+ id: { type: "string", description: "Optional: the agent's id (letters, digits, . _ -); absent, the server makes one." },
113
+ name: { type: "string", description: "The agent's name." },
114
+ description: { type: "string", description: "Optional: one line on what it is for." },
115
+ ...DEFINITION,
116
+ },
117
+ },
118
+ run: routed((args) => ({ method: "POST", path: "/agents", body: { definition: definitionOf(args, []) } })),
119
+ },
120
+ {
121
+ name: "agents_revise", title: "Revise an agent", annotations: WRITE,
122
+ description: "Makes the agent's next revision from its current definition with these fields changed, and any other field in definition (GET /v2/agents/{agent_id}, then PUT /v2/agents/{agent_id}/definition on that revision): fields you leave out stay; null clears model or thinking. Its next run runs the new revision. A revision saved in between is refused (precondition_failed), never overwritten. Its name and description stay as it was created.",
123
+ inputSchema: { type: "object", required: ["agent_id"], properties: { agent_id: AGENT_ID, ...DEFINITION, note: { type: "string", description: "Optional: what this revision changes." } } },
124
+ run: async (args, context) => {
125
+ const agent = text(args, "agent_id");
126
+ const read = await context.call({ method: "GET", path: `/agents/${id(agent)}` });
127
+ if (read.status >= 400)
128
+ return resultOf(read);
129
+ const { note } = args;
130
+ const changes = definitionOf(args, ["agent_id", "note"]);
131
+ const merged = { ...json(read).definition, ...changes };
132
+ // The revision's number is the server's to give, and new instructions make an agentic revision.
133
+ delete merged.version;
134
+ if ("instructions" in changes)
135
+ delete merged.workflow;
136
+ // null clears model or thinking (the server's default then); any other null goes to the route, which checks it.
137
+ for (const key of ["model", "thinking"])
138
+ if (merged[key] === null)
139
+ delete merged[key];
140
+ const etag = read.headers.etag;
141
+ return resultOf(await context.call({ method: "PUT", path: `/agents/${id(agent)}/definition`, body: { definition: merged, ...(note === undefined ? {} : { note }) }, headers: etag ? { "if-match": etag } : {} }));
142
+ },
143
+ },
144
+ {
145
+ name: "runs_start", title: "Start a run", annotations: { ...WRITE, openWorldHint: true },
146
+ description: "Starts a run of the agent's current revision, or of `revision` (POST /v2/agents/{agent_id}/runs), and answers at once with the run, queued. Then call runs_get until its status is completed, failed or cancelled, or input_required (answer with runs_respond). An agentic run's input is {content: \"the first message\"}; a workflow run's is what its workflow's input schema takes.",
147
+ inputSchema: {
148
+ type: "object", required: ["agent_id", "input"],
149
+ properties: {
150
+ agent_id: AGENT_ID,
151
+ input: { type: "object", description: "{content: string} for an agentic agent; the workflow's input for a workflow agent." },
152
+ effort: { type: "string", enum: ["low", "medium", "high"], description: "Optional: how hard the model works on this run. Absent, the revision's own." },
153
+ revision: { type: "string", description: "Optional: a revision id of this agent to run in place of the current one." },
154
+ },
155
+ },
156
+ run: routed((args) => ({ method: "POST", path: `/agents/${id(text(args, "agent_id"))}/runs`, body: without(args, ["agent_id"]) })),
157
+ },
158
+ {
159
+ name: "runs_get", title: "Get a run", annotations: READ,
160
+ description: "A run's status and outcome (GET /v2/runs/{run_id}), and console_url (added here), the run's page. pending is what it waits on, by kind: {kind: \"question\", question} while its status is input_required, else null. status is queued, working, input_required, completed, failed, cancelled or paused. A completed run's answer is result.final_answer (agentic) or result.output (workflow); a failed run's reason is error; cost.usd is null while unknown, never $0.",
161
+ inputSchema: { type: "object", required: ["run_id"], properties: { run_id: RUN_ID } },
162
+ run: async (args, context) => {
163
+ const run = text(args, "run_id");
164
+ const answer = await context.call({ method: "GET", path: `/runs/${id(run)}` });
165
+ if (answer.status >= 400)
166
+ return resultOf(answer);
167
+ return resultOf(answer, { console_url: runLink(context.origin, run) });
168
+ },
169
+ },
170
+ {
171
+ name: "runs_events", title: "Read a run's events", annotations: READ,
172
+ description: `A page of the run's timeline (GET /v2/runs/{run_id}/timeline): its messages, thinking, tool calls and answer, as rows. Start with after 0; each page's next_after is the next page's after, and has_more says whether one waits. A page with final true and has_more false is the run's last. At most limit rows a page (default ${EVENTS_LIMIT}).`,
173
+ inputSchema: {
174
+ type: "object", required: ["run_id"],
175
+ properties: {
176
+ run_id: RUN_ID,
177
+ after: { type: "integer", minimum: 0, description: "0, or next_after from the page before." },
178
+ limit: { type: "integer", minimum: 1, maximum: 500, description: `At most this many rows (default ${EVENTS_LIMIT}).` },
179
+ },
180
+ },
181
+ run: routed((args) => ({ method: "GET", path: `/runs/${id(text(args, "run_id"))}/timeline`, query: { limit: EVENTS_LIMIT, ...pick(args, ["after", "limit"]) } })),
182
+ },
183
+ {
184
+ name: "runs_files", title: "Read a run's files", annotations: READ,
185
+ description: `What the run wrote. Without path, the list (GET /v2/runs/{run_id}/files): each file's path, size and type. With a path, that file (GET /v2/runs/{run_id}/files/{path}): its text, up to ${MAX_TEXT >> 10} KiB (truncated says when it is cut), or for a binary file its type, size and url.`,
186
+ inputSchema: { type: "object", required: ["run_id"], properties: { run_id: RUN_ID, path: { type: "string", description: "Optional: a path from the list." } } },
187
+ run: async (args, context) => {
188
+ const run = text(args, "run_id");
189
+ const path = optionalText(args, "path");
190
+ if (path === undefined)
191
+ return resultOf(await context.call({ method: "GET", path: `/runs/${id(run)}/files` }));
192
+ const route = `/runs/${id(run)}/files/${path.split("/").map(id).join("/")}`;
193
+ const answer = await context.call({ method: "GET", path: route }, MAX_TEXT);
194
+ if (answer.status >= 400)
195
+ return resultOf(answer);
196
+ const type = (answer.headers["content-type"] ?? "application/octet-stream").split(";")[0].trim();
197
+ const size = Number(answer.headers["content-length"] ?? answer.bytes.length);
198
+ const url = `${context.origin}/v2${route}`;
199
+ const textual = type.startsWith("text/") || type === "application/json" || type === "application/x-ndjson";
200
+ const file = { run_id: run, path, content_type: type, size_bytes: size, url, truncated: textual && answer.tooBig, text: textual ? answer.bytes.toString("utf8") : null };
201
+ const shown = textual ? `${file.text}${file.truncated ? `\n\n[cut at ${MAX_TEXT >> 10} KiB of ${size} bytes: read the rest at ${url}]` : ""}` : `A ${type} file of ${size} bytes: download it from ${url} with the token.`;
202
+ return { content: [{ type: "text", text: shown }], structuredContent: file };
203
+ },
204
+ },
205
+ {
206
+ name: "runs_respond", title: "Answer a run", annotations: { ...WRITE, openWorldHint: true },
207
+ description: "Sends an agentic run a message (POST /v2/runs/{run_id}/messages): the answer to the question it asked (its status is input_required; runs_get's pending holds the question), or a follow-up once it completed or was stopped: a fresh turn with its history (a stopped turn is not replayed). mode in the answer says which. A cancelled run takes none: 409 not_continuable, start a new run. Then poll runs_get again.",
208
+ inputSchema: { type: "object", required: ["run_id", "content"], properties: { run_id: RUN_ID, content: { type: "string", description: "The answer, or the message." } } },
209
+ run: routed((args) => ({ method: "POST", path: `/runs/${id(text(args, "run_id"))}/messages`, body: without(args, ["run_id"]) })),
210
+ },
211
+ {
212
+ name: "runs_cancel", title: "Cancel a run", annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
213
+ description: "Ends a run for good (POST /v2/runs/{run_id}/cancel): its status turns cancelled once its process has exited. It keeps what it did, and takes no more messages: a message to it is 409 not_continuable, so go on in a new run (runs_start).",
214
+ inputSchema: { type: "object", required: ["run_id"], properties: { run_id: RUN_ID } },
215
+ run: routed((args) => ({ method: "POST", path: `/runs/${id(text(args, "run_id"))}/cancel` })),
216
+ },
217
+ ];
218
+ const INSTRUCTIONS = "Tools over this AgentRun server's agents and runs. Call whoami first. To run an agent: agents_list (or agents_create, after asking the person), then runs_start, then runs_get every few seconds until its status is completed, failed or cancelled. input_required means it asked a question (runs_get's pending, kind question): answer it with runs_respond, or leave it for the person in the console (console_url). Read its steps with runs_events and what it wrote with runs_files.";
219
+ /** A route's answer, captured: its status, headers and bytes up to `limit`. A route that writes past it is cut off
220
+ * there (`tooBig`): a file stream stops. */
221
+ class Answer extends Writable {
222
+ limit;
223
+ status = 200;
224
+ headers = {};
225
+ headersSent = false;
226
+ tooBig = false;
227
+ size = 0;
228
+ chunks = [];
229
+ settled;
230
+ constructor(limit) {
231
+ super();
232
+ this.limit = limit;
233
+ this.settled = new Promise((done) => (this.once("finish", done), this.once("close", done)));
234
+ // The cut-off is this stream's own error: whoever pipes into it sees it, and nothing else is told.
235
+ this.on("error", () => undefined);
236
+ }
237
+ writeHead(status, headers = {}) {
238
+ this.status = status;
239
+ this.headers = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), String(v)]));
240
+ this.headersSent = true;
241
+ return this;
242
+ }
243
+ _write(chunk, _encoding, next) {
244
+ const room = this.limit - this.size;
245
+ this.size += chunk.length;
246
+ if (chunk.length > room) {
247
+ this.chunks.push(chunk.subarray(0, Math.max(0, room)));
248
+ this.tooBig = true;
249
+ return next(new Error("over the answer limit"));
250
+ }
251
+ this.chunks.push(chunk);
252
+ next();
253
+ }
254
+ answered() {
255
+ return { status: this.status, headers: this.headers, bytes: Buffer.concat(this.chunks), tooBig: this.tooBig };
256
+ }
257
+ }
258
+ const rpcError = (id, code, message) => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
259
+ /** GET /llms.txt: what this server is, for a coding agent, without a credential. The text is the repository's
260
+ * `src/llms.txt`, copied beside the server by the build; it holds no data of this server's. */
261
+ export async function answerLlms(req, res) {
262
+ if (req.method !== "GET" && req.method !== "HEAD")
263
+ throw new ApiError("method_not_allowed", `${req.method} is not a method of /llms.txt`, {}, { allow: "GET, HEAD" });
264
+ const body = await readFile(new URL("./llms.txt", import.meta.url));
265
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "content-length": String(body.length), "cache-control": "no-cache", "x-content-type-options": "nosniff" });
266
+ res.end(req.method === "HEAD" ? undefined : body);
267
+ }
268
+ /** The endpoint: `route` serves each tool, `authorized` checks an Authorization header against the token. */
269
+ export function mcpEndpoint({ route, authorized, authFailed, version }) {
270
+ function reply(res, status, body, headers = {}) {
271
+ res.writeHead(status, { ...(body === undefined ? {} : { "content-type": "application/json" }), "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
272
+ res.end(body === undefined ? undefined : JSON.stringify(body));
273
+ }
274
+ /** A route's answer to `call`, made with the caller's own Authorization: a synthetic request into `route`, and a
275
+ * response that captures what it writes. A refusal is the route's error envelope, as it would have gone out. */
276
+ async function dispatch(call, authorization, requestId, limit = MAX_ANSWER) {
277
+ const search = new URLSearchParams(Object.entries(call.query ?? {}).map(([k, v]) => [k, String(v)]));
278
+ const target = `/v2${call.path}${search.size ? `?${search}` : ""}`;
279
+ const body = call.body === undefined ? [] : [Buffer.from(JSON.stringify(call.body))];
280
+ const headers = { authorization, accept: "application/json", ...(call.body === undefined ? {} : { "content-type": "application/json" }), ...call.headers };
281
+ const req = Object.assign(Readable.from(body), { method: call.method, url: target, headers });
282
+ const res = new Answer(limit);
283
+ try {
284
+ await route(req, res, new URL(target, "http://serve"), call.path);
285
+ if (!res.writableEnded && !res.destroyed)
286
+ throw new Error(`${call.method} ${target} gave no answer`);
287
+ await res.settled;
288
+ }
289
+ catch (error) {
290
+ const known = error instanceof ApiError ? error : storeBusy(error) ? homeBusy() : new ApiError("internal", error?.message ?? String(error));
291
+ if (!(error instanceof ApiError) && !storeBusy(error))
292
+ process.stderr.write(`agentrun-serve: mcp: ${error?.stack ?? String(error)}\n`);
293
+ return { status: known.status, headers: { "content-type": "application/json" }, bytes: Buffer.from(JSON.stringify(known.body(requestId))), tooBig: false };
294
+ }
295
+ return res.answered();
296
+ }
297
+ /** One JSON-RPC request's result, or its error. */
298
+ async function handle(method, params, req, requestId) {
299
+ switch (method) {
300
+ case "initialize": {
301
+ const asked = isObject(params) ? params.protocolVersion : undefined;
302
+ const protocolVersion = typeof asked === "string" && PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0];
303
+ return { result: { protocolVersion, capabilities: { tools: { listChanged: false } }, serverInfo: { name: "agentrun-serve", title: "AgentRun Server", version }, instructions: INSTRUCTIONS } };
304
+ }
305
+ case "ping":
306
+ return { result: {} };
307
+ case "tools/list":
308
+ return { result: { tools: TOOLS.map(({ run: _run, ...tool }) => tool) } };
309
+ case "tools/call": {
310
+ if (!isObject(params) || typeof params.name !== "string")
311
+ return { error: { code: -32602, message: "tools/call takes {name, arguments}" } };
312
+ const tool = TOOLS.find((t) => t.name === params.name);
313
+ if (!tool)
314
+ return { error: { code: -32602, message: `no tool ${params.name}: tools/list names them` } };
315
+ const authorization = String(req.headers.authorization);
316
+ const context = { call: (call, limit) => dispatch(call, authorization, requestId, limit), origin: ownOrigin(req), version, requestId };
317
+ try {
318
+ if (params.arguments !== undefined && !isObject(params.arguments))
319
+ throw new ArgumentError("arguments", "wrong_type", "arguments is an object");
320
+ return { result: await tool.run(params.arguments ?? {}, context) };
321
+ }
322
+ catch (error) {
323
+ // An argument the tool cannot take is the tool's error, as the protocol asks, in the routes' own 422 shape.
324
+ if (!(error instanceof ArgumentError))
325
+ throw error;
326
+ const body = invalid([{ field: error.field, reason: error.reason, message: error.message }]).body(requestId);
327
+ return { result: { content: [{ type: "text", text: JSON.stringify(body) }], structuredContent: body, isError: true } };
328
+ }
329
+ }
330
+ }
331
+ return { error: { code: -32601, message: `no method ${method} here: this server offers initialize, ping, tools/list and tools/call` } };
332
+ }
333
+ async function read(req) {
334
+ const chunks = [];
335
+ let size = 0;
336
+ for await (const chunk of req) {
337
+ size += chunk.length;
338
+ if (size <= MAX_BODY)
339
+ chunks.push(chunk);
340
+ }
341
+ return size > MAX_BODY ? null : Buffer.concat(chunks);
342
+ }
343
+ return async function answer(req, res) {
344
+ const requestId = String(res.getHeader("x-request-id") ?? "");
345
+ const origin = req.headers.origin;
346
+ if (origin !== undefined && origin.toLowerCase() !== ownOrigin(req))
347
+ return reply(res, 403, rpcError(null, -32600, "this Origin may not call this server's MCP endpoint"));
348
+ // The token only: the page's session cookie is not taken here (server.ts answers this path before the page).
349
+ const authorization = req.headers.authorization;
350
+ if (authorization === undefined || !authorized(authorization)) {
351
+ authFailed(MCP_PATH, authorization === undefined ? "no_credential" : "wrong_token");
352
+ return reply(res, 401, rpcError(null, -32001, "the MCP endpoint needs Authorization: Bearer <the token in the data directory>"), { "www-authenticate": "Bearer" });
353
+ }
354
+ if (req.method !== "POST")
355
+ return reply(res, 405, rpcError(null, -32600, "the MCP endpoint takes POST only: this server opens no stream and keeps no session"), { allow: "POST" });
356
+ const asked = req.headers["mcp-protocol-version"];
357
+ if (asked !== undefined && !PROTOCOL_VERSIONS.includes(String(asked)))
358
+ return reply(res, 400, rpcError(null, -32600, `MCP-Protocol-Version ${asked} is not one this server speaks (${PROTOCOL_VERSIONS.join(", ")})`));
359
+ if (!isJson(req))
360
+ return reply(res, 415, rpcError(null, -32600, "the body must be application/json"));
361
+ const raw = await read(req);
362
+ if (raw === null)
363
+ return reply(res, 413, rpcError(null, -32600, `the body is over ${MAX_BODY} bytes`));
364
+ let message;
365
+ try {
366
+ message = JSON.parse(raw.toString("utf8"));
367
+ }
368
+ catch {
369
+ return reply(res, 400, rpcError(null, -32700, "the body is not JSON"));
370
+ }
371
+ if (Array.isArray(message))
372
+ return reply(res, 400, rpcError(null, -32600, "a batch is not taken: send one message per request"));
373
+ if (!isObject(message) || message.jsonrpc !== "2.0")
374
+ return reply(res, 400, rpcError(null, -32600, "not a JSON-RPC 2.0 message"));
375
+ const rpcId = typeof message.id === "string" || typeof message.id === "number" ? message.id : null;
376
+ if (!("method" in message)) {
377
+ // A response to a request of ours (this server sends none): taken, with no body, when it is one.
378
+ if (!("id" in message) || ("result" in message) === ("error" in message))
379
+ return reply(res, 400, rpcError(rpcId, -32600, "not a JSON-RPC request, notification or response"));
380
+ return reply(res, 202);
381
+ }
382
+ if (typeof message.method !== "string")
383
+ return reply(res, 400, rpcError(rpcId, -32600, "method is a string"));
384
+ // A notification: taken, with no body.
385
+ if (!("id" in message))
386
+ return reply(res, 202);
387
+ if (rpcId === null)
388
+ return reply(res, 400, rpcError(null, -32600, "a request's id is a string or a number"));
389
+ const answered = await handle(message.method, message.params, req, requestId);
390
+ return reply(res, 200, { jsonrpc: "2.0", id: rpcId, ...answered });
391
+ };
392
+ }
@@ -0,0 +1,184 @@
1
+ import type { ModelCost, ModelThinkingLevel } from "@earendil-works/pi-ai";
2
+ /** The child's environment names the faux module by absolute path. */
3
+ export declare const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
4
+ /** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_HARNESS, AGENTRUN_SERVE_FAUX_WEB, ...). */
5
+ export declare const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
6
+ /** `env` without a test hook's name: serve sets those from startServe's options alone, so a name the server's own
7
+ * environment holds (an operator's export, a leftover) never gives its runs fake answers or loads a module. */
8
+ export declare const withoutFaux: (env: NodeJS.ProcessEnv) => NodeJS.ProcessEnv;
9
+ /** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
10
+ * tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
11
+ * request to the provider the revision's model names (web_search's, hosted-search.ts); the run's turns stay faux. */
12
+ export declare const FAUX_UPSTREAM_ENV = "AGENTRUN_SERVE_FAUX_UPSTREAM";
13
+ /** A run's `effort`, passed to its child. */
14
+ export declare const EFFORT_ENV = "AGENTRUN_SERVE_EFFORT";
15
+ /** The model the server's keys give a run that names none (hostModel at the run's launch, from every key the server
16
+ * holds), passed to its child as its effort is: behind a gateway the run holds the gateway's key alone, never the key
17
+ * that names its default (runs.ts). A model id, never a secret, so its name has no secret's segment (pi-durable-disk's
18
+ * secret-name rule): a harness's log keeps it (adapters.ts harnessLog). */
19
+ export declare const DEFAULT_MODEL_ENV = "AGENTRUN_SERVE_DEFAULT_MODEL";
20
+ export declare const MODEL_PROVIDER = "agent-model";
21
+ export declare const EFFORTS: readonly ["low", "medium", "high"];
22
+ export type Effort = (typeof EFFORTS)[number];
23
+ /** The thinking levels a revision or the host may name. Never off. */
24
+ export declare const THINKING_LEVELS: readonly ["low", "medium", "high", "xhigh", "max"];
25
+ export declare const TIERS: readonly ["fast", "default", "strong"];
26
+ export type Tier = (typeof TIERS)[number];
27
+ /** The workflow node kinds that run on a model. */
28
+ export declare const MODEL_NODES: readonly ["agent", "decide", "extract", "report"];
29
+ /** The model providers whose key a person may save here (tool-keys.ts' `model` rows), in the order a default is taken
30
+ * from, each with the model a run gets on its key when neither its revision nor the host names one: the provider's
31
+ * capable everyday model, not its dearest (Claude Sonnet 5.5 and GPT-6.1 Sol, each $2 in and $10 out per million
32
+ * tokens). `harnesses`: those that run on the key, pi on any model of it and the harness that is the provider's own;
33
+ * OpenRouter's runs all three. `models`: a harness's own default on the key where it is not `model`. On OpenRouter:
34
+ * pi's is GPT-6 Sol on pi-ai's openrouter provider (/chat/completions, the key as a bearer token, as OpenRouter's docs
35
+ * name it; its Anthropic models go to /v1/messages with the key in x-api-key, which the docs do not), claude-agent's
36
+ * Claude Sonnet 5.5 and codex's GPT-6 Sol, each through OpenRouter's own endpoint for the harness (adapters.ts), the ids
37
+ * a live run took through OpenRouter on 2026-10-29. The row order is the order a default is taken in: a direct
38
+ * provider's key wins over OpenRouter's. */
39
+ export declare const MODEL_KEYS: readonly [{
40
+ readonly id: "anthropic";
41
+ readonly label: "Anthropic";
42
+ readonly field: "ANTHROPIC_API_KEY";
43
+ readonly model: "anthropic/claude-sonnet-5-5";
44
+ readonly harnesses: readonly ["pi" | "claude-agent" | "codex", "claude-agent"];
45
+ }, {
46
+ readonly id: "openai";
47
+ readonly label: "OpenAI";
48
+ readonly field: "OPENAI_API_KEY";
49
+ readonly model: "openai/gpt-6.1-sol";
50
+ readonly harnesses: readonly ["pi" | "claude-agent" | "codex", "codex"];
51
+ }, {
52
+ readonly id: "openrouter";
53
+ readonly label: "OpenRouter";
54
+ readonly field: "OPENROUTER_API_KEY";
55
+ readonly model: "openrouter/openai/gpt-6-sol";
56
+ readonly harnesses: readonly ["pi" | "claude-agent" | "codex", "claude-agent", "codex"];
57
+ readonly models: {
58
+ readonly "claude-agent": "anthropic/claude-sonnet-5.5";
59
+ readonly codex: "openai/gpt-6-sol";
60
+ };
61
+ }];
62
+ /**
63
+ * Whether `harness` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
64
+ * harness's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names
65
+ * (ANTHROPIC_BASE_URL for claude-agent, which needs ANTHROPIC_API_KEY; serve's gateway AGENT_MODEL_BASE_URL for codex,
66
+ * with AGENT_MODEL_API_KEY or none), then the vendor's own key (ANTHROPIC_API_KEY, OPENAI_API_KEY), then OpenRouter. An
67
+ * endpoint the host names never gets the OpenRouter key.
68
+ */
69
+ export declare function openRouterOnly(harness: "claude-agent" | "codex", env: NodeJS.ProcessEnv): boolean;
70
+ /** Whether `harness`'s model requests for `model` (as named, `provider/model-id`; none, the host's for the harness) go
71
+ * through OpenRouter: a model named on it (`openrouter/<vendor>/...`), or the harness's vendor reached only through it
72
+ * (openRouterOnly). The route claudeProvider and codexProvider take (adapters.ts); a gateway (AGENT_MODEL_BASE_URL)
73
+ * comes first for codex. On it a harness's own search does not run: OpenRouter runs no OpenAI hosted web_search for
74
+ * Codex and no Anthropic server search for Claude, and its answers carry no count of searches to price. */
75
+ export declare function viaOpenRouter(env: NodeJS.ProcessEnv, harness: string, model?: string): boolean;
76
+ /** What a person does when no model runs here: add a model provider's key in the console, or set one where AgentRun
77
+ * starts (MODEL_KEYS' fields), OpenRouter's named first, as its one key runs every harness. The order a default is
78
+ * taken in is MODEL_KEYS' own. */
79
+ export declare const ADD_A_KEY: string;
80
+ /** Whether `harness` runs the model `id`: pi any; claude-agent an Anthropic model (`anthropic/...`, or Anthropic's on
81
+ * OpenRouter, `openrouter/anthropic/...`), as it talks to an Anthropic Messages endpoint only; codex, behind a gateway
82
+ * (AGENT_MODEL_BASE_URL), any id, which is the gateway's own string and names no provider here (team/model included),
83
+ * as codex takes that gateway for its OpenAI-compatible endpoint; without one, an OpenAI model (`openai/...`, or OpenAI's
84
+ * on OpenRouter). On the faux harness every harness runs the run's model. */
85
+ export declare function harnessRuns(env: NodeJS.ProcessEnv, id: string, harness: string): boolean;
86
+ /** The model a revision that names none runs on with `harness`, for `tier`: the tier's own variable, else AGENT_MODEL,
87
+ * each only when `harness` runs it (harnessRuns; one it can't is skipped, never an error), else that of the first of
88
+ * MODEL_KEYS whose key is here (a placeholder behind a base URL counts) and that `harness` runs on, else, in a run's
89
+ * process that holds none of those keys, the one the server's keys gave it (DEFAULT_MODEL_ENV). Undefined when none is:
90
+ * the harness has no default here. */
91
+ export declare function hostModel(env: NodeJS.ProcessEnv, tier?: Tier, harness?: string): string | undefined;
92
+ /** `route_prefix`: the routing prefix this server puts before a gateway's model ids (MODEL_PROVIDER), which a reader takes off
93
+ * to show the gateway's own id; null with any other source. */
94
+ /** The values `models.source` takes here: a faux module, a gateway, or each provider with its own key. */
95
+ export declare const MODEL_SOURCES: readonly ["faux", "gateway", "providers"];
96
+ export type ModelSource = {
97
+ source: (typeof MODEL_SOURCES)[number];
98
+ route_prefix: string | null;
99
+ } & Record<Tier, string | null>;
100
+ /** What capabilities say about models here: where they come from, and the model of each tier (`default` is also what a
101
+ * revision that names none runs on). */
102
+ export declare function modelSource(env: NodeJS.ProcessEnv): ModelSource;
103
+ /** A workflow's nodes as the DSL's inspection lists them, each read from the document at its path: only what the
104
+ * workflow's structure makes a node, never data shaped like one (a node's `state` may hold an example node). */
105
+ export declare function workflowNodes(workflow: unknown, inspection: {
106
+ nodes: readonly {
107
+ path: string;
108
+ }[];
109
+ }): Record<string, unknown>[];
110
+ /** The tiers a workflow's model nodes name (`nodes` from workflowNodes); a node that names none is `default`. */
111
+ export declare function nodeTiers(nodes: readonly Record<string, unknown>[]): Tier[];
112
+ /** `tiers` with those a workflow's `llm` calls name (`args.tier`, else default) added: an `llm` call completes on the
113
+ * model of its tier, as a model node does. A tier the state fills in when the call runs (`"{requestedTier}"`, or args
114
+ * filled in whole) may be any of the three, so it adds all three. */
115
+ export declare function llmTiers(nodes: readonly Record<string, unknown>[], tiers: readonly Tier[]): Tier[];
116
+ export type ModelRef = {
117
+ provider: string;
118
+ modelId: string;
119
+ };
120
+ /** What a run that cannot have its model here needs: a provider's key, or another model. */
121
+ export type ModelNeeds = "key" | "model";
122
+ /**
123
+ * The model a revision runs on here, or why it cannot: `ref` is an agentic revision's "provider/model-id", absent for
124
+ * the host's model of `tier`. Through the gateway the ref goes whole, as a gateway such as OpenRouter names its models
125
+ * `vendor/model` (with `AGENT_MODEL_GATEWAY_IDS=bare`, only the part after the provider), and `namedProvider` is that
126
+ * provider, whose catalog entry prices the model. `host` says a setting of this host (a key, a default model) could
127
+ * make it reachable; a model the revision names that pi-ai does not know is not. `needs`: what would: a provider's key
128
+ * (none names a model, or the model's provider has no key here), or another model. `harness` picks the host's model
129
+ * when `ref` is absent (hostModel).
130
+ */
131
+ export declare function chooseModel(env: NodeJS.ProcessEnv, ref: string | undefined, tier?: Tier, harness?: string): Promise<{
132
+ model: ModelRef;
133
+ namedProvider?: string;
134
+ } | {
135
+ why: string;
136
+ host: boolean;
137
+ needs: ModelNeeds;
138
+ }>;
139
+ /**
140
+ * The keys each of pi-ai's providers reads, by its id: pi-ai's own table (env-api-keys' findEnvKeys), and Amazon
141
+ * Bedrock's AWS keys, which that table leaves out as ambient. Every one is on the launcher's list (secrets.ts'
142
+ * SECRET_NAMES), so the server holds it and no environment does, and a run's process is handed a provider's keys over
143
+ * its pipe only when a model it runs is that provider's (runs.ts' secretsFor), as its model's provider reads them from
144
+ * the run's auth context. The custody test checks this against the pi-ai installed, so one that reads another key fails
145
+ * there.
146
+ */
147
+ export declare const PROVIDER_KEYS: Readonly<Record<string, readonly string[]>>;
148
+ /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
149
+ export declare const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
150
+ /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
151
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
152
+ * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
153
+ * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
154
+ export declare function modelKeys(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[]): string[];
155
+ /** A run's thinking level: its `effort`, else its revision's `thinking`, else the host's `AGENT_THINKING`, else medium.
156
+ * Never off. */
157
+ export declare function thinkingOf(env: NodeJS.ProcessEnv, revision?: string): ModelThinkingLevel;
158
+ /** The helpers a faux module's reply gets, so it needs no import of its own. */
159
+ export type FauxHelpers = {
160
+ /** Aborted when the turn is stopped: a slow reply resolves with `message("", { stopReason: "aborted" })`. */
161
+ signal?: AbortSignal;
162
+ /** The model the request names (`faux-1`, or the id a tier's variable names). */
163
+ model?: string;
164
+ message: typeof import("@earendil-works/pi-ai").fauxAssistantMessage;
165
+ text: typeof import("@earendil-works/pi-ai").fauxText;
166
+ thinking: typeof import("@earendil-works/pi-ai").fauxThinking;
167
+ toolCall: typeof import("@earendil-works/pi-ai").fauxToolCall;
168
+ };
169
+ /** The models for a run, and its model of each tier it uses and of no other: an agentic revision's `ref` (or the
170
+ * default) is its `default`, and a workflow's tiers are the ones its nodes name. The faux module's replies, the gateway
171
+ * in the environment, or pi-ai's providers. `unpriced`: the ids of its models serve has no price for (a gateway model the
172
+ * catalog does not list, with no price set), which a cap cannot be kept on. */
173
+ export declare function runModels(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[], harness?: string): Promise<{
174
+ models: import("@earendil-works/pi-ai").MutableModels;
175
+ model: ModelRef | undefined;
176
+ byTier: Map<"default" | "fast" | "strong", ModelRef>;
177
+ unpriced: Set<string>;
178
+ }>;
179
+ export type Listed = {
180
+ provider: string;
181
+ cost: ModelCost;
182
+ };
183
+ /** pi-ai's catalog list prices by model id: every provider's entry for it, in the catalog's order. */
184
+ export declare function catalogPrices(): Promise<Map<string, Listed[]>>;