wave-agent-sdk 0.0.2 → 0.0.4

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 (66) hide show
  1. package/dist/agent.d.ts +5 -1
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +48 -4
  4. package/dist/index.d.ts +0 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +0 -1
  7. package/dist/managers/aiManager.d.ts.map +1 -1
  8. package/dist/managers/aiManager.js +4 -7
  9. package/dist/managers/messageManager.d.ts +8 -0
  10. package/dist/managers/messageManager.d.ts.map +1 -1
  11. package/dist/managers/messageManager.js +26 -2
  12. package/dist/managers/skillManager.d.ts +4 -5
  13. package/dist/managers/skillManager.d.ts.map +1 -1
  14. package/dist/managers/skillManager.js +6 -82
  15. package/dist/managers/subagentManager.d.ts +96 -0
  16. package/dist/managers/subagentManager.d.ts.map +1 -0
  17. package/dist/managers/subagentManager.js +261 -0
  18. package/dist/managers/toolManager.d.ts +33 -1
  19. package/dist/managers/toolManager.d.ts.map +1 -1
  20. package/dist/managers/toolManager.js +43 -5
  21. package/dist/services/aiService.d.ts.map +1 -1
  22. package/dist/services/aiService.js +40 -14
  23. package/dist/services/memory.js +2 -2
  24. package/dist/tools/grepTool.d.ts.map +1 -1
  25. package/dist/tools/grepTool.js +8 -6
  26. package/dist/tools/readTool.d.ts.map +1 -1
  27. package/dist/tools/readTool.js +36 -6
  28. package/dist/tools/skillTool.d.ts +8 -0
  29. package/dist/tools/skillTool.d.ts.map +1 -0
  30. package/dist/tools/skillTool.js +72 -0
  31. package/dist/tools/taskTool.d.ts +8 -0
  32. package/dist/tools/taskTool.d.ts.map +1 -0
  33. package/dist/tools/taskTool.js +109 -0
  34. package/dist/tools/todoWriteTool.d.ts +6 -0
  35. package/dist/tools/todoWriteTool.d.ts.map +1 -0
  36. package/dist/tools/todoWriteTool.js +203 -0
  37. package/dist/types.d.ts +8 -1
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/utils/fileFormat.d.ts +17 -0
  40. package/dist/utils/fileFormat.d.ts.map +1 -0
  41. package/dist/utils/fileFormat.js +35 -0
  42. package/dist/utils/messageOperations.d.ts +18 -0
  43. package/dist/utils/messageOperations.d.ts.map +1 -1
  44. package/dist/utils/messageOperations.js +43 -0
  45. package/dist/utils/subagentParser.d.ts +19 -0
  46. package/dist/utils/subagentParser.d.ts.map +1 -0
  47. package/dist/utils/subagentParser.js +159 -0
  48. package/package.json +1 -1
  49. package/src/agent.ts +55 -5
  50. package/src/index.ts +0 -1
  51. package/src/managers/aiManager.ts +5 -8
  52. package/src/managers/messageManager.ts +55 -1
  53. package/src/managers/skillManager.ts +7 -96
  54. package/src/managers/subagentManager.ts +368 -0
  55. package/src/managers/toolManager.ts +50 -5
  56. package/src/services/aiService.ts +44 -16
  57. package/src/services/memory.ts +2 -2
  58. package/src/tools/grepTool.ts +9 -6
  59. package/src/tools/readTool.ts +40 -6
  60. package/src/tools/skillTool.ts +82 -0
  61. package/src/tools/taskTool.ts +128 -0
  62. package/src/tools/todoWriteTool.ts +232 -0
  63. package/src/types.ts +10 -1
  64. package/src/utils/fileFormat.ts +40 -0
  65. package/src/utils/messageOperations.ts +80 -0
  66. package/src/utils/subagentParser.ts +223 -0
