@within-7/minto 0.3.0 → 0.3.4

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 (84) hide show
  1. package/dist/commands/setup.js +40 -2
  2. package/dist/commands/setup.js.map +2 -2
  3. package/dist/components/SubagentProgress.js +10 -2
  4. package/dist/components/SubagentProgress.js.map +2 -2
  5. package/dist/constants/prompts.js +22 -1
  6. package/dist/constants/prompts.js.map +2 -2
  7. package/dist/entrypoints/cli.js +15 -9
  8. package/dist/entrypoints/cli.js.map +2 -2
  9. package/dist/permissions.js +121 -2
  10. package/dist/permissions.js.map +2 -2
  11. package/dist/screens/ResumeConversation.js +2 -0
  12. package/dist/screens/ResumeConversation.js.map +2 -2
  13. package/dist/services/taskStore.js +205 -0
  14. package/dist/services/taskStore.js.map +7 -0
  15. package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js +40 -3
  16. package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js.map +2 -2
  17. package/dist/tools/BashTool/BashTool.js +21 -4
  18. package/dist/tools/BashTool/BashTool.js.map +2 -2
  19. package/dist/tools/BashTool/prompt.js +6 -0
  20. package/dist/tools/BashTool/prompt.js.map +2 -2
  21. package/dist/tools/FileEditTool/FileEditTool.js +24 -9
  22. package/dist/tools/FileEditTool/FileEditTool.js.map +2 -2
  23. package/dist/tools/FileEditTool/prompt.js +4 -1
  24. package/dist/tools/FileEditTool/prompt.js.map +2 -2
  25. package/dist/tools/FileEditTool/utils.js +10 -4
  26. package/dist/tools/FileEditTool/utils.js.map +2 -2
  27. package/dist/tools/FileReadTool/FileReadTool.js +1 -1
  28. package/dist/tools/FileReadTool/FileReadTool.js.map +1 -1
  29. package/dist/tools/FileReadTool/prompt.js +16 -1
  30. package/dist/tools/FileReadTool/prompt.js.map +2 -2
  31. package/dist/tools/FileWriteTool/FileWriteTool.js +1 -1
  32. package/dist/tools/FileWriteTool/FileWriteTool.js.map +1 -1
  33. package/dist/tools/FileWriteTool/prompt.js +8 -1
  34. package/dist/tools/FileWriteTool/prompt.js.map +2 -2
  35. package/dist/tools/GlobTool/prompt.js +12 -1
  36. package/dist/tools/GlobTool/prompt.js.map +2 -2
  37. package/dist/tools/GrepTool/GrepTool.js +333 -65
  38. package/dist/tools/GrepTool/GrepTool.js.map +2 -2
  39. package/dist/tools/GrepTool/prompt.js +15 -8
  40. package/dist/tools/GrepTool/prompt.js.map +2 -2
  41. package/dist/tools/NotebookEditTool/NotebookEditTool.js +57 -45
  42. package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +2 -2
  43. package/dist/tools/NotebookEditTool/prompt.js +1 -1
  44. package/dist/tools/NotebookEditTool/prompt.js.map +1 -1
  45. package/dist/tools/TaskCreateTool/TaskCreateTool.js +102 -0
  46. package/dist/tools/TaskCreateTool/TaskCreateTool.js.map +7 -0
  47. package/dist/tools/TaskCreateTool/prompt.js +47 -0
  48. package/dist/tools/TaskCreateTool/prompt.js.map +7 -0
  49. package/dist/tools/TaskGetTool/TaskGetTool.js +115 -0
  50. package/dist/tools/TaskGetTool/TaskGetTool.js.map +7 -0
  51. package/dist/tools/TaskGetTool/prompt.js +28 -0
  52. package/dist/tools/TaskGetTool/prompt.js.map +7 -0
  53. package/dist/tools/TaskListTool/TaskListTool.js +102 -0
  54. package/dist/tools/TaskListTool/TaskListTool.js.map +7 -0
  55. package/dist/tools/TaskListTool/prompt.js +27 -0
  56. package/dist/tools/TaskListTool/prompt.js.map +7 -0
  57. package/dist/tools/TaskStopTool/TaskStopTool.js +150 -0
  58. package/dist/tools/TaskStopTool/TaskStopTool.js.map +7 -0
  59. package/dist/tools/TaskStopTool/prompt.js +15 -0
  60. package/dist/tools/TaskStopTool/prompt.js.map +7 -0
  61. package/dist/tools/TaskTool/TaskTool.js +41 -1
  62. package/dist/tools/TaskTool/TaskTool.js.map +2 -2
  63. package/dist/tools/TaskUpdateTool/TaskUpdateTool.js +134 -0
  64. package/dist/tools/TaskUpdateTool/TaskUpdateTool.js.map +7 -0
  65. package/dist/tools/TaskUpdateTool/prompt.js +81 -0
  66. package/dist/tools/TaskUpdateTool/prompt.js.map +7 -0
  67. package/dist/tools/URLFetcherTool/prompt.js +1 -1
  68. package/dist/tools/URLFetcherTool/prompt.js.map +1 -1
  69. package/dist/tools.js +12 -0
  70. package/dist/tools.js.map +2 -2
  71. package/dist/utils/config.js.map +2 -2
  72. package/dist/utils/model.js +15 -2
  73. package/dist/utils/model.js.map +2 -2
  74. package/dist/utils/ripgrep.js +53 -1
  75. package/dist/utils/ripgrep.js.map +2 -2
  76. package/dist/utils/teamConfig.js +160 -0
  77. package/dist/utils/teamConfig.js.map +3 -3
  78. package/dist/utils/terminal.js +12 -0
  79. package/dist/utils/terminal.js.map +2 -2
  80. package/dist/utils/tooling/safeRender.js +13 -14
  81. package/dist/utils/tooling/safeRender.js.map +2 -2
  82. package/dist/version.js +2 -2
  83. package/dist/version.js.map +1 -1
  84. package/package.json +20 -28
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/tools/BashTool/BashTool.tsx"],
4
- "sourcesContent": ["import { statSync } from 'fs'\nimport { EOL } from 'os'\nimport { isAbsolute, relative, resolve } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { PRODUCT_NAME } from '@constants/product'\nimport { queryQuick } from '@services/claude'\nimport { Tool, ValidationResult } from '@tool'\nimport { splitCommand } from '@utils/commands'\nimport { isInDirectory } from '@utils/file'\nimport { logError } from '@utils/log'\nimport {\n PersistentShell,\n type StreamingYield,\n type StreamingResult,\n} from '@utils/PersistentShell'\nimport { getCwd, getOriginalCwd } from '@utils/state'\nimport { getGlobalConfig } from '@utils/config'\nimport { getModelManager } from '@utils/model'\nimport { BackgroundShellManager } from '@utils/BackgroundShellManager'\nimport BashToolResultMessage from './BashToolResultMessage'\nimport {\n BANNED_COMMANDS,\n PROMPT,\n matchesDangerousPattern,\n detectDangerousPatterns,\n} from './prompt'\nimport { formatOutput, getCommandFilePaths } from './utils'\n\nexport const inputSchema = z.strictObject({\n command: z.string().describe('The command to execute'),\n timeout: z\n .number()\n .optional()\n .describe('Optional timeout in milliseconds (max 600000)'),\n run_in_background: z\n .boolean()\n .optional()\n .describe('Set to true to run this command in the background'),\n})\n\ntype In = typeof inputSchema\nexport type Out = {\n stdout: string\n stdoutLines: number // Total number of lines in original stdout, even if `stdout` is now truncated\n stderr: string\n stderrLines: number // Total number of lines in original stderr, even if `stderr` is now truncated\n interrupted: boolean\n shellId?: string // Present if run_in_background is true\n}\n\nexport const BashTool = {\n name: 'Bash',\n async description() {\n return 'Executes shell commands on your computer'\n },\n async prompt() {\n const config = getGlobalConfig()\n // \uD83D\uDD27 Fix: Use ModelManager to get actual current model\n const modelManager = getModelManager()\n const modelName =\n modelManager.getModelName('main') || '<No Model Configured>'\n // Substitute the placeholder in the static PROMPT string\n return PROMPT.replace(/{MODEL_NAME}/g, modelName)\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // BashTool modifies state/files, not safe for concurrent execution\n },\n inputSchema,\n userFacingName() {\n return 'Bash'\n },\n async isEnabled() {\n return true\n },\n needsPermissions(): boolean {\n // Always check per-project permissions for BashTool\n return true\n },\n async validateInput({ command }): Promise<ValidationResult> {\n // Detect dangerous patterns (critical only block, others warn)\n const dangerousPatterns = detectDangerousPatterns(command)\n const criticalPatterns = dangerousPatterns.filter(\n p => p.severity === 'critical',\n )\n\n if (criticalPatterns.length > 0) {\n const patternNames = criticalPatterns.map(p => p.name).join(', ')\n logError(\n `SECURITY: Critical dangerous patterns detected in command: ${patternNames}`,\n )\n return {\n result: false,\n message: `Command contains critical security risks: ${patternNames}. This command has been blocked for security reasons.`,\n }\n }\n\n // Log warnings for high-severity patterns (non-blocking)\n const highPatterns = dangerousPatterns.filter(p => p.severity === 'high')\n if (highPatterns.length > 0) {\n const patternNames = highPatterns.map(p => p.name).join(', ')\n logError(\n `SECURITY WARNING: High-severity patterns detected in command: ${patternNames}. User confirmation required.`,\n )\n }\n\n const commands = splitCommand(command)\n for (const cmd of commands) {\n const parts = cmd.split(' ')\n const baseCmd = parts[0]\n\n // Check if command is banned\n if (baseCmd && BANNED_COMMANDS.includes(baseCmd.toLowerCase())) {\n return {\n result: false,\n message: `Command '${baseCmd}' is not allowed for security reasons`,\n }\n }\n\n // Also check for commands that might be invoked with full path\n // e.g., /usr/bin/curl, /bin/rm\n if (baseCmd && (baseCmd.startsWith('/') || baseCmd.startsWith('./'))) {\n const cmdName = baseCmd.split('/').pop()?.toLowerCase()\n if (cmdName && BANNED_COMMANDS.includes(cmdName)) {\n return {\n result: false,\n message: `Command '${cmdName}' is not allowed for security reasons (full path: ${baseCmd})`,\n }\n }\n }\n\n // Special handling for cd command\n if (baseCmd === 'cd' && parts[1]) {\n const targetDir = parts[1]!.replace(/^['\"]|['\"]$/g, '') // Remove quotes if present\n const fullTargetDir = isAbsolute(targetDir)\n ? targetDir\n : resolve(getCwd(), targetDir)\n if (\n !isInDirectory(\n relative(getOriginalCwd(), fullTargetDir),\n relative(getCwd(), getOriginalCwd()),\n )\n ) {\n return {\n result: false,\n message: `ERROR: cd to '${fullTargetDir}' was blocked. For security, ${PRODUCT_NAME} may only change directories to child directories of the original working directory (${getOriginalCwd()}) for this session.`,\n }\n }\n }\n }\n\n return { result: true }\n },\n renderToolUseMessage({ command }) {\n // Clean up any command that uses the quoted HEREDOC pattern\n if (command.includes(\"\\\"$(cat <<'EOF'\")) {\n const match = command.match(\n /^(.*?)\"?\\$\\(cat <<'EOF'\\n([\\s\\S]*?)\\n\\s*EOF\\n\\s*\\)\"(.*)$/,\n )\n if (match && match[1] && match[2]) {\n const prefix = match[1]\n const content = match[2]\n const suffix = match[3] || ''\n return `${prefix.trim()} \"${content.trim()}\"${suffix.trim()}`\n }\n }\n return command\n },\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n\n renderToolResultMessage(content) {\n return <BashToolResultMessage content={content} verbose={false} />\n },\n renderResultForAssistant({ interrupted, stdout, stderr }) {\n let errorMessage = stderr.trim()\n if (interrupted) {\n if (stderr) errorMessage += EOL\n errorMessage += '<error>Command was aborted before completion</error>'\n }\n const hasBoth = stdout.trim() && errorMessage\n return `${stdout.trim()}${hasBoth ? '\\n' : ''}${errorMessage.trim()}`\n },\n async *call(\n { command, timeout = 120000, run_in_background = false },\n { abortController, readFileTimestamps },\n ) {\n // Handle background execution\n if (run_in_background) {\n const shellId = BackgroundShellManager.getInstance().create(\n command,\n getCwd(),\n )\n\n const data: Out = {\n stdout: `Background shell started with ID: ${shellId}`,\n stdoutLines: 1,\n stderr: '',\n stderrLines: 0,\n interrupted: false,\n shellId,\n }\n\n yield {\n type: 'result',\n resultForAssistant: `Started background shell: ${shellId}\\nCommand: ${command}`,\n data,\n }\n return\n }\n\n let stdout = ''\n let stderr = ''\n\n // \uD83D\uDD27 CRITICAL FIX: Track whether this tool invocation has completed\n // to prevent async callbacks from accessing stale context\n let isCompleted = false\n\n // \uD83D\uDD27 Check if already cancelled before starting execution\n if (abortController.signal.aborted) {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: 'Command cancelled before execution',\n stderrLines: 1,\n interrupted: true,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n return\n }\n\n try {\n // Execute commands with streaming output\n let result: StreamingResult | null = null\n let streamedStdout = ''\n let streamedStderr = ''\n\n // Use streaming execution for real-time output\n const streamingGenerator = PersistentShell.getInstance().execStreaming(\n command,\n abortController.signal,\n timeout,\n )\n\n for await (const chunk of streamingGenerator) {\n if (chunk.type === 'chunk') {\n // Accumulate streamed output\n if (chunk.stdout) {\n streamedStdout += chunk.stdout\n }\n if (chunk.stderr) {\n streamedStderr += chunk.stderr\n }\n\n // Yield progress update for real-time UI feedback\n // Use StreamingProgressContent format for proper rendering\n yield {\n type: 'progress',\n content: {\n type: 'streaming',\n toolName: 'Bash',\n stdout: streamedStdout,\n stderr: streamedStderr,\n isStreaming: true,\n },\n }\n } else if (chunk.type === 'result') {\n // Final result\n result = chunk\n }\n }\n\n // Use the final result (or construct from streamed data)\n if (!result) {\n result = {\n type: 'result',\n stdout: streamedStdout,\n stderr: streamedStderr,\n code: 0,\n interrupted: false,\n }\n }\n\n stdout += (result.stdout || '').trim() + EOL\n stderr += (result.stderr || '').trim() + EOL\n if (result.code !== 0) {\n stderr += `Exit code ${result.code}`\n }\n\n if (!isInDirectory(getCwd(), getOriginalCwd())) {\n // Shell directory is outside original working directory, reset it\n await PersistentShell.getInstance().setCwd(getOriginalCwd())\n stderr = `${stderr.trim()}${EOL}Shell cwd was reset to ${getOriginalCwd()}`\n }\n\n // Update read timestamps for any files referenced by the command\n // Don't block the main thread!\n // Skip this in tests because it makes fixtures non-deterministic (they might not always get written),\n // so will be missing in CI.\n if (process.env.NODE_ENV !== 'test') {\n getCommandFilePaths(command, stdout).then(filePaths => {\n // \uD83D\uDD27 CRITICAL FIX: Check if tool invocation has already completed\n // to prevent accessing potentially stale context\n if (isCompleted) {\n return // Tool has finished, don't access readFileTimestamps\n }\n\n for (const filePath of filePaths) {\n const fullFilePath = isAbsolute(filePath)\n ? filePath\n : resolve(getCwd(), filePath)\n\n // Try/catch in case the file doesn't exist (because Haiku didn't properly extract it)\n try {\n readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs\n } catch (e) {\n logError(e)\n }\n }\n })\n }\n\n const { totalLines: stdoutLines, truncatedContent: stdoutContent } =\n formatOutput(stdout.trim())\n const { totalLines: stderrLines, truncatedContent: stderrContent } =\n formatOutput(stderr.trim())\n\n const data: Out = {\n stdout: stdoutContent,\n stdoutLines,\n stderr: stderrContent,\n stderrLines,\n interrupted: result.interrupted,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n } catch (error) {\n // \uD83D\uDD27 Handle cancellation or other errors properly\n const isAborted = abortController.signal.aborted\n const errorMessage = isAborted\n ? 'Command was cancelled by user'\n : `Command failed: ${error instanceof Error ? error.message : String(error)}`\n\n const data: Out = {\n stdout: stdout.trim(),\n stdoutLines: stdout.split('\\n').length,\n stderr: errorMessage,\n stderrLines: 1,\n interrupted: isAborted,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n } finally {\n // \uD83D\uDD27 CRITICAL FIX: Mark tool invocation as completed\n // This prevents async callbacks (like getCommandFilePaths) from\n // accessing potentially stale context after this tool returns\n isCompleted = true\n }\n },\n} satisfies Tool<In, Out>\n"],
5
- "mappings": "AAAA,SAAS,gBAAgB;AACzB,SAAS,WAAW;AACpB,SAAS,YAAY,UAAU,eAAe;AAC9C,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAG7B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,OAGK;AACP,SAAS,QAAQ,sBAAsB;AACvC,SAAS,uBAAuB;AAChC,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,OAAO,2BAA2B;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,cAAc,2BAA2B;AAE3C,MAAM,cAAc,EAAE,aAAa;AAAA,EACxC,SAAS,EAAE,OAAO,EAAE,SAAS,wBAAwB;AAAA,EACrD,SAAS,EACN,OAAO,EACP,SAAS,EACT,SAAS,+CAA+C;AAAA,EAC3D,mBAAmB,EAChB,QAAQ,EACR,SAAS,EACT,SAAS,mDAAmD;AACjE,CAAC;AAYM,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,MAAM,cAAc;AAClB,WAAO;AAAA,EACT;AAAA,EACA,MAAM,SAAS;AACb,UAAM,SAAS,gBAAgB;AAE/B,UAAM,eAAe,gBAAgB;AACrC,UAAM,YACJ,aAAa,aAAa,MAAM,KAAK;AAEvC,WAAO,OAAO,Q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AAY,aAAa,kBAAkB,cAAc,IAC/D,aAAa,OAAO,KAAK,CAAC;AAC5B,YAAM,EAAE,YAAY,aAAa,kBAAkB,cAAc,IAC/D,aAAa,OAAO,KAAK,CAAC;AAE5B,YAAM,OAAY;AAAA,QAChB,QAAQ;AAAA,QACR;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA,aAAa,OAAO;AAAA,MACtB;AAEA,YAAM;AAAA,QACJ,MAAM;AAAA,QACN,oBAAoB,KAAK,yBAAyB,IAAI;AAAA,QACtD;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AAEd,YAAM,YAAY,gBAAgB,OAAO;AACzC,YAAM,eAAe,YACjB,kCACA,mBAAmB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAE7E,YAAM,OAAY;AAAA,QAChB,QAAQ,OAAO,KAAK;AAAA,QACpB,aAAa,OAAO,MAAM,IAAI,EAAE;AAAA,QAChC,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,aAAa;AAAA,MACf;AAEA,YAAM;AAAA,QACJ,MAAM;AAAA,QACN,oBAAoB,KAAK,yBAAyB,IAAI;AAAA,QACtD;AAAA,MACF;AAAA,IACF,UAAE;AAIA,oBAAc;AAAA,IAChB;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { statSync } from 'fs'\nimport { EOL } from 'os'\nimport { isAbsolute, relative, resolve } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { PRODUCT_NAME } from '@constants/product'\nimport { queryQuick } from '@services/claude'\nimport { Tool, ValidationResult } from '@tool'\nimport { splitCommand } from '@utils/commands'\nimport { isInDirectory } from '@utils/file'\nimport { logError } from '@utils/log'\nimport {\n PersistentShell,\n type StreamingYield,\n type StreamingResult,\n} from '@utils/PersistentShell'\nimport { getCwd, getOriginalCwd } from '@utils/state'\nimport { getGlobalConfig } from '@utils/config'\nimport { getModelManager } from '@utils/model'\nimport { BackgroundShellManager } from '@utils/BackgroundShellManager'\nimport BashToolResultMessage from './BashToolResultMessage'\nimport {\n BANNED_COMMANDS,\n PROMPT,\n matchesDangerousPattern,\n detectDangerousPatterns,\n} from './prompt'\nimport { formatOutput, getCommandFilePaths } from './utils'\n\nexport const inputSchema = z.strictObject({\n command: z.string().describe('The command to execute'),\n timeout: z\n .number()\n .optional()\n .describe('Optional timeout in milliseconds (max 600000)'),\n run_in_background: z\n .boolean()\n .optional()\n .describe('Set to true to run this command in the background'),\n description: z\n .string()\n .optional()\n .describe(\n `Clear, concise description of what this command does in active voice. Never use words like \"complex\" or \"risk\" in the description - just describe what it does.\n\nFor simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):\n- ls \u2192 \"List files in current directory\"\n- git status \u2192 \"Show working tree status\"\n- npm install \u2192 \"Install package dependencies\"\n\nFor commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does:\n- find . -name \"*.tmp\" -exec rm {} \\\\; \u2192 \"Find and delete all .tmp files recursively\"\n- git reset --hard origin/main \u2192 \"Discard all local changes and match remote main\"\n- curl -s url | jq '.data[]' \u2192 \"Fetch JSON from URL and extract data array elements\"`,\n ),\n})\n\ntype In = typeof inputSchema\nexport type Out = {\n stdout: string\n stdoutLines: number // Total number of lines in original stdout, even if `stdout` is now truncated\n stderr: string\n stderrLines: number // Total number of lines in original stderr, even if `stderr` is now truncated\n interrupted: boolean\n shellId?: string // Present if run_in_background is true\n}\n\nexport const BashTool = {\n name: 'Bash',\n async description() {\n return 'Executes shell commands on your computer'\n },\n async prompt() {\n const config = getGlobalConfig()\n // \uD83D\uDD27 Fix: Use ModelManager to get actual current model\n const modelManager = getModelManager()\n const modelName =\n modelManager.getModelName('main') || '<No Model Configured>'\n // Substitute the placeholder in the static PROMPT string\n return PROMPT.replace(/{MODEL_NAME}/g, modelName)\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // BashTool modifies state/files, not safe for concurrent execution\n },\n inputSchema,\n userFacingName() {\n return 'Bash'\n },\n async isEnabled() {\n return true\n },\n needsPermissions(): boolean {\n // Always check per-project permissions for BashTool\n return true\n },\n async validateInput({ command }): Promise<ValidationResult> {\n // Detect dangerous patterns (critical only block, others warn)\n const dangerousPatterns = detectDangerousPatterns(command)\n const criticalPatterns = dangerousPatterns.filter(\n p => p.severity === 'critical',\n )\n\n if (criticalPatterns.length > 0) {\n const patternNames = criticalPatterns.map(p => p.name).join(', ')\n logError(\n `SECURITY: Critical dangerous patterns detected in command: ${patternNames}`,\n )\n return {\n result: false,\n message: `Command contains critical security risks: ${patternNames}. This command has been blocked for security reasons.`,\n }\n }\n\n // Log warnings for high-severity patterns (non-blocking)\n const highPatterns = dangerousPatterns.filter(p => p.severity === 'high')\n if (highPatterns.length > 0) {\n const patternNames = highPatterns.map(p => p.name).join(', ')\n logError(\n `SECURITY WARNING: High-severity patterns detected in command: ${patternNames}. User confirmation required.`,\n )\n }\n\n const commands = splitCommand(command)\n for (const cmd of commands) {\n const parts = cmd.split(' ')\n const baseCmd = parts[0]\n\n // Check if command is banned\n if (baseCmd && BANNED_COMMANDS.includes(baseCmd.toLowerCase())) {\n return {\n result: false,\n message: `Command '${baseCmd}' is not allowed for security reasons`,\n }\n }\n\n // Also check for commands that might be invoked with full path\n // e.g., /usr/bin/curl, /bin/rm\n if (baseCmd && (baseCmd.startsWith('/') || baseCmd.startsWith('./'))) {\n const cmdName = baseCmd.split('/').pop()?.toLowerCase()\n if (cmdName && BANNED_COMMANDS.includes(cmdName)) {\n return {\n result: false,\n message: `Command '${cmdName}' is not allowed for security reasons (full path: ${baseCmd})`,\n }\n }\n }\n\n // Special handling for cd command\n if (baseCmd === 'cd' && parts[1]) {\n const targetDir = parts[1]!.replace(/^['\"]|['\"]$/g, '') // Remove quotes if present\n const fullTargetDir = isAbsolute(targetDir)\n ? targetDir\n : resolve(getCwd(), targetDir)\n if (\n !isInDirectory(\n relative(getOriginalCwd(), fullTargetDir),\n relative(getCwd(), getOriginalCwd()),\n )\n ) {\n return {\n result: false,\n message: `ERROR: cd to '${fullTargetDir}' was blocked. For security, ${PRODUCT_NAME} may only change directories to child directories of the original working directory (${getOriginalCwd()}) for this session.`,\n }\n }\n }\n }\n\n return { result: true }\n },\n renderToolUseMessage({ command, description }) {\n // Clean up any command that uses the quoted HEREDOC pattern\n let displayCommand = command\n if (command.includes(\"\\\"$(cat <<'EOF'\")) {\n const match = command.match(\n /^(.*?)\"?\\$\\(cat <<'EOF'\\n([\\s\\S]*?)\\n\\s*EOF\\n\\s*\\)\"(.*)$/,\n )\n if (match && match[1] && match[2]) {\n const prefix = match[1]\n const content = match[2]\n const suffix = match[3] || ''\n displayCommand = `${prefix.trim()} \"${content.trim()}\"${suffix.trim()}`\n }\n }\n\n // If description is provided, show it instead of (or alongside) the command\n if (description) {\n return description\n }\n\n return displayCommand\n },\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n\n renderToolResultMessage(content) {\n return <BashToolResultMessage content={content} verbose={false} />\n },\n renderResultForAssistant({ interrupted, stdout, stderr }) {\n let errorMessage = stderr.trim()\n if (interrupted) {\n if (stderr) errorMessage += EOL\n errorMessage += '<error>Command was aborted before completion</error>'\n }\n const hasBoth = stdout.trim() && errorMessage\n return `${stdout.trim()}${hasBoth ? '\\n' : ''}${errorMessage.trim()}`\n },\n async *call(\n { command, timeout = 120000, run_in_background = false },\n { abortController, readFileTimestamps },\n ) {\n // Handle background execution\n if (run_in_background) {\n const shellId = BackgroundShellManager.getInstance().create(\n command,\n getCwd(),\n )\n\n const data: Out = {\n stdout: `Background shell started with ID: ${shellId}`,\n stdoutLines: 1,\n stderr: '',\n stderrLines: 0,\n interrupted: false,\n shellId,\n }\n\n yield {\n type: 'result',\n resultForAssistant: `Started background shell: ${shellId}\\nCommand: ${command}`,\n data,\n }\n return\n }\n\n let stdout = ''\n let stderr = ''\n\n // \uD83D\uDD27 CRITICAL FIX: Track whether this tool invocation has completed\n // to prevent async callbacks from accessing stale context\n let isCompleted = false\n\n // \uD83D\uDD27 Check if already cancelled before starting execution\n if (abortController.signal.aborted) {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: 'Command cancelled before execution',\n stderrLines: 1,\n interrupted: true,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n return\n }\n\n try {\n // Execute commands with streaming output\n let result: StreamingResult | null = null\n let streamedStdout = ''\n let streamedStderr = ''\n\n // Use streaming execution for real-time output\n const streamingGenerator = PersistentShell.getInstance().execStreaming(\n command,\n abortController.signal,\n timeout,\n )\n\n for await (const chunk of streamingGenerator) {\n if (chunk.type === 'chunk') {\n // Accumulate streamed output\n if (chunk.stdout) {\n streamedStdout += chunk.stdout\n }\n if (chunk.stderr) {\n streamedStderr += chunk.stderr\n }\n\n // Yield progress update for real-time UI feedback\n // Use StreamingProgressContent format for proper rendering\n yield {\n type: 'progress',\n content: {\n type: 'streaming',\n toolName: 'Bash',\n stdout: streamedStdout,\n stderr: streamedStderr,\n isStreaming: true,\n },\n }\n } else if (chunk.type === 'result') {\n // Final result\n result = chunk\n }\n }\n\n // Use the final result (or construct from streamed data)\n if (!result) {\n result = {\n type: 'result',\n stdout: streamedStdout,\n stderr: streamedStderr,\n code: 0,\n interrupted: false,\n }\n }\n\n stdout += (result.stdout || '').trim() + EOL\n stderr += (result.stderr || '').trim() + EOL\n if (result.code !== 0) {\n stderr += `Exit code ${result.code}`\n }\n\n if (!isInDirectory(getCwd(), getOriginalCwd())) {\n // Shell directory is outside original working directory, reset it\n await PersistentShell.getInstance().setCwd(getOriginalCwd())\n stderr = `${stderr.trim()}${EOL}Shell cwd was reset to ${getOriginalCwd()}`\n }\n\n // Update read timestamps for any files referenced by the command\n // Don't block the main thread!\n // Skip this in tests because it makes fixtures non-deterministic (they might not always get written),\n // so will be missing in CI.\n if (process.env.NODE_ENV !== 'test') {\n getCommandFilePaths(command, stdout).then(filePaths => {\n // \uD83D\uDD27 CRITICAL FIX: Check if tool invocation has already completed\n // to prevent accessing potentially stale context\n if (isCompleted) {\n return // Tool has finished, don't access readFileTimestamps\n }\n\n for (const filePath of filePaths) {\n const fullFilePath = isAbsolute(filePath)\n ? filePath\n : resolve(getCwd(), filePath)\n\n // Try/catch in case the file doesn't exist (because Haiku didn't properly extract it)\n try {\n readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs\n } catch (e) {\n logError(e)\n }\n }\n })\n }\n\n const { totalLines: stdoutLines, truncatedContent: stdoutContent } =\n formatOutput(stdout.trim())\n const { totalLines: stderrLines, truncatedContent: stderrContent } =\n formatOutput(stderr.trim())\n\n const data: Out = {\n stdout: stdoutContent,\n stdoutLines,\n stderr: stderrContent,\n stderrLines,\n interrupted: result.interrupted,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n } catch (error) {\n // \uD83D\uDD27 Handle cancellation or other errors properly\n const isAborted = abortController.signal.aborted\n const errorMessage = isAborted\n ? 'Command was cancelled by user'\n : `Command failed: ${error instanceof Error ? error.message : String(error)}`\n\n const data: Out = {\n stdout: stdout.trim(),\n stdoutLines: stdout.split('\\n').length,\n stderr: errorMessage,\n stderrLines: 1,\n interrupted: isAborted,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(data),\n data,\n }\n } finally {\n // \uD83D\uDD27 CRITICAL FIX: Mark tool invocation as completed\n // This prevents async callbacks (like getCommandFilePaths) from\n // accessing potentially stale context after this tool returns\n isCompleted = true\n }\n },\n} satisfies Tool<In, Out>\n"],
5
+ "mappings": "AAAA,SAAS,gBAAgB;AACzB,SAAS,WAAW;AACpB,SAAS,YAAY,UAAU,eAAe;AAC9C,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAG7B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,OAGK;AACP,SAAS,QA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AAmB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAE7E,YAAM,OAAY;AAAA,QAChB,QAAQ,OAAO,KAAK;AAAA,QACpB,aAAa,OAAO,MAAM,IAAI,EAAE;AAAA,QAChC,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,aAAa;AAAA,MACf;AAEA,YAAM;AAAA,QACJ,MAAM;AAAA,QACN,oBAAoB,KAAK,yBAAyB,IAAI;AAAA,QACtD;AAAA,MACF;AAAA,IACF,UAAE;AAIA,oBAAc;AAAA,IAChB;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -369,6 +369,12 @@ Before executing the command, please follow these steps:
369
369
  - Verify that the command is not one of the banned commands: ${BANNED_COMMANDS.join(", ")}.
