@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
package/dist/server.js CHANGED
@@ -26,26 +26,28 @@ import { DEFAULT_HARNESS, FAUX_HARNESS_ENV, harnessOffers } from "./harness.js";
26
26
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
27
27
  import { IMPORT_ASKED } from "./import.js";
28
28
  import { gradeModelOf, learningBudgetOf, learningOf } from "./learning.js";
29
- import { agentLearning, learningLog, learningNotes, noteBody, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
29
+ import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, readNote, runDiff, runLearning, secretsShown, sendNote, writeNote } from "./learning-routes.js";
30
30
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
31
31
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
32
32
  import { boxesLine, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
33
33
  import { BOX_ALLOW_ENV, boxAllowOf, boxLimitsOf, boxNetworkOf, FAUX_BOX_ENV, fauxBoxes } from "./run-box.js";
34
34
  import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
35
- import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, signedIn } from "./page.js";
35
+ import { answerPage, byOwnerSession, isJson, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
36
+ import { HOST_FIX, hostName, loopbackNames } from "./host-check.js";
36
37
  import { durationMs, logLine } from "./print.js";
37
38
  import { knownToolCostOf, Runs, STATUSES, statusOf, toolCostOf, WAITS_ON_A_PERSON } from "./runs.js";
38
39
  import { runLines } from "./usage-lines.js";
39
40
  import { BOX_QUARANTINE, Quarantine } from "./box/sweep.js";
40
- import { boxesLog, boxRegistry, daytonaApi, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
41
+ import { boxesByDefault, boxesLog, boxRegistry, daytonaApi, enabledBoxes, VM_NO_LIST, VM_PROVIDER } from "./boxes.js";
41
42
  import { FAUX_EGRESS_ENV, sweepEgressDirs } from "./box-egress.js";
43
+ import { startEgressContainer } from "./box-egress-vm.js";
42
44
  import { boxImageOf, clearImage, dockerImage, withImage } from "./box-image.js";
43
45
  import { startBoxRelay } from "./box-relay.js";
44
46
  import { vmRelay } from "./box-relay-vm.js";
45
47
  import { memoryMbOf } from "./run-box.js";
46
48
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
47
49
  import { meterFiguresIn } from "./cap.js";
48
- import { blockersOf, CODE_NODES_ENV, issueOf } from "./runnable.js";
50
+ import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES } from "./runnable.js";
49
51
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
50
52
  import { redactedOutput } from "./key-refusal.js";
51
53
  import { analyticsFilter, analyticsView, pendingOf, statsView } from "./stats.js";
@@ -53,6 +55,7 @@ import { outcomes } from "./usage.js";
53
55
  import { keyOf, SEAL_KEY_ENV, sealKeyOf, TOOL_FIELDS, ToolKeys } from "./tool-keys.js";
54
56
  import { SIGN_INS_DIR, SignIns, vendorsOver } from "./sign-ins.js";
55
57
  import { MCP_AUTH_TYPES, McpServers } from "./mcp-servers.js";
58
+ import { metaToolOf } from "./mcp-meta.js";
56
59
  import { WEBHOOK_EVENTS, Webhooks } from "./webhooks.js";
57
60
  import { HOOK_TOLERANCE_S, hookHeadersRefusal, hookRefusal, TriggerSecrets } from "./trigger-secrets.js";
58
61
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, OVERLAP, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
@@ -208,6 +211,7 @@ export const ROUTES = [
208
211
  { method: "PUT", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "writeLearningFile" },
209
212
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/retire$/, name: "retireLearningFile" },
210
213
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/approve$/, name: "approveLearningFile" },
214
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
211
215
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
212
216
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
213
217
  ];