@@ -0,0 +1,261 @@
1
+ import { randomUUID } from "crypto";
2
+ import { AIManager } from "./aiManager.js";
3
+ import { MessageManager, } from "./messageManager.js";
4
+ export class SubagentManager {
5
+ constructor(options) {
6
+ this.instances = new Map();
7
+ this.cachedConfigurations = null;
8
+ this.workdir = options.workdir;
9
+ this.parentToolManager = options.parentToolManager;
10
+ this.parentMessageManager = options.parentMessageManager;
11
+ this.logger = options.logger;
12
+ this.gatewayConfig = options.gatewayConfig;
13
+ this.modelConfig = options.modelConfig;
14
+ this.tokenLimit = options.tokenLimit;
15
+ }
16
+ /**
17
+ * Initialize the SubagentManager by loading and caching configurations
18
+ */
19
+ async initialize() {
20
+ await this.loadConfigurations();
21
+ }
22
+ /**
23
+ * Load all available subagent configurations and cache them
24
+ */
25
+ async loadConfigurations() {
26
+ if (this.cachedConfigurations === null) {
27
+ const { loadSubagentConfigurations } = await import("../utils/subagentParser.js");
28
+ this.cachedConfigurations = await loadSubagentConfigurations(this.workdir);
29
+ }
30
+ return this.cachedConfigurations;
31
+ }
32
+ /**
33
+ * Get cached configurations synchronously (must call loadConfigurations first)
34
+ */
35
+ getConfigurations() {
36
+ if (this.cachedConfigurations === null) {
37
+ throw new Error("SubagentManager not initialized. Call loadConfigurations() first.");
38
+ }
39
+ return this.cachedConfigurations;
40
+ }
41
+ /**
42
+ * Find subagent by exact name match
43
+ */
44
+ async findSubagent(name) {
45
+ const { findSubagentByName } = await import("../utils/subagentParser.js");
46
+ return findSubagentByName(name, this.workdir);
47
+ }
48
+ /**
49
+ * Create a new subagent instance with isolated managers
50
+ */
51
+ async createInstance(configuration, taskDescription) {
52
+ if (!this.parentToolManager ||
53
+ !this.gatewayConfig ||
54
+ !this.modelConfig ||
55
+ !this.tokenLimit) {
56
+ throw new Error("SubagentManager not properly initialized - call initialize() first");
57
+ }
58
+ const subagentId = randomUUID();
59
+ // Create isolated MessageManager for the subagent
60
+ const subagentCallbacks = {
61
+ // These callbacks will be handled by the parent agent
62
+ onMessagesChange: (messages) => {
63
+ const instance = this.instances.get(subagentId);
64
+ if (instance) {
65
+ instance.messages = messages;
66
+ // Update parent's subagent block with latest messages
67
+ this.parentMessageManager.updateSubagentBlock(subagentId, {
68
+ messages: messages,
69
+ });
70
+ }
71
+ },
72
+ };
73
+ const messageManager = new MessageManager({
74
+ callbacks: subagentCallbacks,
75
+ workdir: this.workdir,
76
+ logger: this.logger,
77
+ });
78
+ // Use the parent tool manager directly - tool restrictions will be handled by allowedTools parameter
79
+ const toolManager = this.parentToolManager;
80
+ // Determine model to use
81
+ const modelToUse = configuration.model && configuration.model !== "inherit"
82
+ ? configuration.model
83
+ : this.modelConfig.agentModel;
84
+ // Create isolated AIManager for the subagent
85
+ const aiManager = new AIManager({
86
+ messageManager,
87
+ toolManager,
88
+ logger: this.logger,
89
+ workdir: this.workdir,
90
+ systemPrompt: configuration.systemPrompt,
91
+ gatewayConfig: this.gatewayConfig,
92
+ modelConfig: {
93
+ ...this.modelConfig,
94
+ agentModel: modelToUse,
95
+ },
96
+ tokenLimit: this.tokenLimit,
97
+ });
98
+ const instance = {
99
+ subagentId,
100
+ configuration,
101
+ aiManager,
102
+ messageManager,
103
+ toolManager,
104
+ status: "initializing",
105
+ taskDescription,
106
+ messages: [],
107
+ };
108
+ this.instances.set(subagentId, instance);
109
+ // Create subagent block in parent message manager
110
+ this.parentMessageManager.addSubagentBlock(subagentId, configuration.name, "active", []);
111
+ return instance;
112
+ }
113
+ /**
114
+ * Execute task using subagent instance
115
+ *
116
+ * IMPORTANT: This method automatically filters out the Task tool from allowedTools
117
+ * to prevent subagents from spawning other subagents (infinite recursion protection)
118
+ */
119
+ async executeTask(instance, prompt) {
120
+ try {
121
+ // Set status to active and update parent
122
+ this.updateInstanceStatus(instance.subagentId, "active");
123
+ this.parentMessageManager.updateSubagentBlock(instance.subagentId, {
124
+ status: "active",
125
+ });
126
+ // Add the user's prompt as a message
127
+ instance.messageManager.addUserMessage(prompt);
128
+ // Create allowed tools list - always exclude Task tool to prevent subagent recursion
129
+ let allowedTools = instance.configuration.tools;
130
+ // Always filter out the Task tool to prevent subagents from creating sub-subagents
131
+ if (allowedTools) {
132
+ allowedTools = allowedTools.filter((tool) => tool !== "Task");
133
+ }
134
+ else {
135
+ // If no tools specified, get all tools except Task
136
+ const allTools = instance.toolManager.list().map((tool) => tool.name);
137
+ allowedTools = allTools.filter((tool) => tool !== "Task");
138
+ }
139
+ // Execute the AI request with tool restrictions
140
+ await instance.aiManager.sendAIMessage({
141
+ allowedTools,
142
+ model: instance.configuration.model !== "inherit"
143
+ ? instance.configuration.model
144
+ : undefined,
145
+ });
146
+ // Get the latest messages to extract the response
147
+ const messages = instance.messageManager.getMessages();
148
+ const lastAssistantMessage = messages
149
+ .filter((msg) => msg.role === "assistant")
150
+ .pop();
151
+ if (!lastAssistantMessage) {
152
+ throw new Error("No response from subagent");
153
+ }
154
+ // Extract text content from the last assistant message
155
+ const textBlocks = lastAssistantMessage.blocks.filter((block) => block.type === "text");
156
+ const response = textBlocks.map((block) => block.content).join("\n");
157
+ // Update status to completed and update parent with final messages
158
+ this.updateInstanceStatus(instance.subagentId, "completed");
159
+ this.parentMessageManager.updateSubagentBlock(instance.subagentId, {
160
+ status: "completed",
161
+ messages: messages,
162
+ });
163
+ return response || "Task completed with no text response";
164
+ }
165
+ catch (error) {
166
+ this.updateInstanceStatus(instance.subagentId, "error");
167
+ this.parentMessageManager.updateSubagentBlock(instance.subagentId, {
168
+ status: "error",
169
+ });
170
+ throw error;
171
+ }
172
+ }
173
+ /**
174
+ * Get instance by subagent ID
175
+ */
176
+ getInstance(subagentId) {
177
+ return this.instances.get(subagentId) || null;
178
+ }
179
+ /**
180
+ * Update instance status
181
+ */
182
+ updateInstanceStatus(subagentId, status) {
183
+ const instance = this.instances.get(subagentId);
184
+ if (instance) {
185
+ instance.status = status;
186
+ }
187
+ }
188
+ /**
189
+ * Add message to instance
190
+ */
191
+ addMessageToInstance(subagentId, message) {
192
+ const instance = this.instances.get(subagentId);
193
+ if (instance) {
194
+ instance.messages.push(message);
195
+ }
196
+ }
197
+ /**
198
+ * Abort a running subagent instance
199
+ */
200
+ abortInstance(subagentId) {
201
+ const instance = this.instances.get(subagentId);
202
+ if (!instance) {
203
+ return false;
204
+ }
205
+ // Only abort active or initializing instances
206
+ if (instance.status !== "active" && instance.status !== "initializing") {
207
+ return false;
208
+ }
209
+ try {
210
+ // Abort the AI manager operations
211
+ instance.aiManager.abortAIMessage();
212
+ // Update status
213
+ this.updateInstanceStatus(subagentId, "aborted");
214
+ this.parentMessageManager.updateSubagentBlock(subagentId, {
215
+ status: "aborted",
216
+ messages: instance.messages,
217
+ });
218
+ this.logger?.info(`Aborted subagent instance: ${subagentId}`);
219
+ return true;
220
+ }
221
+ catch (error) {
222
+ this.logger?.error(`Failed to abort subagent instance ${subagentId}:`, error);
223
+ return false;
224
+ }
225
+ }
226
+ /**
227
+ * Abort all active subagent instances
228
+ */
229
+ abortAllInstances() {
230
+ const activeInstances = this.getActiveInstances();
231
+ for (const instance of activeInstances) {
232
+ this.abortInstance(instance.subagentId);
233
+ }
234
+ }
235
+ /**
236
+ * Clean up completed, errored, or aborted instances
237
+ */
238
+ cleanupInstance(subagentId) {
239
+ const instance = this.instances.get(subagentId);
240
+ if (instance &&
241
+ (instance.status === "completed" ||
242
+ instance.status === "error" ||
243
+ instance.status === "aborted")) {
244
+ this.instances.delete(subagentId);
245
+ }
246
+ }
247
+ /**
248
+ * Get all active instances
249
+ */
250
+ getActiveInstances() {
251
+ return Array.from(this.instances.values()).filter((instance) => instance.status === "active" || instance.status === "initializing");
252
+ }
253
+ /**
254
+ * Clean up all instances (for session end)
255
+ */
256
+ cleanup() {
257
+ // Abort all active instances before cleanup
258
+ this.abortAllInstances();
259
+ this.instances.clear();
260
+ }
261
+ }
@@ -2,6 +2,8 @@ import type { ToolContext, ToolPlugin, ToolResult } from "../tools/types.js";
2
2
  import { McpManager } from "./mcpManager.js";