370
370
 
371
371
  3. Command Execution:
372
+ - Always quote file paths that contain spaces with double quotes (e.g., cd "path with spaces/file.txt")
373
+ - Examples of proper quoting:
374
+ - cd "/Users/name/My Documents" (correct)
375
+ - cd /Users/name/My Documents (incorrect - will fail)
376
+ - python "/path/with spaces/script.py" (correct)
377
+ - python /path/with spaces/script.py (incorrect - will fail)
372
378
  - After ensuring proper quoting, execute the command.
373
379
  - Capture the output of the command.
374
380
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/tools/BashTool/prompt.ts"],
4
- "sourcesContent": ["import { PRODUCT_NAME, PRODUCT_URL } from '@constants/product'\nimport { TOOL_NAME as TASK_TOOL_NAME } from '@tools/TaskTool/constants'\nimport { FileReadTool } from '@tools/FileReadTool/FileReadTool'\nimport { TOOL_NAME_FOR_PROMPT as GLOB_TOOL_NAME } from '@tools/GlobTool/prompt'\nimport { TOOL_NAME_FOR_PROMPT as GREP_TOOL_NAME } from '@tools/GrepTool/prompt'\nimport { LSTool } from '@tools/lsTool/lsTool'\n\nexport const MAX_OUTPUT_LENGTH = 30000\nexport const MAX_RENDERED_LINES = 5\n\n/**\n * Banned commands for security\n *\n * Categories:\n * - Network tools: Could be used for data exfiltration or network attacks\n * - System modification: Could damage the system or escalate privileges\n * - Shell execution: Could bypass command restrictions\n * - Browsers: Could open external content\n * - Dangerous file operations: Could cause data loss\n */\nexport const BANNED_COMMANDS = [\n // Network tools - data exfiltration risk\n 'curl',\n 'curlie',\n 'wget',\n 'axel',\n 'aria2c',\n 'nc',\n 'netcat',\n 'ncat',\n 'telnet',\n 'lynx',\n 'w3m',\n 'links',\n 'httpie',\n 'xh',\n 'http-prompt',\n 'ftp',\n 'sftp',\n 'scp',\n 'rsync',\n 'socat',\n 'nmap',\n 'tcpdump',\n 'wireshark',\n 'tshark',\n\n // Browsers - could open external content\n 'chrome',\n 'chromium',\n 'firefox',\n 'safari',\n 'opera',\n 'brave',\n 'open', // macOS open command could launch apps/URLs\n\n // Privilege escalation - dangerous system access\n 'sudo',\n 'su',\n 'doas',\n 'pkexec',\n 'gksudo',\n 'kdesudo',\n\n // Shell execution - could bypass restrictions\n 'eval',\n 'source',\n 'exec',\n 'bash',\n 'sh',\n 'zsh',\n 'fish',\n 'csh',\n 'tcsh',\n 'ksh',\n 'dash',\n 'ash',\n 'xargs', // Can execute arbitrary commands\n 'parallel', // GNU parallel can execute commands\n 'xonsh',\n 'powershell',\n 'pwsh',\n 'cmd',\n\n // Dangerous file operations - data loss risk\n 'rm',\n 'rmdir',\n 'shred',\n 'srm',\n 'wipe',\n 'dd', // Can overwrite disks\n 'mkfs', // Can format disks\n 'fdisk',\n 'parted',\n 'wipefs',\n\n // System modification - could damage system\n 'chmod',\n 'chown',\n 'chgrp',\n 'chattr',\n 'setfacl',\n 'shutdown',\n 'reboot',\n 'poweroff',\n 'halt',\n 'init',\n 'systemctl',\n 'service',\n 'launchctl', // macOS service control\n\n // Process control - could affect system stability\n 'kill',\n 'killall',\n 'pkill',\n\n // Aliases and functions - could hide malicious commands\n 'alias',\n 'unalias',\n 'function',\n\n // Cron/scheduling - persistent access\n 'crontab',\n 'at',\n 'atq',\n 'atrm',\n\n // User management - privilege escalation\n 'useradd',\n 'userdel',\n 'usermod',\n 'groupadd',\n 'groupdel',\n 'groupmod',\n 'passwd',\n 'chpasswd',\n\n // Package managers - could install malware\n 'apt',\n 'apt-get',\n 'aptitude',\n 'dpkg',\n 'yum',\n 'dnf',\n 'rpm',\n 'pacman',\n 'brew',\n 'port', // MacPorts\n 'pip',\n 'pip3',\n 'npm',\n 'yarn',\n 'pnpm',\n 'gem',\n 'cargo',\n 'go', // go install could install packages\n\n // Compilers/interpreters with execution capability\n 'python',\n 'python3',\n 'python2',\n 'ruby',\n 'perl',\n 'php',\n 'node',\n 'deno',\n 'bun',\n 'lua',\n 'awk',\n 'gawk',\n 'mawk',\n 'nawk',\n 'sed', // Can execute commands with e flag\n\n // Container/VM - could escape sandbox\n 'docker',\n 'podman',\n 'kubectl',\n 'vagrant',\n 'virsh',\n 'qemu',\n 'virtualbox',\n 'vboxmanage',\n\n // System info that could aid attacks\n 'env', // Exposes environment variables including secrets\n\n // Encryption/keys - could exfiltrate secrets\n 'gpg',\n 'openssl',\n 'ssh-keygen',\n 'ssh-agent',\n 'ssh-add',\n]\n\n/**\n * Detailed dangerous pattern match information\n */\nexport interface DangerousPatternMatch {\n pattern: string\n name: string\n match: string\n severity: 'critical' | 'high' | 'medium'\n}\n\n/**\n * Mapping of dangerous patterns with metadata\n */\nconst DANGEROUS_PATTERN_METADATA: Array<{\n pattern: RegExp\n name: string\n severity: 'critical' | 'high' | 'medium'\n}> = [\n // CRITICAL: Command Injection & Execution Bypass\n {\n pattern: /\\$\\([^)]+\\)/,\n name: 'command substitution $(...)',\n severity: 'critical',\n },\n {\n pattern: /`[^`]+`/,\n name: 'backtick command substitution',\n severity: 'critical',\n },\n {\n pattern: /;\\s*(rm|chmod|chown|dd|mkfs)\\b/i,\n name: 'chained destructive command',\n severity: 'critical',\n },\n {\n pattern: /&&\\s*(rm|chmod|chown|dd|mkfs)\\b/i,\n name: 'conditional destructive command',\n severity: 'critical',\n },\n {\n pattern: /\\|\\s*bash\\b/i,\n name: 'pipe to bash',\n severity: 'critical',\n },\n {\n pattern: /\\|\\s*sh\\b/i,\n name: 'pipe to sh',\n severity: 'critical',\n },\n {\n pattern: /curl.*\\|\\s*(bash|sh)\\b/i,\n name: 'curl pipe to shell',\n severity: 'critical',\n },\n {\n pattern: /wget.*\\|\\s*(bash|sh)\\b/i,\n name: 'wget pipe to shell',\n severity: 'critical',\n },\n {\n pattern: /eval\\s+['\"$]/,\n name: 'eval with dynamic input',\n severity: 'critical',\n },\n\n // CRITICAL: Destructive Operations\n {\n pattern: /\\brm\\s+-rf\\s+\\/(?!\\S)/,\n name: 'rm -rf /',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/dev\\/sd[a-z]/i,\n name: 'write to block device',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/dev\\/nvme/i,\n name: 'write to NVMe device',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/etc\\/(passwd|shadow|sudoers)/i,\n name: 'overwrite critical system files',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/boot\\//i,\n name: 'overwrite boot files',\n severity: 'critical',\n },\n\n // CRITICAL: Fork Bomb & DoS\n {\n pattern: /:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;?\\s*:/,\n name: 'fork bomb pattern ()',\n severity: 'critical',\n },\n {\n pattern: /\\.\\s*\\(\\)\\s*\\{\\s*\\.\\s*\\|\\s*\\.\\s*&\\s*\\}\\s*;?\\s*\\./,\n name: 'fork bomb pattern (.)',\n severity: 'critical',\n },\n\n // HIGH: Reverse Shell & Data Exfiltration\n {\n pattern: /\\$\\(\\s*<\\s*\\/dev\\/tcp/i,\n name: 'TCP socket connection',\n severity: 'high',\n },\n {\n pattern: /\\/dev\\/tcp\\//i,\n name: 'direct TCP device access',\n severity: 'high',\n },\n {\n pattern: /\\/dev\\/udp\\//i,\n name: 'direct UDP device access',\n severity: 'high',\n },\n {\n pattern: /mkfifo.*nc/i,\n name: 'named pipe with netcat',\n severity: 'high',\n },\n {\n pattern: /bash\\s+-i\\s+>&\\s*\\/dev\\/tcp/i,\n name: 'interactive bash reverse shell',\n severity: 'high',\n },\n\n // HIGH: Data Encoding & Obfuscation\n {\n pattern: /base64\\s+(-d|--decode).*\\|\\s*(bash|sh|eval)/i,\n name: 'base64 decode and execute',\n severity: 'high',\n },\n {\n pattern: /xxd\\s+-r.*\\|\\s*(bash|sh|eval)/i,\n name: 'hex decode and execute',\n severity: 'high',\n },\n\n // HIGH: System & Security Manipulation\n {\n pattern: /HISTFILE=/i,\n name: 'history file manipulation',\n severity: 'high',\n },\n {\n pattern: /unset\\s+HISTFILE/i,\n name: 'disable command history',\n severity: 'high',\n },\n {\n pattern: /history\\s+-c/i,\n name: 'clear command history',\n severity: 'high',\n },\n {\n pattern: /LD_PRELOAD=/i,\n name: 'library preload injection',\n severity: 'high',\n },\n {\n pattern: /LD_LIBRARY_PATH=/i,\n name: 'library path injection',\n severity: 'high',\n },\n {\n pattern: /DYLD_INSERT_LIBRARIES=/i,\n name: 'macOS library injection',\n severity: 'high',\n },\n\n // MEDIUM: Suspicious Command Patterns\n {\n pattern: /\\$\\{[^}]*\\}/,\n name: 'variable expansion',\n severity: 'medium',\n },\n]\n\n/**\n * Check if a command matches any dangerous pattern and return detailed information\n */\nexport function detectDangerousPatterns(\n command: string,\n): DangerousPatternMatch[] {\n const matches: DangerousPatternMatch[] = []\n\n for (const { pattern, name, severity } of DANGEROUS_PATTERN_METADATA) {\n const match = command.match(pattern)\n if (match) {\n matches.push({\n pattern: pattern.toString(),\n name,\n match: match[0],\n severity,\n })\n }\n }\n\n return matches\n}\n\n/**\n * Check if a command matches any dangerous pattern (backward compatible)\n */\nexport function matchesDangerousPattern(command: string): boolean {\n const criticalMatches = detectDangerousPatterns(command).filter(\n m => m.severity === 'critical',\n )\n return criticalMatches.length > 0\n}\n\nexport const PROMPT = `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\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 LS tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use LS to check that \"foo\" exists and is the intended parent directory\n\n2. Security Check:\n - For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User.\n - Verify that the command is not one of the banned commands: ${BANNED_COMMANDS.join(', ')}.\n\n3. Command Execution:\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\n4. Output Processing:\n - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.\n - Prepare the output for display to the user.\n\n5. Return Result:\n - Provide the processed output of the command.\n - If any errors occurred during execution, include those in the output.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.\n - You can set run_in_background to true to run the command in the background. This is useful for long-running processes like dev servers, build watches, or monitoring tasks. When running in background, you will receive a shell_id that can be used with BashOutputTool and KillShellTool to monitor and manage the task.\n - VERY IMPORTANT: You MUST avoid using search commands like \\`find\\` and \\`grep\\`. Instead use ${GREP_TOOL_NAME}, ${GLOB_TOOL_NAME}, or ${TASK_TOOL_NAME} to search. You MUST avoid read tools like \\`cat\\`, \\`head\\`, \\`tail\\`, and \\`ls\\`, and use ${FileReadTool.name} and ${LSTool.name} to read files.\n - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).\n - IMPORTANT: All commands share the same shell session. Shell state (environment variables, virtual environments, current directory, etc.) persist between commands. For example, if you set an environment variable as part of a command, the environment variable will persist for subsequent commands.\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# Committing changes with git\n\nWhen the user asks you to create a new git commit, follow these steps carefully:\n\n1. Start with a single message that contains exactly three tool_use blocks that do the following (it is VERY IMPORTANT that you send these tool_use blocks in a single message, otherwise it will feel slow to the user!):\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.\n\n2. Use the git context at the start of this conversation to determine which files are relevant to your commit. Add relevant untracked files to the staging area. Do not commit files that were already modified at the start of this conversation, if they are not relevant to your commit.\n\n3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:\n\n<commit_analysis>\n- List the files that have been changed or added\n- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)\n- Brainstorm the purpose or motivation behind these changes\n- Do not use tools to explore code, beyond what is available in the git context\n- Assess the impact of these changes on the overall project\n- Check for any sensitive information that shouldn't be committed\n- Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n- Ensure your language is clear, concise, and to the point\n- 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- Ensure the message is not generic (avoid words like \"Update\" or \"Fix\" without context)\n- Review the draft message to ensure it accurately reflects the changes and their purpose\n</commit_analysis>\n\n4. Create the commit with a message ending with:\n\uD83E\uDD16 Generated with ${PRODUCT_NAME} & {MODEL_NAME}\nCo-Authored-By: ${PRODUCT_NAME} <noreply@${PRODUCT_NAME}.com>\n\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.\n\n \uD83E\uDD16 Generated with ${PRODUCT_NAME} & {MODEL_NAME}\n Co-Authored-By: ${PRODUCT_NAME} <noreply@${PRODUCT_NAME}.com>\n EOF\n )\"\n</example>\n\n5. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.\n\n6. Finally, run git status to make sure the commit succeeded.\n\nImportant notes:\n- When possible, combine the \"git add\" and \"git commit\" commands into a single \"git commit -am\" command, to speed things up\n- However, be careful not to stage files (e.g. with \\`git add .\\`) for commits that aren't part of the change, they may have untracked files they want to keep around, but not commit.\n- NEVER update the git config\n- DO NOT push to the remote repository\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- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.\n- Return an empty response - the user will see the git output directly\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. Understand the current state of the branch. Remember to send a single message that contains multiple tool_use blocks (it is VERY IMPORTANT that you do this in a single message, otherwise it will feel slow to the user!):\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 main...HEAD\\` to understand the full commit history for the current branch (from the time it diverged from the \\`main\\` branch.)\n\n2. Create new branch if needed\n\n3. Commit changes if needed\n\n4. Push to remote with -u flag if needed\n\n5. 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. Wrap your analysis process in <pr_analysis> tags:\n\n<pr_analysis>\n- List the commits since diverging from the main branch\n- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)\n- Brainstorm the purpose or motivation behind these changes\n- Assess the impact of these changes on the overall project\n- Do not use tools to explore code, beyond what is available in the git context\n- Check for any sensitive information that shouldn't be committed\n- Draft a concise (1-2 bullet points) pull request summary that focuses on the \"why\" rather than the \"what\"\n- Ensure the summary accurately reflects all changes since diverging from the main branch\n- Ensure your language is clear, concise, and to the point\n- Ensure the summary accurately reflects the changes and their purpose (ie. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.)\n- Ensure the summary is not generic (avoid words like \"Update\" or \"Fix\" without context)\n- Review the draft summary to ensure it accurately reflects the changes and their purpose\n</pr_analysis>\n\n6. 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[Checklist of TODOs for testing the pull request...]\n\n\uD83E\uDD16 Generated with [${PRODUCT_NAME}](${PRODUCT_URL}) & {MODEL_NAME}\nEOF\n)\"\n</example>\n\nImportant:\n- Return an empty response - the user will see the gh output directly\n- Never update git config`\n"],
5
- "mappings": "AAAA,SAAS,cAAc,mBAAmB;AAC1C,SAAS,aAAa,sBAAsB;AAC5C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB,sBAAsB;AACvD,SAAS,wBAAwB,sBAAsB;AACvD,SAAS,cAAc;AAEhB,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAY3B,MAAM,kBAAkB;AAAA;AAAA,EAE7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BA8DrC,YAAY,KAAK,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
4
+ "sourcesContent": ["import { PRODUCT_NAME, PRODUCT_URL } from '@constants/product'\nimport { TOOL_NAME as TASK_TOOL_NAME } from '@tools/TaskTool/constants'\nimport { FileReadTool } from '@tools/FileReadTool/FileReadTool'\nimport { TOOL_NAME_FOR_PROMPT as GLOB_TOOL_NAME } from '@tools/GlobTool/prompt'\nimport { TOOL_NAME_FOR_PROMPT as GREP_TOOL_NAME } from '@tools/GrepTool/prompt'\nimport { LSTool } from '@tools/lsTool/lsTool'\n\nexport const MAX_OUTPUT_LENGTH = 30000\nexport const MAX_RENDERED_LINES = 5\n\n/**\n * Banned commands for security\n *\n * Categories:\n * - Network tools: Could be used for data exfiltration or network attacks\n * - System modification: Could damage the system or escalate privileges\n * - Shell execution: Could bypass command restrictions\n * - Browsers: Could open external content\n * - Dangerous file operations: Could cause data loss\n */\nexport const BANNED_COMMANDS = [\n // Network tools - data exfiltration risk\n 'curl',\n 'curlie',\n 'wget',\n 'axel',\n 'aria2c',\n 'nc',\n 'netcat',\n 'ncat',\n 'telnet',\n 'lynx',\n 'w3m',\n 'links',\n 'httpie',\n 'xh',\n 'http-prompt',\n 'ftp',\n 'sftp',\n 'scp',\n 'rsync',\n 'socat',\n 'nmap',\n 'tcpdump',\n 'wireshark',\n 'tshark',\n\n // Browsers - could open external content\n 'chrome',\n 'chromium',\n 'firefox',\n 'safari',\n 'opera',\n 'brave',\n 'open', // macOS open command could launch apps/URLs\n\n // Privilege escalation - dangerous system access\n 'sudo',\n 'su',\n 'doas',\n 'pkexec',\n 'gksudo',\n 'kdesudo',\n\n // Shell execution - could bypass restrictions\n 'eval',\n 'source',\n 'exec',\n 'bash',\n 'sh',\n 'zsh',\n 'fish',\n 'csh',\n 'tcsh',\n 'ksh',\n 'dash',\n 'ash',\n 'xargs', // Can execute arbitrary commands\n 'parallel', // GNU parallel can execute commands\n 'xonsh',\n 'powershell',\n 'pwsh',\n 'cmd',\n\n // Dangerous file operations - data loss risk\n 'rm',\n 'rmdir',\n 'shred',\n 'srm',\n 'wipe',\n 'dd', // Can overwrite disks\n 'mkfs', // Can format disks\n 'fdisk',\n 'parted',\n 'wipefs',\n\n // System modification - could damage system\n 'chmod',\n 'chown',\n 'chgrp',\n 'chattr',\n 'setfacl',\n 'shutdown',\n 'reboot',\n 'poweroff',\n 'halt',\n 'init',\n 'systemctl',\n 'service',\n 'launchctl', // macOS service control\n\n // Process control - could affect system stability\n 'kill',\n 'killall',\n 'pkill',\n\n // Aliases and functions - could hide malicious commands\n 'alias',\n 'unalias',\n 'function',\n\n // Cron/scheduling - persistent access\n 'crontab',\n 'at',\n 'atq',\n 'atrm',\n\n // User management - privilege escalation\n 'useradd',\n 'userdel',\n 'usermod',\n 'groupadd',\n 'groupdel',\n 'groupmod',\n 'passwd',\n 'chpasswd',\n\n // Package managers - could install malware\n 'apt',\n 'apt-get',\n 'aptitude',\n 'dpkg',\n 'yum',\n 'dnf',\n 'rpm',\n 'pacman',\n 'brew',\n 'port', // MacPorts\n 'pip',\n 'pip3',\n 'npm',\n 'yarn',\n 'pnpm',\n 'gem',\n 'cargo',\n 'go', // go install could install packages\n\n // Compilers/interpreters with execution capability\n 'python',\n 'python3',\n 'python2',\n 'ruby',\n 'perl',\n 'php',\n 'node',\n 'deno',\n 'bun',\n 'lua',\n 'awk',\n 'gawk',\n 'mawk',\n 'nawk',\n 'sed', // Can execute commands with e flag\n\n // Container/VM - could escape sandbox\n 'docker',\n 'podman',\n 'kubectl',\n 'vagrant',\n 'virsh',\n 'qemu',\n 'virtualbox',\n 'vboxmanage',\n\n // System info that could aid attacks\n 'env', // Exposes environment variables including secrets\n\n // Encryption/keys - could exfiltrate secrets\n 'gpg',\n 'openssl',\n 'ssh-keygen',\n 'ssh-agent',\n 'ssh-add',\n]\n\n/**\n * Detailed dangerous pattern match information\n */\nexport interface DangerousPatternMatch {\n pattern: string\n name: string\n match: string\n severity: 'critical' | 'high' | 'medium'\n}\n\n/**\n * Mapping of dangerous patterns with metadata\n */\nconst DANGEROUS_PATTERN_METADATA: Array<{\n pattern: RegExp\n name: string\n severity: 'critical' | 'high' | 'medium'\n}> = [\n // CRITICAL: Command Injection & Execution Bypass\n {\n pattern: /\\$\\([^)]+\\)/,\n name: 'command substitution $(...)',\n severity: 'critical',\n },\n {\n pattern: /`[^`]+`/,\n name: 'backtick command substitution',\n severity: 'critical',\n },\n {\n pattern: /;\\s*(rm|chmod|chown|dd|mkfs)\\b/i,\n name: 'chained destructive command',\n severity: 'critical',\n },\n {\n pattern: /&&\\s*(rm|chmod|chown|dd|mkfs)\\b/i,\n name: 'conditional destructive command',\n severity: 'critical',\n },\n {\n pattern: /\\|\\s*bash\\b/i,\n name: 'pipe to bash',\n severity: 'critical',\n },\n {\n pattern: /\\|\\s*sh\\b/i,\n name: 'pipe to sh',\n severity: 'critical',\n },\n {\n pattern: /curl.*\\|\\s*(bash|sh)\\b/i,\n name: 'curl pipe to shell',\n severity: 'critical',\n },\n {\n pattern: /wget.*\\|\\s*(bash|sh)\\b/i,\n name: 'wget pipe to shell',\n severity: 'critical',\n },\n {\n pattern: /eval\\s+['\"$]/,\n name: 'eval with dynamic input',\n severity: 'critical',\n },\n\n // CRITICAL: Destructive Operations\n {\n pattern: /\\brm\\s+-rf\\s+\\/(?!\\S)/,\n name: 'rm -rf /',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/dev\\/sd[a-z]/i,\n name: 'write to block device',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/dev\\/nvme/i,\n name: 'write to NVMe device',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/etc\\/(passwd|shadow|sudoers)/i,\n name: 'overwrite critical system files',\n severity: 'critical',\n },\n {\n pattern: />\\s*\\/boot\\//i,\n name: 'overwrite boot files',\n severity: 'critical',\n },\n\n // CRITICAL: Fork Bomb & DoS\n {\n pattern: /:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;?\\s*:/,\n name: 'fork bomb pattern ()',\n severity: 'critical',\n },\n {\n pattern: /\\.\\s*\\(\\)\\s*\\{\\s*\\.\\s*\\|\\s*\\.\\s*&\\s*\\}\\s*;?\\s*\\./,\n name: 'fork bomb pattern (.)',\n severity: 'critical',\n },\n\n // HIGH: Reverse Shell & Data Exfiltration\n {\n pattern: /\\$\\(\\s*<\\s*\\/dev\\/tcp/i,\n name: 'TCP socket connection',\n severity: 'high',\n },\n {\n pattern: /\\/dev\\/tcp\\//i,\n name: 'direct TCP device access',\n severity: 'high',\n },\n {\n pattern: /\\/dev\\/udp\\//i,\n name: 'direct UDP device access',\n severity: 'high',\n },\n {\n pattern: /mkfifo.*nc/i,\n name: 'named pipe with netcat',\n severity: 'high',\n },\n {\n pattern: /bash\\s+-i\\s+>&\\s*\\/dev\\/tcp/i,\n name: 'interactive bash reverse shell',\n severity: 'high',\n },\n\n // HIGH: Data Encoding & Obfuscation\n {\n pattern: /base64\\s+(-d|--decode).*\\|\\s*(bash|sh|eval)/i,\n name: 'base64 decode and execute',\n severity: 'high',\n },\n {\n pattern: /xxd\\s+-r.*\\|\\s*(bash|sh|eval)/i,\n name: 'hex decode and execute',\n severity: 'high',\n },\n\n // HIGH: System & Security Manipulation\n {\n pattern: /HISTFILE=/i,\n name: 'history file manipulation',\n severity: 'high',\n },\n {\n pattern: /unset\\s+HISTFILE/i,\n name: 'disable command history',\n severity: 'high',\n },\n {\n pattern: /history\\s+-c/i,\n name: 'clear command history',\n severity: 'high',\n },\n {\n pattern: /LD_PRELOAD=/i,\n name: 'library preload injection',\n severity: 'high',\n },\n {\n pattern: /LD_LIBRARY_PATH=/i,\n name: 'library path injection',\n severity: 'high',\n },\n {\n pattern: /DYLD_INSERT_LIBRARIES=/i,\n name: 'macOS library injection',\n severity: 'high',\n },\n\n // MEDIUM: Suspicious Command Patterns\n {\n pattern: /\\$\\{[^}]*\\}/,\n name: 'variable expansion',\n severity: 'medium',\n },\n]\n\n/**\n * Check if a command matches any dangerous pattern and return detailed information\n */\nexport function detectDangerousPatterns(\n command: string,\n): DangerousPatternMatch[] {\n const matches: DangerousPatternMatch[] = []\n\n for (const { pattern, name, severity } of DANGEROUS_PATTERN_METADATA) {\n const match = command.match(pattern)\n if (match) {\n matches.push({\n pattern: pattern.toString(),\n name,\n match: match[0],\n severity,\n })\n }\n }\n\n return matches\n}\n\n/**\n * Check if a command matches any dangerous pattern (backward compatible)\n */\nexport function matchesDangerousPattern(command: string): boolean {\n const criticalMatches = detectDangerousPatterns(command).filter(\n m => m.severity === 'critical',\n )\n return criticalMatches.length > 0\n}\n\nexport const PROMPT = `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\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 LS tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use LS to check that \"foo\" exists and is the intended parent directory\n\n2. Security Check:\n - For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User.\n - Verify that the command is not one of the banned commands: ${BANNED_COMMANDS.join(', ')}.\n\n3. 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\n4. Output Processing:\n - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.\n - Prepare the output for display to the user.\n\n5. Return Result:\n - Provide the processed output of the command.\n - If any errors occurred during execution, include those in the output.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes.\n - You can set run_in_background to true to run the command in the background. This is useful for long-running processes like dev servers, build watches, or monitoring tasks. When running in background, you will receive a shell_id that can be used with BashOutputTool and KillShellTool to monitor and manage the task.\n - VERY IMPORTANT: You MUST avoid using search commands like \\`find\\` and \\`grep\\`. Instead use ${GREP_TOOL_NAME}, ${GLOB_TOOL_NAME}, or ${TASK_TOOL_NAME} to search. You MUST avoid read tools like \\`cat\\`, \\`head\\`, \\`tail\\`, and \\`ls\\`, and use ${FileReadTool.name} and ${LSTool.name} to read files.\n - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).\n - IMPORTANT: All commands share the same shell session. Shell state (environment variables, virtual environments, current directory, etc.) persist between commands. For example, if you set an environment variable as part of a command, the environment variable will persist for subsequent commands.\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# Committing changes with git\n\nWhen the user asks you to create a new git commit, follow these steps carefully:\n\n1. Start with a single message that contains exactly three tool_use blocks that do the following (it is VERY IMPORTANT that you send these tool_use blocks in a single message, otherwise it will feel slow to the user!):\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.\n\n2. Use the git context at the start of this conversation to determine which files are relevant to your commit. Add relevant untracked files to the staging area. Do not commit files that were already modified at the start of this conversation, if they are not relevant to your commit.\n\n3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags:\n\n<commit_analysis>\n- List the files that have been changed or added\n- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)\n- Brainstorm the purpose or motivation behind these changes\n- Do not use tools to explore code, beyond what is available in the git context\n- Assess the impact of these changes on the overall project\n- Check for any sensitive information that shouldn't be committed\n- Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n- Ensure your language is clear, concise, and to the point\n- 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- Ensure the message is not generic (avoid words like \"Update\" or \"Fix\" without context)\n- Review the draft message to ensure it accurately reflects the changes and their purpose\n</commit_analysis>\n\n4. Create the commit with a message ending with:\n\uD83E\uDD16 Generated with ${PRODUCT_NAME} & {MODEL_NAME}\nCo-Authored-By: ${PRODUCT_NAME} <noreply@${PRODUCT_NAME}.com>\n\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.\n\n \uD83E\uDD16 Generated with ${PRODUCT_NAME} & {MODEL_NAME}\n Co-Authored-By: ${PRODUCT_NAME} <noreply@${PRODUCT_NAME}.com>\n EOF\n )\"\n</example>\n\n5. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.\n\n6. Finally, run git status to make sure the commit succeeded.\n\nImportant notes:\n- When possible, combine the \"git add\" and \"git commit\" commands into a single \"git commit -am\" command, to speed things up\n- However, be careful not to stage files (e.g. with \\`git add .\\`) for commits that aren't part of the change, they may have untracked files they want to keep around, but not commit.\n- NEVER update the git config\n- DO NOT push to the remote repository\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- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.\n- Return an empty response - the user will see the git output directly\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. Understand the current state of the branch. Remember to send a single message that contains multiple tool_use blocks (it is VERY IMPORTANT that you do this in a single message, otherwise it will feel slow to the user!):\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 main...HEAD\\` to understand the full commit history for the current branch (from the time it diverged from the \\`main\\` branch.)\n\n2. Create new branch if needed\n\n3. Commit changes if needed\n\n4. Push to remote with -u flag if needed\n\n5. 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. Wrap your analysis process in <pr_analysis> tags:\n\n<pr_analysis>\n- List the commits since diverging from the main branch\n- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)\n- Brainstorm the purpose or motivation behind these changes\n- Assess the impact of these changes on the overall project\n- Do not use tools to explore code, beyond what is available in the git context\n- Check for any sensitive information that shouldn't be committed\n- Draft a concise (1-2 bullet points) pull request summary that focuses on the \"why\" rather than the \"what\"\n- Ensure the summary accurately reflects all changes since diverging from the main branch\n- Ensure your language is clear, concise, and to the point\n- Ensure the summary accurately reflects the changes and their purpose (ie. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.)\n- Ensure the summary is not generic (avoid words like \"Update\" or \"Fix\" without context)\n- Review the draft summary to ensure it accurately reflects the changes and their purpose\n</pr_analysis>\n\n6. 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[Checklist of TODOs for testing the pull request...]\n\n\uD83E\uDD16 Generated with [${PRODUCT_NAME}](${PRODUCT_URL}) & {MODEL_NAME}\nEOF\n)\"\n</example>\n\nImportant:\n- Return an empty response - the user will see the gh output directly\n- Never update git config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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mGAWqD,cAAc,KAAK,cAAc,QAAQ,cAAc,+FAA+F,aAAa,IAAI,QAAQ,OAAO,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAuCzQ,YAAY;AAAA,kBACd,YAAY,aAAa,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAOhC,YAAY;AAAA,qBACd,YAAY,aAAa,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BA8DrC,YAAY,KAAK,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
@@ -30,7 +30,10 @@ import { PROJECT_FILE } from "../../constants/product.js";
30
30
  const inputSchema = z.strictObject({
31
31
  file_path: z.string().describe("The absolute path to the file to modify"),
32
32
  old_string: z.string().describe("The text to replace"),
33
- new_string: z.string().describe("The text to replace it with")
33
+ new_string: z.string().describe(
34
+ "The text to replace it with (must be different from old_string)"
35
+ ),
36
+ replace_all: z.boolean().optional().default(false).describe("Replace all occurences of old_string (default false)")
34
37
  });
35
38
  const N_LINES_SNIPPET = 4;
36
39
  const FileEditTool = {
@@ -58,7 +61,9 @@ const FileEditTool = {
58
61
  return !hasWritePermission(file_path);
59
62
  },
60
63
  renderToolUseMessage(input, { verbose }) {
61
- return `file_path: ${verbose ? input.file_path : relative(getCwd(), input.file_path)}`;
64
+ const filePath = verbose ? input.file_path : relative(getCwd(), input.file_path);
65
+ const replaceAllSuffix = input.replace_all ? ", replace_all: true" : "";
66
+ return `file_path: ${filePath}${replaceAllSuffix}`;
62
67
  },
63
68
  renderToolResultMessage(output, options) {
64
69
  const verbose = options?.verbose ?? false;
@@ -75,12 +80,17 @@ const FileEditTool = {
75
80
  }
76
81
  );
77
82
  },
78
- renderToolUseRejectedMessage({ file_path, old_string, new_string } = {}, { columns, verbose } = {}) {
83
+ renderToolUseRejectedMessage({ file_path, old_string, new_string, replace_all } = {}, { columns, verbose } = {}) {
79
84
  try {
80
85
  if (!file_path) {
81
86
  return /* @__PURE__ */ React.createElement(FallbackToolUseRejectedMessage, null);
82
87
  }
83
- const { patch } = applyEdit(file_path, old_string, new_string);
88
+ const { patch } = applyEdit(
89
+ file_path,
90
+ old_string,
91
+ new_string,
92
+ replace_all
93
+ );
84
94
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Text, null, " ", "\u23BF", " ", /* @__PURE__ */ React.createElement(Text, { color: getTheme().error }, "User rejected ", old_string === "" ? "write" : "update", " to", " "), /* @__PURE__ */ React.createElement(Text, { bold: true }, verbose ? file_path : relative(getCwd(), file_path))), intersperse(
85
95
  patch.map((patch2) => /* @__PURE__ */ React.createElement(Box, { flexDirection: "column", paddingLeft: 5, key: patch2.newStart }, /* @__PURE__ */ React.createElement(StructuredDiff, { patch: patch2, dim: true, width: columns - 12 }))),
86
96
  (i) => /* @__PURE__ */ React.createElement(Box, { paddingLeft: 5, key: `ellipsis-${i}` }, /* @__PURE__ */ React.createElement(Text, { color: getTheme().secondaryText }, "..."))
@@ -90,7 +100,7 @@ const FileEditTool = {
90
100
  return /* @__PURE__ */ React.createElement(Box, { flexDirection: "column" }, /* @__PURE__ */ React.createElement(Text, null, " ", "\u23BF (No changes)"));
91
101
  }
92
102
  },
93
- async validateInput({ file_path, old_string, new_string }, { readFileTimestamps }) {
103
+ async validateInput({ file_path, old_string, new_string, replace_all }, { readFileTimestamps }) {
94
104
  if (old_string === new_string) {
95
105
  return {
96
106
  result: false,
@@ -177,10 +187,10 @@ const FileEditTool = {
177
187
  };
178
188
  }
179
189
  const matches = file.split(old_string).length - 1;
180
- if (matches > 1) {
190
+ if (matches > 1 && !replace_all) {
181
191
  return {
182
192
  result: false,
183
- message: `Found ${matches} matches of the string to replace. For safety, this tool only supports replacing exactly one occurrence at a time. Add more lines of context to your edit and try again.`,
193
+ message: `Found ${matches} matches of the string to replace. For safety, this tool only supports replacing exactly one occurrence at a time. Add more lines of context to your edit and try again, or use replace_all to change every instance.`,
184
194
  meta: {
185
195
  isFilePathAbsolute: String(isAbsolute(file_path))
186
196
  }
@@ -188,8 +198,13 @@ const FileEditTool = {
188
198
  }
189
199
  return { result: true };
190
200
  },
191
- async *call({ file_path, old_string, new_string }, { readFileTimestamps }) {
192
- const { patch, updatedFile } = applyEdit(file_path, old_string, new_string);
201
+ async *call({ file_path, old_string, new_string, replace_all }, { readFileTimestamps }) {
202
+ const { patch, updatedFile } = applyEdit(
203
+ file_path,
204
+ old_string,
205
+ new_string,
206
+ replace_all
207
+ );
193
208
  const fullFilePath = isAbsolute(file_path) ? file_path : resolve(getCwd(), file_path);
194
209
  const dir = dirname(fullFilePath);
195
210
  mkdirSync(dir, { recursive: true });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/tools/FileEditTool/FileEditTool.tsx"],
4
- "sourcesContent": ["import { Hunk } from 'diff'\nimport { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'fs'\nimport { Box, Text } from 'ink'\nimport { dirname, isAbsolute, relative, resolve, sep } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FileEditToolUpdatedMessage } from '@components/FileEditToolUpdatedMessage'\nimport { StructuredDiff } from '@components/StructuredDiff'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { Tool, ValidationResult } from '@tool'\nimport { intersperse } from '@utils/array'\nimport {\n addLineNumbers,\n detectFileEncoding,\n detectLineEndings,\n findSimilarFile,\n writeTextContent,\n} from '@utils/file'\nimport { logError } from '@utils/log'\nimport { getCwd } from '@utils/state'\nimport { getTheme } from '@utils/theme'\nimport { emitReminderEvent } from '@services/systemReminder'\nimport { recordFileEdit } from '@services/fileFreshness'\nimport { NotebookEditTool } from '@tools/NotebookEditTool/NotebookEditTool'\nimport { DESCRIPTION } from './prompt'\nimport { applyEdit } from './utils'\nimport {\n hasWritePermission,\n pathInOriginalCwd,\n} from '@utils/permissions/filesystem'\nimport { PROJECT_FILE } from '@constants/product'\n\nconst inputSchema = z.strictObject({\n file_path: z.string().describe('The absolute path to the file to modify'),\n old_string: z.string().describe('The text to replace'),\n new_string: z.string().describe('The text to replace it with'),\n})\n\nexport type In = typeof inputSchema\n\n// Number of lines of context to include before/after the change in our result message\nconst N_LINES_SNIPPET = 4\n\nexport const FileEditTool = {\n name: 'Edit',\n async description() {\n return 'A tool for editing files'\n },\n async prompt() {\n return DESCRIPTION\n },\n inputSchema,\n userFacingName() {\n return 'Edit'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // FileEdit modifies files, not safe for concurrent execution\n },\n needsPermissions({ file_path }) {\n return !hasWritePermission(file_path)\n },\n renderToolUseMessage(input, { verbose }) {\n return `file_path: ${verbose ? input.file_path : relative(getCwd(), input.file_path)}`\n },\n renderToolResultMessage(output, options?: { verbose?: boolean }) {\n const verbose = options?.verbose ?? false\n\n // Guard against undefined or null output\n if (!output) {\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text color={getTheme().secondaryText}>Edit completed</Text>\n </Box>\n </Box>\n )\n }\n\n const { filePath, structuredPatch } = output\n return (\n <FileEditToolUpdatedMessage\n filePath={filePath}\n structuredPatch={structuredPatch}\n verbose={verbose}\n />\n )\n },\n renderToolUseRejectedMessage(\n { file_path, old_string, new_string }: any = {},\n { columns, verbose }: any = {},\n ) {\n try {\n if (!file_path) {\n return <FallbackToolUseRejectedMessage />\n }\n const { patch } = applyEdit(file_path, old_string, new_string)\n return (\n <Box flexDirection=\"column\">\n <Text>\n {' '}\u23BF{' '}\n <Text color={getTheme().error}>\n User rejected {old_string === '' ? 'write' : 'update'} to{' '}\n </Text>\n <Text bold>\n {verbose ? file_path : relative(getCwd(), file_path)}\n </Text>\n </Text>\n {intersperse(\n patch.map(patch => (\n <Box flexDirection=\"column\" paddingLeft={5} key={patch.newStart}>\n <StructuredDiff patch={patch} dim={true} width={columns - 12} />\n </Box>\n )),\n i => (\n <Box paddingLeft={5} key={`ellipsis-${i}`}>\n <Text color={getTheme().secondaryText}>...</Text>\n </Box>\n ),\n )}\n </Box>\n )\n } catch (e) {\n // Handle the case where while we were showing the diff, the user manually made the change.\n // TODO: Find a way to show the diff in this case\n logError(e)\n return (\n <Box flexDirection=\"column\">\n <Text>{' '}\u23BF (No changes)</Text>\n </Box>\n )\n }\n },\n async validateInput(\n { file_path, old_string, new_string },\n { readFileTimestamps },\n ) {\n if (old_string === new_string) {\n return {\n result: false,\n message:\n 'No changes to make: old_string and new_string are exactly the same.',\n meta: {\n old_string,\n },\n } as ValidationResult\n }\n\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n // Security check: Ensure path is within allowed directory\n if (!pathInOriginalCwd(fullFilePath) && !hasWritePermission(fullFilePath)) {\n return {\n result: false,\n message:\n 'Path traversal detected - file must be within the project directory or an allowed write location.',\n }\n }\n\n // Security check: Check for symlinks that could escape directory boundaries\n if (existsSync(fullFilePath)) {\n try {\n const lstats = lstatSync(fullFilePath)\n if (lstats.isSymbolicLink()) {\n return {\n result: false,\n message:\n 'Cannot edit symbolic links for security reasons. Edit the target file directly.',\n }\n }\n } catch {\n // If we can't stat the file, let other checks handle it\n }\n }\n\n if (existsSync(fullFilePath) && old_string === '') {\n return {\n result: false,\n message: 'Cannot create new file - file already exists.',\n }\n }\n\n if (!existsSync(fullFilePath) && old_string === '') {\n return {\n result: true,\n }\n }\n\n if (!existsSync(fullFilePath)) {\n // Try to find a similar file with a different extension\n const similarFilename = findSimilarFile(fullFilePath)\n let message = 'File does not exist.'\n\n // If we found a similar file, suggest it to the assistant\n if (similarFilename) {\n message += ` Did you mean ${similarFilename}?`\n }\n\n return {\n result: false,\n message,\n }\n }\n\n if (fullFilePath.endsWith('.ipynb')) {\n return {\n result: false,\n message: `File is a Jupyter Notebook. Use the ${NotebookEditTool.name} to edit this file.`,\n }\n }\n\n const readTimestamp = readFileTimestamps[fullFilePath]\n if (!readTimestamp) {\n return {\n result: false,\n message:\n 'File has not been read yet. Read it first before writing to it.',\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n // Check if file exists and get its last modified time\n const stats = statSync(fullFilePath)\n const lastWriteTime = stats.mtimeMs\n if (lastWriteTime > readTimestamp) {\n return {\n result: false,\n message:\n 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',\n }\n }\n\n const enc = detectFileEncoding(fullFilePath)\n const file = readFileSync(fullFilePath, enc)\n if (!file.includes(old_string)) {\n return {\n result: false,\n message: `String to replace not found in file.`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n const matches = file.split(old_string).length - 1\n if (matches > 1) {\n return {\n result: false,\n message: `Found ${matches} matches of the string to replace. For safety, this tool only supports replacing exactly one occurrence at a time. Add more lines of context to your edit and try again.`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n return { result: true }\n },\n async *call({ file_path, old_string, new_string }, { readFileTimestamps }) {\n const { patch, updatedFile } = applyEdit(file_path, old_string, new_string)\n\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n const dir = dirname(fullFilePath)\n mkdirSync(dir, { recursive: true })\n const enc = existsSync(fullFilePath)\n ? detectFileEncoding(fullFilePath)\n : 'utf8'\n const endings = existsSync(fullFilePath)\n ? detectLineEndings(fullFilePath)\n : 'LF'\n const originalFile = existsSync(fullFilePath)\n ? readFileSync(fullFilePath, enc)\n : ''\n writeTextContent(fullFilePath, updatedFile, enc, endings)\n\n // Record Agent edit operation for file freshness tracking\n recordFileEdit(fullFilePath, updatedFile)\n\n // Update read timestamp, to invalidate stale writes\n readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs\n\n // Log when editing CLAUDE.md\n if (fullFilePath.endsWith(`${sep}${PROJECT_FILE}`)) {\n }\n\n // Emit file edited event for system reminders\n emitReminderEvent('file:edited', {\n filePath: fullFilePath,\n oldString: old_string,\n newString: new_string,\n timestamp: Date.now(),\n operation:\n old_string === '' ? 'create' : new_string === '' ? 'delete' : 'update',\n })\n\n const data = {\n filePath: file_path,\n oldString: old_string,\n newString: new_string,\n originalFile,\n structuredPatch: patch,\n }\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n renderResultForAssistant({ filePath, originalFile, oldString, newString }) {\n const { snippet, startLine } = getSnippet(\n originalFile || '',\n oldString,\n newString,\n )\n return `The file ${filePath} has been updated. Here's the result of running \\`cat -n\\` on a snippet of the edited file:\n${addLineNumbers({\n content: snippet,\n startLine,\n})}`\n },\n} satisfies Tool<\n typeof inputSchema,\n {\n filePath: string\n oldString: string\n newString: string\n originalFile: string\n structuredPatch: Hunk[]\n }\n>\n\nexport function getSnippet(\n initialText: string,\n oldStr: string,\n newStr: string,\n): { snippet: string; startLine: number } {\n const before = initialText.split(oldStr)[0] ?? ''\n const replacementLine = before.split(/\\r?\\n/).length - 1\n const newFileLines = initialText.replace(oldStr, newStr).split(/\\r?\\n/)\n // Calculate the start and end line numbers for the snippet\n const startLine = Math.max(0, replacementLine - N_LINES_SNIPPET)\n const endLine =\n replacementLine + N_LINES_SNIPPET + newStr.split(/\\r?\\n/).length\n // Get snippet\n const snippetLines = newFileLines.slice(startLine, endLine + 1)\n const snippet = snippetLines.join('\\n')\n return { snippet, startLine: startLine + 1 }\n}\n"],
5
- "mappings": "AACA,SAAS,YAAY,WAAW,WAAW,cAAc,gBAAgB;AACzE,SAAS,KAAK,YAAY;AAC1B,SAAS,SAAS,YAAY,UAAU,SAAS,WAAW;AAC5D,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB,SAAS,kCAAkC;AAC3C,SAAS,sBAAsB;AAC/B,SAAS,sCAAsC;AAE/C,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,cAAc,EAAE,aAAa;AAAA,EACjC,WAAW,EAAE,OAAO,EAAE,SAAS,yCAAyC;AAAA,EACxE,YAAY,EAAE,OAAO,EAAE,SAAS,qBAAqB;AAAA,EACrD,YAAY,EAAE,OAAO,EAAE,SAAS,6BAA6B;AAC/D,CAAC;AAKD,MAAM,kBAAkB;AAEjB,MAAM,eAAe;AAAA,EAC1B,MAAM;AAAA,EACN,MAAM,cAAc;AAClB,WAAO;AAAA,EACT;AAAA,EACA,MAAM,SAAS;AACb,WAAO;AAAA,EACT;AAAA,EACA;AAAA,EACA,iBAAiB;AACf,WAAO;AAAA,EACT;AAAA,EACA,MAAM,YAAY;AAChB,WAAO;A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aACA,QACA,QACwC;AACxC,QAAM,SAAS,YAAY,MAAM,MAAM,EAAE,CAAC,KAAK;AAC/C,QAAM,kBAAkB,OAAO,MAAM,OAAO,EAAE,SAAS;AACvD,QAAM,eAAe,YAAY,QAAQ,QAAQ,MAAM,EAAE,MAAM,OAAO;AAEtE,QAAM,YAAY,KAAK,IAAI,GAAG,kBAAkB,eAAe;AAC/D,QAAM,UACJ,kBAAkB,kBAAkB,OAAO,MAAM,OAAO,EAAE;AAE5D,QAAM,eAAe,aAAa,MAAM,WAAW,UAAU,CAAC;AAC9D,QAAM,UAAU,aAAa,KAAK,IAAI;AACtC,SAAO,EAAE,SAAS,WAAW,YAAY,EAAE;AAC7C;",
4
+ "sourcesContent": ["import { Hunk } from 'diff'\nimport { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'fs'\nimport { Box, Text } from 'ink'\nimport { dirname, isAbsolute, relative, resolve, sep } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { FileEditToolUpdatedMessage } from '@components/FileEditToolUpdatedMessage'\nimport { StructuredDiff } from '@components/StructuredDiff'\nimport { FallbackToolUseRejectedMessage } from '@components/FallbackToolUseRejectedMessage'\nimport { Tool, ValidationResult } from '@tool'\nimport { intersperse } from '@utils/array'\nimport {\n addLineNumbers,\n detectFileEncoding,\n detectLineEndings,\n findSimilarFile,\n writeTextContent,\n} from '@utils/file'\nimport { logError } from '@utils/log'\nimport { getCwd } from '@utils/state'\nimport { getTheme } from '@utils/theme'\nimport { emitReminderEvent } from '@services/systemReminder'\nimport { recordFileEdit } from '@services/fileFreshness'\nimport { NotebookEditTool } from '@tools/NotebookEditTool/NotebookEditTool'\nimport { DESCRIPTION } from './prompt'\nimport { applyEdit } from './utils'\nimport {\n hasWritePermission,\n pathInOriginalCwd,\n} from '@utils/permissions/filesystem'\nimport { PROJECT_FILE } from '@constants/product'\n\nconst inputSchema = z.strictObject({\n file_path: z.string().describe('The absolute path to the file to modify'),\n old_string: z.string().describe('The text to replace'),\n new_string: z\n .string()\n .describe(\n 'The text to replace it with (must be different from old_string)',\n ),\n replace_all: z\n .boolean()\n .optional()\n .default(false)\n .describe('Replace all occurences of old_string (default false)'),\n})\n\nexport type In = typeof inputSchema\n\n// Number of lines of context to include before/after the change in our result message\nconst N_LINES_SNIPPET = 4\n\nexport const FileEditTool = {\n name: 'Edit',\n async description() {\n return 'A tool for editing files'\n },\n async prompt() {\n return DESCRIPTION\n },\n inputSchema,\n userFacingName() {\n return 'Edit'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // FileEdit modifies files, not safe for concurrent execution\n },\n needsPermissions({ file_path }) {\n return !hasWritePermission(file_path)\n },\n renderToolUseMessage(input, { verbose }) {\n const filePath = verbose\n ? input.file_path\n : relative(getCwd(), input.file_path)\n const replaceAllSuffix = input.replace_all ? ', replace_all: true' : ''\n return `file_path: ${filePath}${replaceAllSuffix}`\n },\n renderToolResultMessage(output, options?: { verbose?: boolean }) {\n const verbose = options?.verbose ?? false\n\n // Guard against undefined or null output\n if (!output) {\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text>&nbsp;&nbsp;\u23BF &nbsp;</Text>\n <Text color={getTheme().secondaryText}>Edit completed</Text>\n </Box>\n </Box>\n )\n }\n\n const { filePath, structuredPatch } = output\n return (\n <FileEditToolUpdatedMessage\n filePath={filePath}\n structuredPatch={structuredPatch}\n verbose={verbose}\n />\n )\n },\n renderToolUseRejectedMessage(\n { file_path, old_string, new_string, replace_all }: any = {},\n { columns, verbose }: any = {},\n ) {\n try {\n if (!file_path) {\n return <FallbackToolUseRejectedMessage />\n }\n const { patch } = applyEdit(\n file_path,\n old_string,\n new_string,\n replace_all,\n )\n return (\n <Box flexDirection=\"column\">\n <Text>\n {' '}\u23BF{' '}\n <Text color={getTheme().error}>\n User rejected {old_string === '' ? 'write' : 'update'} to{' '}\n </Text>\n <Text bold>\n {verbose ? file_path : relative(getCwd(), file_path)}\n </Text>\n </Text>\n {intersperse(\n patch.map(patch => (\n <Box flexDirection=\"column\" paddingLeft={5} key={patch.newStart}>\n <StructuredDiff patch={patch} dim={true} width={columns - 12} />\n </Box>\n )),\n i => (\n <Box paddingLeft={5} key={`ellipsis-${i}`}>\n <Text color={getTheme().secondaryText}>...</Text>\n </Box>\n ),\n )}\n </Box>\n )\n } catch (e) {\n // Handle the case where while we were showing the diff, the user manually made the change.\n // TODO: Find a way to show the diff in this case\n logError(e)\n return (\n <Box flexDirection=\"column\">\n <Text>{' '}\u23BF (No changes)</Text>\n </Box>\n )\n }\n },\n async validateInput(\n { file_path, old_string, new_string, replace_all },\n { readFileTimestamps },\n ) {\n if (old_string === new_string) {\n return {\n result: false,\n message:\n 'No changes to make: old_string and new_string are exactly the same.',\n meta: {\n old_string,\n },\n } as ValidationResult\n }\n\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n // Security check: Ensure path is within allowed directory\n if (!pathInOriginalCwd(fullFilePath) && !hasWritePermission(fullFilePath)) {\n return {\n result: false,\n message:\n 'Path traversal detected - file must be within the project directory or an allowed write location.',\n }\n }\n\n // Security check: Check for symlinks that could escape directory boundaries\n if (existsSync(fullFilePath)) {\n try {\n const lstats = lstatSync(fullFilePath)\n if (lstats.isSymbolicLink()) {\n return {\n result: false,\n message:\n 'Cannot edit symbolic links for security reasons. Edit the target file directly.',\n }\n }\n } catch {\n // If we can't stat the file, let other checks handle it\n }\n }\n\n if (existsSync(fullFilePath) && old_string === '') {\n return {\n result: false,\n message: 'Cannot create new file - file already exists.',\n }\n }\n\n if (!existsSync(fullFilePath) && old_string === '') {\n return {\n result: true,\n }\n }\n\n if (!existsSync(fullFilePath)) {\n // Try to find a similar file with a different extension\n const similarFilename = findSimilarFile(fullFilePath)\n let message = 'File does not exist.'\n\n // If we found a similar file, suggest it to the assistant\n if (similarFilename) {\n message += ` Did you mean ${similarFilename}?`\n }\n\n return {\n result: false,\n message,\n }\n }\n\n if (fullFilePath.endsWith('.ipynb')) {\n return {\n result: false,\n message: `File is a Jupyter Notebook. Use the ${NotebookEditTool.name} to edit this file.`,\n }\n }\n\n const readTimestamp = readFileTimestamps[fullFilePath]\n if (!readTimestamp) {\n return {\n result: false,\n message:\n 'File has not been read yet. Read it first before writing to it.',\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n // Check if file exists and get its last modified time\n const stats = statSync(fullFilePath)\n const lastWriteTime = stats.mtimeMs\n if (lastWriteTime > readTimestamp) {\n return {\n result: false,\n message:\n 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',\n }\n }\n\n const enc = detectFileEncoding(fullFilePath)\n const file = readFileSync(fullFilePath, enc)\n if (!file.includes(old_string)) {\n return {\n result: false,\n message: `String to replace not found in file.`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n const matches = file.split(old_string).length - 1\n if (matches > 1 && !replace_all) {\n return {\n result: false,\n message: `Found ${matches} matches of the string to replace. For safety, this tool only supports replacing exactly one occurrence at a time. Add more lines of context to your edit and try again, or use replace_all to change every instance.`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n return { result: true }\n },\n async *call(\n { file_path, old_string, new_string, replace_all },\n { readFileTimestamps },\n ) {\n const { patch, updatedFile } = applyEdit(\n file_path,\n old_string,\n new_string,\n replace_all,\n )\n\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n const dir = dirname(fullFilePath)\n mkdirSync(dir, { recursive: true })\n const enc = existsSync(fullFilePath)\n ? detectFileEncoding(fullFilePath)\n : 'utf8'\n const endings = existsSync(fullFilePath)\n ? detectLineEndings(fullFilePath)\n : 'LF'\n const originalFile = existsSync(fullFilePath)\n ? readFileSync(fullFilePath, enc)\n : ''\n writeTextContent(fullFilePath, updatedFile, enc, endings)\n\n // Record Agent edit operation for file freshness tracking\n recordFileEdit(fullFilePath, updatedFile)\n\n // Update read timestamp, to invalidate stale writes\n readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs\n\n // Log when editing CLAUDE.md\n if (fullFilePath.endsWith(`${sep}${PROJECT_FILE}`)) {\n }\n\n // Emit file edited event for system reminders\n emitReminderEvent('file:edited', {\n filePath: fullFilePath,\n oldString: old_string,\n newString: new_string,\n timestamp: Date.now(),\n operation:\n old_string === '' ? 'create' : new_string === '' ? 'delete' : 'update',\n })\n\n const data = {\n filePath: file_path,\n oldString: old_string,\n newString: new_string,\n originalFile,\n structuredPatch: patch,\n }\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n renderResultForAssistant({ filePath, originalFile, oldString, newString }) {\n const { snippet, startLine } = getSnippet(\n originalFile || '',\n oldString,\n newString,\n )\n return `The file ${filePath} has been updated. Here's the result of running \\`cat -n\\` on a snippet of the edited file:\n${addLineNumbers({\n content: snippet,\n startLine,\n})}`\n },\n} satisfies Tool<\n typeof inputSchema,\n {\n filePath: string\n oldString: string\n newString: string\n originalFile: string\n structuredPatch: Hunk[]\n }\n>\n\nexport function getSnippet(\n initialText: string,\n oldStr: string,\n newStr: string,\n): { snippet: string; startLine: number } {\n const before = initialText.split(oldStr)[0] ?? ''\n const replacementLine = before.split(/\\r?\\n/).length - 1\n const newFileLines = initialText.replace(oldStr, newStr).split(/\\r?\\n/)\n // Calculate the start and end line numbers for the snippet\n const startLine = Math.max(0, replacementLine - N_LINES_SNIPPET)\n const endLine =\n replacementLine + N_LINES_SNIPPET + newStr.split(/\\r?\\n/).length\n // Get snippet\n const snippetLines = newFileLines.slice(startLine, endLine + 1)\n const snippet = snippetLines.join('\\n')\n return { snippet, startLine: startLine + 1 }\n}\n"],
5
+ "mappings": "AACA,SAAS,YAAY,WAAW,WAAW,cAAc,gBAAgB;AACzE,SAAS,KAAK,YAAY;AAC1B,SAAS,SAAS,YAAY,UAAU,SAAS,WAAW;AAC5D,YAAY,WAAW;AACvB,SAAS,SAA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AM,OAAO;AAEtE,QAAM,YAAY,KAAK,IAAI,GAAG,kBAAkB,eAAe;AAC/D,QAAM,UACJ,kBAAkB,kBAAkB,OAAO,MAAM,OAAO,EAAE;AAE5D,QAAM,eAAe,aAAa,MAAM,WAAW,UAAU,CAAC;AAC9D,QAAM,UAAU,aAAa,KAAK,IAAI;AACtC,SAAO,EAAE,SAAS,WAAW,YAAY,EAAE;AAC7C;",
6
6
  "names": ["patch"]
7
7
  }
@@ -15,8 +15,11 @@ To make a file edit, provide the following:
15
15
  1. file_path: The absolute path to the file to modify (must be absolute, not relative)
16
16
  2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)
17
17
  3. new_string: The edited text to replace the old_string
18
+ 4. replace_all: Set to true to replace ALL occurrences of old_string (default is false, which replaces only the first occurrence). Use this for renaming variables or updating strings across the file.
18
19
 
19
- The tool will replace ONE occurrence of old_string with new_string in the specified file.
20
+ The tool will replace ONE occurrence of old_string with new_string in the specified file (unless replace_all is true).
21
+
22
+ IMPORTANT: When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.
20
23
 
21
24
  CRITICAL REQUIREMENTS FOR USING THIS TOOL:
22
25
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/tools/FileEditTool/prompt.ts"],
4
- "sourcesContent": ["import { NotebookEditTool } from '@tools/NotebookEditTool/NotebookEditTool'\nimport { FileWriteTool } from '@tools/FileWriteTool/FileWriteTool'\nimport { FileReadTool } from '@tools/FileReadTool/FileReadTool'\nimport { LSTool } from '@tools/lsTool/lsTool'\n\nexport const DESCRIPTION = `This is a tool for editing files. For moving or renaming files, you should generally use the Bash tool with the 'mv' command instead. For larger edits, use the ${FileWriteTool.name} tool to overwrite files. For Jupyter notebooks (.ipynb files), use the ${NotebookEditTool.name} instead.\n\nBefore using this tool:\n\n1. Use the ${FileReadTool.name} tool to understand the file's contents and context\n\n2. Verify the directory path is correct (only applicable when creating new files):\n - Use the ${LSTool.name} tool to verify the parent directory exists and is the correct location\n\nTo make a file edit, provide the following:\n1. file_path: The absolute path to the file to modify (must be absolute, not relative)\n2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)\n3. new_string: The edited text to replace the old_string\n\nThe tool will replace ONE occurrence of old_string with new_string in the specified file.\n\nCRITICAL REQUIREMENTS FOR USING THIS TOOL:\n\n1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:\n - Include AT LEAST 3-5 lines of context BEFORE the change point\n - Include AT LEAST 3-5 lines of context AFTER the change point\n - Include all whitespace, indentation, and surrounding code exactly as it appears in the file\n\n2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:\n - Make separate calls to this tool for each instance\n - Each call must uniquely identify its specific instance using extensive context\n\n3. VERIFICATION: Before using this tool:\n - Check how many instances of the target text exist in the file\n - If multiple instances exist, gather enough context to uniquely identify each one\n - Plan separate tool calls for each instance\n\nWARNING: If you do not follow these requirements:\n - The tool will fail if old_string matches multiple locations\n - The tool will fail if old_string doesn't match exactly (including whitespace)\n - You may change the wrong instance if you don't include enough context\n\nWhen making edits:\n - Ensure the edit results in idiomatic, correct code\n - Do not leave the code in a broken state\n - Always use absolute file paths (starting with /)\n\nIf you want to create a new file, use:\n - A new file path, including dir name if needed\n - An empty old_string\n - The new file's contents as new_string\n\nRemember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.\n`\n"],
5
- "mappings": "AAAA,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AAEhB,MAAM,cAAc,mKAAmK,cAAc,IAAI,2EAA2E,iBAAiB,IAAI;AAAA;AAAA;AAAA;AAAA,aAInS,aAAa,IAAI;AAAA;AAAA;AAAA,eAGf,OAAO,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
4
+ "sourcesContent": ["import { NotebookEditTool } from '@tools/NotebookEditTool/NotebookEditTool'\nimport { FileWriteTool } from '@tools/FileWriteTool/FileWriteTool'\nimport { FileReadTool } from '@tools/FileReadTool/FileReadTool'\nimport { LSTool } from '@tools/lsTool/lsTool'\n\nexport const DESCRIPTION = `This is a tool for editing files. For moving or renaming files, you should generally use the Bash tool with the 'mv' command instead. For larger edits, use the ${FileWriteTool.name} tool to overwrite files. For Jupyter notebooks (.ipynb files), use the ${NotebookEditTool.name} instead.\n\nBefore using this tool:\n\n1. Use the ${FileReadTool.name} tool to understand the file's contents and context\n\n2. Verify the directory path is correct (only applicable when creating new files):\n - Use the ${LSTool.name} tool to verify the parent directory exists and is the correct location\n\nTo make a file edit, provide the following:\n1. file_path: The absolute path to the file to modify (must be absolute, not relative)\n2. old_string: The text to replace (must be unique within the file, and must match the file contents exactly, including all whitespace and indentation)\n3. new_string: The edited text to replace the old_string\n4. replace_all: Set to true to replace ALL occurrences of old_string (default is false, which replaces only the first occurrence). Use this for renaming variables or updating strings across the file.\n\nThe tool will replace ONE occurrence of old_string with new_string in the specified file (unless replace_all is true).\n\nIMPORTANT: When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.\n\nCRITICAL REQUIREMENTS FOR USING THIS TOOL:\n\n1. UNIQUENESS: The old_string MUST uniquely identify the specific instance you want to change. This means:\n - Include AT LEAST 3-5 lines of context BEFORE the change point\n - Include AT LEAST 3-5 lines of context AFTER the change point\n - Include all whitespace, indentation, and surrounding code exactly as it appears in the file\n\n2. SINGLE INSTANCE: This tool can only change ONE instance at a time. If you need to change multiple instances:\n - Make separate calls to this tool for each instance\n - Each call must uniquely identify its specific instance using extensive context\n\n3. VERIFICATION: Before using this tool:\n - Check how many instances of the target text exist in the file\n - If multiple instances exist, gather enough context to uniquely identify each one\n - Plan separate tool calls for each instance\n\nWARNING: If you do not follow these requirements:\n - The tool will fail if old_string matches multiple locations\n - The tool will fail if old_string doesn't match exactly (including whitespace)\n - You may change the wrong instance if you don't include enough context\n\nWhen making edits:\n - Ensure the edit results in idiomatic, correct code\n - Do not leave the code in a broken state\n - Always use absolute file paths (starting with /)\n\nIf you want to create a new file, use:\n - A new file path, including dir name if needed\n - An empty old_string\n - The new file's contents as new_string\n\nRemember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.\n`\n"],
5
+ "mappings": "AAAA,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AAEhB,MAAM,cAAc,mKAAmK,cAAc,IAAI,2EAA2E,iBAAiB,IAAI;AAAA;AAAA;AAAA;AAAA,aAInS,aAAa,IAAI;AAAA;AAAA;AAAA,eAGf,OAAO,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
@@ -3,8 +3,14 @@ import { getCwd } from "../../utils/state.js";
3
3
  import { readFileSync } from "fs";
4
4
  import { detectFileEncoding } from "../../utils/file.js";
5
5
  import { getPatch } from "../../utils/diff.js";
6
- function applyEdit(file_path, old_string, new_string) {
6
+ function applyEdit(file_path, old_string, new_string, replace_all = false) {
7
7
  const fullFilePath = isAbsolute(file_path) ? file_path : resolve(getCwd(), file_path);
8
+ const replaceString = (source, oldStr, newStr) => {
9
+ if (replace_all) {
10
+ return source.replaceAll(oldStr, newStr);
11
+ }
12
+ return source.replace(oldStr, () => newStr);
13
+ };
8
14
  let originalFile;
9
15
  let updatedFile;
10
16
  if (old_string === "") {
@@ -15,12 +21,12 @@ function applyEdit(file_path, old_string, new_string) {
15
21
  originalFile = readFileSync(fullFilePath, enc);
16
22
  if (new_string === "") {
17
23
  if (!old_string.endsWith("\n") && originalFile.includes(old_string + "\n")) {
18
- updatedFile = originalFile.replace(old_string + "\n", () => new_string);
24
+ updatedFile = replaceString(originalFile, old_string + "\n", new_string);
19
25
  } else {
20
- updatedFile = originalFile.replace(old_string, () => new_string);
26
+ updatedFile = replaceString(originalFile, old_string, new_string);
21
27
  }
22
28
  } else {
23
- updatedFile = originalFile.replace(old_string, () => new_string);
29
+ updatedFile = replaceString(originalFile, old_string, new_string);
24
30
  }
25
31
  if (updatedFile === originalFile) {
26
32
  throw new Error(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/tools/FileEditTool/utils.ts"],
4
- "sourcesContent": ["import { isAbsolute, resolve } from 'path'\nimport { getCwd } from '@utils/state'\nimport { readFileSync } from 'fs'\nimport { detectFileEncoding } from '@utils/file'\nimport { type Hunk } from 'diff'\nimport { getPatch } from '@utils/diff'\n\n/**\n * Applies an edit to a file and returns the patch and updated file.\n * Does not write the file to disk.\n */\nexport function applyEdit(\n file_path: string,\n old_string: string,\n new_string: string,\n): { patch: Hunk[]; updatedFile: string } {\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n let originalFile\n let updatedFile\n if (old_string === '') {\n // Create new file\n originalFile = ''\n updatedFile = new_string\n } else {\n // Edit existing file\n const enc = detectFileEncoding(fullFilePath)\n originalFile = readFileSync(fullFilePath, enc)\n if (new_string === '') {\n if (\n !old_string.endsWith('\\n') &&\n originalFile.includes(old_string + '\\n')\n ) {\n updatedFile = originalFile.replace(old_string + '\\n', () => new_string)\n } else {\n updatedFile = originalFile.replace(old_string, () => new_string)\n }\n } else {\n updatedFile = originalFile.replace(old_string, () => new_string)\n }\n if (updatedFile === originalFile) {\n throw new Error(\n 'Original and edited file match exactly. Failed to apply edit.',\n )\n }\n }\n\n const patch = getPatch({\n filePath: file_path,\n fileContents: originalFile,\n oldStr: originalFile,\n newStr: updatedFile,\n })\n\n return { patch, updatedFile }\n}\n"],
5
- "mappings": "AAAA,SAAS,YAAY,eAAe;AACpC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAEnC,SAAS,gBAAgB;AAMlB,SAAS,UACd,WACA,YACA,YACwC;AACxC,QAAM,eAAe,WAAW,SAAS,IACrC,YACA,QAAQ,OAAO,GAAG,SAAS;AAE/B,MAAI;AACJ,MAAI;AACJ,MAAI,eAAe,IAAI;AAErB,mBAAe;AACf,kBAAc;AAAA,EAChB,OAAO;AAEL,UAAM,MAAM,mBAAmB,YAAY;AAC3C,mBAAe,aAAa,cAAc,GAAG;AAC7C,QAAI,eAAe,IAAI;AACrB,UACE,CAAC,WAAW,SAAS,IAAI,KACzB,aAAa,SAAS,aAAa,IAAI,GACvC;AACA,sBAAc,aAAa,QAAQ,aAAa,MAAM,MAAM,UAAU;AAAA,MACxE,OAAO;AACL,sBAAc,aAAa,QAAQ,YAAY,MAAM,UAAU;AAAA,MACjE;AAAA,IACF,OAAO;AACL,oBAAc,aAAa,QAAQ,YAAY,MAAM,UAAU;AAAA,IACjE;AACA,QAAI,gBAAgB,cAAc;AAChC,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,QAAQ,SAAS;AAAA,IACrB,UAAU;AAAA,IACV,cAAc;AAAA,IACd,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,EAAE,OAAO,YAAY;AAC9B;",
4
+ "sourcesContent": ["import { isAbsolute, resolve } from 'path'\nimport { getCwd } from '@utils/state'\nimport { readFileSync } from 'fs'\nimport { detectFileEncoding } from '@utils/file'\nimport { type Hunk } from 'diff'\nimport { getPatch } from '@utils/diff'\n\n/**\n * Applies an edit to a file and returns the patch and updated file.\n * Does not write the file to disk.\n * @param replace_all - If true, replaces all occurrences of old_string. Defaults to false (replace first occurrence only).\n */\nexport function applyEdit(\n file_path: string,\n old_string: string,\n new_string: string,\n replace_all: boolean = false,\n): { patch: Hunk[]; updatedFile: string } {\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n // Helper function to perform replacement based on replace_all flag\n const replaceString = (\n source: string,\n oldStr: string,\n newStr: string,\n ): string => {\n if (replace_all) {\n return source.replaceAll(oldStr, newStr)\n }\n return source.replace(oldStr, () => newStr)\n }\n\n let originalFile\n let updatedFile\n if (old_string === '') {\n // Create new file\n originalFile = ''\n updatedFile = new_string\n } else {\n // Edit existing file\n const enc = detectFileEncoding(fullFilePath)\n originalFile = readFileSync(fullFilePath, enc)\n if (new_string === '') {\n if (\n !old_string.endsWith('\\n') &&\n originalFile.includes(old_string + '\\n')\n ) {\n updatedFile = replaceString(originalFile, old_string + '\\n', new_string)\n } else {\n updatedFile = replaceString(originalFile, old_string, new_string)\n }\n } else {\n updatedFile = replaceString(originalFile, old_string, new_string)\n }\n if (updatedFile === originalFile) {\n throw new Error(\n 'Original and edited file match exactly. Failed to apply edit.',\n )\n }\n }\n\n const patch = getPatch({\n filePath: file_path,\n fileContents: originalFile,\n oldStr: originalFile,\n newStr: updatedFile,\n })\n\n return { patch, updatedFile }\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY,eAAe;AACpC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAEnC,SAAS,gBAAgB;AAOlB,SAAS,UACd,WACA,YACA,YACA,cAAuB,OACiB;AACxC,QAAM,eAAe,WAAW,SAAS,IACrC,YACA,QAAQ,OAAO,GAAG,SAAS;AAG/B,QAAM,gBAAgB,CACpB,QACA,QACA,WACW;AACX,QAAI,aAAa;AACf,aAAO,OAAO,WAAW,QAAQ,MAAM;AAAA,IACzC;AACA,WAAO,OAAO,QAAQ,QAAQ,MAAM,MAAM;AAAA,EAC5C;AAEA,MAAI;AACJ,MAAI;AACJ,MAAI,eAAe,IAAI;AAErB,mBAAe;AACf,kBAAc;AAAA,EAChB,OAAO;AAEL,UAAM,MAAM,mBAAmB,YAAY;AAC3C,mBAAe,aAAa,cAAc,GAAG;AAC7C,QAAI,eAAe,IAAI;AACrB,UACE,CAAC,WAAW,SAAS,IAAI,KACzB,aAAa,SAAS,aAAa,IAAI,GACvC;AACA,sBAAc,cAAc,cAAc,aAAa,MAAM,UAAU;AAAA,MACzE,OAAO;AACL,sBAAc,cAAc,cAAc,YAAY,UAAU;AAAA,MAClE;AAAA,IACF,OAAO;AACL,oBAAc,cAAc,cAAc,YAAY,UAAU;AAAA,IAClE;AACA,QAAI,gBAAgB,cAAc;AAChC,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,QAAM,QAAQ,SAAS;AAAA,IACrB,UAAU;AAAA,IACV,cAAc;AAAA,IACd,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,EAAE,OAAO,YAAY;AAC9B;",
6
6
  "names": []
7
7
  }
@@ -46,7 +46,7 @@ const inputSchema = z.strictObject({
46
46
  )
47
47
  });
48
48
  const FileReadTool = {
49
- name: "View",
49
+ name: "Read",
50
50
  async description() {
51
51
  return DESCRIPTION;
52
52
  },