@draht/coding-agent 2026.10.23 → 2026.10.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 (92) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +10 -0
  3. package/dist/bundle/chunks/{anthropic-messages-VEMVBETR.js → anthropic-messages-OR5LCIS6.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-EXUP6SLM.js → azure-openai-responses-D6DVM232.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/{chunk-CHRFWNPF.js → chunk-7JJWQ53O.js} +81 -77
  7. package/dist/bundle/chunks/{chunk-DHZBWXZK.js → chunk-AEG546ID.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-FXLM6UQV.js → chunk-CKPJSVRD.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-CI37W6HM.js → chunk-DLEJ4D4T.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-QG2WW2SA.js → chunk-JQF3BGRS.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-DLVZ3EK7.js → chunk-NUUJKLOX.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-YSIQCH4Z.js → chunk-QJADVGUY.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-RGI7SF5G.js → chunk-RMLEJL4F.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-JRHPLIE5.js → chunk-X4UBYFTC.js} +1 -1
  15. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-47PK45EQ.js → cloudflare-workers-ai-system-one-YVG4FYXV.js} +1 -1
  16. package/dist/bundle/chunks/{google-generative-ai-PBPH45HB.js → google-generative-ai-IHELIMAC.js} +1 -1
  17. package/dist/bundle/chunks/{google-vertex-ZPCFQNU6.js → google-vertex-3QCFWSNG.js} +1 -1
  18. package/dist/bundle/chunks/{llama-cpp-classify-MWIQKGBR.js → llama-cpp-classify-6J5XKC7Q.js} +1 -1
  19. package/dist/bundle/chunks/{mistral-conversations-7ODWQ37T.js → mistral-conversations-D3JRG6BL.js} +1 -1
  20. package/dist/bundle/chunks/{openai-codex-responses-7Y2SP2GS.js → openai-codex-responses-CBOPSGUQ.js} +1 -1
  21. package/dist/bundle/chunks/{openai-completions-QNWYJ4H4.js → openai-completions-LDMDMEF2.js} +1 -1
  22. package/dist/bundle/chunks/{openai-decisions-4PKBAPR3.js → openai-decisions-NDYRKL2E.js} +1 -1
  23. package/dist/bundle/chunks/{openai-responses-73WU3TQM.js → openai-responses-EZWJOXWT.js} +1 -1
  24. package/dist/bundle/chunks/{openrouter-images-IMWDSQ5F.js → openrouter-images-ZIDF5HXA.js} +1 -1
  25. package/dist/bundle/chunks/{pi-messages-AMNZ7HKZ.js → pi-messages-R75QWB4G.js} +1 -1
  26. package/dist/bundle/chunks/{typesafe-system-one-AXQRIVVX.js → typesafe-system-one-YUNLPYVG.js} +1 -1
  27. package/dist/bundle/chunks/{virtual-modules-Z4F3ZUX3.js → virtual-modules-4DJB4LTP.js} +1 -1
  28. package/dist/bundle/cli-runtime.js +1 -1
  29. package/dist/bundle/index.js +1 -1
  30. package/dist/bundle/rpc-entry.js +1 -1
  31. package/dist/core/agent-session.d.ts.map +1 -1
  32. package/dist/core/agent-session.js +1 -0
  33. package/dist/core/agent-session.js.map +1 -1
  34. package/dist/core/builtins/budget-guidance.d.ts +2 -0
  35. package/dist/core/builtins/budget-guidance.d.ts.map +1 -0
  36. package/dist/core/builtins/budget-guidance.js +2 -0
  37. package/dist/core/builtins/budget-guidance.js.map +1 -0
  38. package/dist/core/builtins/budgets.d.ts +3 -0
  39. package/dist/core/builtins/budgets.d.ts.map +1 -0
  40. package/dist/core/builtins/budgets.js +272 -0
  41. package/dist/core/builtins/budgets.js.map +1 -0
  42. package/dist/core/builtins/index.d.ts.map +1 -1
  43. package/dist/core/builtins/index.js +2 -0
  44. package/dist/core/builtins/index.js.map +1 -1
  45. package/dist/core/builtins/subagent.d.ts +3 -1
  46. package/dist/core/builtins/subagent.d.ts.map +1 -1
  47. package/dist/core/builtins/subagent.js +6 -3
  48. package/dist/core/builtins/subagent.js.map +1 -1
  49. package/dist/core/extensions/loader.d.ts.map +1 -1
  50. package/dist/core/extensions/loader.js +32 -3
  51. package/dist/core/extensions/loader.js.map +1 -1
  52. package/dist/core/extensions/runner.d.ts.map +1 -1
  53. package/dist/core/extensions/runner.js +2 -2
  54. package/dist/core/extensions/runner.js.map +1 -1
  55. package/dist/core/extensions/types.d.ts +9 -1
  56. package/dist/core/extensions/types.d.ts.map +1 -1
  57. package/dist/core/extensions/types.js.map +1 -1
  58. package/dist/core/mcp-servers.d.ts +3 -0
  59. package/dist/core/mcp-servers.d.ts.map +1 -1
  60. package/dist/core/mcp-servers.js.map +1 -1
  61. package/dist/core/multi-agent/permission-gate.d.ts +37 -8
  62. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  63. package/dist/core/multi-agent/permission-gate.js +158 -17
  64. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  65. package/dist/extensions/mcp/config.d.ts +3 -0
  66. package/dist/extensions/mcp/config.d.ts.map +1 -1
  67. package/dist/extensions/mcp/config.js.map +1 -1
  68. package/dist/extensions/mcp/index.d.ts.map +1 -1
  69. package/dist/extensions/mcp/index.js +29 -7
  70. package/dist/extensions/mcp/index.js.map +1 -1
  71. package/dist/extensions/mcp/tools.d.ts +3 -0
  72. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  73. package/dist/extensions/mcp/tools.js +1 -1
  74. package/dist/extensions/mcp/tools.js.map +1 -1
  75. package/dist/hooks/checks/budget-command.md +22 -0
  76. package/dist/hooks/checks/budgets-cl100k.json.gz +0 -0
  77. package/dist/hooks/checks/budgets-runtime.LICENSE +95 -0
  78. package/dist/hooks/checks/budgets-runtime.cjs +3382 -0
  79. package/docs/budgets.md +122 -0
  80. package/docs/docs.json +4 -0
  81. package/docs/environment-variables.md +1 -1
  82. package/docs/extensions.md +3 -1
  83. package/docs/keybindings.md +1 -1
  84. package/docs/mcp.md +13 -1
  85. package/docs/slash-commands.md +1 -0
  86. package/eval/drahtbank/runtime-checks.d.mts +1 -1
  87. package/eval/drahtbank/runtime-checks.mjs +38 -4
  88. package/hooks/checks/budget-command.md +22 -0
  89. package/hooks/checks/budgets-cl100k.json.gz +0 -0
  90. package/hooks/checks/budgets-runtime.LICENSE +95 -0
  91. package/hooks/checks/budgets-runtime.cjs +3382 -0
  92. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-servers.js","sourceRoot":"","sources":["../../src/core/mcp-servers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;GAGG;AACH,SAAS,iBAAiB,CAAC,OAAe;IACzC,MAAM,MAAM,GAAG,OAAO;SACpB,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;SACzD,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,OAAO,IAAI,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;AAClC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,qBAAqB,CAAC,OAA0B;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IACvF,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,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AC,CAAC,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5G,CAAC;IAED,iGAAiG;IACjG,iBAAiB,CAAC,QAAkC;QACnD,IAAI,CAAC,cAAc,GAAG,QAAQ,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * MCP server configuration and the servers extensions register with `pi.registerMcpServer()`.\n *\n * The core only validates and stores registrations. The MCP extension (built in, or another\n * extension that handles `mcp_servers_change`) connects them next to the servers from `mcp.json`.\n */\n\n/**\n * Regular expression for a tool name pattern where `*` matches any characters, as `toolExposure`,\n * `--tools`, and `--exclude-tools` accept them.\n */\nfunction toolPatternRegExp(pattern: string): RegExp {\n\tconst source = pattern\n\t\t.split(\"*\")\n\t\t.map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n\t\t.join(\".*\");\n\treturn new RegExp(`^${source}$`);\n}\n\n/** Whether a tool name matches any of the entries, each an exact name or a pattern. */\nexport function createToolNameMatcher(entries: readonly string[]): (name: string) => boolean {\n\tconst names = new Set(entries.filter((entry) => !entry.includes(\"*\")));\n\tconst patterns = entries.filter((entry) => entry.includes(\"*\")).map(toolPatternRegExp);\n\treturn (name) => names.has(name) || patterns.some((pattern) => pattern.test(name));\n}\n\n/** MCP resource tools, which reach every server with resources. */\nexport const LIST_MCP_RESOURCES_TOOL = \"list_mcp_resources\";\nexport const LIST_MCP_RESOURCE_TEMPLATES_TOOL = \"list_mcp_resource_templates\";\nexport const READ_MCP_RESOURCE_TOOL = \"read_mcp_resource\";\n\nconst MCP_RESOURCE_TOOLS: ReadonlySet<string> = new Set([\n\tLIST_MCP_RESOURCES_TOOL,\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n]);\n\n/** Whether a tool comes from MCP: a server tool (`mcp__<server>__<tool>`) or a resource tool. */\nexport function isMcpToolName(name: string): boolean {\n\treturn name.startsWith(\"mcp__\") || MCP_RESOURCE_TOOLS.has(name);\n}\n\n/**\n * - `codemode`: tools are callable from codemode scripts but neither declared to the model nor\n * listed in the codemode description, which lists only the server's namespace. Scripts find them\n * with `searchTools()`. `codemode-deferred` is accepted as an alias.\n * - `deferred`: not declared to the model until the `tool_search` tool loads them; the model then\n * calls them directly. Does not need codemode.\n * - `direct`: tools are declared to the model like any other tool (and callable from codemode).\n * - `hidden`: tools are registered but unreachable.\n */\nexport type McpExposure = \"codemode\" | \"deferred\" | \"direct\" | \"hidden\";\n\nconst MCP_EXPOSURES: readonly string[] = [\"codemode\", \"deferred\", \"direct\", \"hidden\"] satisfies McpExposure[];\n\n/** Older exposure names, accepted in configs and replaced by their current name when validated. */\nconst MCP_EXPOSURE_ALIASES: Readonly<Record<string, McpExposure>> = { \"codemode-deferred\": \"codemode\" };\n\ninterface McpServerConfigBase {\n\t/** Default: `codemode`. */\n\texposure?: McpExposure;\n\t/**\n\t * What the server offers, in a sentence. The `mcp_servers` system prompt section lists the server\n\t * with it, tool search ranks the server's tools by it, and codemode's `describeNamespace()` returns it.\n\t */\n\tdescription?: string;\n\t/**\n\t * Exposure of single tools, overriding `exposure`. Keys are tool names as the server offers them,\n\t * or patterns where `*` matches any characters. An exact name wins over patterns; among patterns\n\t * the first match in the object wins. `hidden` removes tools, so `\"exposure\": \"hidden\"` with\n\t * overrides for a few tools exposes only those.\n\t */\n\ttoolExposure?: Record<string, McpExposure>;\n\t/** Set to false to keep the entry without connecting. Default: true. */\n\tenabled?: boolean;\n\t/** Per-request timeout in seconds. Progress notifications from the server reset it. Default: 60. */\n\ttimeout?: number;\n}\n\nexport interface McpStdioServerConfig extends McpServerConfigBase {\n\ttype?: \"stdio\";\n\tcommand: string;\n\targs?: string[];\n\t/** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\tenv?: Record<string, string>;\n\t/** Relative paths resolve against the session working directory. */\n\tcwd?: string;\n}\n\n/** OAuth client settings for servers that do not support dynamic client registration. */\nexport interface McpOAuthConfig {\n\t/** Pre-registered client id. Without it, pi registers a client with the authorization server. */\n\tclientId?: string;\n\t/** May reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\tclientSecret?: string;\n\t/**\n\t * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without\n\t * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`.\n\t */\n\tcallbackPort?: number;\n\t/**\n\t * Redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`. It must\n\t * be an `http` URI on `localhost`, `127.0.0.1`, or `[::1]`. Without a port, the callback server\n\t * listens on `callbackPort` or a free port, which is added to the URI (RFC 8252).\n\t */\n\tcallbackUrl?: string;\n\t/** Scopes to request, separated by spaces. Default: the scopes the server advertises. */\n\tscope?: string;\n\t/**\n\t * `client_name` sent with dynamic client registration, for servers that only accept known clients.\n\t * Default: `APP_NAME` (`draht`).\n\t */\n\tclientName?: string;\n\t/**\n\t * How draht identifies itself without `clientId`. `dcr` (default): dynamic client registration.\n\t * `cimd`: an operator-hosted Client ID Metadata Document under `clientMetadataBaseUrl`. The server\n\t * must support it for public clients, and the callback must use the default path `/callback`.\n\t */\n\tclientRegistration?: \"dcr\" | \"cimd\";\n\t/** Required for `cimd`: HTTPS metadata service base, without userinfo, query, or fragment. No default. */\n\tclientMetadataBaseUrl?: string;\n\t/**\n\t * Authorization server metadata document (RFC 8414 or OpenID Connect discovery) to use instead of\n\t * discovery through the server, for servers that advertise a wrong authorization server or none.\n\t * The document is trusted as configured. Must use https, except on loopback hosts.\n\t */\n\tauthServerMetadataUrl?: string;\n}\n\nconst LOOPBACK_HOSTS = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\n\n/** Whether a redirect URI can be served by pi's loopback callback server. */\nexport function isLoopbackRedirectUri(value: string): boolean {\n\tif (!URL.canParse(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === \"\" && url.hash === \"\";\n}\n\nexport interface McpHttpServerConfig extends McpServerConfigBase {\n\ttype?: \"http\";\n\turl: string;\n\t/** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\theaders?: Record<string, string>;\n\toauth?: McpOAuthConfig;\n\t/**\n\t * Send the token of a pi provider (`/login <provider>`) instead of using OAuth. Not allowed in project\n\t * `mcp.json` files, and requires https except on loopback hosts, since it sends the credential to `url`.\n\t */\n\tauth?: { provider: string };\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;\n\nconst SERVER_NAME = /^[A-Za-z0-9_-]+$/;\n\n/** Namespace of a server's tools: `mcp__<server>` with `-` replaced by `_`, like the tool names. */\nexport function mcpNamespace(server: string): string {\n\treturn `mcp__${server.replace(/-/g, \"_\")}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn isRecord(value) && Object.values(value).every((entry) => typeof entry === \"string\");\n}\n\nfunction validateOAuth(value: unknown): McpOAuthConfig | string | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) return \"oauth must be an object\";\n\tif (value.clientId !== undefined && typeof value.clientId !== \"string\") return \"oauth.clientId must be a string\";\n\tif (value.clientSecret !== undefined && typeof value.clientSecret !== \"string\") {\n\t\treturn \"oauth.clientSecret must be a string\";\n\t}\n\tconst port = value.callbackPort;\n\tif (port !== undefined && (typeof port !== \"number\" || !Number.isInteger(port) || port < 1 || port > 65535)) {\n\t\treturn \"oauth.callbackPort must be a port number\";\n\t}\n\tif (value.callbackUrl !== undefined) {\n\t\tif (typeof value.callbackUrl !== \"string\" || !isLoopbackRedirectUri(value.callbackUrl)) {\n\t\t\treturn \"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment\";\n\t\t}\n\t\tconst urlPort = new URL(value.callbackUrl).port;\n\t\tif (urlPort && port !== undefined && Number(urlPort) !== port) {\n\t\t\treturn \"oauth.callbackUrl and oauth.callbackPort name different ports\";\n\t\t}\n\t}\n\tif (value.scope !== undefined && typeof value.scope !== \"string\") return \"oauth.scope must be a string\";\n\tif (value.clientName !== undefined && (typeof value.clientName !== \"string\" || !value.clientName.trim())) {\n\t\treturn \"oauth.clientName must be a non-empty string\";\n\t}\n\tif (value.clientRegistration !== undefined && value.clientRegistration !== \"dcr\") {\n\t\tif (value.clientRegistration !== \"cimd\") return 'oauth.clientRegistration must be \"dcr\" or \"cimd\"';\n\t\tif (value.clientId !== undefined || value.clientName !== undefined || value.clientSecret !== undefined) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret';\n\t\t}\n\t\tconst callback = typeof value.callbackUrl === \"string\" ? new URL(value.callbackUrl) : undefined;\n\t\tif (callback && (callback.hostname === \"[::1]\" || callback.pathname !== \"/callback\")) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';\n\t\t}\n\t}\n\tlet clientMetadataBaseUrl: string | undefined;\n\tif (value.clientRegistration === \"cimd\") {\n\t\tconst base = value.clientMetadataBaseUrl;\n\t\tconst url = typeof base === \"string\" && URL.canParse(base) ? new URL(base) : undefined;\n\t\tif (\n\t\t\t!url ||\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.href.includes(\"?\") ||\n\t\t\turl.href.includes(\"#\")\n\t\t) {\n\t\t\treturn 'oauth.clientMetadataBaseUrl is required for \"cimd\" and must be an absolute HTTPS URL without userinfo, query, or fragment';\n\t\t}\n\t\turl.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/`;\n\t\tclientMetadataBaseUrl = url.href;\n\t} else if (value.clientMetadataBaseUrl !== undefined) {\n\t\treturn 'oauth.clientMetadataBaseUrl requires oauth.clientRegistration \"cimd\"';\n\t}\n\tconst metadataUrl = value.authServerMetadataUrl;\n\tif (metadataUrl !== undefined) {\n\t\tconst url = typeof metadataUrl === \"string\" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;\n\t\tif (!url || !(url.protocol === \"https:\" || (url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname)))) {\n\t\t\treturn \"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]\";\n\t\t}\n\t}\n\treturn { ...value, ...(clientMetadataBaseUrl ? { clientMetadataBaseUrl } : {}) } as McpOAuthConfig;\n}\n\nfunction isExposure(value: unknown): value is McpExposure {\n\treturn typeof value === \"string\" && MCP_EXPOSURES.includes(value);\n}\n\n/** The exposure an alias stands for; other values are returned unchanged. */\nfunction resolveExposureAlias(value: unknown): unknown {\n\treturn typeof value === \"string\" ? (MCP_EXPOSURE_ALIASES[value] ?? value) : value;\n}\n\n/** A copy of the server entry with exposure aliases replaced by their current names. */\nfunction resolveExposureAliases(value: Record<string, unknown>): Record<string, unknown> {\n\tconst { exposure, toolExposure } = value;\n\tconst resolved: Record<string, unknown> = { ...value };\n\tif (exposure !== undefined) resolved.exposure = resolveExposureAlias(exposure);\n\tif (isRecord(toolExposure)) {\n\t\tresolved.toolExposure = Object.fromEntries(\n\t\t\tObject.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposureAlias(entry)]),\n\t\t);\n\t}\n\treturn resolved;\n}\n\n/** Exposure of one tool of a server: its `toolExposure` entry, else the server's `exposure`. */\nexport function getMcpToolExposure(config: McpServerConfig, toolName: string): McpExposure {\n\tconst overrides = config.toolExposure ?? {};\n\tconst exact = overrides[toolName];\n\tif (exact !== undefined) return exact;\n\tfor (const [pattern, exposure] of Object.entries(overrides)) {\n\t\tif (pattern.includes(\"*\") && toolPatternRegExp(pattern).test(toolName)) return exposure;\n\t}\n\treturn config.exposure ?? \"codemode\";\n}\n\n/**\n * Validate one server entry of the `mcpServers` shape. Returns a copy of the config with exposure\n * aliases resolved, or an error message.\n */\nexport function validateMcpServerConfig(name: string, raw: unknown): McpServerConfig | string {\n\tif (!SERVER_NAME.test(name)) return `invalid server name \"${name}\" (use letters, digits, \"_\" and \"-\")`;\n\tif (!isRecord(raw)) return `server \"${name}\" must be an object`;\n\tconst value = resolveExposureAliases(raw);\n\tconst { type, exposure, enabled, timeout, toolExposure, description } = value;\n\tconst exposures = MCP_EXPOSURES.map((value) => `\"${value}\"`).join(\", \");\n\tif (exposure !== undefined && !isExposure(exposure)) {\n\t\treturn `server \"${name}\": exposure must be one of ${exposures}`;\n\t}\n\tif (toolExposure !== undefined) {\n\t\tif (!isRecord(toolExposure)) return `server \"${name}\": toolExposure must map tool names to exposures`;\n\t\tfor (const [tool, value] of Object.entries(toolExposure)) {\n\t\t\tif (!isExposure(value)) return `server \"${name}\": toolExposure \"${tool}\" must be one of ${exposures}`;\n\t\t}\n\t}\n\tif (enabled !== undefined && typeof enabled !== \"boolean\") return `server \"${name}\": enabled must be a boolean`;\n\tif (description !== undefined && typeof description !== \"string\") {\n\t\treturn `server \"${name}\": description must be a string`;\n\t}\n\tif (timeout !== undefined && (typeof timeout !== \"number\" || !(timeout > 0))) {\n\t\treturn `server \"${name}\": timeout must be a positive number of seconds`;\n\t}\n\tif (type === \"sse\") return `server \"${name}\": legacy SSE transport is not supported; use the streamable HTTP URL`;\n\n\tif (typeof value.url === \"string\" && (type === undefined || type === \"http\" || type === \"streamable-http\")) {\n\t\tif (!URL.canParse(value.url) || !/^https?:$/.test(new URL(value.url).protocol)) {\n\t\t\treturn `server \"${name}\": url must be an http or https URL`;\n\t\t}\n\t\tif (value.headers !== undefined && !isStringRecord(value.headers)) {\n\t\t\treturn `server \"${name}\": headers must map names to strings`;\n\t\t}\n\t\tconst oauth = validateOAuth(value.oauth);\n\t\tif (typeof oauth === \"string\") return `server \"${name}\": ${oauth}`;\n\t\tif (oauth !== undefined) value.oauth = oauth;\n\t\tif (value.auth !== undefined) {\n\t\t\tif (!isRecord(value.auth) || typeof value.auth.provider !== \"string\" || !value.auth.provider) {\n\t\t\t\treturn `server \"${name}\": auth.provider must be a provider name`;\n\t\t\t}\n\t\t\tconst url = new URL(value.url);\n\t\t\tif (url.protocol !== \"https:\" && !LOOPBACK_HOSTS.includes(url.hostname)) {\n\t\t\t\treturn `server \"${name}\": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`;\n\t\t\t}\n\t\t}\n\t\treturn value as unknown as McpHttpServerConfig;\n\t}\n\tif (typeof value.command === \"string\" && (type === undefined || type === \"stdio\")) {\n\t\tif (\n\t\t\tvalue.args !== undefined &&\n\t\t\t!(Array.isArray(value.args) && value.args.every((arg) => typeof arg === \"string\"))\n\t\t) {\n\t\t\treturn `server \"${name}\": args must be an array of strings`;\n\t\t}\n\t\tif (value.env !== undefined && !isStringRecord(value.env))\n\t\t\treturn `server \"${name}\": env must map names to strings`;\n\t\tif (value.cwd !== undefined && typeof value.cwd !== \"string\") return `server \"${name}\": cwd must be a string`;\n\t\treturn value as unknown as McpStdioServerConfig;\n\t}\n\treturn `server \"${name}\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)`;\n}\n\n/** A server an extension registered with `pi.registerMcpServer()`. */\nexport interface RegisteredMcpServer {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Path of the extension that registered the server. */\n\textensionPath: string;\n}\n\n/** Servers registered by the extensions of one runtime. */\nexport class McpServerRegistry {\n\tprivate readonly servers = new Map<string, RegisteredMcpServer>();\n\tprivate changeListener: (() => void) | undefined;\n\n\t/** Register or replace a server. The caller checks ownership. */\n\tregister(server: RegisteredMcpServer): void {\n\t\tthis.servers.set(server.name, server);\n\t\tthis.changeListener?.();\n\t}\n\n\t/** Remove a server registered by `extensionPath`. Servers of other extensions are left alone. */\n\tunregister(name: string, extensionPath: string): void {\n\t\tif (this.servers.get(name)?.extensionPath !== extensionPath) return;\n\t\tthis.servers.delete(name);\n\t\tthis.changeListener?.();\n\t}\n\n\tget(name: string): RegisteredMcpServer | undefined {\n\t\treturn this.servers.get(name);\n\t}\n\n\t/** Copies of the registered servers, in registration order. */\n\tlist(): RegisteredMcpServer[] {\n\t\treturn [...this.servers.values()].map((server) => ({ ...server, config: structuredClone(server.config) }));\n\t}\n\n\t/** Called after every change. The runner sets it when it binds, to emit `mcp_servers_change`. */\n\tsetChangeListener(listener: (() => void) | undefined): void {\n\t\tthis.changeListener = listener;\n\t}\n}\n"]}
