@cloudflare/think 0.5.0 → 0.5.1

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.
@@ -4,10 +4,18 @@ import { FileInfo, Workspace } from "@cloudflare/shell";
4
4
  //#region src/tools/workspace.d.ts
5
5
  type WorkspaceLike = Pick<
6
6
  Workspace,
7
- "readFile" | "writeFile" | "readDir" | "rm" | "glob" | "mkdir" | "stat"
7
+ | "readFile"
8
+ | "readFileBytes"
9
+ | "writeFile"
10
+ | "readDir"
11
+ | "rm"
12
+ | "glob"
13
+ | "mkdir"
14
+ | "stat"
8
15
  >;
9
16
  interface ReadOperations {
10
17
  readFile(path: string): Promise<string | null>;
18
+ readFileBytes(path: string): Promise<Uint8Array | null>;
11
19
  stat(path: string): Promise<FileInfo | null> | FileInfo | null;
12
20
  }
13
21
  interface WriteOperations {
@@ -77,7 +85,7 @@ declare function createWorkspaceTools(workspace: WorkspaceLike): {
77
85
  offset?: number | undefined;
78
86
  limit?: number | undefined;
79
87
  },
80
- Record<string, unknown>
88
+ ReadToolOutput
81
89
  >;
82
90
  write: _$ai.Tool<
83
91
  {
@@ -167,6 +175,44 @@ declare function createWorkspaceTools(workspace: WorkspaceLike): {
167
175
  }
168
176
  >;
169
177
  };
178
+ type TextReadToolOutput = {
179
+ path: string;
180
+ content: string;
181
+ totalLines: number;
182
+ fromLine?: number;
183
+ toLine?: number;
184
+ };
185
+ type ImageReadToolOutput = {
186
+ kind: "image";
187
+ path: string;
188
+ name: string;
189
+ mediaType: string;
190
+ sizeBytes: number;
191
+ };
192
+ type FileReadToolOutput = {
193
+ kind: "file";
194
+ path: string;
195
+ name: string;
196
+ mediaType: string;
197
+ sizeBytes: number;
198
+ };
199
+ type BinaryReadToolOutput = {
200
+ kind: "binary";
201
+ path: string;
202
+ name: string;
203
+ mediaType: string;
204
+ sizeBytes: number;
205
+ unsupported: true;
206
+ };
207
+ type ReadToolError = {
208
+ error: string;
209
+ };
210
+ type ReadToolOutput =
211
+ | TextReadToolOutput
212
+ | ImageReadToolOutput
213
+ | FileReadToolOutput
214
+ | BinaryReadToolOutput
215
+ | ReadToolError;
170
216
  interface ReadToolOptions {
171
217
  ops: ReadOperations;
172
218
  }
@@ -176,7 +222,7 @@ declare function createReadTool(options: ReadToolOptions): _$ai.Tool<
176
222
  offset?: number | undefined;
177
223
  limit?: number | undefined;
178
224
  },
179
- Record<string, unknown>
225
+ ReadToolOutput
180
226
  >;