@@ -353,7 +357,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, needs, toolSettings
353
357
  tool_keys: { routes: true, at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
354
358
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the same seal key
355
359
  * (mcp-servers.ts); with none, only servers that take no credential are kept. */
356
- mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable" },
360
+ mcp_client: { routes: true, transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: sealKeyOf(env[SEAL_KEY_ENV]) ? "sealed" : "unavailable", harnesses: [...MCP_HARNESSES] },
357
361
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
358
362
  learning,
359
363
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -464,6 +468,15 @@ export async function startServe(options) {
464
468
  }
465
469
  async function startHolding(options, data, lock, checked, stops) {
466
470
  const { maxRuns, minFreeBytes, learning, learningBudget, boxAllow } = checked;
471
+ /** What an agent's view says of its learning: how many learned items wait for its owner's OK, for an agent that learns
472
+ * on this server (learning on, its current revision `learning: true`); none for another, or when the count cannot be
473
+ * read (the view never fails for it). */
474
+ const learningOfAgent = async (entry) => {
475
+ if (learning === "off" || entry.revision?.kind !== "agentic" || entry.revision.body.learning !== true)
476
+ return undefined;
477
+ const pending = await pendingCount(data, entry.agent.id);
478
+ return pending === undefined ? undefined : { pending };
479
+ };
467
480
  const tokenFile = options.token === undefined ? join(data, TOKEN_FILE) : null;
468
481
  const stored = options.token === undefined ? await tokenIn(tokenFile) : undefined;
469
482
  const token = options.token ?? stored.token;
@@ -497,6 +510,27 @@ async function startHolding(options, data, lock, checked, stops) {
497
510
  // A stored key that does not open is said once at the start, never a refusal to start.
498
511
  toolKeys.view();
499
512
  const mcpServers = new McpServers(data, withSecrets(base, "own"), VERSION);
513
+ // What a run's grants are checked against, its pin made from and its credentials read from (runs.ts, runnable.ts).
514
+ const mcpSource = {
515
+ server: (name) => {
516
+ try {
517
+ const saved = mcpServers.get(name);
518
+ return { url: saved.url, tools: saved.tools.map(({ name: tool, title, description, input_schema, annotations }) => ({ name: tool, ...(title ? { title } : {}), ...(description ? { description } : {}), inputSchema: input_schema, ...(annotations ? { annotations: annotations } : {}) })), ...(saved.prices ? { prices: saved.prices } : {}) };
519
+ }
520
+ catch {
521
+ return undefined;
522
+ }
523
+ },
524
+ headers: (name) => mcpServers.headers(name),
525
+ };
526
+ // Each with whether it can be granted: a known meta tool can't (mcp-meta.ts).
527
+ const mcpTools = (server) => {
528
+ const saved = mcpSource.server(server);
529
+ return saved?.tools.map((tool) => {
530
+ const meta = metaToolOf(saved.url, tool.name);
531
+ return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
532
+ });
533
+ };
500
534
  // The server's tool settings, beside the agent store: capabilities say what they resolve to, again after a PUT.
501
535
  const settings = new ToolSettings(data);
502
536
  // The server's reading, in parts: `env`, its environment with its secrets, saved keys among them (storedKeys);
@@ -548,7 +582,7 @@ async function startHolding(options, data, lock, checked, stops) {
548
582
  else
549
583
  await probe("key");
550
584
  };
551
- // The boxes AGENTRUN_BOXES lists, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
585
+ // The boxes AGENTRUN_BOXES lists, docker when it is not set, each probed once (boxes.ts); runs execute in Docker's (place.ts). Under --faux, a faux
552
586
  // box stands in for Docker, and nothing asks Docker.
553
587
  // Under --faux, the tests' fake stands in for the VM provider's SDK (startServe's `fauxVm`), never the provider.
554
588
  const boxes = await boxRegistry(env, options.faux && options.fauxVm ? { vmSdk: () => import(pathToFileURL(resolve(options.fauxVm)).href) } : {});
@@ -559,11 +593,21 @@ async function startHolding(options, data, lock, checked, stops) {
559
593
  let image;
560
594
  // What a Docker box's programs reach, resolved once here (run-box.ts boxNetworkOf): the setting's list, on a Docker
561
595
  // daemon of this Linux machine's own; else none, and why. A run's process gets the list or none (RUN_BOX_ALLOW_ENV).
562
- const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : boxes.provider("docker") ? await boxNetworkOf(env) : { allow: "none", reason: "no Docker box on this server" };
596
+ const boxNetwork = fauxBox ? { allow: "none", reason: "a faux box (tests)" } : boxes.provider("docker") ? await boxNetworkOf(env, options.faux && options.fauxPlatform ? { platform: options.fauxPlatform } : {}) : { allow: "none", reason: "no Docker box on this server" };
563
597
  // The proxy directories runs that are gone left in /tmp (box-egress.ts): a live run's, any server's, stays.
564
598
  if (!fauxBox && boxes.provider("docker"))
565
599
  await sweepEgressDirs().catch(() => 0);
566
- const dockerNetwork = (offer) => !offer.available ? offer : boxNetwork.allow === "none" ? { ...offer, network: "none", network_reason: boxNetwork.reason } : { ...offer, network: "allowlist" };
600
+ // On a Mac whose Docker runs in a VM this server knows, the list is served by one proxy container inside that VM
601
+ // (box-egress-vm.ts): a box's network is the list once it is ready, and none, saying why, until then or when it can't start.
602
+ let egress;
603
+ const dockerNetwork = (offer) => {
604
+ if (!offer.available)
605
+ return offer;
606
+ if (boxNetwork.allow === "none")
607
+ return { ...offer, network: "none", network_reason: boxNetwork.reason };
608
+ const proxy = egress?.state();
609
+ return proxy && proxy.state !== "ready" ? { ...offer, network: "none", network_reason: proxy.reason } : { ...offer, network: "allowlist" };
610
+ };
567
611
  // A Daytona box reaches the hosts AGENTRUN_BOX_ALLOW names, through Daytona's domain list, until Daytona cannot keep
568
612
  // one here (an organization whose tier takes none): from then on each is made with no network, and capabilities say why.
569
613
  let daytonaNoList;
@@ -581,6 +625,7 @@ async function startHolding(options, data, lock, checked, stops) {
581
625
  onChange: (state, ms) => {
582
626
  boxOffers = offersNow();
583
627
  imageLog(state, { ms });
628
+ options.onBoxImage?.(state);
584
629
  // The box's state is in caps alone, not in the offers: recomposed now, or, while the start's probe of the offers
585
630
  // has not ended, by that probe, which reads the box offers when it does.
586
631
  if (offers)
@@ -588,6 +633,7 @@ async function startHolding(options, data, lock, checked, stops) {
588
633
  },
589
634
  });
590
635
  stops.push(async () => void (await image?.close()));
636
+ options.onBoxImage?.(image.state());
591
637
  }
592
638
  else
593
639
  await clearImage(data);
@@ -616,6 +662,22 @@ async function startHolding(options, data, lock, checked, stops) {
616
662
  if (offers)
617
663
  recompose();
618
664
  };
665
+ if (boxNetwork.allow !== "none" && boxNetwork.vm) {
666
+ const allow = boxNetwork.allow;
667
+ const egressLog = (state) => log?.(logLine("box_egress", { runtime: boxNetwork.vm, state: state.state, ...("reason" in state ? { reason: state.reason } : {}) }));
668
+ egress = await startEgressContainer({
669
+ env, data, allow, uid: process.getuid?.() ?? 0, gid: process.getgid?.() ?? 0,
670
+ onChange: (state) => {
671
+ egressLog(state);
672
+ boxOffers = offersNow();
673
+ if (offers)
674
+ recompose();
675
+ },
676
+ });
677
+ stops.push(() => egress.close());
678
+ egressLog(egress.state());
679
+ boxOffers = offersNow();
680
+ }
619
681
  log?.(logLine("boxes", boxesLog(boxOffers, enabledBoxes(env))));
620
682
  if (image)
621
683
  imageLog(image.state());
@@ -636,7 +698,7 @@ async function startHolding(options, data, lock, checked, stops) {
636
698
  const documents = options.documents ?? process.env[DOCUMENTS_ENV];
637
699
  if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
638
700
  throw new Error(`the documents directory ${documents} is not a directory`);
639
- const runs = new Runs({ dockerAllow: boxNetwork.allow, agents, token, storedKeys, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(vmBoxes && vmRelayHalf ? { vmBoxes, vmLimits, vmRelay: vmRelayHalf } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(remoteBoxes ? { boxAllow, onNoBoxList } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker), ownSecrets: () => triggerSecrets?.values() ?? [], signIns, approvers: options.accounts === true });
701
+ const runs = new Runs({ dockerAllow: boxNetwork.allow, ...(egress?.volume ? { dockerVolume: egress.volume } : {}), agents, token, storedKeys, mcpServers: mcpSource, doorTokenFile, doorToken, learning, learningBudget, ...(documents ? { documents: resolve(documents) } : {}), fauxEnv: fauxEnvOf(options), toolSettings: () => settings.get(), ...(runBoxes ? { runBoxes } : {}), ...(remoteBoxes ? { remoteBoxes } : {}), ...(vmBoxes && vmRelayHalf ? { vmBoxes, vmLimits, vmRelay: vmRelayHalf } : {}), ...(remoteBoxes && daytonaApi(env) ? { remoteApi: daytonaApi(env) } : {}), ...(remoteBoxes ? { boxAllow, onNoBoxList } : {}), ...(options.drainTimeout ? { drainTimeout: options.drainTimeout } : {}), ...(options.carryBackRetry ? { carryBackRetry: options.carryBackRetry } : {}), maxRuns, ...(options.box ? { box: { host: options.box, quarantine: await Quarantine.open(join(data, BOX_QUARANTINE)) } } : {}), ...(options.settleRetryMs ? { settleRetryMs: options.settleRetryMs } : {}), ...(options.readyTimeoutMs ? { readyTimeoutMs: options.readyTimeoutMs } : {}), ...(options.reflectTimeoutMs ? { reflectTimeoutMs: options.reflectTimeoutMs } : {}), ...(options.gradeTimeoutMs ? { gradeTimeoutMs: options.gradeTimeoutMs } : {}), ...(options.gradeModel ? { gradeModel: options.gradeModel } : {}), ...(log ? { log: (event, fields) => log(logLine(event, fields)) } : {}), notify: (event, run, marker) => webhooks.emit(event, run, marker), ownSecrets: () => triggerSecrets?.values() ?? [], signIns, approvers: options.accounts === true });
640
702
  const daytona = daytonaApi(env);
641
703
  const relay = (remoteBoxes && daytona) || vmRelayHalf ? await startBoxRelay({ root: data, tokenOf: (id) => runs.relayToken(id), ...(remoteBoxes && daytona ? daytona : {}), ...(vmRelayHalf ? { vm: vmRelayHalf } : {}), serves: (id) => runs.servesBox(id), ensure: (id) => runs.ensureBox(id) }) : undefined;
642
704
  if (relay)
@@ -975,7 +1037,7 @@ async function startHolding(options, data, lock, checked, stops) {
975
1037
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
976
1038
  async function runnable(revision, place, { capped = false } = {}) {
977
1039
  const shape = { ...shapeOf(revision), place };
978
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers });
1040
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, offers, mcp: mcpTools });
979
1041
  if (!blockers.length)
980
1042
  return;
981
1043
  const message = blockers.map((b) => b.message).join(" ");
@@ -995,14 +1057,14 @@ async function startHolding(options, data, lock, checked, stops) {
995
1057
  /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. */
996
1058
  async function saveable(revision) {
997
1059
  const shape = revision.kind === "agentic" ? revision : workflowShape(revision);
998
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, offers });
1060
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, offers, mcp: mcpTools });
999
1061
  // An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
1000
1062
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1001
1063
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1002
1064
  if (revision.kind === "agentic" && (revision.maxCostUsd ?? 0) > 0) {
1003
1065
  const key = (b) => `${b.field}\n${b.message}`;
1004
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers })).map(key));
1005
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers });
1066
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, offers, mcp: mcpTools })).map(key));
1067
+ const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, offers, mcp: mcpTools });
1006
1068
  blockers.push(...capped.filter((b) => !plain.has(key(b))).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1007
1069
  }
