This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathSaveImageTool.ts
More file actions
278 lines (228 loc) · 8.9 KB
/
Copy pathSaveImageTool.ts
File metadata and controls
278 lines (228 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import path from "path"
import fs from "fs/promises"
import * as vscode from "vscode"
import { Task } from "../task/Task"
import { formatResponse } from "../prompts/responses"
import { getReadablePath } from "../../utils/path"
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
import { fileExistsAtPath } from "../../utils/fs"
import { BaseTool, ToolCallbacks } from "./BaseTool"
import type { ToolUse } from "../../shared/tools"
import { t } from "../../i18n"
interface SaveImageParams {
path: string
data?: string
source_path?: string
}
export class SaveImageTool extends BaseTool<"save_image"> {
readonly name = "save_image" as const
async execute(params: SaveImageParams, task: Task, callbacks: ToolCallbacks): Promise<void> {
const { path: relPath, data, source_path: sourcePath } = params
const { handleError, pushToolResult, askApproval } = callbacks
// Validate required parameters
if (!relPath) {
task.consecutiveMistakeCount++
task.recordToolError("save_image")
pushToolResult(await task.sayAndCreateMissingParamError("save_image", "path"))
return
}
// Need either source_path or data
if (!sourcePath && !data) {
task.consecutiveMistakeCount++
task.recordToolError("save_image")
await task.say(
"error",
t("tools:saveImage.missingSourceOrData", {
defaultValue:
"Either 'source_path' or 'data' parameter is required. Use 'source_path' for images from MCP tools, or 'data' for base64 data URLs.",
}),
)
task.didToolFailInCurrentTurn = true
pushToolResult(
formatResponse.toolError(
"Either 'source_path' or 'data' parameter is required. Use 'source_path' for images from MCP tools, or 'data' for base64 data URLs.",
),
)
return
}
// If source_path is provided, use it to copy the file
if (sourcePath) {
await this.copyFromSourcePath(task, sourcePath, relPath, callbacks)
return
}
// Otherwise, use the data parameter (base64 data URL)
// Validate the image data format first (to determine finalPath)
const base64Match = data!.match(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,(.+)$/)
if (!base64Match) {
await task.say("error", t("tools:saveImage.invalidDataFormat"))
task.didToolFailInCurrentTurn = true
pushToolResult(
formatResponse.toolError(
"Invalid image data format. Expected a base64 data URL (e.g., 'data:image/png;base64,...').",
),
)
return
}
const imageFormat = base64Match[1]
const base64Data = base64Match[2]
// Ensure the path has a valid image extension
let finalPath = relPath
if (!finalPath.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i)) {
// Add extension based on the data format
const ext = imageFormat === "jpeg" ? "jpg" : imageFormat === "svg+xml" ? "svg" : imageFormat
finalPath = `${finalPath}.${ext}`
}
// Validate access via .rooignore (using finalPath after extension is added)
const accessAllowed = task.rooIgnoreController?.validateAccess(finalPath)
if (!accessAllowed) {
await task.say("rooignore_error", finalPath)
pushToolResult(formatResponse.rooIgnoreError(finalPath))
return
}
// Check write protection (using finalPath after extension is added)
const isWriteProtected = task.rooProtectedController?.isWriteProtected(finalPath) || false
const fullPath = path.resolve(task.cwd, finalPath)
const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
const sharedMessageProps = {
tool: "saveImage" as const,
path: getReadablePath(task.cwd, finalPath),
isOutsideWorkspace,
isProtected: isWriteProtected,
}
try {
task.consecutiveMistakeCount = 0
const approvalMessage = JSON.stringify({
...sharedMessageProps,
content: `Save image to ${getReadablePath(task.cwd, finalPath)}`,
})
const didApprove = await askApproval("tool", approvalMessage, undefined, isWriteProtected)
if (!didApprove) {
return
}
// Convert base64 to buffer and save
const imageBuffer = Buffer.from(base64Data, "base64")
const absolutePath = path.resolve(task.cwd, finalPath)
const directory = path.dirname(absolutePath)
await fs.mkdir(directory, { recursive: true })
await fs.writeFile(absolutePath, imageBuffer)
// Track the file context
if (finalPath) {
await task.fileContextTracker.trackFileContext(finalPath, "roo_edited")
}
task.didEditFile = true
task.recordToolUsage("save_image")
const provider = task.providerRef.deref()
const fullImagePath = path.join(task.cwd, finalPath)
let imageUri = provider?.convertToWebviewUri?.(fullImagePath) ?? vscode.Uri.file(fullImagePath).toString()
// Add cache buster to force refresh
const cacheBuster = Date.now()
imageUri = imageUri.includes("?") ? `${imageUri}&t=${cacheBuster}` : `${imageUri}?t=${cacheBuster}`
await task.say("image", JSON.stringify({ imageUri, imagePath: fullImagePath }))
pushToolResult(formatResponse.toolResult(`Image saved to ${getReadablePath(task.cwd, finalPath)}`))
} catch (error) {
await handleError("saving image", error as Error)
}
}
/**
* Copy an image from a source path (typically from MCP temp storage) to the destination path.
* This is the preferred method for saving images from MCP tools as it avoids passing
* raw base64 through LLM context.
*/
private async copyFromSourcePath(
task: Task,
sourcePath: string,
destRelPath: string,
callbacks: ToolCallbacks,
): Promise<void> {
const { handleError, pushToolResult, askApproval } = callbacks
try {
// Check if source file exists
const sourceExists = await fileExistsAtPath(sourcePath)
if (!sourceExists) {
task.consecutiveMistakeCount++
task.recordToolError("save_image")
await task.say(
"error",
t("tools:saveImage.sourceNotFound", {
defaultValue: `Source image not found at path: ${sourcePath}`,
path: sourcePath,
}),
)
task.didToolFailInCurrentTurn = true
pushToolResult(formatResponse.toolError(`Source image not found at path: ${sourcePath}`))
return
}
// Get extension from source file
const sourceExt = path.extname(sourcePath).toLowerCase()
const validExtensions = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"]
if (!validExtensions.includes(sourceExt)) {
task.consecutiveMistakeCount++
task.recordToolError("save_image")
await task.say("error", t("tools:saveImage.invalidSourceFormat"))
task.didToolFailInCurrentTurn = true
pushToolResult(
formatResponse.toolError(
`Invalid source image format. Supported formats: ${validExtensions.join(", ")}`,
),
)
return
}
// Ensure the destination path has the correct extension
let finalPath = destRelPath
if (!finalPath.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i)) {
finalPath = `${finalPath}${sourceExt}`
}
// Validate access via .rooignore
const accessAllowed = task.rooIgnoreController?.validateAccess(finalPath)
if (!accessAllowed) {
await task.say("rooignore_error", finalPath)
pushToolResult(formatResponse.rooIgnoreError(finalPath))
return
}
// Check write protection
const isWriteProtected = task.rooProtectedController?.isWriteProtected(finalPath) || false
const fullPath = path.resolve(task.cwd, finalPath)
const isOutsideWorkspace = isPathOutsideWorkspace(fullPath)
const sharedMessageProps = {
tool: "saveImage" as const,
path: getReadablePath(task.cwd, finalPath),
isOutsideWorkspace,
isProtected: isWriteProtected,
}
task.consecutiveMistakeCount = 0
const approvalMessage = JSON.stringify({
...sharedMessageProps,
content: `Save image from ${sourcePath} to ${getReadablePath(task.cwd, finalPath)}`,
})
const didApprove = await askApproval("tool", approvalMessage, undefined, isWriteProtected)
if (!didApprove) {
return
}
// Create destination directory and copy file
const absolutePath = path.resolve(task.cwd, finalPath)
const directory = path.dirname(absolutePath)
await fs.mkdir(directory, { recursive: true })
await fs.copyFile(sourcePath, absolutePath)
// Track the file context
if (finalPath) {
await task.fileContextTracker.trackFileContext(finalPath, "roo_edited")
}
task.didEditFile = true
task.recordToolUsage("save_image")
const provider = task.providerRef.deref()
const fullImagePath = path.join(task.cwd, finalPath)
let imageUri = provider?.convertToWebviewUri?.(fullImagePath) ?? vscode.Uri.file(fullImagePath).toString()
// Add cache buster to force refresh
const cacheBuster = Date.now()
imageUri = imageUri.includes("?") ? `${imageUri}&t=${cacheBuster}` : `${imageUri}?t=${cacheBuster}`
await task.say("image", JSON.stringify({ imageUri, imagePath: fullImagePath }))
pushToolResult(formatResponse.toolResult(`Image saved to ${getReadablePath(task.cwd, finalPath)}`))
} catch (error) {
await handleError("saving image", error as Error)
}
}
override async handlePartial(task: Task, block: ToolUse<"save_image">): Promise<void> {
return
}
}
export const saveImageTool = new SaveImageTool()