@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.31

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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +182 -26
  3. package/dist/agents.d.ts +8 -3
  4. package/dist/agents.js +4 -1
  5. package/dist/app.js +23 -8
  6. package/dist/background.d.ts +2 -1
  7. package/dist/background.js +41 -20
  8. package/dist/box-egress-vm.d.ts +125 -0
  9. package/dist/box-egress-vm.js +350 -0
  10. package/dist/box-egress.d.ts +3 -2
  11. package/dist/box-relay-vm.d.ts +4 -0
  12. package/dist/box-relay-vm.js +76 -55
  13. package/dist/boxes.d.ts +7 -2
  14. package/dist/boxes.js +30 -11
  15. package/dist/cap.d.ts +2 -1
  16. package/dist/cap.js +2 -1
  17. package/dist/cli.js +30 -4
  18. package/dist/console/assets/{index-34jfpIbQ.js → index-CnJBf7Lc.js} +90 -85
  19. package/dist/console/index.html +1 -1
  20. package/dist/decisions.d.ts +3 -3
  21. package/dist/decisions.js +4 -3
  22. package/dist/files.d.ts +3 -0
  23. package/dist/files.js +3 -0
  24. package/dist/grade.d.ts +5 -2
  25. package/dist/grade.js +13 -5
  26. package/dist/harness-app.js +10 -1
  27. package/dist/host-check.d.ts +12 -0
  28. package/dist/host-check.js +34 -0
  29. package/dist/key-words.d.ts +37 -0
  30. package/dist/key-words.js +40 -0
  31. package/dist/learn/grade.d.ts +3 -0
  32. package/dist/learn/grade.js +3 -1
  33. package/dist/learn/index.d.ts +1 -1
  34. package/dist/learn/index.js +1 -1
  35. package/dist/learn/reflect.js +2 -0
  36. package/dist/learn/skills.d.ts +2 -0
  37. package/dist/learn/skills.js +16 -0
  38. package/dist/learning-routes.d.ts +30 -1
  39. package/dist/learning-routes.js +173 -19
  40. package/dist/learning-run.d.ts +1 -1
  41. package/dist/learning-run.js +25 -4
  42. package/dist/learning-words.d.ts +7 -3
  43. package/dist/learning-words.js +26 -8
  44. package/dist/learning.d.ts +9 -1
  45. package/dist/learning.js +57 -2
  46. package/dist/mcp-gateway.d.ts +96 -0
  47. package/dist/mcp-gateway.js +408 -0
  48. package/dist/mcp-meta.d.ts +17 -0
  49. package/dist/mcp-meta.js +38 -0
  50. package/dist/mcp-servers.d.ts +26 -5
  51. package/dist/mcp-servers.js +53 -10
  52. package/dist/openapi.js +52 -9
  53. package/dist/page.d.ts +2 -0
  54. package/dist/page.js +3 -0
  55. package/dist/place.d.ts +3 -2
  56. package/dist/place.js +11 -3
  57. package/dist/print.d.ts +7 -0
  58. package/dist/print.js +13 -0
  59. package/dist/run-box.js +15 -5
  60. package/dist/runnable.d.ts +8 -1
  61. package/dist/runnable.js +51 -2
  62. package/dist/runs.d.ts +15 -8
  63. package/dist/runs.js +66 -13
  64. package/dist/secrets.d.ts +15 -0
  65. package/dist/secrets.js +20 -2
  66. package/dist/server.d.ts +10 -1
  67. package/dist/server.js +111 -29
  68. package/dist/tool-gate.d.ts +18 -3
  69. package/dist/tool-gate.js +44 -13
  70. package/dist/tool-keys.d.ts +2 -1
  71. package/dist/tool-keys.js +4 -8
  72. package/dist/tool-plane.d.ts +5 -1
  73. package/dist/tool-plane.js +30 -6
  74. package/dist/tools.js +8 -5
  75. package/dist/web-fetch.js +3 -3
  76. package/package.json +12 -16
@@ -10,6 +10,7 @@ import { join } from "node:path";
10
10
  import { seal, unseal } from "@parcha/pi-durable-agent";
11
11
  import { ApiError, invalid } from "./errors.js";
12
12
  import { writeDurableSync } from "./files.js";
13
+ import { metaToolOf } from "./mcp-meta.js";
13
14
  import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
14
15
  import { isObject, unknownFields } from "./validate.js";
15
16
  export const MCP_SERVERS_FILE = "mcp-servers.json";
@@ -67,12 +68,12 @@ export class McpServers {
67
68
  throw invalid(issues);
68
69
  const name = String(body.name);
69
70
  const kept = this.need(name);
70
- return listServer(new URL(kept.url), this.opened(name, kept, "name"), this.version, stop);
71
+ return marked(kept.url, await listServer(new URL(kept.url), this.opened(name, kept, "name"), this.version, stop));
71
72
  }
72
73
  const { url, auth } = this.admit(body);
73
74
  if (auth.type !== "none" && !auth.headers)
74
75
  throw invalid([credentialMissing(auth.type, "A preview needs the credential it is to connect with.")]);
75
- return listServer(url, auth.headers ?? {}, this.version, stop);
76
+ return marked(url.href, await listServer(url, auth.headers ?? {}, this.version, stop));
76
77
  }
77
78
  /** PUT: preview, then keep the server with the tools listed. A body with no credential keeps the sealed one, while
78
79
  * the auth type and the URL's origin stay the same. */