1
+ {"version":3,"file":"mcp-servers.js","sourceRoot":"","sources":["../../src/core/mcp-servers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH;;;GAGG;AACH,SAAS,iBAAiB,CAAC,OAAe;IACzC,MAAM,MAAM,GAAG,OAAO;SACpB,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;SACzD,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,OAAO,IAAI,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;AAClC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,qBAAqB,CAAC,OAA0B;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACvE,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IACvF,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACpF,CAAC;AAED,mEAAmE;AACnE,MAAM,CAAC,MAA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AAC,CAAC;IAC5G,CAAC;IAED,iGAAiG;IACjG,iBAAiB,CAAC,QAAkC;QACnD,IAAI,CAAC,cAAc,GAAG,QAAQ,CAAC;IAChC,CAAC;CACD","sourcesContent":["/**\n * MCP server configuration and the servers extensions register with `pi.registerMcpServer()`.\n *\n * The core only validates and stores registrations. The MCP extension (built in, or another\n * extension that handles `mcp_servers_change`) connects them next to the servers from `mcp.json`.\n */\n\nimport type { SourceScope } from \"./source-info.ts\";\n\n/**\n * Regular expression for a tool name pattern where `*` matches any characters, as `toolExposure`,\n * `--tools`, and `--exclude-tools` accept them.\n */\nfunction toolPatternRegExp(pattern: string): RegExp {\n\tconst source = pattern\n\t\t.split(\"*\")\n\t\t.map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\"))\n\t\t.join(\".*\");\n\treturn new RegExp(`^${source}$`);\n}\n\n/** Whether a tool name matches any of the entries, each an exact name or a pattern. */\nexport function createToolNameMatcher(entries: readonly string[]): (name: string) => boolean {\n\tconst names = new Set(entries.filter((entry) => !entry.includes(\"*\")));\n\tconst patterns = entries.filter((entry) => entry.includes(\"*\")).map(toolPatternRegExp);\n\treturn (name) => names.has(name) || patterns.some((pattern) => pattern.test(name));\n}\n\n/** MCP resource tools, which reach every server with resources. */\nexport const LIST_MCP_RESOURCES_TOOL = \"list_mcp_resources\";\nexport const LIST_MCP_RESOURCE_TEMPLATES_TOOL = \"list_mcp_resource_templates\";\nexport const READ_MCP_RESOURCE_TOOL = \"read_mcp_resource\";\n\nconst MCP_RESOURCE_TOOLS: ReadonlySet<string> = new Set([\n\tLIST_MCP_RESOURCES_TOOL,\n\tLIST_MCP_RESOURCE_TEMPLATES_TOOL,\n\tREAD_MCP_RESOURCE_TOOL,\n]);\n\n/** Whether a tool comes from MCP: a server tool (`mcp__<server>__<tool>`) or a resource tool. */\nexport function isMcpToolName(name: string): boolean {\n\treturn name.startsWith(\"mcp__\") || MCP_RESOURCE_TOOLS.has(name);\n}\n\n/**\n * - `codemode`: tools are callable from codemode scripts but neither declared to the model nor\n * listed in the codemode description, which lists only the server's namespace. Scripts find them\n * with `searchTools()`. `codemode-deferred` is accepted as an alias.\n * - `deferred`: not declared to the model until the `tool_search` tool loads them; the model then\n * calls them directly. Does not need codemode.\n * - `direct`: tools are declared to the model like any other tool (and callable from codemode).\n * - `hidden`: tools are registered but unreachable.\n */\nexport type McpExposure = \"codemode\" | \"deferred\" | \"direct\" | \"hidden\";\n\nconst MCP_EXPOSURES: readonly string[] = [\"codemode\", \"deferred\", \"direct\", \"hidden\"] satisfies McpExposure[];\n\n/** Older exposure names, accepted in configs and replaced by their current name when validated. */\nconst MCP_EXPOSURE_ALIASES: Readonly<Record<string, McpExposure>> = { \"codemode-deferred\": \"codemode\" };\n\ninterface McpServerConfigBase {\n\t/** Default: `codemode`. */\n\texposure?: McpExposure;\n\t/**\n\t * What the server offers, in a sentence. The `mcp_servers` system prompt section lists the server\n\t * with it, tool search ranks the server's tools by it, and codemode's `describeNamespace()` returns it.\n\t */\n\tdescription?: string;\n\t/**\n\t * Exposure of single tools, overriding `exposure`. Keys are tool names as the server offers them,\n\t * or patterns where `*` matches any characters. An exact name wins over patterns; among patterns\n\t * the first match in the object wins. `hidden` removes tools, so `\"exposure\": \"hidden\"` with\n\t * overrides for a few tools exposes only those.\n\t */\n\ttoolExposure?: Record<string, McpExposure>;\n\t/** Set to false to keep the entry without connecting. Default: true. */\n\tenabled?: boolean;\n\t/** Per-request timeout in seconds. Progress notifications from the server reset it. Default: 60. */\n\ttimeout?: number;\n}\n\nexport interface McpStdioServerConfig extends McpServerConfigBase {\n\ttype?: \"stdio\";\n\tcommand: string;\n\targs?: string[];\n\t/** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\tenv?: Record<string, string>;\n\t/** Relative paths resolve against the session working directory. */\n\tcwd?: string;\n}\n\n/** OAuth client settings for servers that do not support dynamic client registration. */\nexport interface McpOAuthConfig {\n\t/** Pre-registered client id. Without it, pi registers a client with the authorization server. */\n\tclientId?: string;\n\t/** May reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\tclientSecret?: string;\n\t/**\n\t * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without\n\t * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`.\n\t */\n\tcallbackPort?: number;\n\t/**\n\t * Redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`. It must\n\t * be an `http` URI on `localhost`, `127.0.0.1`, or `[::1]`. Without a port, the callback server\n\t * listens on `callbackPort` or a free port, which is added to the URI (RFC 8252).\n\t */\n\tcallbackUrl?: string;\n\t/** Scopes to request, separated by spaces. Default: the scopes the server advertises. */\n\tscope?: string;\n\t/**\n\t * `client_name` sent with dynamic client registration, for servers that only accept known clients.\n\t * Default: `APP_NAME` (`draht`).\n\t */\n\tclientName?: string;\n\t/**\n\t * How draht identifies itself without `clientId`. `dcr` (default): dynamic client registration.\n\t * `cimd`: an operator-hosted Client ID Metadata Document under `clientMetadataBaseUrl`. The server\n\t * must support it for public clients, and the callback must use the default path `/callback`.\n\t */\n\tclientRegistration?: \"dcr\" | \"cimd\";\n\t/** Required for `cimd`: HTTPS metadata service base, without userinfo, query, or fragment. No default. */\n\tclientMetadataBaseUrl?: string;\n\t/**\n\t * Authorization server metadata document (RFC 8414 or OpenID Connect discovery) to use instead of\n\t * discovery through the server, for servers that advertise a wrong authorization server or none.\n\t * The document is trusted as configured. Must use https, except on loopback hosts.\n\t */\n\tauthServerMetadataUrl?: string;\n}\n\nconst LOOPBACK_HOSTS = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\n\n/** Whether a redirect URI can be served by pi's loopback callback server. */\nexport function isLoopbackRedirectUri(value: string): boolean {\n\tif (!URL.canParse(value)) return false;\n\tconst url = new URL(value);\n\treturn url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === \"\" && url.hash === \"\";\n}\n\nexport interface McpHttpServerConfig extends McpServerConfigBase {\n\ttype?: \"http\";\n\turl: string;\n\t/** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */\n\theaders?: Record<string, string>;\n\toauth?: McpOAuthConfig;\n\t/**\n\t * Send the token of a pi provider (`/login <provider>`) instead of using OAuth. Not allowed in project\n\t * `mcp.json` files, and requires https except on loopback hosts, since it sends the credential to `url`.\n\t */\n\tauth?: { provider: string };\n}\n\nexport type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;\n\nconst SERVER_NAME = /^[A-Za-z0-9_-]+$/;\n\n/** Namespace of a server's tools: `mcp__<server>` with `-` replaced by `_`, like the tool names. */\nexport function mcpNamespace(server: string): string {\n\treturn `mcp__${server.replace(/-/g, \"_\")}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn isRecord(value) && Object.values(value).every((entry) => typeof entry === \"string\");\n}\n\nfunction validateOAuth(value: unknown): McpOAuthConfig | string | undefined {\n\tif (value === undefined) return undefined;\n\tif (!isRecord(value)) return \"oauth must be an object\";\n\tif (value.clientId !== undefined && typeof value.clientId !== \"string\") return \"oauth.clientId must be a string\";\n\tif (value.clientSecret !== undefined && typeof value.clientSecret !== \"string\") {\n\t\treturn \"oauth.clientSecret must be a string\";\n\t}\n\tconst port = value.callbackPort;\n\tif (port !== undefined && (typeof port !== \"number\" || !Number.isInteger(port) || port < 1 || port > 65535)) {\n\t\treturn \"oauth.callbackPort must be a port number\";\n\t}\n\tif (value.callbackUrl !== undefined) {\n\t\tif (typeof value.callbackUrl !== \"string\" || !isLoopbackRedirectUri(value.callbackUrl)) {\n\t\t\treturn \"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment\";\n\t\t}\n\t\tconst urlPort = new URL(value.callbackUrl).port;\n\t\tif (urlPort && port !== undefined && Number(urlPort) !== port) {\n\t\t\treturn \"oauth.callbackUrl and oauth.callbackPort name different ports\";\n\t\t}\n\t}\n\tif (value.scope !== undefined && typeof value.scope !== \"string\") return \"oauth.scope must be a string\";\n\tif (value.clientName !== undefined && (typeof value.clientName !== \"string\" || !value.clientName.trim())) {\n\t\treturn \"oauth.clientName must be a non-empty string\";\n\t}\n\tif (value.clientRegistration !== undefined && value.clientRegistration !== \"dcr\") {\n\t\tif (value.clientRegistration !== \"cimd\") return 'oauth.clientRegistration must be \"dcr\" or \"cimd\"';\n\t\tif (value.clientId !== undefined || value.clientName !== undefined || value.clientSecret !== undefined) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" cannot be combined with oauth.clientId, oauth.clientName, or oauth.clientSecret';\n\t\t}\n\t\tconst callback = typeof value.callbackUrl === \"string\" ? new URL(value.callbackUrl) : undefined;\n\t\tif (callback && (callback.hostname === \"[::1]\" || callback.pathname !== \"/callback\")) {\n\t\t\treturn 'oauth.clientRegistration \"cimd\" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';\n\t\t}\n\t}\n\tlet clientMetadataBaseUrl: string | undefined;\n\tif (value.clientRegistration === \"cimd\") {\n\t\tconst base = value.clientMetadataBaseUrl;\n\t\tconst url = typeof base === \"string\" && URL.canParse(base) ? new URL(base) : undefined;\n\t\tif (\n\t\t\t!url ||\n\t\t\turl.protocol !== \"https:\" ||\n\t\t\turl.username ||\n\t\t\turl.password ||\n\t\t\turl.href.includes(\"?\") ||\n\t\t\turl.href.includes(\"#\")\n\t\t) {\n\t\t\treturn 'oauth.clientMetadataBaseUrl is required for \"cimd\" and must be an absolute HTTPS URL without userinfo, query, or fragment';\n\t\t}\n\t\turl.pathname = `${url.pathname.replace(/\\/+$/, \"\")}/`;\n\t\tclientMetadataBaseUrl = url.href;\n\t} else if (value.clientMetadataBaseUrl !== undefined) {\n\t\treturn 'oauth.clientMetadataBaseUrl requires oauth.clientRegistration \"cimd\"';\n\t}\n\tconst metadataUrl = value.authServerMetadataUrl;\n\tif (metadataUrl !== undefined) {\n\t\tconst url = typeof metadataUrl === \"string\" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;\n\t\tif (!url || !(url.protocol === \"https:\" || (url.protocol === \"http:\" && LOOPBACK_HOSTS.includes(url.hostname)))) {\n\t\t\treturn \"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]\";\n\t\t}\n\t}\n\treturn { ...value, ...(clientMetadataBaseUrl ? { clientMetadataBaseUrl } : {}) } as McpOAuthConfig;\n}\n\nfunction isExposure(value: unknown): value is McpExposure {\n\treturn typeof value === \"string\" && MCP_EXPOSURES.includes(value);\n}\n\n/** The exposure an alias stands for; other values are returned unchanged. */\nfunction resolveExposureAlias(value: unknown): unknown {\n\treturn typeof value === \"string\" ? (MCP_EXPOSURE_ALIASES[value] ?? value) : value;\n}\n\n/** A copy of the server entry with exposure aliases replaced by their current names. */\nfunction resolveExposureAliases(value: Record<string, unknown>): Record<string, unknown> {\n\tconst { exposure, toolExposure } = value;\n\tconst resolved: Record<string, unknown> = { ...value };\n\tif (exposure !== undefined) resolved.exposure = resolveExposureAlias(exposure);\n\tif (isRecord(toolExposure)) {\n\t\tresolved.toolExposure = Object.fromEntries(\n\t\t\tObject.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposureAlias(entry)]),\n\t\t);\n\t}\n\treturn resolved;\n}\n\n/** Exposure of one tool of a server: its `toolExposure` entry, else the server's `exposure`. */\nexport function getMcpToolExposure(config: McpServerConfig, toolName: string): McpExposure {\n\tconst overrides = config.toolExposure ?? {};\n\tconst exact = overrides[toolName];\n\tif (exact !== undefined) return exact;\n\tfor (const [pattern, exposure] of Object.entries(overrides)) {\n\t\tif (pattern.includes(\"*\") && toolPatternRegExp(pattern).test(toolName)) return exposure;\n\t}\n\treturn config.exposure ?? \"codemode\";\n}\n\n/**\n * Validate one server entry of the `mcpServers` shape. Returns a copy of the config with exposure\n * aliases resolved, or an error message.\n */\nexport function validateMcpServerConfig(name: string, raw: unknown): McpServerConfig | string {\n\tif (!SERVER_NAME.test(name)) return `invalid server name \"${name}\" (use letters, digits, \"_\" and \"-\")`;\n\tif (!isRecord(raw)) return `server \"${name}\" must be an object`;\n\tconst value = resolveExposureAliases(raw);\n\tconst { type, exposure, enabled, timeout, toolExposure, description } = value;\n\tconst exposures = MCP_EXPOSURES.map((value) => `\"${value}\"`).join(\", \");\n\tif (exposure !== undefined && !isExposure(exposure)) {\n\t\treturn `server \"${name}\": exposure must be one of ${exposures}`;\n\t}\n\tif (toolExposure !== undefined) {\n\t\tif (!isRecord(toolExposure)) return `server \"${name}\": toolExposure must map tool names to exposures`;\n\t\tfor (const [tool, value] of Object.entries(toolExposure)) {\n\t\t\tif (!isExposure(value)) return `server \"${name}\": toolExposure \"${tool}\" must be one of ${exposures}`;\n\t\t}\n\t}\n\tif (enabled !== undefined && typeof enabled !== \"boolean\") return `server \"${name}\": enabled must be a boolean`;\n\tif (description !== undefined && typeof description !== \"string\") {\n\t\treturn `server \"${name}\": description must be a string`;\n\t}\n\tif (timeout !== undefined && (typeof timeout !== \"number\" || !(timeout > 0))) {\n\t\treturn `server \"${name}\": timeout must be a positive number of seconds`;\n\t}\n\tif (type === \"sse\") return `server \"${name}\": legacy SSE transport is not supported; use the streamable HTTP URL`;\n\n\tif (typeof value.url === \"string\" && (type === undefined || type === \"http\" || type === \"streamable-http\")) {\n\t\tif (!URL.canParse(value.url) || !/^https?:$/.test(new URL(value.url).protocol)) {\n\t\t\treturn `server \"${name}\": url must be an http or https URL`;\n\t\t}\n\t\tif (value.headers !== undefined && !isStringRecord(value.headers)) {\n\t\t\treturn `server \"${name}\": headers must map names to strings`;\n\t\t}\n\t\tconst oauth = validateOAuth(value.oauth);\n\t\tif (typeof oauth === \"string\") return `server \"${name}\": ${oauth}`;\n\t\tif (oauth !== undefined) value.oauth = oauth;\n\t\tif (value.auth !== undefined) {\n\t\t\tif (!isRecord(value.auth) || typeof value.auth.provider !== \"string\" || !value.auth.provider) {\n\t\t\t\treturn `server \"${name}\": auth.provider must be a provider name`;\n\t\t\t}\n\t\t\tconst url = new URL(value.url);\n\t\t\tif (url.protocol !== \"https:\" && !LOOPBACK_HOSTS.includes(url.hostname)) {\n\t\t\t\treturn `server \"${name}\": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`;\n\t\t\t}\n\t\t}\n\t\treturn value as unknown as McpHttpServerConfig;\n\t}\n\tif (typeof value.command === \"string\" && (type === undefined || type === \"stdio\")) {\n\t\tif (\n\t\t\tvalue.args !== undefined &&\n\t\t\t!(Array.isArray(value.args) && value.args.every((arg) => typeof arg === \"string\"))\n\t\t) {\n\t\t\treturn `server \"${name}\": args must be an array of strings`;\n\t\t}\n\t\tif (value.env !== undefined && !isStringRecord(value.env))\n\t\t\treturn `server \"${name}\": env must map names to strings`;\n\t\tif (value.cwd !== undefined && typeof value.cwd !== \"string\") return `server \"${name}\": cwd must be a string`;\n\t\treturn value as unknown as McpStdioServerConfig;\n\t}\n\treturn `server \"${name}\" needs either \"command\" (stdio) or \"url\" (streamable HTTP)`;\n}\n\n/** A server an extension registered with `pi.registerMcpServer()`. */\nexport interface RegisteredMcpServer {\n\tname: string;\n\tconfig: McpServerConfig;\n\t/** Path of the extension that registered the server. */\n\textensionPath: string;\n\t/** Scope the extension that registered the server was loaded from. */\n\textensionScope: SourceScope;\n}\n\n/** Servers registered by the extensions of one runtime. */\nexport class McpServerRegistry {\n\tprivate readonly servers = new Map<string, RegisteredMcpServer>();\n\tprivate changeListener: (() => void) | undefined;\n\n\t/** Register or replace a server. The caller checks ownership. */\n\tregister(server: RegisteredMcpServer): void {\n\t\tthis.servers.set(server.name, server);\n\t\tthis.changeListener?.();\n\t}\n\n\t/** Remove a server registered by `extensionPath`. Servers of other extensions are left alone. */\n\tunregister(name: string, extensionPath: string): void {\n\t\tif (this.servers.get(name)?.extensionPath !== extensionPath) return;\n\t\tthis.servers.delete(name);\n\t\tthis.changeListener?.();\n\t}\n\n\tget(name: string): RegisteredMcpServer | undefined {\n\t\treturn this.servers.get(name);\n\t}\n\n\t/** Copies of the registered servers, in registration order. */\n\tlist(): RegisteredMcpServer[] {\n\t\treturn [...this.servers.values()].map((server) => ({ ...server, config: structuredClone(server.config) }));\n\t}\n\n\t/** Called after every change. The runner sets it when it binds, to emit `mcp_servers_change`. */\n\tsetChangeListener(listener: (() => void) | undefined): void {\n\t\tthis.changeListener = listener;\n\t}\n}\n"]}
@@ -27,12 +27,21 @@
27
27
  * action: approve
28
28
  * ```
29
29
  *
30
- * Rules are evaluated top-to-bottom; the first matching rule wins.
30
+ * Rules are evaluated top-to-bottom; the first matching rule wins. A rule's
31
+ * `tool` is a tool name or a glob over tool names, where `*` stands for any
32
+ * run of characters and `?` for one, matched case-insensitively:
33
+ * `mcp__docs__*` covers every tool whose name starts with `mcp__docs__`, such
34
+ * as the tools of the `docs` MCP server.
31
35
  *
32
36
  * On top of the rules sits a session-level `PermissionMode` (`ask` /
33
37
  * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and
34
38
  * `approve` outcomes are handled — `deny` rules are never relaxed.
35
39
  *
40
+ * An unmatched tool the gate has no default for requires approval, unless it
41
+ * declares itself read-only (`readOnlyHint`) through sources trusted to say
42
+ * so (`hasTrustedReadOnlyHint`); then it is allowed within the project, in
43
+ * `ask` and `supervised` only when it also declares `openWorldHint: false`.
44
+ *
36
45
  * `pattern` matching against bash commands is textual (no real shell
37
46
  * parser), so `deny` and `allow`/`approve` patterns are matched with
38
47
  * deliberately asymmetric strategies to stay fail-safe: `deny` scans every
@@ -46,13 +55,18 @@
46
55
  * in particular, `pattern` can never guarantee real path containment; use
47
56
  * `paths` for that.
48
57
  */
58
+ import type { SourceInfo, SourceScope } from "../source-info.ts";
49
59
  /** The three permission tiers a rule (or default) can resolve to. */
50
60
  export type PermissionAction = "deny" | "allow" | "approve";
51
61
  /**
52
- * Session-level permission mode. Modes only relax the gate's *default*
62
+ * Session-level permission mode. Modes only change the gate's *default*
53
63
  * decisions — explicit rules from `permissions.yml` always win first:
54
64
  *
65
+ * - `supervised`: like `ask`, and unmatched `write`/`edit` calls require
66
+ * approval inside the project too.
55
67
  * - `ask`: rules as authored; unmatched bash/powershell requires approval.
68
+ * A trusted read-only tool runs unasked only when it also declares
69
+ * `openWorldHint: false` (as in `supervised`).
56
70
  * - `auto`: unmatched bash is auto-allowed unless it trips the built-in
57
71
  * danger filter (`DANGEROUS_COMMAND_PATTERNS`), in which case it still
58
72
  * requires approval. `powershell` is excluded from this auto-allow — the
@@ -64,13 +78,13 @@ export type PermissionAction = "deny" | "allow" | "approve";
64
78
  * `allow`. Explicit `deny` rules still block — yolo is "stop asking",
65
79
  * not "disable the gate".
66
80
  */
67
- export type PermissionMode = "ask" | "auto" | "yolo";
81
+ export type PermissionMode = "supervised" | "ask" | "auto" | "yolo";
68
82
  /** Strictest first: `stricterPermissionMode` relies on this order. */
69
83
  export declare const PERMISSION_MODES: readonly PermissionMode[];
70
84
  /**
71
85
  * The mode a session starts in when `DRAHT_PERMISSION_MODE` names none. A `PermissionGate`
72
- * constructed without a mode still uses `ask`, the strictest, so a caller that forgets to
73
- * pass the session's mode never gets a laxer gate than the session has. Never `yolo`: `/yolo`
86
+ * constructed without a mode still uses `ask`, so a caller that forgets to pass the session's
87
+ * mode never gets a laxer gate than any session but a `supervised` one has. Never `yolo`: `/yolo`
74
88
  * switches back to this mode when nothing else was chosen.
75
89
  */
76
90
  export declare const DEFAULT_SESSION_PERMISSION_MODE: Exclude<PermissionMode, "yolo">;
@@ -79,7 +93,7 @@ export declare function isPermissionMode(value: unknown): value is PermissionMod
79
93
  export declare function stricterPermissionMode(a: PermissionMode, b: PermissionMode): PermissionMode;
80
94
  /** A single permission rule as authored in `permissions.yml`. */
81
95
  export interface PermissionRule {
82
- /** Tool identifier this rule applies to (e.g. "bash", "read", "write", "edit"), or "*" for any tool. */
96
+ /** Tool this rule applies to (e.g. "bash", "read", "write", "edit"), or a glob over tool names ("mcp__docs__*", "*"). */
83
97
  tool: string;
84
98
  /** Glob pattern matched against the bash command string (only meaningful for tools with a `command` arg). */
85
99
  pattern?: string;
@@ -128,6 +142,18 @@ export declare const DANGEROUS_COMMAND_PATTERNS: readonly string[];
128
142
  * `undefined` if the command passes the filter.
129
143
  */
130
144
  export declare function findDangerousPattern(command: string): string | undefined;
145
+ /** What the gate reads about a called tool besides its name: the matching parts of its `ToolInfo`. */
146
+ export interface GatedTool {
147
+ annotations?: {
148
+ readOnlyHint?: boolean;
149
+ destructiveHint?: boolean;
150
+ openWorldHint?: boolean;
151
+ };
152
+ /** Scope of the source the annotations come from, when the registering extension relays them. */
153
+ annotationsScope?: SourceScope;
154
+ /** Where the extension that registered the tool was loaded from. */
155
+ sourceInfo: Pick<SourceInfo, "scope">;
156
+ }
131
157
  export interface PermissionGateOptions {
132
158
  /** Project root used to determine whether a path is "within the project" for default decisions. Defaults to `process.cwd()`. */
133
159
  cwd?: string;
@@ -143,8 +169,11 @@ export declare class PermissionGate {
143
169
  private readonly cwd;
144
170
  private readonly mode;
145
171
  constructor(rules?: PermissionRule[], options?: PermissionGateOptions);
146
- /** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */
147
- evaluate(toolName: string, args?: Record<string, unknown>): PermissionDecision;
172
+ /**
173
+ * Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit.
174
+ * `tool` is the called tool as the session registered it, if known; its hints only inform default decisions.
175
+ */
176
+ evaluate(toolName: string, args?: Record<string, unknown>, tool?: GatedTool): PermissionDecision;
148
177
  /**
149
178
  * Applies the session mode to a decision. `deny` is never relaxed by any
150
179
  * mode; `yolo` downgrades every `approve` to `allow`.
@@ -1 +1 @@
1
- {"version":3,"file":"permission-gate.d.ts","sourceRoot":"","sources":["../../../src/core/multi-agent/permission-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AASH,qEAAqE;AACrE,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;AAE5D;;;;;;;;;;;;;;;G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B;AAED;;;GAGG;AACH,qBAAa,cAAc;IAC1B,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmB;IACzC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiB;IAEtC,YAAY,KAAK,GAAE,cAAc,EAAO,EAAE,OAAO,GAAE,qBAA0B,EAI5E;IAED;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EAAE,IAAI,CAAC,EAAE,SAAS,GAAG,kBAAkB,CA0BnG;IAED;;;OAGG;IACH,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,eAAe;CA+IvB"}
@@ -27,12 +27,21 @@
27
27
  * action: approve
28
28
  * ```
29
29
  *
30
- * Rules are evaluated top-to-bottom; the first matching rule wins.
30
+ * Rules are evaluated top-to-bottom; the first matching rule wins. A rule's
31
+ * `tool` is a tool name or a glob over tool names, where `*` stands for any
32
+ * run of characters and `?` for one, matched case-insensitively:
33
+ * `mcp__docs__*` covers every tool whose name starts with `mcp__docs__`, such
34
+ * as the tools of the `docs` MCP server.
31
35
  *
32
36
  * On top of the rules sits a session-level `PermissionMode` (`ask` /
33
37
  * `auto` / `yolo`, see the type doc) that relaxes how unmatched calls and
34
38
  * `approve` outcomes are handled — `deny` rules are never relaxed.
35
39
  *
40
+ * An unmatched tool the gate has no default for requires approval, unless it
41
+ * declares itself read-only (`readOnlyHint`) through sources trusted to say
42
+ * so (`hasTrustedReadOnlyHint`); then it is allowed within the project, in
43
+ * `ask` and `supervised` only when it also declares `openWorldHint: false`.
44
+ *
36
45
  * `pattern` matching against bash commands is textual (no real shell
37
46
  * parser), so `deny` and `allow`/`approve` patterns are matched with
38
47
  * deliberately asymmetric strategies to stay fail-safe: `deny` scans every
@@ -53,11 +62,11 @@ import { parse } from "yaml";
53
62
  import { CONFIG_DIR_NAME, getAgentDir } from "../../config.js";
54
63
  import { resolveToCwd } from "../tools/path-utils.js";
55
64
  /** Strictest first: `stricterPermissionMode` relies on this order. */
56
- export const PERMISSION_MODES = ["ask", "auto", "yolo"];
65
+ export const PERMISSION_MODES = ["supervised", "ask", "auto", "yolo"];
57
66
  /**
58
67
  * The mode a session starts in when `DRAHT_PERMISSION_MODE` names none. A `PermissionGate`
59
- * constructed without a mode still uses `ask`, the strictest, so a caller that forgets to
60
- * pass the session's mode never gets a laxer gate than the session has. Never `yolo`: `/yolo`
68
+ * constructed without a mode still uses `ask`, so a caller that forgets to pass the session's
69
+ * mode never gets a laxer gate than any session but a `supervised` one has. Never `yolo`: `/yolo`
61
70
  * switches back to this mode when nothing else was chosen.
62
71
  */
63
72
  export const DEFAULT_SESSION_PERMISSION_MODE = "auto";
@@ -102,6 +111,10 @@ function validateRule(raw, index) {
102
111
  if (typeof record.tool !== "string" || record.tool.length === 0) {
103
112
  throw new Error(`permissions.yml: rule at index ${index} is missing a valid "tool" field`);
104
113
  }
114
+ // `paths` globs know braces and brackets; in `tool` they would silently never match a tool name.
115
+ if (/[{}[\]]/.test(record.tool)) {
116
+ throw new Error(`permissions.yml: rule at index ${index} has braces or brackets in "tool"; only * and ? are wildcards there`);
117
+ }
105
118
  if (!isPermissionAction(record.action)) {
106
119
  throw new Error(`permissions.yml: rule at index ${index} has an invalid "action" (must be one of ${VALID_ACTIONS.join(", ")})`);
107
120
  }
@@ -1852,19 +1865,58 @@ function describeMatch(rule) {
1852
1865
  return `matched rule (${parts.join(", ")}) -> ${rule.action}`;
1853
1866
  }
1854
1867
  /**
1855
- * A `tool: bash` rule's `pattern` is authored against bash command shapes, so
1856
- * only its `deny` half is safe to reuse for `powershell` calls: a bash `deny`
1857
- * over-matching onto a powershell command is the fail-safe direction, while a
1858
- * bash `allow`/`approve` pattern (e.g. `ls *`) under-matching real
1859
- * powershell syntax would otherwise create the illusion of coverage without
1860
- * actually vetting powershell-specific danger. `tool: powershell` rules
1861
- * (and `tool: "*"`) are unaffected and keep matching normally.
1868
+ * A rule whose `tool` names bash (`tool: bash`, or a glob such as `b*`) has a
1869
+ * `pattern` authored against bash command shapes, so only its `deny` half is
1870
+ * safe to reuse for `powershell` calls: a bash `deny` over-matching onto a
1871
+ * powershell command is the fail-safe direction, while a bash
1872
+ * `allow`/`approve` pattern (e.g. `ls *`) under-matching real powershell
1873
+ * syntax would otherwise create the illusion of coverage without actually
1874
+ * vetting powershell-specific danger. Rules whose `tool` names powershell
1875
+ * itself (`tool: powershell`, `tool: "*"`) are unaffected and keep matching
1876
+ * normally.
1862
1877
  */
1863
1878
  function bashDenyRuleAppliesToPowershell(rule, toolName) {
1864
- return toolName === "powershell" && rule.tool.toLowerCase() === "bash" && rule.action === "deny";
1879
+ return toolName === "powershell" && rule.action === "deny" && toolPatternMatches(rule.tool, "bash");
1880
+ }
1881
+ /** Whether a rule's `tool` names `toolName` (lowercase): exactly, or as a glob of `*` and `?`, in any letter case. */
1882
+ function toolPatternMatches(pattern, toolName) {
1883
+ return matchesWildcards(pattern.toLowerCase(), toolName);
1884
+ }
1885
+ /**
1886
+ * Whether `text` matches `glob`, where `*` stands for any run of characters and `?` for one, in time
1887
+ * proportional to the product of their lengths. Not `globToRegExp`: a regex of many `*` backtracks
1888
+ * exponentially on a long text it does not match (`*a*a*a*a*a*a*b` takes seconds on 64 characters).
1889
+ */
1890
+ function matchesWildcards(glob, text) {
1891
+ let g = 0;
1892
+ let t = 0;
1893
+ // The last `*` seen, and where in `text` its run ends so far, to widen it when a later part fails.
1894
+ let star = -1;
1895
+ let starEnd = 0;
1896
+ while (t < text.length) {
1897
+ // `*` first: taken as a literal for a `*` in `text`, it would leave no point to widen from.
1898
+ if (glob[g] === "*") {
1899
+ star = g++;
1900
+ starEnd = t;
1901
+ }
1902
+ else if (g < glob.length && (glob[g] === "?" || glob[g] === text[t])) {
1903
+ g++;
1904
+ t++;
1905
+ }
1906
+ else if (star !== -1) {
1907
+ g = star + 1;
1908
+ t = ++starEnd;
1909
+ }
1910
+ else {
1911
+ return false;
1912
+ }
1913
+ }
1914
+ while (glob[g] === "*")
1915
+ g++;
1916
+ return g === glob.length;
1865
1917
  }
1866
1918
  function toolMatchesRule(rule, toolName) {
1867
- return rule.tool === "*" || rule.tool.toLowerCase() === toolName || bashDenyRuleAppliesToPowershell(rule, toolName);
1919
+ return toolPatternMatches(rule.tool, toolName) || bashDenyRuleAppliesToPowershell(rule, toolName);
1868
1920
  }
1869
1921
  function ruleMatches(rule, toolName, args, cwd) {
1870
1922
  if (!toolMatchesRule(rule, toolName))
@@ -1890,6 +1942,68 @@ function ruleMatches(rule, toolName, args, cwd) {
1890
1942
  }
1891
1943
  return true;
1892
1944
  }
1945
+ /**
1946
+ * Whether `tool` declares itself read-only through sources trusted to say so. Hints are not
1947
+ * verified, so a project's own configuration never vouches for one: the extension that registered
1948
+ * the tool must come from outside the project (built in, `-e`, the SDK, the user's own extensions
1949
+ * and packages: scope `temporary` or `user`), and so must any source it relays the hints from
1950
+ * (`annotationsScope`, such as the `mcp.json` that defines an MCP server). Not `source`: a project
1951
+ * package can be named `builtin`. A tool that also declares itself destructive contradicts itself,
1952
+ * so its hint does not count either.
1953
+ */
1954
+ function hasTrustedReadOnlyHint(tool) {
1955
+ if (tool.annotations?.readOnlyHint !== true || tool.annotations.destructiveHint === true)
1956
+ return false;
1957
+ return tool.sourceInfo.scope !== "project" && tool.annotationsScope !== "project";
1958
+ }
1959
+ /** Past these bounds the walk over a call's arguments stops, and the call counts as naming a path outside. */
1960
+ const MAX_PATH_SCAN_DEPTH = 32;
1961
+ const MAX_PATH_SCAN_VALUES = 10_000;
1962
+ /**
1963
+ * Whether `value` names a file location rather than plain text: an absolute path, one under `~`,
1964
+ * a drive letter, a leading `@` (the tools strip it) or a `file:` URL, or a path climbing with `..`.
1965
+ */
1966
+ function looksLikePath(value) {
1967
+ return isAbsolute(value) || /^(?:~|@|file:|[A-Za-z]:)/i.test(value) || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(value);
1968
+ }
1969
+ /**
1970
+ * Whether every string in `args` that looks like a path, at any depth, names a location inside
1971
+ * `cwd`. Tools name their paths under keys of their own (`paths`, `uri`, nested options), so the key
1972
+ * does not decide. A path that does not resolve, and arguments too deep or too many to walk, count
1973
+ * as naming one outside.
1974
+ */
1975
+ function argsStayWithinProject(args, cwd) {
1976
+ const pending = [{ value: args, depth: 0 }];
1977
+ let visited = 0;
1978
+ for (let item = pending.pop(); item !== undefined; item = pending.pop()) {
1979
+ if (++visited > MAX_PATH_SCAN_VALUES)
1980
+ return false;
1981
+ const { value, depth } = item;
1982
+ if (typeof value === "string") {
1983
+ const candidate = value.trim();
1984
+ if (!looksLikePath(candidate))
1985
+ continue;
1986
+ try {
1987
+ if (!isWithinProject(candidate, cwd))
1988
+ return false;
1989
+ }
1990
+ catch {
1991
+ // `file://host/x` and other URLs no tool can open.
1992
+ return false;
1993
+ }
1994
+ }
1995
+ else if (typeof value === "object" && value !== null) {
1996
+ if (depth >= MAX_PATH_SCAN_DEPTH)
1997
+ return false;
1998
+ for (const child of Object.values(value)) {
1999
+ if (pending.length >= MAX_PATH_SCAN_VALUES)
2000
+ return false;
2001
+ pending.push({ value: child, depth: depth + 1 });
2002
+ }
2003
+ }
2004
+ }
2005
+ return true;
2006
+ }
1893
2007
  /**
1894
2008
  * Evaluates tool calls against an ordered list of permission rules,
1895
2009
  * returning a `deny` / `allow` / `approve` decision.
@@ -1903,8 +2017,11 @@ export class PermissionGate {
1903
2017
  this.cwd = options.cwd ?? process.cwd();
1904
2018
  this.mode = options.mode ?? "ask";
1905
2019
  }
1906
- /** Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit. */
1907
- evaluate(toolName, args = {}) {
2020
+ /**
2021
+ * Evaluate a tool call. `args` should carry `command` for bash, or `path`/`file_path` for read/write/edit.
2022
+ * `tool` is the called tool as the session registered it, if known; its hints only inform default decisions.
2023
+ */
2024
+ evaluate(toolName, args = {}, tool) {
1908
2025
  const normalizedTool = toolName.toLowerCase();
1909
2026
  if (normalizedTool === "bash" || normalizedTool === "powershell") {
1910
2027
  const command = getCommandArg(args);
@@ -1923,7 +2040,7 @@ export class PermissionGate {
1923
2040
  return this.applyMode({ action: rule.action, reason: describeMatch(rule) });
1924
2041
  }
1925
2042
  }
1926
- return this.applyMode(this.defaultDecision(normalizedTool, args));
2043
+ return this.applyMode(this.defaultDecision(normalizedTool, args, tool));
1927
2044
  }
1928
2045
  /**
1929
2046
  * Applies the session mode to a decision. `deny` is never relaxed by any
@@ -1935,7 +2052,7 @@ export class PermissionGate {
1935
2052
  }
1936
2053
  return decision;
1937
2054
  }
1938
- defaultDecision(toolName, args) {
2055
+ defaultDecision(toolName, args, tool) {
1939
2056
  if (DEFAULT_ALLOWED_TOOLS.has(toolName)) {
1940
2057
  return { action: "allow", reason: `no rule matched; "${toolName}" is allowed by default` };
1941
2058
  }
@@ -2018,6 +2135,9 @@ export class PermissionGate {
2018
2135
  if (PATH_SCOPED_TOOLS.has(toolName)) {
2019
2136
  const filePaths = getPathArgs(args);
2020
2137
  if (filePaths.length > 0 && filePaths.every((filePath) => isWithinProject(filePath, this.cwd))) {
2138
+ if (this.mode === "supervised" && toolName !== "read") {
2139
+ return { action: "approve", reason: "supervised mode: file changes require approval" };
2140
+ }
2021
2141
  return { action: "allow", reason: "no rule matched; allowed by default within the project" };
2022
2142
  }
2023
2143
  return {
@@ -2038,6 +2158,27 @@ export class PermissionGate {
2038
2158
  reason: "no rule matched; path is outside the project, requires approval",
2039
2159
  };
2040
2160
  }
2161
+ if (tool !== undefined && hasTrustedReadOnlyHint(tool)) {
2162
+ // In `ask` and `supervised`, only a tool that also stays in a closed world: a read-only tool that
2163
+ // reaches the web can still carry what it read out in a query or URL.
2164
+ if ((this.mode === "ask" || this.mode === "supervised") && tool.annotations?.openWorldHint !== false) {
2165
+ return {
2166
+ action: "approve",
2167
+ reason: `${this.mode} mode: "${toolName}" is read-only but may reach an open world (no openWorldHint: false), requires approval`,
2168
+ };
2169
+ }
2170
+ // Like grep/find/ls: a read-only tool still asks before it reads a path outside the project.
2171
+ if (argsStayWithinProject(args, this.cwd)) {
2172
+ return {
2173
+ action: "allow",
2174
+ reason: `no rule matched; "${toolName}" is read-only by a trusted source's hint, allowed by default within the project`,
2175
+ };
2176
+ }
2177
+ return {
2178
+ action: "approve",
2179
+ reason: `no rule matched; "${toolName}" is read-only by a trusted source's hint, but names a path outside the project, requires approval`,
2180
+ };
2181
+ }
2041
2182
  return { action: "approve", reason: `no rule matched for tool "${toolName}"; defaults to approve` };
2042
2183
  }
2043
2184
  }