wave-agent-sdk 1.0.4 → 1.0.6

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 (194) hide show
  1. package/dist/agent.d.ts +23 -1
  2. package/dist/agent.js +34 -4
  3. package/dist/managers/aiManager.d.ts +36 -0
  4. package/dist/managers/aiManager.js +240 -8
  5. package/dist/managers/messageManager.d.ts +1 -3
  6. package/dist/managers/messageManager.js +19 -9
  7. package/dist/managers/slashCommandManager.js +28 -0
  8. package/dist/managers/subagentManager.d.ts +0 -2
  9. package/dist/services/session.js +2 -9
  10. package/dist/telemetry/instrumentation.d.ts +1 -1
  11. package/dist/telemetry/instrumentation.js +57 -28
  12. package/dist/tools/bashTool.js +16 -6
  13. package/dist/tools/grepTool.js +11 -3
  14. package/dist/types/index.d.ts +3 -0
  15. package/dist/types/messaging.d.ts +2 -0
  16. package/dist/utils/containerSetup.js +0 -3
  17. package/dist/utils/messageOperations.d.ts +10 -1
  18. package/dist/utils/messageOperations.js +19 -1
  19. package/dist/utils/notificationXml.js +5 -0
  20. package/dist/utils/ripgrep.d.ts +4 -4
  21. package/dist/utils/ripgrep.js +4 -27
  22. package/package.json +20 -8
  23. package/bin/rg +0 -79
  24. package/dist/managers/forkedAgentManager.d.ts +0 -50
  25. package/dist/managers/forkedAgentManager.js +0 -130
  26. package/scripts/install_ripgrep.js +0 -111
  27. package/scripts/postinstall.js +0 -38
  28. package/src/agent.ts +0 -1271
  29. package/src/constants/subagents.ts +0 -4
  30. package/src/constants/toolLimits.ts +0 -15
  31. package/src/constants/tools.ts +0 -24
  32. package/src/core/plugin.ts +0 -237
  33. package/src/core/session.ts +0 -9
  34. package/src/index.ts +0 -38
  35. package/src/managers/MemoryRuleManager.ts +0 -198
  36. package/src/managers/aiManager.ts +0 -2429
  37. package/src/managers/backgroundTaskManager.ts +0 -480
  38. package/src/managers/bangManager.ts +0 -119
  39. package/src/managers/cronManager.ts +0 -401
  40. package/src/managers/foregroundTaskManager.ts +0 -30
  41. package/src/managers/forkedAgentManager.ts +0 -216
  42. package/src/managers/hookManager.ts +0 -1089
  43. package/src/managers/liveConfigManager.ts +0 -445
  44. package/src/managers/lspManager.ts +0 -470
  45. package/src/managers/mcpManager.ts +0 -1010
  46. package/src/managers/messageManager.ts +0 -1180
  47. package/src/managers/messageQueue.ts +0 -157
  48. package/src/managers/permissionManager.ts +0 -1140
  49. package/src/managers/planManager.ts +0 -112
  50. package/src/managers/pluginManager.ts +0 -330
  51. package/src/managers/pluginScopeManager.ts +0 -124
  52. package/src/managers/reversionManager.ts +0 -178
  53. package/src/managers/skillManager.ts +0 -578
  54. package/src/managers/slashCommandManager.ts +0 -564
  55. package/src/managers/subagentManager.ts +0 -915
  56. package/src/managers/toolManager.ts +0 -489
  57. package/src/managers/workflowManager.ts +0 -493
  58. package/src/prompts/autoMemory.ts +0 -33
  59. package/src/prompts/autoMemoryExtraction.ts +0 -146
  60. package/src/prompts/index.ts +0 -506
  61. package/src/prompts/planModeReminders.ts +0 -126
  62. package/src/services/GitService.ts +0 -131
  63. package/src/services/MarketplaceService.ts +0 -1052
  64. package/src/services/MemoryRuleService.ts +0 -71
  65. package/src/services/aiService.ts +0 -919
  66. package/src/services/authService.ts +0 -565
  67. package/src/services/autoMemoryService.ts +0 -280
  68. package/src/services/configurationService.ts +0 -1520
  69. package/src/services/fileWatcher.ts +0 -319
  70. package/src/services/hook.ts +0 -348
  71. package/src/services/initializationService.ts +0 -357
  72. package/src/services/interactionService.ts +0 -229
  73. package/src/services/jsonlHandler.ts +0 -295
  74. package/src/services/memory.ts +0 -234
  75. package/src/services/pluginLoader.ts +0 -252
  76. package/src/services/remoteSettingsService.ts +0 -366
  77. package/src/services/reversionService.ts +0 -122
  78. package/src/services/session.ts +0 -922
  79. package/src/services/taskManager.ts +0 -321
  80. package/src/telemetry/events.ts +0 -65
  81. package/src/telemetry/instrumentation.ts +0 -499
  82. package/src/telemetry/sessionTracing.ts +0 -348
  83. package/src/tools/agentTool.ts +0 -322
  84. package/src/tools/askUserQuestion.ts +0 -160
  85. package/src/tools/bashTool.ts +0 -621
  86. package/src/tools/buildTool.ts +0 -61
  87. package/src/tools/cronCreateTool.ts +0 -161
  88. package/src/tools/cronDeleteTool.ts +0 -51
  89. package/src/tools/cronListTool.ts +0 -47
  90. package/src/tools/editTool.ts +0 -313
  91. package/src/tools/enterPlanMode.ts +0 -124
  92. package/src/tools/enterWorktreeTool.ts +0 -190
  93. package/src/tools/exitPlanMode.ts +0 -139
  94. package/src/tools/exitWorktreeTool.ts +0 -236
  95. package/src/tools/globTool.ts +0 -167
  96. package/src/tools/grepTool.ts +0 -399
  97. package/src/tools/lspTool.ts +0 -883
  98. package/src/tools/readTool.ts +0 -426
  99. package/src/tools/skillTool.ts +0 -248
  100. package/src/tools/taskManagementTools.ts +0 -574
  101. package/src/tools/taskStopTool.ts +0 -78
  102. package/src/tools/types.ts +0 -137
  103. package/src/tools/webFetchTool.ts +0 -373
  104. package/src/tools/workflowTool.ts +0 -205
  105. package/src/tools/writeTool.ts +0 -267
  106. package/src/types/agent.ts +0 -128
  107. package/src/types/auth.ts +0 -19
  108. package/src/types/commands.ts +0 -30
  109. package/src/types/config.ts +0 -43
  110. package/src/types/configuration.ts +0 -168
  111. package/src/types/core.ts +0 -105
  112. package/src/types/cron.ts +0 -13
  113. package/src/types/environment.ts +0 -106
  114. package/src/types/fileSearch.ts +0 -4
  115. package/src/types/history.ts +0 -7
  116. package/src/types/hooks.ts +0 -256
  117. package/src/types/index.ts +0 -41
  118. package/src/types/lsp.ts +0 -98
  119. package/src/types/marketplace.ts +0 -71
  120. package/src/types/mcp.ts +0 -43
  121. package/src/types/memoryRule.ts +0 -31
  122. package/src/types/messaging.ts +0 -114
  123. package/src/types/permissions.ts +0 -80
  124. package/src/types/plugins.ts +0 -39
  125. package/src/types/processes.ts +0 -99
  126. package/src/types/reversion.ts +0 -29
  127. package/src/types/session.ts +0 -12
  128. package/src/types/skills.ts +0 -108
  129. package/src/types/tasks.ts +0 -13
  130. package/src/types/telemetry.ts +0 -98
  131. package/src/types/tools.ts +0 -44
  132. package/src/types/workflow.ts +0 -6
  133. package/src/utils/abortUtils.ts +0 -118
  134. package/src/utils/atomicWrite.ts +0 -61
  135. package/src/utils/bashParser.ts +0 -899
  136. package/src/utils/cacheControlUtils.ts +0 -426
  137. package/src/utils/commandArgumentParser.ts +0 -161
  138. package/src/utils/commandPathResolver.ts +0 -88
  139. package/src/utils/configPaths.ts +0 -220
  140. package/src/utils/configValidator.ts +0 -100
  141. package/src/utils/constants.ts +0 -39
  142. package/src/utils/container.ts +0 -92
  143. package/src/utils/containerSetup.ts +0 -371
  144. package/src/utils/convertMessagesForAPI.ts +0 -326
  145. package/src/utils/cronTasks.ts +0 -128
  146. package/src/utils/cronTasksLock.ts +0 -182
  147. package/src/utils/cronToHuman.ts +0 -99
  148. package/src/utils/customCommands.ts +0 -95
  149. package/src/utils/editUtils.ts +0 -20
  150. package/src/utils/fileFormat.ts +0 -40
  151. package/src/utils/fileSearch.ts +0 -151
  152. package/src/utils/fileUtils.ts +0 -223
  153. package/src/utils/gitUtils.ts +0 -315
  154. package/src/utils/globalLogger.ts +0 -128
  155. package/src/utils/groupMessagesByApiRound.ts +0 -121
  156. package/src/utils/hookMatcher.ts +0 -176
  157. package/src/utils/markdownParser.ts +0 -317
  158. package/src/utils/mcpUtils.ts +0 -138
  159. package/src/utils/messageOperations.ts +0 -641
  160. package/src/utils/modelCapabilities.ts +0 -30
  161. package/src/utils/nameGenerator.ts +0 -99
  162. package/src/utils/notificationXml.ts +0 -57
  163. package/src/utils/openaiClient.ts +0 -251
  164. package/src/utils/parseCronExpression.ts +0 -78
  165. package/src/utils/path.ts +0 -72
  166. package/src/utils/pathEncoder.ts +0 -400
  167. package/src/utils/pathSafety.ts +0 -40
  168. package/src/utils/promptHistory.ts +0 -168
  169. package/src/utils/ripgrep.ts +0 -35
  170. package/src/utils/shellResolver.ts +0 -190
  171. package/src/utils/skillParser.ts +0 -246
  172. package/src/utils/stringUtils.ts +0 -156
  173. package/src/utils/subagentParser.ts +0 -279
  174. package/src/utils/taskReminder.ts +0 -96
  175. package/src/utils/tokenCalculation.ts +0 -43
  176. package/src/utils/tokenEstimate.ts +0 -34
  177. package/src/utils/toolResultStorage.ts +0 -117
  178. package/src/utils/worktreeSession.ts +0 -26
  179. package/src/utils/worktreeUtils.ts +0 -786
  180. package/src/workflow/budgetTracker.ts +0 -34
  181. package/src/workflow/concurrencyLimiter.ts +0 -47
  182. package/src/workflow/journal.ts +0 -95
  183. package/src/workflow/progressReporter.ts +0 -141
  184. package/src/workflow/runState.ts +0 -65
  185. package/src/workflow/scriptRuntime.ts +0 -274
  186. package/src/workflow/structuredOutput.ts +0 -123
  187. package/src/workflow/types.ts +0 -101
  188. package/src/workflow/workflowApis.ts +0 -410
  189. package/vendor/ripgrep/linux-aarch64/rg +0 -0
  190. package/vendor/ripgrep/linux-x86_64/rg +0 -0
  191. package/vendor/ripgrep/macos-aarch64/rg +0 -0
  192. package/vendor/ripgrep/macos-x86_64/rg +0 -0
  193. package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
  194. package/vendor/ripgrep/windows-x86_64/rg.exe +0 -0
