wave-agent-sdk 1.0.5 → 1.0.7

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 (202) hide show
  1. package/dist/agent.d.ts +34 -1
  2. package/dist/agent.js +49 -4
  3. package/dist/index.d.ts +3 -1
  4. package/dist/index.js +1 -1
  5. package/dist/managers/aiManager.d.ts +36 -0
  6. package/dist/managers/aiManager.js +240 -11
  7. package/dist/managers/messageManager.d.ts +2 -4
  8. package/dist/managers/messageManager.js +14 -7
  9. package/dist/managers/slashCommandManager.js +28 -0
  10. package/dist/managers/subagentManager.d.ts +0 -2
  11. package/dist/services/aiService.d.ts +2 -3
  12. package/dist/services/aiService.js +4 -18
  13. package/dist/services/configurationService.d.ts +7 -0
  14. package/dist/services/configurationService.js +10 -0
  15. package/dist/telemetry/instrumentation.d.ts +1 -1
  16. package/dist/telemetry/instrumentation.js +57 -28
  17. package/dist/tools/bashTool.js +16 -6
  18. package/dist/tools/grepTool.js +11 -3
  19. package/dist/types/core.d.ts +1 -34
  20. package/dist/types/index.d.ts +4 -0
  21. package/dist/types/messaging.d.ts +2 -0
  22. package/dist/utils/cacheControlUtils.d.ts +5 -27
  23. package/dist/utils/cacheControlUtils.js +12 -73
  24. package/dist/utils/containerSetup.js +0 -3
  25. package/dist/utils/messageOperations.d.ts +2 -1
  26. package/dist/utils/messageOperations.js +2 -1
  27. package/dist/utils/notificationXml.js +5 -0
  28. package/dist/utils/ripgrep.d.ts +4 -4
  29. package/dist/utils/ripgrep.js +4 -27
  30. package/package.json +20 -8
  31. package/bin/rg +0 -79
  32. package/dist/managers/forkedAgentManager.d.ts +0 -50
  33. package/dist/managers/forkedAgentManager.js +0 -130
  34. package/scripts/install_ripgrep.js +0 -111
  35. package/scripts/postinstall.js +0 -38
  36. package/src/agent.ts +0 -1271
  37. package/src/constants/subagents.ts +0 -4
  38. package/src/constants/toolLimits.ts +0 -15
  39. package/src/constants/tools.ts +0 -24
  40. package/src/core/plugin.ts +0 -237
  41. package/src/core/session.ts +0 -9
  42. package/src/index.ts +0 -38
  43. package/src/managers/MemoryRuleManager.ts +0 -198
  44. package/src/managers/aiManager.ts +0 -2429
  45. package/src/managers/backgroundTaskManager.ts +0 -480
  46. package/src/managers/bangManager.ts +0 -119
  47. package/src/managers/cronManager.ts +0 -401
  48. package/src/managers/foregroundTaskManager.ts +0 -30
  49. package/src/managers/forkedAgentManager.ts +0 -216
  50. package/src/managers/hookManager.ts +0 -1089
  51. package/src/managers/liveConfigManager.ts +0 -445
  52. package/src/managers/lspManager.ts +0 -470
  53. package/src/managers/mcpManager.ts +0 -1010
  54. package/src/managers/messageManager.ts +0 -1184
  55. package/src/managers/messageQueue.ts +0 -157
  56. package/src/managers/permissionManager.ts +0 -1140
  57. package/src/managers/planManager.ts +0 -112
  58. package/src/managers/pluginManager.ts +0 -330
  59. package/src/managers/pluginScopeManager.ts +0 -124
  60. package/src/managers/reversionManager.ts +0 -178
  61. package/src/managers/skillManager.ts +0 -578
  62. package/src/managers/slashCommandManager.ts +0 -564
  63. package/src/managers/subagentManager.ts +0 -915
  64. package/src/managers/toolManager.ts +0 -489
  65. package/src/managers/workflowManager.ts +0 -493
  66. package/src/prompts/autoMemory.ts +0 -33
  67. package/src/prompts/autoMemoryExtraction.ts +0 -146
  68. package/src/prompts/index.ts +0 -506
  69. package/src/prompts/planModeReminders.ts +0 -126
  70. package/src/services/GitService.ts +0 -131
  71. package/src/services/MarketplaceService.ts +0 -1052
  72. package/src/services/MemoryRuleService.ts +0 -71
  73. package/src/services/aiService.ts +0 -919
  74. package/src/services/authService.ts +0 -565
  75. package/src/services/autoMemoryService.ts +0 -280
  76. package/src/services/configurationService.ts +0 -1520
  77. package/src/services/fileWatcher.ts +0 -319
  78. package/src/services/hook.ts +0 -348
  79. package/src/services/initializationService.ts +0 -357
  80. package/src/services/interactionService.ts +0 -229
  81. package/src/services/jsonlHandler.ts +0 -295
  82. package/src/services/memory.ts +0 -234
  83. package/src/services/pluginLoader.ts +0 -252
  84. package/src/services/remoteSettingsService.ts +0 -366
  85. package/src/services/reversionService.ts +0 -122
  86. package/src/services/session.ts +0 -917
  87. package/src/services/taskManager.ts +0 -321
  88. package/src/telemetry/events.ts +0 -65
  89. package/src/telemetry/instrumentation.ts +0 -499
  90. package/src/telemetry/sessionTracing.ts +0 -348
  91. package/src/tools/agentTool.ts +0 -322
  92. package/src/tools/askUserQuestion.ts +0 -160
  93. package/src/tools/bashTool.ts +0 -621
  94. package/src/tools/buildTool.ts +0 -61
  95. package/src/tools/cronCreateTool.ts +0 -161
  96. package/src/tools/cronDeleteTool.ts +0 -51
  97. package/src/tools/cronListTool.ts +0 -47
  98. package/src/tools/editTool.ts +0 -313
  99. package/src/tools/enterPlanMode.ts +0 -124
  100. package/src/tools/enterWorktreeTool.ts +0 -190
  101. package/src/tools/exitPlanMode.ts +0 -139
  102. package/src/tools/exitWorktreeTool.ts +0 -236
  103. package/src/tools/globTool.ts +0 -167
  104. package/src/tools/grepTool.ts +0 -399
  105. package/src/tools/lspTool.ts +0 -883
  106. package/src/tools/readTool.ts +0 -426
  107. package/src/tools/skillTool.ts +0 -248
  108. package/src/tools/taskManagementTools.ts +0 -574
  109. package/src/tools/taskStopTool.ts +0 -78
  110. package/src/tools/types.ts +0 -137
  111. package/src/tools/webFetchTool.ts +0 -373
  112. package/src/tools/workflowTool.ts +0 -205
  113. package/src/tools/writeTool.ts +0 -267
  114. package/src/types/agent.ts +0 -128
  115. package/src/types/auth.ts +0 -19
  116. package/src/types/commands.ts +0 -30
  117. package/src/types/config.ts +0 -43
  118. package/src/types/configuration.ts +0 -168
  119. package/src/types/core.ts +0 -105
  120. package/src/types/cron.ts +0 -13
  121. package/src/types/environment.ts +0 -106
  122. package/src/types/fileSearch.ts +0 -4
  123. package/src/types/history.ts +0 -7
  124. package/src/types/hooks.ts +0 -256
  125. package/src/types/index.ts +0 -41
  126. package/src/types/lsp.ts +0 -98
  127. package/src/types/marketplace.ts +0 -71
  128. package/src/types/mcp.ts +0 -43
  129. package/src/types/memoryRule.ts +0 -31
  130. package/src/types/messaging.ts +0 -114
  131. package/src/types/permissions.ts +0 -80
  132. package/src/types/plugins.ts +0 -39
  133. package/src/types/processes.ts +0 -99
  134. package/src/types/reversion.ts +0 -29
  135. package/src/types/session.ts +0 -12
  136. package/src/types/skills.ts +0 -108
  137. package/src/types/tasks.ts +0 -13
  138. package/src/types/telemetry.ts +0 -98
  139. package/src/types/tools.ts +0 -44
  140. package/src/types/workflow.ts +0 -6
  141. package/src/utils/abortUtils.ts +0 -118
  142. package/src/utils/atomicWrite.ts +0 -61
  143. package/src/utils/bashParser.ts +0 -899
  144. package/src/utils/cacheControlUtils.ts +0 -426
  145. package/src/utils/commandArgumentParser.ts +0 -161
  146. package/src/utils/commandPathResolver.ts +0 -88
  147. package/src/utils/configPaths.ts +0 -220
  148. package/src/utils/configValidator.ts +0 -100
  149. package/src/utils/constants.ts +0 -39
  150. package/src/utils/container.ts +0 -92
  151. package/src/utils/containerSetup.ts +0 -371
  152. package/src/utils/convertMessagesForAPI.ts +0 -326
  153. package/src/utils/cronTasks.ts +0 -128
  154. package/src/utils/cronTasksLock.ts +0 -182
  155. package/src/utils/cronToHuman.ts +0 -99
  156. package/src/utils/customCommands.ts +0 -95
  157. package/src/utils/editUtils.ts +0 -20
  158. package/src/utils/fileFormat.ts +0 -40
  159. package/src/utils/fileSearch.ts +0 -151
  160. package/src/utils/fileUtils.ts +0 -223
  161. package/src/utils/gitUtils.ts +0 -315
  162. package/src/utils/globalLogger.ts +0 -128
  163. package/src/utils/groupMessagesByApiRound.ts +0 -121
  164. package/src/utils/hookMatcher.ts +0 -176
  165. package/src/utils/markdownParser.ts +0 -317
  166. package/src/utils/mcpUtils.ts +0 -138
  167. package/src/utils/messageOperations.ts +0 -659
  168. package/src/utils/modelCapabilities.ts +0 -30
  169. package/src/utils/nameGenerator.ts +0 -99
  170. package/src/utils/notificationXml.ts +0 -57
  171. package/src/utils/openaiClient.ts +0 -251
  172. package/src/utils/parseCronExpression.ts +0 -78
  173. package/src/utils/path.ts +0 -72
  174. package/src/utils/pathEncoder.ts +0 -400
  175. package/src/utils/pathSafety.ts +0 -40
  176. package/src/utils/promptHistory.ts +0 -168
  177. package/src/utils/ripgrep.ts +0 -35
  178. package/src/utils/shellResolver.ts +0 -190
  179. package/src/utils/skillParser.ts +0 -246
  180. package/src/utils/stringUtils.ts +0 -156
  181. package/src/utils/subagentParser.ts +0 -279
  182. package/src/utils/taskReminder.ts +0 -96
  183. package/src/utils/tokenCalculation.ts +0 -43
  184. package/src/utils/tokenEstimate.ts +0 -34
  185. package/src/utils/toolResultStorage.ts +0 -117
  186. package/src/utils/worktreeSession.ts +0 -26
  187. package/src/utils/worktreeUtils.ts +0 -786
  188. package/src/workflow/budgetTracker.ts +0 -34
  189. package/src/workflow/concurrencyLimiter.ts +0 -47
  190. package/src/workflow/journal.ts +0 -95
  191. package/src/workflow/progressReporter.ts +0 -141
  192. package/src/workflow/runState.ts +0 -65
  193. package/src/workflow/scriptRuntime.ts +0 -274
  194. package/src/workflow/structuredOutput.ts +0 -123
  195. package/src/workflow/types.ts +0 -101
  196. package/src/workflow/workflowApis.ts +0 -410
  197. package/vendor/ripgrep/linux-aarch64/rg +0 -0
  198. package/vendor/ripgrep/linux-x86_64/rg +0 -0
  199. package/vendor/ripgrep/macos-aarch64/rg +0 -0
  200. package/vendor/ripgrep/macos-x86_64/rg +0 -0
  201. package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
  202. package/vendor/ripgrep/windows-x86_64/rg.exe +0 -0