@@ -81,7 +82,7 @@ export class McpServers {
81
82
  throw invalid([{ field: "name", reason: "invalid", message: "A server's name is 1 to 32 lowercase letters, digits and dashes, starting with a letter (no underscores, so mcp__<server>__<tool> splits one way)." }]);
82
83
  if (RESERVED_MCP_NAMES.includes(name))
83
84
  throw invalid([{ field: "name", reason: "reserved", message: `'${name}' is reserved for AgentRun's own tools: a server under it would take their names and their permissions. Name the server another way.` }]);
84
- const { url, auth } = this.admit(body);
85
+ const { url, auth, prices } = this.admit(body, true);
85
86
  if (auth.type !== "none" && !this.key)
86
87
  throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so it keeps no MCP server credential: it never keeps one in the clear.`);
87
88
  const was = this.servers()[name];
@@ -94,10 +95,14 @@ export class McpServers {
94
95
  headers = this.opened(name, was, auth.type === "bearer" ? "auth.token" : "auth.headers");
95
96
  }
96
97
  const listed = await listServer(url, headers ?? {}, this.version, stop);
98
+ // A price names a tool the server listed now, or nothing is saved.
99
+ const unlisted = Object.keys(prices ?? {}).filter((tool) => !listed.tools.some((listedTool) => listedTool.name === tool));
100
+ if (unlisted.length)
101
+ throw invalid(unlisted.map((tool) => ({ field: `prices.${tool}`, reason: "not_an_option", message: `The server ${name} lists no tool ${tool}; its tools are ${listed.tools.map((t) => t.name).join(", ") || "none"}.` })));
97
102
  const now = new Date().toISOString();
98
103
  const sealed = headers && Object.fromEntries(Object.entries(headers).map(([header, value]) => [header, seal(this.key, Buffer.from(value, "utf8"), aad(name, header)).toString("base64")]));
99
104
  const servers = this.servers();
100
- servers[name] = { url: url.href, auth: { type: auth.type, ...(sealed ? { sealed, check: this.sealCheck } : {}) }, ...listed, listed_at: now, updated_at: now };
105
+ servers[name] = { url: url.href, auth: { type: auth.type, ...(sealed ? { sealed, check: this.sealCheck } : {}) }, ...listed, ...(prices && Object.keys(prices).length ? { prices } : {}), listed_at: now, updated_at: now };
101
106
  this.write(servers);
102
107
  return this.view(name, servers[name]);
103
108
  }
@@ -114,7 +119,14 @@ export class McpServers {
114
119
  throw new ApiError("unavailable", `The server ${name} was changed while its tools were listed: refresh it again.`);
115
120
  const before = new Map(now.tools.map((tool) => [tool.name, canonical(tool)]));
116
121
  const after = new Map(listed.tools.map((tool) => [tool.name, canonical(tool)]));
117
- servers[name] = { ...now, ...listed, listed_at: new Date().toISOString() };
122
+ const next = { ...now, ...listed, listed_at: new Date().toISOString() };
123
+ // A price of a tool the server no longer lists goes with it.
124
+ const prices = Object.entries(now.prices ?? {}).filter(([tool]) => after.has(tool));
125
+ if (prices.length)
126
+ next.prices = Object.fromEntries(prices);
127
+ else
128
+ delete next.prices;
129
+ servers[name] = next;
118
130
  this.write(servers);
119
131
  return {
120
132
  added: [...after.keys()].filter((tool) => !before.has(tool)),
@@ -123,6 +135,15 @@ export class McpServers {
123
135
  server: this.view(name, servers[name]),
124
136
  };
125
137
  }
138
+ /** The saved server's credential, opened, for a run's launch: its headers; undefined when it has none, or none that opens. */
139
+ headers(name) {
140
+ const servers = this.kept();
141
+ const kept = servers === "unreadable" || !Object.hasOwn(servers, name) ? undefined : servers[name];
142
+ if (!kept || kept.auth.type === "none")
143
+ return undefined;
144
+ const opened = this.open(name, kept);
145
+ return "headers" in opened ? opened.headers : undefined;
146
+ }
126
147
  remove(name) {
127
148
  const servers = this.servers();
128
149
  if (!servers[name])
@@ -141,7 +162,7 @@ export class McpServers {
141
162
  const opened = auth.type === "none" ? null : this.open(name, kept);
142
163
  return {
143
164
  name,
144
- ...rest,
165
+ ...marked(kept.url, rest),
145
166
  auth: { type: auth.type, ...(auth.type === "headers" ? { headers: Object.keys(auth.sealed ?? {}) } : {}) },
146
167
  credential: opened === null ? null : "headers" in opened ? "sealed" : opened.unreadable,
147
168
  };
@@ -169,14 +190,15 @@ export class McpServers {
169
190
  throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so the saved credential of ${name} does not open.`);
170
191
  throw invalid([{ field, reason: "missing", message: `The saved credential of ${name} does not open here (sealed under another seal key, or damaged): send it again.` }]);
171
192
  }