1008
1070
  const never = blockers.filter((b) => !b.host);
@@ -1305,6 +1367,8 @@ async function startHolding(options, data, lock, checked, stops) {
1305
1367
  if (!["meter", "agent", "key", "day", "region"].includes(group))
1306
1368
  throw new ApiError("bad_request", "group_by is meter, agent, key, day or region");
1307
1369
  const lines = new Map();
1370
+ // Tool calls run with no price (an MCP tool its owner set none for): outside every cost, counted on `tools`.
1371
+ let notMetered = 0;
1308
1372
  const total = { usd: 0, unpriced: 0 };
1309
1373
  // The browser_time line's seconds: its ended runs' (their stores keep each charge's), none once a live run is in it.
1310
1374
  let browserSeconds = 0;
@@ -1333,7 +1397,7 @@ async function startHolding(options, data, lock, checked, stops) {
1333
1397
  // ended (a call a crash cut makes `tools` unknown, never `tokens`). An unknown meter counts the run as unpriced on it.
1334
1398
  // An ended run's are its store's figures (metersOf keeps them, never its timeline), read for its lines by meter and,
1335
1399
  // by any group, for what a run of unknown cost is known to have spent.
1336
- const read = (group === "meter" && usd !== 0) || usd === null ? (live ? { tools: toolCostOf(live.rows), tokens: null, browser: { usd: toolCostOf(live.rows, "browser"), seconds: null }, others: toolCostOf(live.rows.filter((r) => r.tool_name !== "browser")), known: { tokens: 0, browser: knownToolCostOf(live.rows, "browser"), others: knownToolCostOf(live.rows, "browser", true) } } : metersOf(row)) : undefined;
1400
+ const read = (group === "meter" && usd !== 0) || usd === null ? (live ? { tools: toolCostOf(live.rows), tokens: null, browser: { usd: toolCostOf(live.rows, "browser"), seconds: null }, others: toolCostOf(live.rows, "browser", true), known: { tokens: 0, browser: knownToolCostOf(live.rows, "browser"), others: knownToolCostOf(live.rows, "browser", true) } } : metersOf(row)) : undefined;
1337
1401
  // A run whose cost is unknown still spent what is known of it (so_far: each meter's known dollars): that is in the
1338
1402
  // total and its lines, and the run is counted unpriced, so a total is never below a line of its own and reads as
1339
1403
  // the lower bound unpriced_runs says it is.
@@ -1342,6 +1406,12 @@ async function startHolding(options, data, lock, checked, stops) {
1342
1406
  if (meters && meters.browser.usd !== 0)
1343
1407
  browserSeconds = browserSeconds === null || meters.browser.seconds === null ? null : browserSeconds + meters.browser.seconds;
1344
1408
  // Its parts of the lines (usage-lines.ts): an unknown one counts the run unpriced there and adds what is known of it.
1409
+ // An unpriced MCP call is in none of them: counted apart as not metered on the tools line, which a $0 run shows only
1410
+ // when it made one.
1411
+ const unmetered = group !== "meter" ? 0 : ((live ? live.rows.find((one) => one.kind === "usage")?.usage?.not_metered : metersOf(row).notMetered) ?? 0);
1412
+ notMetered += unmetered;
1413
+ if (unmetered && !lines.has("tools"))
1414
+ lines.set("tools", { usd: 0, unpriced: 0 });
1345
1415
  for (const part of runLines({ usd, soFar, key, meters })) {
1346
1416
  const line = lines.get(part.name) ?? lines.set(part.name, { usd: 0, unpriced: 0 }).get(part.name);
1347
1417
  line.usd += part.usd;
@@ -1361,7 +1431,7 @@ async function startHolding(options, data, lock, checked, stops) {
1361
1431
  const round = (v) => Math.round(v * 1e6) / 1e6;
1362
1432
  return {
1363
1433
  from: new Date(from).toISOString(), to: new Date(to).toISOString(), currency: "USD", basis: "estimate", group_by: group, total_usd: round(total.usd), unpriced_runs: total.unpriced,
1364
- lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced })),
1434
+ lines: [...lines].map(([key, line]) => ({ group: key, ...(group === "meter" ? { meter: key } : {}), ...(key === "browser_time" && group === "meter" && browserSeconds !== null ? { quantity: round(browserSeconds), unit: "second" } : {}), usd: round(line.usd), unpriced_runs: line.unpriced, ...(group === "meter" && key === "tools" && notMetered ? { not_metered_calls: notMetered } : {}) })),
1365
1435
  account: null,
1366
1436
  };
1367
1437
  }
@@ -1498,6 +1568,11 @@ async function startHolding(options, data, lock, checked, stops) {
1498
1568
  // page cookie a token can mint (accounts off). The page's cookie stands in for the token only on its own origin
1499
1569
  // with a JSON body (page.ts), so this is CSRF-checked as every page write is. With no credential at all it is 401,
1500
1570
  // as every route is.
1571
+ // Restoring a retired one puts it back in every later run, as an approval does: the same owner's session alone.
1572
+ if (found.name === "restoreLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1573
+ authFailed(`/v2${path}`, "restore_without_session");
1574
+ throw new ApiError("forbidden", owner ? "Restoring a retired note takes the owner's password sign-in in the console, never a token." : "Restoring a retired note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
1575
+ }
1501
1576
  if (found.name === "approveLearningFile" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
1502
1577
  authFailed(`/v2${path}`, "approve_without_session");
1503
1578
  throw new ApiError("forbidden", owner ? "Approving a note takes the owner's password sign-in in the console, never a token." : "Approving a note takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
@@ -1527,7 +1602,7 @@ async function startHolding(options, data, lock, checked, stops) {
1527
1602
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1528
1603
  const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1529
1604
  const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
1530
- return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
1605
+ return { status: 201, body: { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
1531
1606
  });
1532
1607
  return send(res, answer.status, answer.body, answer.headers);
1533
1608
  }
@@ -1536,13 +1611,13 @@ async function startHolding(options, data, lock, checked, stops) {
1536
1611
  const offset = cursorOf(url.searchParams.get("cursor"));
1537
1612
  const archived = archivedParam(url);
1538
1613
  const all = (await agents.list()).filter((entry) => Boolean(entry.agent.archivedAt) === archived);
1539
- return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await signIns.view(entry.agent.id)))), next_cursor: nextCursor(offset + limit, all.length) });
1614
+ return send(res, 200, { agents: await Promise.all(all.slice(offset, offset + limit).map(async (entry) => agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)))), next_cursor: nextCursor(offset + limit, all.length) });
1540
1615
  }