@@ -1,426 +0,0 @@
1
- import { readFile, stat } from "fs/promises";
2
- import { extname } from "path";
3
- import { createHash } from "crypto";
4
- import { logger } from "../utils/globalLogger.js";
5
- import type { ToolPlugin, ToolResult, ToolContext } from "./types.js";
6
- import { resolvePath, getDisplayPath } from "../utils/path.js";
7
- import { formatLineNumberPrefix } from "../utils/stringUtils.js";
8
- import { estimateTokens } from "../utils/tokenEstimate.js";
9
- import {
10
- isBinaryDocument,
11
- getBinaryDocumentError,
12
- } from "../utils/fileFormat.js";
13
- import { convertImageToBase64 } from "../utils/messageOperations.js";
14
- import { READ_TOOL_NAME } from "../constants/tools.js";
15
-
16
- /**
17
- * Supported image file extensions
18
- */
19
- const SUPPORTED_IMAGE_EXTENSIONS = [
20
- "png",
21
- "jpeg",
22
- "jpg",
23
- "gif",
24
- "webp",
25
- ] as const;
26
-
27
- /**
28
- * Check if a file path represents an image file
29
- * @param filePath - Path to the file
30
- * @returns true if the file is a supported image format
31
- */
32
- function isImageFile(filePath: string): boolean {
33
- const ext = extname(filePath).toLowerCase().substring(1);
34
- return (SUPPORTED_IMAGE_EXTENSIONS as readonly string[]).includes(ext);
35
- }
36
-
37
- /**
38
- * Validate image file size
39
- * @param filePath - Path to the image file
40
- * @param maxSizeBytes - Maximum allowed file size in bytes (default: 20MB)
41
- * @returns Promise<boolean> - true if file size is within limit
42
- */
43
- async function validateImageFileSize(
44
- filePath: string,
45
- maxSizeBytes: number = 20 * 1024 * 1024,
46
- ): Promise<boolean> {
47
- try {
48
- const stats = await stat(filePath);
49
- return stats.size <= maxSizeBytes;
50
- } catch {
51
- return false;
52
- }
53
- }
54
-
55
- /**
56
- * Get MIME type for image file based on extension
57
- * @param filePath - Path to the image file
58
- * @returns MIME type string
59
- */
60
- function getImageMimeType(filePath: string): string {
61
- const ext = extname(filePath).toLowerCase().substring(1);
62
- switch (ext) {
63
- case "png":
64
- return "image/png";
65
- case "jpg":
66
- case "jpeg":
67
- return "image/jpeg";
68
- case "gif":
69
- return "image/gif";
70
- case "webp":
71
- return "image/webp";
72
- default:
73
- return "image/png"; // Default fallback
74
- }
75
- }
76
-
77
- /**
78
- * Process an image file and return ToolResult with image data
79
- * @param filePath - Path to the image file
80
- * @param context - Tool execution context
81
- * @returns Promise<ToolResult> with image data
82
- */
83
- async function processImageFile(
84
- filePath: string,
85
- context: ToolContext,
86
- ): Promise<ToolResult> {
87
- try {
88
- // Resolve path
89
- const actualFilePath = filePath.startsWith("/")
90
- ? filePath
91
- : resolvePath(filePath, context.workdir);
92
-
93
- // Validate file size
94
- const isValidSize = await validateImageFileSize(actualFilePath);
95
- if (!isValidSize) {
96
- const stats = await stat(actualFilePath);
97
- const sizeMB = (stats.size / (1024 * 1024)).toFixed(2);
98
- return {
99
- success: false,
100
- content: "",
101
- error: `Image file exceeds 20MB limit (actual: ${sizeMB}MB)`,
102
- };
103
- }
104
-
105
- // Convert image to base64
106
- const imageDataUrl = convertImageToBase64(actualFilePath);
107
- const mimeType = getImageMimeType(actualFilePath);
108
-
109
- // Extract base64 data from data URL (remove data:image/type;base64, prefix)
110
- const base64Data = imageDataUrl.split(",")[1] || "";
111
-
112
- return {
113
- success: true,
114
- content: `Image file processed: ${getDisplayPath(filePath, context.workdir)}\nFormat: ${mimeType}\nSize: Available for AI processing`,
115
- shortResult: `Image processed (${mimeType})`,
116
- images: [
117
- {
118
- data: base64Data,
119
- mediaType: mimeType,
120
- },
121
- ],
122
- metadata: {
123
- type: "image",
124
- mimeType,
125
- },
126
- };
127
- } catch (error) {
128
- return {
129
- success: false,
130
- content: "",
131
- error: `Failed to process image: ${error instanceof Error ? error.message : String(error)}`,
132
- };
133
- }
134
- }
135
-
136
- /**
137
- * Read Tool Plugin - Read file content
138
- */
139
- export const readTool: ToolPlugin = {
140
- name: READ_TOOL_NAME,
141
- prompt:
142
- () => `Reads a file from the local filesystem. You can access any file directly by using this tool.
143
- Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
144
-
145
- Usage:
146
- - The file_path parameter must be an absolute path, not a relative path
147
- - By default, it reads up to 2000 lines starting from the beginning of the file
148
- - You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters
149
- - If the file content exceeds the token limit, use offset and limit parameters to read specific portions of the file, or use Bash with grep/jq to extract specific content
150
- - Results are returned using cat -n format, with line numbers starting at 1
151
- - This tool allows Agent to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Agent is a multimodal LLM.
152
- - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
153
- - You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
154
- - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.
155
- - Binary document formats (PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX) are not supported and will return an error.`,
156
- config: {
157
- type: "function",
158
- function: {
159
- name: READ_TOOL_NAME,
160
- description: "Read a file from the local filesystem.",
161
- parameters: {
162
- type: "object",
163
- properties: {
164
- file_path: {
165
- type: "string",
166
- description: "The absolute path to the file to read",
167
- },
168
- offset: {
169
- type: "number",
170
- description:
171
- "The line number to start reading from. Only provide if the file is too large to read at once",
172
- },
173
- limit: {
174
- type: "number",
175
- description:
176
- "The number of lines to read. Only provide if the file is too large to read at once.",
177
- },
178
- },
179
- required: ["file_path"],
180
- },
181
- },
182
- },
183
- execute: async (
184
- args: Record<string, unknown>,
185
- context: ToolContext,
186
- ): Promise<ToolResult> => {
187
- const filePath = args.file_path as string;
188
- const offset = args.offset as number;
189
- const limit = args.limit as number;
190
-
191
- if (!filePath || typeof filePath !== "string") {
192
- return {
193
- success: false,
194
- content: "",
195
- error: "file_path parameter is required and must be a string",
196
- };
197
- }
198
-
199
- // Trigger conditional rule loading for this file
200
- context.messageManager?.triggerFileRead(filePath);
201
-
202
- // Check for binary document formats
203
- if (isBinaryDocument(filePath)) {
204
- const isPdf = filePath.toLowerCase().endsWith(".pdf");
205
- return {
206
- success: false,
207
- content: "",
208
- error: getBinaryDocumentError(filePath),
209
- metadata: {
210
- type: isPdf ? "pdf" : "binary",
211
- },
212
- };
213
- }
214
-
215
- // Check permissions
216
- if (context.permissionManager) {
217
- const permissionContext = context.permissionManager.createContext(
218
- READ_TOOL_NAME,
219
- context.permissionMode || "default",
220
- context.canUseToolCallback,
221
- args,
222
- );
223
- const decision =
224
- await context.permissionManager.checkPermission(permissionContext);
225
- if (decision.behavior === "deny") {
226
- return {
227
- success: false,
228
- content: "",
229
- error: decision.message || "Permission denied",
230
- };
231
- }
232
- }
233
-
234
- // Check if this is an image file
235
- if (isImageFile(filePath)) {
236
- return processImageFile(filePath, context);
237
- }
238
-
239
- try {
240
- // Note: New Read tool requires absolute paths, so we don't use resolvePath
241
- // But for compatibility, if it's not an absolute path, we still try to resolve
242
- const actualFilePath = filePath.startsWith("/")
243
- ? filePath
244
- : resolvePath(filePath, context.workdir);
245
-
246
- const stats = await stat(actualFilePath);
247
-
248
- // Deduplication: only dedup if the exact same range was read before
249
- if (context.readFileState) {
250
- const state = context.readFileState.get(actualFilePath);
251
- // Only dedup entries from a prior Read with explicit offset (not Edit/Write entries)
252
- if (
253
- state &&
254
- state.mtime === stats.mtime.getTime() &&
255
- state.offset !== undefined
256
- ) {
257
- const rangeMatch = state.offset === offset && state.limit === limit;
258
- if (rangeMatch) {
259
- return {
260
- success: true,
261
- content: `File ${filePath} has not changed since last read. The content from the earlier Read tool_result in this conversation is still current — refer to that instead of re-reading.`,
262
- shortResult: "File unchanged",
263
- metadata: {
264
- type: "file_unchanged",
265
- },
266
- };
267
- }
268
- }
269
- }
270
-
271
- // Resource Limits — align with Claude Code: 256KB default, bypassed only
272
- // when the caller provides an explicit line limit (not offset alone).
273
- const maxSizeBytes =
274
- context.fileReadingLimits?.maxSizeBytes ?? 0.25 * 1024 * 1024; // Default 256KB
275
- if (stats.size > maxSizeBytes && typeof limit !== "number") {
276
- return {
277
- success: false,
278
- content: "",
279
- error: `File size (${(stats.size / 1024).toFixed(2)}KB) exceeds limit (${(maxSizeBytes / 1024).toFixed(2)}KB). Please use offset and limit to read a portion of the file.`,
280
- metadata: {
281
- type: "error_limit_exceeded",
282
- size: stats.size,
283
- limit: maxSizeBytes,
284
- },
285
- };
286
- }
287
-
288
- const fileContent = await readFile(actualFilePath, "utf-8");
289
-
290
- // Update readFileState
291
- if (context.readFileState) {
292
- const hash = createHash("sha256").update(fileContent).digest("hex");
293
- context.readFileState.set(actualFilePath, {
294
- mtime: stats.mtime.getTime(),
295
- hash,
296
- offset, // undefined for full reads
297
- limit, // undefined for full reads
298
- });
299
- }
300
-
301
- // Check if file is empty
302
- if (fileContent.length === 0) {
303
- logger.warn(`File ${filePath} exists but has empty contents`);
304
- return {
305
- success: true,
306
- content: "System reminder: This file exists but has empty contents.",
307
- shortResult: "Empty file",
308
- metadata: {
309
- type: "text",
310
- isEmpty: true,
311
- },
312
- };
313
- }
314
-
315
- const allLines = fileContent.split("\n");
316
- const totalLines = allLines.length;
317
-
318
- // Handle offset and limit
319
- let startLine = 1;
320
- if (typeof offset === "number") {
321
- startLine = Math.max(1, offset);
322
- }
323
-
324
- let endLine = Math.min(
325
- totalLines,
326
- startLine + (typeof limit === "number" ? limit : 2000) - 1,
327
- );
328
-
329
- // If no offset and limit specified, read entire file (maximum 2000 lines)
330
- if (typeof offset !== "number" && typeof limit !== "number") {
331
- startLine = 1;
332
- endLine = Math.min(totalLines, 2000);
333
- }
334
-
335
- // Validate line number range
336
- if (startLine > totalLines) {
337
- return {
338
- success: false,
339
- content: "",
340
- error: `Start line ${startLine} exceeds total lines ${totalLines}`,
341
- };
342
- }
343
-
344
- // Extract specified line range
345
- const selectedLines = allLines.slice(startLine - 1, endLine);
346
-
347
- // Format output (cat -n format, with line numbers)
348
- const formattedContent = selectedLines
349
- .map((line, index) => {
350
- const lineNumber = startLine + index;
351
- return `${formatLineNumberPrefix(lineNumber)}${line}`;
352
- })
353
- .join("\n");
354
-
355
- // Token-level validation: estimate tokens and reject if over limit
356
- const maxTokens = context.fileReadingLimits?.maxTokens ?? 25000; // Default 25000 tokens
357
- const ext = extname(actualFilePath).toLowerCase().slice(1);
358
- const estimatedTokens = estimateTokens(formattedContent, ext);
359
- if (estimatedTokens > maxTokens) {
360
- return {
361
- success: false,
362
- content: "",
363
- error: `File content (~${estimatedTokens.toLocaleString()} tokens) exceeds maximum allowed tokens (${maxTokens.toLocaleString()}). Use offset and limit parameters to read specific portions of the file, or use Bash with grep/jq to search within it for specific content.`,
364
- metadata: {
365
- type: "error_token_limit_exceeded",
366
- estimatedTokens,
367
- maxTokens,
368
- },
369
- };
370
- }
371
-
372
- // Add file information header
373
- let content = `File: ${filePath}\n`;
374
- if (startLine > 1 || endLine < totalLines) {
375
- content += `Lines ${startLine}-${endLine} of ${totalLines}\n`;
376
- } else {
377
- content += `Total lines: ${totalLines}\n`;
378
- }
379
- content += "─".repeat(50) + "\n";
380
- content += formattedContent;
381
-
382
- // If only showing partial content, add prompt
383
- if (endLine < totalLines) {
384
- content += `\n${"─".repeat(50)}\n`;
385
- content += `... ${totalLines - endLine} more lines not shown`;
386
- }
387
-
388
- return {
389
- success: true,
390
- content,
391
- shortResult: `Read ${selectedLines.length} lines${totalLines > 2000 ? " (truncated)" : ""}`,
392
- metadata: {
393
- type: "text",
394
- totalLines,
395
- startLine,
396
- endLine,
397
- truncated: endLine < totalLines,
398
- },
399
- };
400
- } catch (error) {
401
- return {
402
- success: false,
403
- content: "",
404
- error: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,
405
- };
406
- }
407
- },
408
- formatCompactParams: (
409
- params: Record<string, unknown>,
410
- context: ToolContext,
411
- ) => {
412
- const filePath = params.file_path as string;
413
- const offset = params.offset as number;
414
- const limit = params.limit as number;
415
-
416
- let displayPath = getDisplayPath(filePath || "", context.workdir);
417
-
418
- if (typeof offset === "number" || typeof limit === "number") {
419
- const offsetStr = typeof offset === "number" ? offset.toString() : "1";
420
- const limitStr = typeof limit === "number" ? limit.toString() : "2000";
421
- displayPath += ` ${offsetStr}:${limitStr}`;
422
- }
423
-
424
- return displayPath;
425
- },
426
- };
@@ -1,248 +0,0 @@
1
- import type { ToolPlugin, ToolResult, ToolContext } from "./types.js";
2
- import { SKILL_TOOL_NAME } from "../constants/tools.js";
3
- import { GENERAL_PURPOSE_SUBAGENT_TYPE } from "../constants/subagents.js";
4
- import type { SkillMetadata } from "../types/skills.js";
5
- import { logger } from "../utils/globalLogger.js";
6
- import {
7
- countToolBlocks,
8
- formatToolTokenSummary,
9
- } from "../utils/messageOperations.js";
10
-
11
- /**
12
- * Skill tool plugin for invoking Wave skills
13
- */
14
- const SKILL_TOOL_DESCRIPTION =
15
- "Execute a skill within the main conversation. When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.";
16
-
17
- export const skillTool: ToolPlugin = {
18
- name: SKILL_TOOL_NAME,
19
- config: {
20
- type: "function" as const,
21
- function: {
22
- name: SKILL_TOOL_NAME,
23
- description: SKILL_TOOL_DESCRIPTION,
24
- parameters: {
25
- type: "object",
26
- properties: {
27
- skill_name: {
28
- type: "string",
29
- description: "Name of the skill to invoke",
30
- },
31
- args: {
32
- type: "string",
33
- description: "Optional arguments to pass to the skill",
34
- },
35
- },
36
- required: ["skill_name"],
37
- },
38
- },
39
- },
40
-
41
- prompt: (args?: {
42
- availableSkills?: SkillMetadata[];
43
- isSubagent?: boolean;
44
- }) => {
45
- let availableSkills = args?.availableSkills?.filter(
46
- (skill) => !skill.disableModelInvocation,
47
- );
48
-
49
- if (args?.isSubagent) {
50
- availableSkills = availableSkills?.filter(
51
- (skill) => skill.context !== "fork",
52
- );
53
- }
54
-
55
- if (!availableSkills || availableSkills.length === 0) {
56
- return `${SKILL_TOOL_DESCRIPTION} No skills are currently available.`;
57
- }
58
-
59
- const skillList = availableSkills
60
- .map(
61
- (skill) => `• **${skill.name}** (${skill.type}): ${skill.description}`,
62
- )
63
- .join("\n");
64
-
65
- return `${SKILL_TOOL_DESCRIPTION} Do not invoke the same skill repeatedly if it has already been called with the same arguments.\n\nAvailable skills:\n${skillList}`;
66
- },
67
-
68
- execute: async (
69
- args: Record<string, unknown>,
70
- context: ToolContext,
71
- ): Promise<ToolResult> => {
72
- try {
73
- const skillManager = context.skillManager;
74
- if (!skillManager) {
75
- return {
76
- success: false,
77
- content: "",
78
- error: "Skill manager not available in tool context",
79
- };
80
- }
81
-
82
- // Validate arguments
83
- const skillName = args.skill_name as string;
84
- const skillArgs = args.args as string | undefined;
85
-
86
- if (!skillName || typeof skillName !== "string") {
87
- return {
88
- success: false,
89
- content: "",
90
- error: "skill_name parameter is required and must be a string",
91
- };
92
- }
93
-
94
- const skillMetadata = skillManager.getSkillMetadata(skillName);
95
-
96
- if (skillMetadata?.disableModelInvocation) {
97
- return {
98
- success: false,
99
- content: "",
100
- error: `Skill "${skillName}" is not available for model invocation.`,
101
- };
102
- }
103
-
104
- // Handle fork context
105
- if (skillMetadata?.context === "fork") {
106
- const subagentManager = context.subagentManager;
107
- if (!subagentManager) {
108
- return {
109
- success: false,
110
- content: "",
111
- error: "Subagent manager not available in tool context",
112
- };
113
- }
114
-
115
- const agentType = skillMetadata.agent || GENERAL_PURPOSE_SUBAGENT_TYPE;
116
- const configuration = await subagentManager.findSubagent(agentType);
117
-
118
- if (!configuration) {
119
- return {
120
- success: false,
121
- content: "",
122
- error: `No subagent found matching "${agentType}" for skill "${skillName}"`,
123
- };
124
- }
125
-
126
- // Execute the skill to get the content
127
- const skillResult = await skillManager.executeSkill({
128
- skill_name: skillName,
129
- args: skillArgs,
130
- });
131
-
132
- logger.debug(`Skill ${skillName} executed, allowedTools:`, {
133
- allowedTools: skillResult.allowedTools,
134
- });
135
-
136
- // Create subagent instance
137
- const instance = await subagentManager.createInstance(
138
- configuration,
139
- {
140
- description: `Skill: ${skillName}`,
141
- prompt: skillResult.content,
142
- subagent_type: agentType,
143
- allowedTools: skillResult.allowedTools,
144
- model: skillMetadata.model,
145
- },
146
- false, // run_in_background
147
- () => {
148
- // Update shortResult
149
- const messages = instance.messageManager.getMessages();
150
- const tokens = instance.messageManager.getLatestTotalTokens();
151
- const usedTools = instance.usedTools;
152
-
153
- const toolCount = countToolBlocks(messages);
154
- const summary = formatToolTokenSummary(toolCount, tokens);
155
-
156
- const getDisplayParam = (t: {
157
- name: string;
158
- parameters: string;
159
- compactParams?: string;
160
- stage?: string;
161
- }) => {
162
- if (
163
- (t.stage === "end" || t.stage === "running") &&
164
- t.compactParams
165
- ) {
166
- return t.compactParams;
167
- }
168
- const flat = t.parameters.replace(/\n/g, "\\n");
169
- return flat.length > 30 ? `…${flat.slice(-30)}` : flat;
170
- };
171
-
172
- let shortResult = "";
173
- if (toolCount > 2) {
174
- shortResult += "... ";
175
- }
176
- shortResult += summary;
177
- if (usedTools.length > 0) {
178
- shortResult +=
179
- "\n" +
180
- usedTools
181
- .map((t) => `${t.name} ${getDisplayParam(t)}`)
182
- .join("\n");
183
- }
184
-
185
- context.onShortResultUpdate?.(shortResult);
186
- },
187
- );
188
-
189
- try {
190
- const result = await subagentManager.executeAgent(
191
- instance,
192
- skillResult.content,
193
- context.abortSignal,
194
- false,
195
- );
196
-
197
- // Cleanup subagent instance after agent completion
198
- subagentManager.cleanupInstance(instance.subagentId);
199
-
200
- const messages = instance.messageManager.getMessages();
201
- const tokens = instance.messageManager.getLatestTotalTokens();
202
- const toolCount = countToolBlocks(messages);
203
- const summary = formatToolTokenSummary(toolCount, tokens);
204
-
205
- return {
206
- success: true,
207
- content: result,
208
- shortResult: `Invoked skill: ${skillName}${summary ? ` ${summary}` : ""}`,
209
- };
210
- } catch (error) {
211
- return {
212
- success: false,
213
- content: "",
214
- error: `Skill fork failed: ${error instanceof Error ? error.message : String(error)}`,
215
- };
216
- }
217
- }
218
-
219
- // Standard execution
220
- const result = await skillManager.executeSkill({
221
- skill_name: skillName,
222
- args: skillArgs,
223
- });
224
-
225
- // Add temporary rules if allowedTools are present
226
- if (result.allowedTools && result.allowedTools.length > 0) {
227
- context.permissionManager?.addTemporaryRules(result.allowedTools);
228
- }
229
-
230
- return {
231
- success: true,
232
- content: result.content,
233
- shortResult: `Invoked skill: ${skillName}`,
234
- };
235
- } catch (error) {
236
- return {
237
- success: false,
238
- content: "",
239
- error: error instanceof Error ? error.message : String(error),
240
- };
241
- }
242
- },
243
-
244
- formatCompactParams: (params: Record<string, unknown>) => {
245
- const skillName = params.skill_name as string;
246
- return skillName || "unknown-skill";
247
- },
248
- };