172
- /** A body's URL and auth, or 422. */
173
- admit(body) {
174
- const issues = unknownFields(body, ["url", "auth"]);
193
+ /** A body's URL, auth and prices, or 422. */
194
+ admit(body, priced = false) {
195
+ const issues = unknownFields(body, priced ? ["url", "auth", "prices"] : ["url", "auth"]);
175
196
  const url = urlOf(body.url, issues);
176
197
  const auth = authOf(body.auth, issues);
198
+ const prices = pricesOf(body.prices, issues);
177
199
  if (issues.length)
178
200
  throw invalid(issues);
179
- return { url: url, auth: auth };
201
+ return { url: url, auth: auth, ...(prices ? { prices } : {}) };
180
202
  }
181
203
  /** The saved servers: none with no file, "unreadable" when the file does not read as this format. */
182
204
  kept() {
@@ -199,6 +221,14 @@ export class McpServers {
199
221
  writeDurableSync(this.file, `${JSON.stringify({ format: FORMAT, servers }, null, 2)}\n`);
200
222
  }
201
223
  }
224
+ /** `listed` with each known meta tool (mcp-meta.ts) marked `grantable: false` with its reason: the snapshot keeps what
225
+ * the server listed, and every read says which of its tools can't be granted. */
226
+ function marked(url, listed) {
227
+ return { ...listed, tools: listed.tools.map((tool) => {
228
+ const meta = metaToolOf(url, tool.name);
229
+ return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
230
+ }) };
231
+ }
202
232
  const aad = (name, header) => `mcp:${name}:${header}`;
203
233
  /** `text` with every credential value cut out: each header's value, and a bearer's token alone, which a server may
204
234
  * echo without its scheme. */
@@ -209,6 +239,19 @@ const credentialMissing = (type, message) => ({ field: type === "bearer" ? "auth
209
239
  const canonical = (value) => Array.isArray(value) ? `[${value.map(canonical).join(",")}]`
210
240
  : isObject(value) ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`
211
241
  : JSON.stringify(value) ?? "null";
242
+ /** The body's prices: each tool's USD a call, a finite number, 0 or more. Which tools the server lists is checked once
243
+ * it has listed them. */
244
+ function pricesOf(value, issues) {
245
+ if (value === undefined)
246
+ return undefined;
247
+ if (!isObject(value))
248
+ return void issues.push({ field: "prices", reason: "wrong_type", message: "prices is an object of the server's tool names to their price in USD a call." });
249
+ const bad = Object.entries(value).filter(([, usd]) => typeof usd !== "number" || !Number.isFinite(usd) || usd < 0);
250
+ for (const [tool] of bad)
251
+ issues.push({ field: `prices.${tool}`, reason: "invalid", message: `prices.${tool} is a price in USD a call: a finite number, 0 or more.` });
252
+ // Keyed by tool names, which may be an object's own properties (`__proto__`): no prototype to fall into.
253
+ return bad.length ? undefined : Object.assign(Object.create(null), value);
254
+ }
212
255
  function urlOf(value, issues) {
213
256
  if (typeof value !== "string" || value === "")
214
257
  return void issues.push({ field: "url", reason: value === undefined ? "missing" : "wrong_type", message: "url is the MCP server's Streamable HTTP endpoint, as text." });
package/dist/openapi.js CHANGED
@@ -199,6 +199,8 @@ const MCP_TOOL = {
199
199
  input_schema: { type: "object", description: "The JSON Schema of the tool's arguments, as the server gave it." },
200
200
  output_schema: { type: "object", description: "The JSON Schema of its structured result, when the server gives one." },
201
201
  annotations: { type: "object", description: "The server's own claims about the tool (read-only, destructive, and so on): the server's word, not checked." },
202
+ grantable: { const: false, description: "Present, and false, on a known meta tool: one that runs other actions by name (Composio's COMPOSIO_MULTI_EXECUTE_TOOL, Klavis Strata's execute_action, Zapier's execute actions, Arcade's UseTool, Docker's mcp-exec, Cloudflare's portal_execute and code mode). A grant of it could not name the real action, so none is granted: a save that grants it is 422 with `reason`, and a run that pinned one is refused at its launch. Absent on every other tool.", "x-agentrun-serve": "mcpservers/1" },
203
+ reason: { type: "string", description: "Beside `grantable: false`: why the tool can't be granted.", "x-agentrun-serve": "mcpservers/1" },
202
204
  },
203
205
  };
204
206
  const MCP_LISTING = {
@@ -208,6 +210,11 @@ const MCP_LISTING = {
208
210
  tools: { type: "array", items: MCP_TOOL, description: "Every tool it lists, all pages." },
209
211
  };
210
212
  const MCP_PREVIEW = { type: "object", additionalProperties: false, required: ["protocol", "server_info", "tools"], properties: MCP_LISTING };
213
+ /** The owner's declared prices of a server's tools. */
214
+ const MCP_PRICES = {
215
+ type: "object", additionalProperties: { type: "number", minimum: 0 },
216
+ description: "Each tool's price in USD a call, as the owner declared it, for tools the server lists (a refresh drops the price of a tool it no longer lists). A priced call is held at its price under a run's cap (refused unsent when the cap cannot take it) and booked as the run's tool cost, as any paid call; a tool with none runs, shown \"not metered\" on the run's timeline and in GET /usage, outside the run's cost and its cap. A run keeps the prices its first launch saw.",
217
+ };
211
218
  const MCP_SERVER_VIEW = {
212
219
  type: "object", additionalProperties: false, required: ["name", "url", "auth", "credential", "protocol", "server_info", "tools", "listed_at", "updated_at"],
213
220
  properties: {
@@ -215,6 +222,7 @@ const MCP_SERVER_VIEW = {
215
222
  auth: { type: "object", additionalProperties: false, required: ["type"], properties: { type: { enum: [...MCP_AUTH_TYPES] }, headers: { type: "array", items: { type: "string" }, description: "For `headers`: the names of the headers kept (lowercase), never a value." } } },
216
223
  credential: { enum: ["sealed", "seal_key_missing", "unreadable", null], description: "`sealed`: kept sealed and opens here; `seal_key_missing`: the server was handed no seal key, so it does not open; `unreadable`: sealed under another seal key, or damaged: a PUT with the credential seals it again. Null for `auth.type` none. Never a value." },
217
224
  ...MCP_LISTING,
225
+ prices: MCP_PRICES,
218
226
  listed_at: { type: "string", format: "date-time", description: "When its tools were last listed (a PUT or a refresh)." },
219
227
  updated_at: { type: "string", format: "date-time", description: "When it was last saved." },
220
228
  },
@@ -342,7 +350,7 @@ const LEARNING_REASON = {
342
350
  const NULL_STRING = { type: ["string", "null"] };
343
351
  const MARK = { "x-agentrun-serve": "learning/1" };
344
352
  const PAGE = (item, description) => closed({ items: { type: "array", items: item }, total: { ...COUNT, description: "How many there are in all, at the commit the page was read at." }, next_cursor: { ...NULL_STRING, description: "The next page, read at the same commit of main as this one: opaque. Null on the last." } }, description);
345
- const LEARNING_NOTE = closed({
353
+ const LEARNING_NOTE_REQUIRED = closed({
346
354
  file: { type: "string", description: "The note's file name, `<slug>.md`, at the folder's top; `[redacted]` when it holds one of the host's secrets as they are now (its route still answers the real name)." },
347
355
  name: { type: "string" }, description: { type: "string" }, type: { enum: [...NOTE_TYPES] },
348
356
  status: { enum: [...NOTE_STATUSES], description: "Absent from the note's front matter: active. Only an active note is in MEMORY.md. `pending`: a rule the grader held as risky, the user's or the run's own, to wait for its owner's OK; no run reads it." },
@@ -351,6 +359,18 @@ const LEARNING_NOTE = closed({
351
359
  text: { type: "string", description: "The note's whole file, front matter included." },
352
360
  etag: { type: "string", description: "The note's version on main, the same ETag as `GET .../learning/files/{file}` answers: send it as `If-Match` to edit or retire the version shown, and a 412 means it changed since.", "x-agentrun-serve": "learning/2" },
353
361
  });
362
+ /** When a retired note, skill or draft was retired, and by whom: on a retired one alone. */
363
+ const RETIRED = closed({
364
+ at: { type: "string", format: "date-time", description: "When: the commit that retired it." },
365
+ by: { enum: ["person", "run"], description: "`person`: its owner, in the console or with POST .../retire (the time of that retire; an edit since moves it not); `run`: anything else that set it." },
366
+ }, "When and by whom it was retired; absent unless `status` is `retired`. POST .../restore makes it active again.");
367
+ /** The newest change to a note, skill or draft, from the newest commit on its file. */
368
+ const LAST_CHANGE = closed({
369
+ kind: { enum: ["approved", "edited", "created", "retired", "restored", "learned"], description: "What the change was: a person's approval, edit, creation, retire or restore (named by its commit), or `learned`, a run's merge." },
370
+ by: { enum: ["person", "run"], description: "`person`: its owner, in the console or through the API; `run`: a run's merge." },
371
+ at: { type: "string", format: "date-time", description: "When: the commit's time." },
372
+ }, "The item's last change: the newest commit on its file (a note's file, a skill's SKILL.md, a draft's README.md), a person's (named by its subject's fixed prefix, `learning: <kind> by a person: `) or a run's merge (its Run-Id: `learned`). Absent when that commit is neither (the folder's own first commit, or one made outside the server).");
373
+ const LEARNING_NOTE = { ...LEARNING_NOTE_REQUIRED, properties: { ...LEARNING_NOTE_REQUIRED.properties, retired: RETIRED, last_change: LAST_CHANGE } };
354
374
  const LEARNING_CHANGE = closed({
355
375
  by: { oneOf: [closed({ run: { type: "string" } }), { type: "object", additionalProperties: false, required: ["user"], properties: { user: { type: "boolean", const: true }, via: { type: "string", description: "On an approval: how it came, `console` (the owner's signed-in page)." } } }], description: "A run's merge (its commit's `Run-Id` trailer), or a person's edit, creation, retirement or approval through this API (`Changed-By: user`, and `Approved-Via` on an approval)." },
356
376
  commit: { type: "string" }, at: { type: "string", format: "date-time" },
@@ -383,6 +403,8 @@ const LEARNED_ITEM = (kind) => ({
383
403
  run: { ...NULL_STRING, description: "The run whose merge last changed it; null when no merge names one." },
384
404
  bytes: { ...COUNT, description: `The size of its ${kind === "skill" ? "SKILL.md" : "workflow.json"} on main.` },
385
405
  etag: { type: "string", description: `The version of its ${kind === "skill" ? "SKILL.md" : "README.md"} on main, as its file's GET answers it: an approval sends it as If-Match.` },
406
+ retired: RETIRED,
407
+ last_change: LAST_CHANGE,
386
408
  },
387
409
  "x-agentrun-serve": "learning/3",
388
410
  });
@@ -636,6 +658,15 @@ const LEARNING_EXTENSIONS = {
636
658
  parameters: [AGENT_ID, NOTE_PARAM, IF_MATCH], responses: { "200": NOTE_TEXT("The note, approved."), ...WRITE_ERRORS, ...errors(403) }, ...MARK,
637
659
  },
638
660
  },
