@cursor/july 0.1.103 → 0.1.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/dist/channels/change-monitors/change-monitors-channel.d.ts +5 -0
  2. package/dist/channels/change-monitors/change-monitors-channel.d.ts.map +1 -0
  3. package/dist/channels/change-monitors/change-monitors-channel.js +41 -0
  4. package/dist/channels/change-monitors/index.d.ts +4 -0
  5. package/dist/channels/change-monitors/index.d.ts.map +1 -0
  6. package/dist/channels/change-monitors/index.js +2 -0
  7. package/dist/channels/change-monitors/types.d.ts +39 -0
  8. package/dist/channels/change-monitors/types.d.ts.map +1 -0
  9. package/dist/channels/change-monitors/types.js +1 -0
  10. package/dist/channels/github/defaults.d.ts.map +1 -1
  11. package/dist/channels/github/defaults.js +4 -0
  12. package/dist/channels/github/progress.d.ts +22 -0
  13. package/dist/channels/github/progress.d.ts.map +1 -1
  14. package/dist/channels/github/progress.js +32 -5
  15. package/dist/channels/issues/index.d.ts +4 -0
  16. package/dist/channels/issues/index.d.ts.map +1 -0
  17. package/dist/channels/issues/index.js +2 -0
  18. package/dist/channels/issues/issues-channel.d.ts +5 -0
  19. package/dist/channels/issues/issues-channel.d.ts.map +1 -0
  20. package/dist/channels/issues/issues-channel.js +37 -0
  21. package/dist/channels/issues/types.d.ts +33 -0
  22. package/dist/channels/issues/types.d.ts.map +1 -0
  23. package/dist/channels/issues/types.js +1 -0
  24. package/dist/docs/404.html +2 -2
  25. package/dist/docs/ab.html +4 -4
  26. package/dist/docs/assets/{app.DW9pXkpL.js → app.DbMWUyGb.js} +1 -1
  27. package/dist/docs/assets/chunks/@localSearchIndexroot.Bqsulb9K.js +1 -0
  28. package/dist/docs/assets/chunks/{VPLocalSearchBox.CdEIUwDg.js → VPLocalSearchBox.DcNeTh9o.js} +1 -1
  29. package/dist/docs/assets/chunks/{theme.YZMHgPgg.js → theme.DMjhY3gl.js} +2 -2
  30. package/dist/docs/assets/{guides_github.md.DKYiT9do.js → guides_github.md.c0gdGJ-D.js} +1 -1
  31. package/dist/docs/assets/{guides_github.md.DKYiT9do.lean.js → guides_github.md.c0gdGJ-D.lean.js} +1 -1
  32. package/dist/docs/assets/{reference_channels.md.Dz8Cnudp.js → reference_channels.md.DBGcaB7m.js} +2 -2
  33. package/dist/docs/assets/{reference_channels.md.Dz8Cnudp.lean.js → reference_channels.md.DBGcaB7m.lean.js} +1 -1
  34. package/dist/docs/building-with-agents.html +4 -4
  35. package/dist/docs/concepts.html +4 -4
  36. package/dist/docs/deployment.html +4 -4
  37. package/dist/docs/design/filesystem.md +376 -0
  38. package/dist/docs/evals.html +4 -4
  39. package/dist/docs/guides/agent-to-agent.html +4 -4
  40. package/dist/docs/guides/cloud-agents.html +4 -4
  41. package/dist/docs/guides/convert-automation.html +4 -4
  42. package/dist/docs/guides/github.html +6 -6
  43. package/dist/docs/guides/github.md +5 -0
  44. package/dist/docs/guides/human-in-the-loop.html +4 -4
  45. package/dist/docs/guides/mcp-oauth.html +4 -4
  46. package/dist/docs/guides/opentelemetry.html +4 -4
  47. package/dist/docs/guides/slack.html +4 -4
  48. package/dist/docs/guides/webhooks.html +4 -4
  49. package/dist/docs/hashmap.json +1 -1
  50. package/dist/docs/hillclimbing.html +4 -4
  51. package/dist/docs/index.html +4 -4
  52. package/dist/docs/llms-full.txt +406 -0
  53. package/dist/docs/llms.txt +1 -0
  54. package/dist/docs/quickstart.html +4 -4
  55. package/dist/docs/reference/agent-config.html +4 -4
  56. package/dist/docs/reference/artifacts.html +4 -4
  57. package/dist/docs/reference/channels.html +6 -6
  58. package/dist/docs/reference/channels.md +20 -0
  59. package/dist/docs/reference/cli.html +4 -4
  60. package/dist/docs/reference/connections.html +4 -4
  61. package/dist/docs/reference/extensions.html +4 -4
  62. package/dist/docs/reference/hooks.html +4 -4
  63. package/dist/docs/reference/http-api.html +4 -4
  64. package/dist/docs/reference/instructions.html +4 -4
  65. package/dist/docs/reference/playground.html +4 -4
  66. package/dist/docs/reference/project-layout.html +4 -4
  67. package/dist/docs/reference/prompt.html +4 -4
  68. package/dist/docs/reference/result.html +4 -4
  69. package/dist/docs/reference/schedules.html +4 -4
  70. package/dist/docs/reference/sessions.html +4 -4
  71. package/dist/docs/reference/skills.html +4 -4
  72. package/dist/docs/reference/subagents.html +4 -4
  73. package/dist/docs/reference/tools.html +4 -4
  74. package/dist/docs/scaffolding-agents.html +4 -4
  75. package/dist/docs/skills/ab.html +4 -4
  76. package/dist/docs/skills/create-agent.html +4 -4
  77. package/dist/docs/skills/debug.html +4 -4
  78. package/dist/docs/skills/evals.html +4 -4
  79. package/dist/docs/skills/framework-map.html +4 -4
  80. package/dist/docs/skills/github.html +4 -4
  81. package/dist/docs/skills/hillclimb.html +4 -4
  82. package/dist/docs/skills/index.html +4 -4
  83. package/dist/docs/skills/mcp-auth.html +4 -4
  84. package/dist/docs/skills/otel.html +4 -4
  85. package/dist/docs/skills/setup-slack.html +4 -4
  86. package/dist/docs/storage.html +4 -4
  87. package/dist/docs/templates/agentic-owners.html +4 -4
  88. package/dist/docs/templates/agents-md.html +4 -4
  89. package/dist/docs/templates/code-wiki.html +4 -4
  90. package/dist/docs/templates/demo.html +4 -4
  91. package/dist/docs/templates/pr-autofixer.html +4 -4
  92. package/dist/docs/templates/security-help.html +4 -4
  93. package/dist/docs/templates/security-reviewer.html +4 -4
  94. package/dist/docs/templates/triage.html +4 -4
  95. package/dist/docs/troubleshooting.html +4 -4
  96. package/dist/filesystem.d.ts +440 -0
  97. package/dist/filesystem.d.ts.map +1 -0
  98. package/dist/filesystem.js +1694 -0
  99. package/dist/index.d.ts +2 -0
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +1 -0
  102. package/dist/internal/continuation-channel.d.ts +4 -2
  103. package/dist/internal/continuation-channel.d.ts.map +1 -1
  104. package/dist/internal/continuation-channel.js +21 -12
  105. package/dist/internal/continuation-identity.d.ts +13 -5
  106. package/dist/internal/continuation-identity.d.ts.map +1 -1
  107. package/dist/internal/continuation-identity.js +74 -35
  108. package/dist/internal/discovery/agent.d.ts.map +1 -1
  109. package/dist/internal/discovery/agent.js +80 -8
  110. package/dist/internal/discovery/info.d.ts.map +1 -1
  111. package/dist/internal/discovery/info.js +3 -0
  112. package/dist/internal/factory-resource-channel.d.ts +33 -0
  113. package/dist/internal/factory-resource-channel.d.ts.map +1 -0
  114. package/dist/internal/factory-resource-channel.js +77 -0
  115. package/dist/internal/filesystem/errors.d.ts +64 -0
  116. package/dist/internal/filesystem/errors.d.ts.map +1 -0
  117. package/dist/internal/filesystem/errors.js +175 -0
  118. package/dist/internal/filesystem/format.d.ts +28 -0
  119. package/dist/internal/filesystem/format.d.ts.map +1 -0
  120. package/dist/internal/filesystem/format.js +213 -0
  121. package/dist/internal/filesystem/merge.d.ts +34 -0
  122. package/dist/internal/filesystem/merge.d.ts.map +1 -0
  123. package/dist/internal/filesystem/merge.js +196 -0
  124. package/dist/internal/filesystem/scratch.d.ts +59 -0
  125. package/dist/internal/filesystem/scratch.d.ts.map +1 -0
  126. package/dist/internal/filesystem/scratch.js +212 -0
  127. package/dist/internal/filesystem/sdk-schemas.d.ts +29 -0
  128. package/dist/internal/filesystem/sdk-schemas.d.ts.map +1 -0
  129. package/dist/internal/filesystem/sdk-schemas.js +153 -0
  130. package/dist/internal/filesystem/tools.d.ts +42 -0
  131. package/dist/internal/filesystem/tools.d.ts.map +1 -0
  132. package/dist/internal/filesystem/tools.js +618 -0
  133. package/dist/internal/filesystem/walk.d.ts +74 -0
  134. package/dist/internal/filesystem/walk.d.ts.map +1 -0
  135. package/dist/internal/filesystem/walk.js +339 -0
  136. package/dist/internal/guest-network.d.ts +5 -2
  137. package/dist/internal/guest-network.d.ts.map +1 -1
  138. package/dist/internal/guest-network.js +7 -2
  139. package/dist/internal/hosted-delivery.d.ts.map +1 -1
  140. package/dist/internal/hosted-delivery.js +12 -2
  141. package/dist/internal/sdk-runner.d.ts +1 -1
  142. package/dist/internal/sdk-runner.d.ts.map +1 -1
  143. package/dist/internal/sdk-runner.js +3 -1
  144. package/dist/internal/session-engine.d.ts +22 -0
  145. package/dist/internal/session-engine.d.ts.map +1 -1
  146. package/dist/internal/session-engine.js +362 -40
  147. package/dist/internal/testing/factory-resource-fixtures.d.ts +48 -0
  148. package/dist/internal/testing/factory-resource-fixtures.d.ts.map +1 -0
  149. package/dist/internal/testing/factory-resource-fixtures.js +41 -0
  150. package/dist/playground/assets/{index-59KvgREd.js → index-8YiozU89.js} +38 -38
  151. package/dist/playground/index.html +1 -1
  152. package/dist/types.d.ts +51 -3
  153. package/dist/types.d.ts.map +1 -1
  154. package/docs/design/filesystem.md +376 -0
  155. package/docs/guides/github.md +5 -0
  156. package/docs/reference/channels.md +20 -0
  157. package/package.json +16 -2
  158. package/src/channels/change-monitors/change-monitors-channel.ts +62 -0
  159. package/src/channels/change-monitors/index.ts +8 -0
  160. package/src/channels/change-monitors/types.ts +44 -0
  161. package/src/channels/github/defaults.ts +4 -0
  162. package/src/channels/github/progress.ts +76 -10
  163. package/src/channels/issues/index.ts +9 -0
  164. package/src/channels/issues/issues-channel.ts +51 -0
  165. package/src/channels/issues/types.ts +41 -0
  166. package/src/filesystem.ts +2074 -0
  167. package/src/index.ts +28 -0
  168. package/src/internal/continuation-channel.ts +29 -12
  169. package/src/internal/continuation-identity.ts +122 -37
  170. package/src/internal/discovery/agent.ts +87 -1
  171. package/src/internal/discovery/info.ts +3 -0
  172. package/src/internal/factory-resource-channel.ts +122 -0
  173. package/src/internal/filesystem/errors.ts +220 -0
  174. package/src/internal/filesystem/format.ts +276 -0
  175. package/src/internal/filesystem/merge.ts +195 -0
  176. package/src/internal/filesystem/scratch.ts +255 -0
  177. package/src/internal/filesystem/sdk-schemas.ts +204 -0
  178. package/src/internal/filesystem/tools.ts +821 -0
  179. package/src/internal/filesystem/walk.ts +369 -0
  180. package/src/internal/guest-network.ts +8 -2
  181. package/src/internal/hosted-delivery.ts +18 -1
  182. package/src/internal/sdk-runner.ts +4 -0
  183. package/src/internal/session-engine.ts +439 -29
  184. package/src/internal/testing/factory-resource-fixtures.ts +85 -0
  185. package/src/types.ts +49 -3
  186. package/dist/docs/assets/chunks/@localSearchIndexroot.nrl1ifBq.js +0 -1