1541
1616
  case "getAgent": {
1542
1617
  const entry = await needAgent(id);
1543
1618
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
1544
1619
  const tools = entry.revision ? agentTools(env, settings.get(), await toolingOf(entry.revision), caps.tools.map((tool) => tool.name)) : [];
1545
- return send(res, 200, { ...agentView(entry, await signIns.view(entry.agent.id)), tools }, { etag: etagOf(entry) });
1620
+ return send(res, 200, { ...agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), tools }, { etag: etagOf(entry) });
1546
1621
  }
1547
1622
  case "updateDefinition": {
1548
1623
  const entry = await needAgent(id);
@@ -1565,7 +1640,7 @@ async function startHolding(options, data, lock, checked, stops) {
1565
1640
  let warnings = [];
1566
1641
  const check = async (revision) => void (warnings = await saveable(revision));
1567
1642
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
1568
- return send(res, 200, { ...agentView(edited, await signIns.view(edited.agent.id)), warnings }, { etag: etagOf(edited) });
1643
+ return send(res, 200, { ...agentView(edited, await signIns.view(edited.agent.id), await learningOfAgent(edited)), warnings }, { etag: etagOf(edited) });
1569
1644
  }
1570
1645
  case "listRevisions": {
1571
1646
  const entry = await needAgent(id);
@@ -1587,7 +1662,7 @@ async function startHolding(options, data, lock, checked, stops) {
1587
1662
  if (!(await agents.revision(id, revision)))
1588
1663
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
1589
1664
  const moved = await agents.setCurrent(entry, revision);
1590
- return send(res, 200, agentView(moved, await signIns.view(moved.agent.id)), { etag: etagOf(moved) });
1665
+ return send(res, 200, agentView(moved, await signIns.view(moved.agent.id), await learningOfAgent(moved)), { etag: etagOf(moved) });
1591
1666
  }
1592
1667
  case "archiveAgent":
1593
1668
  case "unarchiveAgent": {
@@ -1596,7 +1671,7 @@ async function startHolding(options, data, lock, checked, stops) {
1596
1671
  if (found.name === "archiveAgent")
1597
1672
  await runs.archived();
1598
1673
  const entry = await needAgent(id);
1599
- return send(res, 200, agentView(entry, await signIns.view(entry.agent.id)), { etag: etagOf(entry) });
1674
+ return send(res, 200, agentView(entry, await signIns.view(entry.agent.id), await learningOfAgent(entry)), { etag: etagOf(entry) });
1600
1675
  }
1601
1676
  case "forgetSignIn": {
1602
1677
  await needAgent(id);
@@ -1767,7 +1842,7 @@ async function startHolding(options, data, lock, checked, stops) {
1767
1842
  const { issues, warnings } = await workflowIssues(body.workflow, body.tools);
1768
1843
  // What a save refuses on this host (a model node's tool, a code node where none runs), and what it lacks yet.
1769
1844
  if (!issues.length) {
1770
- for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers }).catch(() => [])) {
1845
+ for (const blocker of await blockersOf(env, { kind: "workflow", workflow: body.workflow, ...(body.tools ? { tools: body.tools } : {}) }, settings.get(), { offers, mcp: mcpTools }).catch(() => [])) {
1771
1846
  if (blocker.host)
1772
1847
  warnings.push(blocker.message);
1773
1848
  else
@@ -1903,11 +1978,12 @@ async function startHolding(options, data, lock, checked, stops) {
1903
1978
  return sendNote(res, 200, await readNote(data, id, second, secretsShown(learningSecrets())));
1904
1979
  case "writeLearningFile":
1905
1980
  case "retireLearningFile":
1906
- case "approveLearningFile": {
1981
+ case "approveLearningFile":
1982
+ case "restoreLearningFile": {
1907
1983
  await needAgent(id);
1908
1984
  const header = (name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
1909
1985
  const body = found.name === "writeLearningFile" ? await noteBody(req, MAX_BODY) : undefined;
1910
- const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile" });
1986
+ const written = await writeNote(data, id, second, { ifMatch: header("if-match"), ifNoneMatch: header("if-none-match"), body, refuse: learningSecrets(), approve: found.name === "approveLearningFile", restore: found.name === "restoreLearningFile" });
1911
1987
  // A name holding a secret (one the checks let by) is never echoed, not even as where the note is.
1912
1988
  const shown = secretsShown(learningSecrets());
1913
1989
  const located = written.status === 201 && shown.name(written.file) === written.file;
@@ -2003,9 +2079,13 @@ async function startHolding(options, data, lock, checked, stops) {
2003
2079
  catch {
2004
2080
  return fail(new ApiError("bad_request", "the request target is not a URL"));
2005
2081
  }
2006
- // On loopback, a Host that is not a loopback name is a page that rebound a name of its own to this address.
2007
- if (names && !names.has(String(req.headers.host ?? "").toLowerCase()))
2008
- return fail(new ApiError("forbidden", "unexpected Host header"));
2082
+ // On loopback, a Host that is not one of its names (host-check.ts) is a page that rebound a name of its own to this
2083
+ // address. A browser is shown a page that says which names work; a script, the same in the error.
2084
+ if (names && !names.has(hostName(req.headers.host) ?? "")) {
2085
+ if (/\btext\/html\b/i.test(String(req.headers.accept ?? "")))
2086
+ return sendHostRefused(req, res);
2087
+ return fail(new ApiError("forbidden", `unexpected Host header: ${HOST_FIX}`));
2088
+ }
2009
2089
  // Routed on the path as sent: a parsed URL folds `..` and `%2E%2E` segments away, and a file path must see them.
2010
2090
  const raw = (req.url ?? "/").split("?")[0];
2011
2091
  // Before the page: its cookie must not stand in for the token on the owner's own routes, nor on the MCP endpoint.
@@ -2055,7 +2135,7 @@ async function startHolding(options, data, lock, checked, stops) {
2055
2135
  countSessions();
2056
2136
  const address = server.address();
2057
2137
  if (isLoopback(host))
2058
- names = new Set(["localhost", "127.0.0.1", "[::1]", host, ...(options.allowHosts ?? [])].map((h) => `${h.toLowerCase()}:${address.port}`));
2138
+ names = loopbackNames(host, options.allowHosts, options.publicUrl);
2059
2139
  // An address of every interface is reached on this machine at its loopback one.
2060
2140
  const shown = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
2061
2141
  const url = `http://${shown.includes(":") ? `[${shown}]` : shown}:${address.port}`;
@@ -2096,6 +2176,8 @@ async function startHolding(options, data, lock, checked, stops) {
2096
2176
  await relay?.close();
2097
2177
  // Before the lock goes: the image's last record lands first (box-image.ts), never after the next server's start.
2098
2178
  await image?.close();
2179
+ // The box network proxy goes with the server that owns it (box-egress-vm.ts); its volume stays for the next start.
2180
+ await egress?.close();
2099
2181
  await webhooks.close();
2100
2182
  await new Promise((done) => (server.close(done), server.closeAllConnections()));
2101
2183
  agents.close();
@@ -2110,7 +2192,7 @@ async function startHolding(options, data, lock, checked, stops) {
2110
2192
  tokenFile,
2111
2193
  tokenMade: stored?.made ?? false,
2112
2194
  ...(setupUrl ? { setupUrl } : {}),
2113
- boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow),
2195
+ boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
2114
2196
  // Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
2115
2197
  // never writes this data root's record again (the next server's, by then).
2116
2198
  close: () => (stopped ??= stop()),
@@ -14,8 +14,13 @@ export declare const isCatalogTool: (name: string) => boolean;
14
14
  /** The owner's defaults (11-01): a built-in kernel tool allow; a third-party catalog tool ask. */
15
15
  export declare const defaultPermission: (name: string) => Permission;
16
16
  /** The tools that run a command in the run's box (background.ts SHELL_TOOLS), each held to bash's setting: bash: deny
17
- * refuses bash_background as it refuses bash, and none of them is a settings key of its own. */
17
+ * refuses bash_background as it refuses bash, and none of them is a settings key of its own. Under bash: ask the
18
+ * watchers (SHELL_WATCHERS) run unasked. */
18
19
  export declare const SHELL_FAMILY: Readonly<Record<string, string>>;
20
+ /** The shell tools that only watch or end a process the run already started, by its own id (background.ts: an id is
21
+ * digits under the run's own work/background/, and another's is "no background process"): under bash: ask they run
22
+ * unasked, so watching an approved process costs no approval per page. bash: deny still refuses them. */
23
+ export declare const SHELL_WATCHERS: ReadonlySet<string>;
19
24
  /** The settings keys that may set `name`'s permission, most specific first: the tool's own name, then, for an MCP
20
25
  * tool, its server's wildcard `mcp:<server>/*`. */
21
26
  export declare function permissionKeys(name: string): string[];
@@ -25,12 +30,14 @@ export declare function permissionKeys(name: string): string[];
25
30
  * wire name) and on OpenCode `<server>_<tool>`, is `mcp:<server>/<tool>`; a catalog's wire name (`monid_run`) is its
26
31
  * catalog name; the browser's registrations are `browser`. OpenCode's `<server>_<tool>` maps only for a server of
27
32
  * `mcpServers` (the run's configured MCP servers), never by its shape, since a host tool's name has the same shape.
28
- * Undefined: nothing maps it, and the gate asks. The key only: an MCP call enters the gate once, in the MCP gateway. */
33
+ * Undefined: nothing maps it, and the gate asks. The key only: an MCP call enters the gate once, in the MCP gateway for a
34
+ * registration it marks (GATED_BY_GATEWAY), else where its tool is wrapped. */
29
35
  export declare function settingsKeyOf(harness: string, name: string, mcpServers?: readonly string[]): string | undefined;
30
36
  /** A layer of tool settings (the server's, PUT /v2/settings/tools, or an agent's own, definition.tool_settings) as the
31
37
  * gate reads it: a permission by settings key. */
32
38
  export type PermissionSettings = Readonly<Record<string, {
33
- permission?: Permission;
39
+ permission?: Permission; /** Not as written: a value not offered, read as its fail-closed stand-in (tool-plane.ts readToolSettings). Never shown. */
40
+ fallback?: true;
34
41
  } | undefined>>;
35
42
  /** `name`'s permission in force and the layer it came from, most specific first: the agent's exact key, the agent's
36
43
  * server wildcard, the server's exact key, the server's server wildcard, then the default. Rules over a call's
@@ -88,6 +95,14 @@ export type Entered = undefined | (ToolAnswer & {
88
95
  * call's deadline: the gate puts no wall-clock bound on it (only a stop or a cancel cuts it, through `signal`), so an
89
96
  * executor bounds its own work and answers a timeout as an error result (`isError: true`), never by waiting on. */
90
97
  export type Executor = (tool: string, args: unknown, callId: string, signal: AbortSignal) => Promise<ToolAnswer>;
98
+ /** The mark a tool registration carries when its calls are gated by whoever registered it (the MCP gateway, which marks
99
+ * its registrations only when it holds this run's gate and park, and enters the gate in each call): RunGate.extension
100
+ * does not wrap it again. `Symbol.for`, so the mark is the same symbol whichever copy of this module set or reads it. */
101
+ export declare const GATED_BY_GATEWAY: unique symbol;
102
+ /** A registration that may carry GATED_BY_GATEWAY. */
103
+ export type GatewayMarked = ToolRegistration & {
104
+ [GATED_BY_GATEWAY]?: true;
105
+ };
91
106
  /** The gate of one run, in the run's process. */
92
107
  export interface Gate {
93
108
  /** One model-initiated call at the gate: allow, deny, or ask, which parks (see the header). */
package/dist/tool-gate.js CHANGED
@@ -55,7 +55,8 @@ export const isCatalogTool = (name) => name.startsWith("monid.") || isMcpTool(na
55
55
  /** The owner's defaults (11-01): a built-in kernel tool allow; a third-party catalog tool ask. */
56
56
  export const defaultPermission = (name) => (isCatalogTool(name) ? "ask" : "allow");
57
57
  /** The tools that run a command in the run's box (background.ts SHELL_TOOLS), each held to bash's setting: bash: deny
58
- * refuses bash_background as it refuses bash, and none of them is a settings key of its own. */
58
+ * refuses bash_background as it refuses bash, and none of them is a settings key of its own. Under bash: ask the
59
+ * watchers (SHELL_WATCHERS) run unasked. */
59
60
  export const SHELL_FAMILY = Object.freeze(Object.fromEntries(SHELL_TOOLS.map((name) => [name, "bash"])));
60
61
  /** The shell tool a call named `name` is, under claude-agent's host-tool name too (`mcp__hands__bash_background`), when
61
62
  * it is one held to another's setting: its own name, which its request, its refusal and its approved call keep. */
@@ -63,6 +64,12 @@ const shellToolOf = (name) => {
63
64
  const own = name.replace(/^mcp__hands__/, "");
64
65
  return Object.hasOwn(SHELL_FAMILY, own) && SHELL_FAMILY[own] !== own ? own : undefined;
65
66
  };
67
+ /** The shell tools that only watch or end a process the run already started, by its own id (background.ts: an id is
68
+ * digits under the run's own work/background/, and another's is "no background process"): under bash: ask they run
69
+ * unasked, so watching an approved process costs no approval per page. bash: deny still refuses them. */
70
+ export const SHELL_WATCHERS = new Set(["bash_output", "bash_list", "bash_signal"]);
71
+ /** Shell tool `name`'s permission, given bash's: a watcher's ask is allow; any other keeps bash's. */
72
+ const shellPermission = (name, bash) => (bash === "ask" && SHELL_WATCHERS.has(name) ? "allow" : bash);
66
73
  /** The settings keys that may set `name`'s permission, most specific first: the tool's own name, then, for an MCP
67
74
  * tool, its server's wildcard `mcp:<server>/*`. */
68
75
  export function permissionKeys(name) {
@@ -86,7 +93,8 @@ const HOST_TOOLS_SERVER = "hands";
86
93
  * wire name) and on OpenCode `<server>_<tool>`, is `mcp:<server>/<tool>`; a catalog's wire name (`monid_run`) is its
87
94
  * catalog name; the browser's registrations are `browser`. OpenCode's `<server>_<tool>` maps only for a server of
88
95
  * `mcpServers` (the run's configured MCP servers), never by its shape, since a host tool's name has the same shape.
89
- * Undefined: nothing maps it, and the gate asks. The key only: an MCP call enters the gate once, in the MCP gateway. */
96
+ * Undefined: nothing maps it, and the gate asks. The key only: an MCP call enters the gate once, in the MCP gateway for a
97
+ * registration it marks (GATED_BY_GATEWAY), else where its tool is wrapped. */
90
98
  export function settingsKeyOf(harness, name, mcpServers = []) {
91
99
  // A legacy name the tool plane folds into a capability (fetch_page into web_fetch) is held to that capability's key,
92
100
  // and a tool that runs a command in the box (bash_background and the rest) to bash's: before the table's own names.
@@ -114,21 +122,39 @@ export function settingsKeyOf(harness, name, mcpServers = []) {
114
122
  * server wildcard, the server's exact key, the server's server wildcard, then the default. Rules over a call's
115
123
  * arguments are not in V1. */
116
124
  export function permissionFrom(name, server, agent = {}) {
117
- // A shell tool's permission is bash's (SHELL_FAMILY), wherever it is read: the gate, capabilities, an agent's tools.
118
- if (Object.hasOwn(SHELL_FAMILY, name) && SHELL_FAMILY[name] !== name)
119
- return permissionFrom(SHELL_FAMILY[name], server, agent);
125
+ // A shell tool's permission is bash's (SHELL_FAMILY), from bash's layer, wherever it is read: the gate, capabilities, an
126
+ // agent's tools. A watcher (SHELL_WATCHERS) runs unasked only under an ask set as written in a layer: an ask that stands
127
+ // in for anything else (a value not offered, nothing set) stays an ask. No key of its own is read, so none lifts bash's.
128
+ if (Object.hasOwn(SHELL_FAMILY, name) && SHELL_FAMILY[name] !== name) {
129
+ const bash = settingFrom(SHELL_FAMILY[name], server, agent);
130
+ return { permission: bash.written ? shellPermission(name, bash.permission) : bash.permission, from: bash.from };
131
+ }
132
+ const { permission, from } = settingFrom(name, server, agent);
133
+ return { permission, from };
134
+ }
135
+ /** permissionFrom's own read, and whether the permission is `written`: a valid one set in a layer as it reads there, not
136
+ * a stand-in. A value that is no permission at all reads ask, never the value. */
137
+ function settingFrom(name, server, agent) {
120
138
  for (const [from, layer] of [["agent", agent], ["server", server]]) {
121
139
  for (const key of permissionKeys(name)) {
122
- const set = layer[key]?.permission;
123
- if (set)
124
- return { permission: set, from };
140
+ const setting = layer[key];
141
+ const set = setting?.permission;
142
+ if (!set)
143
+ continue;
144
+ if (!PERMISSIONS.includes(set))
145
+ return { permission: "ask", from, written: false };
146
+ return { permission: set, from, written: setting.fallback !== true };
125
147
  }
126
148
  }
127
- return { permission: defaultPermission(name), from: "default" };
149
+ return { permission: defaultPermission(name), from: "default", written: false };
128
150
  }
129
151
  /** `name`'s permission in force (permissionFrom): the one rule every path reads, the gate's, the tool plane's and a
130
152
  * workflow's call nodes'. */
131
153
  export const permissionOf = (name, server, agent = {}) => permissionFrom(name, server, agent).permission;
154
+ /** The mark a tool registration carries when its calls are gated by whoever registered it (the MCP gateway, which marks
155
+ * its registrations only when it holds this run's gate and park, and enters the gate in each call): RunGate.extension
156
+ * does not wrap it again. `Symbol.for`, so the mark is the same symbol whichever copy of this module set or reads it. */
157
+ export const GATED_BY_GATEWAY = Symbol.for("agentrun.gatedByGateway");
132
158
  /** The refusal of a call whose tool is set to deny; of one held to another tool's setting (`heldTo`, a shell tool's
133
159
  * bash), naming the setting to change. */
134
160
  export const deniedText = (tool, heldTo) => heldTo && heldTo !== tool ? `Permission denied: ${tool} follows ${heldTo}'s setting, which is deny on this server. Don't retry it.` : `Permission denied: ${tool} is set to deny on this server. Don't retry it.`;
@@ -243,10 +269,13 @@ export class RunGate {
243
269
  if (key === undefined)
244
270
  return "ask";
245
271
  const server = this.serverSettings();
246
- // No settings ever read: every tool asks, or keeps the revision's own deny.
272
+ // No settings ever read: every tool asks, the shell watchers too (fail closed: an ask nothing read is never lifted),
273
+ // or keeps the revision's own deny.
247
274
  if (server === undefined)
248
275
  return permissionOf(key, {}, this.overrides) === "deny" ? "deny" : "ask";
249
- return permissionOf(key, server, this.overrides);
276
+ // A shell tool under every harness's name for it is read as its own name, by bash's key (permissionFrom): a watcher's
277
+ // ask is allow only where bash's ask is set as written.
278
+ return permissionOf(shellToolOf(tool) ?? key, server, this.overrides);
250
279
  };
251
280
  lastGood;
252
281
  told = new Set();
@@ -321,8 +350,10 @@ export class RunGate {
321
350
  /** pi's `tools` behind the gate: wraps, by name, for the run's registry, which apply wherever it is selected (every
322
351
  * agent selects it: the root by default, a workflow's model node by name, app.ts). */
323
352
  extension(tools) {
324
- // pi's MCP tools (mcp__<server>__<tool>) are gated by the MCP gateway itself, inside their execute: not wrapped here.
325
- const named = [...new Map(tools.filter((tool) => !tool.name.startsWith("mcp__")).map((tool) => [tool.name, tool])).values()];
353
+ // Every tool is wrapped, an mcp__ name too, except a registration marked GATED_BY_GATEWAY: the MCP gateway marks the
354
+ // ones whose calls it takes to this gate itself (gate.enter in its call), so such a call passes one gate, once. Nothing
355
+ // is skipped by its name: an unmarked mcp__ tool is gated here as any tool is.
356
+ const named = [...new Map(tools.filter((tool) => tool[GATED_BY_GATEWAY] !== true).map((tool) => [tool.name, tool])).values()];
326
357
  return defineExtension({ name: "tool-gate", wraps: named.map((tool) => wrapTool(tool, (inner) => this.wrap(inner))) });
327
358
  }
328
359
  wrap(tool) {
@@ -5,7 +5,8 @@ export declare const SEAL_KEY_ENV = "AGENTRUN_SEAL_KEY";
5
5
  * and is kept the same way), and what it may unlock: tools by name, and `decisions.<id>`, a workflow's decision
6
6
  * provider. GET lists only those this server binds (unlockedBy), so a name here the server does not bind is never
7
7
  * promised, and one shows by itself once the server binds it. A `tool` key's fields reach only the runs that name a
8
- * tool it unlocks (runs.ts' secretsFor); a key of any other kind (a model's) reaches every run. */
8
+ * tool it unlocks (runs.ts' secretsFor); a key of any other kind (a model's) reaches every run. The tool rows live in
9
+ * key-words.ts (TOOL_KEY_ROWS), whose words name this page where a key is not set. */
9
10
  export declare const TOOL_KEYS: readonly [{
10
11
  readonly id: "parallel";
11
12
  readonly kind: "tool";
package/dist/tool-keys.js CHANGED
@@ -21,6 +21,7 @@ import { HARNESSES } from "./harness.js";
21
21
  import { checkKey } from "./key-check.js";
22
22
  import { toolsView } from "./tools.js";
23
23
  import { MODEL_KEYS } from "./model.js";
24
+ import { TOOL_KEY_ROWS } from "./key-words.js";
24
25
  import { isObject, unknownFields } from "./validate.js";
25
26
  export const TOOL_KEYS_FILE = "tool-keys.json";
26
27
  export const SEAL_KEY_ENV = "AGENTRUN_SEAL_KEY";
@@ -31,15 +32,10 @@ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
31
32
  * and is kept the same way), and what it may unlock: tools by name, and `decisions.<id>`, a workflow's decision
32
33
  * provider. GET lists only those this server binds (unlockedBy), so a name here the server does not bind is never
33
34
  * promised, and one shows by itself once the server binds it. A `tool` key's fields reach only the runs that name a
34
- * tool it unlocks (runs.ts' secretsFor); a key of any other kind (a model's) reaches every run. */
35
+ * tool it unlocks (runs.ts' secretsFor); a key of any other kind (a model's) reaches every run. The tool rows live in
36
+ * key-words.ts (TOOL_KEY_ROWS), whose words name this page where a key is not set. */
35
37
  export const TOOL_KEYS = [
36
- { id: "parallel", kind: "tool", label: "Parallel", fields: ["PARALLEL_API_KEY"], unlocks: ["web_fetch", "web_search", "decisions.parallel"] },
37
- { id: "monid", kind: "tool", label: "Monid", fields: ["MONID_API_KEY"], unlocks: ["monid.discover", "monid.inspect", "monid.run"] },
38
- { id: "browserbase", kind: "tool", label: "Browserbase", fields: ["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"], unlocks: ["browser"] },
39
- // The browser's other vendor (tool-plane.ts BROWSER_KEYS): a run's browser is the one its plane picks.
40
- { id: "kernel", kind: "tool", label: "Kernel", fields: ["KERNEL_API_KEY"], unlocks: ["browser"] },
41
- // Jev's decision provider (decisions.ts' `jev`), on TypeSafe's key: a workflow's judges, as Parallel's key unlocks its.
42
- { id: "typesafe", kind: "tool", label: "TypeSafe (Jev)", fields: ["TYPESAFE_API_KEY"], unlocks: ["decisions.jev"] },
38
+ ...TOOL_KEY_ROWS,
43
39
  // A model provider's key (model.ts' MODEL_KEYS, which give each its default model): every run gets it, as the
44
40
  // launcher's model keys reach every run. Its harnesses are pi and those that talk to the provider's API (MODEL_KEYS).
45
41
  ...MODEL_KEYS.map(({ id, label, field, harnesses }) => ({ id, kind: "model", label, fields: [field], unlocks: [], harnesses })),
@@ -45,7 +45,9 @@ export declare const SERVE_OWN_TOOLS: readonly string[];
45
45
  /** One tool's settings: its provider (a capability that has a choice) and its permission. */
46
46
  export type ToolSetting = {
47
47
  provider?: string;
48
- permission?: Permission;
48
+ permission?: Permission; /** Read as a stand-in for a value not offered (readToolSettings); never shown or written. */
49
+ fallback?: true; /** The stand-in's value as written in the file, which a save that keeps the stand-in writes back (ToolSettings.put). Never shown. */
50
+ raw?: unknown;
49
51
  };
50
52
  /** The tools' settings, the server's (`/v2/settings/tools`) and an agent's own (`definition.tool_settings`), one shape:
51
53
  * by settings key. */
@@ -94,6 +96,8 @@ export declare function explainCapability(capability: Pickable, input: ResolveIn
94
96
  export declare const resolveCapability: (capability: Pickable, input: ResolveInput) => Resolution;
95
97
  export declare const isUnavailable: (resolution: Resolution | undefined) => resolution is `unavailable: ${string}`;
96
98
  /** Why a resolution is unavailable: its words after "unavailable: " (any other resolution as it is). */
99
+ /** Why `resolution` is unavailable, in words. A vendor picked whose key this server does not hold (its value, kept in a
100
+ * run's meta and read back, names the variables) names where to save the key first, then the variable to set. */
97
101
  export declare const whyUnavailable: (resolution: string) => string;
98
102
  /** The keys each of the browser's vendors needs, by name: a tool key's fields (tool-keys.ts), set or saved. Its plane
99
103
  * value is the vendor's id: `kernel` on browser is Kernel's hosted browser, never the guarded fetch web_fetch calls so. */