661
+ "/agents/{agent_id}/learning/files/{file}/restore": {
662
+ post: {
663
+ operationId: "restoreLearningFile", tags: ["agents"], summary: "Restore a retired note, skill or workflow draft: active again for the next run",
664
+ description: "A retired note is made active, a skill (its SKILL.md) or a workflow draft (its README.md) is given to every later run again, in one commit on main (`learning: restored by a person: <file>`, Changed-By: user) with MEMORY.md rebuilt. The text is checked again as a new note or skill is (a secret's shape, the host's own values, a hidden character, its format), so a value a retire took out of every run never comes back: such a note stays retired, and the answer names the rule, never the value. Only a retired one is restored (else 400). The owner's password session alone, as an approval.",
665
+ security: [{ ownerSession: [] }],
666
+ requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, maxProperties: 0 } } } },
667
+ parameters: [AGENT_ID, NOTE_PARAM, IF_MATCH], responses: { "200": NOTE_TEXT("The note, restored."), ...WRITE_ERRORS, ...errors(403) }, ...MARK,
668
+ },
669
+ },
639
670
  "/runs/{run_id}/learning": {
640
671
  get: {
641
672
  operationId: "getRunLearning", tags: ["runs"], summary: "The run's learning whole: its seed, merge, verdict, problems and cost",
@@ -909,9 +940,9 @@ const EXTENSIONS = {
909
940
  },
910
941
  put: {
911
942
  operationId: "saveMcpServer", tags: ["local"], summary: "Preview a remote MCP server, then save it with the tools listed and its credential sealed",
912
- description: `Each credential header's value is sealed under the server's seal key and bound to the server's name and the header, and kept in the data directory as ciphertext alone. 409 no_sealing_key when the server was handed no seal key and \`auth.type\` is not none (nothing is contacted). A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. 422 too for a bad name, URL or auth. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds.`,
943
+ description: `Each credential header's value is sealed under the server's seal key and bound to the server's name and the header, and kept in the data directory as ciphertext alone. 409 no_sealing_key when the server was handed no seal key and \`auth.type\` is not none (nothing is contacted). A body with no credential keeps the sealed one while the type and the URL's origin stay the same; else it is 422. 422 too for a bad name, URL or auth, or a price that is not a finite number 0 or more or names a tool the server does not list. ${MCP_CONNECTS} Nothing is saved unless the listing succeeds.`,
913
944
  parameters: [MCP_NAME],
914
- requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["url"], properties: { url: MCP_URL, auth: MCP_AUTH } } } } },
945
+ requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: false, required: ["url"], properties: { url: MCP_URL, auth: MCP_AUTH, prices: MCP_PRICES } } } } },
915
946
  responses: { "200": json(MCP_SERVER_VIEW, "The server, as saved."), ...errors(400, 401, 409, 415, 422, 429, 500), ...MCP_FAILED },
916
947
  "x-agentrun-serve": "mcpservers/1",
917
948
  },
@@ -1241,7 +1272,8 @@ const SO_FAR = {
1241
1272
  };