@@ -0,0 +1,821 @@
1
+ /**
2
+ * Native file tools synthesized from a bound {@link FileSystem}.
3
+ *
4
+ * Advertised name / input / output match `@cursor/sdk` tool-call types.
5
+ * Each tool is a `defineTool` whose runtime `inputSchema` accepts those
6
+ * fields plus the native aliases the harness still sends.
7
+ */
8
+
9
+ import { Buffer } from "node:buffer";
10
+ import { minimatch } from "minimatch";
11
+ import { z } from "zod";
12
+ import {
13
+ canonicalizeFileSystemToolName,
14
+ collectGrepMatches,
15
+ type FileSystem,
16
+ type FileSystemToolName,
17
+ fileSystemImage,
18
+ fileSystemText,
19
+ type GrepContentHit,
20
+ type GrepOutputMode,
21
+ type GrepResult,
22
+ InvalidGrepPatternError,
23
+ type SearchResult,
24
+ shapeGrepUnion,
25
+ sliceReadContent,
26
+ strReplaceOnFileSystem,
27
+ } from "../../filesystem.js";
28
+ import { defineTool } from "../../tools.js";
29
+ import type { DiscoveredTool, ToolDefinition } from "../../types.js";
30
+ import {
31
+ toolInputJsonSchema,
32
+ toolOutputJsonSchema,
33
+ validateToolInput,
34
+ } from "../json-schema.js";
35
+ import {
36
+ formatGlobOutput,
37
+ formatGrepOutput,
38
+ formatLsTree,
39
+ formatNumberedLines,
40
+ formatStrReplaceOutput,
41
+ formatWriteOutput,
42
+ slicedReadStartLine,
43
+ } from "./format.js";
44
+ import {
45
+ sdkDeleteArgs,
46
+ sdkDeleteResult,
47
+ sdkEditResult,
48
+ sdkGlobArgs,
49
+ sdkGlobResult,
50
+ sdkGrepArgs,
51
+ sdkGrepResult,
52
+ sdkLsArgs,
53
+ sdkLsResult,
54
+ sdkReadArgs,
55
+ sdkReadResult,
56
+ sdkSemSearchArgs,
57
+ sdkSemSearchResult,
58
+ sdkStrReplaceArgs,
59
+ sdkWriteArgs,
60
+ sdkWriteResult,
61
+ } from "./sdk-schemas.js";
62
+ import { collectGlob, collectListOrStat, lsFromList } from "./walk.js";
63
+
64
+ export const SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES = [
65
+ "Read",
66
+ "LS",
67
+ "Glob",
68
+ "Grep",
69
+ "Write",
70
+ "StrReplace",
71
+ "Delete",
72
+ "SemanticSearch",
73
+ ] as const;
74
+
75
+ export type SynthesizedFileSystemToolName =
76
+ (typeof SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES)[number];
77
+
78
+ const SYNTHESIZED_NAME_SET = new Set<string>(
79
+ SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES
80
+ );
81
+
82
+ export function isSynthesizedFileSystemToolName(name: string): boolean {
83
+ if (SYNTHESIZED_NAME_SET.has(name)) {
84
+ return true;
85
+ }
86
+ const canonical = canonicalizeFileSystemToolName(name);
87
+ return canonical !== undefined && SYNTHESIZED_NAME_SET.has(canonical);
88
+ }
89
+
90
+ export function rootFileToolsFromAuthored(
91
+ tools: readonly string[] | undefined
92
+ ): FileSystemToolName[] | undefined {
93
+ if (tools === undefined) {
94
+ return undefined;
95
+ }
96
+ if (tools.length === 0) {
97
+ return [];
98
+ }
99
+ const files: FileSystemToolName[] = [];
100
+ for (const name of tools) {
101
+ if (name === "edit") {
102
+ files.push("Write", "StrReplace");
103
+ continue;
104
+ }
105
+ const canonical = canonicalizeFileSystemToolName(name);
106
+ if (canonical !== undefined) {
107
+ files.push(canonical);
108
+ }
109
+ }
110
+ return files.length === 0 ? undefined : [...new Set(files)];
111
+ }
112
+
113
+ /**
114
+ * Host-default file-tool filter. Omitted `tools` keeps the default
115
+ * seven-tool set (`undefined`). A listed allowlist is closed: names that
116
+ * are not FileSystem methods synthesize nothing, so agents that already
117
+ * replaced natives with authored VFS tools (`tools: ["updateTodos"]` plus
118
+ * `agent/tools/Delete.ts`) do not also get host-disk Delete.
119
+ *
120
+ * Authored `root` still uses {@link rootFileToolsFromAuthored}, where a
121
+ * no-file-name allowlist means the default-on file layer.
122
+ */
123
+ export function hostFileToolsFromAuthored(
124
+ tools: readonly string[] | undefined
125
+ ): FileSystemToolName[] | undefined {
126
+ if (tools === undefined) {
127
+ return undefined;
128
+ }
129
+ return rootFileToolsFromAuthored(tools) ?? [];
130
+ }
131
+
132
+ const HOST_DEFAULT_SYNTHESIZED_NAMES: readonly SynthesizedFileSystemToolName[] =
133
+ SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES.filter(
134
+ (name) => name !== "SemanticSearch"
135
+ );
136
+
137
+ /**
138
+ * Names July will actually synthesize for this agent. Discovery reserves
139
+ * only this set, not every FileSystem alias.
140
+ */
141
+ export function synthesizedFileSystemToolNames(options: {
142
+ hasRoot: boolean;
143
+ tools?: readonly string[];
144
+ }): readonly SynthesizedFileSystemToolName[] {
145
+ const filter = options.hasRoot
146
+ ? rootFileToolsFromAuthored(options.tools)
147
+ : hostFileToolsFromAuthored(options.tools);
148
+ const catalog = options.hasRoot
149
+ ? SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES
150
+ : HOST_DEFAULT_SYNTHESIZED_NAMES;
151
+ if (filter === undefined) {
152
+ return catalog;
153
+ }
154
+ return catalog.filter((name) => filter.includes(name));
155
+ }
156
+
157
+ function wantsTool(
158
+ filter: readonly FileSystemToolName[] | undefined,
159
+ name: FileSystemToolName
160
+ ): boolean {
161
+ return filter === undefined || filter.includes(name);
162
+ }
163
+
164
+ /**
165
+ * Copy native aliases onto the canonical SDK field when the canonical
166
+ * field is absent. Zod sees the SDK shape; callers can still send
167
+ * `contents` / `old_string` / `output_mode`.
168
+ */
169
+ function aliasKeys(aliases: Record<string, string>) {
170
+ return (raw: unknown): unknown => {
171
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
172
+ return raw;
173
+ }
174
+ const input = { ...(raw as Record<string, unknown>) };
175
+ for (const [from, to] of Object.entries(aliases)) {
176
+ if (input[to] === undefined && input[from] !== undefined) {
177
+ input[to] = input[from];
178
+ }
179
+ }
180
+ return input;
181
+ };
182
+ }
183
+
184
+ function lineCount(content: string): number {
185
+ return content === "" ? 0 : content.split("\n").length;
186
+ }
187
+
188
+ function parseGrepOutputMode(value: string | undefined): GrepOutputMode {
189
+ if (value === "files" || value === "files_with_matches") {
190
+ return "files_with_matches";
191
+ }
192
+ if (value === "count") {
193
+ return "count";
194
+ }
195
+ return "content";
196
+ }
197
+
198
+ function contextLineCount(
199
+ specific: number | undefined,
200
+ both: number | undefined
201
+ ): number {
202
+ const value = specific ?? both;
203
+ if (value === undefined || !Number.isFinite(value)) {
204
+ return 0;
205
+ }
206
+ return Math.max(0, Math.floor(value));
207
+ }
208
+
209
+ function compileToolGrepPattern(
210
+ pattern: string,
211
+ options: { caseInsensitive?: boolean; multiline?: boolean }
212
+ ): RegExp {
213
+ try {
214
+ const flags = `${options.caseInsensitive === true ? "i" : ""}${
215
+ options.multiline === true ? "s" : ""
216
+ }`;
217
+ return new RegExp(pattern, flags === "" ? undefined : flags);
218
+ } catch {
219
+ throw new InvalidGrepPatternError(pattern);
220
+ }
221
+ }
222
+
223
+ /**
224
+ * File discovery for multiline Grep. A file `path` is that file (the
225
+ * caller spelling, so host-default relative paths stay relative). A
226
+ * directory or omitted path uses `FileSystem.glob`, which applies the
227
+ * mount's own root. Slash-free globs are recursive, matching line grep.
228
+ */
229
+ async function collectMultilineGrepFiles(
230
+ root: FileSystem,
231
+ input: { path?: string; glob?: string }
232
+ ): Promise<string[]> {
233
+ const listed = await collectListOrStat(root, input.path);
234
+ if (listed.kind === "file") {
235
+ const filePath = input.path ?? "";
236
+ if (
237
+ input.glob !== undefined &&
238
+ !fileMatchesGrepGlob(filePath, input.glob)
239
+ ) {
240
+ return [];
241
+ }
242
+ return [filePath];
243
+ }
244
+ if (listed.kind === "missing") {
245
+ return [];
246
+ }
247
+ const entries = await collectGlob(root, {
248
+ pattern: recursiveGrepGlob(input.glob),
249
+ ...(input.path === undefined ? {} : { dir: input.path }),
250
+ });
251
+ return entries.map((entry) => entry.path);
252
+ }
253
+
254
+ function recursiveGrepGlob(glob: string | undefined): string {
255
+ if (glob === undefined || glob.length === 0) {
256
+ return "**/*";
257
+ }
258
+ if (glob.startsWith("**/") || glob.includes("/")) {
259
+ return glob;
260
+ }
261
+ return `**/${glob}`;
262
+ }
263
+
264
+ function fileMatchesGrepGlob(filePath: string, globPattern: string): boolean {
265
+ const relative = filePath.replace(/^\//, "");
266
+ if (
267
+ minimatch(relative, globPattern, { dot: true }) ||
268
+ minimatch(filePath, globPattern, { dot: true })
269
+ ) {
270
+ return true;
271
+ }
272
+ if (!globPattern.includes("/")) {
273
+ const slash = Math.max(
274
+ relative.lastIndexOf("/"),
275
+ relative.lastIndexOf("\\")
276
+ );
277
+ const base = slash === -1 ? relative : relative.slice(slash + 1);
278
+ return minimatch(base, globPattern, { dot: true });
279
+ }
280
+ return false;
281
+ }
282
+
283
+ function multilineHitsInContent(
284
+ path: string,
285
+ content: string,
286
+ regex: RegExp
287
+ ): GrepResult[] {
288
+ const global = new RegExp(
289
+ regex.source,
290
+ regex.flags.includes("g") ? regex.flags : `${regex.flags}g`
291
+ );
292
+ const hits: GrepResult[] = [];
293
+ let match = global.exec(content);
294
+ while (match !== null) {
295
+ hits.push({
296
+ path,
297
+ lineNumber: content.slice(0, match.index).split("\n").length,
298
+ line: content.slice(match.index).split("\n")[0] ?? "",
299
+ });
300
+ if (match[0].length === 0) {
301
+ global.lastIndex += 1;
302
+ }
303
+ match = global.exec(content);
304
+ }
305
+ return hits;
306
+ }
307
+
308
+ async function collectMultilineGrepMatches(
309
+ root: FileSystem,
310
+ input: {
311
+ pattern: string;
312
+ path?: string;
313
+ glob?: string;
314
+ caseInsensitive?: boolean;
315
+ },
316
+ opts: { outputMode: GrepOutputMode; headLimit?: number; offset?: number }
317
+ ): Promise<GrepResult[]> {
318
+ const regex = compileToolGrepPattern(input.pattern, {
319
+ caseInsensitive: input.caseInsensitive,
320
+ multiline: true,
321
+ });
322
+ const files = await collectMultilineGrepFiles(root, input);
323
+ const matches: GrepResult[] = [];
324
+ const offset = opts.offset !== undefined && opts.offset > 0 ? opts.offset : 0;
325
+ const headLimit =
326
+ opts.headLimit !== undefined && opts.headLimit > 0
327
+ ? opts.headLimit
328
+ : undefined;
329
+ let skippedItems = 0;
330
+ let takenItems = 0;
331
+ for (const filePath of files) {
332
+ let content: string | Uint8Array;
333
+ try {
334
+ content = await root.read(filePath);
335
+ } catch {
336
+ continue;
337
+ }
338
+ if (typeof content !== "string") {
339
+ continue;
340
+ }
341
+ const hits = multilineHitsInContent(filePath, content, regex);
342
+ if (hits.length === 0) {
343
+ continue;
344
+ }
345
+ if (opts.outputMode === "content") {
346
+ for (const hit of hits) {
347
+ if (skippedItems < offset) {
348
+ skippedItems++;
349
+ continue;
350
+ }
351
+ matches.push(hit);
352
+ takenItems++;
353
+ if (headLimit !== undefined && takenItems >= headLimit) {
354
+ return matches;
355
+ }
356
+ }
357
+ continue;
358
+ }
359
+ if (skippedItems < offset) {
360
+ skippedItems++;
361
+ continue;
362
+ }
363
+ if (headLimit !== undefined && takenItems >= headLimit) {
364
+ break;
365
+ }
366
+ matches.push(...hits);
367
+ takenItems++;
368
+ }
369
+ return matches;
370
+ }
371
+
372
+ async function attachGrepContext(
373
+ root: FileSystem,
374
+ matches: GrepResult[],
375
+ context: { before: number; after: number }
376
+ ): Promise<GrepContentHit[]> {
377
+ if (context.before === 0 && context.after === 0) {
378
+ return matches;
379
+ }
380
+ const linesByPath = new Map<string, string[]>();
381
+ const hits: GrepContentHit[] = [];
382
+ for (const match of matches) {
383
+ let lines = linesByPath.get(match.path);
384
+ if (lines === undefined) {
385
+ try {
386
+ const content = await root.read(match.path);
387
+ lines = typeof content === "string" ? content.split("\n") : [];
388
+ } catch {
389
+ lines = [];
390
+ }
391
+ linesByPath.set(match.path, lines);
392
+ }
393
+ const index = match.lineNumber - 1;
394
+ hits.push({
395
+ ...match,
396
+ ...(context.before > 0
397
+ ? {
398
+ beforeContext: lines.slice(
399
+ Math.max(0, index - context.before),
400
+ Math.max(0, index)
401
+ ),
402
+ }
403
+ : {}),
404
+ ...(context.after > 0
405
+ ? { afterContext: lines.slice(index + 1, index + 1 + context.after) }
406
+ : {}),
407
+ });
408
+ }
409
+ return hits;
410
+ }
411
+
412
+ function discovered(
413
+ name: FileSystemToolName,
414
+ definition: ToolDefinition,
415
+ contract: { input: z.ZodTypeAny; output: z.ZodTypeAny }
416
+ ): DiscoveredTool {
417
+ const effect =
418
+ typeof definition.effect === "function" ? "dynamic" : definition.effect;
419
+ return {
420
+ name,
421
+ description: definition.description,
422
+ inputSchema: toolInputJsonSchema(contract.input),
423
+ outputSchema: toolOutputJsonSchema(contract.output),
424
+ execution: "server",
425
+ needsApproval: false,
426
+ ...(effect === undefined ? {} : { effect }),
427
+ definition,
428
+ };
429
+ }
430
+
431
+ const readInputSchema = z.preprocess(
432
+ aliasKeys({}),
433
+ z.object({
434
+ path: z.string(),
435
+ offset: z.number().int().optional(),
436
+ limit: z.number().int().optional(),
437
+ })
438
+ );
439
+
440
+ function readTool(root: FileSystem): DiscoveredTool {
441
+ return discovered(
442
+ "Read",
443
+ defineTool({
444
+ description:
445
+ "Reads a file from the local filesystem. This tool can also read image files when called with the appropriate path. Formats supported: jpeg/jpg, png, gif, webp.",
446
+ inputSchema: readInputSchema,
447
+ effect: "read",
448
+ async execute({ path, offset, limit }) {
449
+ const content = await root.read(path);
450
+ const image = fileSystemImage(content, path);
451
+ if (image !== undefined) {
452
+ return {
453
+ content: [
454
+ { type: "text" as const, text: `Read image file: ${path}` },
455
+ {
456
+ type: "image" as const,
457
+ data: Buffer.from(image.bytes).toString("base64"),
458
+ mimeType: image.mimeType,
459
+ },
460
+ ],
461
+ };
462
+ }
463
+ const text = fileSystemText(content);
464
+ const totalLines = lineCount(text);
465
+ return formatNumberedLines(sliceReadContent(text, offset, limit), {
466
+ startLine: slicedReadStartLine(totalLines, offset),
467
+ totalLines,
468
+ });
469
+ },
470
+ }),
471
+ { input: sdkReadArgs, output: sdkReadResult }
472
+ );
473
+ }
474
+
475
+ const lsInputSchema = z.preprocess(
476
+ aliasKeys({ target_directory: "path", ignore_globs: "ignore" }),
477
+ z.object({
478
+ path: z.string(),
479
+ ignore: z.array(z.string()).optional(),
480
+ })
481
+ );
482
+
483
+ function lsTool(root: FileSystem): DiscoveredTool {
484
+ return discovered(
485
+ "LS",
486
+ defineTool({
487
+ description: `Lists files and directories in a given path.
488
+ The 'path' parameter must be an absolute path.
489
+ You can optionally provide an array of glob patterns to ignore with the "ignore" parameter.
490
+
491
+ Other details:
492
+ - The result does not display dot-files and dot-directories.`,
493
+ inputSchema: lsInputSchema,
494
+ effect: "read",
495
+ async execute({ path, ignore }) {
496
+ const listed = await lsFromList(root, path, ignore);
497
+ if (listed.status === "error") {
498
+ throw new Error(`Error listing directory: ${listed.error.message}`);
499
+ }
500
+ return formatLsTree(listed.value.directoryTreeRoot);
501
+ },
502
+ }),
503
+ { input: sdkLsArgs, output: sdkLsResult }
504
+ );
505
+ }
506
+
507
+ const globInputSchema = z.preprocess(
508
+ aliasKeys({
509
+ glob_pattern: "globPattern",
510
+ target_directory: "targetDirectory",
511
+ path: "targetDirectory",
512
+ }),
513
+ z.object({
514
+ targetDirectory: z.string().optional(),
515
+ globPattern: z.string(),
516
+ })
517
+ );
518
+
519
+ function globTool(root: FileSystem): DiscoveredTool {
520
+ return discovered(
521
+ "Glob",
522
+ defineTool({
523
+ description: `
524
+ Tool to search for files matching a glob pattern
525
+
526
+ - Works fast with codebases of any size
527
+ - Returns matching file paths sorted by modification time
528
+ - Use this tool when you need to find files by name patterns
529
+ - You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches that are potentially useful as a batch.
530
+ `,
531
+ inputSchema: globInputSchema,
532
+ effect: "read",
533
+ async execute({ globPattern, targetDirectory }) {
534
+ const dir = targetDirectory ?? "/";
535
+ const files = (
536
+ await collectGlob(root, {
537
+ pattern: globPattern,
538
+ ...(targetDirectory === undefined ? {} : { dir: targetDirectory }),
539
+ })
540
+ ).map((entry) => entry.path);
541
+ return formatGlobOutput(dir, files);
542
+ },
543
+ }),
544
+ { input: sdkGlobArgs, output: sdkGlobResult }
545
+ );
546
+ }
547
+
548
+ const grepInputSchema = z.preprocess(
549
+ (raw) => {
550
+ const aliased = aliasKeys({
551
+ output_mode: "outputMode",
552
+ head_limit: "headLimit",
553
+ "-i": "caseInsensitive",
554
+ "-A": "contextAfter",
555
+ "-B": "contextBefore",
556
+ "-C": "context",
557
+ })(raw);
558
+ if (
559
+ aliased !== null &&
560
+ typeof aliased === "object" &&
561
+ !Array.isArray(aliased)
562
+ ) {
563
+ const input = aliased as { outputMode?: unknown };
564
+ if (input.outputMode === "files") {
565
+ input.outputMode = "files_with_matches";
566
+ }
567
+ }
568
+ return aliased;
569
+ },
570
+ z.object({
571
+ pattern: z.string(),
572
+ path: z.string().optional(),
573
+ glob: z.string().optional(),
574
+ outputMode: z.string().optional(),
575
+ contextBefore: z.number().optional(),
576
+ contextAfter: z.number().optional(),
577
+ context: z.number().optional(),
578
+ caseInsensitive: z.boolean().optional(),
579
+ type: z.string().optional(),
580
+ headLimit: z.number().optional(),
581
+ offset: z.number().optional(),
582
+ multiline: z.boolean().optional(),
583
+ sort: z.string().optional(),
584
+ sortAscending: z.boolean().optional(),
585
+ })
586
+ );
587
+
588
+ function grepTool(root: FileSystem): DiscoveredTool {
589
+ return discovered(
590
+ "Grep",
591
+ defineTool({
592
+ description: `A search tool built on ripgrep. Results are capped to several thousand output lines for responsiveness; when truncation occurs, the results report "at least" counts, but are otherwise accurate.`,
593
+ inputSchema: grepInputSchema,
594
+ effect: "read",
595
+ async execute(input) {
596
+ const outputMode = parseGrepOutputMode(input.outputMode);
597
+ const query = {
598
+ pattern: input.pattern,
599
+ ...(input.path === undefined ? {} : { path: input.path }),
600
+ ...(input.glob === undefined ? {} : { glob: input.glob }),
601
+ caseInsensitive: input.caseInsensitive === true,
602
+ };
603
+ const page = {
604
+ outputMode,
605
+ ...(input.headLimit === undefined
606
+ ? {}
607
+ : { headLimit: input.headLimit }),
608
+ ...(input.offset === undefined ? {} : { offset: input.offset }),
609
+ };
610
+ const matches =
611
+ input.multiline === true
612
+ ? await collectMultilineGrepMatches(root, query, page)
613
+ : await collectGrepMatches(root, query, page);
614
+ const before = contextLineCount(input.contextBefore, input.context);
615
+ const after = contextLineCount(input.contextAfter, input.context);
616
+ const hits =
617
+ outputMode === "content"
618
+ ? await attachGrepContext(root, matches, { before, after })
619
+ : matches;
620
+ return formatGrepOutput(shapeGrepUnion(hits, outputMode));
621
+ },
622
+ }),
623
+ { input: sdkGrepArgs, output: sdkGrepResult }
624
+ );
625
+ }
626
+
627
+ const writeInputSchema = z.preprocess(
628
+ aliasKeys({ contents: "fileText" }),
629
+ z.object({
630
+ path: z.string(),
631
+ fileText: z.string(),
632
+ returnFileContentAfterWrite: z.boolean().optional(),
633
+ })
634
+ );
635
+
636
+ function writeTool(root: FileSystem): DiscoveredTool {
637
+ return discovered(
638
+ "Write",
639
+ defineTool({
640
+ description: "Writes a file to the local filesystem.",
641
+ inputSchema: writeInputSchema,
642
+ effect: "write",
643
+ async execute({ path, fileText }) {
644
+ await root.write(path, fileText);
645
+ return formatWriteOutput(path);
646
+ },
647
+ }),
648
+ { input: sdkWriteArgs, output: sdkWriteResult }
649
+ );
650
+ }
651
+
652
+ const strReplaceInputSchema = z.preprocess(
653
+ aliasKeys({
654
+ old_string: "oldText",
655
+ new_string: "newText",
656
+ replace_all: "replaceAll",
657
+ }),
658
+ z.object({
659
+ path: z.string(),
660
+ oldText: z.string(),
661
+ newText: z.string(),
662
+ replaceAll: z.boolean().optional(),
663
+ })
664
+ );
665
+
666
+ function strReplaceTool(root: FileSystem): DiscoveredTool {
667
+ return discovered(
668
+ "StrReplace",
669
+ defineTool({
670
+ description: "Performs exact string replacements in files.",
671
+ inputSchema: strReplaceInputSchema,
672
+ effect: "write",
673
+ async execute({ path, oldText, newText, replaceAll }) {
674
+ const { occurrencesModified } = await strReplaceOnFileSystem(root, {
675
+ path,
676
+ oldText,
677
+ newText,
678
+ ...(replaceAll === undefined ? {} : { replaceAll }),
679
+ });
680
+ return formatStrReplaceOutput({
681
+ path,
682
+ replaceAll: replaceAll === true,
683
+ occurrencesModified,
684
+ });
685
+ },
686
+ }),
687
+ { input: sdkStrReplaceArgs, output: sdkEditResult }
688
+ );
689
+ }
690
+
691
+ const deleteInputSchema = z.object({
692
+ path: z.string(),
693
+ });
694
+
695
+ function deleteTool(root: FileSystem): DiscoveredTool {
696
+ return discovered(
697
+ "Delete",
698
+ defineTool({
699
+ description: `Deletes a file at the specified path. The operation will fail gracefully if:
700
+ - The file doesn't exist
701
+ - The operation is rejected for security reasons
702
+ - The file cannot be deleted`,
703
+ inputSchema: deleteInputSchema,
704
+ effect: "write",
705
+ async execute({ path }) {
706
+ await root.delete(path);
707
+ return "";
708
+ },
709
+ }),
710
+ { input: sdkDeleteArgs, output: sdkDeleteResult }
711
+ );
712
+ }
713
+
714
+ const semanticSearchInputSchema = z.preprocess(
715
+ aliasKeys({ num_results: "numResults" }),
716
+ z.object({
717
+ query: z.string(),
718
+ targetDirectories: z.array(z.string()).optional(),
719
+ explanation: z.string().optional(),
720
+ numResults: z.number().optional(),
721
+ })
722
+ );
723
+
724
+ function semanticSearchTool(root: FileSystem): DiscoveredTool {
725
+ return discovered(
726
+ "SemanticSearch",
727
+ defineTool({
728
+ description:
729
+ "`SemanticSearch`: semantic search that finds code by meaning, not exact text",
730
+ inputSchema: semanticSearchInputSchema,
731
+ effect: "read",
732
+ async execute({ query, targetDirectories, numResults }) {
733
+ const cap =
734
+ numResults !== undefined && numResults > 0 ? numResults : undefined;
735
+ const hits: SearchResult[] = [];
736
+ for await (const hit of root.search({
737
+ query,
738
+ ...(targetDirectories === undefined ? {} : { targetDirectories }),
739
+ ...(cap === undefined ? {} : { maxResults: cap }),
740
+ })) {
741
+ hits.push(hit);
742
+ if (cap !== undefined && hits.length >= cap) {
743
+ break;
744
+ }
745
+ }
746
+ return hits.map((hit) => `${hit.path}: ${hit.snippet}`).join("\n");
747
+ },
748
+ }),
749
+ { input: sdkSemSearchArgs, output: sdkSemSearchResult }
750
+ );
751
+ }
752
+
753
+ const FILE_SYSTEM_TOOL_FACTORIES: Record<
754
+ FileSystemToolName,
755
+ (root: FileSystem) => DiscoveredTool
756
+ > = {
757
+ Read: readTool,
758
+ LS: lsTool,
759
+ Glob: globTool,
760
+ Grep: grepTool,
761
+ Write: writeTool,
762
+ StrReplace: strReplaceTool,
763
+ Delete: deleteTool,
764
+ SemanticSearch: semanticSearchTool,
765
+ };
766
+
767
+ /**
768
+ * Look up the `defineTool` factory for a native or allowlist name.
769
+ * The only name that still inspects `input` is legacy `edit`:
770
+ * `fileText` / `contents` selects Write, otherwise StrReplace.
771
+ */
772
+ export function fileSystemTool(
773
+ root: FileSystem,
774
+ name: string,
775
+ input: Record<string, unknown> = {}
776
+ ): DiscoveredTool | undefined {
777
+ if (name === "edit") {
778
+ return "fileText" in input || "contents" in input
779
+ ? writeTool(root)
780
+ : strReplaceTool(root);
781
+ }
782
+ const canonical = canonicalizeFileSystemToolName(name);
783
+ if (canonical === undefined) {
784
+ return undefined;
785
+ }
786
+ return FILE_SYSTEM_TOOL_FACTORIES[canonical](root);
787
+ }
788
+
789
+ /** Validate and run the same tool a turn or `callTool` would. */
790
+ export async function runFileSystemTool(
791
+ root: FileSystem,
792
+ name: string,
793
+ input: Record<string, unknown> = {}
794
+ ): Promise<unknown> {
795
+ const tool = fileSystemTool(root, name, input);
796
+ if (tool === undefined) {
797
+ throw new Error(`Unknown file system tool: ${name}`);
798
+ }
799
+ const execute = tool.definition.execute;
800
+ if (typeof execute !== "function") {
801
+ throw new Error(`File system tool ${name} has no execute`);
802
+ }
803
+ const validation = validateToolInput(tool.definition.inputSchema, input);
804
+ if (!validation.ok) {
805
+ throw new Error(validation.message);
806
+ }
807
+ return execute(validation.value as never, {} as never);
808
+ }
809
+
810
+ export function synthesizeFileSystemTools(
811
+ root: FileSystem,
812
+ filter?: readonly FileSystemToolName[]
813
+ ): DiscoveredTool[] {
814
+ const tools: DiscoveredTool[] = [];
815
+ for (const name of SYNTHESIZED_FILE_SYSTEM_TOOL_NAMES) {
816
+ if (wantsTool(filter, name)) {
817
+ tools.push(FILE_SYSTEM_TOOL_FACTORIES[name](root));
818
+ }
819
+ }
820
+ return tools;
821
+ }