@cloudflare/think 0.20.1 → 0.21.0
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.
- package/README.md +69 -39
- package/dist/classPrivateFieldSet2-DwGJfC3w.js +27 -0
- package/dist/extensions/index.js +2 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/fetch-9f1p8UrI.js +772 -0
- package/dist/fetch-9f1p8UrI.js.map +1 -0
- package/dist/{fetch-By3eIQ-a.d.ts → fetch-C7s1mpgg.d.ts} +70 -20
- package/dist/{index-CmhSKa6U.d.ts → index-Cjq_e9F2.d.ts} +55 -75
- package/dist/{manager-Cb3DNZgp.js → manager-BubfmA3q.js} +3 -28
- package/dist/{manager-Cb3DNZgp.js.map → manager-BubfmA3q.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +3 -4
- package/dist/think.js +79 -97
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +19 -24
- package/dist/tools/execute.js +20 -40
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +2 -2
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/fetch.d.ts +2 -4
- package/dist/tools/fetch.js +1 -645
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +4 -4
- package/docs/index.md +31 -16
- package/docs/multi-chat.md +22 -59
- package/docs/sub-agents.md +13 -13
- package/docs/tools.md +90 -109
- package/package.json +7 -11
- package/dist/tools/fetch.js.map +0 -1
- package/dist/tools/workspace.d.ts +0 -60
- package/dist/tools/workspace.js +0 -869
- package/dist/tools/workspace.js.map +0 -1
- package/dist/workspace-CNeXc2vl.d.ts +0 -201
package/dist/tools/workspace.js
DELETED
|
@@ -1,869 +0,0 @@
|
|
|
1
|
-
import { tool } from "ai";
|
|
2
|
-
import { Bash } from "just-bash";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
//#region src/tools/workspace.ts
|
|
5
|
-
function workspaceReadOps(ws) {
|
|
6
|
-
return {
|
|
7
|
-
readFile: (path) => ws.readFile(path),
|
|
8
|
-
readFileBytes: (path) => ws.readFileBytes(path),
|
|
9
|
-
stat: (path) => ws.stat(path)
|
|
10
|
-
};
|
|
11
|
-
}
|
|
12
|
-
function workspaceWriteOps(ws) {
|
|
13
|
-
return {
|
|
14
|
-
writeFile: (path, content) => ws.writeFile(path, content),
|
|
15
|
-
mkdir: (path, opts) => ws.mkdir(path, opts)
|
|
16
|
-
};
|
|
17
|
-
}
|
|
18
|
-
function workspaceEditOps(ws) {
|
|
19
|
-
return {
|
|
20
|
-
readFile: (path) => ws.readFile(path),
|
|
21
|
-
writeFile: (path, content) => ws.writeFile(path, content)
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
function workspaceListOps(ws) {
|
|
25
|
-
return { readDir: (dir, opts) => ws.readDir(dir, opts) };
|
|
26
|
-
}
|
|
27
|
-
function workspaceFindOps(ws) {
|
|
28
|
-
return { glob: (pattern) => ws.glob(pattern) };
|
|
29
|
-
}
|
|
30
|
-
function workspaceDeleteOps(ws) {
|
|
31
|
-
return { rm: (path, opts) => ws.rm(path, opts) };
|
|
32
|
-
}
|
|
33
|
-
function workspaceGrepOps(ws) {
|
|
34
|
-
return {
|
|
35
|
-
glob: (pattern) => ws.glob(pattern),
|
|
36
|
-
readFile: (path) => ws.readFile(path)
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
function workspaceBashOps(ws) {
|
|
40
|
-
const maybeBytesWriter = ws;
|
|
41
|
-
return {
|
|
42
|
-
readDir: (dir, opts) => ws.readDir(dir, opts),
|
|
43
|
-
readFileBytes: (path) => ws.readFileBytes(path),
|
|
44
|
-
writeFile: (path, content) => ws.writeFile(path, content),
|
|
45
|
-
writeFileBytes: maybeBytesWriter.writeFileBytes ? (path, content) => maybeBytesWriter.writeFileBytes(path, content) : void 0,
|
|
46
|
-
mkdir: (path, opts) => ws.mkdir(path, opts),
|
|
47
|
-
rm: (path, opts) => ws.rm(path, opts)
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Create a complete set of AI SDK tools backed by a workspace.
|
|
52
|
-
*
|
|
53
|
-
* Accepts either a concrete `Workspace` from `@cloudflare/shell` or any
|
|
54
|
-
* `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a
|
|
55
|
-
* shared workspace owned by a parent DO.
|
|
56
|
-
*
|
|
57
|
-
* ```ts
|
|
58
|
-
* import { Workspace } from "@cloudflare/shell";
|
|
59
|
-
* import { createWorkspaceTools } from "@cloudflare/think";
|
|
60
|
-
*
|
|
61
|
-
* class MyAgent extends Agent<Env> {
|
|
62
|
-
* workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });
|
|
63
|
-
*
|
|
64
|
-
* async onChatMessage() {
|
|
65
|
-
* const tools = createWorkspaceTools(this.workspace);
|
|
66
|
-
* const result = streamText({ model, tools, messages });
|
|
67
|
-
* return result.toUIMessageStreamResponse();
|
|
68
|
-
* }
|
|
69
|
-
* }
|
|
70
|
-
* ```
|
|
71
|
-
*/
|
|
72
|
-
function createWorkspaceTools(workspace, options = {}) {
|
|
73
|
-
const tools = {
|
|
74
|
-
read: createReadTool({ ops: workspaceReadOps(workspace) }),
|
|
75
|
-
write: createWriteTool({ ops: workspaceWriteOps(workspace) }),
|
|
76
|
-
edit: createEditTool({ ops: workspaceEditOps(workspace) }),
|
|
77
|
-
list: createListTool({ ops: workspaceListOps(workspace) }),
|
|
78
|
-
find: createFindTool({ ops: workspaceFindOps(workspace) }),
|
|
79
|
-
grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),
|
|
80
|
-
delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })
|
|
81
|
-
};
|
|
82
|
-
if (options.bash !== false) tools.bash = createBashTool({
|
|
83
|
-
...typeof options.bash === "object" ? options.bash : {},
|
|
84
|
-
ops: workspaceBashOps(workspace)
|
|
85
|
-
});
|
|
86
|
-
return tools;
|
|
87
|
-
}
|
|
88
|
-
const MAX_LINES = 2e3;
|
|
89
|
-
const MAX_LINE_LENGTH = 2e3;
|
|
90
|
-
const MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;
|
|
91
|
-
function createReadTool(options) {
|
|
92
|
-
const { ops } = options;
|
|
93
|
-
return tool({
|
|
94
|
-
description: "Read a workspace file. Text files return line-numbered content. Images and PDFs are passed to capable models as file content. Use offset and limit for large text files. Returns null if the file does not exist.",
|
|
95
|
-
inputSchema: z.object({
|
|
96
|
-
path: z.string().describe("Absolute path to the file"),
|
|
97
|
-
offset: z.number().int().min(1).optional().describe("1-indexed line number to start reading from"),
|
|
98
|
-
limit: z.number().int().min(1).optional().describe("Number of lines to read")
|
|
99
|
-
}),
|
|
100
|
-
execute: async ({ path, offset, limit }) => {
|
|
101
|
-
const stat = await ops.stat(path);
|
|
102
|
-
if (!stat) return { error: `File not found: ${path}` };
|
|
103
|
-
if (stat.type === "directory") return { error: `${path} is a directory, not a file` };
|
|
104
|
-
const mediaType = await detectWorkspaceMediaType({
|
|
105
|
-
ops,
|
|
106
|
-
path,
|
|
107
|
-
stat
|
|
108
|
-
});
|
|
109
|
-
if (mediaType.startsWith("image/")) return {
|
|
110
|
-
kind: "image",
|
|
111
|
-
path,
|
|
112
|
-
name: stat.name,
|
|
113
|
-
mediaType,
|
|
114
|
-
sizeBytes: stat.size
|
|
115
|
-
};
|
|
116
|
-
if (mediaType === "application/pdf") return {
|
|
117
|
-
kind: "file",
|
|
118
|
-
path,
|
|
119
|
-
name: stat.name,
|
|
120
|
-
mediaType,
|
|
121
|
-
sizeBytes: stat.size
|
|
122
|
-
};
|
|
123
|
-
if (!isTextMediaType(mediaType)) return {
|
|
124
|
-
kind: "binary",
|
|
125
|
-
path,
|
|
126
|
-
name: stat.name,
|
|
127
|
-
mediaType,
|
|
128
|
-
sizeBytes: stat.size,
|
|
129
|
-
unsupported: true
|
|
130
|
-
};
|
|
131
|
-
return readTextWithLineNumbers({
|
|
132
|
-
ops,
|
|
133
|
-
path,
|
|
134
|
-
offset,
|
|
135
|
-
limit
|
|
136
|
-
});
|
|
137
|
-
},
|
|
138
|
-
toModelOutput: async ({ input, output }) => {
|
|
139
|
-
const replayOutput = output;
|
|
140
|
-
if (!isRecord(replayOutput)) return {
|
|
141
|
-
type: "text",
|
|
142
|
-
value: String(replayOutput)
|
|
143
|
-
};
|
|
144
|
-
if (typeof replayOutput.error === "string") return {
|
|
145
|
-
type: "error-text",
|
|
146
|
-
value: replayOutput.error
|
|
147
|
-
};
|
|
148
|
-
if (typeof replayOutput.content === "string") return {
|
|
149
|
-
type: "text",
|
|
150
|
-
value: replayOutput.content
|
|
151
|
-
};
|
|
152
|
-
if (replayOutput.kind === "binary") return {
|
|
153
|
-
type: "json",
|
|
154
|
-
value: toJSONValue(replayOutput)
|
|
155
|
-
};
|
|
156
|
-
if (!isModelFileReadOutput(replayOutput)) return {
|
|
157
|
-
type: "json",
|
|
158
|
-
value: toJSONValue(replayOutput)
|
|
159
|
-
};
|
|
160
|
-
if (!isReadToolInput(input)) return {
|
|
161
|
-
type: "json",
|
|
162
|
-
value: toJSONValue(replayOutput)
|
|
163
|
-
};
|
|
164
|
-
const bytes = await ops.readFileBytes(input.path);
|
|
165
|
-
if (bytes === null) return {
|
|
166
|
-
type: "error-text",
|
|
167
|
-
value: `Could not read file bytes: ${input.path}`
|
|
168
|
-
};
|
|
169
|
-
if (bytes.byteLength > MAX_MODEL_FILE_BYTES) return {
|
|
170
|
-
type: "error-text",
|
|
171
|
-
value: `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}), but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`
|
|
172
|
-
};
|
|
173
|
-
const data = uint8ArrayToBase64(bytes);
|
|
174
|
-
const note = `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}).`;
|
|
175
|
-
if (replayOutput.kind === "image") return {
|
|
176
|
-
type: "content",
|
|
177
|
-
value: [{
|
|
178
|
-
type: "text",
|
|
179
|
-
text: note
|
|
180
|
-
}, {
|
|
181
|
-
type: "image-data",
|
|
182
|
-
data,
|
|
183
|
-
mediaType: replayOutput.mediaType
|
|
184
|
-
}]
|
|
185
|
-
};
|
|
186
|
-
return {
|
|
187
|
-
type: "content",
|
|
188
|
-
value: [{
|
|
189
|
-
type: "text",
|
|
190
|
-
text: note
|
|
191
|
-
}, {
|
|
192
|
-
type: "file-data",
|
|
193
|
-
data,
|
|
194
|
-
mediaType: replayOutput.mediaType,
|
|
195
|
-
filename: replayOutput.name
|
|
196
|
-
}]
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
function isRecord(value) {
|
|
202
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
203
|
-
}
|
|
204
|
-
function isModelFileReadOutput(value) {
|
|
205
|
-
return (value.kind === "image" || value.kind === "file") && typeof value.path === "string" && typeof value.name === "string" && typeof value.mediaType === "string";
|
|
206
|
-
}
|
|
207
|
-
function isReadToolInput(value) {
|
|
208
|
-
return isRecord(value) && typeof value.path === "string";
|
|
209
|
-
}
|
|
210
|
-
function toJSONValue(value) {
|
|
211
|
-
try {
|
|
212
|
-
const json = JSON.stringify(value);
|
|
213
|
-
return json === void 0 ? null : JSON.parse(json);
|
|
214
|
-
} catch {
|
|
215
|
-
return String(value);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
function readTextWithLineNumbers({ ops, path, offset, limit }) {
|
|
219
|
-
return Promise.resolve(ops.readFile(path)).then((content) => {
|
|
220
|
-
if (content === null) return { error: `Could not read file: ${path}` };
|
|
221
|
-
const allLines = content.split("\n");
|
|
222
|
-
const totalLines = allLines.length;
|
|
223
|
-
const startLine = offset ? offset - 1 : 0;
|
|
224
|
-
const endLine = limit ? startLine + limit : allLines.length;
|
|
225
|
-
const numbered = allLines.slice(startLine, endLine).map((line, i) => {
|
|
226
|
-
return `${startLine + i + 1}\t${line.length > MAX_LINE_LENGTH ? line.slice(0, MAX_LINE_LENGTH) + "... (truncated)" : line}`;
|
|
227
|
-
});
|
|
228
|
-
let output;
|
|
229
|
-
if (numbered.length > MAX_LINES) output = numbered.slice(0, MAX_LINES).join("\n") + `\n... (${numbered.length - MAX_LINES} more lines truncated)`;
|
|
230
|
-
else output = numbered.join("\n");
|
|
231
|
-
const result = {
|
|
232
|
-
path,
|
|
233
|
-
content: output,
|
|
234
|
-
totalLines
|
|
235
|
-
};
|
|
236
|
-
if (offset || limit) {
|
|
237
|
-
result.fromLine = startLine + 1;
|
|
238
|
-
result.toLine = Math.min(endLine, totalLines);
|
|
239
|
-
}
|
|
240
|
-
return result;
|
|
241
|
-
});
|
|
242
|
-
}
|
|
243
|
-
async function detectWorkspaceMediaType({ ops, path, stat }) {
|
|
244
|
-
const statMime = normalizeMediaType(stat.mimeType);
|
|
245
|
-
if (statMime && !isGenericMediaType(statMime)) return statMime;
|
|
246
|
-
const bytes = await ops.readFileBytes(path);
|
|
247
|
-
if (bytes === null) return statMime || "application/octet-stream";
|
|
248
|
-
const sniffed = sniffMediaType(bytes);
|
|
249
|
-
if (sniffed) return sniffed;
|
|
250
|
-
return looksLikeText(bytes) ? "text/plain" : "application/octet-stream";
|
|
251
|
-
}
|
|
252
|
-
function normalizeMediaType(mediaType) {
|
|
253
|
-
return mediaType?.split(";")[0]?.trim().toLowerCase() || null;
|
|
254
|
-
}
|
|
255
|
-
function isGenericMediaType(mediaType) {
|
|
256
|
-
return mediaType === "application/octet-stream" || mediaType === "binary/octet-stream";
|
|
257
|
-
}
|
|
258
|
-
function isTextMediaType(mediaType) {
|
|
259
|
-
return mediaType.startsWith("text/") || mediaType === "application/json" || mediaType === "application/javascript" || mediaType === "application/typescript" || mediaType === "application/xml" || mediaType === "application/x-javascript" || mediaType.endsWith("+json") || mediaType.endsWith("+xml");
|
|
260
|
-
}
|
|
261
|
-
function sniffMediaType(bytes) {
|
|
262
|
-
if (startsWith(bytes, [
|
|
263
|
-
137,
|
|
264
|
-
80,
|
|
265
|
-
78,
|
|
266
|
-
71,
|
|
267
|
-
13,
|
|
268
|
-
10,
|
|
269
|
-
26,
|
|
270
|
-
10
|
|
271
|
-
])) return "image/png";
|
|
272
|
-
if (startsWith(bytes, [
|
|
273
|
-
255,
|
|
274
|
-
216,
|
|
275
|
-
255
|
|
276
|
-
])) return "image/jpeg";
|
|
277
|
-
if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a")) return "image/gif";
|
|
278
|
-
if (startsWithAscii(bytes, "RIFF") && asciiAt(bytes, 8, 12) === "WEBP") return "image/webp";
|
|
279
|
-
if (startsWithAscii(bytes, "%PDF-")) return "application/pdf";
|
|
280
|
-
if (looksLikeSvg(bytes)) return "image/svg+xml";
|
|
281
|
-
return null;
|
|
282
|
-
}
|
|
283
|
-
function startsWith(bytes, prefix) {
|
|
284
|
-
if (bytes.length < prefix.length) return false;
|
|
285
|
-
return prefix.every((byte, index) => bytes[index] === byte);
|
|
286
|
-
}
|
|
287
|
-
function startsWithAscii(bytes, prefix) {
|
|
288
|
-
return asciiAt(bytes, 0, prefix.length) === prefix;
|
|
289
|
-
}
|
|
290
|
-
function asciiAt(bytes, start, end) {
|
|
291
|
-
return String.fromCharCode(...bytes.subarray(start, end));
|
|
292
|
-
}
|
|
293
|
-
function looksLikeSvg(bytes) {
|
|
294
|
-
const prefix = new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 512))).trimStart().toLowerCase();
|
|
295
|
-
return prefix.startsWith("<svg") || prefix.includes("<svg");
|
|
296
|
-
}
|
|
297
|
-
function looksLikeText(bytes) {
|
|
298
|
-
if (bytes.length === 0) return true;
|
|
299
|
-
if (bytes.includes(0)) return false;
|
|
300
|
-
const text = new TextDecoder().decode(bytes.subarray(0, 4096));
|
|
301
|
-
if (text.length === 0) return true;
|
|
302
|
-
let replacementChars = 0;
|
|
303
|
-
for (const char of text) if (char === "�") replacementChars++;
|
|
304
|
-
return replacementChars / text.length < .01;
|
|
305
|
-
}
|
|
306
|
-
function uint8ArrayToBase64(bytes) {
|
|
307
|
-
let binary = "";
|
|
308
|
-
const chunkSize = 32768;
|
|
309
|
-
for (let i = 0; i < bytes.length; i += chunkSize) binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
|
|
310
|
-
return btoa(binary);
|
|
311
|
-
}
|
|
312
|
-
function createWriteTool(options) {
|
|
313
|
-
const { ops } = options;
|
|
314
|
-
return tool({
|
|
315
|
-
description: "Write content to a file. Creates the file if it does not exist, overwrites if it does. Parent directories are created automatically.",
|
|
316
|
-
inputSchema: z.object({
|
|
317
|
-
path: z.string().describe("Absolute path to the file"),
|
|
318
|
-
content: z.string().describe("Content to write to the file")
|
|
319
|
-
}),
|
|
320
|
-
execute: async ({ path, content }) => {
|
|
321
|
-
const parent = path.replace(/\/[^/]+$/, "");
|
|
322
|
-
if (parent && parent !== "/") await ops.mkdir(parent, { recursive: true });
|
|
323
|
-
await ops.writeFile(path, content);
|
|
324
|
-
const lines = content.split("\n").length;
|
|
325
|
-
return {
|
|
326
|
-
path,
|
|
327
|
-
bytesWritten: new TextEncoder().encode(content).byteLength,
|
|
328
|
-
lines
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
});
|
|
332
|
-
}
|
|
333
|
-
function createEditTool(options) {
|
|
334
|
-
const { ops } = options;
|
|
335
|
-
return tool({
|
|
336
|
-
description: "Make a targeted edit to a file by replacing an exact string match. Provide the old_string to find and new_string to replace it with. The old_string must match exactly (including whitespace and indentation). Use an empty old_string with new_string to create a new file.",
|
|
337
|
-
inputSchema: z.object({
|
|
338
|
-
path: z.string().describe("Absolute path to the file"),
|
|
339
|
-
old_string: z.string().describe("Exact text to find and replace. Empty string to create a new file."),
|
|
340
|
-
new_string: z.string().describe("Replacement text")
|
|
341
|
-
}),
|
|
342
|
-
execute: async ({ path, old_string, new_string }) => {
|
|
343
|
-
if (old_string === "") {
|
|
344
|
-
if (await ops.readFile(path) !== null) return { error: "File already exists. Provide old_string to edit, or use the write tool to overwrite." };
|
|
345
|
-
await ops.writeFile(path, new_string);
|
|
346
|
-
return {
|
|
347
|
-
path,
|
|
348
|
-
created: true,
|
|
349
|
-
lines: new_string.split("\n").length
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
const content = await ops.readFile(path);
|
|
353
|
-
if (content === null) return { error: `File not found: ${path}` };
|
|
354
|
-
const occurrences = countOccurrences(content, old_string);
|
|
355
|
-
if (occurrences === 0) {
|
|
356
|
-
const fuzzyResult = fuzzyReplace(content, old_string, new_string);
|
|
357
|
-
if (fuzzyResult === "ambiguous") return { error: "old_string matches multiple locations after whitespace normalization. Include more surrounding context to make the match unique." };
|
|
358
|
-
if (fuzzyResult !== null) {
|
|
359
|
-
await ops.writeFile(path, fuzzyResult);
|
|
360
|
-
return {
|
|
361
|
-
path,
|
|
362
|
-
replaced: true,
|
|
363
|
-
fuzzyMatch: true,
|
|
364
|
-
lines: fuzzyResult.split("\n").length
|
|
365
|
-
};
|
|
366
|
-
}
|
|
367
|
-
return { error: "old_string not found in file. Make sure it matches exactly, including whitespace and indentation. Read the file first to verify." };
|
|
368
|
-
}
|
|
369
|
-
if (occurrences > 1) return { error: `old_string appears ${occurrences} times in the file. Include more surrounding context to make the match unique.` };
|
|
370
|
-
const newContent = content.replace(old_string, new_string);
|
|
371
|
-
await ops.writeFile(path, newContent);
|
|
372
|
-
return {
|
|
373
|
-
path,
|
|
374
|
-
replaced: true,
|
|
375
|
-
lines: newContent.split("\n").length
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
});
|
|
379
|
-
}
|
|
380
|
-
function countOccurrences(text, search) {
|
|
381
|
-
let count = 0;
|
|
382
|
-
let pos = 0;
|
|
383
|
-
while (true) {
|
|
384
|
-
const idx = text.indexOf(search, pos);
|
|
385
|
-
if (idx === -1) break;
|
|
386
|
-
count++;
|
|
387
|
-
pos = idx + 1;
|
|
388
|
-
}
|
|
389
|
-
return count;
|
|
390
|
-
}
|
|
391
|
-
/**
|
|
392
|
-
* Fuzzy replacement: normalize whitespace in both the file content
|
|
393
|
-
* and the search string, find the match, then replace the corresponding
|
|
394
|
-
* region in the original content.
|
|
395
|
-
*/
|
|
396
|
-
function fuzzyReplace(content, oldStr, newStr) {
|
|
397
|
-
const normalizedContent = normalizeWhitespace(content);
|
|
398
|
-
const normalizedSearch = normalizeWhitespace(oldStr);
|
|
399
|
-
if (!normalizedSearch) return null;
|
|
400
|
-
const idx = normalizedContent.indexOf(normalizedSearch);
|
|
401
|
-
if (idx === -1) return null;
|
|
402
|
-
if (normalizedContent.indexOf(normalizedSearch, idx + normalizedSearch.length) !== -1) return "ambiguous";
|
|
403
|
-
const originalStart = mapToOriginal(content, idx);
|
|
404
|
-
const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);
|
|
405
|
-
return content.slice(0, originalStart) + newStr + content.slice(originalEnd);
|
|
406
|
-
}
|
|
407
|
-
function normalizeWhitespace(s) {
|
|
408
|
-
return s.replace(/[ \t]+/g, " ").replace(/\r\n/g, "\n");
|
|
409
|
-
}
|
|
410
|
-
/**
|
|
411
|
-
* Map a position in the normalized string back to the original string.
|
|
412
|
-
* Walks both strings char-by-char, skipping extra whitespace in the original.
|
|
413
|
-
*/
|
|
414
|
-
function mapToOriginal(original, normalizedPos) {
|
|
415
|
-
let ni = 0;
|
|
416
|
-
let oi = 0;
|
|
417
|
-
while (ni < normalizedPos && oi < original.length) {
|
|
418
|
-
const oc = original[oi];
|
|
419
|
-
if (oc === "\r" && original[oi + 1] === "\n") {
|
|
420
|
-
oi += 2;
|
|
421
|
-
ni += 1;
|
|
422
|
-
} else if (oc === " " || oc === " ") {
|
|
423
|
-
oi++;
|
|
424
|
-
while (oi < original.length && (original[oi] === " " || original[oi] === " ")) oi++;
|
|
425
|
-
ni++;
|
|
426
|
-
} else {
|
|
427
|
-
oi++;
|
|
428
|
-
ni++;
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
return oi;
|
|
432
|
-
}
|
|
433
|
-
function createListTool(options) {
|
|
434
|
-
const { ops } = options;
|
|
435
|
-
return tool({
|
|
436
|
-
description: "List files and directories in a given path. Returns names, types, and sizes for each entry.",
|
|
437
|
-
inputSchema: z.object({
|
|
438
|
-
path: z.string().default("/").describe("Absolute path to the directory to list"),
|
|
439
|
-
limit: z.number().int().min(1).max(1e3).optional().describe("Maximum number of entries to return (default: 200)"),
|
|
440
|
-
offset: z.number().int().min(0).optional().describe("Number of entries to skip (for pagination)")
|
|
441
|
-
}),
|
|
442
|
-
execute: async ({ path, limit, offset }) => {
|
|
443
|
-
const maxEntries = limit ?? 200;
|
|
444
|
-
const entries = await ops.readDir(path, {
|
|
445
|
-
limit: maxEntries,
|
|
446
|
-
offset: offset ?? 0
|
|
447
|
-
});
|
|
448
|
-
const formatted = entries.map((entry) => {
|
|
449
|
-
const suffix = entry.type === "directory" ? "/" : "";
|
|
450
|
-
const sizeStr = entry.type === "file" ? ` (${formatSize(entry.size)})` : "";
|
|
451
|
-
return `${entry.name}${suffix}${sizeStr}`;
|
|
452
|
-
});
|
|
453
|
-
return {
|
|
454
|
-
path,
|
|
455
|
-
count: entries.length,
|
|
456
|
-
entries: formatted
|
|
457
|
-
};
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
function formatSize(bytes) {
|
|
462
|
-
if (bytes < 1024) return `${bytes} B`;
|
|
463
|
-
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
464
|
-
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
465
|
-
}
|
|
466
|
-
function createFindTool(options) {
|
|
467
|
-
const { ops } = options;
|
|
468
|
-
return tool({
|
|
469
|
-
description: "Find files matching a glob pattern. Supports standard glob syntax: * matches any file, ** matches directories recursively, ? matches a single character. Returns matching file paths with types and sizes.",
|
|
470
|
-
inputSchema: z.object({ pattern: z.string().describe("Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")") }),
|
|
471
|
-
execute: async ({ pattern }) => {
|
|
472
|
-
const matches = await ops.glob(pattern);
|
|
473
|
-
const MAX_RESULTS = 200;
|
|
474
|
-
const truncated = matches.length > MAX_RESULTS;
|
|
475
|
-
const formatted = matches.slice(0, MAX_RESULTS).map((entry) => {
|
|
476
|
-
const suffix = entry.type === "directory" ? "/" : "";
|
|
477
|
-
return `${entry.path}${suffix}`;
|
|
478
|
-
});
|
|
479
|
-
const result = {
|
|
480
|
-
pattern,
|
|
481
|
-
count: matches.length,
|
|
482
|
-
files: formatted
|
|
483
|
-
};
|
|
484
|
-
if (truncated) {
|
|
485
|
-
result.truncated = true;
|
|
486
|
-
result.showing = MAX_RESULTS;
|
|
487
|
-
}
|
|
488
|
-
return result;
|
|
489
|
-
}
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
const MAX_MATCHES = 200;
|
|
493
|
-
const MAX_FILE_SIZE = 1048576;
|
|
494
|
-
function createGrepTool(options) {
|
|
495
|
-
const { ops } = options;
|
|
496
|
-
return tool({
|
|
497
|
-
description: "Search file contents using a regular expression or fixed string. Returns matching lines with file paths and line numbers. Searches all files matching the include glob, or all files if not specified.",
|
|
498
|
-
inputSchema: z.object({
|
|
499
|
-
query: z.string().describe("Search pattern (regex or fixed string)"),
|
|
500
|
-
include: z.string().optional().describe("Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\""),
|
|
501
|
-
fixedString: z.boolean().optional().describe("If true, treat query as a literal string instead of regex"),
|
|
502
|
-
caseSensitive: z.boolean().optional().describe("If true, search is case-sensitive (default: false)"),
|
|
503
|
-
contextLines: z.number().int().min(0).max(10).optional().describe("Number of context lines around each match (default: 0)")
|
|
504
|
-
}),
|
|
505
|
-
execute: async ({ query, include, fixedString, caseSensitive, contextLines }) => {
|
|
506
|
-
const pattern = include ?? "**/*";
|
|
507
|
-
const files = (await ops.glob(pattern)).filter((f) => f.type === "file");
|
|
508
|
-
let regex;
|
|
509
|
-
try {
|
|
510
|
-
const escaped = fixedString ? escapeRegex(query) : query;
|
|
511
|
-
regex = new RegExp(escaped, caseSensitive ? "g" : "gi");
|
|
512
|
-
} catch {
|
|
513
|
-
return { error: `Invalid regex: ${query}` };
|
|
514
|
-
}
|
|
515
|
-
const ctx = contextLines ?? 0;
|
|
516
|
-
const matches = [];
|
|
517
|
-
let totalMatches = 0;
|
|
518
|
-
let filesSearched = 0;
|
|
519
|
-
let filesWithMatches = 0;
|
|
520
|
-
let filesSkipped = 0;
|
|
521
|
-
for (const file of files) {
|
|
522
|
-
if (totalMatches >= MAX_MATCHES) break;
|
|
523
|
-
if (file.size > MAX_FILE_SIZE) {
|
|
524
|
-
filesSkipped++;
|
|
525
|
-
continue;
|
|
526
|
-
}
|
|
527
|
-
const content = await ops.readFile(file.path);
|
|
528
|
-
if (content === null) continue;
|
|
529
|
-
filesSearched++;
|
|
530
|
-
const lines = content.split("\n");
|
|
531
|
-
let fileHasMatch = false;
|
|
532
|
-
for (let i = 0; i < lines.length; i++) {
|
|
533
|
-
if (totalMatches >= MAX_MATCHES) break;
|
|
534
|
-
regex.lastIndex = 0;
|
|
535
|
-
if (regex.test(lines[i])) {
|
|
536
|
-
if (!fileHasMatch) {
|
|
537
|
-
fileHasMatch = true;
|
|
538
|
-
filesWithMatches++;
|
|
539
|
-
}
|
|
540
|
-
totalMatches++;
|
|
541
|
-
const match = {
|
|
542
|
-
file: file.path,
|
|
543
|
-
line: i + 1,
|
|
544
|
-
text: lines[i]
|
|
545
|
-
};
|
|
546
|
-
if (ctx > 0) {
|
|
547
|
-
const start = Math.max(0, i - ctx);
|
|
548
|
-
const end = Math.min(lines.length, i + ctx + 1);
|
|
549
|
-
match.context = lines.slice(start, end).map((l, j) => {
|
|
550
|
-
const lineNum = start + j + 1;
|
|
551
|
-
return `${lineNum === i + 1 ? ">" : " "} ${lineNum}\t${l}`;
|
|
552
|
-
});
|
|
553
|
-
}
|
|
554
|
-
matches.push(match);
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
const result = {
|
|
559
|
-
query,
|
|
560
|
-
filesSearched,
|
|
561
|
-
filesWithMatches,
|
|
562
|
-
totalMatches,
|
|
563
|
-
matches: matches.map((m) => {
|
|
564
|
-
if (m.context) return {
|
|
565
|
-
file: m.file,
|
|
566
|
-
line: m.line,
|
|
567
|
-
context: m.context.join("\n")
|
|
568
|
-
};
|
|
569
|
-
return `${m.file}:${m.line}: ${m.text}`;
|
|
570
|
-
})
|
|
571
|
-
};
|
|
572
|
-
if (totalMatches >= MAX_MATCHES) result.truncated = true;
|
|
573
|
-
if (filesSkipped > 0) {
|
|
574
|
-
result.filesSkipped = filesSkipped;
|
|
575
|
-
result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;
|
|
576
|
-
}
|
|
577
|
-
return result;
|
|
578
|
-
}
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
function escapeRegex(s) {
|
|
582
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
583
|
-
}
|
|
584
|
-
const DEFAULT_BASH_TIMEOUT_MS = 3e4;
|
|
585
|
-
const DEFAULT_BASH_MAX_WORKSPACE_FILES = 1e3;
|
|
586
|
-
const DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES = 1e6;
|
|
587
|
-
const DEFAULT_BASH_MAX_OUTPUT_BYTES = 64e3;
|
|
588
|
-
const BASH_READDIR_PAGE_SIZE = 1e3;
|
|
589
|
-
const BASH_EXCLUDED_SYNC_ROOTS = [
|
|
590
|
-
"/bin",
|
|
591
|
-
"/usr",
|
|
592
|
-
"/dev",
|
|
593
|
-
"/proc",
|
|
594
|
-
"/sys"
|
|
595
|
-
];
|
|
596
|
-
function createBashTool(options) {
|
|
597
|
-
return tool({
|
|
598
|
-
description: "Run a Bash script against the workspace. Use for shell-style workflows that combine multiple file operations. The script runs in a sandboxed virtual filesystem with the workspace mounted at `/` (also the default working directory) — there is no `/workspace` or `/home`; use absolute paths like `/notes.txt`. Changed files are written back to the workspace.",
|
|
599
|
-
inputSchema: z.object({
|
|
600
|
-
script: z.string().describe("Bash script to run"),
|
|
601
|
-
cwd: z.string().optional().describe("Working directory for the script. Defaults to / (the workspace root)")
|
|
602
|
-
}),
|
|
603
|
-
execute: async ({ script, cwd }) => {
|
|
604
|
-
const timeout = options.timeout ?? DEFAULT_BASH_TIMEOUT_MS;
|
|
605
|
-
const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;
|
|
606
|
-
const snapshot = await snapshotWorkspaceForBash(options);
|
|
607
|
-
const bash = new Bash({
|
|
608
|
-
files: snapshot.files,
|
|
609
|
-
cwd: normalizeWorkspacePath(cwd ?? "/"),
|
|
610
|
-
defenseInDepth: true,
|
|
611
|
-
network: options.network ? {} : void 0
|
|
612
|
-
});
|
|
613
|
-
const controller = new AbortController();
|
|
614
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
615
|
-
let result;
|
|
616
|
-
try {
|
|
617
|
-
for (const directory of snapshot.directories) await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});
|
|
618
|
-
try {
|
|
619
|
-
result = await bash.exec(script, {
|
|
620
|
-
cwd: normalizeWorkspacePath(cwd ?? "/"),
|
|
621
|
-
signal: controller.signal,
|
|
622
|
-
rawScript: true
|
|
623
|
-
});
|
|
624
|
-
} catch (error) {
|
|
625
|
-
result = {
|
|
626
|
-
stdout: "",
|
|
627
|
-
stderr: errorMessage(error),
|
|
628
|
-
exitCode: controller.signal.aborted ? 124 : 1
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
const sync = await syncBashFilesToWorkspace({
|
|
632
|
-
ops: options.ops,
|
|
633
|
-
bash,
|
|
634
|
-
initialFiles: snapshot.initialFiles,
|
|
635
|
-
initialDirectories: snapshot.initialDirectories,
|
|
636
|
-
protectedPaths: snapshot.protectedPaths
|
|
637
|
-
});
|
|
638
|
-
return {
|
|
639
|
-
stdout: truncateToolOutput(result.stdout, maxOutputBytes),
|
|
640
|
-
stderr: truncateToolOutput(result.stderr, maxOutputBytes),
|
|
641
|
-
exitCode: result.exitCode,
|
|
642
|
-
changedFiles: sync.changedFiles,
|
|
643
|
-
...snapshot.skippedFiles.length > 0 ? { skippedFiles: snapshot.skippedFiles } : {},
|
|
644
|
-
...sync.errors.length > 0 ? { errors: sync.errors } : {}
|
|
645
|
-
};
|
|
646
|
-
} finally {
|
|
647
|
-
clearTimeout(timer);
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
async function snapshotWorkspaceForBash(options) {
|
|
653
|
-
const maxFiles = options.maxWorkspaceFiles ?? DEFAULT_BASH_MAX_WORKSPACE_FILES;
|
|
654
|
-
const maxFileBytes = options.maxWorkspaceFileBytes ?? DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES;
|
|
655
|
-
const files = {};
|
|
656
|
-
const initialFiles = /* @__PURE__ */ new Map();
|
|
657
|
-
const initialDirectories = /* @__PURE__ */ new Set(["/"]);
|
|
658
|
-
const protectedPaths = /* @__PURE__ */ new Set();
|
|
659
|
-
const skippedFiles = [];
|
|
660
|
-
const pending = ["/"];
|
|
661
|
-
while (pending.length > 0) {
|
|
662
|
-
const dir = pending.shift();
|
|
663
|
-
const entries = await readAllBashDirEntries(options.ops, dir);
|
|
664
|
-
for (const entry of entries) {
|
|
665
|
-
const path = normalizeWorkspacePath(entry.path);
|
|
666
|
-
if (entry.type === "directory") {
|
|
667
|
-
initialDirectories.add(path);
|
|
668
|
-
pending.push(path);
|
|
669
|
-
continue;
|
|
670
|
-
}
|
|
671
|
-
if (entry.type !== "file") continue;
|
|
672
|
-
if (initialFiles.size >= maxFiles || entry.size > maxFileBytes) {
|
|
673
|
-
protectedPaths.add(path);
|
|
674
|
-
skippedFiles.push(path);
|
|
675
|
-
continue;
|
|
676
|
-
}
|
|
677
|
-
const bytes = await options.ops.readFileBytes(path);
|
|
678
|
-
if (bytes === null) {
|
|
679
|
-
protectedPaths.add(path);
|
|
680
|
-
skippedFiles.push(path);
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
files[path] = bytes;
|
|
684
|
-
initialFiles.set(path, bytes);
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
return {
|
|
688
|
-
files,
|
|
689
|
-
initialFiles,
|
|
690
|
-
initialDirectories,
|
|
691
|
-
protectedPaths,
|
|
692
|
-
directories: [...initialDirectories].sort((a, b) => a.localeCompare(b)),
|
|
693
|
-
skippedFiles
|
|
694
|
-
};
|
|
695
|
-
}
|
|
696
|
-
async function readAllBashDirEntries(ops, dir) {
|
|
697
|
-
const entries = [];
|
|
698
|
-
let offset = 0;
|
|
699
|
-
while (true) {
|
|
700
|
-
const page = await ops.readDir(dir, {
|
|
701
|
-
limit: BASH_READDIR_PAGE_SIZE,
|
|
702
|
-
offset
|
|
703
|
-
});
|
|
704
|
-
entries.push(...page);
|
|
705
|
-
if (page.length !== BASH_READDIR_PAGE_SIZE) break;
|
|
706
|
-
offset += page.length;
|
|
707
|
-
}
|
|
708
|
-
return entries;
|
|
709
|
-
}
|
|
710
|
-
async function syncBashFilesToWorkspace({ ops, bash, initialFiles, initialDirectories, protectedPaths }) {
|
|
711
|
-
const changedFiles = {
|
|
712
|
-
created: [],
|
|
713
|
-
updated: [],
|
|
714
|
-
deleted: [],
|
|
715
|
-
directoriesCreated: [],
|
|
716
|
-
directoriesDeleted: []
|
|
717
|
-
};
|
|
718
|
-
const errors = [];
|
|
719
|
-
const finalFiles = /* @__PURE__ */ new Map();
|
|
720
|
-
const finalDirectories = /* @__PURE__ */ new Set(["/"]);
|
|
721
|
-
for (const rawPath of bash.fs.getAllPaths()) {
|
|
722
|
-
const path = normalizeWorkspacePath(rawPath);
|
|
723
|
-
if (!shouldSyncBashPath(path, initialFiles, protectedPaths)) continue;
|
|
724
|
-
const stat = await bash.fs.stat(path).catch(() => null);
|
|
725
|
-
if (stat?.isDirectory) {
|
|
726
|
-
finalDirectories.add(path);
|
|
727
|
-
continue;
|
|
728
|
-
}
|
|
729
|
-
if (stat?.isFile) finalFiles.set(path, await bash.fs.readFileBuffer(path));
|
|
730
|
-
}
|
|
731
|
-
for (const path of [...finalDirectories].sort((a, b) => a.localeCompare(b))) {
|
|
732
|
-
if (path === "/" || initialDirectories.has(path)) continue;
|
|
733
|
-
if (hasProtectedDescendant(path, protectedPaths)) {
|
|
734
|
-
errors.push(`Skipped creating directory ${path}: contains protected paths.`);
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
if (!await Promise.resolve(ops.mkdir(path, { recursive: true })).then(() => true).catch((error) => {
|
|
738
|
-
errors.push(`Failed to create directory ${path}: ${errorMessage(error)}`);
|
|
739
|
-
return false;
|
|
740
|
-
})) continue;
|
|
741
|
-
changedFiles.directoriesCreated.push(path);
|
|
742
|
-
}
|
|
743
|
-
for (const [path, bytes] of finalFiles) {
|
|
744
|
-
if (protectedPaths.has(path)) {
|
|
745
|
-
errors.push(`Skipped writing protected workspace file: ${path}`);
|
|
746
|
-
continue;
|
|
747
|
-
}
|
|
748
|
-
const existing = initialFiles.get(path);
|
|
749
|
-
if (existing && bytesEqual(existing, bytes)) continue;
|
|
750
|
-
if (!await writeWorkspaceBytes(ops, path, bytes, errors)) continue;
|
|
751
|
-
if (existing) changedFiles.updated.push(path);
|
|
752
|
-
else changedFiles.created.push(path);
|
|
753
|
-
}
|
|
754
|
-
for (const path of [...initialFiles.keys()].sort((a, b) => b.localeCompare(a))) {
|
|
755
|
-
if (finalFiles.has(path) || protectedPaths.has(path)) continue;
|
|
756
|
-
if (!await ops.rm(path, { force: true }).then(() => true).catch((error) => {
|
|
757
|
-
errors.push(`Failed to delete ${path}: ${errorMessage(error)}`);
|
|
758
|
-
return false;
|
|
759
|
-
})) continue;
|
|
760
|
-
changedFiles.deleted.push(path);
|
|
761
|
-
}
|
|
762
|
-
for (const path of [...initialDirectories].sort((a, b) => b.localeCompare(a))) {
|
|
763
|
-
if (path === "/" || finalDirectories.has(path)) continue;
|
|
764
|
-
if (hasProtectedDescendant(path, protectedPaths)) {
|
|
765
|
-
errors.push(`Skipped deleting protected workspace directory: ${path}`);
|
|
766
|
-
continue;
|
|
767
|
-
}
|
|
768
|
-
if (!await ops.rm(path, {
|
|
769
|
-
recursive: true,
|
|
770
|
-
force: true
|
|
771
|
-
}).then(() => true).catch((error) => {
|
|
772
|
-
errors.push(`Failed to delete directory ${path}: ${errorMessage(error)}`);
|
|
773
|
-
return false;
|
|
774
|
-
})) continue;
|
|
775
|
-
changedFiles.directoriesDeleted.push(path);
|
|
776
|
-
}
|
|
777
|
-
changedFiles.created.sort();
|
|
778
|
-
changedFiles.updated.sort();
|
|
779
|
-
changedFiles.deleted.sort();
|
|
780
|
-
changedFiles.directoriesCreated.sort();
|
|
781
|
-
changedFiles.directoriesDeleted.sort();
|
|
782
|
-
return {
|
|
783
|
-
changedFiles,
|
|
784
|
-
errors
|
|
785
|
-
};
|
|
786
|
-
}
|
|
787
|
-
async function writeWorkspaceBytes(ops, path, bytes, errors) {
|
|
788
|
-
const parent = parentDir(path);
|
|
789
|
-
if (parent !== "/") {
|
|
790
|
-
if (!await Promise.resolve(ops.mkdir(parent, { recursive: true })).then(() => true).catch((error) => {
|
|
791
|
-
errors.push(`Failed to create parent directory ${parent}: ${errorMessage(error)}`);
|
|
792
|
-
return false;
|
|
793
|
-
})) return false;
|
|
794
|
-
}
|
|
795
|
-
if (ops.writeFileBytes) return ops.writeFileBytes(path, bytes).then(() => true).catch((error) => {
|
|
796
|
-
errors.push(`Failed to write ${path}: ${errorMessage(error)}`);
|
|
797
|
-
return false;
|
|
798
|
-
});
|
|
799
|
-
if (!looksLikeText(bytes)) {
|
|
800
|
-
errors.push(`Could not persist binary file ${path}: workspace does not support writeFileBytes.`);
|
|
801
|
-
return false;
|
|
802
|
-
}
|
|
803
|
-
const content = new TextDecoder().decode(bytes);
|
|
804
|
-
return ops.writeFile(path, content).then(() => true).catch((error) => {
|
|
805
|
-
errors.push(`Failed to write ${path}: ${errorMessage(error)}`);
|
|
806
|
-
return false;
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
function shouldSyncBashPath(path, initialFiles, protectedPaths) {
|
|
810
|
-
if (path === "/") return false;
|
|
811
|
-
if (initialFiles.has(path)) return true;
|
|
812
|
-
if (protectedPaths.has(path)) return true;
|
|
813
|
-
if (path === "/tmp" || path.startsWith("/tmp/")) return false;
|
|
814
|
-
return !BASH_EXCLUDED_SYNC_ROOTS.some((root) => path === root || path.startsWith(`${root}/`));
|
|
815
|
-
}
|
|
816
|
-
function hasProtectedDescendant(path, protectedPaths) {
|
|
817
|
-
const prefix = path.endsWith("/") ? path : `${path}/`;
|
|
818
|
-
for (const protectedPath of protectedPaths) if (protectedPath.startsWith(prefix)) return true;
|
|
819
|
-
return false;
|
|
820
|
-
}
|
|
821
|
-
function normalizeWorkspacePath(path) {
|
|
822
|
-
const parts = [];
|
|
823
|
-
const raw = path.startsWith("/") ? path : `/${path}`;
|
|
824
|
-
for (const part of raw.split("/")) {
|
|
825
|
-
if (!part || part === ".") continue;
|
|
826
|
-
if (part === "..") parts.pop();
|
|
827
|
-
else parts.push(part);
|
|
828
|
-
}
|
|
829
|
-
return `/${parts.join("/")}`;
|
|
830
|
-
}
|
|
831
|
-
function parentDir(path) {
|
|
832
|
-
const normalized = normalizeWorkspacePath(path);
|
|
833
|
-
const index = normalized.lastIndexOf("/");
|
|
834
|
-
return index <= 0 ? "/" : normalized.slice(0, index);
|
|
835
|
-
}
|
|
836
|
-
function bytesEqual(a, b) {
|
|
837
|
-
if (a.byteLength !== b.byteLength) return false;
|
|
838
|
-
for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
|
|
839
|
-
return true;
|
|
840
|
-
}
|
|
841
|
-
function truncateToolOutput(value, maxBytes) {
|
|
842
|
-
const bytes = new TextEncoder().encode(value);
|
|
843
|
-
if (bytes.byteLength <= maxBytes) return value;
|
|
844
|
-
return `${new TextDecoder().decode(bytes.slice(0, maxBytes))}\n... (${formatSize(bytes.byteLength - maxBytes)} truncated)`;
|
|
845
|
-
}
|
|
846
|
-
function errorMessage(error) {
|
|
847
|
-
return error instanceof Error ? error.message : String(error);
|
|
848
|
-
}
|
|
849
|
-
function createDeleteTool(options) {
|
|
850
|
-
const { ops } = options;
|
|
851
|
-
return tool({
|
|
852
|
-
description: "Delete a file or directory. Set recursive to true to remove non-empty directories.",
|
|
853
|
-
inputSchema: z.object({
|
|
854
|
-
path: z.string().describe("Absolute path to the file or directory"),
|
|
855
|
-
recursive: z.boolean().optional().describe("If true, remove directories and their contents recursively")
|
|
856
|
-
}),
|
|
857
|
-
execute: async ({ path, recursive }) => {
|
|
858
|
-
await ops.rm(path, {
|
|
859
|
-
recursive,
|
|
860
|
-
force: true
|
|
861
|
-
});
|
|
862
|
-
return { deleted: path };
|
|
863
|
-
}
|
|
864
|
-
});
|
|
865
|
-
}
|
|
866
|
-
//#endregion
|
|
867
|
-
export { createBashTool, createDeleteTool, createEditTool, createFindTool, createGrepTool, createListTool, createReadTool, createWorkspaceTools, createWriteTool };
|
|
868
|
-
|
|
869
|
-
//# sourceMappingURL=workspace.js.map
|