3
3
  import { ChatCompletionFunctionTool } from "openai/resources.js";
4
4
  import type { Logger } from "../types.js";
5
+ import type { SubagentManager } from "./subagentManager.js";
6
+ import type { SkillManager } from "./skillManager.js";
5
7
  export interface ToolManagerOptions {
6
8
  mcpManager: McpManager;
7
9
  logger?: Logger;
@@ -14,7 +16,37 @@ declare class ToolManager {
14
16
  private mcpManager;
15
17
  private logger?;
16
18
  constructor(options: ToolManagerOptions);
17
- private initializeBuiltInTools;
19
+ /**
20
+ * Register a new tool
21
+ */
22
+ register(tool: ToolPlugin): void;
23
+ /**
24
+ * Initialize built-in tools. Can be called with dependencies for tools that require them.
25
+ *
26
+ * This method can be called multiple times safely. When called without dependencies,
27
+ * it registers basic tools (Bash, Read, Write, TodoWrite, etc.). When called with
28
+ * dependencies, it also registers tools that require managers (Task, Skill).
29
+ *
30
+ * @param deps Optional dependencies for advanced tools
31
+ * @param deps.subagentManager SubagentManager instance for Task tool
32
+ * @param deps.skillManager SkillManager instance for Skill tool
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * // Initialize basic tools only
37
+ * toolManager.initializeBuiltInTools();
38
+ *
39
+ * // Initialize all tools including those requiring dependencies
40
+ * toolManager.initializeBuiltInTools({
41
+ * subagentManager: mySubagentManager,
42
+ * skillManager: mySkillManager
43
+ * });
44
+ * ```
45
+ */
46
+ initializeBuiltInTools(deps?: {
47
+ subagentManager?: SubagentManager;
48
+ skillManager?: SkillManager;
49
+ }): void;
18
50
  execute(name: string, args: Record<string, unknown>, context: ToolContext): Promise<ToolResult>;
19
51
  list(): ToolPlugin[];
20
52
  getToolsConfig(): ChatCompletionFunctionTool[];
@@ -1 +1 @@
1
- {"version":3,"file":"toolManager.d.ts","sourceRoot":"","sources":["../../src/managers/toolManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAY7E,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,UAAU,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,cAAM,WAAW;IACf,OAAO,CAAC,KAAK,CAAiC;IAC9C,OAAO,CAAC,UAAU,CAAa;IAC/B,OAAO,CAAC,MAAM,CAAC,CAAS;gBAEZ,OAAO,EAAE,kBAAkB;IAQvC,OAAO,CAAC,sBAAsB;IAqBxB,OAAO,CACX,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,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,CAAC;IA2BtB,IAAI,IAAI,UAAU,EAAE;IAMpB,cAAc,IAAI,0BAA0B,EAAE;CAO/C;AAGD,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -8,7 +8,9 @@ import { globTool } from "../tools/globTool.js";
8
8
  import { grepTool } from "../tools/grepTool.js";
9
9
  import { lsTool } from "../tools/lsTool.js";
10
10
  import { readTool } from "../tools/readTool.js";
11
- import { SkillManager } from "./skillManager.js";
11
+ import { todoWriteTool } from "../tools/todoWriteTool.js";
12
+ import { createTaskTool } from "../tools/taskTool.js";
13
+ import { createSkillTool } from "../tools/skillTool.js";
12
14
  /**
13
15
  * Tool Manager
14
16
  */
@@ -17,10 +19,37 @@ class ToolManager {
17
19
  this.tools = new Map();
18
20
  this.mcpManager = options.mcpManager;
19
21
  this.logger = options.logger;
20
- // Initialize built-in tools
21
- this.initializeBuiltInTools();
22
22
  }
23
- initializeBuiltInTools() {
23
+ /**
24
+ * Register a new tool
25
+ */
26
+ register(tool) {
27
+ this.tools.set(tool.name, tool);
28
+ }
29
+ /**
30
+ * Initialize built-in tools. Can be called with dependencies for tools that require them.
31
+ *
32
+ * This method can be called multiple times safely. When called without dependencies,
33
+ * it registers basic tools (Bash, Read, Write, TodoWrite, etc.). When called with
34
+ * dependencies, it also registers tools that require managers (Task, Skill).
35
+ *
36
+ * @param deps Optional dependencies for advanced tools
37
+ * @param deps.subagentManager SubagentManager instance for Task tool
38
+ * @param deps.skillManager SkillManager instance for Skill tool
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * // Initialize basic tools only
43
+ * toolManager.initializeBuiltInTools();
44
+ *
45
+ * // Initialize all tools including those requiring dependencies
46
+ * toolManager.initializeBuiltInTools({
47
+ * subagentManager: mySubagentManager,
48
+ * skillManager: mySkillManager
49
+ * });
50
+ * ```
51
+ */
52
+ initializeBuiltInTools(deps) {
24
53
  const builtInTools = [
25
54
  bashTool,
26
55
  bashOutputTool,
@@ -33,11 +62,20 @@ class ToolManager {
33
62
  grepTool,
34
63
  lsTool,
35
64
  readTool,
36
- new SkillManager({ logger: this.logger }).createTool(),
65
+ todoWriteTool,
37
66
  ];
38
67
  for (const tool of builtInTools) {
39
68
  this.tools.set(tool.name, tool);
40
69
  }
70
+ // Register tools that require dependencies
71
+ if (deps?.subagentManager) {
72
+ const taskTool = createTaskTool(deps.subagentManager);
73
+ this.tools.set(taskTool.name, taskTool);
74
+ }
75
+ if (deps?.skillManager) {
76
+ const skillTool = createSkillTool(deps.skillManager);
77
+ this.tools.set(skillTool.name, skillTool);
78
+ }
41
79
  }
42
80
  async execute(name, args, context) {
43
81
  // Check if it's an MCP tool first
@@ -1 +1 @@
1
- {"version":3,"file":"aiService.d.ts","sourceRoot":"","sources":["../../src/services/aiService.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAEL,0BAA0B,EAC1B,0BAA0B,EAC3B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAmC9D,MAAM,WAAW,gBAAgB;IAE/B,aAAa,EAAE,aAAa,CAAC;IAC7B,WAAW,EAAE,WAAW,CAAC;IAGzB,QAAQ,EAAE,0BAA0B,EAAE,CAAC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,0BAA0B,EAAE,CAAC;IACrC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,6BAA6B,EAAE,CAAC;IAC7C,KAAK,CAAC,EAAE;QACN,aAAa,EAAE,MAAM,CAAC;QACtB,iBAAi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ACtB,iBAAiB,EAAE,MAAM,CAAC;QAC1B,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;CACH;AAED,wBAAsB,SAAS,CAC7B,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,eAAe,CAAC,CA6G1B;AAED,MAAM,WAAW,uBAAuB;IAEtC,aAAa,EAAE,aAAa,CAAC;IAC7B,WAAW,EAAE,WAAW,CAAC;IAGzB,QAAQ,EAAE,0BAA0B,EAAE,CAAC;IACvC,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAED,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,MAAM,CAAC,CAyFjB"}
@@ -1,4 +1,29 @@
1
1
  import OpenAI from "openai";
2
+ import * as os from "os";
3
+ import * as fs from "fs";
4
+ import * as path from "path";
5
+ /**
6
+ * Check if a directory is a git repository
7
+ * @param dirPath Directory path to check
8
+ * @returns "Yes" if it's a git repo, "No" otherwise
9
+ */
10
+ function isGitRepository(dirPath) {
11
+ try {
12
+ // Check if .git directory exists in current directory or any parent directory
13
+ let currentPath = path.resolve(dirPath);
14
+ while (currentPath !== path.dirname(currentPath)) {
15
+ const gitPath = path.join(currentPath, ".git");
16
+ if (fs.existsSync(gitPath)) {
17
+ return "Yes";
18
+ }
19
+ currentPath = path.dirname(currentPath);
20
+ }
21
+ return "No";
22
+ }
23
+ catch {
24
+ return "No";
25
+ }
26
+ }
2
27
  /**
3
28
  * Get specific configuration parameters based on model name
4
29
  * @param modelName Model name
@@ -27,22 +52,23 @@ export async function callAgent(options) {
27
52
  baseURL: gatewayConfig.baseURL,
28
53
  });
29
54
  // Build system prompt content
30
- let systemContent;
31
- if (systemPrompt) {
32
- // Use custom system prompt if provided
33
- systemContent = systemPrompt;
34
- }
35
- else {
36
- // Use default system prompt
37
- systemContent = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
55
+ let systemContent = systemPrompt ||
56
+ `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.`;
57
+ // Always add environment information
58
+ systemContent += `
38
59
 
39
- ## Current Working Directory
40
- ${workdir}
60
+ Here is useful information about the environment you are running in:
61
+ <env>
62
+ Working directory: ${workdir}
63
+ Is directory a git repo: ${isGitRepository(workdir)}
64
+ Platform: ${os.platform()}
65
+ OS Version: ${os.type()} ${os.release()}
66
+ Today's date: ${new Date().toISOString().split("T")[0]}
67
+ </env>
41
68
  `;
42
- // If there is memory content, add it to the system prompt
43
- if (memory && memory.trim()) {
44
- systemContent += `\n\n## Memory Context\n\nThe following is important context and memory from previous interactions:\n\n${memory}`;
45
- }
69
+ // If there is memory content, add it to the system prompt
70
+ if (memory && memory.trim()) {
71
+ systemContent += `\n## Memory Context\n\nThe following is important context and memory from previous interactions:\n\n${memory}`;
46
72
  }
47
73
  // Add system prompt
48
74
  const systemMessage = {
@@ -10,7 +10,7 @@ export const addMemory = async (message, workdir) => {
10
10
  return;
11
11
  }
12
12
  try {
13
- const memoryFilePath = path.join(workdir, "WAVE.md");
13
+ const memoryFilePath = path.join(workdir, "AGENTS.md");
14
14
  // Format memory entry, starting with -, no timestamp
15
15
  const memoryEntry = `- ${message.substring(1).trim()}\n`;
16
16
  // Check if file exists
@@ -97,7 +97,7 @@ export const getUserMemoryContent = async () => {
97
97
  // Read project memory file content
98
98
  export const readMemoryFile = async (workdir) => {
99
99
  try {
100
- const memoryFilePath = path.join(workdir, "WAVE.md");
100
+ const memoryFilePath = path.join(workdir, "AGENTS.md");
101
101
  return await fs.readFile(memoryFilePath, "utf-8");
102
102
  }
103
103
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"grepTool.d.ts","sourceRoot":"","sources":["../../src/tools/grepTool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAA2B,MAAM,YAAY,CAAC;AAMtE;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,UA0QtB,CAAC"}
1
+ {"version":3,"file":"grepTool.d.ts","sourceRoot":"","sources":["../../src/tools/grepTool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAA2B,MAAM,YAAY,CAAC;AAMtE;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,UA6QtB,CAAC"}
@@ -58,7 +58,7 @@ export const grepTool = {
58
58
  },
59
59
  head_limit: {
60
60
  type: "number",
61
- description: '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). When unspecified, shows all results from ripgrep.',
61
+ description: '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 100 to prevent excessive token usage.',
62
62
  },
63
63
  multiline: {
64
64
  type: "boolean",
@@ -176,11 +176,13 @@ export const grepTool = {
176
176
  shortResult: "No matches found",
177
177
  };
178
178
  }
179
- // Apply head_limit
179
+ // Apply head_limit with default fallback
180
180
  let finalOutput = output;
181
181
  let lines = output.split("\n");
182
- if (headLimit && headLimit > 0 && lines.length > headLimit) {
183
- lines = lines.slice(0, headLimit);
182
+ // Set default head_limit if not specified to prevent excessive token usage
183
+ const effectiveHeadLimit = headLimit || 100;
184
+ if (lines.length > effectiveHeadLimit) {
185
+ lines = lines.slice(0, effectiveHeadLimit);
184
186
  finalOutput = lines.join("\n");
185
187
  }
186
188
  // Generate short result
@@ -195,8 +197,8 @@ export const grepTool = {
195
197
  else {
196
198
  shortResult = `Found ${totalLines} matching line${totalLines === 1 ? "" : "s"}`;
197
199
  }
198
- if (headLimit && totalLines > headLimit) {
199
- shortResult += ` (showing first ${headLimit})`;
200
+ if (effectiveHeadLimit && totalLines > effectiveHeadLimit) {
201
+ shortResult += ` (showing first ${effectiveHeadLimit})`;
200
202
  }
201
203
  return {
202
204
  success: true,
@@ -1 +1 @@
1
- {"version":3,"file":"readTool.d.ts","sourceRoot":"","sources":["../../src/tools/readTool.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAA2B,MAAM,YAAY,CAAC;AAGtE;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,UA6JtB,CAAC"}
1
+ {"version":3,"file":"readTool.d.ts","sourceRoot":"","sources":["../../src/tools/readTool.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAA2B,MAAM,YAAY,CAAC;AAOtE;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,UA2LtB,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { readFile } from "fs/promises";
2
2
  import { resolvePath, getDisplayPath } from "../utils/path.js";
3
+ import { isBinaryDocument, getBinaryDocumentError, } from "../utils/fileFormat.js";
3
4
  /**
4
5
  * Read Tool Plugin - Read file content
5
6
  */
@@ -9,7 +10,7 @@ export const readTool = {
9
10
  type: "function",
10
11
  function: {
11
12
  name: "Read",
12
- description: "Reads a file from the local filesystem. You can access any file directly by using this tool.\nAssume 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.\n\nUsage:\n- The file_path parameter must be an absolute path, not a relative path\n- By default, it reads up to 2000 lines starting from the beginning of the file\n- 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\n- Any lines longer than 2000 characters will be truncated\n- Results are returned using cat -n format, with line numbers starting at 1\n- This tool allows Claude Code to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.\n- This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.\n- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.\n- 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.\n- 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\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.",
13
+ description: "Reads a file from the local filesystem. You can access any file directly by using this tool.\nAssume 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.\n\nUsage:\n- The file_path parameter must be an absolute path, not a relative path\n- By default, it reads up to 2000 lines starting from the beginning of the file\n- 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\n- Any lines longer than 2000 characters will be truncated\n- Results are returned using cat -n format, with line numbers starting at 1\n- This tool allows Claude Code to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.\n- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.\n- 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.\n- 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\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Binary document formats (PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX) are not supported and will return an error.",
13
14
  parameters: {
14
15
  type: "object",
15
16
  properties: {
@@ -41,6 +42,14 @@ export const readTool = {
41
42
  error: "file_path parameter is required and must be a string",
42
43
  };
43
44
  }
45
+ // Check for binary document formats
46
+ if (isBinaryDocument(filePath)) {
47
+ return {
48
+ success: false,
49
+ content: "",
50
+ error: getBinaryDocumentError(filePath),
51
+ };
52
+ }
44
53
  try {
45
54
  // Note: New Read tool requires absolute paths, so we don't use resolvePath
46
55
  // But for compatibility, if it's not an absolute path, we still try to resolve
@@ -57,8 +66,17 @@ export const readTool = {
57
66
  shortResult: "Empty file",
58
67
  };
59
68
  }
60
- const lines = fileContent.split("\n");
69
+ // Check content size limit (100KB)
70
+ const MAX_CONTENT_SIZE = 100 * 1024; // 100KB
71
+ let contentToProcess = fileContent;
72
+ let contentTruncated = false;
73
+ if (fileContent.length > MAX_CONTENT_SIZE) {
74
+ contentToProcess = fileContent.substring(0, MAX_CONTENT_SIZE);
75
+ contentTruncated = true;
76
+ }
77
+ const lines = contentToProcess.split("\n");
61
78
  const totalLines = lines.length;
79
+ const originalTotalLines = fileContent.split("\n").length;
62
80
  // Handle offset and limit
63
81
  let startLine = 1;
64
82
  let endLine = Math.min(totalLines, 2000); // Default maximum read 2000 lines
@@ -94,7 +112,11 @@ export const readTool = {
94
112
  .join("\n");
95
113
  // Add file information header
96
114
  let content = `File: ${filePath}\n`;
97
- if (startLine > 1 || endLine < totalLines) {
115
+ if (contentTruncated) {
116
+ content += `Content truncated at ${MAX_CONTENT_SIZE} bytes\n`;
117
+ content += `Lines ${startLine}-${endLine} of ${totalLines} (original file: ${originalTotalLines} lines)\n`;
118
+ }
119
+ else if (startLine > 1 || endLine < totalLines) {
98
120
  content += `Lines ${startLine}-${endLine} of ${totalLines}\n`;
99
121
  }
100
122
  else {
@@ -103,14 +125,22 @@ export const readTool = {
103
125
  content += "─".repeat(50) + "\n";
104
126
  content += formattedContent;
105
127
  // If only showing partial content, add prompt
106
- if (endLine < totalLines) {
128
+ if (endLine < totalLines || contentTruncated) {
107
129
  content += `\n${"─".repeat(50)}\n`;
108
- content += `... ${totalLines - endLine} more lines not shown`;
130
+ if (contentTruncated) {
131
+ content += `... content truncated due to size limit (${MAX_CONTENT_SIZE} bytes)`;
132
+ if (endLine < totalLines) {
133
+ content += ` and ${totalLines - endLine} more lines not shown`;
134
+ }
135
+ }
136
+ else {
137
+ content += `... ${totalLines - endLine} more lines not shown`;
138
+ }
109
139
  }
110
140
  return {
111
141
  success: true,
112
142
  content,
113
- shortResult: `Read ${selectedLines.length} lines${totalLines > 2000 ? " (truncated)" : ""}`,
143
+ shortResult: `Read ${selectedLines.length} lines${totalLines > 2000 || contentTruncated ? " (truncated)" : ""}`,
114
144
  };
115
145
  }
116
146
  catch (error) {
@@ -0,0 +1,8 @@
1
+ import type { ToolPlugin } from "./types.js";
2
+ import type { SkillManager } from "../managers/skillManager.js";
3
+ /**
4
+ * Create a skill tool plugin that uses the provided SkillManager
5
+ * Note: SkillManager should be initialized before calling this function
6
+ */
7
+ export declare function createSkillTool(skillManager: SkillManager): ToolPlugin;
8
+ //# sourceMappingURL=skillTool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skillTool.d.ts","sourceRoot":"","sources":["../../src/tools/skillTool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,YAAY,CAAC;AACzD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,YAAY,EAAE,YAAY,GAAG,UAAU,CA0EtE"}