|
| 1 | +import { DiffStrategy, DiffResult, ToolUse } from "../../../shared/tools" |
| 2 | +import { ToolProgressStatus } from "@roo-code/types" |
| 3 | +import { JupyterNotebookHandler } from "../../../integrations/misc/jupyter-notebook-handler" |
| 4 | +import { MultiSearchReplaceDiffStrategy } from "./multi-search-replace" |
| 5 | + |
| 6 | +export class JupyterNotebookDiffStrategy implements DiffStrategy { |
| 7 | + private fallbackStrategy: MultiSearchReplaceDiffStrategy |
| 8 | + |
| 9 | + constructor(fuzzyThreshold?: number, bufferLines?: number) { |
| 10 | + // Use MultiSearchReplaceDiffStrategy as fallback for non-cell operations |
| 11 | + this.fallbackStrategy = new MultiSearchReplaceDiffStrategy(fuzzyThreshold, bufferLines) |
| 12 | + } |
| 13 | + |
| 14 | + getName(): string { |
| 15 | + return "JupyterNotebookDiff" |
| 16 | + } |
| 17 | + |
| 18 | + getToolDescription(args: { cwd: string; toolOptions?: { [key: string]: string } }): string { |
| 19 | + return `## apply_diff (Jupyter Notebook Support) |
| 20 | +Description: Request to apply PRECISE, TARGETED modifications to Jupyter notebook (.ipynb) files. This tool supports both cell-level operations and content-level changes within cells. |
| 21 | +
|
| 22 | +For Jupyter notebooks, you can: |
| 23 | +1. Edit specific cells by cell number |
| 24 | +2. Add new cells |
| 25 | +3. Delete cells |
| 26 | +4. Apply standard search/replace within cells |
| 27 | +
|
| 28 | +Parameters: |
| 29 | +- path: (required) The path of the file to modify (relative to the current workspace directory ${args.cwd}) |
| 30 | +- diff: (required) The search/replace block or cell operation defining the changes. |
| 31 | +
|
| 32 | +Cell-Level Operations Format: |
| 33 | +\`\`\` |
| 34 | +<<<<<<< CELL_OPERATION |
| 35 | +:operation: [edit|add|delete] |
| 36 | +:cell_index: [cell number, 0-based] |
| 37 | +:cell_type: [code|markdown|raw] (required for 'add' operation) |
| 38 | +------- |
| 39 | +[content for edit/add operations] |
| 40 | +======= |
| 41 | +[new content for edit operations, empty for delete] |
| 42 | +>>>>>>> CELL_OPERATION |
| 43 | +\`\`\` |
| 44 | +
|
| 45 | +Standard Diff Format (for content within cells): |
| 46 | +\`\`\` |
| 47 | +<<<<<<< SEARCH |
| 48 | +:cell_index: [optional cell number to limit search] |
| 49 | +:start_line: [optional line number within cell] |
| 50 | +------- |
| 51 | +[exact content to find] |
| 52 | +======= |
| 53 | +[new content to replace with] |
| 54 | +>>>>>>> REPLACE |
| 55 | +\`\`\` |
| 56 | +
|
| 57 | +Examples: |
| 58 | +
|
| 59 | +1. Edit a specific cell: |
| 60 | +\`\`\` |
| 61 | +<<<<<<< CELL_OPERATION |
| 62 | +:operation: edit |
| 63 | +:cell_index: 2 |
| 64 | +------- |
| 65 | +# Old cell content |
| 66 | +print("Hello") |
| 67 | +======= |
| 68 | +# New cell content |
| 69 | +print("Hello, World!") |
| 70 | +>>>>>>> CELL_OPERATION |
| 71 | +\`\`\` |
| 72 | +
|
| 73 | +2. Add a new cell: |
| 74 | +\`\`\` |
| 75 | +<<<<<<< CELL_OPERATION |
| 76 | +:operation: add |
| 77 | +:cell_index: 1 |
| 78 | +:cell_type: code |
| 79 | +------- |
| 80 | +======= |
| 81 | +import numpy as np |
| 82 | +import pandas as pd |
| 83 | +>>>>>>> CELL_OPERATION |
| 84 | +\`\`\` |
| 85 | +
|
| 86 | +3. Delete a cell: |
| 87 | +\`\`\` |
| 88 | +<<<<<<< CELL_OPERATION |
| 89 | +:operation: delete |
| 90 | +:cell_index: 3 |
| 91 | +------- |
| 92 | +======= |
| 93 | +>>>>>>> CELL_OPERATION |
| 94 | +\`\`\` |
| 95 | +
|
| 96 | +4. Search and replace within a specific cell: |
| 97 | +\`\`\` |
| 98 | +<<<<<<< SEARCH |
| 99 | +:cell_index: 0 |
| 100 | +------- |
| 101 | +old_function() |
| 102 | +======= |
| 103 | +new_function() |
| 104 | +>>>>>>> REPLACE |
| 105 | +\`\`\` |
| 106 | +
|
| 107 | +Usage: |
| 108 | +<apply_diff> |
| 109 | +<path>notebook.ipynb</path> |
| 110 | +<diff> |
| 111 | +Your cell operation or search/replace content here |
| 112 | +</diff> |
| 113 | +</apply_diff>` |
| 114 | + } |
| 115 | + |
| 116 | + async applyDiff( |
| 117 | + originalContent: string, |
| 118 | + diffContent: string, |
| 119 | + _paramStartLine?: number, |
| 120 | + _paramEndLine?: number, |
| 121 | + ): Promise<DiffResult> { |
| 122 | + // Check if this is a Jupyter notebook by trying to parse it |
| 123 | + let handler: JupyterNotebookHandler |
| 124 | + try { |
| 125 | + handler = new JupyterNotebookHandler("", originalContent) |
| 126 | + } catch (error) { |
| 127 | + // Not a valid notebook, fall back to standard diff |
| 128 | + return this.fallbackStrategy.applyDiff(originalContent, diffContent, _paramStartLine, _paramEndLine) |
| 129 | + } |
| 130 | + |
| 131 | + // Check if this is a cell operation |
| 132 | + const cellOperationMatch = diffContent.match( |
| 133 | + /<<<<<<< CELL_OPERATION\s*\n(?::operation:\s*(edit|add|delete)\s*\n)?(?::cell_index:\s*(\d+)\s*\n)?(?::cell_type:\s*(code|markdown|raw)\s*\n)?(?:-------\s*\n)?([\s\S]*?)(?:\n)?=======\s*\n([\s\S]*?)(?:\n)?>>>>>>> CELL_OPERATION/, |
| 134 | + ) |
| 135 | + |
| 136 | + if (cellOperationMatch) { |
| 137 | + const operation = cellOperationMatch[1] |
| 138 | + const cellIndex = parseInt(cellOperationMatch[2] || "0") |
| 139 | + const cellType = cellOperationMatch[3] as "code" | "markdown" | "raw" |
| 140 | + const searchContent = cellOperationMatch[4] || "" |
| 141 | + const replaceContent = cellOperationMatch[5] || "" |
| 142 | + |
| 143 | + let success = false |
| 144 | + let error: string | undefined |
| 145 | + |
| 146 | + switch (operation) { |
| 147 | + case "edit": |
| 148 | + if (cellIndex >= 0 && cellIndex < handler.getCellCount()) { |
| 149 | + success = handler.updateCell(cellIndex, replaceContent) |
| 150 | + if (!success) { |
| 151 | + error = `Failed to update cell ${cellIndex}` |
| 152 | + } |
| 153 | + } else { |
| 154 | + error = `Cell index ${cellIndex} is out of range (0-${handler.getCellCount() - 1})` |
| 155 | + } |
| 156 | + break |
| 157 | + |
| 158 | + case "add": |
| 159 | + if (!cellType) { |
| 160 | + error = "Cell type is required for add operation" |
| 161 | + } else { |
| 162 | + success = handler.insertCell(cellIndex, cellType, replaceContent) |
| 163 | + if (!success) { |
| 164 | + error = `Failed to insert cell at index ${cellIndex}` |
| 165 | + } |
| 166 | + } |
| 167 | + break |
| 168 | + |
| 169 | + case "delete": |
| 170 | + success = handler.deleteCell(cellIndex) |
| 171 | + if (!success) { |
| 172 | + error = `Failed to delete cell ${cellIndex}` |
| 173 | + } |
| 174 | + break |
| 175 | + |
| 176 | + default: |
| 177 | + error = `Unknown operation: ${operation}` |
| 178 | + } |
| 179 | + |
| 180 | + if (success) { |
| 181 | + return { |
| 182 | + success: true, |
| 183 | + content: handler.toJSON(), |
| 184 | + } |
| 185 | + } else { |
| 186 | + return { |
| 187 | + success: false, |
| 188 | + error: error || "Cell operation failed", |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + // Check if this is a cell-specific search/replace |
| 194 | + const cellSearchMatch = diffContent.match( |
| 195 | + /<<<<<<< SEARCH\s*\n(?::cell_index:\s*(\d+)\s*\n)?(?::start_line:\s*(\d+)\s*\n)?(?:-------\s*\n)?([\s\S]*?)(?:\n)?=======\s*\n([\s\S]*?)(?:\n)?>>>>>>> REPLACE/, |
| 196 | + ) |
| 197 | + |
| 198 | + if (cellSearchMatch) { |
| 199 | + const cellIndex = cellSearchMatch[1] ? parseInt(cellSearchMatch[1]) : undefined |
| 200 | + const searchContent = cellSearchMatch[3] || "" |
| 201 | + const replaceContent = cellSearchMatch[4] || "" |
| 202 | + |
| 203 | + if (cellIndex !== undefined) { |
| 204 | + // Apply diff to specific cell |
| 205 | + const success = handler.applyCellDiff(cellIndex, searchContent, replaceContent) |
| 206 | + if (success) { |
| 207 | + return { |
| 208 | + success: true, |
| 209 | + content: handler.toJSON(), |
| 210 | + } |
| 211 | + } else { |
| 212 | + return { |
| 213 | + success: false, |
| 214 | + error: `Failed to apply diff to cell ${cellIndex}. Content not found or cell doesn't exist.`, |
| 215 | + } |
| 216 | + } |
| 217 | + } else { |
| 218 | + // Search across all cells |
| 219 | + let applied = false |
| 220 | + for (let i = 0; i < handler.getCellCount(); i++) { |
| 221 | + if (handler.applyCellDiff(i, searchContent, replaceContent)) { |
| 222 | + applied = true |
| 223 | + // Continue to apply to all matching cells |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + if (applied) { |
| 228 | + return { |
| 229 | + success: true, |
| 230 | + content: handler.toJSON(), |
| 231 | + } |
| 232 | + } else { |
| 233 | + return { |
| 234 | + success: false, |
| 235 | + error: "Search content not found in any cell", |
| 236 | + } |
| 237 | + } |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + // Fall back to standard diff strategy for the text representation |
| 242 | + const textRepresentation = handler.extractTextWithCellMarkers() |
| 243 | + const result = await this.fallbackStrategy.applyDiff( |
| 244 | + textRepresentation, |
| 245 | + diffContent, |
| 246 | + _paramStartLine, |
| 247 | + _paramEndLine, |
| 248 | + ) |
| 249 | + |
| 250 | + if (result.success && result.content) { |
| 251 | + // Convert back from text representation to notebook format |
| 252 | + // This is a simplified approach - in production, we'd need more sophisticated parsing |
| 253 | + return { |
| 254 | + success: true, |
| 255 | + content: handler.toJSON(), |
| 256 | + } |
| 257 | + } |
| 258 | + |
| 259 | + return result |
| 260 | + } |
| 261 | + |
| 262 | + getProgressStatus(toolUse: ToolUse, result?: DiffResult): ToolProgressStatus { |
| 263 | + const diffContent = toolUse.params.diff |
| 264 | + if (diffContent) { |
| 265 | + const icon = "notebook" |
| 266 | + if (diffContent.includes("CELL_OPERATION")) { |
| 267 | + const operation = diffContent.match(/:operation:\s*(edit|add|delete)/)?.[1] |
| 268 | + return { icon, text: operation || "cell" } |
| 269 | + } else { |
| 270 | + return this.fallbackStrategy.getProgressStatus(toolUse, result) |
| 271 | + } |
| 272 | + } |
| 273 | + return {} |
| 274 | + } |
| 275 | +} |
0 commit comments