1242
1273
  const FIELD_EXTENSIONS = {
1243
1274
  Cost: SO_FAR,
1244
- TimelineUsage: SO_FAR,
1275
+ TimelineUsage: { ...SO_FAR, not_metered: { type: "integer", minimum: 1, description: "Set when the run made tool calls with no price (an MCP tool its owner set none for): how many. They ran outside the run's cost and its cap, and never make `usd` unknown.", "x-agentrun-serve": "mcpservers/1" } },
1276
+ UsageLine: { unpriced_runs: { type: "integer", minimum: 0, description: "How many of the runs counted on this line have a cost no one knows on it: they add no dollars to `usd`, so no sum passes them off as $0.", "x-agentrun-serve": "costsofar/1" }, not_metered_calls: { type: "integer", minimum: 1, description: "On the `tools` meter's line, set when the runs counted made tool calls with no price (an MCP tool its owner set none for): how many. They are outside `usd`.", "x-agentrun-serve": "mcpservers/1" } },
1245
1277
  Run: {
1246
1278
  ...RUN_FIELDS,
1247
1279
  last_progress_at: {
@@ -1332,6 +1364,14 @@ const FIELD_EXTENSIONS = {
1332
1364
  revision: { type: ["string", "null"], description: "The current revision's id; null before the agent has one.", "x-agentrun-serve": "serve/1" },
1333
1365
  revisions: { type: "integer", minimum: 0, description: "How many revisions the agent has.", "x-agentrun-serve": "serve/1" },
1334
1366
  archived_at: { type: ["string", "null"], description: "When the agent was archived, while it is; else null.", "x-agentrun-serve": "serve/1" },
1367
+ learning: {
1368
+ type: "object", additionalProperties: false, required: ["pending"],
1369
+ description: "For an agent that learns (its current revision `learning: true`, on a server whose learning is on): what waits on it. Absent for any other agent, and from an older server.",
1370
+ properties: {
1371
+ pending: { type: "integer", minimum: 0, description: "How many of its learned items wait for its owner's OK: notes, skills and workflow drafts held with `status: pending` on its learning folder's main (approve them on GET /agents/{agent_id}/learning)." },
1372
+ },
1373
+ "x-agentrun-serve": "serve/1",
1374
+ },
1335
1375
  },
1336
1376
  Capabilities: {
1337
1377
  learning: {
@@ -1350,7 +1390,7 @@ const FIELD_EXTENSIONS = {
1350
1390
  properties: {
1351
1391
  modes: { type: "array", items: { enum: [...PLACE_MODES] } },
1352
1392
  default: { enum: [...PLACE_MODES], description: "Where a revision that names no place runs: `runner`. It stays `runner` because a revision saved with no place (an agent made before new agents were given a box, or where docker was unavailable, or a workflow) keeps running where it ran. What a NEW agent gets is `default_place`." },
1353
- boxes: { type: "array", items: { type: "object", additionalProperties: false, required: ["id", "available", "state"], properties: { id: { enum: [...BOX_IDS] }, available: { type: "boolean" }, state: { enum: [...BOX_STATES], description: "`ready`; `preparing`, available while the server builds (or pulls) the Docker box's image at its start (a sandbox run's first box waits for it, with a timeline row); `unavailable`, with the `reason`." }, reason: { type: "string", description: "Why the box is unavailable, or what a preparing one waits for." }, network: { enum: [...BOX_NETWORKS], description: "What an available box reaches: `allowlist`, the hosts in `allow`, and nothing else (a Docker box through its egress proxy, on Linux with a daemon of that machine's own; a program that skips the proxy has no route; a Daytona box through Daytona's domain list, whose proxy re-signs TLS with Daytona's CA), or `none`. A Docker box's `none` comes with `network_reason`, and so does a Daytona box's when Daytona could not keep a list here (a tier that takes none); neither has one when AGENTRUN_BOX_ALLOW is `none`.", "x-agentrun-serve": "place/2" }, network_reason: { type: "string", description: "Why an available box has no network for a cause of its own, naming what the server found: a Docker in a VM, a daemon on another machine, docker info that did not answer; or a Daytona that could not keep its domain list.", "x-agentrun-serve": "place/2" } } } },
1393
+ boxes: { type: "array", items: { type: "object", additionalProperties: false, required: ["id", "available", "state"], properties: { id: { enum: [...BOX_IDS] }, available: { type: "boolean" }, state: { enum: [...BOX_STATES], description: "`ready`; `preparing`, available while the server builds (or pulls) the Docker box's image at its start (a sandbox run's first box waits for it, with a timeline row); `unavailable`, with the `reason`." }, reason: { type: "string", description: "Why the box is unavailable, or what a preparing one waits for. Docker is set up by default (AGENTRUN_BOXES not set), so docker's reason says first, in plain words, what is wrong on this machine, then what to do (`Docker isn't running on this machine (no docker command on PATH): install or start Docker, then restart AgentRun`); every other box AGENTRUN_BOXES does not list says the setting that lists it." }, network: { enum: [...BOX_NETWORKS], description: "What an available box reaches: `allowlist`, the hosts in `allow`, and nothing else (a Docker box through its egress proxy, on Linux with a daemon of that machine's own; a program that skips the proxy has no route; a Daytona box through Daytona's domain list, whose proxy re-signs TLS with Daytona's CA), or `none`. A Docker box's `none` comes with `network_reason`, and so does a Daytona box's when Daytona could not keep a list here (a tier that takes none); neither has one when AGENTRUN_BOX_ALLOW is `none`.", "x-agentrun-serve": "place/2" }, network_reason: { type: "string", description: "Why an available box has no network for a cause of its own, naming what the server found: a Docker in a VM, a daemon on another machine, docker info that did not answer; or a Daytona that could not keep its domain list.", "x-agentrun-serve": "place/2" } } } },
1354
1394
  },
1355
1395
  description: "The places a revision may name, this host's default, each box (whether this server has it, its state: ready, preparing or unavailable, and when not, why) and the hosts a box may reach.",
1356
1396
  "x-agentrun-serve": "place/1",
@@ -1423,7 +1463,7 @@ const FIELD_EXTENSIONS = {
1423
1463
  description: "The place a NEW agentic agent that names none is saved with, written on its revision at its create: the Docker box (`{\"mode\": \"sandbox\", \"box\": \"docker\"}`) where this server has docker, ready or preparing (its first run waits for the image, with a timeline row), with tools [\"bash\"] when the definition names no tools; else the runner, with `default_reason`. It is not `default`: that one is where a revision saved with no place runs, and stays `runner`, so an agent made before keeps running where it ran.",
1424
1464
  "x-agentrun-serve": "place/3",
1425
1465
  },
1426
- default_reason: { type: "string", description: "Why a new agent is not given a box here, when `default_place` is the runner, in docker's own words: `new agents run on the runner, because the docker box is unavailable here: <docker's reason>`.", "x-agentrun-serve": "place/3" },
1466
+ default_reason: { type: "string", description: "Why a new agent is not given a box here, when `default_place` is the runner, in docker's own words: `new agents run on the runner, because the docker box is unavailable here: <docker's reason>`, such as `Docker isn't running on this machine (no docker command on PATH): install or start Docker, then restart AgentRun`, or, with AGENTRUN_BOXES set to a list without docker, empty or `none`, the setting that turns it on.", "x-agentrun-serve": "place/3" },
1427
1467
  allow: { type: "array", items: { type: "string" }, description: "The hosts a box whose `network` is `allowlist` may reach: AGENTRUN_BOX_ALLOW's, else the package registries and GitHub; empty when it is `none`.", "x-agentrun-serve": "place/2" },
1428
1468
  },
1429
1469
  "Capabilities/workflows": {
@@ -1459,8 +1499,8 @@ const FIELD_EXTENSIONS = {
1459
1499
  "x-agentrun-serve": "toolkeys/1",
1460
1500
  },
1461
1501
  mcp_client: {
1462
- type: "object", additionalProperties: false, required: ["routes", "transports", "auth", "at_rest"],
1463
- properties: { routes: { type: "boolean" }, transports: { type: "array", items: { const: "streamable-http" } }, auth: { type: "array", items: { enum: [...MCP_AUTH_TYPES] } }, at_rest: { enum: ["sealed", "unavailable"] } },
1502
+ type: "object", additionalProperties: false, required: ["routes", "transports", "auth", "at_rest", "harnesses"],
1503
+ properties: { routes: { type: "boolean" }, transports: { type: "array", items: { const: "streamable-http" } }, auth: { type: "array", items: { enum: [...MCP_AUTH_TYPES] } }, at_rest: { enum: ["sealed", "unavailable"] }, harnesses: { type: "array", items: { type: "string" }, description: "The harnesses whose agents call a saved server's tools, each granted as mcp:<server>/<tool> in definition.tools." } },
1464
1504
  description: "/settings/mcp-servers: remote MCP servers over Streamable HTTP, previewed and saved with the auth types listed; a credential kept `sealed` under the seal key the server was handed, `unavailable` with none, when only servers that take no credential are kept.",
1465
1505
  "x-agentrun-serve": "mcpservers/1",
1466
1506
  },
@@ -1561,7 +1601,10 @@ export function openapiDocument(capabilityOf) {
1561
1601
  }
1562
1602
  // A contract field this server takes with a meaning of its own, said on it.
1563
1603
  definition.properties.max_cost_usd = { ...definition.properties.max_cost_usd, "x-agentrun-serve-note": "The agent's default cap of each run started without a max_cost_usd of its own (a run's own wins), kept with its revision: above 0 sets it, 0 clears it (no default), and an edit that leaves the field out keeps the agent's, so leaving a field out never removes a spend limit. An agentic definition only: on a workflow's, above 0 is 422 not_allowed, as a workflow run is not capped here." };
1564
- const noted = ["DefinitionInput.max_cost_usd"];
1604
+ // A row's usage: the contract's shape, on more rows here than the usage row (pi-durable-agent's timeline, BROWSER_CHARGE).
1605
+ const timelineRow = schemas.TimelineRow;
1606
+ timelineRow.properties.usage = { ...timelineRow.properties.usage, "x-agentrun-serve-note": "On the `usage` row, the run's cost so far. On a paid tool's charge row (a `phase` row, \"Tool cost: monid charged $0.0030 for monid.run\", `tool_name` the tool, `tool_use_id` the call), that charge alone. On a browser call's `tool_use` row (`tool_name` one of the browser's tools: snapshot, run, browser_read, ...), the browser session time booked under that call: what the session ran since its last charge, and, on the session's last call, its release's charge topped up to the provider's minimum. A browser charge has no row of its own. A charge booked after the row was served (a release after the answer) is served as a change of that row, with the same `id` and its new `usage`. `requests` is 0 on every row but the usage row; `usd` is null once a charge on the row has no price, with `so_far_usd` and `unpriced` saying what is known. The run's cost counts each charge once, wherever it shows: summing every row's `usage` but the usage row's gives what its paid tools charged." };
1607
+ const noted = ["DefinitionInput.max_cost_usd", "TimelineRow.usage"];
1565
1608
  // PUT .../definition takes the contract's body (the definition itself) or this server's own, POST /agents' body with a
1566
1609
  // note: exactly one, as only this server's holds `definition` and both are closed. If-Match is the contract's
1567
1610
  // precondition for its body; this server's own body may leave it out.
package/dist/page.d.ts CHANGED
@@ -9,6 +9,8 @@ export declare const ownerCookieName: (req: IncomingMessage) => string;
9
9
  export declare const ownerCookie: (req: IncomingMessage, value: string, maxAgeS: number) => string;
10
10
  /** Whether the request holds a session the owner signed in. */
11
11
  export declare const signedIn: (req: IncomingMessage, owner: Owner) => boolean;
12
+ /** A browser's answer for a Host the server refuses (host-check.ts): 403, a fixed page under the console's CSP. */
13
+ export declare const sendHostRefused: (req: IncomingMessage, res: ServerResponse) => void;
12
14
  /** `takesBytes`: whether a request of `method` to `path` (under /v2) goes to a route whose body is bytes (server.ts). */
13
15
  type PageServer = {
14
16
  token: string;
package/dist/page.js CHANGED
@@ -10,6 +10,7 @@ import { extname, join, sep } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { storeApi } from "@parcha/pi-durable-agent/serve";
12
12
  import { ApiError } from "./errors.js";
13
+ import { HOST_REFUSED_PAGE } from "./host-check.js";
13
14
  const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
14
15
  const SECURITY = { "content-security-policy": CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "cache-control": "no-store" };
15
16
  const HTML = "text/html; charset=utf-8";
@@ -43,6 +44,8 @@ function send(req, res, status, type, body, headers = {}) {
43
44
  res.writeHead(status, { ...SECURITY, "content-type": type, "content-length": bytes.length, ...headers });
44
45
  res.end(req.method === "HEAD" ? undefined : bytes);
45
46
  }
47
+ /** A browser's answer for a Host the server refuses (host-check.ts): 403, a fixed page under the console's CSP. */
48
+ export const sendHostRefused = (req, res) => send(req, res, 403, HTML, HOST_REFUSED_PAGE);
46
49
  const refuse = (req, res, error) => send(req, res, error.status, "application/json", JSON.stringify(error.body(String(res.getHeader("x-request-id") ?? ""))), error.headers);
47
50
  const redirect = (res, location, headers = {}) => (res.writeHead(303, { ...SECURITY, location, "content-length": 0, ...headers }), void res.end());
48
51
  /** A file of the console: a known type inside `dir`, read through no link that leaves it. Vite's hashed assets are cached
package/dist/place.d.ts CHANGED
@@ -30,8 +30,9 @@ export declare const NEW_AGENT_TOOLS: readonly string[];
30
30
  export declare function noBoxReason(registry: readonly BoxOffer[]): string | undefined;
31
31
  /** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
32
32
  * available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
33
- * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
34
- export declare function boxesLine(registry: readonly BoxOffer[], listed: ReadonlySet<BoxId>, allow?: readonly string[] | "none"): string;
33
+ * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do.
34
+ * `byDefault`, with AGENTRUN_BOXES not set at all: short, docker alone, said to be on by default, or why it is not. */
35
+ export declare function boxesLine(registry: readonly BoxOffer[], listed: ReadonlySet<BoxId>, allow?: readonly string[] | "none", byDefault?: boolean): string;
35
36
  /** `places` in capabilities: the modes a revision may name, where a revision that names none runs (`default`: the runner,
36
37
  * for a revision saved with no place), the place a new agent is saved with (`default_place`, with `default_reason` when
37
38
  * it is the runner), each box, and the hosts a box whose `network` is `allowlist` reaches (`allow`, run-box.ts
package/dist/place.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // (newAgentPlace). The place is written on the revision then, never resolved at run time, so a revision saved with none
13
13
  // (before this, or where docker was not there) runs on the runner, whatever the server has now.
14
14
  import { join } from "node:path";
15
- import { BOX_IDS, VM_PROVIDER } from "./boxes.js";
15
+ import { BOX_IDS, BOXES_ENV, VM_PROVIDER } from "./boxes.js";
16
16
  import { sentence } from "./errors.js";
17
17
  export const PLACE_MODES = ["runner", "sandbox"];
18
18
  export const DEFAULT_PLACE_MODE = "runner";
@@ -52,8 +52,9 @@ export function noBoxReason(registry) {
52
52
  }
53
53
  /** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
54
54
  * available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
55
- * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
56
- export function boxesLine(registry, listed, allow = "none") {
55
+ * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do.
56
+ * `byDefault`, with AGENTRUN_BOXES not set at all: short, docker alone, said to be on by default, or why it is not. */
57
+ export function boxesLine(registry, listed, allow = "none", byDefault = false) {
57
58
  const boxes = boxAvailability(registry);
58
59
  const preparing = (box) => box.state === "preparing";
59
60
  const ready = boxes.filter((box) => box.available && !preparing(box)).map((box) => box.id);
@@ -67,6 +68,13 @@ export function boxesLine(registry, listed, allow = "none") {
67
68
  // What an available box's programs reach, as capabilities say (`network`, `network_reason`, `places.allow`).
68
69
  const hosts = new Intl.ListFormat("en", { type: "conjunction" }).format(allow === "none" ? [] : allow);
69
70
  const reach = boxes.filter((box) => box.available && box.network).map((box) => box.network === "allowlist" ? sentence(`${box.id} boxes reach only ${hosts}`) : sentence(`${box.id} boxes have no network${box.network_reason ? `: ${box.network_reason}` : ""}`));
71
+ if (byDefault) {
72
+ const docker = boxes.find((box) => box.id === "docker");
73
+ if (!docker?.available)
74
+ return `Boxes: none, so new agents run on the runner. ${sentence(docker?.reason ?? "Docker is not set up")}`;
75
+ const coming = preparing(docker) ? ` docker is preparing${docker.reason ? ` (${docker.reason})` : ""}.` : "";
76
+ return [`Boxes: docker (on by default; set ${BOXES_ENV} to change).${coming}`, ...reach].join(" ");
77
+ }
70
78
  return ["Boxes:", ...(none ? ["none is ready, so sandbox agents do not run here."] : said), ...reach, ...why.map((box) => sentence(`${box.id}: ${box.reason ?? "not available"}`))].join(" ");
71
79
  }
72
80
  /** `places` in capabilities: the modes a revision may name, where a revision that names none runs (`default`: the runner,
package/dist/print.d.ts CHANGED
@@ -1,3 +1,10 @@
1
+ import type { ImageState } from "./box-image.js";
2
+ /** The line said as the Docker box image's first build (or pull) starts: it takes minutes, and nothing waits on it but
3
+ * a sandbox run's first box. */
4
+ export declare const IMAGE_PREPARING = "Preparing the Docker box image (first start only, a few minutes); agents can be made now, and their first run waits for it.";
5
+ /** The line for the Docker box image's state `state`, said once as its build starts and once as it ends (`started`: the
6
+ * start was said); undefined for any other, an image Docker already had among them. */
7
+ export declare function boxImageLine(state: ImageState, started: boolean): string | undefined;
1
8
  /** Where the token came from: made at this start (printed this once), kept in DIR/.token, or the environment's. */
2
9
  export type TokenSource = "made" | "file" | "env";
3
10
  /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
package/dist/print.js CHANGED
@@ -1,6 +1,19 @@
1
1
  // What the server prints on stdout: its banner at start, and one line per request, per run start and end, and per
2
2
  // refused credential (logfmt: `at=<time> event=<name> key=value ...`). No line holds a token or any part of one.
3
3
  import { join } from "node:path";
4
+ import { sentence } from "./errors.js";
5
+ /** The line said as the Docker box image's first build (or pull) starts: it takes minutes, and nothing waits on it but
6
+ * a sandbox run's first box. */
7
+ export const IMAGE_PREPARING = "Preparing the Docker box image (first start only, a few minutes); agents can be made now, and their first run waits for it.";
8
+ /** The line for the Docker box image's state `state`, said once as its build starts and once as it ends (`started`: the
9
+ * start was said); undefined for any other, an image Docker already had among them. */
10
+ export function boxImageLine(state, started) {
11
+ if (state.state === "preparing")
12
+ return started ? undefined : IMAGE_PREPARING;
13
+ if (!started)
14
+ return undefined;
15
+ return state.state === "ready" ? "The Docker box image is ready." : `The Docker box image failed: ${sentence(state.reason)}`;
16
+ }
4
17
  /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
5
18
  * people open (AGENTRUN_PUBLIC_URL), which the base URL and the link use. With `accounts` the page is the owner's
6
19
  * password, so its link holds no token. `boxes`: which boxes are ready, in words (Serve's boxesLine), last. */
package/dist/run-box.js CHANGED
@@ -19,7 +19,8 @@ import { appendFile, lstat, readFile, realpath } from "node:fs/promises";
19
19
  import { isAbsolute, join, posix, relative, sep } from "node:path";
20
20
  import { pathToFileURL } from "node:url";
21
21
  import { BACKGROUND_CONTEXT as BACKGROUND } from "@earendil-works/chord/context";
22
- import { egressBlockedBy, forwarderStart, hostEgress, PROXY_ENV, relayFailed, runBoxAllowOf } from "./box-egress.js";
22
+ import { EGRESS_MOUNT, egressBlockedBy, forwarderStart, hostEgress, PROXY_ENV, relayFailed, runBoxAllowOf } from "./box-egress.js";
23
+ import { runBoxVolumeOf, vmDocker, vmEgress } from "./box-egress-vm.js";
23
24
  import { awaitImage, boxImageOf } from "./box-image.js";
24
25
  import { RELAYED_KEY, relayedBox, relayFetch } from "./box-relay.js";
25
26
  import { VM_PROVIDER } from "./boxes.js";
@@ -126,7 +127,14 @@ export async function boxNetworkOf(env, options = {}) {
126
127
  if (allow === "none")
127
128
  return { allow: "none", reason: `${BOX_ALLOW_ENV} is none` };
128
129
  const blocked = await egressBlockedBy(env, options);
129
- return blocked ? { allow: "none", reason: blocked } : { allow };
130
+ if (!blocked)
131
+ return { allow };
132
+ // On a Mac only: a Docker that docker info names as a VM runtime this server knows gets the proxy container
133
+ // (box-egress-vm.ts); any other stays none, saying why.
134
+ if ((options.platform ?? process.platform) !== "darwin")
135
+ return { allow: "none", reason: blocked };
136
+ const vm = await vmDocker(env, { ...(options.platform ? { platform: options.platform } : {}), ...(options.kernel ? { kernel: options.kernel } : {}), ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}) });
137
+ return "runtime" in vm ? { allow, vm: vm.runtime } : { allow: "none", reason: vm.reason };
130
138
  }
131
139
  /** Under `--faux` only: a module whose default export, given the data root, is the provider runs' boxes come from in
132
140
  * place of Docker (the tests' faux box). */
@@ -177,11 +185,13 @@ export async function runBoxProvider(place, env, root) {
177
185
  const image = boxImageOf(env);
178
186
  // The list the server resolved for this run's box (box-egress.ts boxNetworkOf), or none.
179
187
  const allow = runBoxAllowOf(env);
188
+ // On a Mac, the server's proxy container's volume (box-egress-vm.ts), which every box mounts read-only.
189
+ const volume = allow === "none" ? undefined : runBoxVolumeOf(env);
180
190
  return {
181
- ...dockerBoxes({ image, ...(user ? { user } : {}), ...boxLimitsOf(env), dropCapabilities: true }),
191
+ ...dockerBoxes({ image, ...(user ? { user } : {}), ...boxLimitsOf(env), dropCapabilities: true, ...(volume ? { volumes: [{ name: volume, target: EGRESS_MOUNT, readOnly: true }] } : {}) }),
182
192
  ready: (context, note) => awaitImage(root, image, context, note),
183
193
  // Where the proxy runs: the one line that picks it (box-egress.ts BoxEgress).
184
- ...(allow === "none" ? {} : { egress: hostEgress(allow, env, egressLog), net: netLabelOf(allow) }),
194
+ ...(allow === "none" ? {} : { egress: volume ? vmEgress : hostEgress(allow, env, egressLog), net: netLabelOf(allow) }),
185
195
  };
186
196
  }
187
197
  /** The tests' faux box provider, from its module. */
@@ -352,7 +362,7 @@ async function localRunBox(boxes, run, context, note) {
352
362
  // Docker's network stays none either way: the box's only way out is the proxy's socket, which checks everything.
353
363
  const spec = {
354
364
  env: egress ? { ...BOX_ENV, ...PROXY_ENV } : BOX_ENV, workspace: agentWorkDir(run.dir, run.place),
355
- mounts: [...(await boxMounts(run.root, run.dir, run.place)), ...(egress ? [egress.mount] : [])],
365
+ mounts: [...(await boxMounts(run.root, run.dir, run.place)), ...(egress?.mount ? [egress.mount] : [])],
356
366
  labels: { [RUN_LABEL]: run.id, [KIND_LABEL]: "run", ...(boxes.net ? { [NET_LABEL]: boxes.net } : {}) }, network: "none", maxLifetimeMs: BOX_LIFETIME_MS,
357
367
  };
358
368
  const made = await boxes.create(spec, context);
@@ -3,6 +3,9 @@ import { type HarnessCapability } from "./harness.js";
3
3
  import { type ModelRef } from "./model.js";
4
4
  import type { BoxOffer } from "./boxes.js";
5
5
  import { type ToolSettingsMap } from "./tool-plane.js";
6
+ import { type McpTool } from "@parcha/agentrun-kernel";
7
+ /** The harnesses an agent's MCP tools run on here. */
8
+ export declare const MCP_HARNESSES: readonly string[];
6
9
  /** A revision's body as it is saved or stored. */
7
10
  export type RevisionShape = {
8
11
  kind: "agentic";
@@ -74,10 +77,14 @@ export declare const CODE_NODES_ENV = "AGENTRUN_SERVE_CODE_NODES";
74
77
  /** What keeps `revision` from running in `env` under the server's tool `settings` (tool-plane.ts). `boxes`: what this
75
78
  * server's box registry set up at its start (boxes.ts); none, every box is unavailable. `offers`: the harnesses' offers
76
79
  * the server already holds (its reading); none given, they are probed here. */
77
- export declare function blockersOf(env: NodeJS.ProcessEnv, revision: RevisionShape, settings?: ToolSettingsMap, { capped, boxes, offers }?: {
80
+ export declare function blockersOf(env: NodeJS.ProcessEnv, revision: RevisionShape, settings?: ToolSettingsMap, { capped, boxes, offers, mcp }?: {
78
81
  capped?: boolean;
79
82
  boxes?: readonly BoxOffer[];
80
83
  offers?: readonly HarnessCapability[];
84
+ mcp?: (server: string) => readonly (McpTool & {
85
+ grantable?: false;
86
+ reason?: string;
87
+ })[] | undefined;
81
88
  }): Promise<Blocker[]>;
82
89
  /** A blocker as a field issue, for a 422 or a warning. */
83
90
  export declare const issueOf: ({ field, reason, message, fix }: Blocker) => InputIssue;
package/dist/runnable.js CHANGED
@@ -13,6 +13,12 @@ import { allows, BOUND_TOOLS, CALL_TOOLS, grantedTools, missingEnv, NODE_TOOLS,
13
13
  import { capabilityOf, DENIED, isUnavailable, NO_PARALLEL_KEY, planeFor, whyUnavailable } from "./tool-plane.js";
14
14
  import { permissionOf } from "./tool-gate.js";
15
15
  import { PARALLEL_KEY_ENV } from "./decisions.js";
16
+ import { keyNeeded } from "./key-words.js";
17
+ import { wireName } from "./catalog.js";
18
+ import { mcpHeaderProblem, mcpNameOf } from "./mcp-gateway.js";
19
+ import { toolSchemaProblems } from "@parcha/agentrun-kernel";
20
+ /** The harnesses an agent's MCP tools run on here. */
21
+ export const MCP_HARNESSES = [DEFAULT_HARNESS, "claude-agent"];
16
22
  /**
17
23
  * The model `harness` runs an agentic revision on here: `ref`, its own `provider/model-id`, or with none this host's
18
24
  * default for that harness. `why`: the model itself is the problem (`host`, a setting of this host could fix it);
@@ -47,7 +53,7 @@ export const CODE_NODES_ENV = "AGENTRUN_SERVE_CODE_NODES";
47
53
  /** What keeps `revision` from running in `env` under the server's tool `settings` (tool-plane.ts). `boxes`: what this
48
54
  * server's box registry set up at its start (boxes.ts); none, every box is unavailable. `offers`: the harnesses' offers
49
55
  * the server already holds (its reading); none given, they are probed here. */
50
- export async function blockersOf(env, revision, settings = {}, { capped = false, boxes = [], offers } = {}) {
56
+ export async function blockersOf(env, revision, settings = {}, { capped = false, boxes = [], offers, mcp } = {}) {
51
57
  const out = [];
52
58
  /** A web tool its run would resolve unavailable (tool-plane.ts): a warning at save, a 409 at a run, never another
53
59
  * provider in its place. One set to deny is not: its run starts, and the gate refuses each call. */
@@ -60,7 +66,7 @@ export async function blockersOf(env, revision, settings = {}, { capped = false,
60
66
  const unset = (field, tool) => {
61
67
  const vars = missingEnv(toolOf(tool), env);
62
68
  if (vars.length)
63
- out.push({ field, reason: NOT_SET_UP, message: `This server's environment does not set what the tool needs: the tool ${tool} needs ${vars.join(" and ")}.`, host: true, missing: { tool, vars } });
69
+ out.push({ field, reason: NOT_SET_UP, message: `The tool ${tool} needs ${keyNeeded(vars)}.`, host: true, missing: { tool, vars } });
64
70
  };
65
71
  const harness = revision.harness ?? DEFAULT_HARNESS;
66
72
  const offer = (offers ?? (await harnessOffers(env))).find((h) => h.id === harness);
@@ -81,6 +87,41 @@ export async function blockersOf(env, revision, settings = {}, { capped = false,
81
87
  if (!revision.instructions.trim())
82
88
  out.push({ field: "definition.instructions", reason: "too_short", message: "definition.instructions is empty: an agentic revision needs instructions.", host: false });
83
89
  (revision.tools ?? []).forEach((tool, index) => {
90
+ // A remote MCP server's tool: one its saved snapshot lists, on a harness that binds them.
91
+ if (tool.startsWith("mcp:")) {
92
+ const field = `definition.tools[${index}]`;
93
+ const named = mcpNameOf(tool);
94
+ const saved = named && mcp?.(named.server);
95
+ const listed = saved && saved.map((t) => t.name);
96
+ const listedTool = saved && named ? saved.find((t) => t.name === named.tool) : undefined;
97
+ const schema = listedTool?.inputSchema;
98
+ const declared = schema ? mcpHeaderProblem(schema) : undefined;
99
+ // On claude-agent the CLI drops a tool whose schema fails the kernel's check, or whose root holds anyOf, allOf or
100
+ // oneOf (harness-claude's check, measured on the pinned CLI), without a word: refused here, not missing at the run.
101
+ const dropped = schema && named && harness === "claude-agent" ? [...toolSchemaProblems(`mcp__${named.server}__${named.tool}`, schema), ...["anyOf", "allOf", "oneOf"].filter((key) => key in schema).map((key) => `/${key}: the Claude Agent CLI drops a tool whose root has ${key}`)][0] : undefined;
102
+ if (!named)
103
+ out.push({ field, reason: "not_an_option", message: `${tool} is not an MCP tool's name: mcp:<server>/<tool>, the server's name in lowercase letters, digits and -.`, host: false, tool });
104
+ // claude-agent's own tools are its MCP server `hands`: a remote server of that name could never be called there.
105
+ else if (named.server === "hands")
106
+ out.push({ field, reason: "not_an_option", message: `${tool} names the MCP server hands, a name the harnesses keep for their own tools: save the server under another name.`, host: false, tool });
107
+ // A meta tool runs other actions by name: a grant of it could not name the action (mcp-meta.ts). Refused before
108
+ // the harness's check, since no host setup makes it grantable.
109
+ else if (listedTool?.grantable === false)
110
+ out.push({ field, reason: "not_an_option", message: `${tool} can't be granted: ${listedTool.reason}`, host: false, tool });
111
+ else if (!MCP_HARNESSES.includes(harness))
112
+ out.push({ field, reason: NOT_SET_UP, message: `${tool} runs on ${MCP_HARNESSES.join(" and ")} here; on ${harness} MCP tools are not bound yet.`, host: true, tool });
113
+ else if (!listed)
114
+ out.push({ field, reason: "not_an_option", message: `No MCP server ${named.server} is saved on this server: add it in Settings → MCP servers first.`, host: false, tool });
115
+ else if (!listed.includes(named.tool))
116
+ out.push({ field, reason: "not_an_option", message: `The MCP server ${named.server} has no tool ${named.tool}; its tools are ${listed.join(", ") || "none"}.`, host: false, tool });
117
+ else if (dropped)
118
+ out.push({ field, reason: "not_an_option", message: `The MCP server ${named.server}'s tool ${named.tool} cannot be offered on claude-agent: ${dropped.replace(/^mcp__\S+: /, "")}.`, host: false, tool });
119
+ else if (declared)
120
+ out.push({ field, reason: "not_an_option", message: `The MCP server ${named.server}'s tool ${named.tool} declares a header it cannot send: ${declared}.`, host: false, tool });
121
+ else if (wireName(tool) !== `mcp__${named.server}__${named.tool}`)
122
+ out.push({ field, reason: "not_an_option", message: `${tool} is too long: mcp__${named.server}__${named.tool} must be at most 52 characters, the budget every harness's tool names share.`, host: false, tool });
123
+ return;
124
+ }
84
125
  if (!allows(BOUND_TOOLS, tool))
85
126
  out.push({ field: `definition.tools[${index}]`, reason: "not_an_option", message: `agentrun-serve binds the tools ${BOUND_TOOLS.join(", ")}; ${tool} is not one of them.`, host: false, tool });
86
127
  // A shell runs only in a box: no place, or the runner, has none.
@@ -108,6 +149,14 @@ export async function blockersOf(env, revision, settings = {}, { capped = false,
108
149
  out.push({ field: revision.model ? "definition.model" : "definition.harness", reason: NOT_SET_UP, message: resolved.refused, host: true, harness });
109
150
  return out;
110
151
  }
152
+ // A workflow's own grants hold a known MCP meta tool to the same rule (mcp-meta.ts): refused at the save, never a
153
+ // workflow that cannot launch.
154
+ (revision.tools ?? []).forEach((tool, index) => {
155
+ const named = tool.startsWith("mcp:") ? mcpNameOf(tool) : undefined;
156
+ const listed = named ? mcp?.(named.server)?.find((t) => t.name === named.tool) : undefined;
157
+ if (listed?.grantable === false)
158
+ out.push({ field: `definition.tools[${index}]`, reason: "not_an_option", message: `${tool} can't be granted: ${listed.reason}`, host: false, tool });
159
+ });
111
160
  // A workflow's model nodes run on pi here; on another harness they are not bound yet, and never run on pi instead.
112
161
  if (harness !== DEFAULT_HARNESS)
113
162
  out.push({ field: "definition.workflow", reason: NOT_SET_UP, message: `A workflow runs on pi here; on ${harness} its model nodes are not bound yet.`, host: true, harness });