181
227
  interface WriteToolOptions {
182
228
  ops: WriteOperations;
@@ -4,6 +4,7 @@ import { z } from "zod";
4
4
  function workspaceReadOps(ws) {
5
5
  return {
6
6
  readFile: (path) => ws.readFile(path),
7
+ readFileBytes: (path) => ws.readFileBytes(path),
7
8
  stat: (path) => ws.stat(path)
8
9
  };
9
10
  }
@@ -69,10 +70,11 @@ function createWorkspaceTools(workspace) {
69
70
  }
70
71
  const MAX_LINES = 2e3;
71
72
  const MAX_LINE_LENGTH = 2e3;
73
+ const MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;
72
74
  function createReadTool(options) {
73
75
  const { ops } = options;
74
76
  return tool({
75
- description: "Read the contents of a file. Returns the file content with line numbers. Use offset and limit for large files. Returns null if the file does not exist.",
77
+ 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.",
76
78
  inputSchema: z.object({
77
79
  path: z.string().describe("Absolute path to the file"),
78
80
  offset: z.number().int().min(1).optional().describe("1-indexed line number to start reading from"),
@@ -82,31 +84,184 @@ function createReadTool(options) {
82
84
  const stat = await ops.stat(path);
83
85
  if (!stat) return { error: `File not found: ${path}` };
84
86
  if (stat.type === "directory") return { error: `${path} is a directory, not a file` };
85
- const content = await ops.readFile(path);
86
- if (content === null) return { error: `Could not read file: ${path}` };
87
- const allLines = content.split("\n");
88
- const totalLines = allLines.length;
89
- const startLine = offset ? offset - 1 : 0;
90
- const endLine = limit ? startLine + limit : allLines.length;
91
- const numbered = allLines.slice(startLine, endLine).map((line, i) => {
92
- return `${startLine + i + 1}\t${line.length > MAX_LINE_LENGTH ? line.slice(0, MAX_LINE_LENGTH) + "... (truncated)" : line}`;
87
+ const mediaType = await detectWorkspaceMediaType({
88
+ ops,
89
+ path,
90
+ stat
93
91
  });
94
- let output;
95
- if (numbered.length > MAX_LINES) output = numbered.slice(0, MAX_LINES).join("\n") + `\n... (${numbered.length - MAX_LINES} more lines truncated)`;
96
- else output = numbered.join("\n");
97
- const result = {
92
+ if (mediaType.startsWith("image/")) return {
93
+ kind: "image",
98
94
  path,
99
- content: output,
100
- totalLines
95
+ name: stat.name,
96
+ mediaType,
97
+ sizeBytes: stat.size
101
98
  };
102
- if (offset || limit) {
103
- result.fromLine = startLine + 1;
104
- result.toLine = Math.min(endLine, totalLines);
105
- }
106
- return result;
99
+ if (mediaType === "application/pdf") return {
100
+ kind: "file",
101
+ path,
102
+ name: stat.name,
103
+ mediaType,
104
+ sizeBytes: stat.size
105
+ };
106
+ if (!isTextMediaType(mediaType)) return {
107
+ kind: "binary",
108
+ path,
109
+ name: stat.name,
110
+ mediaType,
111
+ sizeBytes: stat.size,
112
+ unsupported: true
113
+ };
114
+ return readTextWithLineNumbers({
115
+ ops,
116
+ path,
117
+ offset,
118
+ limit
119
+ });
120
+ },
121
+ toModelOutput: async ({ input, output }) => {
122
+ if ("error" in output) return {
123
+ type: "error-text",
124
+ value: output.error
125
+ };
126
+ if ("content" in output) return {
127
+ type: "text",
128
+ value: output.content
129
+ };
130
+ if (output.kind === "binary") return {
131
+ type: "json",
132
+ value: output
133
+ };
134
+ const bytes = await ops.readFileBytes(input.path);
135
+ if (bytes === null) return {
136
+ type: "error-text",
137
+ value: `Could not read file bytes: ${input.path}`
138
+ };
139
+ if (bytes.byteLength > MAX_MODEL_FILE_BYTES) return {
140
+ type: "error-text",
141
+ value: `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}), but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`
142
+ };
143
+ const data = uint8ArrayToBase64(bytes);
144
+ const note = `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}).`;
145
+ if (output.kind === "image") return {
146
+ type: "content",
147
+ value: [{
148
+ type: "text",
149
+ text: note
150
+ }, {
151
+ type: "image-data",
152
+ data,
153
+ mediaType: output.mediaType
154
+ }]
155
+ };
156
+ return {
157
+ type: "content",
158
+ value: [{
159
+ type: "text",
160
+ text: note
161
+ }, {
162
+ type: "file-data",
163
+ data,
164
+ mediaType: output.mediaType,
165
+ filename: output.name
166
+ }]
167
+ };
168
+ }
169
+ });
170
+ }
171
+ function readTextWithLineNumbers({ ops, path, offset, limit }) {
172
+ return Promise.resolve(ops.readFile(path)).then((content) => {
173
+ if (content === null) return { error: `Could not read file: ${path}` };
174
+ const allLines = content.split("\n");
175
+ const totalLines = allLines.length;
176
+ const startLine = offset ? offset - 1 : 0;
177
+ const endLine = limit ? startLine + limit : allLines.length;
178
+ const numbered = allLines.slice(startLine, endLine).map((line, i) => {
179
+ return `${startLine + i + 1}\t${line.length > MAX_LINE_LENGTH ? line.slice(0, MAX_LINE_LENGTH) + "... (truncated)" : line}`;
180
+ });
181
+ let output;
182
+ if (numbered.length > MAX_LINES) output = numbered.slice(0, MAX_LINES).join("\n") + `\n... (${numbered.length - MAX_LINES} more lines truncated)`;
183
+ else output = numbered.join("\n");
184
+ const result = {
185
+ path,
186
+ content: output,
187
+ totalLines
188
+ };
189
+ if (offset || limit) {
190
+ result.fromLine = startLine + 1;
191
+ result.toLine = Math.min(endLine, totalLines);
107
192
  }
193
+ return result;
108
194
  });
109
195
  }
196
+ async function detectWorkspaceMediaType({ ops, path, stat }) {
197
+ const statMime = normalizeMediaType(stat.mimeType);
198
+ if (statMime && !isGenericMediaType(statMime)) return statMime;
199
+ const bytes = await ops.readFileBytes(path);
200
+ if (bytes === null) return statMime || "application/octet-stream";
201
+ const sniffed = sniffMediaType(bytes);
202
+ if (sniffed) return sniffed;
203
+ return looksLikeText(bytes) ? "text/plain" : "application/octet-stream";
204
+ }
205
+ function normalizeMediaType(mediaType) {
206
+ return mediaType?.split(";")[0]?.trim().toLowerCase() || null;
207
+ }
208
+ function isGenericMediaType(mediaType) {
209
+ return mediaType === "application/octet-stream" || mediaType === "binary/octet-stream";
210
+ }
211
+ function isTextMediaType(mediaType) {
212
+ 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");
213
+ }
214
+ function sniffMediaType(bytes) {
215
+ if (startsWith(bytes, [
216
+ 137,
217
+ 80,
218
+ 78,
219
+ 71,
220
+ 13,
221
+ 10,
222
+ 26,
223
+ 10
224
+ ])) return "image/png";
225
+ if (startsWith(bytes, [
226
+ 255,
227
+ 216,
228
+ 255
229
+ ])) return "image/jpeg";
230
+ if (startsWithAscii(bytes, "GIF87a") || startsWithAscii(bytes, "GIF89a")) return "image/gif";
231
+ if (startsWithAscii(bytes, "RIFF") && asciiAt(bytes, 8, 12) === "WEBP") return "image/webp";
232
+ if (startsWithAscii(bytes, "%PDF-")) return "application/pdf";
233
+ if (looksLikeSvg(bytes)) return "image/svg+xml";
234
+ return null;
235
+ }
236
+ function startsWith(bytes, prefix) {
237
+ if (bytes.length < prefix.length) return false;
238
+ return prefix.every((byte, index) => bytes[index] === byte);
239
+ }
240
+ function startsWithAscii(bytes, prefix) {
241
+ return asciiAt(bytes, 0, prefix.length) === prefix;
242
+ }
243
+ function asciiAt(bytes, start, end) {
244
+ return String.fromCharCode(...bytes.subarray(start, end));
245
+ }
246
+ function looksLikeSvg(bytes) {
247
+ const prefix = new TextDecoder().decode(bytes.subarray(0, Math.min(bytes.length, 512))).trimStart().toLowerCase();
248
+ return prefix.startsWith("<svg") || prefix.includes("<svg");
249
+ }
250
+ function looksLikeText(bytes) {
251
+ if (bytes.length === 0) return true;
252
+ if (bytes.includes(0)) return false;
253
+ const text = new TextDecoder().decode(bytes.subarray(0, 4096));
254
+ if (text.length === 0) return true;
255
+ let replacementChars = 0;
256
+ for (const char of text) if (char === "�") replacementChars++;
257
+ return replacementChars / text.length < .01;
258
+ }
259
+ function uint8ArrayToBase64(bytes) {
260
+ let binary = "";
261
+ const chunkSize = 32768;
262
+ for (let i = 0; i < bytes.length; i += chunkSize) binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
263
+ return btoa(binary);
264
+ }
110
265
  function createWriteTool(options) {
111
266
  const { ops } = options;
112
267
  return tool({
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). A concrete `Workspace` from `@cloudflare/shell`\n// satisfies this; so do custom implementations like the `SharedWorkspace`\n// proxy in `examples/assistant` that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n \"readFile\" | \"writeFile\" | \"readDir\" | \"rm\" | \"glob\" | \"mkdir\" | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: WorkspaceLike) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read the contents of a file. Returns the file content with line numbers. \" +\n \"Use offset and limit for large files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({ path, offset, limit }) => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: Record<string, unknown> = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n }\n });\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AAoEA,SAAS,iBAAiB,IAAmC;AAC3D,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH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,MAAM;AAC1B,SAAI,EAAE,QACJ,QAAO;MACL,MAAM,EAAE;MACR,MAAM,EAAE;MACR,SAAS,EAAE,QAAQ,KAAK,KAAK;MAC9B;AAEH,YAAO,GAAG,EAAE,KAAK,GAAG,EAAE,KAAK,IAAI,EAAE;MACjC;IACH;AAED,OAAI,gBAAgB,YAClB,QAAO,YAAY;AAErB,OAAI,eAAe,GAAG;AACpB,WAAO,eAAe;AACtB,WAAO,OAAO,GAAG,aAAa;;AAGhC,UAAO;;EAEV,CAAC;;AAGJ,SAAS,YAAY,GAAmB;AACtC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AASjD,SAAgB,iBAAiB,SAA4B;CAC3D,MAAM,EAAE,QAAQ;AAEhB,QAAO,KAAK;EACV,aACE;EAEF,aAAa,EAAE,OAAO;GACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,yCAAyC;GACnE,WAAW,EACR,SAAS,CACT,UAAU,CACV,SAAS,6DAA6D;GAC1E,CAAC;EACF,SAAS,OAAO,EAAE,MAAM,gBAAgB;AACtC,SAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;IAAM,CAAC;AAC9C,UAAO,EAAE,SAAS,MAAM;;EAE3B,CAAC"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). The read tool also needs `readFileBytes` so image/PDF\n// reads can be rehydrated as AI SDK multimodal content. A concrete\n// `Workspace` from `@cloudflare/shell` satisfies this; so do custom\n// implementations like the `SharedWorkspace` proxy in `examples/assistant`\n// that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n | \"readFile\"\n | \"readFileBytes\"\n | \"writeFile\"\n | \"readDir\"\n | \"rm\"\n | \"glob\"\n | \"mkdir\"\n | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n readFileBytes(path: string): Promise<Uint8Array | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n readFileBytes: (path) => ws.readFileBytes(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: WorkspaceLike) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;\n\ntype TextReadToolOutput = {\n path: string;\n content: string;\n totalLines: number;\n fromLine?: number;\n toLine?: number;\n};\n\ntype ImageReadToolOutput = {\n kind: \"image\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype FileReadToolOutput = {\n kind: \"file\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype BinaryReadToolOutput = {\n kind: \"binary\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n unsupported: true;\n};\n\ntype ReadToolError = { error: string };\n\ntype ReadToolOutput =\n | TextReadToolOutput\n | ImageReadToolOutput\n | FileReadToolOutput\n | BinaryReadToolOutput\n | ReadToolError;\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read a workspace file. Text files return line-numbered content. \" +\n \"Images and PDFs are passed to capable models as file content. \" +\n \"Use offset and limit for large text files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({ path, offset, limit }): Promise<ReadToolOutput> => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const mediaType = await detectWorkspaceMediaType({ ops, path, stat });\n\n if (mediaType.startsWith(\"image/\")) {\n return {\n kind: \"image\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (mediaType === \"application/pdf\") {\n return {\n kind: \"file\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (!isTextMediaType(mediaType)) {\n return {\n kind: \"binary\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size,\n unsupported: true\n };\n }\n\n return readTextWithLineNumbers({ ops, path, offset, limit });\n },\n toModelOutput: async ({ input, output }) => {\n if (\"error\" in output) {\n return { type: \"error-text\", value: output.error };\n }\n\n if (\"content\" in output) {\n return { type: \"text\", value: output.content };\n }\n\n if (output.kind === \"binary\") {\n return {\n type: \"json\",\n value: output\n };\n }\n\n const bytes = await ops.readFileBytes(input.path);\n if (bytes === null) {\n return {\n type: \"error-text\",\n value: `Could not read file bytes: ${input.path}`\n };\n }\n if (bytes.byteLength > MAX_MODEL_FILE_BYTES) {\n return {\n type: \"error-text\",\n value:\n `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}), ` +\n `but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`\n };\n }\n\n const data = uint8ArrayToBase64(bytes);\n const note = `Read ${output.path} (${output.mediaType}, ${formatSize(bytes.byteLength)}).`;\n\n if (output.kind === \"image\") {\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n { type: \"image-data\", data, mediaType: output.mediaType }\n ]\n };\n }\n\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n {\n type: \"file-data\",\n data,\n mediaType: output.mediaType,\n filename: output.name\n }\n ]\n };\n }\n });\n}\n\nfunction readTextWithLineNumbers({\n ops,\n path,\n offset,\n limit\n}: {\n ops: ReadOperations;\n path: string;\n offset?: number;\n limit?: number;\n}): Promise<TextReadToolOutput | ReadToolError> {\n return Promise.resolve(ops.readFile(path)).then((content) => {\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: TextReadToolOutput = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n });\n}\n\nasync function detectWorkspaceMediaType({\n ops,\n path,\n stat\n}: {\n ops: ReadOperations;\n path: string;\n stat: FileInfo;\n}): Promise<string> {\n const statMime = normalizeMediaType(stat.mimeType);\n if (statMime && !isGenericMediaType(statMime)) {\n return statMime;\n }\n\n const bytes = await ops.readFileBytes(path);\n if (bytes === null) {\n return statMime || \"application/octet-stream\";\n }\n\n const sniffed = sniffMediaType(bytes);\n if (sniffed) {\n return sniffed;\n }\n\n return looksLikeText(bytes) ? \"text/plain\" : \"application/octet-stream\";\n}\n\nfunction normalizeMediaType(mediaType: string | undefined): string | null {\n const normalized = mediaType?.split(\";\")[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction isGenericMediaType(mediaType: string): boolean {\n return (\n mediaType === \"application/octet-stream\" ||\n mediaType === \"binary/octet-stream\"\n );\n}\n\nfunction isTextMediaType(mediaType: string): boolean {\n return (\n mediaType.startsWith(\"text/\") ||\n mediaType === \"application/json\" ||\n mediaType === \"application/javascript\" ||\n mediaType === \"application/typescript\" ||\n mediaType === \"application/xml\" ||\n mediaType === \"application/x-javascript\" ||\n mediaType.endsWith(\"+json\") ||\n mediaType.endsWith(\"+xml\")\n );\n}\n\nfunction sniffMediaType(bytes: Uint8Array): string | null {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n if (startsWithAscii(bytes, \"GIF87a\") || startsWithAscii(bytes, \"GIF89a\")) {\n return \"image/gif\";\n }\n if (startsWithAscii(bytes, \"RIFF\") && asciiAt(bytes, 8, 12) === \"WEBP\") {\n return \"image/webp\";\n }\n if (startsWithAscii(bytes, \"%PDF-\")) {\n return \"application/pdf\";\n }\n if (looksLikeSvg(bytes)) {\n return \"image/svg+xml\";\n }\n return null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n return prefix.every((byte, index) => bytes[index] === byte);\n}\n\nfunction startsWithAscii(bytes: Uint8Array, prefix: string): boolean {\n return asciiAt(bytes, 0, prefix.length) === prefix;\n}\n\nfunction asciiAt(bytes: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = new TextDecoder()\n .decode(bytes.subarray(0, Math.min(bytes.length, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || prefix.includes(\"<svg\");\n}\n\nfunction looksLikeText(bytes: Uint8Array): boolean {\n if (bytes.length === 0) return true;\n if (bytes.includes(0)) return false;\n\n const text = new TextDecoder().decode(bytes.subarray(0, 4096));\n if (text.length === 0) return true;\n\n let replacementChars = 0;\n for (const char of text) {\n if (char === \"\\uFFFD\") {\n replacementChars++;\n }\n }\n return replacementChars / text.length < 0.01;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AA8EA,SAAS,iBAAiB,IAAmC;AAC3D,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,gBAAgB,SAAS,GAAG,cAAc,KAAK;EAC/C,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAoC;AAC7D,QAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EACzD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,KAAK;EAC5C;;AAGH,SAAS,iBAAiB,IAAmC;AAC3D,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EAC1D;;AAGH,SAAS,iBAAiB,IAAmC;AAC3D,QAAO,EACL,UAAU,KAAK,SAAS,GAAG,QAAQ,KAAK,KAAK,EAC9C;;AAGH,SAAS,iBAAiB,IAAmC;AAC3D,QAAO,EACL,OAAO,YAAY,GAAG,KAAK,QAAQ,EACpC;;AAGH,SAAS,mBAAmB,IAAqC;AAC/D,QAAO,EACL,KAAK,MAAM,SAAS,GAAG,GAAG,MAAM,KAAK,EACtC;;AAGH,SAAS,iBAAiB,IAAmC;AAC3D,QAAO;EACL,OAAO,YAAY,GAAG,KAAK,QAAQ;EACnC,WAA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AO,EAAE,SAAS,MAAM;;EAE3B,CAAC"}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.5.0",
12
+ "version": "0.5.1",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -21,8 +21,8 @@
21
21
  "url": "https://github.com/cloudflare/agents/issues"
22
22
  },
23
23
  "devDependencies": {
24
- "@cloudflare/shell": "^0.3.5",
25
- "ai": "^6.0.170",
24
+ "@cloudflare/shell": "^0.3.6",
25
+ "ai": "^6.0.172",
26
26
  "zod": "^4.4.1"
27
27
  },
28
28
  "peerDependencies": {