pybao-cli 1.5.49 → 1.5.50

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 (151) hide show
  1. package/dist/REPL-5XUDCAF4.js +53 -0
  2. package/dist/{acp-6X7A2AET.js → acp-VXAHCMQ4.js} +30 -30
  3. package/dist/{agentsValidate-GRUUS3WU.js → agentsValidate-PFVCK6ZC.js} +7 -7
  4. package/dist/{ask-HZDW4LTP.js → ask-7RQ2G5S3.js} +30 -30
  5. package/dist/{autoUpdater-SPEKG26M.js → autoUpdater-TDN3ABMG.js} +3 -3
  6. package/dist/{chunk-7NJKFUVQ.js → chunk-3IPEAISZ.js} +3 -3
  7. package/dist/{chunk-ALMRZ6TK.js → chunk-5ITEAEJC.js} +1 -1
  8. package/dist/{chunk-ALMRZ6TK.js.map → chunk-5ITEAEJC.js.map} +1 -1
  9. package/dist/{chunk-X7L2ZXEQ.js → chunk-5P4A6TN2.js} +2 -2
  10. package/dist/{chunk-KH3BWQJI.js → chunk-7MR3XX5X.js} +2 -2
  11. package/dist/{chunk-I33HG6MZ.js → chunk-A45A3UUU.js} +1 -1
  12. package/dist/{chunk-AIKGRPJR.js → chunk-BQCQ3DEN.js} +2 -2
  13. package/dist/{chunk-NSPAFJYF.js → chunk-C7BUAPKP.js} +3 -3
  14. package/dist/{chunk-3OA76CSA.js → chunk-CHH6TEXB.js} +1 -1
  15. package/dist/{chunk-JJNZ7WEP.js → chunk-CNBKKQSV.js} +1 -1
  16. package/dist/{chunk-NYRCQC7E.js → chunk-CNW45NOZ.js} +3 -3
  17. package/dist/{chunk-V6B67TTT.js → chunk-DBMDQEQO.js} +3 -3
  18. package/dist/{chunk-AKDLTQJZ.js → chunk-EY3ZOE75.js} +1 -1
  19. package/dist/{chunk-UEF22EAA.js → chunk-FNDIHEBT.js} +48 -10
  20. package/dist/{chunk-UEF22EAA.js.map → chunk-FNDIHEBT.js.map} +2 -2
  21. package/dist/{chunk-V633SD3K.js → chunk-IXFDCJ25.js} +3 -3
  22. package/dist/{chunk-EPTONOB3.js → chunk-J6HKEIL2.js} +1 -1
  23. package/dist/{chunk-7OKEXFNZ.js → chunk-K3QEELFX.js} +3 -3
  24. package/dist/{chunk-4DMR3345.js → chunk-KKNO6B2K.js} +38 -38
  25. package/dist/{chunk-XRHL3B3W.js → chunk-L4CGYTJQ.js} +1 -1
  26. package/dist/{chunk-E5CC5UGF.js → chunk-LE5VGGP6.js} +4 -4
  27. package/dist/{chunk-NRGFDG57.js → chunk-NBDDIZNJ.js} +2 -2
  28. package/dist/{chunk-SQL5Q5UT.js → chunk-NQGIALRP.js} +4 -4
  29. package/dist/{chunk-SCZBEZ4L.js → chunk-NRORTICH.js} +2 -2
  30. package/dist/{chunk-OT7EHZKB.js → chunk-NSFU6Y4R.js} +1 -1
  31. package/dist/{chunk-XGSD7RT6.js → chunk-PXRUNRK7.js} +1 -1
  32. package/dist/{chunk-ZBUV2OFZ.js → chunk-UJRT7VK2.js} +1 -1
  33. package/dist/{chunk-KSDMNPM3.js → chunk-VAZ4VRTA.js} +3 -3
  34. package/dist/{chunk-C2BMJGBF.js → chunk-XHAEEYYH.js} +1 -1
  35. package/dist/{chunk-F4IOWWDV.js → chunk-Y7I4XTJJ.js} +3 -3
  36. package/dist/{chunk-TBPXZUAE.js → chunk-YFVKGHW2.js} +2 -2
  37. package/dist/{chunk-ZYI3GZHI.js → chunk-ZDDVFBS4.js} +4 -4
  38. package/dist/{chunk-VII5ABW7.js → chunk-ZKW5V7MR.js} +1 -1
  39. package/dist/{cli-E24TVQWL.js → cli-PMOATR2H.js} +90 -90
  40. package/dist/commands-HA2TW7NU.js +57 -0
  41. package/dist/{config-U5HHXO56.js → config-PQYZDDGW.js} +4 -4
  42. package/dist/{context-5XAWTXIF.js → context-BWXP2WB4.js} +6 -6
  43. package/dist/{conversationPersistence-COKR4DJM.js → conversationPersistence-CS2SQ6Z6.js} +3 -3
  44. package/dist/{conversationTracker-CFWPAQJQ.js → conversationTracker-3OLKEYWM.js} +4 -4
  45. package/dist/{customCommands-KV4SPPEJ.js → customCommands-VPTXXYYR.js} +4 -4
  46. package/dist/{env-6Z2X4SGO.js → env-G5ZYCG5S.js} +2 -2
  47. package/dist/{file-EYJLYMU7.js → file-2I2KXCVN.js} +4 -4
  48. package/dist/index.js +3 -3
  49. package/dist/{llm-JRNCNUVN.js → llm-KXF74SNS.js} +31 -31
  50. package/dist/{llmLazy-ULKOVGTW.js → llmLazy-L3IJUBN2.js} +1 -1
  51. package/dist/{loader-YC2J4JQD.js → loader-CJOJNOV7.js} +4 -4
  52. package/dist/{lsp-YOU3CXAU.js → lsp-OKPL75YW.js} +6 -6
  53. package/dist/{lspAnchor-XLKJXJ4F.js → lspAnchor-7Z5YNXX3.js} +6 -6
  54. package/dist/{mcp-ZBXWPPEQ.js → mcp-C65V4JYM.js} +7 -7
  55. package/dist/{mentionProcessor-D7A5SR2F.js → mentionProcessor-EDZBHP7Y.js} +5 -5
  56. package/dist/{messages-N4BMW6FO.js → messages-YBAYUMKL.js} +1 -1
  57. package/dist/{model-3R63GBXV.js → model-7WMFC6F7.js} +5 -5
  58. package/dist/{openai-OE2BXCWW.js → openai-YWEX6G4I.js} +5 -5
  59. package/dist/{outputStyles-7NXCPWAM.js → outputStyles-N6S27KGD.js} +4 -4
  60. package/dist/{pluginRuntime-DUFKGBKI.js → pluginRuntime-3XWIAPQ7.js} +6 -6
  61. package/dist/{pluginValidation-TUI4RWTL.js → pluginValidation-2JLTTMJL.js} +6 -6
  62. package/dist/prompts-HCGQPTDJ.js +59 -0
  63. package/dist/{pybAgentSessionLoad-OHCESID3.js → pybAgentSessionLoad-XJ6XWCK5.js} +4 -4
  64. package/dist/{pybAgentSessionResume-X7TO6VQ7.js → pybAgentSessionResume-SMNXFGFB.js} +4 -4
  65. package/dist/{pybAgentStreamJsonSession-3XCK4MLN.js → pybAgentStreamJsonSession-33YU7WNJ.js} +1 -1
  66. package/dist/{pybHooks-WGTXY2KQ.js → pybHooks-6JRPW3VW.js} +4 -4
  67. package/dist/query-GGJC3XT2.js +57 -0
  68. package/dist/{registry-V4XMLWYT.js → registry-67P26WKJ.js} +5 -5
  69. package/dist/{ripgrep-ITNB4VGR.js → ripgrep-DPLWHL7O.js} +3 -3
  70. package/dist/{skillMarketplace-YYMKIEEM.js → skillMarketplace-MGU4KRUF.js} +3 -3
  71. package/dist/{state-ZQW77MQC.js → state-NZVNNCHH.js} +2 -2
  72. package/dist/{theme-L3I3PP7H.js → theme-XV4CTBG6.js} +5 -5
  73. package/dist/{toolPermissionSettings-ZHMSXSXS.js → toolPermissionSettings-NEXN25B3.js} +6 -6
  74. package/dist/tools-R7EDLOFS.js +57 -0
  75. package/dist/{userInput-VSYAOPNU.js → userInput-PHXM4ITY.js} +32 -32
  76. package/package.json +1 -1
  77. package/dist/REPL-QOH5GRZO.js +0 -53
  78. package/dist/commands-M75WK3OK.js +0 -57
  79. package/dist/prompts-VLIUTRIV.js +0 -59
  80. package/dist/query-Y332XP4J.js +0 -57
  81. package/dist/tools-CM5X3TT5.js +0 -57
  82. /package/dist/{REPL-QOH5GRZO.js.map → REPL-5XUDCAF4.js.map} +0 -0
  83. /package/dist/{acp-6X7A2AET.js.map → acp-VXAHCMQ4.js.map} +0 -0
  84. /package/dist/{agentsValidate-GRUUS3WU.js.map → agentsValidate-PFVCK6ZC.js.map} +0 -0
  85. /package/dist/{ask-HZDW4LTP.js.map → ask-7RQ2G5S3.js.map} +0 -0
  86. /package/dist/{autoUpdater-SPEKG26M.js.map → autoUpdater-TDN3ABMG.js.map} +0 -0
  87. /package/dist/{chunk-7NJKFUVQ.js.map → chunk-3IPEAISZ.js.map} +0 -0
  88. /package/dist/{chunk-X7L2ZXEQ.js.map → chunk-5P4A6TN2.js.map} +0 -0
  89. /package/dist/{chunk-KH3BWQJI.js.map → chunk-7MR3XX5X.js.map} +0 -0
  90. /package/dist/{chunk-I33HG6MZ.js.map → chunk-A45A3UUU.js.map} +0 -0
  91. /package/dist/{chunk-AIKGRPJR.js.map → chunk-BQCQ3DEN.js.map} +0 -0
  92. /package/dist/{chunk-NSPAFJYF.js.map → chunk-C7BUAPKP.js.map} +0 -0
  93. /package/dist/{chunk-3OA76CSA.js.map → chunk-CHH6TEXB.js.map} +0 -0
  94. /package/dist/{chunk-JJNZ7WEP.js.map → chunk-CNBKKQSV.js.map} +0 -0
  95. /package/dist/{chunk-NYRCQC7E.js.map → chunk-CNW45NOZ.js.map} +0 -0
  96. /package/dist/{chunk-V6B67TTT.js.map → chunk-DBMDQEQO.js.map} +0 -0
  97. /package/dist/{chunk-AKDLTQJZ.js.map → chunk-EY3ZOE75.js.map} +0 -0
  98. /package/dist/{chunk-V633SD3K.js.map → chunk-IXFDCJ25.js.map} +0 -0
  99. /package/dist/{chunk-EPTONOB3.js.map → chunk-J6HKEIL2.js.map} +0 -0
  100. /package/dist/{chunk-7OKEXFNZ.js.map → chunk-K3QEELFX.js.map} +0 -0
  101. /package/dist/{chunk-4DMR3345.js.map → chunk-KKNO6B2K.js.map} +0 -0
  102. /package/dist/{chunk-XRHL3B3W.js.map → chunk-L4CGYTJQ.js.map} +0 -0
  103. /package/dist/{chunk-E5CC5UGF.js.map → chunk-LE5VGGP6.js.map} +0 -0
  104. /package/dist/{chunk-NRGFDG57.js.map → chunk-NBDDIZNJ.js.map} +0 -0
  105. /package/dist/{chunk-SQL5Q5UT.js.map → chunk-NQGIALRP.js.map} +0 -0
  106. /package/dist/{chunk-SCZBEZ4L.js.map → chunk-NRORTICH.js.map} +0 -0
  107. /package/dist/{chunk-OT7EHZKB.js.map → chunk-NSFU6Y4R.js.map} +0 -0
  108. /package/dist/{chunk-XGSD7RT6.js.map → chunk-PXRUNRK7.js.map} +0 -0
  109. /package/dist/{chunk-ZBUV2OFZ.js.map → chunk-UJRT7VK2.js.map} +0 -0
  110. /package/dist/{chunk-KSDMNPM3.js.map → chunk-VAZ4VRTA.js.map} +0 -0
  111. /package/dist/{chunk-C2BMJGBF.js.map → chunk-XHAEEYYH.js.map} +0 -0
  112. /package/dist/{chunk-F4IOWWDV.js.map → chunk-Y7I4XTJJ.js.map} +0 -0
  113. /package/dist/{chunk-TBPXZUAE.js.map → chunk-YFVKGHW2.js.map} +0 -0
  114. /package/dist/{chunk-ZYI3GZHI.js.map → chunk-ZDDVFBS4.js.map} +0 -0
  115. /package/dist/{chunk-VII5ABW7.js.map → chunk-ZKW5V7MR.js.map} +0 -0
  116. /package/dist/{cli-E24TVQWL.js.map → cli-PMOATR2H.js.map} +0 -0
  117. /package/dist/{commands-M75WK3OK.js.map → commands-HA2TW7NU.js.map} +0 -0
  118. /package/dist/{config-U5HHXO56.js.map → config-PQYZDDGW.js.map} +0 -0
  119. /package/dist/{context-5XAWTXIF.js.map → context-BWXP2WB4.js.map} +0 -0
  120. /package/dist/{conversationPersistence-COKR4DJM.js.map → conversationPersistence-CS2SQ6Z6.js.map} +0 -0
  121. /package/dist/{conversationTracker-CFWPAQJQ.js.map → conversationTracker-3OLKEYWM.js.map} +0 -0
  122. /package/dist/{customCommands-KV4SPPEJ.js.map → customCommands-VPTXXYYR.js.map} +0 -0
  123. /package/dist/{env-6Z2X4SGO.js.map → env-G5ZYCG5S.js.map} +0 -0
  124. /package/dist/{file-EYJLYMU7.js.map → file-2I2KXCVN.js.map} +0 -0
  125. /package/dist/{llm-JRNCNUVN.js.map → llm-KXF74SNS.js.map} +0 -0
  126. /package/dist/{llmLazy-ULKOVGTW.js.map → llmLazy-L3IJUBN2.js.map} +0 -0
  127. /package/dist/{loader-YC2J4JQD.js.map → loader-CJOJNOV7.js.map} +0 -0
  128. /package/dist/{lsp-YOU3CXAU.js.map → lsp-OKPL75YW.js.map} +0 -0
  129. /package/dist/{lspAnchor-XLKJXJ4F.js.map → lspAnchor-7Z5YNXX3.js.map} +0 -0
  130. /package/dist/{mcp-ZBXWPPEQ.js.map → mcp-C65V4JYM.js.map} +0 -0
  131. /package/dist/{mentionProcessor-D7A5SR2F.js.map → mentionProcessor-EDZBHP7Y.js.map} +0 -0
  132. /package/dist/{messages-N4BMW6FO.js.map → messages-YBAYUMKL.js.map} +0 -0
  133. /package/dist/{model-3R63GBXV.js.map → model-7WMFC6F7.js.map} +0 -0
  134. /package/dist/{openai-OE2BXCWW.js.map → openai-YWEX6G4I.js.map} +0 -0
  135. /package/dist/{outputStyles-7NXCPWAM.js.map → outputStyles-N6S27KGD.js.map} +0 -0
  136. /package/dist/{pluginRuntime-DUFKGBKI.js.map → pluginRuntime-3XWIAPQ7.js.map} +0 -0
  137. /package/dist/{pluginValidation-TUI4RWTL.js.map → pluginValidation-2JLTTMJL.js.map} +0 -0
  138. /package/dist/{prompts-VLIUTRIV.js.map → prompts-HCGQPTDJ.js.map} +0 -0
  139. /package/dist/{pybAgentSessionLoad-OHCESID3.js.map → pybAgentSessionLoad-XJ6XWCK5.js.map} +0 -0
  140. /package/dist/{pybAgentSessionResume-X7TO6VQ7.js.map → pybAgentSessionResume-SMNXFGFB.js.map} +0 -0
  141. /package/dist/{pybAgentStreamJsonSession-3XCK4MLN.js.map → pybAgentStreamJsonSession-33YU7WNJ.js.map} +0 -0
  142. /package/dist/{pybHooks-WGTXY2KQ.js.map → pybHooks-6JRPW3VW.js.map} +0 -0
  143. /package/dist/{query-Y332XP4J.js.map → query-GGJC3XT2.js.map} +0 -0
  144. /package/dist/{registry-V4XMLWYT.js.map → registry-67P26WKJ.js.map} +0 -0
  145. /package/dist/{ripgrep-ITNB4VGR.js.map → ripgrep-DPLWHL7O.js.map} +0 -0
  146. /package/dist/{skillMarketplace-YYMKIEEM.js.map → skillMarketplace-MGU4KRUF.js.map} +0 -0
  147. /package/dist/{state-ZQW77MQC.js.map → state-NZVNNCHH.js.map} +0 -0
  148. /package/dist/{theme-L3I3PP7H.js.map → theme-XV4CTBG6.js.map} +0 -0
  149. /package/dist/{toolPermissionSettings-ZHMSXSXS.js.map → toolPermissionSettings-NEXN25B3.js.map} +0 -0
  150. /package/dist/{tools-CM5X3TT5.js.map → tools-R7EDLOFS.js.map} +0 -0
  151. /package/dist/{userInput-VSYAOPNU.js.map → userInput-PHXM4ITY.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/services/mcp/client.ts", "../src/services/mcp/internal/jsonc.ts", "../src/services/mcp/discovery.ts", "../src/services/mcp/tools-integration.ts", "../src/tools/mcp/MCPTool/MCPTool.tsx", "../src/ui/components/FallbackToolUseRejectedMessage.tsx", "../src/tools/mcp/MCPTool/prompt.ts", "../src/tools/system/BashTool/OutputLine.tsx", "../src/utils/sandbox/sandboxConfig.ts", "../src/tools/filesystem/FileReadTool/prompt.ts", "../src/tools/filesystem/FileEditTool/prompt.ts", "../src/tools/filesystem/FileWriteTool/prompt.ts", "../src/tools/filesystem/GlobTool/prompt.ts", "../src/tools/search/GrepTool/prompt.ts", "../src/tools/search/LspTool/prompt.ts", "../src/tools/agent/TaskTool/constants.ts", "../src/tools/system/BashTool/prompt.ts", "../src/services/mcp/cli-utils.ts"],
4
- "sourcesContent": ["import type { McpServerConfig } from '@utils/config'\nimport {\n getCurrentProjectConfig,\n getGlobalConfig,\n getProjectMcpServerDefinitions,\n} from '@utils/config'\nimport { existsSync, readFileSync } from 'fs'\nimport { resolve } from 'path'\nimport { getCwd } from '@utils/state'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport { WebSocketClientTransport } from '@modelcontextprotocol/sdk/client/websocket.js'\nimport { memoize, pickBy } from 'lodash-es'\nimport { logMCPError } from '@utils/log'\nimport { PRODUCT_COMMAND } from '@constants/product'\nimport { parseJsonOrJsonc } from './internal/jsonc'\nimport { getMcprcServerStatus, listPluginMCPServers } from './discovery'\n\nfunction getMcpServerConnectionBatchSize(): number {\n const raw = process.env.MCP_SERVER_CONNECTION_BATCH_SIZE\n const parsed = raw ? Number.parseInt(raw, 10) : NaN\n if (Number.isFinite(parsed) && parsed > 0 && parsed <= 50) return parsed\n return 3\n}\n\nasync function connectToServer(\n name: string,\n serverRef: McpServerConfig,\n): Promise<Client> {\n type Candidate = { transport: unknown; kind: 'stdio' | 'sse' | 'http' | 'ws' }\n\n const ensureWebSocketGlobal = async () => {\n if (typeof (globalThis as any).WebSocket === 'function') return\n try {\n const undici = await import('undici')\n if (typeof (undici as any).WebSocket === 'function') {\n ;(globalThis as any).WebSocket = (undici as any).WebSocket\n }\n } catch {}\n }\n\n const candidates: Candidate[] = await (async () => {\n switch (serverRef.type) {\n case 'sse': {\n const ref = serverRef\n return [\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n {\n kind: 'http',\n transport: new StreamableHTTPClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'sse-ide': {\n const ref = serverRef\n return [\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'http': {\n const ref = serverRef\n return [\n {\n kind: 'http',\n transport: new StreamableHTTPClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'ws': {\n const ref = serverRef\n await ensureWebSocketGlobal()\n return [\n {\n kind: 'ws',\n transport: new WebSocketClientTransport(new URL(ref.url)),\n },\n ]\n }\n case 'ws-ide': {\n const ref = serverRef\n\n let url = ref.url\n if (ref.authToken) {\n try {\n const parsed = new URL(url)\n if (!parsed.searchParams.has('authToken')) {\n parsed.searchParams.set('authToken', ref.authToken)\n url = parsed.toString()\n }\n } catch {}\n }\n\n await ensureWebSocketGlobal()\n return [\n {\n kind: 'ws',\n transport: new WebSocketClientTransport(new URL(url)),\n },\n ]\n }\n case 'stdio':\n default: {\n const ref = serverRef\n return [\n {\n kind: 'stdio',\n transport: new StdioClientTransport({\n command: ref.command,\n args: ref.args,\n env: {\n ...process.env,\n ...ref.env,\n } as Record<string, string>,\n stderr: 'pipe',\n }),\n },\n ]\n }\n }\n })()\n\n const rawTimeout = process.env.MCP_CONNECTION_TIMEOUT_MS\n const parsedTimeout = rawTimeout ? Number.parseInt(rawTimeout, 10) : NaN\n const CONNECTION_TIMEOUT_MS = Number.isFinite(parsedTimeout)\n ? parsedTimeout\n : 30_000\n\n let lastError: unknown\n\n for (const candidate of candidates) {\n const client = new Client(\n {\n name: PRODUCT_COMMAND,\n version: '0.1.0',\n },\n {\n capabilities: {},\n },\n )\n\n try {\n const connectPromise = client.connect(candidate.transport as any)\n if (CONNECTION_TIMEOUT_MS > 0) {\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutId = setTimeout(() => {\n reject(\n new Error(\n `Connection to MCP server \"${name}\" timed out after ${CONNECTION_TIMEOUT_MS}ms`,\n ),\n )\n }, CONNECTION_TIMEOUT_MS)\n\n connectPromise.then(\n () => clearTimeout(timeoutId),\n () => clearTimeout(timeoutId),\n )\n })\n\n await Promise.race([connectPromise, timeoutPromise])\n } else {\n await connectPromise\n }\n\n if (candidate.kind === 'stdio') {\n ;(candidate.transport as StdioClientTransport).stderr?.on(\n 'data',\n (data: Buffer) => {\n const errorText = data.toString().trim()\n if (errorText) {\n logMCPError(name, `Server stderr: ${errorText}`)\n }\n },\n )\n }\n\n if (candidates.length > 1 && candidate !== candidates[0]) {\n logMCPError(\n name,\n `Connected using fallback transport \"${candidate.kind}\". Consider setting the server type explicitly in your MCP config.`,\n )\n }\n\n return client\n } catch (error) {\n lastError = error\n try {\n await client.close()\n } catch {}\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(`Failed to connect to MCP server \"${name}\"`)\n}\n\ntype ConnectedClient = {\n client: Client\n capabilities?: Record<string, unknown> | null\n name: string\n type: 'connected'\n}\ntype FailedClient = {\n name: string\n type: 'failed'\n}\nexport type WrappedClient = ConnectedClient | FailedClient\n\nexport const getClients = memoize(async (): Promise<WrappedClient[]> => {\n if (process.env.CI && process.env.NODE_ENV !== 'test') {\n return []\n }\n\n const pluginServers = listPluginMCPServers()\n const globalServers = getGlobalConfig().mcpServers ?? {}\n const projectFileServers = getProjectMcpServerDefinitions().servers\n const projectServers = getCurrentProjectConfig().mcpServers ?? {}\n\n const approvedProjectFileServers = pickBy(\n projectFileServers,\n (_, name) => getMcprcServerStatus(name) === 'approved',\n )\n\n const allServers = {\n ...pluginServers,\n ...globalServers,\n ...approvedProjectFileServers,\n ...projectServers,\n }\n\n const batchSize = getMcpServerConnectionBatchSize()\n const entries = Object.entries(allServers)\n const results: WrappedClient[] = []\n\n for (let i = 0; i < entries.length; i += batchSize) {\n const batch = entries.slice(i, i + batchSize)\n const batchResults = await Promise.all(\n batch.map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n let capabilities: Record<string, unknown> | null = null\n try {\n capabilities = client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n return { name, client, capabilities, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n results.push(...batchResults)\n }\n\n return results\n})\n\nfunction parseMcpServersFromCliConfigEntries(options: {\n entries: string[]\n projectDir: string\n}): Record<string, McpServerConfig> {\n const out: Record<string, McpServerConfig> = {}\n\n for (const rawEntry of options.entries) {\n const entry = String(rawEntry ?? '').trim()\n if (!entry) continue\n\n const resolvedPath = resolve(options.projectDir, entry)\n const payload = existsSync(resolvedPath)\n ? readFileSync(resolvedPath, 'utf8')\n : existsSync(entry)\n ? readFileSync(entry, 'utf8')\n : entry\n\n const parsed = parseJsonOrJsonc(payload)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue\n\n const rawServers =\n (parsed as any).mcpServers &&\n typeof (parsed as any).mcpServers === 'object' &&\n !Array.isArray((parsed as any).mcpServers)\n ? (parsed as any).mcpServers\n : parsed\n\n if (!rawServers || typeof rawServers !== 'object' || Array.isArray(rawServers))\n continue\n\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n out[name] = cfg as McpServerConfig\n }\n }\n\n return out\n}\n\nexport async function getClientsForCliMcpConfig(options: {\n mcpConfig?: string[]\n strictMcpConfig?: boolean\n projectDir?: string\n}): Promise<WrappedClient[]> {\n const projectDir = options.projectDir ?? getCwd()\n const entries =\n Array.isArray(options.mcpConfig) && options.mcpConfig.length > 0\n ? options.mcpConfig\n : []\n const strict = options.strictMcpConfig === true\n\n if (entries.length === 0 && !strict) {\n return getClients()\n }\n\n const cliServers = parseMcpServersFromCliConfigEntries({\n entries,\n projectDir,\n })\n\n const pluginServers = strict ? {} : listPluginMCPServers()\n const globalServers = strict ? {} : (getGlobalConfig().mcpServers ?? {})\n const projectFileServers = strict ? {} : getProjectMcpServerDefinitions().servers\n const projectServers = strict ? {} : (getCurrentProjectConfig().mcpServers ?? {})\n\n const approvedProjectFileServers = strict\n ? {}\n : pickBy(projectFileServers, (_, name) => getMcprcServerStatus(name) === 'approved')\n\n const allServers = {\n ...(pluginServers ?? {}),\n ...(globalServers ?? {}),\n ...(approvedProjectFileServers ?? {}),\n ...(projectServers ?? {}),\n ...(cliServers ?? {}),\n }\n\n const batchSize = getMcpServerConnectionBatchSize()\n const entriesToConnect = Object.entries(allServers)\n const results: WrappedClient[] = []\n\n for (let i = 0; i < entriesToConnect.length; i += batchSize) {\n const batch = entriesToConnect.slice(i, i + batchSize)\n const batchResults = await Promise.all(\n batch.map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n let capabilities: Record<string, unknown> | null = null\n try {\n capabilities = client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n return { name, client, capabilities, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n results.push(...batchResults)\n }\n\n return results\n}\n", "function stripJsonComments(input: string): string {\n let out = ''\n let inString = false\n let escaped = false\n let inLineComment = false\n let inBlockComment = false\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]!\n const next = i + 1 < input.length ? input[i + 1]! : ''\n\n if (inLineComment) {\n if (ch === '\\n') {\n inLineComment = false\n out += ch\n }\n continue\n }\n\n if (inBlockComment) {\n if (ch === '*' && next === '/') {\n inBlockComment = false\n i++\n }\n continue\n }\n\n if (inString) {\n out += ch\n if (escaped) {\n escaped = false\n continue\n }\n if (ch === '\\\\') {\n escaped = true\n continue\n }\n if (ch === '\"') inString = false\n continue\n }\n\n if (ch === '\"') {\n inString = true\n out += ch\n continue\n }\n\n if (ch === '/' && next === '/') {\n inLineComment = true\n i++\n continue\n }\n\n if (ch === '/' && next === '*') {\n inBlockComment = true\n i++\n continue\n }\n\n out += ch\n }\n\n return out\n}\n\nexport function parseJsonOrJsonc(text: string): unknown {\n const raw = String(text ?? '')\n if (!raw.trim()) return null\n try {\n return JSON.parse(raw)\n } catch {\n try {\n return JSON.parse(stripJsonComments(raw))\n } catch {\n return null\n }\n }\n}\n\n", "import {\n getCurrentProjectConfig,\n getGlobalConfig,\n getProjectMcpServerDefinitions,\n saveCurrentProjectConfig,\n saveGlobalConfig,\n addMcprcServerForTesting,\n removeMcprcServerForTesting,\n type McpServerConfig,\n} from '@utils/config'\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\nimport { getCwd } from '@utils/state'\nimport { safeParseJSON } from '@utils/text/json'\nimport { getSessionPlugins } from '@utils/session/sessionPlugins'\nimport { parseJsonOrJsonc } from './internal/jsonc'\n\ntype McpName = string\n\nfunction expandTemplateString(value: string, pluginRoot: string): string {\n return value.replace(/\\$\\{([^}]+)\\}/g, (match, key) => {\n const k = String(key ?? '').trim()\n if (!k) return match\n if (k === 'PYB_PLUGIN_ROOT') return pluginRoot\n const env = process.env[k]\n return env !== undefined ? env : match\n })\n}\n\nfunction expandTemplateDeep(value: unknown, pluginRoot: string): unknown {\n if (typeof value === 'string') return expandTemplateString(value, pluginRoot)\n if (Array.isArray(value))\n return value.map(v => expandTemplateDeep(v, pluginRoot))\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n out[k] = expandTemplateDeep(v, pluginRoot)\n }\n return out\n }\n return value\n}\n\nexport function listPluginMCPServers(): Record<string, McpServerConfig> {\n const plugins = getSessionPlugins()\n if (plugins.length === 0) return {}\n\n const out: Record<string, McpServerConfig> = {}\n\n for (const plugin of plugins) {\n const pluginRoot = plugin.rootDir\n const pluginName = plugin.name\n\n const configs: Array<Record<string, McpServerConfig>> = []\n\n for (const configPath of plugin.mcpConfigFiles ?? []) {\n try {\n const raw = readFileSync(configPath, 'utf8')\n const parsed = parseJsonOrJsonc(raw)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n continue\n const rawServers =\n (parsed as any).mcpServers &&\n typeof (parsed as any).mcpServers === 'object' &&\n !Array.isArray((parsed as any).mcpServers)\n ? (parsed as any).mcpServers\n : parsed\n\n if (\n !rawServers ||\n typeof rawServers !== 'object' ||\n Array.isArray(rawServers)\n )\n continue\n\n const servers: Record<string, McpServerConfig> = {}\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n servers[name] = expandTemplateDeep(cfg, pluginRoot) as McpServerConfig\n }\n configs.push(servers)\n } catch {\n continue\n }\n }\n\n const manifestRaw = (plugin.manifest as any)?.mcpServers\n if (\n manifestRaw &&\n typeof manifestRaw === 'object' &&\n !Array.isArray(manifestRaw)\n ) {\n const rawServers =\n (manifestRaw as any).mcpServers &&\n typeof (manifestRaw as any).mcpServers === 'object' &&\n !Array.isArray((manifestRaw as any).mcpServers)\n ? (manifestRaw as any).mcpServers\n : manifestRaw\n\n if (\n rawServers &&\n typeof rawServers === 'object' &&\n !Array.isArray(rawServers)\n ) {\n const servers: Record<string, McpServerConfig> = {}\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n servers[name] = expandTemplateDeep(cfg, pluginRoot) as McpServerConfig\n }\n configs.push(servers)\n }\n }\n\n const merged: Record<string, McpServerConfig> = Object.assign({}, ...configs)\n\n for (const [serverName, cfg] of Object.entries(merged)) {\n const fullName = `plugin_${pluginName}_${serverName}`\n out[fullName] = cfg\n }\n }\n\n return out\n}\n\nexport function parseEnvVars(\n rawEnvArgs: string[] | undefined,\n): Record<string, string> {\n const parsedEnv: Record<string, string> = {}\n\n if (rawEnvArgs) {\n for (const envStr of rawEnvArgs) {\n const [key, ...valueParts] = envStr.split('=')\n if (!key || valueParts.length === 0) {\n throw new Error(\n `Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`,\n )\n }\n parsedEnv[key] = valueParts.join('=')\n }\n }\n return parsedEnv\n}\n\nconst VALID_SCOPES = ['project', 'global', 'mcprc', 'mcpjson'] as const\ntype ConfigScope = (typeof VALID_SCOPES)[number]\nconst EXTERNAL_SCOPES = [\n 'project',\n 'global',\n 'mcprc',\n 'mcpjson',\n] as ConfigScope[]\n\nexport function ensureConfigScope(scope?: string): ConfigScope {\n if (!scope) return 'project'\n\n const scopesToCheck =\n process.env.USER_TYPE === 'external' ? EXTERNAL_SCOPES : VALID_SCOPES\n\n if (!scopesToCheck.includes(scope as ConfigScope)) {\n throw new Error(\n `Invalid scope: ${scope}. Must be one of: ${scopesToCheck.join(', ')}`,\n )\n }\n\n return scope as ConfigScope\n}\n\nexport function addMcpServer(\n name: McpName,\n server: McpServerConfig,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n addMcprcServerForTesting(name, server)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n let mcprcConfig: Record<string, McpServerConfig> = {}\n\n if (existsSync(mcprcPath)) {\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const existingConfig = safeParseJSON(mcprcContent)\n if (existingConfig && typeof existingConfig === 'object') {\n mcprcConfig = existingConfig as Record<string, McpServerConfig>\n }\n } catch {\n }\n }\n\n mcprcConfig[name] = server\n\n try {\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcprc: ${error}`)\n }\n }\n } else if (scope === 'mcpjson') {\n const mcpJsonPath = join(getCwd(), '.mcp.json')\n let config: Record<string, unknown> = { mcpServers: {} }\n\n if (existsSync(mcpJsonPath)) {\n try {\n const content = readFileSync(mcpJsonPath, 'utf-8')\n const parsed = safeParseJSON(content)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n config = parsed as Record<string, unknown>\n }\n } catch {\n }\n }\n\n const rawServers = (config as { mcpServers?: unknown }).mcpServers\n const servers =\n rawServers && typeof rawServers === 'object' && !Array.isArray(rawServers)\n ? (rawServers as Record<string, McpServerConfig>)\n : ({} as Record<string, McpServerConfig>)\n\n servers[name] = server\n config.mcpServers = servers\n\n try {\n writeFileSync(mcpJsonPath, JSON.stringify(config, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcp.json: ${error}`)\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function removeMcpServer(\n name: McpName,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n removeMcprcServerForTesting(name)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n throw new Error('No .mcprc file found in this directory')\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const mcprcConfig = safeParseJSON(mcprcContent) as Record<\n string,\n McpServerConfig\n > | null\n\n if (\n !mcprcConfig ||\n typeof mcprcConfig !== 'object' ||\n !mcprcConfig[name]\n ) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n\n delete mcprcConfig[name]\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) {\n throw error\n }\n throw new Error(`Failed to remove from .mcprc: ${error}`)\n }\n }\n } else if (scope === 'mcpjson') {\n const mcpJsonPath = join(getCwd(), '.mcp.json')\n if (!existsSync(mcpJsonPath)) {\n throw new Error('No .mcp.json file found in this directory')\n }\n\n try {\n const content = readFileSync(mcpJsonPath, 'utf-8')\n const parsed = safeParseJSON(content) as Record<string, unknown> | null\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Invalid .mcp.json format')\n }\n\n const rawServers = (parsed as { mcpServers?: unknown }).mcpServers\n if (\n !rawServers ||\n typeof rawServers !== 'object' ||\n Array.isArray(rawServers)\n ) {\n throw new Error('Invalid .mcp.json format (missing mcpServers)')\n }\n\n const servers = rawServers as Record<string, McpServerConfig>\n if (!servers[name]) {\n throw new Error(`No MCP server found with name: ${name} in .mcp.json`)\n }\n\n delete servers[name]\n ;(parsed as any).mcpServers = servers\n writeFileSync(mcpJsonPath, JSON.stringify(parsed, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) throw error\n throw new Error(`Failed to remove from .mcp.json: ${error}`)\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No global MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No local MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function listMCPServers(): Record<string, McpServerConfig> {\n const pluginServers = listPluginMCPServers()\n const globalConfig = getGlobalConfig()\n const projectFileConfig = getProjectMcpServerDefinitions().servers\n const projectConfig = getCurrentProjectConfig()\n return {\n ...(pluginServers ?? {}),\n ...(globalConfig.mcpServers ?? {}),\n ...(projectFileConfig ?? {}),\n ...(projectConfig.mcpServers ?? {}),\n }\n}\n\nexport type ScopedMcpServerConfig = McpServerConfig & {\n scope: ConfigScope\n}\n\nexport function getMcpServer(name: McpName): ScopedMcpServerConfig | undefined {\n const projectConfig = getCurrentProjectConfig()\n const projectFileDefinitions = getProjectMcpServerDefinitions()\n const projectFileConfig = projectFileDefinitions.servers\n const globalConfig = getGlobalConfig()\n\n if (projectConfig.mcpServers?.[name]) {\n return { ...projectConfig.mcpServers[name], scope: 'project' }\n }\n\n if (projectFileConfig?.[name]) {\n const source = projectFileDefinitions.sources[name]\n const scope: ConfigScope = source === '.mcp.json' ? 'mcpjson' : 'mcprc'\n return { ...projectFileConfig[name], scope }\n }\n\n if (globalConfig.mcpServers?.[name]) {\n return { ...globalConfig.mcpServers[name], scope: 'global' }\n }\n\n return undefined\n}\n\nexport function getMcprcServerStatus(\n serverName: string,\n): 'approved' | 'rejected' | 'pending' {\n const config = getCurrentProjectConfig()\n if (config.approvedMcprcServers?.includes(serverName)) {\n return 'approved'\n }\n if (config.rejectedMcprcServers?.includes(serverName)) {\n return 'rejected'\n }\n return 'pending'\n}\n", "import { zipObject, memoize } from 'lodash-es'\nimport type { Tool } from '@tool'\nimport { MCPTool } from '@tools/mcp/MCPTool/MCPTool'\nimport { logMCPError } from '@utils/log'\nimport type { Command } from '@commands'\nimport type {\n ImageBlockParam,\n MessageParam,\n ToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/index.mjs'\nimport {\n CallToolResultSchema,\n type ClientRequest,\n type ListPromptsResult,\n ListPromptsResultSchema,\n type ListToolsResult,\n ListToolsResultSchema,\n type Result,\n ResultSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { getClients, type WrappedClient } from './client'\n\ntype ConnectedClient = Extract<WrappedClient, { type: 'connected' }>\n\nfunction sanitizeMcpIdentifierPart(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction getMcpToolTimeoutMs(): number | null {\n const raw = process.env.MCP_TOOL_TIMEOUT\n const parsed = raw ? Number.parseInt(raw, 10) : NaN\n if (!Number.isFinite(parsed) || parsed <= 0) return null\n return parsed\n}\n\ntype TimeoutSignal = { signal: AbortSignal; cleanup: () => void }\n\nfunction createTimeoutSignal(timeoutMs: number): TimeoutSignal {\n const timeoutFn = (AbortSignal as any)?.timeout\n if (typeof timeoutFn === 'function') {\n return { signal: timeoutFn(timeoutMs) as AbortSignal, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n const id = setTimeout(() => controller.abort(), timeoutMs)\n return { signal: controller.signal, cleanup: () => clearTimeout(id) }\n}\n\nfunction mergeAbortSignals(\n signals: Array<AbortSignal | undefined>,\n): { signal: AbortSignal; cleanup: () => void } | null {\n const active = signals.filter((s): s is AbortSignal => !!s)\n if (active.length === 0) return null\n if (active.length === 1) return { signal: active[0]!, cleanup: () => {} }\n\n const controller = new AbortController()\n\n const abort = () => {\n try {\n controller.abort()\n } catch {}\n }\n\n for (const s of active) {\n if (s.aborted) {\n abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n s.addEventListener('abort', abort, { once: true })\n }\n\n return { signal: controller.signal, cleanup: () => {} }\n}\n\nconst IDE_MCP_TOOL_ALLOWLIST = new Set([\n 'mcp__ide__executeCode',\n 'mcp__ide__getDiagnostics',\n])\n\nasync function requestAll<\n ResultT extends Result,\n ResultSchemaT extends typeof ResultSchema,\n>(\n req: ClientRequest,\n resultSchema: ResultSchemaT,\n requiredCapability: string,\n): Promise<{ client: ConnectedClient; result: ResultT }[]> {\n const timeoutMs = getMcpToolTimeoutMs()\n const clients = await getClients()\n const results = await Promise.allSettled(\n clients.map(async client => {\n if (client.type === 'failed') return null\n\n let timeoutSignal: TimeoutSignal | null = null\n\n try {\n let capabilities: Record<string, unknown> | null = client.capabilities ?? null\n\n if (!capabilities) {\n try {\n capabilities = client.client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n client.capabilities = capabilities\n }\n\n if (!(capabilities as any)?.[requiredCapability]) {\n return null\n }\n\n timeoutSignal = timeoutMs ? createTimeoutSignal(timeoutMs) : null\n const merged = mergeAbortSignals([timeoutSignal?.signal])\n\n return {\n client,\n result: (await client.client.request(\n req,\n resultSchema,\n merged?.signal ? ({ signal: merged.signal } as any) : undefined,\n )) as ResultT,\n }\n } catch (error) {\n if (client.type === 'connected') {\n logMCPError(\n client.name,\n `Failed to request '${req.method}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return null\n } finally {\n timeoutSignal?.cleanup()\n }\n }),\n )\n return results\n .filter(\n (\n result,\n ): result is PromiseFulfilledResult<{ client: ConnectedClient; result: ResultT } | null> =>\n result.status === 'fulfilled',\n )\n .map(result => result.value)\n .filter((result): result is { client: ConnectedClient; result: ResultT } => result !== null)\n}\n\nexport const getMCPTools = memoize(async (): Promise<Tool[]> => {\n const toolsList = await requestAll<ListToolsResult, typeof ListToolsResultSchema>(\n {\n method: 'tools/list',\n },\n ListToolsResultSchema,\n 'tools',\n )\n\n return toolsList.flatMap(({ client, result: { tools } }) => {\n const serverPart = sanitizeMcpIdentifierPart(client.name)\n\n return tools\n .map((tool): Tool | null => {\n const toolPart = sanitizeMcpIdentifierPart(tool.name)\n const name = `mcp__${serverPart}__${toolPart}`\n\n if (name.startsWith('mcp__ide__') && !IDE_MCP_TOOL_ALLOWLIST.has(name)) {\n return null\n }\n\n return {\n ...MCPTool,\n name,\n isConcurrencySafe() {\n return tool.annotations?.readOnlyHint ?? false\n },\n isReadOnly() {\n return tool.annotations?.readOnlyHint ?? false\n },\n async description() {\n return tool.description ?? ''\n },\n async prompt() {\n return tool.description ?? ''\n },\n inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'],\n async validateInput() {\n return { result: true }\n },\n async *call(args: Record<string, unknown>, context) {\n const data = await callMCPTool({\n client,\n tool: tool.name,\n args,\n toolUseId: context.toolUseId,\n signal: context.abortController.signal,\n })\n yield {\n type: 'result' as const,\n data,\n resultForAssistant: data,\n }\n },\n userFacingName() {\n const title = tool.annotations?.title || tool.name\n return `${client.name} - ${title} (MCP)`\n },\n }\n })\n .filter((tool): tool is Tool => tool !== null)\n })\n})\n\nasync function callMCPTool({\n client: { client, name },\n tool,\n args,\n toolUseId,\n signal,\n}: {\n client: ConnectedClient\n tool: string\n args: Record<string, unknown>\n toolUseId?: string\n signal?: AbortSignal\n}): Promise<ToolResultBlockParam['content']> {\n const timeoutMs = getMcpToolTimeoutMs()\n const timeoutSignal = timeoutMs ? createTimeoutSignal(timeoutMs) : null\n const merged = mergeAbortSignals([signal, timeoutSignal?.signal])\n\n const meta =\n toolUseId && toolUseId.trim()\n ? { 'claudecode/toolUseId': toolUseId }\n : undefined\n\n try {\n const result = await client.callTool(\n {\n name: tool,\n arguments: args,\n ...(meta ? { _meta: meta } : {}),\n },\n CallToolResultSchema,\n merged?.signal ? ({ signal: merged.signal } as any) : undefined,\n )\n\n if ('isError' in result && result.isError) {\n const contentText =\n 'content' in result && Array.isArray(result.content)\n ? result.content.find(item => item.type === 'text' && 'text' in item)\n : null\n\n const rawMessage =\n contentText && typeof (contentText as any).text === 'string'\n ? String((contentText as any).text)\n : 'error' in result && result.error\n ? String(result.error)\n : ''\n\n const message = rawMessage || `Error calling tool ${tool}`\n logMCPError(name, `Error calling tool ${tool}: ${message}`)\n throw new Error(message)\n }\n\n if ('toolResult' in result) {\n return String(result.toolResult)\n }\n\n if ('structuredContent' in result && result.structuredContent !== undefined) {\n return JSON.stringify(result.structuredContent)\n }\n\n if ('content' in result && Array.isArray(result.content)) {\n return result.content.map(item => {\n if (item.type === 'image') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: String(item.data),\n media_type: item.mimeType as ImageBlockParam.Source['media_type'],\n },\n }\n }\n return item\n })\n }\n\n throw Error(`Unexpected response format from tool ${tool}`)\n } finally {\n timeoutSignal?.cleanup()\n }\n}\n\nexport const getMCPCommands = memoize(async (): Promise<Command[]> => {\n const results = await requestAll<ListPromptsResult, typeof ListPromptsResultSchema>(\n {\n method: 'prompts/list',\n },\n ListPromptsResultSchema,\n 'prompts',\n )\n\n return results.flatMap(({ client, result }) =>\n result.prompts?.map(_ => {\n const serverPart = sanitizeMcpIdentifierPart(client.name)\n const argNames = Object.values(_.arguments ?? {}).map(k => k.name)\n return {\n type: 'prompt',\n name: `mcp__${serverPart}__${_.name}`,\n description: _.description ?? '',\n isEnabled: true,\n isHidden: false,\n progressMessage: 'running',\n userFacingName() {\n const title = typeof (_ as any).title === 'string' ? (_ as any).title : _.name\n return `${client.name}:${title} (MCP)`\n },\n argNames,\n async getPromptForCommand(args: string) {\n const argsArray = args.split(' ')\n return await runCommand({ name: _.name, client }, zipObject(argNames, argsArray))\n },\n } satisfies Command\n }),\n )\n})\n\nexport async function runCommand(\n { name, client }: { name: string; client: ConnectedClient },\n args: Record<string, string>,\n): Promise<MessageParam[]> {\n try {\n const result = await client.client.getPrompt({ name, arguments: args })\n return result.messages.map((message): MessageParam => {\n const content = message.content\n if (content.type === 'text') {\n return {\n role: message.role,\n content: [\n {\n type: 'text',\n text: content.text,\n },\n ],\n }\n }\n if (content.type === 'image' && 'data' in content) {\n return {\n role: message.role,\n content: [\n {\n type: 'image',\n source: {\n data: String((content as any).data),\n media_type: (content as any).mimeType as ImageBlockParam.Source['media_type'],\n type: 'base64',\n },\n },\n ],\n }\n }\n return {\n role: message.role,\n content: [\n {\n type: 'text',\n text: `Unsupported MCP content type ${(content as any)?.type ?? 'unknown'}`,\n },\n ],\n }\n })\n } catch (error) {\n logMCPError(\n client.name,\n `Error running command '${name}': ${error instanceof Error ? error.message : String(error)}`,\n )\n throw error\n }\n}\n\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { type Tool } from '@tool'\nimport { getTheme } from '@utils/theme'\nimport { DESCRIPTION, PROMPT, TOOL_NAME } from './prompt'\nimport { OutputLine } from '@tools/BashTool/OutputLine'\n\nconst inputSchema = z.object({}).passthrough()\n\nexport const MCPTool = {\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false\n },\n name: TOOL_NAME,\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n async *call() {\n yield {\n type: 'result',\n data: '',\n resultForAssistant: '',\n }\n },\n needsPermissions() {\n return true\n },\n renderToolUseMessage(input) {\n return Object.entries(input)\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(', ')\n },\n userFacingName: () => 'mcp',\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n renderToolResultMessage(output) {\n const verbose = false\n if (Array.isArray(output)) {\n return (\n <Box flexDirection=\"column\">\n {output.map((item, i) => {\n if (item.type === 'image') {\n return (\n <Box\n key={i}\n justifyContent=\"space-between\"\n overflowX=\"hidden\"\n width=\"100%\"\n >\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text>[Image]</Text>\n </Box>\n </Box>\n )\n }\n const lines = item.text.split('\\n').length\n return (\n <OutputLine\n key={i}\n content={item.text}\n lines={lines}\n verbose={verbose}\n />\n )\n })}\n </Box>\n )\n }\n\n if (!output) {\n return (\n <Box justifyContent=\"space-between\" overflowX=\"hidden\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text color={getTheme().secondaryText}>(No content)</Text>\n </Box>\n </Box>\n )\n }\n\n const lines = output.split('\\n').length\n return <OutputLine content={output} lines={lines} verbose={verbose} />\n },\n renderResultForAssistant(content) {\n return content\n },\n} satisfies Tool<typeof inputSchema, string>\n", "import * as React from 'react'\nimport { getTheme } from '@utils/theme'\nimport { Text } from 'ink'\nimport { PRODUCT_NAME } from '@constants/product'\n\nexport function FallbackToolUseRejectedMessage(): React.ReactNode {\n return (\n <Text>\n &nbsp;&nbsp;\u23BF &nbsp;\n <Text color={getTheme().error}>\n No (tell {PRODUCT_NAME} what to do differently)\n </Text>\n </Text>\n )\n}\n", "export const TOOL_NAME = 'mcp'\nexport const PROMPT = ''\nexport const DESCRIPTION = ''\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { getTheme } from '@utils/theme'\nimport { MAX_RENDERED_LINES } from './prompt'\nimport chalk from 'chalk'\n\nfunction renderTruncatedContent(content: string, totalLines: number): string {\n const allLines = content.split('\\n')\n if (allLines.length <= MAX_RENDERED_LINES) {\n return allLines.join('\\n')\n }\n\n const lastLines = allLines.slice(-MAX_RENDERED_LINES)\n return [\n chalk.grey(\n `Showing last ${MAX_RENDERED_LINES} lines of ${totalLines} total lines`,\n ),\n ...lastLines,\n ].join('\\n')\n}\n\nexport function OutputLine({\n content,\n lines,\n verbose,\n isError,\n}: {\n content: string\n lines: number\n verbose: boolean\n isError?: boolean\n key?: React.Key\n}) {\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Box flexDirection=\"column\">\n <Text color={isError ? getTheme().error : undefined}>\n {verbose\n ? content.trim()\n : renderTruncatedContent(content.trim(), lines)}\n </Text>\n </Box>\n </Box>\n </Box>\n )\n}\n", "import { watchFile, unwatchFile } from 'fs'\nimport { homedir } from 'os'\nimport {\n getSettingsFileCandidates,\n loadSettingsWithLegacyFallback,\n} from '@utils/config/settingsFiles'\n\nexport type SandboxNetworkConfig = {\n allowedDomains: string[]\n deniedDomains: string[]\n allowUnixSockets: string[]\n allowAllUnixSockets?: boolean\n allowLocalBinding?: boolean\n httpProxyPort?: number\n socksProxyPort?: number\n}\n\nexport type SandboxFilesystemConfig = {\n denyRead: string[]\n allowWrite: string[]\n denyWrite: string[]\n}\n\nexport type SandboxRipgrepConfig = {\n command: string\n args: string[]\n}\n\nexport type SandboxRuntimeConfig = {\n network: SandboxNetworkConfig\n filesystem: SandboxFilesystemConfig\n ignoreViolations?: boolean\n enableWeakerNestedSandbox?: boolean\n ripgrep: SandboxRipgrepConfig\n excludedCommands?: string[]\n}\n\ntype SettingsPermissions = {\n allow?: unknown\n deny?: unknown\n}\n\ntype SettingsSandboxNetwork = {\n allowedDomains?: unknown\n deniedDomains?: unknown\n allowUnixSockets?: unknown\n allowAllUnixSockets?: unknown\n allowLocalBinding?: unknown\n httpProxyPort?: unknown\n socksProxyPort?: unknown\n}\n\ntype SettingsSandboxRipgrep = {\n command?: unknown\n args?: unknown\n}\n\ntype SettingsSandbox = {\n enabled?: unknown\n autoAllowBashIfSandboxed?: unknown\n allowUnsandboxedCommands?: unknown\n network?: SettingsSandboxNetwork\n ignoreViolations?: unknown\n enableWeakerNestedSandbox?: unknown\n ripgrep?: SettingsSandboxRipgrep\n excludedCommands?: unknown\n}\n\nexport type PybSettingsFile = {\n permissions?: SettingsPermissions\n sandbox?: SettingsSandbox\n [key: string]: unknown\n}\n\ntype ToolRuleValue = { toolName: string; ruleContent?: string }\n\nfunction parseToolRuleString(rule: string): ToolRuleValue {\n const match = rule.match(/^([^(]+)\\(([^)]+)\\)$/)\n if (!match) return { toolName: rule }\n\n const toolName = match[1]\n const ruleContent = match[2]\n if (!toolName || !ruleContent) return { toolName: rule }\n return { toolName, ruleContent }\n}\n\nfunction uniqueStrings(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const out: string[] = []\n const seen = new Set<string>()\n for (const item of value) {\n if (typeof item !== 'string') continue\n const trimmed = item.trim()\n if (!trimmed) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n return out\n}\n\nfunction uniqueStringsUnion(...lists: string[][]): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n for (const list of lists) {\n for (const item of list) {\n const trimmed = item.trim()\n if (!trimmed) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n }\n return out\n}\n\nfunction mergeSandboxSettings(\n base: SettingsSandbox | undefined,\n next: SettingsSandbox | undefined,\n): SettingsSandbox | undefined {\n if (!base && !next) return undefined\n const merged: SettingsSandbox = { ...(base ?? {}) }\n\n const mergeBool = (k: keyof SettingsSandbox) => {\n if (next && k in next && next[k] !== undefined) merged[k] = next[k]\n }\n mergeBool('enabled')\n mergeBool('autoAllowBashIfSandboxed')\n mergeBool('allowUnsandboxedCommands')\n mergeBool('ignoreViolations')\n mergeBool('enableWeakerNestedSandbox')\n mergeBool('excludedCommands')\n\n if (next?.network) {\n merged.network = { ...(merged.network ?? {}), ...next.network }\n }\n if (next?.ripgrep) {\n merged.ripgrep = { ...(merged.ripgrep ?? {}), ...next.ripgrep }\n }\n\n return merged\n}\n\nexport function loadMergedSettings(options?: {\n projectDir?: string\n homeDir?: string\n}): PybSettingsFile {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir\n\n const user = loadSettingsWithLegacyFallback({\n destination: 'userSettings',\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n const project = loadSettingsWithLegacyFallback({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n const local = loadSettingsWithLegacyFallback({\n destination: 'localSettings',\n projectDir,\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n\n const allow = uniqueStringsUnion(\n uniqueStrings(user?.permissions?.allow),\n uniqueStrings(project?.permissions?.allow),\n uniqueStrings(local?.permissions?.allow),\n )\n const deny = uniqueStringsUnion(\n uniqueStrings(user?.permissions?.deny),\n uniqueStrings(project?.permissions?.deny),\n uniqueStrings(local?.permissions?.deny),\n )\n\n const sandbox = mergeSandboxSettings(\n mergeSandboxSettings(user?.sandbox, project?.sandbox),\n local?.sandbox,\n )\n\n return {\n permissions: { allow, deny },\n ...(sandbox ? { sandbox } : {}),\n }\n}\n\nexport function normalizeSandboxRuntimeConfigFromSettings(\n settings: PybSettingsFile,\n options?: {\n projectDir?: string\n homeDir?: string\n defaultRipgrep?: SandboxRipgrepConfig\n },\n): SandboxRuntimeConfig {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir ?? homedir()\n\n const permissions = settings.permissions ?? {}\n const allowRules = uniqueStrings(permissions.allow)\n const denyRules = uniqueStrings(permissions.deny)\n\n const explicitAllowedDomains = uniqueStrings(\n settings.sandbox?.network?.allowedDomains,\n )\n const allowedDomains: string[] = [...explicitAllowedDomains]\n const deniedDomains: string[] = []\n\n for (const rule of allowRules) {\n const parsed = parseToolRuleString(rule)\n if (\n parsed?.toolName === 'WebFetch' &&\n parsed.ruleContent?.startsWith('domain:')\n ) {\n allowedDomains.push(parsed.ruleContent.substring(7))\n }\n }\n\n for (const rule of denyRules) {\n const parsed = parseToolRuleString(rule)\n if (\n parsed?.toolName === 'WebFetch' &&\n parsed.ruleContent?.startsWith('domain:')\n ) {\n deniedDomains.push(parsed.ruleContent.substring(7))\n }\n }\n\n const allowWrite: string[] = ['.']\n const denyWrite: string[] = []\n const denyRead: string[] = []\n\n const userCandidates = getSettingsFileCandidates({\n destination: 'userSettings',\n homeDir,\n })\n const userCandidatesWithEnv = getSettingsFileCandidates({\n destination: 'userSettings',\n })\n const projectCandidates = getSettingsFileCandidates({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n })\n const localCandidates = getSettingsFileCandidates({\n destination: 'localSettings',\n projectDir,\n homeDir,\n })\n\n for (const path of [\n userCandidates?.primary,\n ...(userCandidates?.legacy ?? []),\n userCandidatesWithEnv?.primary,\n ...(userCandidatesWithEnv?.legacy ?? []),\n projectCandidates?.primary,\n ...(projectCandidates?.legacy ?? []),\n localCandidates?.primary,\n ...(localCandidates?.legacy ?? []),\n ]) {\n if (!path) continue\n if (denyWrite.includes(path)) continue\n denyWrite.push(path)\n }\n\n for (const rule of allowRules) {\n const parsed = parseToolRuleString(rule)\n if (\n (parsed?.toolName === 'Write' || parsed?.toolName === 'Edit') &&\n parsed.ruleContent\n ) {\n allowWrite.push(parsed.ruleContent)\n }\n }\n\n for (const rule of denyRules) {\n const parsed = parseToolRuleString(rule)\n if (\n (parsed?.toolName === 'Write' || parsed?.toolName === 'Edit') &&\n parsed.ruleContent\n ) {\n denyWrite.push(parsed.ruleContent)\n }\n if (parsed?.toolName === 'Read' && parsed.ruleContent) {\n denyRead.push(parsed.ruleContent)\n }\n }\n\n const sandboxNetwork = settings.sandbox?.network\n\n const defaultRipgrep: SandboxRipgrepConfig = options?.defaultRipgrep ?? {\n command: 'rg',\n args: [],\n }\n const ripgrep: SandboxRipgrepConfig =\n typeof settings.sandbox?.ripgrep?.command === 'string'\n ? {\n command: settings.sandbox!.ripgrep!.command as string,\n args: Array.isArray(settings.sandbox?.ripgrep?.args)\n ? (settings.sandbox!.ripgrep!.args as unknown[]).filter(\n (v): v is string => typeof v === 'string',\n )\n : [],\n }\n : defaultRipgrep\n\n return {\n network: {\n allowedDomains: uniqueStringsUnion(allowedDomains),\n deniedDomains: uniqueStringsUnion(deniedDomains),\n allowUnixSockets: Array.isArray(sandboxNetwork?.allowUnixSockets)\n ? (sandboxNetwork!.allowUnixSockets as unknown[]).filter(\n (v): v is string => typeof v === 'string',\n )\n : [],\n allowAllUnixSockets:\n typeof sandboxNetwork?.allowAllUnixSockets === 'boolean'\n ? sandboxNetwork.allowAllUnixSockets\n : undefined,\n allowLocalBinding:\n typeof sandboxNetwork?.allowLocalBinding === 'boolean'\n ? sandboxNetwork.allowLocalBinding\n : undefined,\n httpProxyPort:\n typeof sandboxNetwork?.httpProxyPort === 'number'\n ? sandboxNetwork.httpProxyPort\n : undefined,\n socksProxyPort:\n typeof sandboxNetwork?.socksProxyPort === 'number'\n ? sandboxNetwork.socksProxyPort\n : undefined,\n },\n filesystem: {\n denyRead: uniqueStringsUnion(denyRead),\n allowWrite: uniqueStringsUnion(allowWrite),\n denyWrite: uniqueStringsUnion(denyWrite),\n },\n ignoreViolations:\n typeof settings.sandbox?.ignoreViolations === 'boolean'\n ? settings.sandbox.ignoreViolations\n : undefined,\n enableWeakerNestedSandbox:\n typeof settings.sandbox?.enableWeakerNestedSandbox === 'boolean'\n ? settings.sandbox.enableWeakerNestedSandbox\n : undefined,\n excludedCommands: uniqueStrings(settings.sandbox?.excludedCommands),\n ripgrep,\n }\n}\n\nfunction looksLikeLinuxGlobPattern(ruleContent: string): boolean {\n const trimmed = ruleContent.replace(/\\/\\*\\*$/, '')\n return /[*?[\\]]/.test(trimmed)\n}\n\nexport function getLinuxSandboxGlobPatternWarnings(\n settings: PybSettingsFile,\n options?: { platform?: NodeJS.Platform },\n): string[] {\n const platform = options?.platform ?? process.platform\n if (platform !== 'linux') return []\n if (settings.sandbox?.enabled !== true) return []\n\n const permissions = settings.permissions ?? {}\n const allow = uniqueStrings(permissions.allow)\n const deny = uniqueStrings(permissions.deny)\n\n const warnings: string[] = []\n for (const rule of [...allow, ...deny]) {\n const parsed = parseToolRuleString(rule)\n if (!parsed?.ruleContent) continue\n if (\n parsed.toolName !== 'Write' &&\n parsed.toolName !== 'Edit' &&\n parsed.toolName !== 'Read'\n )\n continue\n if (!looksLikeLinuxGlobPattern(parsed.ruleContent)) continue\n warnings.push(rule)\n }\n\n return warnings\n}\n\nexport type SandboxConfigListener = (config: SandboxRuntimeConfig) => void\n\nexport class SandboxConfigManager {\n private listeners = new Set<SandboxConfigListener>()\n private watchPaths: string[] = []\n private current: SandboxRuntimeConfig | null = null\n\n getCurrent(): SandboxRuntimeConfig {\n if (!this.current) {\n const settings = loadMergedSettings()\n this.current = normalizeSandboxRuntimeConfigFromSettings(settings)\n }\n return this.current\n }\n\n subscribe(listener: SandboxConfigListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n initialize(options?: { projectDir?: string; homeDir?: string }): void {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir ?? homedir()\n const user = getSettingsFileCandidates({\n destination: 'userSettings',\n homeDir,\n })\n const userEnv = getSettingsFileCandidates({ destination: 'userSettings' })\n const project = getSettingsFileCandidates({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n })\n const local = getSettingsFileCandidates({\n destination: 'localSettings',\n projectDir,\n homeDir,\n })\n\n const paths = [\n user?.primary,\n ...(user?.legacy ?? []),\n userEnv?.primary,\n ...(userEnv?.legacy ?? []),\n project?.primary,\n ...(project?.legacy ?? []),\n local?.primary,\n ...(local?.legacy ?? []),\n ].filter((p): p is string => Boolean(p))\n this.watchPaths = Array.from(new Set(paths))\n\n for (const p of this.watchPaths) {\n watchFile(p, { interval: 1000 }, () => {\n const settings = loadMergedSettings({ projectDir, homeDir })\n this.current = normalizeSandboxRuntimeConfigFromSettings(settings, {\n projectDir,\n homeDir,\n })\n for (const listener of this.listeners) listener(this.current)\n })\n }\n }\n\n close(): void {\n for (const p of this.watchPaths) {\n try {\n unwatchFile(p)\n } catch {}\n }\n this.watchPaths = []\n }\n}\n", "const MAX_LINES_TO_READ = 2000\nconst MAX_LINE_LENGTH = 2000\n\nexport const TOOL_NAME = 'Read'\nexport const DESCRIPTION = 'Read a file or directory from the local filesystem.'\n\nexport const PROMPT = `Reads a file or directory from the local filesystem. You can access any file or directory directly by using this tool.Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid; otherwise, Ensure the path is confirmed by Glob/Grep before reading.\n\n## Best Practice\n- **Read vs Analyze**: Use this tool when you need to inspect full implementation details.\n- **Workflow**: Locate file (Glob/Grep) -> Read file (FileRead) -> Edit file.\n- **Avoid**: Do not use this to 'search' for code strings; use 'Grep' or 'Glob' for that.\n\n## When NOT to Use Read Tool\n- **Unverified Paths**: Do NOT read a file if the path was inferred or guessed from context. Always verify the path exists using Glob/Grep first.\n- **Exploration Phase**: When exploring unfamiliar code, do NOT assume file locations. Use Glob/Grep to discover actual paths before reading.\n- It is okay to read a file that does not exist; an error will be returned. \n\n## Usage Details\n- The file_path parameter must be an absolute path, not a relative path\n- This tool supports both file mode and directory mode\n- In directory mode, offset/limit are 1-based entry pagination and offset>=1 is required\n- In file mode, offset/limit are 1-based line pagination; offset=1 starts from the first line shown in cat -n output\n- By default, file mode reads up to ${MAX_LINES_TO_READ} lines starting from the beginning of the file\n- You can optionally specify a line offset and limit (especially handy for long files). **Smart Truncation is active** only in file mode when \\`limit\\` is provided and \\`symbol_name\\` is not provided: if your limit cuts a function or class in the middle, the tool will automatically extend the read range to include the full semantic block (up to 500 extra lines).\n- Smart Truncation is a best-effort semantic boundary repair (Tree-sitter). If semantic parsing fails, Read falls back to the original offset/limit window.\n- symbol_name enables LSP-assisted symbol read: provide an exact symbol name to resolve the symbol range and read that block directly\n- When \\`symbol_name\\` is provided, Read resolves symbol range via LSP and reads that block directly (offset/limit are ignored for range selection).\n- Use symbol_name only after file path is confirmed and when you need a specific class/function definition; if symbol is missing, unresolved, or LSP is unavailable, fallback to offset/limit or use LspTool for semantic discovery first.\n- Directory mode returns a one-level tree structure using \u251C\u2500\u2500/\u2514\u2500\u2500 and supports pagination continuation hints\n- For large files, iterate in chunks: offset=1 limit=200, then offset=201 limit=200, and so on until the needed region is covered\n- File text truncation is capped at 50KB per result and 2000 lines; 50KB is file text truncation and not a directory access gate\n- Any lines longer than ${MAX_LINE_LENGTH} characters will be truncated\n- Results are returned using cat -n format, with line numbers starting at 1\n- This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually.\n- This tool can read PDF files and return them as document blocks for analysis.\n- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.\n- For wide repository exploration, still prefer Glob first, then use Read for focused file/directory inspection.\n- You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.\n- You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n\n## Typical Usage Examples\n### Example 1: Exploring Unfamiliar Codebase\n <example>\n user: How does authentication work in this project?\n assistant: [uses Grep tool with pattern=\"auth|login\" to find relevant files]\n [uses Glob tool with pattern=\"**/auth*.{ts,js}\" to locate auth modules]\n [reads the matched files after confirming their paths]\n </example>\n\n### Example 2: User Mentions a Concept Without Path\n <example>\n user: Check the database configuration\n assistant: [uses Glob tool with pattern=\"**/config*.{ts,js,json}\"]\n [uses Grep tool with pattern=\"database|db_\" to find config files with db settings]\n [reads the confirmed config file]\n </example>\n\n### Example 3: Read Directory Structure Then Read File\n <example>\n user: Check the API module layout and read router implementation\n assistant: [uses Glob tool with pattern=\"**/api*\"]\n [reads the confirmed api directory path to get one-level tree structure with Read]\n [reads the router file path found in that directory tree]\n </example>\n\n### Example 4: LSP-Assisted Symbol Read\n <example>\n user: I only need the function that actually executes file reading, not the whole file\n assistant: [uses Glob/Grep to confirm FileReadTool file path]\n [uses Read with file_path=\"<absolute path>/FileReadTool.tsx\" symbol_name=\"call\"]\n [if symbol is missing or unresolved, uses LspTool documentSymbol to discover exact symbol names, then retries]\n [if LSP is unavailable, falls back to offset/limit chunked reads around likely implementation area]\n <reasoning>\n The assistant used symbol_name-based Read because:\n 1. User intent is a specific implementation block, not whole-file browsing\n 2. symbol_name gives precise semantic range selection and avoids noisy context\n 3. LspTool is used only for symbol discovery fallback, while Read remains the code retrieval tool\n </reasoning>\n </example>\n\n### Example 5: Smart Truncation on Partial Window\n <example>\n user: Please read this file section for me; I do not know where the function ends\n assistant: [uses Read with file_path=\"<absolute path>/service.ts\" offset=120 limit=30]\n [relies on Smart Truncation to auto-extend when the requested window cuts a function/class boundary]\n [checks returned startLine/numLines and continues with adjacent chunks if more context is needed]\n [if semantic parsing fails, falls back to original offset/limit and continues chunked reading]\n <reasoning>\n The assistant used offset/limit Read with Smart Truncation because:\n 1. User asked for a local section without symbol-level knowledge\n 2. Pagination windows can split semantic containers, causing misleading partial code\n 3. Smart Truncation repairs semantic boundaries while preserving pagination workflow\n </reasoning>\n </example>\n`.trim()\n", "export const TOOL_NAME = 'Edit'\nexport const DESCRIPTION = `Performs smart string replacements in files using SEARCH/REPLACE blocks.\n\nUsage:\n1. **Read First**: You must use your \\`Read\\` tool at least once before editing.\n2. **Block Format**: Provide changes as one or more SEARCH/REPLACE blocks.\n \\`\\`\\`\n <<<<<<< SEARCH\n [original code to replace]\n =======\n [new code to insert]\n >>>>>>> REPLACE\n \\`\\`\\`\n3. **Multiple Edits**: You can provide multiple blocks in a single turn to perform batch edits.\n4. **Context**: Include enough surrounding lines in the SEARCH block to ensure uniqueness.\n5. **Indentation**: Preserve the exact indentation (tabs/spaces) of the original file in your SEARCH block.\n6. **Smart Matching**: The tool uses a fuzzy matching engine. It can locate code even if there are minor differences in whitespace or indentation.\n7. **Conditional Edit**: Use \\`if_not_contains\\` to skip the edit if the file already contains a specific string.\n8. **Thinking**: You can include \"thinking\" text between blocks; the tool will ignore it.\n\n## LSP-Integrated Behavior\n- **Semantic Anchor Assist**: Before fuzzy replacement, Edit tries LSP anchor matching to narrow replacement to the most relevant symbol range.\n- **When It Helps**: Especially useful when the same snippet appears multiple times and plain text matching may hit the wrong block.\n- **Fallback**: If LSP anchor is unavailable, Edit falls back to normal SEARCH/REPLACE matching.\n- **Post-Edit Verification**: Set \\`verify: true\\` to run LSP diagnostics after applying edits.\n- **Verification Guardrail**: If syntax/type diagnostics contain errors after edit, Edit reverts changes and returns a verification failure.\n- **When LSP Is Unavailable**: You may receive verification unavailable; retry with \\`verify: false\\` only when you have high confidence in edit safety.\n\nNotes:\n- The edit will FAIL if the SEARCH block matches multiple locations(ambiguous). Provide more context.\n- To delete code, leave the REPLACE section empty.\n- To create a new file, use an empty SEARCH block with the desired content in REPLACE.\n- ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\n- For Jupyter Notebooks (.ipynb), use the NotebookEditTool instead.\n\n## Typical Usage Examples\n### Example 1: Ambiguous Duplicate Snippet with LSP Anchor\n<example>\nuser: Update the constructor guard in UserService, not the test helper copy\nassistant: [uses Read on UserService file to confirm target block]\n[uses Edit with SEARCH/REPLACE block and verify=true]\n[relies on LSP anchor assist to prefer semantic symbol region when duplicate text exists]\n<reasoning>\nThe assistant enabled semantic-safe editing because:\n1. Duplicate snippets can cause ambiguous fuzzy matches\n2. LSP anchor narrows replacement to the intended symbol scope\n3. verify=true adds post-edit diagnostics guardrail and auto-revert on syntax errors\n</reasoning>\n</example>\n\n### Example 2: Verification-Unavailable Recovery\n<example>\nuser: Apply this quick rename in a generated file\nassistant: [uses Read to confirm exact path and block]\n[uses Edit with verify=true]\n[if response says verification unavailable, retries with verify=false and tighter SEARCH context]\n<reasoning>\nThe assistant keeps verification first, then degrades safely because:\n1. LSP verification is preferred for correctness\n2. Generated or unsupported files may not have active LSP diagnostics\n3. Retrying with verify=false is acceptable only after narrowing context\n</reasoning>\n</example>\n`.trim()\n", "import { TOOL_NAME as TOOL_NAME_READ } from '../FileReadTool/prompt'\n\nexport const TOOL_NAME = 'Write'\nexport const DESCRIPTION = 'Write a file to the local filesystem.'\n\nexport const PROMPT = `Writes a file to the local filesystem.\n\nUsage:\n- This tool will overwrite the existing file if there is one at the provided path.\n- If this is an existing file, you MUST use the ${TOOL_NAME_READ} tool first to read the file's contents. This tool will fail if you did not read the file first.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.\n- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.\n`.trim()\n", "export const TOOL_NAME = 'Glob'\n\nexport const DESCRIPTION = `Fast file pattern matching tool that works with any codebase size\n\n ## WhenToUse & Best Practice\n - If you have keywords or fuzzy paths, use Glob first to narrow candidates.\n - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead\n - You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.\n - This tool is for FINDING files.\n\n ## Directory Structure Guidance\n - For one-level directory structure, use Read directly on the directory path (offset>=1, optional limit)\n - Use Glob for file-path discovery and candidate narrowing, not as the primary one-level directory listing workflow\n\n ## Search Strategy\n - **Broad-to-Narrow Pattern**: Start with a broad pattern, then narrow based on results.\n - Step 1: Use broad patterns like \\`**/*.ts\\` or \\`src/**/*\\` to get an overview\n - Step 2: Analyze results and refine with more specific patterns\n - Example: \"\\`**/*.test.ts\\`\" \u2192 too many results \u2192 \"src/**/auth*.test.ts\"\n - **Pattern Selection Guide**:\n - Unknown structure? Start with \\`**/*.{ext}\\` to discover layout, then use Read on specific directory paths for one-level structure\n - Looking for specific type? Use descriptive names: \\`**/test*\\`, \\`**/config*\\`\n - In a specific area? Combine path + pattern: \\`src/auth/**/*.ts\\`\n - **Discovery Workflow**: For unfamiliar codebases, run these in parallel:\n - \\`**/package.json\\`, \\`**/*.{ts,js,tsx,jsx}\\`, \\`**/README*\\`, \\`**/*config*.{ts,js,json}\\`\n - Analyze structure \u2192 refine search \u2192 read key files\n - **Tool Collaboration**:\n - Read \\`directory_path\\` \u2192 Get one-level directory tree structure\n - Grep \u2192 After Glob finds files, use Grep to search content\n - Read \u2192 Read the found file contents\n\n ## Usage Details\n - Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n - Returns absolute file paths sorted by modification time (most recent first)\n - Use this tool when you need to find files by name patterns\n - Powered by ripgrep with \\`--files\\` mode for fast pattern matching\n - \\`path\\` parameter: Specify the directory to search in. If omitted, uses the current working directory. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Supports both relative and absolute paths.\n - Results are limited to 100 files by default. If truncated, use a more specific path or pattern to narrow results.\n - Search ignores .gitignore rules and includes hidden files by default.\n - **Empty Results**: When no files are found, try broader patterns (e.g., src/**/*) or verify path exists.\n - **Error Handling**: Returns error if \\`path\\` does not exist or is not a valid directory.\n - **LSP Semantic Mode**: \\`semantic: true\\` enables workspace symbol fallback when file globbing returns empty.\n - **Semantic search is opt-in**: Only set \\`semantic: true\\` when you intentionally want LSP-assisted fallback.\n - Semantic output may include:\n - \\`semanticNotice\\`: human-readable semantic fallback note\n - \\`semanticReason\\`: structured reason code (e.g., \\`SYMBOLS_ADDED\\`, \\`NO_SYMBOL_MATCH\\`, \\`LSP_UNAVAILABLE\\`)\n - \\`semanticSuggestion\\`: suggested next action aligned to reason code\n - **Truncated Results**: When results are truncated (limited to 100 files), narrow down using:\n 1. Add a more specific path: \\`src/core/**/*.ts\\` instead of \\`**/*.ts\\`\n 2. Use file extension filter: \\`src/**/*.test.ts\\` instead of \\`src/**/*.ts\\`\n 3. Use Read on a specific directory path to confirm one-level structure, then target specific directories with Glob\n\n ## Typical Usage Examples\n\n ### Example 1: Project Structure Discovery (Unknown Codebase)\n <example>\n user: I'm new to this project, what's the structure? \n assistant: [uses Glob tool with pattern=\"**/package.json\" to find project roots]\n [reads the confirmed source directory path to inspect one-level tree structure]\n [uses Glob tool with pattern=\"**/*.{ts,tsx,js,jsx}\" to locate major source areas]\n </example>\n\n ### Example 2: Find Files by Type in Specific Area\n <example>\n user: Find all test files in the auth module\n assistant: [uses Glob tool with pattern=\"src/auth/**/*.test.ts\"]\n [uses Read tool to examine specific test files]\n </example>\n\n ### Example 3: Config File Location (Deterministic) \n <example>\n user: Where is the webpack configuration?\n assistant: [uses Glob tool with pattern=\"**/webpack*.{js,ts,json}\"]\n [uses Read tool on the matched config file]\n </example>\n\n ### Example 4: Parallel Discovery for Entry Points\n <example>\n user: What are the main entry points of this application?\n assistant: [uses Glob tool with pattern=\"**/index.{ts,js}\"]\n [uses Glob tool with pattern=\"**/main.{ts,js}\"]\n [uses Glob tool with pattern=\"**/app.{ts,js}\"]\n [uses Read tool to examine the entry point files]\n </example>\n\n ### Example 5: Narrow Down After Broad Results\n <example>\n user: Find all TypeScript files in the project\n assistant: [uses Glob tool with pattern=\"**/*.ts\" - returns 500+ files, truncated]\n [uses Glob tool with pattern=\"src/**/*.ts\" to focus on source code]\n [uses Glob tool with pattern=\"src/core/**/*.ts\" to narrow further if needed]\n </example>\n\n ### Example 6: Semantic Fallback for Unknown File Path\n <example>\n user: Find where AuthService is implemented, I do not know the file name\n assistant: [uses Glob tool with pattern=\"**/*AuthService*\" semantic=false first]\n [if no files found, retries with semantic=true]\n [reads semanticReason and semanticSuggestion to decide next step]\n <reasoning>\n The assistant switches to semantic mode because:\n 1. Filename-based glob failed and user intent is symbol-oriented\n 2. semantic=true allows LSP workspace symbols to recover likely file paths\n 3. semanticReason + semanticSuggestion provide explicit fallback diagnostics\n </reasoning>\n </example>\n`.trim()\n", "export const TOOL_NAME = 'Grep'\n\nexport const DESCRIPTION = `A powerful fast content search tool that works with any codebase size\n\n ## Best Practice\n - Use Grep as a \"Scout\" to *find* entry points based on text patterns.\n - STEP 1: Search for a unique string (e.g., error message, URL route, specific variable name).\n - STEP 2: Once you get a match (File + Line Number), STOP grepping.\n - STEP 3: Use Read to get the exact line + character, then call LspTool for definition or references.\n - AVOID: Do not use Grep to trace execution flow (e.g., searching for \"functionName\" manually). Use LSP for that.\n - Hotspot strategy: narrow the path scope first, then paginate or refine the search; after truncation, focus on high-signal directories to avoid full-repo scans.\n\n ## Search Strategy\n - **Pattern Refinement Workflow**:\n - Start broad: simple keyword first, observe results\n - Narrow down: add constraints (type, glob, path) if too many matches\n - Switch mode: \\`files_with_matches\\` for discovery, \\`content\\` for details\n - **From Vague Intent to Precise Pattern**:\n - \"How does auth work?\" \u2192 Start with Grep(\"auth\", type=\"ts\") \u2192 Analyze results \u2192 Refine pattern\n - \"Find the API endpoints\" \u2192 Grep(\"router|route|endpoint\", type=\"ts\") \u2192 Read key files\n - \"Where is this error from?\" \u2192 Grep(exact error message) \u2192 Trace back to source\n - **Iterative Narrowing**:\n - Too many results? Add \\`glob\\`, \\`type\\`, or narrower \\`path\\`\n - No results? Broaden pattern, try case-insensitive (\\`-i\\`), or try alternative keywords\n - Wrong results? Adjust pattern, check regex syntax, try alternative keywords\n - **Tool Collaboration**:\n - Read \"directory_path\" \u2192 Confirm one-level directory structure for search scope\n - Glob \"file_path\" \u2192 Confirm file path existence\n - Read \u2192 Read specific content of matched files\n - LspTool \u2192 Trace definitions and references (replace manual Grep tracing)\n\n ## Usage Details\n - ALWAYS use Grep for search tasks. NEVER invoke \\`grep\\` or \\`rg\\` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Powered by ripgrep for fast text search with full regex support (e.g., \"log.*Error\", \"function\\\\s+\\\\w+\")\n - Pattern syntax: Uses ripgrep - literal braces need escaping (use \\`interface\\\\{\\\\}\\` to find \\`interface{}\\` in Go code)\n - Excludes version control directories (.git, .svn, .hg, .bzr) automatically\n - Includes hidden files by default\n\n **Path & Scope**:\n - \\`path\\` parameter: File or directory to search in. Defaults to current working directory.\n - \\`glob\\` parameter: Filter files by glob pattern (e.g., \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob\n - \\`type\\` parameter: Filter by file type (e.g., \"js\", \"py\", \"rust\", \"go\", \"java\") - more efficient than glob for standard types\n - Path guidance: If user provides a path, use it directly. If uncertain, confirm with Glob first.\n\n **Output Modes**:\n - \\`files_with_matches\\` (default): Returns file paths sorted by modification time\n - \\`content\\`: Shows matching lines with line numbers (supports -A/-B/-C context)\n - \\`count\\`: Shows match counts per file\n\n **Context & Pagination**:\n - \\`-B\\`, \\`-A\\`, \\`-C\\`: Context lines before/after/around matches (requires output_mode: \"content\")\n - \\`-n\\`: Show line numbers (default: true, requires output_mode: \"content\")\n - \\`head_limit\\`: Limit output to first N entries (works across all modes)\n - \\`offset\\`: Skip first N entries before applying head_limit\n - \\`multiline\\`: Enable multiline mode where . matches newlines (default: false)\n\n **Case Sensitivity**:\n - \\`-i\\`: Enable case-insensitive search\n\n **Result Handling**:\n - Results are truncated at 20,000 characters if too large\n - Use Task tool for open-ended searches requiring multiple rounds\n - **Semantic Fallback** (\\`semantic: true\\`): when text grep has no hit (or \\`symbol_type\\` is provided), Grep can query LSP workspace symbols.\n - Semantic-enhanced outputs may include:\n - \\`semanticNotice\\`: fallback summary\n - \\`semanticReason\\`: structured reason code (e.g., \\`SYMBOLS_ADDED\\`, \\`NO_SYMBOL_MATCH\\`, \\`LSP_UNAVAILABLE\\`)\n - \\`semanticSuggestion\\`: suggested next action by reason code\n - Keep deterministic workflow: text search first, semantic fallback second.\n\n **Typical Usage Examples**:\n\n Example 1: Exact Error Message Tracing (Deterministic)\n <example>\n user: Where does the error \"Connection timeout after 30s\" come from?\n assistant: [uses Grep tool with pattern=\"Connection timeout after 30s\"output_mode=\"content\"]\n [uses Read tool to examine the error source and surrounding context]\n </example>\n\n Example 2: Precise Function Definition Lookup (Deterministic)\n <example>\n user: Find the implementation of \\`calculateCompoundInterest\\` function\n assistant: [uses Grep tool with pattern=\"calculateCompoundInterest\" type=\"ts\"output_mode=\"content\"]\n [uses Read tool on the matched file to read the full implementation]\n </example>\n \n Example 3: Iterative Narrowing for Broad Patterns\n <example>\n user: Find all API route definitions\n assistant: [uses Grep tool with pattern=\"router\\\\.(get|post|put|delete)\" type=\"ts\"] \n [if too many results: adds path=\"src/routes\" to narrow scope]\n [uses Read tool to inspect specific route handlers]\n </example>\n\n Example 4: Handoff to LSP After Entry Point Found\n <example>\n user: Find all usages of the \\`PaymentService\\` class\n assistant: [uses Grep tool with pattern=\"class PaymentService\" type=\"ts\"output_mode=\"content\"]\n [uses LSP findReferences at the class definition location to get all references]\n </example>\n\n Example 5: Case-Insensitive Search for Config Values\n <example>\n user: Where is the database host configured?\n assistant: [uses Grep tool with pattern=\"database.*host|db_host|DB_HOST\" -i: true] \n [uses Read tool to examine configuration files]\n </example>\n\n Example 6: Semantic Fallback with Structured Reason\n <example>\n user: Find usages of PaymentSrvce (name might be misspelled)\n assistant: [uses Grep tool with pattern=\"PaymentSrvce\" output_mode=\"files_with_matches\"]\n [if no hit, retries with semantic=true]\n [uses semanticReason and semanticSuggestion to decide whether to broaden query or switch to LspTool]\n <reasoning>\n The assistant uses semantic fallback because:\n 1. Text grep may miss typo-tolerant symbol matches\n 2. LSP workspace symbols can recover intended semantic targets\n 3. Structured reason fields make fallback outcomes explicit and actionable\n </reasoning>\n </example>\n `.trim()\n", "export const TOOL_NAME = 'LSP'\n\nexport const PROMPT = `Interact with Language Server Protocol (LSP) servers to get code intelligence features.Supports all languages.\n\n## Capabilities & Scenarios\nThis tool acts as your \"Code Analyst\". Use it to understand the codebase semantically, rather than just matching text.\n\n### 1. Tracing Logic (Where does this go?)\n- **Scenario**: You see a function call \\`calculateTax(amount)\\` and need to know its formula.\n- **Action**: Use \\`goToDefinition\\` on the function name.\n- **Why**: It jumps directly to the implementation, even if it's imported from another file.\n\n### 2. Impact Analysis (What uses this?)\n- **Scenario**: You are planning to rename or modify the \\`User\\` class.\n- **Action**: Use \\`findReferences\\` at the symbol position (line + character) in the file where \\`User\\` is declared or used.\n- **Why**: It lists every file and line where \\`User\\` is referenced, ensuring you don't break dependents.\n\n### 3. Exploring New Files (What's in here?)\n- **Scenario**: You just opened a large file \\`utils.ts\\` and want a quick overview.\n- **Action**: Use \\`documentSymbol\\`.\n- **Why**: It returns a structured outline (Classes, Functions, Variables) using LspFacade policy: LSP-first for accuracy, Tree-Sitter fallback for speed when needed.\n\n### 4. Interface Implementation (Who implements this?)\n- **Scenario**: You see an interface \\`IStorage\\` and want to find the concrete class (e.g., \\`S3Storage\\`).\n- **Action**: Use \\`goToImplementation\\`.\n- **Why**: Grep might just find the import; LSP finds the actual code that implements the interface.\n\n### 5. Scope Analysis (What is visible here?)\n- **Scenario**: You are debugging a closure or nested function and want to know which variables are captured or locally defined.\n- **Action**: Use \\`getScope\\`.\n- **Why**: It returns the local variables and closure captures at the current position. Essential for debugging Python closures or JavaScript lexical scopes.\n\n### 6. Real-time Diagnostics (Is this correct?)\n- **Scenario**: You just edited a file and want to verify if you introduced any syntax errors.\n- **Action**: Use \\`diagnostics\\` with \\`waitForDiagnostics: true\\`.\n- **Why**: It waits for the language server to re-analyze the file and returns fresh errors/warnings. This is your \"Self-Correction\" mechanism.\n\n### 7. Workspace Symbol Search (Where is this symbol?)\n- **Scenario**: You need to find a class or function across the entire project.\n- **Action**: Use \\`workspaceSymbol\\` with a query string and a scoped filePath (module or directory).\n- **Why**: It searches across all files in the scope. **Important**: Must provide a scoped path to avoid unbounded full-repo queries.\n\n## Supported Operations\n\n### Location-Based Operations (require line + character)\nThese 8 operations require precise symbol position:\n- \\`goToDefinition\\`: Find where a symbol is defined\n- \\`findReferences\\`: Find all references to a symbol\n- \\`hover\\`: Get hover information (documentation, type info) for a symbol\n- \\`goToImplementation\\`: Find implementations of an interface or abstract method\n- \\`prepareCallHierarchy\\`: Get call hierarchy item at a position (functions/methods)\n- \\`incomingCalls\\`: Find all functions/methods that call the function at a position\n- \\`outgoingCalls\\`: Find all functions/methods called by the function at a position\n- \\`getScope\\`: Get local variables and closure captures at a position\n\n### Document-Level Operations (no position required)\n- \\`documentSymbol\\`: Get all symbols (functions, classes, variables) in a document\n- \\`diagnostics\\`: Get validation errors and warnings for a file (supports waiting for fresh results)\n\n### Workspace-Level Operations\n- \\`workspaceSymbol\\`: Search for symbols across the entire workspace (requires query + scoped filePath)\n\n## Parameters\n\nAll operations require:\n- \\`filePath\\`: The file or directory to operate on\n\nLocation-based operations require:\n- \\`line\\`: The line number (1-based, as shown in editors)\n- \\`character\\`: The character offset (1-based, as shown in editors)\n\n\\`workspaceSymbol\\` requires:\n- \\`query\\`: The symbol name or keyword to search for\n\nOptional:\n- \\`waitForDiagnostics\\`: If true, wait for fresh diagnostics (used with \"diagnostics\" operation)\n- \\`timeout\\`: Timeout in milliseconds for waiting operations (default: 5000)\n\n## Intelligent Position Handling\n\n**Do not pass a symbol name.** LSPTool works on positions, not names. Use Read to locate the symbol and derive line + character first.\n\n### Auto-Adjustment Mechanism\nIf the specified position is not on a valid symbol, the tool automatically searches for the nearest valid token:\n- **Search scope**: Current line, then previous line, then next line\n- **Priority**: Current line tokens are preferred (lower score)\n- **Skipped tokens**: Keywords (function, class, if, for, return, etc.) and operators (=, =>, +, -, &&, ||, etc.) are automatically skipped\n- **If no valid token found**: Returns an error message\n\n### Best Practice for Position\n1. Use Read to open the file and locate the symbol\n2. Provide accurate 1-based line and character offset\n3. Position should be on the symbol name itself, not on keywords/operators\n4. If unsure, position at the start of the symbol name\n\n## Workflow & Scope Guidelines\n- **Priority order**: documentSymbol \u2192 hotspot detection \u2192 Read \u2192 LSP (ensure line + character)\n- **workspaceSymbol**: Must provide scoped filePath (module or directory), avoid unbounded full-repo queries\n- **documentSymbol**: Uses LspFacade policy (LSP-first for accuracy, Tree-Sitter fallback for speed)\n\n## Typical Usage Examples\n### Example 1: Find Symbol Then Read Precise Block\n<example>\nuser: Locate JWT validation implementation quickly\nassistant: [uses LSP workspaceSymbol with query=\"jwt validate\" and scoped filePath]\n[uses Read on the discovered file and then LSP documentSymbol/definition as needed]\n<reasoning>\nThe assistant starts semantically because:\n1. User asks for implementation location, not broad text grep\n2. workspaceSymbol narrows candidate files efficiently\n3. Read is then used for exact code extraction once target is known\n</reasoning>\n</example>\n\n### Example 2: Diagnostics-First Debugging\n<example>\nuser: Build failed in api package, tell me real code errors\nassistant: [uses LSP diagnostics with waitForDiagnostics=true on scoped filePath]\n[uses goToDefinition/findReferences for follow-up impact tracing]\n<reasoning>\nThe assistant prioritizes diagnostics because:\n1. Diagnostics provide direct semantic errors from language tooling\n2. Scoped path avoids unbounded workspace queries\n3. Follow-up LSP ops can trace root-cause dependencies\n</reasoning>\n</example>\n\nNote: LSP servers are automatically managed and installed for most languages. For system-level languages (like C++, Java), ensure the corresponding tools (clangd, jdtls) are in your PATH.`\n\nexport const DESCRIPTION = PROMPT\n", "export const TOOL_NAME = 'Task'\n", "import {\n loadMergedSettings,\n normalizeSandboxRuntimeConfigFromSettings,\n} from '@utils/sandbox/sandboxConfig'\nimport { TOOL_NAME as TOOL_NAME_READ } from '../../filesystem/FileReadTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_EDIT } from '../../filesystem/FileEditTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_WRITE } from '../../filesystem/FileWriteTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_GLOB } from '../../filesystem/GlobTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_GREP } from '../../search/GrepTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_LSP } from '../../search/LspTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_TASK } from '../../agent/TaskTool/constants'\n\nexport const DEFAULT_TIMEOUT_MS = 120000\nexport const MAX_TIMEOUT_MS = 600000\nexport const MAX_OUTPUT_LENGTH = 30000\nexport const MAX_RENDERED_LINES = 5\n\nconst PROJECT_URL = 'https://github.com/pyb-xc/pyb-ts'\nconst DEFAULT_CO_AUTHOR = 'PYB-XC'\n\nexport const TOOL_NAME = 'Bash'\n\nfunction isExperimentalMcpCliEnabled(): boolean {\n const value = process.env.ENABLE_EXPERIMENTAL_MCP_CLI\n if (!value) return false\n return ['1', 'true', 'yes', 'on'].includes(String(value).trim().toLowerCase())\n}\n\nfunction indentJsonForPrompt(value: unknown): string {\n return JSON.stringify(value, null, 2).split('\\n').join('\\n ')\n}\n\nfunction getAttribution(): { commit: string; pr: string } {\n const pr = `\uD83E\uDD16 Generated with [Pyb Agent](${PROJECT_URL})`\n const commit = `${pr}\\n\\n Co-Authored-By: ${DEFAULT_CO_AUTHOR} <pyb-xc@foxmail.com>`\n return { commit, pr }\n}\n\nfunction getBashSandboxPrompt(): string {\n const settings = loadMergedSettings()\n if (settings.sandbox?.enabled !== true) return ''\n\n const runtimeConfig = normalizeSandboxRuntimeConfigFromSettings(settings)\n\n const fsReadConfig = { denyOnly: runtimeConfig.filesystem.denyRead }\n const fsWriteConfig = {\n allowOnly: runtimeConfig.filesystem.allowWrite,\n denyWithinAllow: runtimeConfig.filesystem.denyWrite,\n }\n\n const filesystem = { read: fsReadConfig, write: fsWriteConfig }\n\n const allowUnixSockets =\n runtimeConfig.network.allowAllUnixSockets === true\n ? true\n : runtimeConfig.network.allowUnixSockets.length > 0\n ? runtimeConfig.network.allowUnixSockets\n : undefined\n\n const network = {\n ...(runtimeConfig.network.allowedDomains.length\n ? { allowedHosts: runtimeConfig.network.allowedDomains }\n : {}),\n ...(runtimeConfig.network.deniedDomains.length\n ? { deniedHosts: runtimeConfig.network.deniedDomains }\n : {}),\n ...(allowUnixSockets ? { allowUnixSockets } : {}),\n }\n\n const ignoredViolations = runtimeConfig.ignoreViolations\n const allowUnsandboxedCommands =\n settings.sandbox?.allowUnsandboxedCommands !== false\n\n const sections: string[] = []\n sections.push(` - Filesystem: ${indentJsonForPrompt(filesystem)}`)\n if (Object.keys(network).length > 0) {\n sections.push(` - Network: ${indentJsonForPrompt(network)}`)\n }\n if (ignoredViolations) {\n sections.push(\n ` - Ignored violations: ${indentJsonForPrompt(ignoredViolations)}`,\n )\n }\n\n const mcpCliException = isExperimentalMcpCliEnabled()\n ? ' - EXCEPTION: `mcp-cli` commands must always be called with `dangerouslyDisableSandbox: true` as they do not work properly in sandboxed mode\\n'\n : ''\n\n const overridePolicy = allowUnsandboxedCommands\n ? ` - CRITICAL: Commands run in sandbox mode by default - do NOT set \\`dangerouslyDisableSandbox\\`\n - Even if you have recently run commands with \\`dangerouslyDisableSandbox: true\\`, you MUST NOT continue that pattern\n - VERY IMPORTANT: Do NOT learn from or repeat the pattern of overriding sandbox - each command should run sandboxed by default\n${mcpCliException} - Set \\`dangerouslyDisableSandbox: true\\` if:\n 1. The user *explicitly* asks to bypass sandbox, OR\n 2. A command just failed and you see evidence of sandbox restrictions causing the failure\n - When analyzing failures:\n - Commands can fail for many reasons unrelated to the sandbox (missing files, wrong arguments, network issues, etc.)\n - Evidence of sandbox-caused failures includes:\n - \"Operation not permitted\" errors for file/network operations\n - Access denied to specific paths outside allowed directories\n - Network connection failures to non-whitelisted hosts\n - Unix socket connection errors\n - Sandbox violation logs can be noisy, but clear permission errors are strong indicators\n - When you see evidence of sandbox-caused failure:\n - IMMEDIATELY retry with \\`dangerouslyDisableSandbox: true\\` (don't ask, just do it)\n - Briefly explain what sandbox restriction likely caused the failure\n - Mention: \"Use \\`/sandbox\\` to manage restrictions\"\n - This will prompt the user for permission\n - Example of normal usage: { \"command\": \"ls\", \"description\": \"List files\" }\n - Example of override: { \"command\": \"my-tool\", \"description\": \"Run my-tool\", \"dangerouslyDisableSandbox\": true }\n - DO NOT suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the allowlist`\n : ` - CRITICAL: All commands MUST run in sandbox mode - the \\`dangerouslyDisableSandbox\\` parameter is disabled by policy\n - Commands cannot run outside the sandbox under any circumstances\n - If a command fails due to sandbox restrictions, work with the user to adjust sandbox settings instead`\n\n return `- Commands run in a sandbox by default with the following restrictions:\n${sections.join('\\n')}\n${overridePolicy}\n - IMPORTANT: For temporary files, rely on the sandbox temp directory via \\`TMPDIR\\`\n - In sandbox mode, \\`TMPDIR\\` is set to a dedicated temp directory\n - Prefer using \\`TMPDIR\\` over writing directly to \\`/tmp\\`\n - Most programs that respect \\`TMPDIR\\` will automatically use it`\n}\n\nfunction getBashGitPrompt(): string {\n const { commit, pr } = getAttribution()\n return `# Committing changes with git\n\nOnly create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:\n\nGit Safety Protocol:\n- NEVER update the git config\n- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them \n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it\n- NEVER run force push to main/master, warn the user if they request it\n- Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook (additional instructions below) \n- Before amending: ALWAYS check authorship (git log -1 --format='%an %ae')\n- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel, each using the ${TOOL_NAME} tool:\n - Run a git status command to see all untracked files.\n - Run a git diff command to see both staged and unstaged changes that will be committed.\n - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.\n2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:\n - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.).\n - Do not commit files that likely contain secrets (.env, credentials.json, etc). Warn the user if they specifically request to commit those files\n - Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n - Ensure it accurately reflects the changes and their purpose\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands:\n - Add relevant untracked files to the staging area.\n - Create the commit with a message${commit ? ` ending with:\\n ${commit}` : '.'}\n - Run git status after the commit completes to verify success.\n Note: git status depends on the commit completing, so run it sequentially after the commit.\n4. If the commit fails due to pre-commit hook changes, retry ONCE. If it succeeds but files were modified by the hook, verify it's safe to amend:\n - Check HEAD commit: git log -1 --format='[%h] (%an <%ae>) %s'. VERIFY it matches your commit\n - Check not pushed: git status shows \"Your branch is ahead\"\n - If both true: amend your commit. Otherwise: create NEW commit (never amend other developers' commits)\n\nImportant notes:\n- NEVER run additional commands to read or explore code, besides git bash commands\n- NEVER use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- DO NOT push to the remote repository unless the user explicitly asks you to do so\n- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.\n- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit\n- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:\n<example>\ngit commit -m \"$(cat <<'EOF'\n Commit message here.${commit ? `\\n\\n ${commit}` : ''}\n EOF\n )\"\n</example>\n\n# Creating pull requests\nUse the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.\n\nIMPORTANT: When the user asks you to create a pull request, follow these steps carefully:\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel using the ${TOOL_NAME} tool, in order to understand the current state of the branch since it diverged from the main branch:\n - Run a git status command to see all untracked files\n - Run a git diff command to see both staged and unstaged changes that will be committed\n - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote\n - Run a git log command and \\`git diff [base-branch]...HEAD\\` to understand the full commit history for the current branch (from the time it diverged from the base branch)\n2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel:\n - Create new branch if needed\n - Push to remote with -u flag if needed\n - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.\n<example>\ngh pr create --title \"the pr title\" --body \"$(cat <<'EOF'\n## Summary\n<1-3 bullet points>\n\n## Test plan\n[Bulleted markdown checklist of TODOs for testing the pull request...]${pr ? `\\n\\n${pr}` : ''}\nEOF\n)\"\n</example>\n\nImportant:\n- DO NOT use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- Return the PR URL when you're done, so the user can see it\n\n# Other common operations\n- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments`\n}\n\nexport function getBashToolPrompt(): string {\n const sandboxPrompt = getBashSandboxPrompt()\n return `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nIMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use the ${TOOL_NAME_GLOB} tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first check if \"foo\" exists\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - cd \"/Users/name/My Documents\" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to ${MAX_TIMEOUT_MS}ms / ${MAX_TIMEOUT_MS / 60000} minutes). If not specified, commands will timeout after ${DEFAULT_TIMEOUT_MS}ms (${DEFAULT_TIMEOUT_MS / 60000} minutes).\n - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.\n - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.\n - You can use the \\`run_in_background\\` parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the ${TOOL_NAME} tool as it becomes available. You do not need to use '&' at the end of the command when using this parameter.\n ${sandboxPrompt}\n - Avoid using Bash with the \\`find\\`, \\`grep\\`, \\`cat\\`, \\`head\\`, \\`tail\\`, \\`sed\\`, \\`awk\\`, \\`echo\\`, \\`ls\\`, \\`dir\\`, or \\`tree\\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:\n - File search: Use ${TOOL_NAME_GLOB} (NOT find or ls)\n - Directory structure and information: use ${TOOL_NAME_READ} (NOT ls/dir/tree)\n - Content search: Use ${TOOL_NAME_GREP} (NOT grep or rg)\n - Symbol navigation: Use ${TOOL_NAME_LSP} (NOT ctags/gtags)\n - Read files: Use ${TOOL_NAME_READ} (NOT cat/head/tail)\n - Edit files: Use ${TOOL_NAME_EDIT} (NOT sed/awk)\n - Write files: Use ${TOOL_NAME_WRITE} (NOT echo >/cat <<EOF)\n - Delete files: Use Delete (NOT rm/rmdir/del). Example: Delete({ file_paths: [\"/path/to/file\"] })\n - Communication: Output text directly (NOT echo/printf)\n - When issuing multiple commands:\n - If the commands are independent and can run in parallel, make multiple ${TOOL_NAME} tool calls in a single message. For example, if you need to run \"git status\" and \"git diff\", send a single message with two ${TOOL_NAME} tool calls in parallel.\n - If the commands depend on each other and must run sequentially, use a single ${TOOL_NAME} call with '&&' to chain them together (e.g., \\`git add . && git commit -m \"message\" && git push\\`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead.\n - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail\n - DO NOT use newlines to separate commands (newlines are ok in quoted strings)\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \\`cd\\`. You may use \\`cd\\` if the User explicitly requests it.\n <good-example>\n pytest /foo/bar/tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n${getBashGitPrompt()}`\n}\n", "import { ensureConfigScope } from './discovery'\n\nexport type McpCliTransport = 'stdio' | 'sse' | 'http'\n\nexport function looksLikeMcpUrl(value: string): boolean {\n const trimmed = value.trim()\n if (!trimmed) return false\n\n if (/^(https?|wss?):\\/\\//i.test(trimmed)) return true\n if (/^localhost(?::\\d+)?(\\/|$)/i.test(trimmed)) return true\n if (/^\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?(\\/|$)/.test(trimmed)) return true\n return trimmed.endsWith('/sse') || trimmed.endsWith('/mcp')\n}\n\nexport function parseMcpHeaders(\n raw: string[] | undefined,\n): Record<string, string> | undefined {\n if (!raw || raw.length === 0) return undefined\n const headers: Record<string, string> = {}\n for (const item of raw) {\n const idx = item.indexOf(':')\n if (idx === -1) {\n throw new Error(\n `Invalid header format: \"${item}\". Expected format: \"Header-Name: value\"`,\n )\n }\n const key = item.slice(0, idx).trim()\n const value = item.slice(idx + 1).trim()\n if (!key) {\n throw new Error(`Invalid header: \"${item}\". Header name cannot be empty.`)\n }\n headers[key] = value\n }\n return headers\n}\n\nexport function normalizeMcpScopeForCli(scope: string | undefined): {\n scope: ReturnType<typeof ensureConfigScope>\n display: string\n} {\n const raw = (scope ?? 'local').trim() || 'local'\n\n if (raw === 'local')\n return { scope: ensureConfigScope('project'), display: 'local' }\n if (raw === 'user')\n return { scope: ensureConfigScope('global'), display: 'user' }\n if (raw === 'project')\n return { scope: ensureConfigScope('mcpjson'), display: 'project' }\n\n if (raw === 'global')\n return { scope: ensureConfigScope('global'), display: 'user' }\n if (raw === 'projectConfig' || raw === 'project-config') {\n return { scope: ensureConfigScope('project'), display: 'local' }\n }\n\n return { scope: ensureConfigScope(raw), display: raw }\n}\n\nexport function normalizeMcpTransport(transport: string | undefined): {\n transport: McpCliTransport\n explicit: boolean\n} {\n if (!transport) return { transport: 'stdio', explicit: false }\n const normalized = transport.trim()\n if (normalized === 'stdio' || normalized === 'sse' || normalized === 'http') {\n return { transport: normalized, explicit: true }\n }\n throw new Error(\n `Invalid transport type: ${transport}. Must be one of: stdio, sse, http`,\n )\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,eAAe;AAExB,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AACnC,SAAS,qCAAqC;AAC9C,SAAS,gCAAgC;AACzC,SAAS,SAAS,cAAc;;;ACdhC,SAAS,kBAAkB,OAAuB;AAChD,MAAI,MAAM;AACV,MAAI,WAAW;AACf,MAAI,UAAU;AACd,MAAI,gBAAgB;AACpB,MAAI,iBAAiB;AAErB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,KAAK,MAAM,CAAC;AAClB,UAAM,OAAO,IAAI,IAAI,MAAM,SAAS,MAAM,IAAI,CAAC,IA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cesContent": ["import type { McpServerConfig } from '@utils/config'\nimport {\n getCurrentProjectConfig,\n getGlobalConfig,\n getProjectMcpServerDefinitions,\n} from '@utils/config'\nimport { existsSync, readFileSync } from 'fs'\nimport { resolve } from 'path'\nimport { getCwd } from '@utils/state'\nimport { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'\nimport { WebSocketClientTransport } from '@modelcontextprotocol/sdk/client/websocket.js'\nimport { memoize, pickBy } from 'lodash-es'\nimport { logMCPError } from '@utils/log'\nimport { PRODUCT_COMMAND } from '@constants/product'\nimport { parseJsonOrJsonc } from './internal/jsonc'\nimport { getMcprcServerStatus, listPluginMCPServers } from './discovery'\n\nfunction getMcpServerConnectionBatchSize(): number {\n const raw = process.env.MCP_SERVER_CONNECTION_BATCH_SIZE\n const parsed = raw ? Number.parseInt(raw, 10) : NaN\n if (Number.isFinite(parsed) && parsed > 0 && parsed <= 50) return parsed\n return 3\n}\n\nasync function connectToServer(\n name: string,\n serverRef: McpServerConfig,\n): Promise<Client> {\n type Candidate = { transport: unknown; kind: 'stdio' | 'sse' | 'http' | 'ws' }\n\n const ensureWebSocketGlobal = async () => {\n if (typeof (globalThis as any).WebSocket === 'function') return\n try {\n const undici = await import('undici')\n if (typeof (undici as any).WebSocket === 'function') {\n ;(globalThis as any).WebSocket = (undici as any).WebSocket\n }\n } catch {}\n }\n\n const candidates: Candidate[] = await (async () => {\n switch (serverRef.type) {\n case 'sse': {\n const ref = serverRef\n return [\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n {\n kind: 'http',\n transport: new StreamableHTTPClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'sse-ide': {\n const ref = serverRef\n return [\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'http': {\n const ref = serverRef\n return [\n {\n kind: 'http',\n transport: new StreamableHTTPClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n {\n kind: 'sse',\n transport: new SSEClientTransport(new URL(ref.url), {\n ...(ref.headers ? { requestInit: { headers: ref.headers } } : {}),\n }),\n },\n ]\n }\n case 'ws': {\n const ref = serverRef\n await ensureWebSocketGlobal()\n return [\n {\n kind: 'ws',\n transport: new WebSocketClientTransport(new URL(ref.url)),\n },\n ]\n }\n case 'ws-ide': {\n const ref = serverRef\n\n let url = ref.url\n if (ref.authToken) {\n try {\n const parsed = new URL(url)\n if (!parsed.searchParams.has('authToken')) {\n parsed.searchParams.set('authToken', ref.authToken)\n url = parsed.toString()\n }\n } catch {}\n }\n\n await ensureWebSocketGlobal()\n return [\n {\n kind: 'ws',\n transport: new WebSocketClientTransport(new URL(url)),\n },\n ]\n }\n case 'stdio':\n default: {\n const ref = serverRef\n return [\n {\n kind: 'stdio',\n transport: new StdioClientTransport({\n command: ref.command,\n args: ref.args,\n env: {\n ...process.env,\n ...ref.env,\n } as Record<string, string>,\n stderr: 'pipe',\n }),\n },\n ]\n }\n }\n })()\n\n const rawTimeout = process.env.MCP_CONNECTION_TIMEOUT_MS\n const parsedTimeout = rawTimeout ? Number.parseInt(rawTimeout, 10) : NaN\n const CONNECTION_TIMEOUT_MS = Number.isFinite(parsedTimeout)\n ? parsedTimeout\n : 30_000\n\n let lastError: unknown\n\n for (const candidate of candidates) {\n const client = new Client(\n {\n name: PRODUCT_COMMAND,\n version: '0.1.0',\n },\n {\n capabilities: {},\n },\n )\n\n try {\n const connectPromise = client.connect(candidate.transport as any)\n if (CONNECTION_TIMEOUT_MS > 0) {\n const timeoutPromise = new Promise<never>((_, reject) => {\n const timeoutId = setTimeout(() => {\n reject(\n new Error(\n `Connection to MCP server \"${name}\" timed out after ${CONNECTION_TIMEOUT_MS}ms`,\n ),\n )\n }, CONNECTION_TIMEOUT_MS)\n\n connectPromise.then(\n () => clearTimeout(timeoutId),\n () => clearTimeout(timeoutId),\n )\n })\n\n await Promise.race([connectPromise, timeoutPromise])\n } else {\n await connectPromise\n }\n\n if (candidate.kind === 'stdio') {\n ;(candidate.transport as StdioClientTransport).stderr?.on(\n 'data',\n (data: Buffer) => {\n const errorText = data.toString().trim()\n if (errorText) {\n logMCPError(name, `Server stderr: ${errorText}`)\n }\n },\n )\n }\n\n if (candidates.length > 1 && candidate !== candidates[0]) {\n logMCPError(\n name,\n `Connected using fallback transport \"${candidate.kind}\". Consider setting the server type explicitly in your MCP config.`,\n )\n }\n\n return client\n } catch (error) {\n lastError = error\n try {\n await client.close()\n } catch {}\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(`Failed to connect to MCP server \"${name}\"`)\n}\n\ntype ConnectedClient = {\n client: Client\n capabilities?: Record<string, unknown> | null\n name: string\n type: 'connected'\n}\ntype FailedClient = {\n name: string\n type: 'failed'\n}\nexport type WrappedClient = ConnectedClient | FailedClient\n\nexport const getClients = memoize(async (): Promise<WrappedClient[]> => {\n if (process.env.CI && process.env.NODE_ENV !== 'test') {\n return []\n }\n\n const pluginServers = listPluginMCPServers()\n const globalServers = getGlobalConfig().mcpServers ?? {}\n const projectFileServers = getProjectMcpServerDefinitions().servers\n const projectServers = getCurrentProjectConfig().mcpServers ?? {}\n\n const approvedProjectFileServers = pickBy(\n projectFileServers,\n (_, name) => getMcprcServerStatus(name) === 'approved',\n )\n\n const allServers = {\n ...pluginServers,\n ...globalServers,\n ...approvedProjectFileServers,\n ...projectServers,\n }\n\n const batchSize = getMcpServerConnectionBatchSize()\n const entries = Object.entries(allServers)\n const results: WrappedClient[] = []\n\n for (let i = 0; i < entries.length; i += batchSize) {\n const batch = entries.slice(i, i + batchSize)\n const batchResults = await Promise.all(\n batch.map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n let capabilities: Record<string, unknown> | null = null\n try {\n capabilities = client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n return { name, client, capabilities, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n results.push(...batchResults)\n }\n\n return results\n})\n\nfunction parseMcpServersFromCliConfigEntries(options: {\n entries: string[]\n projectDir: string\n}): Record<string, McpServerConfig> {\n const out: Record<string, McpServerConfig> = {}\n\n for (const rawEntry of options.entries) {\n const entry = String(rawEntry ?? '').trim()\n if (!entry) continue\n\n const resolvedPath = resolve(options.projectDir, entry)\n const payload = existsSync(resolvedPath)\n ? readFileSync(resolvedPath, 'utf8')\n : existsSync(entry)\n ? readFileSync(entry, 'utf8')\n : entry\n\n const parsed = parseJsonOrJsonc(payload)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue\n\n const rawServers =\n (parsed as any).mcpServers &&\n typeof (parsed as any).mcpServers === 'object' &&\n !Array.isArray((parsed as any).mcpServers)\n ? (parsed as any).mcpServers\n : parsed\n\n if (!rawServers || typeof rawServers !== 'object' || Array.isArray(rawServers))\n continue\n\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n out[name] = cfg as McpServerConfig\n }\n }\n\n return out\n}\n\nexport async function getClientsForCliMcpConfig(options: {\n mcpConfig?: string[]\n strictMcpConfig?: boolean\n projectDir?: string\n}): Promise<WrappedClient[]> {\n const projectDir = options.projectDir ?? getCwd()\n const entries =\n Array.isArray(options.mcpConfig) && options.mcpConfig.length > 0\n ? options.mcpConfig\n : []\n const strict = options.strictMcpConfig === true\n\n if (entries.length === 0 && !strict) {\n return getClients()\n }\n\n const cliServers = parseMcpServersFromCliConfigEntries({\n entries,\n projectDir,\n })\n\n const pluginServers = strict ? {} : listPluginMCPServers()\n const globalServers = strict ? {} : (getGlobalConfig().mcpServers ?? {})\n const projectFileServers = strict ? {} : getProjectMcpServerDefinitions().servers\n const projectServers = strict ? {} : (getCurrentProjectConfig().mcpServers ?? {})\n\n const approvedProjectFileServers = strict\n ? {}\n : pickBy(projectFileServers, (_, name) => getMcprcServerStatus(name) === 'approved')\n\n const allServers = {\n ...(pluginServers ?? {}),\n ...(globalServers ?? {}),\n ...(approvedProjectFileServers ?? {}),\n ...(projectServers ?? {}),\n ...(cliServers ?? {}),\n }\n\n const batchSize = getMcpServerConnectionBatchSize()\n const entriesToConnect = Object.entries(allServers)\n const results: WrappedClient[] = []\n\n for (let i = 0; i < entriesToConnect.length; i += batchSize) {\n const batch = entriesToConnect.slice(i, i + batchSize)\n const batchResults = await Promise.all(\n batch.map(async ([name, serverRef]) => {\n try {\n const client = await connectToServer(name, serverRef as McpServerConfig)\n let capabilities: Record<string, unknown> | null = null\n try {\n capabilities = client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n return { name, client, capabilities, type: 'connected' as const }\n } catch (error) {\n logMCPError(\n name,\n `Connection failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n return { name, type: 'failed' as const }\n }\n }),\n )\n results.push(...batchResults)\n }\n\n return results\n}\n", "function stripJsonComments(input: string): string {\n let out = ''\n let inString = false\n let escaped = false\n let inLineComment = false\n let inBlockComment = false\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i]!\n const next = i + 1 < input.length ? input[i + 1]! : ''\n\n if (inLineComment) {\n if (ch === '\\n') {\n inLineComment = false\n out += ch\n }\n continue\n }\n\n if (inBlockComment) {\n if (ch === '*' && next === '/') {\n inBlockComment = false\n i++\n }\n continue\n }\n\n if (inString) {\n out += ch\n if (escaped) {\n escaped = false\n continue\n }\n if (ch === '\\\\') {\n escaped = true\n continue\n }\n if (ch === '\"') inString = false\n continue\n }\n\n if (ch === '\"') {\n inString = true\n out += ch\n continue\n }\n\n if (ch === '/' && next === '/') {\n inLineComment = true\n i++\n continue\n }\n\n if (ch === '/' && next === '*') {\n inBlockComment = true\n i++\n continue\n }\n\n out += ch\n }\n\n return out\n}\n\nexport function parseJsonOrJsonc(text: string): unknown {\n const raw = String(text ?? '')\n if (!raw.trim()) return null\n try {\n return JSON.parse(raw)\n } catch {\n try {\n return JSON.parse(stripJsonComments(raw))\n } catch {\n return null\n }\n }\n}\n\n", "import {\n getCurrentProjectConfig,\n getGlobalConfig,\n getProjectMcpServerDefinitions,\n saveCurrentProjectConfig,\n saveGlobalConfig,\n addMcprcServerForTesting,\n removeMcprcServerForTesting,\n type McpServerConfig,\n} from '@utils/config'\nimport { existsSync, readFileSync, writeFileSync } from 'fs'\nimport { join } from 'path'\nimport { getCwd } from '@utils/state'\nimport { safeParseJSON } from '@utils/text/json'\nimport { getSessionPlugins } from '@utils/session/sessionPlugins'\nimport { parseJsonOrJsonc } from './internal/jsonc'\n\ntype McpName = string\n\nfunction expandTemplateString(value: string, pluginRoot: string): string {\n return value.replace(/\\$\\{([^}]+)\\}/g, (match, key) => {\n const k = String(key ?? '').trim()\n if (!k) return match\n if (k === 'PYB_PLUGIN_ROOT') return pluginRoot\n const env = process.env[k]\n return env !== undefined ? env : match\n })\n}\n\nfunction expandTemplateDeep(value: unknown, pluginRoot: string): unknown {\n if (typeof value === 'string') return expandTemplateString(value, pluginRoot)\n if (Array.isArray(value))\n return value.map(v => expandTemplateDeep(v, pluginRoot))\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n out[k] = expandTemplateDeep(v, pluginRoot)\n }\n return out\n }\n return value\n}\n\nexport function listPluginMCPServers(): Record<string, McpServerConfig> {\n const plugins = getSessionPlugins()\n if (plugins.length === 0) return {}\n\n const out: Record<string, McpServerConfig> = {}\n\n for (const plugin of plugins) {\n const pluginRoot = plugin.rootDir\n const pluginName = plugin.name\n\n const configs: Array<Record<string, McpServerConfig>> = []\n\n for (const configPath of plugin.mcpConfigFiles ?? []) {\n try {\n const raw = readFileSync(configPath, 'utf8')\n const parsed = parseJsonOrJsonc(raw)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))\n continue\n const rawServers =\n (parsed as any).mcpServers &&\n typeof (parsed as any).mcpServers === 'object' &&\n !Array.isArray((parsed as any).mcpServers)\n ? (parsed as any).mcpServers\n : parsed\n\n if (\n !rawServers ||\n typeof rawServers !== 'object' ||\n Array.isArray(rawServers)\n )\n continue\n\n const servers: Record<string, McpServerConfig> = {}\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n servers[name] = expandTemplateDeep(cfg, pluginRoot) as McpServerConfig\n }\n configs.push(servers)\n } catch {\n continue\n }\n }\n\n const manifestRaw = (plugin.manifest as any)?.mcpServers\n if (\n manifestRaw &&\n typeof manifestRaw === 'object' &&\n !Array.isArray(manifestRaw)\n ) {\n const rawServers =\n (manifestRaw as any).mcpServers &&\n typeof (manifestRaw as any).mcpServers === 'object' &&\n !Array.isArray((manifestRaw as any).mcpServers)\n ? (manifestRaw as any).mcpServers\n : manifestRaw\n\n if (\n rawServers &&\n typeof rawServers === 'object' &&\n !Array.isArray(rawServers)\n ) {\n const servers: Record<string, McpServerConfig> = {}\n for (const [name, cfg] of Object.entries(rawServers as any)) {\n if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue\n servers[name] = expandTemplateDeep(cfg, pluginRoot) as McpServerConfig\n }\n configs.push(servers)\n }\n }\n\n const merged: Record<string, McpServerConfig> = Object.assign({}, ...configs)\n\n for (const [serverName, cfg] of Object.entries(merged)) {\n const fullName = `plugin_${pluginName}_${serverName}`\n out[fullName] = cfg\n }\n }\n\n return out\n}\n\nexport function parseEnvVars(\n rawEnvArgs: string[] | undefined,\n): Record<string, string> {\n const parsedEnv: Record<string, string> = {}\n\n if (rawEnvArgs) {\n for (const envStr of rawEnvArgs) {\n const [key, ...valueParts] = envStr.split('=')\n if (!key || valueParts.length === 0) {\n throw new Error(\n `Invalid environment variable format: ${envStr}, environment variables should be added as: -e KEY1=value1 -e KEY2=value2`,\n )\n }\n parsedEnv[key] = valueParts.join('=')\n }\n }\n return parsedEnv\n}\n\nconst VALID_SCOPES = ['project', 'global', 'mcprc', 'mcpjson'] as const\ntype ConfigScope = (typeof VALID_SCOPES)[number]\nconst EXTERNAL_SCOPES = [\n 'project',\n 'global',\n 'mcprc',\n 'mcpjson',\n] as ConfigScope[]\n\nexport function ensureConfigScope(scope?: string): ConfigScope {\n if (!scope) return 'project'\n\n const scopesToCheck =\n process.env.USER_TYPE === 'external' ? EXTERNAL_SCOPES : VALID_SCOPES\n\n if (!scopesToCheck.includes(scope as ConfigScope)) {\n throw new Error(\n `Invalid scope: ${scope}. Must be one of: ${scopesToCheck.join(', ')}`,\n )\n }\n\n return scope as ConfigScope\n}\n\nexport function addMcpServer(\n name: McpName,\n server: McpServerConfig,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n addMcprcServerForTesting(name, server)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n let mcprcConfig: Record<string, McpServerConfig> = {}\n\n if (existsSync(mcprcPath)) {\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const existingConfig = safeParseJSON(mcprcContent)\n if (existingConfig && typeof existingConfig === 'object') {\n mcprcConfig = existingConfig as Record<string, McpServerConfig>\n }\n } catch {\n }\n }\n\n mcprcConfig[name] = server\n\n try {\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcprc: ${error}`)\n }\n }\n } else if (scope === 'mcpjson') {\n const mcpJsonPath = join(getCwd(), '.mcp.json')\n let config: Record<string, unknown> = { mcpServers: {} }\n\n if (existsSync(mcpJsonPath)) {\n try {\n const content = readFileSync(mcpJsonPath, 'utf-8')\n const parsed = safeParseJSON(content)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n config = parsed as Record<string, unknown>\n }\n } catch {\n }\n }\n\n const rawServers = (config as { mcpServers?: unknown }).mcpServers\n const servers =\n rawServers && typeof rawServers === 'object' && !Array.isArray(rawServers)\n ? (rawServers as Record<string, McpServerConfig>)\n : ({} as Record<string, McpServerConfig>)\n\n servers[name] = server\n config.mcpServers = servers\n\n try {\n writeFileSync(mcpJsonPath, JSON.stringify(config, null, 2), 'utf-8')\n } catch (error) {\n throw new Error(`Failed to write to .mcp.json: ${error}`)\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers) {\n config.mcpServers = {}\n }\n config.mcpServers[name] = server\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function removeMcpServer(\n name: McpName,\n scope: ConfigScope = 'project',\n): void {\n if (scope === 'mcprc') {\n if (process.env.NODE_ENV === 'test') {\n removeMcprcServerForTesting(name)\n } else {\n const mcprcPath = join(getCwd(), '.mcprc')\n if (!existsSync(mcprcPath)) {\n throw new Error('No .mcprc file found in this directory')\n }\n\n try {\n const mcprcContent = readFileSync(mcprcPath, 'utf-8')\n const mcprcConfig = safeParseJSON(mcprcContent) as Record<\n string,\n McpServerConfig\n > | null\n\n if (\n !mcprcConfig ||\n typeof mcprcConfig !== 'object' ||\n !mcprcConfig[name]\n ) {\n throw new Error(`No MCP server found with name: ${name} in .mcprc`)\n }\n\n delete mcprcConfig[name]\n writeFileSync(mcprcPath, JSON.stringify(mcprcConfig, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) {\n throw error\n }\n throw new Error(`Failed to remove from .mcprc: ${error}`)\n }\n }\n } else if (scope === 'mcpjson') {\n const mcpJsonPath = join(getCwd(), '.mcp.json')\n if (!existsSync(mcpJsonPath)) {\n throw new Error('No .mcp.json file found in this directory')\n }\n\n try {\n const content = readFileSync(mcpJsonPath, 'utf-8')\n const parsed = safeParseJSON(content) as Record<string, unknown> | null\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Invalid .mcp.json format')\n }\n\n const rawServers = (parsed as { mcpServers?: unknown }).mcpServers\n if (\n !rawServers ||\n typeof rawServers !== 'object' ||\n Array.isArray(rawServers)\n ) {\n throw new Error('Invalid .mcp.json format (missing mcpServers)')\n }\n\n const servers = rawServers as Record<string, McpServerConfig>\n if (!servers[name]) {\n throw new Error(`No MCP server found with name: ${name} in .mcp.json`)\n }\n\n delete servers[name]\n ;(parsed as any).mcpServers = servers\n writeFileSync(mcpJsonPath, JSON.stringify(parsed, null, 2), 'utf-8')\n } catch (error) {\n if (error instanceof Error) throw error\n throw new Error(`Failed to remove from .mcp.json: ${error}`)\n }\n } else if (scope === 'global') {\n const config = getGlobalConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No global MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveGlobalConfig(config)\n } else {\n const config = getCurrentProjectConfig()\n if (!config.mcpServers?.[name]) {\n throw new Error(`No local MCP server found with name: ${name}`)\n }\n delete config.mcpServers[name]\n saveCurrentProjectConfig(config)\n }\n}\n\nexport function listMCPServers(): Record<string, McpServerConfig> {\n const pluginServers = listPluginMCPServers()\n const globalConfig = getGlobalConfig()\n const projectFileConfig = getProjectMcpServerDefinitions().servers\n const projectConfig = getCurrentProjectConfig()\n return {\n ...(pluginServers ?? {}),\n ...(globalConfig.mcpServers ?? {}),\n ...(projectFileConfig ?? {}),\n ...(projectConfig.mcpServers ?? {}),\n }\n}\n\nexport type ScopedMcpServerConfig = McpServerConfig & {\n scope: ConfigScope\n}\n\nexport function getMcpServer(name: McpName): ScopedMcpServerConfig | undefined {\n const projectConfig = getCurrentProjectConfig()\n const projectFileDefinitions = getProjectMcpServerDefinitions()\n const projectFileConfig = projectFileDefinitions.servers\n const globalConfig = getGlobalConfig()\n\n if (projectConfig.mcpServers?.[name]) {\n return { ...projectConfig.mcpServers[name], scope: 'project' }\n }\n\n if (projectFileConfig?.[name]) {\n const source = projectFileDefinitions.sources[name]\n const scope: ConfigScope = source === '.mcp.json' ? 'mcpjson' : 'mcprc'\n return { ...projectFileConfig[name], scope }\n }\n\n if (globalConfig.mcpServers?.[name]) {\n return { ...globalConfig.mcpServers[name], scope: 'global' }\n }\n\n return undefined\n}\n\nexport function getMcprcServerStatus(\n serverName: string,\n): 'approved' | 'rejected' | 'pending' {\n const config = getCurrentProjectConfig()\n if (config.approvedMcprcServers?.includes(serverName)) {\n return 'approved'\n }\n if (config.rejectedMcprcServers?.includes(serverName)) {\n return 'rejected'\n }\n return 'pending'\n}\n", "import { zipObject, memoize } from 'lodash-es'\nimport type { Tool } from '@tool'\nimport { MCPTool } from '@tools/mcp/MCPTool/MCPTool'\nimport { logMCPError } from '@utils/log'\nimport type { Command } from '@commands'\nimport type {\n ImageBlockParam,\n MessageParam,\n ToolResultBlockParam,\n} from '@anthropic-ai/sdk/resources/index.mjs'\nimport {\n CallToolResultSchema,\n type ClientRequest,\n type ListPromptsResult,\n ListPromptsResultSchema,\n type ListToolsResult,\n ListToolsResultSchema,\n type Result,\n ResultSchema,\n} from '@modelcontextprotocol/sdk/types.js'\nimport { getClients, type WrappedClient } from './client'\n\ntype ConnectedClient = Extract<WrappedClient, { type: 'connected' }>\n\nfunction sanitizeMcpIdentifierPart(value: string): string {\n return value.replace(/[^a-zA-Z0-9_-]/g, '_')\n}\n\nfunction getMcpToolTimeoutMs(): number | null {\n const raw = process.env.MCP_TOOL_TIMEOUT\n const parsed = raw ? Number.parseInt(raw, 10) : NaN\n if (!Number.isFinite(parsed) || parsed <= 0) return null\n return parsed\n}\n\ntype TimeoutSignal = { signal: AbortSignal; cleanup: () => void }\n\nfunction createTimeoutSignal(timeoutMs: number): TimeoutSignal {\n const timeoutFn = (AbortSignal as any)?.timeout\n if (typeof timeoutFn === 'function') {\n return { signal: timeoutFn(timeoutMs) as AbortSignal, cleanup: () => {} }\n }\n\n const controller = new AbortController()\n const id = setTimeout(() => controller.abort(), timeoutMs)\n return { signal: controller.signal, cleanup: () => clearTimeout(id) }\n}\n\nfunction mergeAbortSignals(\n signals: Array<AbortSignal | undefined>,\n): { signal: AbortSignal; cleanup: () => void } | null {\n const active = signals.filter((s): s is AbortSignal => !!s)\n if (active.length === 0) return null\n if (active.length === 1) return { signal: active[0]!, cleanup: () => {} }\n\n const controller = new AbortController()\n\n const abort = () => {\n try {\n controller.abort()\n } catch {}\n }\n\n for (const s of active) {\n if (s.aborted) {\n abort()\n return { signal: controller.signal, cleanup: () => {} }\n }\n s.addEventListener('abort', abort, { once: true })\n }\n\n return { signal: controller.signal, cleanup: () => {} }\n}\n\nconst IDE_MCP_TOOL_ALLOWLIST = new Set([\n 'mcp__ide__executeCode',\n 'mcp__ide__getDiagnostics',\n])\n\nasync function requestAll<\n ResultT extends Result,\n ResultSchemaT extends typeof ResultSchema,\n>(\n req: ClientRequest,\n resultSchema: ResultSchemaT,\n requiredCapability: string,\n): Promise<{ client: ConnectedClient; result: ResultT }[]> {\n const timeoutMs = getMcpToolTimeoutMs()\n const clients = await getClients()\n const results = await Promise.allSettled(\n clients.map(async client => {\n if (client.type === 'failed') return null\n\n let timeoutSignal: TimeoutSignal | null = null\n\n try {\n let capabilities: Record<string, unknown> | null = client.capabilities ?? null\n\n if (!capabilities) {\n try {\n capabilities = client.client.getServerCapabilities() as any\n } catch {\n capabilities = null\n }\n client.capabilities = capabilities\n }\n\n if (!(capabilities as any)?.[requiredCapability]) {\n return null\n }\n\n timeoutSignal = timeoutMs ? createTimeoutSignal(timeoutMs) : null\n const merged = mergeAbortSignals([timeoutSignal?.signal])\n\n return {\n client,\n result: (await client.client.request(\n req,\n resultSchema,\n merged?.signal ? ({ signal: merged.signal } as any) : undefined,\n )) as ResultT,\n }\n } catch (error) {\n if (client.type === 'connected') {\n logMCPError(\n client.name,\n `Failed to request '${req.method}': ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return null\n } finally {\n timeoutSignal?.cleanup()\n }\n }),\n )\n return results\n .filter(\n (\n result,\n ): result is PromiseFulfilledResult<{ client: ConnectedClient; result: ResultT } | null> =>\n result.status === 'fulfilled',\n )\n .map(result => result.value)\n .filter((result): result is { client: ConnectedClient; result: ResultT } => result !== null)\n}\n\nexport const getMCPTools = memoize(async (): Promise<Tool[]> => {\n const toolsList = await requestAll<ListToolsResult, typeof ListToolsResultSchema>(\n {\n method: 'tools/list',\n },\n ListToolsResultSchema,\n 'tools',\n )\n\n return toolsList.flatMap(({ client, result: { tools } }) => {\n const serverPart = sanitizeMcpIdentifierPart(client.name)\n\n return tools\n .map((tool): Tool | null => {\n const toolPart = sanitizeMcpIdentifierPart(tool.name)\n const name = `mcp__${serverPart}__${toolPart}`\n\n if (name.startsWith('mcp__ide__') && !IDE_MCP_TOOL_ALLOWLIST.has(name)) {\n return null\n }\n\n return {\n ...MCPTool,\n name,\n isConcurrencySafe() {\n return tool.annotations?.readOnlyHint ?? false\n },\n isReadOnly() {\n return tool.annotations?.readOnlyHint ?? false\n },\n async description() {\n return tool.description ?? ''\n },\n async prompt() {\n return tool.description ?? ''\n },\n inputJSONSchema: tool.inputSchema as Tool['inputJSONSchema'],\n async validateInput() {\n return { result: true }\n },\n async *call(args: Record<string, unknown>, context) {\n const data = await callMCPTool({\n client,\n tool: tool.name,\n args,\n toolUseId: context.toolUseId,\n signal: context.abortController.signal,\n })\n yield {\n type: 'result' as const,\n data,\n resultForAssistant: data,\n }\n },\n userFacingName() {\n const title = tool.annotations?.title || tool.name\n return `${client.name} - ${title} (MCP)`\n },\n }\n })\n .filter((tool): tool is Tool => tool !== null)\n })\n})\n\nasync function callMCPTool({\n client: { client, name },\n tool,\n args,\n toolUseId,\n signal,\n}: {\n client: ConnectedClient\n tool: string\n args: Record<string, unknown>\n toolUseId?: string\n signal?: AbortSignal\n}): Promise<ToolResultBlockParam['content']> {\n const timeoutMs = getMcpToolTimeoutMs()\n const timeoutSignal = timeoutMs ? createTimeoutSignal(timeoutMs) : null\n const merged = mergeAbortSignals([signal, timeoutSignal?.signal])\n\n const meta =\n toolUseId && toolUseId.trim()\n ? { 'claudecode/toolUseId': toolUseId }\n : undefined\n\n try {\n const result = await client.callTool(\n {\n name: tool,\n arguments: args,\n ...(meta ? { _meta: meta } : {}),\n },\n CallToolResultSchema,\n merged?.signal ? ({ signal: merged.signal } as any) : undefined,\n )\n\n if ('isError' in result && result.isError) {\n const contentText =\n 'content' in result && Array.isArray(result.content)\n ? result.content.find(item => item.type === 'text' && 'text' in item)\n : null\n\n const rawMessage =\n contentText && typeof (contentText as any).text === 'string'\n ? String((contentText as any).text)\n : 'error' in result && result.error\n ? String(result.error)\n : ''\n\n const message = rawMessage || `Error calling tool ${tool}`\n logMCPError(name, `Error calling tool ${tool}: ${message}`)\n throw new Error(message)\n }\n\n if ('toolResult' in result) {\n return String(result.toolResult)\n }\n\n if ('structuredContent' in result && result.structuredContent !== undefined) {\n return JSON.stringify(result.structuredContent)\n }\n\n if ('content' in result && Array.isArray(result.content)) {\n return result.content.map(item => {\n if (item.type === 'image') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: String(item.data),\n media_type: item.mimeType as ImageBlockParam.Source['media_type'],\n },\n }\n }\n return item\n })\n }\n\n throw Error(`Unexpected response format from tool ${tool}`)\n } finally {\n timeoutSignal?.cleanup()\n }\n}\n\nexport const getMCPCommands = memoize(async (): Promise<Command[]> => {\n const results = await requestAll<ListPromptsResult, typeof ListPromptsResultSchema>(\n {\n method: 'prompts/list',\n },\n ListPromptsResultSchema,\n 'prompts',\n )\n\n return results.flatMap(({ client, result }) =>\n result.prompts?.map(_ => {\n const serverPart = sanitizeMcpIdentifierPart(client.name)\n const argNames = Object.values(_.arguments ?? {}).map(k => k.name)\n return {\n type: 'prompt',\n name: `mcp__${serverPart}__${_.name}`,\n description: _.description ?? '',\n isEnabled: true,\n isHidden: false,\n progressMessage: 'running',\n userFacingName() {\n const title = typeof (_ as any).title === 'string' ? (_ as any).title : _.name\n return `${client.name}:${title} (MCP)`\n },\n argNames,\n async getPromptForCommand(args: string) {\n const argsArray = args.split(' ')\n return await runCommand({ name: _.name, client }, zipObject(argNames, argsArray))\n },\n } satisfies Command\n }),\n )\n})\n\nexport async function runCommand(\n { name, client }: { name: string; client: ConnectedClient },\n args: Record<string, string>,\n): Promise<MessageParam[]> {\n try {\n const result = await client.client.getPrompt({ name, arguments: args })\n return result.messages.map((message): MessageParam => {\n const content = message.content\n if (content.type === 'text') {\n return {\n role: message.role,\n content: [\n {\n type: 'text',\n text: content.text,\n },\n ],\n }\n }\n if (content.type === 'image' && 'data' in content) {\n return {\n role: message.role,\n content: [\n {\n type: 'image',\n source: {\n data: String((content as any).data),\n media_type: (content as any).mimeType as ImageBlockParam.Source['media_type'],\n type: 'base64',\n },\n },\n ],\n }\n }\n return {\n role: message.role,\n content: [\n {\n type: 'text',\n text: `Unsupported MCP content type ${(content as any)?.type ?? 'unknown'}`,\n },\n ],\n }\n })\n } catch (error) {\n logMCPError(\n client.name,\n `Error running command '${name}': ${error instanceof Error ? error.message : String(error)}`,\n )\n throw error\n }\n}\n\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { type Tool } from '@tool'\nimport { getTheme } from '@utils/theme'\nimport { DESCRIPTION, PROMPT, TOOL_NAME } from './prompt'\nimport { OutputLine } from '@tools/BashTool/OutputLine'\n\nconst inputSchema = z.object({}).passthrough()\n\nexport const MCPTool = {\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false\n },\n name: TOOL_NAME,\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n async *call() {\n yield {\n type: 'result',\n data: '',\n resultForAssistant: '',\n }\n },\n needsPermissions() {\n return true\n },\n renderToolUseMessage(input) {\n return Object.entries(input)\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(', ')\n },\n userFacingName: () => 'mcp',\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n renderToolResultMessage(output) {\n const verbose = false\n if (Array.isArray(output)) {\n return (\n <Box flexDirection=\"column\">\n {output.map((item, i) => {\n if (item.type === 'image') {\n return (\n <Box\n key={i}\n justifyContent=\"space-between\"\n overflowX=\"hidden\"\n width=\"100%\"\n >\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text>[Image]</Text>\n </Box>\n </Box>\n )\n }\n const lines = item.text.split('\\n').length\n return (\n <OutputLine\n key={i}\n content={item.text}\n lines={lines}\n verbose={verbose}\n />\n )\n })}\n </Box>\n )\n }\n\n if (!output) {\n return (\n <Box justifyContent=\"space-between\" overflowX=\"hidden\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text color={getTheme().secondaryText}>(No content)</Text>\n </Box>\n </Box>\n )\n }\n\n const lines = output.split('\\n').length\n return <OutputLine content={output} lines={lines} verbose={verbose} />\n },\n renderResultForAssistant(content) {\n return content\n },\n} satisfies Tool<typeof inputSchema, string>\n", "import * as React from 'react'\nimport { getTheme } from '@utils/theme'\nimport { Text } from 'ink'\nimport { PRODUCT_NAME } from '@constants/product'\n\nexport function FallbackToolUseRejectedMessage(): React.ReactNode {\n return (\n <Text>\n &nbsp;&nbsp;\u23BF &nbsp;\n <Text color={getTheme().error}>\n No (tell {PRODUCT_NAME} what to do differently)\n </Text>\n </Text>\n )\n}\n", "export const TOOL_NAME = 'mcp'\nexport const PROMPT = ''\nexport const DESCRIPTION = ''\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { getTheme } from '@utils/theme'\nimport { MAX_RENDERED_LINES } from './prompt'\nimport chalk from 'chalk'\n\nfunction renderTruncatedContent(content: string, totalLines: number): string {\n const allLines = content.split('\\n')\n if (allLines.length <= MAX_RENDERED_LINES) {\n return allLines.join('\\n')\n }\n\n const lastLines = allLines.slice(-MAX_RENDERED_LINES)\n return [\n chalk.grey(\n `Showing last ${MAX_RENDERED_LINES} lines of ${totalLines} total lines`,\n ),\n ...lastLines,\n ].join('\\n')\n}\n\nexport function OutputLine({\n content,\n lines,\n verbose,\n isError,\n}: {\n content: string\n lines: number\n verbose: boolean\n isError?: boolean\n key?: React.Key\n}) {\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Box flexDirection=\"column\">\n <Text color={isError ? getTheme().error : undefined}>\n {verbose\n ? content.trim()\n : renderTruncatedContent(content.trim(), lines)}\n </Text>\n </Box>\n </Box>\n </Box>\n )\n}\n", "import { watchFile, unwatchFile } from 'fs'\nimport { homedir } from 'os'\nimport {\n getSettingsFileCandidates,\n loadSettingsWithLegacyFallback,\n} from '@utils/config/settingsFiles'\n\nexport type SandboxNetworkConfig = {\n allowedDomains: string[]\n deniedDomains: string[]\n allowUnixSockets: string[]\n allowAllUnixSockets?: boolean\n allowLocalBinding?: boolean\n httpProxyPort?: number\n socksProxyPort?: number\n}\n\nexport type SandboxFilesystemConfig = {\n denyRead: string[]\n allowWrite: string[]\n denyWrite: string[]\n}\n\nexport type SandboxRipgrepConfig = {\n command: string\n args: string[]\n}\n\nexport type SandboxRuntimeConfig = {\n network: SandboxNetworkConfig\n filesystem: SandboxFilesystemConfig\n ignoreViolations?: boolean\n enableWeakerNestedSandbox?: boolean\n ripgrep: SandboxRipgrepConfig\n excludedCommands?: string[]\n}\n\ntype SettingsPermissions = {\n allow?: unknown\n deny?: unknown\n}\n\ntype SettingsSandboxNetwork = {\n allowedDomains?: unknown\n deniedDomains?: unknown\n allowUnixSockets?: unknown\n allowAllUnixSockets?: unknown\n allowLocalBinding?: unknown\n httpProxyPort?: unknown\n socksProxyPort?: unknown\n}\n\ntype SettingsSandboxRipgrep = {\n command?: unknown\n args?: unknown\n}\n\ntype SettingsSandbox = {\n enabled?: unknown\n autoAllowBashIfSandboxed?: unknown\n allowUnsandboxedCommands?: unknown\n network?: SettingsSandboxNetwork\n ignoreViolations?: unknown\n enableWeakerNestedSandbox?: unknown\n ripgrep?: SettingsSandboxRipgrep\n excludedCommands?: unknown\n}\n\nexport type PybSettingsFile = {\n permissions?: SettingsPermissions\n sandbox?: SettingsSandbox\n [key: string]: unknown\n}\n\ntype ToolRuleValue = { toolName: string; ruleContent?: string }\n\nfunction parseToolRuleString(rule: string): ToolRuleValue {\n const match = rule.match(/^([^(]+)\\(([^)]+)\\)$/)\n if (!match) return { toolName: rule }\n\n const toolName = match[1]\n const ruleContent = match[2]\n if (!toolName || !ruleContent) return { toolName: rule }\n return { toolName, ruleContent }\n}\n\nfunction uniqueStrings(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n const out: string[] = []\n const seen = new Set<string>()\n for (const item of value) {\n if (typeof item !== 'string') continue\n const trimmed = item.trim()\n if (!trimmed) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n return out\n}\n\nfunction uniqueStringsUnion(...lists: string[][]): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n for (const list of lists) {\n for (const item of list) {\n const trimmed = item.trim()\n if (!trimmed) continue\n if (seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n }\n return out\n}\n\nfunction mergeSandboxSettings(\n base: SettingsSandbox | undefined,\n next: SettingsSandbox | undefined,\n): SettingsSandbox | undefined {\n if (!base && !next) return undefined\n const merged: SettingsSandbox = { ...(base ?? {}) }\n\n const mergeBool = (k: keyof SettingsSandbox) => {\n if (next && k in next && next[k] !== undefined) merged[k] = next[k]\n }\n mergeBool('enabled')\n mergeBool('autoAllowBashIfSandboxed')\n mergeBool('allowUnsandboxedCommands')\n mergeBool('ignoreViolations')\n mergeBool('enableWeakerNestedSandbox')\n mergeBool('excludedCommands')\n\n if (next?.network) {\n merged.network = { ...(merged.network ?? {}), ...next.network }\n }\n if (next?.ripgrep) {\n merged.ripgrep = { ...(merged.ripgrep ?? {}), ...next.ripgrep }\n }\n\n return merged\n}\n\nexport function loadMergedSettings(options?: {\n projectDir?: string\n homeDir?: string\n}): PybSettingsFile {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir\n\n const user = loadSettingsWithLegacyFallback({\n destination: 'userSettings',\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n const project = loadSettingsWithLegacyFallback({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n const local = loadSettingsWithLegacyFallback({\n destination: 'localSettings',\n projectDir,\n homeDir,\n migrateToPrimary: true,\n }).settings as PybSettingsFile | null\n\n const allow = uniqueStringsUnion(\n uniqueStrings(user?.permissions?.allow),\n uniqueStrings(project?.permissions?.allow),\n uniqueStrings(local?.permissions?.allow),\n )\n const deny = uniqueStringsUnion(\n uniqueStrings(user?.permissions?.deny),\n uniqueStrings(project?.permissions?.deny),\n uniqueStrings(local?.permissions?.deny),\n )\n\n const sandbox = mergeSandboxSettings(\n mergeSandboxSettings(user?.sandbox, project?.sandbox),\n local?.sandbox,\n )\n\n return {\n permissions: { allow, deny },\n ...(sandbox ? { sandbox } : {}),\n }\n}\n\nexport function normalizeSandboxRuntimeConfigFromSettings(\n settings: PybSettingsFile,\n options?: {\n projectDir?: string\n homeDir?: string\n defaultRipgrep?: SandboxRipgrepConfig\n },\n): SandboxRuntimeConfig {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir ?? homedir()\n\n const permissions = settings.permissions ?? {}\n const allowRules = uniqueStrings(permissions.allow)\n const denyRules = uniqueStrings(permissions.deny)\n\n const explicitAllowedDomains = uniqueStrings(\n settings.sandbox?.network?.allowedDomains,\n )\n const allowedDomains: string[] = [...explicitAllowedDomains]\n const deniedDomains: string[] = []\n\n for (const rule of allowRules) {\n const parsed = parseToolRuleString(rule)\n if (\n parsed?.toolName === 'WebFetch' &&\n parsed.ruleContent?.startsWith('domain:')\n ) {\n allowedDomains.push(parsed.ruleContent.substring(7))\n }\n }\n\n for (const rule of denyRules) {\n const parsed = parseToolRuleString(rule)\n if (\n parsed?.toolName === 'WebFetch' &&\n parsed.ruleContent?.startsWith('domain:')\n ) {\n deniedDomains.push(parsed.ruleContent.substring(7))\n }\n }\n\n const allowWrite: string[] = ['.']\n const denyWrite: string[] = []\n const denyRead: string[] = []\n\n const userCandidates = getSettingsFileCandidates({\n destination: 'userSettings',\n homeDir,\n })\n const userCandidatesWithEnv = getSettingsFileCandidates({\n destination: 'userSettings',\n })\n const projectCandidates = getSettingsFileCandidates({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n })\n const localCandidates = getSettingsFileCandidates({\n destination: 'localSettings',\n projectDir,\n homeDir,\n })\n\n for (const path of [\n userCandidates?.primary,\n ...(userCandidates?.legacy ?? []),\n userCandidatesWithEnv?.primary,\n ...(userCandidatesWithEnv?.legacy ?? []),\n projectCandidates?.primary,\n ...(projectCandidates?.legacy ?? []),\n localCandidates?.primary,\n ...(localCandidates?.legacy ?? []),\n ]) {\n if (!path) continue\n if (denyWrite.includes(path)) continue\n denyWrite.push(path)\n }\n\n for (const rule of allowRules) {\n const parsed = parseToolRuleString(rule)\n if (\n (parsed?.toolName === 'Write' || parsed?.toolName === 'Edit') &&\n parsed.ruleContent\n ) {\n allowWrite.push(parsed.ruleContent)\n }\n }\n\n for (const rule of denyRules) {\n const parsed = parseToolRuleString(rule)\n if (\n (parsed?.toolName === 'Write' || parsed?.toolName === 'Edit') &&\n parsed.ruleContent\n ) {\n denyWrite.push(parsed.ruleContent)\n }\n if (parsed?.toolName === 'Read' && parsed.ruleContent) {\n denyRead.push(parsed.ruleContent)\n }\n }\n\n const sandboxNetwork = settings.sandbox?.network\n\n const defaultRipgrep: SandboxRipgrepConfig = options?.defaultRipgrep ?? {\n command: 'rg',\n args: [],\n }\n const ripgrep: SandboxRipgrepConfig =\n typeof settings.sandbox?.ripgrep?.command === 'string'\n ? {\n command: settings.sandbox!.ripgrep!.command as string,\n args: Array.isArray(settings.sandbox?.ripgrep?.args)\n ? (settings.sandbox!.ripgrep!.args as unknown[]).filter(\n (v): v is string => typeof v === 'string',\n )\n : [],\n }\n : defaultRipgrep\n\n return {\n network: {\n allowedDomains: uniqueStringsUnion(allowedDomains),\n deniedDomains: uniqueStringsUnion(deniedDomains),\n allowUnixSockets: Array.isArray(sandboxNetwork?.allowUnixSockets)\n ? (sandboxNetwork!.allowUnixSockets as unknown[]).filter(\n (v): v is string => typeof v === 'string',\n )\n : [],\n allowAllUnixSockets:\n typeof sandboxNetwork?.allowAllUnixSockets === 'boolean'\n ? sandboxNetwork.allowAllUnixSockets\n : undefined,\n allowLocalBinding:\n typeof sandboxNetwork?.allowLocalBinding === 'boolean'\n ? sandboxNetwork.allowLocalBinding\n : undefined,\n httpProxyPort:\n typeof sandboxNetwork?.httpProxyPort === 'number'\n ? sandboxNetwork.httpProxyPort\n : undefined,\n socksProxyPort:\n typeof sandboxNetwork?.socksProxyPort === 'number'\n ? sandboxNetwork.socksProxyPort\n : undefined,\n },\n filesystem: {\n denyRead: uniqueStringsUnion(denyRead),\n allowWrite: uniqueStringsUnion(allowWrite),\n denyWrite: uniqueStringsUnion(denyWrite),\n },\n ignoreViolations:\n typeof settings.sandbox?.ignoreViolations === 'boolean'\n ? settings.sandbox.ignoreViolations\n : undefined,\n enableWeakerNestedSandbox:\n typeof settings.sandbox?.enableWeakerNestedSandbox === 'boolean'\n ? settings.sandbox.enableWeakerNestedSandbox\n : undefined,\n excludedCommands: uniqueStrings(settings.sandbox?.excludedCommands),\n ripgrep,\n }\n}\n\nfunction looksLikeLinuxGlobPattern(ruleContent: string): boolean {\n const trimmed = ruleContent.replace(/\\/\\*\\*$/, '')\n return /[*?[\\]]/.test(trimmed)\n}\n\nexport function getLinuxSandboxGlobPatternWarnings(\n settings: PybSettingsFile,\n options?: { platform?: NodeJS.Platform },\n): string[] {\n const platform = options?.platform ?? process.platform\n if (platform !== 'linux') return []\n if (settings.sandbox?.enabled !== true) return []\n\n const permissions = settings.permissions ?? {}\n const allow = uniqueStrings(permissions.allow)\n const deny = uniqueStrings(permissions.deny)\n\n const warnings: string[] = []\n for (const rule of [...allow, ...deny]) {\n const parsed = parseToolRuleString(rule)\n if (!parsed?.ruleContent) continue\n if (\n parsed.toolName !== 'Write' &&\n parsed.toolName !== 'Edit' &&\n parsed.toolName !== 'Read'\n )\n continue\n if (!looksLikeLinuxGlobPattern(parsed.ruleContent)) continue\n warnings.push(rule)\n }\n\n return warnings\n}\n\nexport type SandboxConfigListener = (config: SandboxRuntimeConfig) => void\n\nexport class SandboxConfigManager {\n private listeners = new Set<SandboxConfigListener>()\n private watchPaths: string[] = []\n private current: SandboxRuntimeConfig | null = null\n\n getCurrent(): SandboxRuntimeConfig {\n if (!this.current) {\n const settings = loadMergedSettings()\n this.current = normalizeSandboxRuntimeConfigFromSettings(settings)\n }\n return this.current\n }\n\n subscribe(listener: SandboxConfigListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n initialize(options?: { projectDir?: string; homeDir?: string }): void {\n const projectDir = options?.projectDir ?? process.cwd()\n const homeDir = options?.homeDir ?? homedir()\n const user = getSettingsFileCandidates({\n destination: 'userSettings',\n homeDir,\n })\n const userEnv = getSettingsFileCandidates({ destination: 'userSettings' })\n const project = getSettingsFileCandidates({\n destination: 'projectSettings',\n projectDir,\n homeDir,\n })\n const local = getSettingsFileCandidates({\n destination: 'localSettings',\n projectDir,\n homeDir,\n })\n\n const paths = [\n user?.primary,\n ...(user?.legacy ?? []),\n userEnv?.primary,\n ...(userEnv?.legacy ?? []),\n project?.primary,\n ...(project?.legacy ?? []),\n local?.primary,\n ...(local?.legacy ?? []),\n ].filter((p): p is string => Boolean(p))\n this.watchPaths = Array.from(new Set(paths))\n\n for (const p of this.watchPaths) {\n watchFile(p, { interval: 1000 }, () => {\n const settings = loadMergedSettings({ projectDir, homeDir })\n this.current = normalizeSandboxRuntimeConfigFromSettings(settings, {\n projectDir,\n homeDir,\n })\n for (const listener of this.listeners) listener(this.current)\n })\n }\n }\n\n close(): void {\n for (const p of this.watchPaths) {\n try {\n unwatchFile(p)\n } catch {}\n }\n this.watchPaths = []\n }\n}\n", "const MAX_LINES_TO_READ = 2000\nconst MAX_LINE_LENGTH = 2000\n\nexport const TOOL_NAME = 'Read'\nexport const DESCRIPTION = 'Read a file or directory from the local filesystem.'\n\nexport const PROMPT = `Reads a file or directory from the local filesystem. You can access any file or directory directly by using this tool.Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid; otherwise, Ensure the path is confirmed by Glob/Grep before reading.\n\n## Best Practice\n- **Read vs Analyze**: Use this tool when you need to inspect full implementation details.\n- **Workflow**: Locate file (Glob/Grep) -> Read file (FileRead) -> Edit file.\n- **Avoid**: Do not use this to 'search' for code strings; use 'Grep' or 'Glob' for that.\n\n## When NOT to Use Read Tool\n- **Unverified Paths**: Do NOT read a file if the path was inferred or guessed from context. Always verify the path exists using Glob/Grep first.\n- **Exploration Phase**: When exploring unfamiliar code, do NOT assume file locations. Use Glob/Grep to discover actual paths before reading.\n- It is okay to read a file that does not exist; an error will be returned. \n\n## Usage Details\n- The file_path parameter must be an absolute path, not a relative path\n- This tool supports both file mode and directory mode\n- In directory mode, offset/limit are 1-based entry pagination and offset>=1 is required\n- In file mode, offset/limit are 1-based line pagination; offset=1 starts from the first line shown in cat -n output\n- By default, file mode reads up to ${MAX_LINES_TO_READ} lines starting from the beginning of the file\n- You can optionally specify a line offset and limit (especially handy for long files). **Smart Truncation is active** only in file mode when \\`limit\\` is provided and \\`symbol_name\\` is not provided: if your limit cuts a function or class in the middle, the tool will automatically extend the read range to include the full semantic block (up to 500 extra lines).\n- Smart Truncation is a best-effort semantic boundary repair (Tree-sitter). If semantic parsing fails, Read falls back to the original offset/limit window.\n- symbol_name enables LSP-assisted symbol read: provide an exact symbol name to resolve the symbol range and read that block directly\n- When \\`symbol_name\\` is provided, Read resolves symbol range via LSP and reads that block directly (offset/limit are ignored for range selection).\n- Use symbol_name only after file path is confirmed and when you need a specific class/function definition; if symbol is missing, unresolved, or LSP is unavailable, fallback to offset/limit or use LspTool for semantic discovery first.\n- Directory mode returns a one-level tree structure using \u251C\u2500\u2500/\u2514\u2500\u2500 and supports pagination continuation hints\n- For large files, iterate in chunks: offset=1 limit=200, then offset=201 limit=200, and so on until the needed region is covered\n- File text truncation is capped at 50KB per result and 2000 lines; 50KB is file text truncation and not a directory access gate\n- Any lines longer than ${MAX_LINE_LENGTH} characters will be truncated\n- Results are returned using cat -n format, with line numbers starting at 1\n- This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually.\n- This tool can read PDF files and return them as document blocks for analysis.\n- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.\n- For wide repository exploration, still prefer Glob first, then use Read for focused file/directory inspection.\n- You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.\n- You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n\n## Typical Usage Examples\n### Example 1: Exploring Unfamiliar Codebase\n <example>\n user: How does authentication work in this project?\n assistant: [uses Grep tool with pattern=\"auth|login\" to find relevant files]\n [uses Glob tool with pattern=\"**/auth*.{ts,js}\" to locate auth modules]\n [reads the matched files after confirming their paths]\n </example>\n\n### Example 2: User Mentions a Concept Without Path\n <example>\n user: Check the database configuration\n assistant: [uses Glob tool with pattern=\"**/config*.{ts,js,json}\"]\n [uses Grep tool with pattern=\"database|db_\" to find config files with db settings]\n [reads the confirmed config file]\n </example>\n\n### Example 3: Read Directory Structure Then Read File\n <example>\n user: Check the API module layout and read router implementation\n assistant: [uses Glob tool with pattern=\"**/api*\"]\n [reads the confirmed api directory path to get one-level tree structure with Read]\n [reads the router file path found in that directory tree]\n </example>\n\n### Example 4: LSP-Assisted Symbol Read\n <example>\n user: I only need the function that actually executes file reading, not the whole file\n assistant: [uses Glob/Grep to confirm FileReadTool file path]\n [uses Read with file_path=\"<absolute path>/FileReadTool.tsx\" symbol_name=\"call\"]\n [if symbol is missing or unresolved, uses LspTool documentSymbol to discover exact symbol names, then retries]\n [if LSP is unavailable, falls back to offset/limit chunked reads around likely implementation area]\n <reasoning>\n The assistant used symbol_name-based Read because:\n 1. User intent is a specific implementation block, not whole-file browsing\n 2. symbol_name gives precise semantic range selection and avoids noisy context\n 3. LspTool is used only for symbol discovery fallback, while Read remains the code retrieval tool\n </reasoning>\n </example>\n\n### Example 5: Smart Truncation on Partial Window\n <example>\n user: Please read this file section for me; I do not know where the function ends\n assistant: [uses Read with file_path=\"<absolute path>/service.ts\" offset=120 limit=30]\n [relies on Smart Truncation to auto-extend when the requested window cuts a function/class boundary]\n [checks returned startLine/numLines and continues with adjacent chunks if more context is needed]\n [if semantic parsing fails, falls back to original offset/limit and continues chunked reading]\n <reasoning>\n The assistant used offset/limit Read with Smart Truncation because:\n 1. User asked for a local section without symbol-level knowledge\n 2. Pagination windows can split semantic containers, causing misleading partial code\n 3. Smart Truncation repairs semantic boundaries while preserving pagination workflow\n </reasoning>\n </example>\n`.trim()\n", "export const TOOL_NAME = 'Edit'\nexport const DESCRIPTION = `Performs smart string replacements in files using SEARCH/REPLACE blocks.\n\nUsage:\n1. **Read First**: You must use your \\`Read\\` tool at least once before editing.\n2. **Block Format**: Provide changes as one or more SEARCH/REPLACE blocks.\n \\`\\`\\`\n <<<<<<< SEARCH\n [original code to replace]\n =======\n [new code to insert]\n >>>>>>> REPLACE\n \\`\\`\\`\n3. **Multiple Edits**: You can provide multiple blocks in a single turn to perform batch edits.\n4. **Context**: Include enough surrounding lines in the SEARCH block to ensure uniqueness.\n5. **Indentation**: Preserve the exact indentation (tabs/spaces) of the original file in your SEARCH block.\n6. **Smart Matching**: The tool uses a fuzzy matching engine. It can locate code even if there are minor differences in whitespace or indentation.\n7. **Conditional Edit**: Use \\`if_not_contains\\` to skip the edit if the file already contains a specific string.\n8. **Thinking**: You can include \"thinking\" text between blocks; the tool will ignore it.\n\n## LSP-Integrated Behavior\n- **Semantic Anchor Assist**: Before fuzzy replacement, Edit tries LSP anchor matching to narrow replacement to the most relevant symbol range.\n- **When It Helps**: Especially useful when the same snippet appears multiple times and plain text matching may hit the wrong block.\n- **Fallback**: If LSP anchor is unavailable, Edit falls back to normal SEARCH/REPLACE matching.\n- **Post-Edit Verification**: Set \\`verify: true\\` to run LSP diagnostics after applying edits.\n- **Verification Guardrail**: If syntax/type diagnostics contain errors after edit, Edit reverts changes and returns a verification failure.\n- **When LSP Is Unavailable**: You may receive verification unavailable; retry with \\`verify: false\\` only when you have high confidence in edit safety.\n\nNotes:\n- The edit will FAIL if the SEARCH block matches multiple locations(ambiguous). Provide more context.\n- To delete code, leave the REPLACE section empty.\n- To create a new file with Edit, use an empty SEARCH block with the desired content in REPLACE only in efficiency-focused scenarios (for example, when you are already performing a multi-block edit workflow and adding one small new helper file in the same operation).\n- ALWAYS prefer editing existing files. NEVER write new files unless explicitly required.\n- For Jupyter Notebooks (.ipynb), use the NotebookEditTool instead.\n\n## Typical Usage Examples\n### Example 1: Ambiguous Duplicate Snippet with LSP Anchor\n<example>\nuser: Update the constructor guard in UserService, not the test helper copy\nassistant: [uses Read on UserService file to confirm target block]\n[uses Edit with SEARCH/REPLACE block and verify=true]\n[relies on LSP anchor assist to prefer semantic symbol region when duplicate text exists]\n<reasoning>\nThe assistant enabled semantic-safe editing because:\n1. Duplicate snippets can cause ambiguous fuzzy matches\n2. LSP anchor narrows replacement to the intended symbol scope\n3. verify=true adds post-edit diagnostics guardrail and auto-revert on syntax errors\n</reasoning>\n</example>\n\n### Example 2: Verification-Unavailable Recovery\n<example>\nuser: Apply this quick rename in a generated file\nassistant: [uses Read to confirm exact path and block]\n[uses Edit with verify=true]\n[if response says verification unavailable, retries with verify=false and tighter SEARCH context]\n<reasoning>\nThe assistant keeps verification first, then degrades safely because:\n1. LSP verification is preferred for correctness\n2. Generated or unsupported files may not have active LSP diagnostics\n3. Retrying with verify=false is acceptable only after narrowing context\n</reasoning>\n</example>\n`.trim()\n", "import { TOOL_NAME as TOOL_NAME_READ } from '../FileReadTool/prompt'\n\nexport const TOOL_NAME = 'Write'\nexport const DESCRIPTION = 'Write a file to the local filesystem.'\n\nexport const PROMPT = `Writes a file to the local filesystem.\n\n## Best Practice\n- **Write vs Edit**: Use this tool when you need to create a new file or fully replace a file's content.\n- **Primary Role**: This is the default tool for new file,parent directories creation and full-file replacement.\n- **Workflow**: Locate path (Glob/Grep) -> Read existing file with ${TOOL_NAME_READ} when applicable -> Write full target content.\n- **Directory Handling**: If parent directories do not exist, this tool creates them automatically. Do NOT use Bash mkdir for this.\n\n## When NOT to Use Write Tool\n- **Partial updates**: If you only need to change a small section, prefer Edit instead of replacing the entire file.\n- **Unread existing file**: Do NOT overwrite an existing file unless it has been read first with ${TOOL_NAME_READ}.\n- **Unnecessary new files**: ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- **Unrequested docs**: NEVER proactively create documentation files (*.md) or README files. Only create them when explicitly requested by the User.\n\n## Usage Details\n- The file_path parameter must be an absolute path, not a relative path.\n- This tool overwrites existing files at the provided path.\n- For existing files, this tool enforces a read-before-write safety check using ${TOOL_NAME_READ}.\n- For new files, this tool creates missing parent directories automatically.\n- The content parameter should be the complete desired final file content.\n- Preserve repository conventions (line endings, encoding, and formatting) in the written content.\n- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.\n\n## Typical Usage Examples\n### Example 1: Create a New File in Nested Directory\n<example>\n user: Create src/features/auth/config/defaults.ts with these defaults...\n assistant: [uses Glob/Grep to confirm target area and naming conventions]\n [uses Write with file_path as absolute path under src/features/auth/config/defaults.ts]\n [Write auto-creates missing parent directories]\n</example>\n\n### Example 2: Replace Entire Existing File Safely\n<example>\n user: Rewrite this config file completely with the new schema\n assistant: [uses ${TOOL_NAME_READ} to read the existing file first]\n [uses Write to replace the whole file content]\n</example>\n\n### Example 3: Avoid Write for Small Localized Change\n<example>\n user: Change only one import line in this file\n assistant: [uses ${TOOL_NAME_READ} to inspect file]\n [uses Edit for localized update instead of Write]\n</example>\n`.trim()\n", "export const TOOL_NAME = 'Glob'\n\nexport const DESCRIPTION = `Fast file pattern matching tool that works with any codebase size\n\n ## WhenToUse & Best Practice\n - If you have keywords or fuzzy paths, use Glob first to narrow candidates.\n - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead\n - You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.\n - This tool is for FINDING files.\n\n ## Directory Structure Guidance\n - For one-level directory structure, use Read directly on the directory path (offset>=1, optional limit)\n - Use Glob for file-path discovery and candidate narrowing, not as the primary one-level directory listing workflow\n\n ## Search Strategy\n - **Broad-to-Narrow Pattern**: Start with a broad pattern, then narrow based on results.\n - Step 1: Use broad patterns like \\`**/*.ts\\` or \\`src/**/*\\` to get an overview\n - Step 2: Analyze results and refine with more specific patterns\n - Example: \"\\`**/*.test.ts\\`\" \u2192 too many results \u2192 \"src/**/auth*.test.ts\"\n - **Pattern Selection Guide**:\n - Unknown structure? Start with \\`**/*.{ext}\\` to discover layout, then use Read on specific directory paths for one-level structure\n - Looking for specific type? Use descriptive names: \\`**/test*\\`, \\`**/config*\\`\n - In a specific area? Combine path + pattern: \\`src/auth/**/*.ts\\`\n - **Discovery Workflow**: For unfamiliar codebases, run these in parallel:\n - \\`**/package.json\\`, \\`**/*.{ts,js,tsx,jsx}\\`, \\`**/README*\\`, \\`**/*config*.{ts,js,json}\\`\n - Analyze structure \u2192 refine search \u2192 read key files\n - **Tool Collaboration**:\n - Read \\`directory_path\\` \u2192 Get one-level directory tree structure\n - Grep \u2192 After Glob finds files, use Grep to search content\n - Read \u2192 Read the found file contents\n\n ## Usage Details\n - Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n - Returns absolute file paths sorted by modification time (most recent first)\n - Use this tool when you need to find files by name patterns\n - Powered by ripgrep with \\`--files\\` mode for fast pattern matching\n - \\`path\\` parameter: Specify the directory to search in. If omitted, uses the current working directory. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Supports both relative and absolute paths.\n - Results are limited to 100 files by default. If truncated, use a more specific path or pattern to narrow results.\n - Search ignores .gitignore rules and includes hidden files by default.\n - **Empty Results**: When no files are found, try broader patterns (e.g., src/**/*) or verify path exists.\n - **Error Handling**: Returns error if \\`path\\` does not exist or is not a valid directory.\n - **LSP Semantic Mode**: \\`semantic: true\\` enables workspace symbol fallback when file globbing returns empty.\n - **Semantic search is opt-in**: Only set \\`semantic: true\\` when you intentionally want LSP-assisted fallback.\n - Semantic output may include:\n - \\`semanticNotice\\`: human-readable semantic fallback note\n - \\`semanticReason\\`: structured reason code (e.g., \\`SYMBOLS_ADDED\\`, \\`NO_SYMBOL_MATCH\\`, \\`LSP_UNAVAILABLE\\`)\n - \\`semanticSuggestion\\`: suggested next action aligned to reason code\n - **Truncated Results**: When results are truncated (limited to 100 files), narrow down using:\n 1. Add a more specific path: \\`src/core/**/*.ts\\` instead of \\`**/*.ts\\`\n 2. Use file extension filter: \\`src/**/*.test.ts\\` instead of \\`src/**/*.ts\\`\n 3. Use Read on a specific directory path to confirm one-level structure, then target specific directories with Glob\n\n ## Typical Usage Examples\n\n ### Example 1: Project Structure Discovery (Unknown Codebase)\n <example>\n user: I'm new to this project, what's the structure? \n assistant: [uses Glob tool with pattern=\"**/package.json\" to find project roots]\n [reads the confirmed source directory path to inspect one-level tree structure]\n [uses Glob tool with pattern=\"**/*.{ts,tsx,js,jsx}\" to locate major source areas]\n </example>\n\n ### Example 2: Find Files by Type in Specific Area\n <example>\n user: Find all test files in the auth module\n assistant: [uses Glob tool with pattern=\"src/auth/**/*.test.ts\"]\n [uses Read tool to examine specific test files]\n </example>\n\n ### Example 3: Config File Location (Deterministic) \n <example>\n user: Where is the webpack configuration?\n assistant: [uses Glob tool with pattern=\"**/webpack*.{js,ts,json}\"]\n [uses Read tool on the matched config file]\n </example>\n\n ### Example 4: Parallel Discovery for Entry Points\n <example>\n user: What are the main entry points of this application?\n assistant: [uses Glob tool with pattern=\"**/index.{ts,js}\"]\n [uses Glob tool with pattern=\"**/main.{ts,js}\"]\n [uses Glob tool with pattern=\"**/app.{ts,js}\"]\n [uses Read tool to examine the entry point files]\n </example>\n\n ### Example 5: Narrow Down After Broad Results\n <example>\n user: Find all TypeScript files in the project\n assistant: [uses Glob tool with pattern=\"**/*.ts\" - returns 500+ files, truncated]\n [uses Glob tool with pattern=\"src/**/*.ts\" to focus on source code]\n [uses Glob tool with pattern=\"src/core/**/*.ts\" to narrow further if needed]\n </example>\n\n ### Example 6: Semantic Fallback for Unknown File Path\n <example>\n user: Find where AuthService is implemented, I do not know the file name\n assistant: [uses Glob tool with pattern=\"**/*AuthService*\" semantic=false first]\n [if no files found, retries with semantic=true]\n [reads semanticReason and semanticSuggestion to decide next step]\n <reasoning>\n The assistant switches to semantic mode because:\n 1. Filename-based glob failed and user intent is symbol-oriented\n 2. semantic=true allows LSP workspace symbols to recover likely file paths\n 3. semanticReason + semanticSuggestion provide explicit fallback diagnostics\n </reasoning>\n </example>\n`.trim()\n", "export const TOOL_NAME = 'Grep'\n\nexport const DESCRIPTION = `A powerful fast content search tool that works with any codebase size\n\n ## Best Practice\n - Use Grep as a \"Scout\" to *find* entry points based on text patterns.\n - STEP 1: Search for a unique string (e.g., error message, URL route, specific variable name).\n - STEP 2: Once you get a match (File + Line Number), STOP grepping.\n - STEP 3: Use Read to get the exact line + character, then call LspTool for definition or references.\n - AVOID: Do not use Grep to trace execution flow (e.g., searching for \"functionName\" manually). Use LSP for that.\n - Hotspot strategy: narrow the path scope first, then paginate or refine the search; after truncation, focus on high-signal directories to avoid full-repo scans.\n\n ## Search Strategy\n - **Pattern Refinement Workflow**:\n - Start broad: simple keyword first, observe results\n - Narrow down: add constraints (type, glob, path) if too many matches\n - Switch mode: \\`files_with_matches\\` for discovery, \\`content\\` for details\n - **From Vague Intent to Precise Pattern**:\n - \"How does auth work?\" \u2192 Start with Grep(\"auth\", type=\"ts\") \u2192 Analyze results \u2192 Refine pattern\n - \"Find the API endpoints\" \u2192 Grep(\"router|route|endpoint\", type=\"ts\") \u2192 Read key files\n - \"Where is this error from?\" \u2192 Grep(exact error message) \u2192 Trace back to source\n - **Iterative Narrowing**:\n - Too many results? Add \\`glob\\`, \\`type\\`, or narrower \\`path\\`\n - No results? Broaden pattern, try case-insensitive (\\`-i\\`), or try alternative keywords\n - Wrong results? Adjust pattern, check regex syntax, try alternative keywords\n - **Tool Collaboration**:\n - Read \"directory_path\" \u2192 Confirm one-level directory structure for search scope\n - Glob \"file_path\" \u2192 Confirm file path existence\n - Read \u2192 Read specific content of matched files\n - LspTool \u2192 Trace definitions and references (replace manual Grep tracing)\n\n ## Usage Details\n - ALWAYS use Grep for search tasks. NEVER invoke \\`grep\\` or \\`rg\\` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Powered by ripgrep for fast text search with full regex support (e.g., \"log.*Error\", \"function\\\\s+\\\\w+\")\n - Pattern syntax: Uses ripgrep - literal braces need escaping (use \\`interface\\\\{\\\\}\\` to find \\`interface{}\\` in Go code)\n - Excludes version control directories (.git, .svn, .hg, .bzr) automatically\n - Includes hidden files by default\n\n **Path & Scope**:\n - \\`path\\` parameter: File or directory to search in. Defaults to current working directory.\n - \\`glob\\` parameter: Filter files by glob pattern (e.g., \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob\n - \\`type\\` parameter: Filter by file type (e.g., \"js\", \"py\", \"rust\", \"go\", \"java\") - more efficient than glob for standard types\n - Path guidance: If user provides a path, use it directly. If uncertain, confirm with Glob first.\n\n **Output Modes**:\n - \\`files_with_matches\\` (default): Returns file paths sorted by modification time\n - \\`content\\`: Shows matching lines with line numbers (supports -A/-B/-C context)\n - \\`count\\`: Shows match counts per file\n\n **Context & Pagination**:\n - \\`-B\\`, \\`-A\\`, \\`-C\\`: Context lines before/after/around matches (requires output_mode: \"content\")\n - \\`-n\\`: Show line numbers (default: true, requires output_mode: \"content\")\n - \\`head_limit\\`: Limit output to first N entries (works across all modes)\n - \\`offset\\`: Skip first N entries before applying head_limit\n - \\`multiline\\`: Enable multiline mode where . matches newlines (default: false)\n\n **Case Sensitivity**:\n - \\`-i\\`: Enable case-insensitive search\n\n **Result Handling**:\n - Results are truncated at 20,000 characters if too large\n - Use Task tool for open-ended searches requiring multiple rounds\n - **Semantic Fallback** (\\`semantic: true\\`): when text grep has no hit (or \\`symbol_type\\` is provided), Grep can query LSP workspace symbols.\n - Semantic-enhanced outputs may include:\n - \\`semanticNotice\\`: fallback summary\n - \\`semanticReason\\`: structured reason code (e.g., \\`SYMBOLS_ADDED\\`, \\`NO_SYMBOL_MATCH\\`, \\`LSP_UNAVAILABLE\\`)\n - \\`semanticSuggestion\\`: suggested next action by reason code\n - Keep deterministic workflow: text search first, semantic fallback second.\n\n **Typical Usage Examples**:\n\n Example 1: Exact Error Message Tracing (Deterministic)\n <example>\n user: Where does the error \"Connection timeout after 30s\" come from?\n assistant: [uses Grep tool with pattern=\"Connection timeout after 30s\"output_mode=\"content\"]\n [uses Read tool to examine the error source and surrounding context]\n </example>\n\n Example 2: Precise Function Definition Lookup (Deterministic)\n <example>\n user: Find the implementation of \\`calculateCompoundInterest\\` function\n assistant: [uses Grep tool with pattern=\"calculateCompoundInterest\" type=\"ts\"output_mode=\"content\"]\n [uses Read tool on the matched file to read the full implementation]\n </example>\n \n Example 3: Iterative Narrowing for Broad Patterns\n <example>\n user: Find all API route definitions\n assistant: [uses Grep tool with pattern=\"router\\\\.(get|post|put|delete)\" type=\"ts\"] \n [if too many results: adds path=\"src/routes\" to narrow scope]\n [uses Read tool to inspect specific route handlers]\n </example>\n\n Example 4: Handoff to LSP After Entry Point Found\n <example>\n user: Find all usages of the \\`PaymentService\\` class\n assistant: [uses Grep tool with pattern=\"class PaymentService\" type=\"ts\"output_mode=\"content\"]\n [uses LSP findReferences at the class definition location to get all references]\n </example>\n\n Example 5: Case-Insensitive Search for Config Values\n <example>\n user: Where is the database host configured?\n assistant: [uses Grep tool with pattern=\"database.*host|db_host|DB_HOST\" -i: true] \n [uses Read tool to examine configuration files]\n </example>\n\n Example 6: Semantic Fallback with Structured Reason\n <example>\n user: Find usages of PaymentSrvce (name might be misspelled)\n assistant: [uses Grep tool with pattern=\"PaymentSrvce\" output_mode=\"files_with_matches\"]\n [if no hit, retries with semantic=true]\n [uses semanticReason and semanticSuggestion to decide whether to broaden query or switch to LspTool]\n <reasoning>\n The assistant uses semantic fallback because:\n 1. Text grep may miss typo-tolerant symbol matches\n 2. LSP workspace symbols can recover intended semantic targets\n 3. Structured reason fields make fallback outcomes explicit and actionable\n </reasoning>\n </example>\n `.trim()\n", "export const TOOL_NAME = 'LSP'\n\nexport const PROMPT = `Interact with Language Server Protocol (LSP) servers to get code intelligence features.Supports all languages.\n\n## Capabilities & Scenarios\nThis tool acts as your \"Code Analyst\". Use it to understand the codebase semantically, rather than just matching text.\n\n### 1. Tracing Logic (Where does this go?)\n- **Scenario**: You see a function call \\`calculateTax(amount)\\` and need to know its formula.\n- **Action**: Use \\`goToDefinition\\` on the function name.\n- **Why**: It jumps directly to the implementation, even if it's imported from another file.\n\n### 2. Impact Analysis (What uses this?)\n- **Scenario**: You are planning to rename or modify the \\`User\\` class.\n- **Action**: Use \\`findReferences\\` at the symbol position (line + character) in the file where \\`User\\` is declared or used.\n- **Why**: It lists every file and line where \\`User\\` is referenced, ensuring you don't break dependents.\n\n### 3. Exploring New Files (What's in here?)\n- **Scenario**: You just opened a large file \\`utils.ts\\` and want a quick overview.\n- **Action**: Use \\`documentSymbol\\`.\n- **Why**: It returns a structured outline (Classes, Functions, Variables) using LspFacade policy: LSP-first for accuracy, Tree-Sitter fallback for speed when needed.\n\n### 4. Interface Implementation (Who implements this?)\n- **Scenario**: You see an interface \\`IStorage\\` and want to find the concrete class (e.g., \\`S3Storage\\`).\n- **Action**: Use \\`goToImplementation\\`.\n- **Why**: Grep might just find the import; LSP finds the actual code that implements the interface.\n\n### 5. Scope Analysis (What is visible here?)\n- **Scenario**: You are debugging a closure or nested function and want to know which variables are captured or locally defined.\n- **Action**: Use \\`getScope\\`.\n- **Why**: It returns the local variables and closure captures at the current position. Essential for debugging Python closures or JavaScript lexical scopes.\n\n### 6. Real-time Diagnostics (Is this correct?)\n- **Scenario**: You just edited a file and want to verify if you introduced any syntax errors.\n- **Action**: Use \\`diagnostics\\` with \\`waitForDiagnostics: true\\`.\n- **Why**: It waits for the language server to re-analyze the file and returns fresh errors/warnings. This is your \"Self-Correction\" mechanism.\n\n### 7. Workspace Symbol Search (Where is this symbol?)\n- **Scenario**: You need to find a class or function across the entire project.\n- **Action**: Use \\`workspaceSymbol\\` with a query string and a scoped filePath (module or directory).\n- **Why**: It searches across all files in the scope. **Important**: Must provide a scoped path to avoid unbounded full-repo queries.\n\n## Supported Operations\n\n### Location-Based Operations (require line + character)\nThese 8 operations require precise symbol position:\n- \\`goToDefinition\\`: Find where a symbol is defined\n- \\`findReferences\\`: Find all references to a symbol\n- \\`hover\\`: Get hover information (documentation, type info) for a symbol\n- \\`goToImplementation\\`: Find implementations of an interface or abstract method\n- \\`prepareCallHierarchy\\`: Get call hierarchy item at a position (functions/methods)\n- \\`incomingCalls\\`: Find all functions/methods that call the function at a position\n- \\`outgoingCalls\\`: Find all functions/methods called by the function at a position\n- \\`getScope\\`: Get local variables and closure captures at a position\n\n### Document-Level Operations (no position required)\n- \\`documentSymbol\\`: Get all symbols (functions, classes, variables) in a document\n- \\`diagnostics\\`: Get validation errors and warnings for a file (supports waiting for fresh results)\n\n### Workspace-Level Operations\n- \\`workspaceSymbol\\`: Search for symbols across the entire workspace (requires query + scoped filePath)\n\n## Parameters\n\nAll operations require:\n- \\`filePath\\`: The file or directory to operate on\n\nLocation-based operations require:\n- \\`line\\`: The line number (1-based, as shown in editors)\n- \\`character\\`: The character offset (1-based, as shown in editors)\n\n\\`workspaceSymbol\\` requires:\n- \\`query\\`: The symbol name or keyword to search for\n\nOptional:\n- \\`waitForDiagnostics\\`: If true, wait for fresh diagnostics (used with \"diagnostics\" operation)\n- \\`timeout\\`: Timeout in milliseconds for waiting operations (default: 5000)\n\n## Intelligent Position Handling\n\n**Do not pass a symbol name.** LSPTool works on positions, not names. Use Read to locate the symbol and derive line + character first.\n\n### Auto-Adjustment Mechanism\nIf the specified position is not on a valid symbol, the tool automatically searches for the nearest valid token:\n- **Search scope**: Current line, then previous line, then next line\n- **Priority**: Current line tokens are preferred (lower score)\n- **Skipped tokens**: Keywords (function, class, if, for, return, etc.) and operators (=, =>, +, -, &&, ||, etc.) are automatically skipped\n- **If no valid token found**: Returns an error message\n\n### Best Practice for Position\n1. Use Read to open the file and locate the symbol\n2. Provide accurate 1-based line and character offset\n3. Position should be on the symbol name itself, not on keywords/operators\n4. If unsure, position at the start of the symbol name\n\n## Workflow & Scope Guidelines\n- **Priority order**: documentSymbol \u2192 hotspot detection \u2192 Read \u2192 LSP (ensure line + character)\n- **workspaceSymbol**: Must provide scoped filePath (module or directory), avoid unbounded full-repo queries\n- **documentSymbol**: Uses LspFacade policy (LSP-first for accuracy, Tree-Sitter fallback for speed)\n\n## Typical Usage Examples\n### Example 1: Find Symbol Then Read Precise Block\n<example>\nuser: Locate JWT validation implementation quickly\nassistant: [uses LSP workspaceSymbol with query=\"jwt validate\" and scoped filePath]\n[uses Read on the discovered file and then LSP documentSymbol/definition as needed]\n<reasoning>\nThe assistant starts semantically because:\n1. User asks for implementation location, not broad text grep\n2. workspaceSymbol narrows candidate files efficiently\n3. Read is then used for exact code extraction once target is known\n</reasoning>\n</example>\n\n### Example 2: Diagnostics-First Debugging\n<example>\nuser: Build failed in api package, tell me real code errors\nassistant: [uses LSP diagnostics with waitForDiagnostics=true on scoped filePath]\n[uses goToDefinition/findReferences for follow-up impact tracing]\n<reasoning>\nThe assistant prioritizes diagnostics because:\n1. Diagnostics provide direct semantic errors from language tooling\n2. Scoped path avoids unbounded workspace queries\n3. Follow-up LSP ops can trace root-cause dependencies\n</reasoning>\n</example>\n\nNote: LSP servers are automatically managed and installed for most languages. For system-level languages (like C++, Java), ensure the corresponding tools (clangd, jdtls) are in your PATH.`\n\nexport const DESCRIPTION = PROMPT\n", "export const TOOL_NAME = 'Task'\n", "import {\n loadMergedSettings,\n normalizeSandboxRuntimeConfigFromSettings,\n} from '@utils/sandbox/sandboxConfig'\nimport { TOOL_NAME as TOOL_NAME_READ } from '../../filesystem/FileReadTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_EDIT } from '../../filesystem/FileEditTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_WRITE } from '../../filesystem/FileWriteTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_GLOB } from '../../filesystem/GlobTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_GREP } from '../../search/GrepTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_LSP } from '../../search/LspTool/prompt'\nimport { TOOL_NAME as TOOL_NAME_TASK } from '../../agent/TaskTool/constants'\n\nexport const DEFAULT_TIMEOUT_MS = 120000\nexport const MAX_TIMEOUT_MS = 600000\nexport const MAX_OUTPUT_LENGTH = 30000\nexport const MAX_RENDERED_LINES = 5\n\nconst PROJECT_URL = 'https://github.com/pyb-xc/pyb-ts'\nconst DEFAULT_CO_AUTHOR = 'PYB-XC'\n\nexport const TOOL_NAME = 'Bash'\n\nfunction isExperimentalMcpCliEnabled(): boolean {\n const value = process.env.ENABLE_EXPERIMENTAL_MCP_CLI\n if (!value) return false\n return ['1', 'true', 'yes', 'on'].includes(String(value).trim().toLowerCase())\n}\n\nfunction indentJsonForPrompt(value: unknown): string {\n return JSON.stringify(value, null, 2).split('\\n').join('\\n ')\n}\n\nfunction getAttribution(): { commit: string; pr: string } {\n const pr = `\uD83E\uDD16 Generated with [Pyb Agent](${PROJECT_URL})`\n const commit = `${pr}\\n\\n Co-Authored-By: ${DEFAULT_CO_AUTHOR} <pyb-xc@foxmail.com>`\n return { commit, pr }\n}\n\nfunction getBashSandboxPrompt(): string {\n const settings = loadMergedSettings()\n if (settings.sandbox?.enabled !== true) return ''\n\n const runtimeConfig = normalizeSandboxRuntimeConfigFromSettings(settings)\n\n const fsReadConfig = { denyOnly: runtimeConfig.filesystem.denyRead }\n const fsWriteConfig = {\n allowOnly: runtimeConfig.filesystem.allowWrite,\n denyWithinAllow: runtimeConfig.filesystem.denyWrite,\n }\n\n const filesystem = { read: fsReadConfig, write: fsWriteConfig }\n\n const allowUnixSockets =\n runtimeConfig.network.allowAllUnixSockets === true\n ? true\n : runtimeConfig.network.allowUnixSockets.length > 0\n ? runtimeConfig.network.allowUnixSockets\n : undefined\n\n const network = {\n ...(runtimeConfig.network.allowedDomains.length\n ? { allowedHosts: runtimeConfig.network.allowedDomains }\n : {}),\n ...(runtimeConfig.network.deniedDomains.length\n ? { deniedHosts: runtimeConfig.network.deniedDomains }\n : {}),\n ...(allowUnixSockets ? { allowUnixSockets } : {}),\n }\n\n const ignoredViolations = runtimeConfig.ignoreViolations\n const allowUnsandboxedCommands =\n settings.sandbox?.allowUnsandboxedCommands !== false\n\n const sections: string[] = []\n sections.push(` - Filesystem: ${indentJsonForPrompt(filesystem)}`)\n if (Object.keys(network).length > 0) {\n sections.push(` - Network: ${indentJsonForPrompt(network)}`)\n }\n if (ignoredViolations) {\n sections.push(\n ` - Ignored violations: ${indentJsonForPrompt(ignoredViolations)}`,\n )\n }\n\n const mcpCliException = isExperimentalMcpCliEnabled()\n ? ' - EXCEPTION: `mcp-cli` commands must always be called with `dangerouslyDisableSandbox: true` as they do not work properly in sandboxed mode\\n'\n : ''\n\n const overridePolicy = allowUnsandboxedCommands\n ? ` - CRITICAL: Commands run in sandbox mode by default - do NOT set \\`dangerouslyDisableSandbox\\`\n - Even if you have recently run commands with \\`dangerouslyDisableSandbox: true\\`, you MUST NOT continue that pattern\n - VERY IMPORTANT: Do NOT learn from or repeat the pattern of overriding sandbox - each command should run sandboxed by default\n${mcpCliException} - Set \\`dangerouslyDisableSandbox: true\\` if:\n 1. The user *explicitly* asks to bypass sandbox, OR\n 2. A command just failed and you see evidence of sandbox restrictions causing the failure\n - When analyzing failures:\n - Commands can fail for many reasons unrelated to the sandbox (missing files, wrong arguments, network issues, etc.)\n - Evidence of sandbox-caused failures includes:\n - \"Operation not permitted\" errors for file/network operations\n - Access denied to specific paths outside allowed directories\n - Network connection failures to non-whitelisted hosts\n - Unix socket connection errors\n - Sandbox violation logs can be noisy, but clear permission errors are strong indicators\n - When you see evidence of sandbox-caused failure:\n - IMMEDIATELY retry with \\`dangerouslyDisableSandbox: true\\` (don't ask, just do it)\n - Briefly explain what sandbox restriction likely caused the failure\n - Mention: \"Use \\`/sandbox\\` to manage restrictions\"\n - This will prompt the user for permission\n - Example of normal usage: { \"command\": \"ls\", \"description\": \"List files\" }\n - Example of override: { \"command\": \"my-tool\", \"description\": \"Run my-tool\", \"dangerouslyDisableSandbox\": true }\n - DO NOT suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the allowlist`\n : ` - CRITICAL: All commands MUST run in sandbox mode - the \\`dangerouslyDisableSandbox\\` parameter is disabled by policy\n - Commands cannot run outside the sandbox under any circumstances\n - If a command fails due to sandbox restrictions, work with the user to adjust sandbox settings instead`\n\n return `- Commands run in a sandbox by default with the following restrictions:\n${sections.join('\\n')}\n${overridePolicy}\n - IMPORTANT: For temporary files, rely on the sandbox temp directory via \\`TMPDIR\\`\n - In sandbox mode, \\`TMPDIR\\` is set to a dedicated temp directory\n - Prefer using \\`TMPDIR\\` over writing directly to \\`/tmp\\`\n - Most programs that respect \\`TMPDIR\\` will automatically use it`\n}\n\nfunction getBashGitPrompt(): string {\n const { commit, pr } = getAttribution()\n return `# Committing changes with git\n\nOnly create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:\n\nGit Safety Protocol:\n- NEVER update the git config\n- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them \n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it\n- NEVER run force push to main/master, warn the user if they request it\n- Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook (additional instructions below) \n- Before amending: ALWAYS check authorship (git log -1 --format='%an %ae')\n- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel, each using the ${TOOL_NAME} tool:\n - Run a git status command to see all untracked files.\n - Run a git diff command to see both staged and unstaged changes that will be committed.\n - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.\n2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:\n - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.).\n - Do not commit files that likely contain secrets (.env, credentials.json, etc). Warn the user if they specifically request to commit those files\n - Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n - Ensure it accurately reflects the changes and their purpose\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands:\n - Add relevant untracked files to the staging area.\n - Create the commit with a message${commit ? ` ending with:\\n ${commit}` : '.'}\n - Run git status after the commit completes to verify success.\n Note: git status depends on the commit completing, so run it sequentially after the commit.\n4. If the commit fails due to pre-commit hook changes, retry ONCE. If it succeeds but files were modified by the hook, verify it's safe to amend:\n - Check HEAD commit: git log -1 --format='[%h] (%an <%ae>) %s'. VERIFY it matches your commit\n - Check not pushed: git status shows \"Your branch is ahead\"\n - If both true: amend your commit. Otherwise: create NEW commit (never amend other developers' commits)\n\nImportant notes:\n- NEVER run additional commands to read or explore code, besides git bash commands\n- NEVER use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- DO NOT push to the remote repository unless the user explicitly asks you to do so\n- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.\n- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit\n- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:\n<example>\ngit commit -m \"$(cat <<'EOF'\n Commit message here.${commit ? `\\n\\n ${commit}` : ''}\n EOF\n )\"\n</example>\n\n# Creating pull requests\nUse the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.\n\nIMPORTANT: When the user asks you to create a pull request, follow these steps carefully:\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel using the ${TOOL_NAME} tool, in order to understand the current state of the branch since it diverged from the main branch:\n - Run a git status command to see all untracked files\n - Run a git diff command to see both staged and unstaged changes that will be committed\n - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote\n - Run a git log command and \\`git diff [base-branch]...HEAD\\` to understand the full commit history for the current branch (from the time it diverged from the base branch)\n2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel:\n - Create new branch if needed\n - Push to remote with -u flag if needed\n - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.\n<example>\ngh pr create --title \"the pr title\" --body \"$(cat <<'EOF'\n## Summary\n<1-3 bullet points>\n\n## Test plan\n[Bulleted markdown checklist of TODOs for testing the pull request...]${pr ? `\\n\\n${pr}` : ''}\nEOF\n)\"\n</example>\n\nImportant:\n- DO NOT use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- Return the PR URL when you're done, so the user can see it\n\n# Other common operations\n- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments`\n}\n\nexport function getBashToolPrompt(): string {\n const sandboxPrompt = getBashSandboxPrompt()\n return `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nIMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use the ${TOOL_NAME_GLOB} tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first check if \"foo\" exists\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - cd \"/Users/name/My Documents\" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to ${MAX_TIMEOUT_MS}ms / ${MAX_TIMEOUT_MS / 60000} minutes). If not specified, commands will timeout after ${DEFAULT_TIMEOUT_MS}ms (${DEFAULT_TIMEOUT_MS / 60000} minutes).\n - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.\n - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.\n - You can use the \\`run_in_background\\` parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the ${TOOL_NAME} tool as it becomes available. You do not need to use '&' at the end of the command when using this parameter.\n ${sandboxPrompt}\n - Avoid using Bash with the \\`find\\`, \\`grep\\`, \\`cat\\`, \\`head\\`, \\`tail\\`, \\`sed\\`, \\`awk\\`, \\`echo\\`, \\`ls\\`, \\`dir\\`, or \\`tree\\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:\n - File search: Use ${TOOL_NAME_GLOB} (NOT find or ls)\n - Directory structure and information: use ${TOOL_NAME_READ} (NOT ls/dir/tree)\n - Content search: Use ${TOOL_NAME_GREP} (NOT grep or rg)\n - Symbol navigation: Use ${TOOL_NAME_LSP} (NOT ctags/gtags)\n - Read files: Use ${TOOL_NAME_READ} (NOT cat/head/tail)\n - Edit files: Use ${TOOL_NAME_EDIT} (NOT sed/awk)\n - Create directories/files for content writing: Use ${TOOL_NAME_WRITE} directly (NOT mkdir/touch first)\n - Write files: Use ${TOOL_NAME_WRITE} (NOT echo >/cat <<EOF)\n - Delete files: Use Delete (NOT rm/rmdir/del). Example: Delete({ file_paths: [\"/path/to/file\"] })\n - Communication: Output text directly (NOT echo/printf)\n - When issuing multiple commands:\n - If the commands are independent and can run in parallel, make multiple ${TOOL_NAME} tool calls in a single message. For example, if you need to run \"git status\" and \"git diff\", send a single message with two ${TOOL_NAME} tool calls in parallel.\n - If the commands depend on each other and must run sequentially, use a single ${TOOL_NAME} call with '&&' to chain them together (e.g., \\`git add . && git commit -m \"message\" && git push\\`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead.\n - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail\n - DO NOT use newlines to separate commands (newlines are ok in quoted strings)\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \\`cd\\`. You may use \\`cd\\` if the User explicitly requests it.\n <good-example>\n pytest /foo/bar/tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n${getBashGitPrompt()}`\n}\n", "import { ensureConfigScope } from './discovery'\n\nexport type McpCliTransport = 'stdio' | 'sse' | 'http'\n\nexport function looksLikeMcpUrl(value: string): boolean {\n const trimmed = value.trim()\n if (!trimmed) return false\n\n if (/^(https?|wss?):\\/\\//i.test(trimmed)) return true\n if (/^localhost(?::\\d+)?(\\/|$)/i.test(trimmed)) return true\n if (/^\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?(\\/|$)/.test(trimmed)) return true\n return trimmed.endsWith('/sse') || trimmed.endsWith('/mcp')\n}\n\nexport function parseMcpHeaders(\n raw: string[] | undefined,\n): Record<string, string> | undefined {\n if (!raw || raw.length === 0) return undefined\n const headers: Record<string, string> = {}\n for (const item of raw) {\n const idx = item.indexOf(':')\n if (idx === -1) {\n throw new Error(\n `Invalid header format: \"${item}\". Expected format: \"Header-Name: value\"`,\n )\n }\n const key = item.slice(0, idx).trim()\n const value = item.slice(idx + 1).trim()\n if (!key) {\n throw new Error(`Invalid header: \"${item}\". Header name cannot be empty.`)\n }\n headers[key] = value\n }\n return headers\n}\n\nexport function normalizeMcpScopeForCli(scope: string | undefined): {\n scope: ReturnType<typeof ensureConfigScope>\n display: string\n} {\n const raw = (scope ?? 'local').trim() || 'local'\n\n if (raw === 'local')\n return { scope: ensureConfigScope('project'), display: 'local' }\n if (raw === 'user')\n return { scope: ensureConfigScope('global'), display: 'user' }\n if (raw === 'project')\n return { scope: ensureConfigScope('mcpjson'), display: 'project' }\n\n if (raw === 'global')\n return { scope: ensureConfigScope('global'), display: 'user' }\n if (raw === 'projectConfig' || raw === 'project-config') {\n return { scope: ensureConfigScope('project'), display: 'local' }\n }\n\n return { scope: ensureConfigScope(raw), display: raw }\n}\n\nexport function normalizeMcpTransport(transport: string | undefined): {\n transport: McpCliTransport\n explicit: boolean\n} {\n if (!transport) return { transport: 'stdio', explicit: false }\n const normalized = transport.trim()\n if (normalized === 'stdio' || normalized === 'sse' || normalized === 'http') {\n return { transport: normalized, explicit: true }\n }\n throw new Error(\n `Invalid transport type: ${transport}. Must be one of: stdio, sse, http`,\n )\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,eAAe;AAExB,SAAS,cAAc;AACvB,S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O,EAAE,OAAO,kBAAkB,QAAQ,GAAG,SAAS,OAAO;AAC/D,MAAI,QAAQ;AACV,WAAO,EAAE,OAAO,kBAAkB,SAAS,GAAG,SAAS,UAAU;AAEnE,MAAI,QAAQ;AACV,WAAO,EAAE,OAAO,kBAAkB,QAAQ,GAAG,SAAS,OAAO;AAC/D,MAAI,QAAQ,mBAAmB,QAAQ,kBAAkB;AACvD,WAAO,EAAE,OAAO,kBAAkB,SAAS,GAAG,SAAS,QAAQ;AAAA,EACjE;AAEA,SAAO,EAAE,OAAO,kBAAkB,GAAG,GAAG,SAAS,IAAI;AACvD;AAEO,SAAS,sBAAsB,WAGpC;AACA,MAAI,CAAC,UAAW,QAAO,EAAE,WAAW,SAAS,UAAU,MAAM;AAC7D,QAAM,aAAa,UAAU,KAAK;AAClC,MAAI,eAAe,WAAW,eAAe,SAAS,eAAe,QAAQ;AAC3E,WAAO,EAAE,WAAW,YAAY,UAAU,KAAK;AAAA,EACjD;AACA,QAAM,IAAI;AAAA,IACR,2BAA2B,SAAS;AAAA,EACtC;AACF;",
6
6
  "names": ["existsSync", "readFileSync", "existsSync", "readFileSync", "memoize", "Box", "Text", "React", "Text", "React", "TOOL_NAME", "DESCRIPTION", "PROMPT", "TOOL_NAME", "DESCRIPTION", "TOOL_NAME", "DESCRIPTION", "PROMPT", "TOOL_NAME", "DESCRIPTION", "TOOL_NAME", "DESCRIPTION", "TOOL_NAME", "PROMPT", "DESCRIPTION", "TOOL_NAME", "TOOL_NAME", "Text", "Box", "Text", "lines", "memoize"]
7
7
  }