@@ -1,167 +0,0 @@
1
- import { glob } from "glob";
2
- import { stat } from "fs/promises";
3
- import type { ToolPlugin, ToolResult, ToolContext } from "./types.js";
4
- import { resolvePath, getDisplayPath } from "../utils/path.js";
5
- import { GLOB_TOOL_NAME } from "../constants/tools.js";
6
-
7
- /**
8
- * Maximum number of files returned by glob tool
9
- */
10
- const MAX_GLOB_RESULTS = 100;
11
-
12
- /**
13
- * Glob Tool Plugin - Fast file pattern matching
14
- */
15
- export const globTool: ToolPlugin = {
16
- name: GLOB_TOOL_NAME,
17
- config: {
18
- type: "function",
19
- function: {
20
- name: GLOB_TOOL_NAME,
21
- description:
22
- "Fast file pattern matching tool that works with any codebase size",
23
- parameters: {
24
- type: "object",
25
- properties: {
26
- pattern: {
27
- type: "string",
28
- description: "The glob pattern to match files against",
29
- },
30
- path: {
31
- type: "string",
32
- description:
33
- 'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',
34
- },
35
- limit: {
36
- type: "number",
37
- description: "Maximum number of files to return. Defaults to 100.",
38
- },
39
- },
40
- required: ["pattern"],
41
- },
42
- },
43
- },
44
- prompt:
45
- () => `- Fast file pattern matching tool that works with any codebase size
46
- - Supports glob patterns like "**/*.js" or "src/**/*.ts"
47
- - Returns matching file paths sorted by modification time
48
- - Use this tool when you need to find files by name patterns
49
- - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead
50
- - You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.`,
51
- execute: async (
52
- args: Record<string, unknown>,
53
- context: ToolContext,
54
- ): Promise<ToolResult> => {
55
- const pattern = args.pattern as string;
56
- const searchPath = args.path as string;
57
- const limit = (args.limit as number) || MAX_GLOB_RESULTS;
58
- const startTime = Date.now();
59
-
60
- if (!pattern || typeof pattern !== "string") {
61
- return {
62
- success: false,
63
- content: "",
64
- error: "pattern parameter is required and must be a string",
65
- };
66
- }
67
-
68
- try {
69
- // Determine search directory
70
- const workdir = searchPath
71
- ? resolvePath(searchPath, context.workdir)
72
- : context.workdir;
73
-
74
- // Execute glob search using glob package
75
- const matches = await glob(pattern, {
76
- cwd: workdir,
77
- nodir: true,
78
- dot: true,
79
- ignore: ["**/.git/**"],
80
- });
81
-
82
- if (matches.length === 0) {
83
- return {
84
- success: true,
85
- content: "No files match the pattern",
86
- shortResult: "No matches found",
87
- };
88
- }
89
-
90
- // Get file modification time and sort
91
- const filesWithStats = await Promise.allSettled(
92
- matches.map(async (file) => {
93
- try {
94
- const fullPath = resolvePath(file, workdir);
95
- const stats = await stat(fullPath);
96
- return {
97
- path: file,
98
- mtime: stats.mtime,
99
- };
100
- } catch {
101
- // If unable to get file stats, use current time
102
- return {
103
- path: file,
104
- mtime: new Date(),
105
- };
106
- }
107
- }),
108
- );
109
-
110
- // Filter successful results and sort by modification time
111
- const sortedFiles = filesWithStats
112
- .filter((result) => result.status === "fulfilled")
113
- .map(
114
- (result) =>
115
- (result as PromiseFulfilledResult<{ path: string; mtime: Date }>)
116
- .value,
117
- )
118
- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime()) // Most recently modified files first
119
- .map((item) => item.path);
120
-
121
- const totalCount = sortedFiles.length;
122
- const finalFiles = sortedFiles.slice(0, limit);
123
-
124
- // Format output
125
- const output = finalFiles
126
- .map((file, index) => `${index + 1}. ${file}`)
127
- .join("\n");
128
-
129
- const isTruncated = totalCount > limit;
130
- const shortResult = isTruncated
131
- ? `Found ${totalCount} files (showing first ${limit})`
132
- : `Found ${totalCount} file${totalCount === 1 ? "" : "s"}`;
133
-
134
- const durationMs = Date.now() - startTime;
135
-
136
- return {
137
- success: true,
138
- content: output,
139
- shortResult,
140
- metadata: {
141
- durationMs,
142
- numFiles: totalCount,
143
- truncated: isTruncated,
144
- },
145
- };
146
- } catch (error) {
147
- return {
148
- success: false,
149
- content: "",
150
- error: `Glob search failed: ${error instanceof Error ? error.message : String(error)}`,
151
- };
152
- }
153
- },
154
- formatCompactParams: (
155
- params: Record<string, unknown>,
156
- context: ToolContext,
157
- ) => {
158
- const pattern = params.pattern as string;
159
- const path = params.path as string;
160
-
161
- if (path) {
162
- const displayPath = getDisplayPath(path, context.workdir);
163
- return `${pattern} in ${displayPath}`;
164
- }
165
- return pattern || "";
166
- },
167
- };
@@ -1,399 +0,0 @@
1
- import type { ToolPlugin, ToolResult, ToolContext } from "./types.js";
2
- import { spawn } from "child_process";
3
- import { rgPath } from "../utils/ripgrep.js";
4
- import { getDisplayPath } from "../utils/path.js";
5
- import { logger } from "../utils/globalLogger.js";
6
- import {
7
- GREP_TOOL_NAME,
8
- BASH_TOOL_NAME,
9
- AGENT_TOOL_NAME,
10
- } from "../constants/tools.js";
11
-
12
- // Version control system directories to exclude from searches.
13
- // These are excluded automatically because they create noise in search results.
14
- // Mirrors Claude Code's VCS_DIRECTORIES_TO_EXCLUDE.
15
- const VCS_DIRECTORIES_TO_EXCLUDE = [
16
- ".git",
17
- ".svn",
18
- ".hg",
19
- ".bzr",
20
- ".jj",
21
- ".sl",
22
- ] as const;
23
-
24
- /**
25
- * Grep tool plugin - powerful search tool based on ripgrep
26
- */
27
- export const grepTool: ToolPlugin = {
28
- name: GREP_TOOL_NAME,
29
- config: {
30
- type: "function",
31
- function: {
32
- name: GREP_TOOL_NAME,
33
- description: "A powerful search tool built on ripgrep",
34
- parameters: {
35
- type: "object",
36
- properties: {
37
- pattern: {
38
- type: "string",
39
- description:
40
- "The regular expression pattern to search for in file contents",
41
- },
42
- path: {
43
- type: "string",
44
- description:
45
- "File or directory to search in (rg PATH). Defaults to current working directory.",
46
- },
47
- glob: {
48
- type: "string",
49
- description:
50
- 'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob',
51
- },
52
- output_mode: {
53
- type: "string",
54
- enum: ["content", "files_with_matches", "count"],
55
- description:
56
- 'Output mode: "content" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), "files_with_matches" shows file paths (supports head_limit), "count" shows match counts (supports head_limit). Defaults to "files_with_matches".',
57
- },
58
- "-B": {
59
- type: "number",
60
- description:
61
- 'Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise.',
62
- },
63
- "-A": {
64
- type: "number",
65
- description:
66
- 'Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise.',
67
- },
68
- "-C": {
69
- type: "number",
70
- description:
71
- 'Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise.',
72
- },
73
- "-n": {
74
- type: "boolean",
75
- description:
76
- 'Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true.',
77
- },
78
- "-i": {
79
- type: "boolean",
80
- description: "Case insensitive search (rg -i)",
81
- },
82
- type: {
83
- type: "string",
84
- description:
85
- "File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types.",
86
- },
87
- head_limit: {
88
- type: "number",
89
- description:
90
- 'Limit output to first N lines/entries, equivalent to "| head -N". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults to 0 (unlimited).',
91
- },
92
- multiline: {
93
- type: "boolean",
94
- description:
95
- "Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false.",
96
- },
97
- offset: {
98
- type: "number",
99
- description: "The number of matches to skip.",
100
- },
101
- context: {
102
- type: "number",
103
- description:
104
- 'Alias for -C. Number of lines to show before and after each match. Requires output_mode: "content", ignored otherwise.',
105
- },
106
- },
107
- required: ["pattern"],
108
- },
109
- },
110
- },
111
- prompt: () => `A powerful search tool built on ripgrep
112
-
113
- Usage:
114
- - ALWAYS use ${GREP_TOOL_NAME} for search tasks. NEVER invoke \`grep\` or \`rg\` as a ${BASH_TOOL_NAME} command. The ${GREP_TOOL_NAME} tool has been optimized for correct permissions and access.
115
- - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
116
- - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
117
- - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
118
- - Use ${AGENT_TOOL_NAME} tool for open-ended searches requiring multiple rounds
119
- - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
120
- - Multiline matching: By default patterns match within single lines only. For cross-line patterns like \`struct \\{[\\s\\S]*?field\`, use \`multiline: true\`
121
- `,
122
- execute: async (
123
- args: Record<string, unknown>,
124
- context: ToolContext,
125
- ): Promise<ToolResult> => {
126
- const pattern = args.pattern as string;
127
- const searchPath = args.path as string;
128
- const globPattern = args.glob as string;
129
- const outputMode = (args.output_mode as string) || "files_with_matches";
130
- const contextBefore = args["-B"] as number;
131
- const contextAfter = args["-A"] as number;
132
- const contextAround = args["-C"] as number;
133
- const showLineNumbers = args["-n"] !== false;
134
- const caseInsensitive = args["-i"] as boolean;
135
- const fileType = args.type as string;
136
- const headLimit = args.head_limit as number;
137
- const multiline = args.multiline as boolean;
138
- const offset = args.offset as number;
139
- const contextArg = args.context as number;
140
-
141
- if (!pattern || typeof pattern !== "string") {
142
- return {
143
- success: false,
144
- content: "",
145
- error: "pattern parameter is required and must be a string",
146
- };
147
- }
148
-
149
- if (!rgPath) {
150
- return {
151
- success: false,
152
- content: "",
153
- error:
154
- "ripgrep is not available. Please install @vscode/ripgrep package.",
155
- };
156
- }
157
-
158
- try {
159
- const workdir = context.workdir;
160
- const rgArgs: string[] = [
161
- "--color=never",
162
- "--max-columns=500",
163
- // Search hidden files/directories by default (aligns with Claude Code).
164
- // --hidden does NOT disable .gitignore; only --no-ignore would.
165
- "--hidden",
166
- ];
167
-
168
- // Exclude VCS directories to avoid noise from version control metadata.
169
- // --hidden above would otherwise traverse .git/.svn/etc.
170
- for (const dir of VCS_DIRECTORIES_TO_EXCLUDE) {
171
- rgArgs.push("--glob", `!${dir}`);
172
- }
173
-
174
- // Set output mode
175
- if (outputMode === "files_with_matches") {
176
- rgArgs.push("-l");
177
- } else if (outputMode === "count") {
178
- rgArgs.push("-c");
179
- }
180
- // content mode is default, no special parameters needed
181
-
182
- // Add line numbers (only effective in content mode)
183
- if (showLineNumbers && outputMode === "content") {
184
- rgArgs.push("-n");
185
- }
186
-
187
- // Add file names (in content mode)
188
- if (outputMode === "content") {
189
- rgArgs.push("-H");
190
- }
191
-
192
- // Case insensitive
193
- if (caseInsensitive) {
194
- rgArgs.push("-i");
195
- }
196
-
197
- // Multiline mode
198
- if (multiline) {
199
- rgArgs.push("-U", "--multiline-dotall");
200
- }
201
-
202
- // Context lines (only effective in content mode)
203
- if (outputMode === "content") {
204
- const effectiveContext = contextArg ?? contextAround;
205
- if (effectiveContext) {
206
- rgArgs.push("-C", effectiveContext.toString());
207
- } else {
208
- if (contextBefore) {
209
- rgArgs.push("-B", contextBefore.toString());
210
- }
211
- if (contextAfter) {
212
- rgArgs.push("-A", contextAfter.toString());
213
- }
214
- }
215
- }
216
-
217
- // File type filtering
218
- if (fileType) {
219
- rgArgs.push("--type", fileType);
220
- }
221
-
222
- // Glob pattern filtering
223
- if (globPattern) {
224
- rgArgs.push("--glob", globPattern);
225
- }
226
-
227
- // Add search pattern - use -e parameter to avoid patterns starting with - being mistaken as command line options
228
- rgArgs.push("-e", pattern);
229
-
230
- // Add search path
231
- if (searchPath) {
232
- rgArgs.push(searchPath);
233
- } else {
234
- rgArgs.push(".");
235
- }
236
-
237
- const result = await executeCommand(rgPath, rgArgs, workdir);
238
-
239
- // Only a process-level spawn failure (exitCode null) is a hard error.
240
- // rg exit 2 means some files were unreadable (e.g. device-name files
241
- // like "nul" on Windows); stdout still holds usable partial results.
242
- if (result.exitCode === null) {
243
- return {
244
- success: false,
245
- content: "",
246
- error: `ripgrep failed: ${result.stderr}`,
247
- };
248
- }
249
-
250
- if (result.exitCode !== 0 && result.exitCode !== 1) {
251
- logger.debug(
252
- `ripgrep exited with code ${result.exitCode}, keeping partial results: ${result.stderr.trim()}`,
253
- );
254
- }
255
-
256
- const output = result.stdout.trim();
257
- if (!output) {
258
- return {
259
- success: true,
260
- content:
261
- "No matches found. Suggestion: specify the 'path' field to search in ignored or other directories (e.g., 'node_modules'), as the default search path is the current working directory and respects .gitignore.",
262
- shortResult: "No matches found",
263
- metadata: {
264
- numMatches: 0,
265
- },
266
- };
267
- }
268
-
269
- let lines = output.split("\n");
270
- const totalMatches = lines.length;
271
-
272
- // Apply offset
273
- const effectiveOffset = offset || 0;
274
- if (effectiveOffset > 0) {
275
- lines = lines.slice(effectiveOffset);
276
- }
277
-
278
- // Apply head_limit
279
- const effectiveHeadLimit = headLimit || 0;
280
- let truncated = false;
281
- if (effectiveHeadLimit > 0 && lines.length > effectiveHeadLimit) {
282
- lines = lines.slice(0, effectiveHeadLimit);
283
- truncated = true;
284
- }
285
-
286
- const finalOutput = lines.join("\n");
287
-
288
- // Generate short result
289
- let shortResult: string;
290
- const numMatches = lines.length;
291
-
292
- if (outputMode === "files_with_matches") {
293
- shortResult = `Found ${numMatches} file${numMatches === 1 ? "" : "s"}`;
294
- } else if (outputMode === "count") {
295
- shortResult = `Match counts for ${numMatches} file${numMatches === 1 ? "" : "s"}`;
296
- } else {
297
- shortResult = `Found ${numMatches} matching line${numMatches === 1 ? "" : "s"}`;
298
- }
299
-
300
- if (effectiveOffset > 0 || truncated) {
301
- shortResult += ` (showing ${numMatches} of ${totalMatches})`;
302
- }
303
-
304
- return {
305
- success: true,
306
- content: finalOutput,
307
- shortResult,
308
- metadata: {
309
- numMatches: totalMatches,
310
- truncated,
311
- appliedLimit: effectiveHeadLimit,
312
- appliedOffset: effectiveOffset,
313
- },
314
- };
315
- } catch (error) {
316
- return {
317
- success: false,
318
- content: "",
319
- error: `Search failed: ${error instanceof Error ? error.message : String(error)}`,
320
- };
321
- }
322
- },
323
- formatCompactParams: (
324
- params: Record<string, unknown>,
325
- context: ToolContext,
326
- ) => {
327
- const pattern = params.pattern as string;
328
- const outputMode = params.output_mode as string;
329
- const fileType = params.type as string;
330
- const path = params.path as string;
331
-
332
- let result = pattern || "";
333
-
334
- if (fileType) {
335
- result += ` ${fileType}`;
336
- }
337
-
338
- if (path) {
339
- const displayPath = getDisplayPath(path, context.workdir);
340
- result += ` in ${displayPath}`;
341
- }
342
-
343
- if (outputMode && outputMode !== "files_with_matches") {
344
- result += ` [${outputMode}]`;
345
- }
346
-
347
- return result;
348
- },
349
- };
350
-
351
- /**
352
- * Execute command and return result
353
- */
354
- function executeCommand(
355
- command: string,
356
- args: string[],
357
- cwd: string,
358
- ): Promise<{
359
- stdout: string;
360
- stderr: string;
361
- exitCode: number | null;
362
- error: boolean;
363
- }> {
364
- return new Promise((resolve) => {
365
- const child = spawn(command, args, {
366
- cwd,
367
- stdio: ["ignore", "pipe", "pipe"],
368
- });
369
-
370
- let stdout = "";
371
- let stderr = "";
372
-
373
- child.stdout?.on("data", (data) => {
374
- stdout += data.toString();
375
- });
376
-
377
- child.stderr?.on("data", (data) => {
378
- stderr += data.toString();
379
- });
380
-
381
- child.on("close", (code) => {
382
- resolve({
383
- stdout,
384
- stderr,
385
- exitCode: code,
386
- error: code !== 0 && code !== 1, // rg returns 1 for no matches, not an error
387
- });
388
- });
389
-
390
- child.on("error", (err) => {
391
- resolve({
392
- stdout,
393
- stderr: err.message,
394
- exitCode: null,
395
- error: true,
396
- });
397
- });
398
- });
399
- }