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,279 +0,0 @@
1
- import { readFileSync, readdirSync, statSync } from "fs";
2
- import { join, extname, basename } from "path";
3
- import { logger } from "./globalLogger.js";
4
- import { getBuiltinSubagentsDir } from "./configPaths.js";
5
-
6
- export interface SubagentConfiguration {
7
- name: string;
8
- description: string;
9
- tools?: string[];
10
- model?: string;
11
- systemPrompt: string;
12
- filePath: string;
13
- scope: "project" | "user" | "builtin" | "plugin";
14
- priority: number;
15
- /** Plugin root directory path, set when scope is "plugin" */
16
- pluginRoot?: string;
17
- }
18
-
19
- interface SubagentFrontmatter {
20
- name?: string;
21
- description?: string;
22
- tools?: string[];
23
- model?: string;
24
- }
25
-
26
- /**
27
- * Parse YAML frontmatter from markdown file content
28
- */
29
- function parseFrontmatter(content: string): {
30
- frontmatter: SubagentFrontmatter;
31
- body: string;
32
- } {
33
- const frontmatterRegex =
34
- /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n([\s\S]*)$/;
35
- const match = content.match(frontmatterRegex);
36
-
37
- if (!match) {
38
- return { frontmatter: {}, body: content.trim() };
39
- }
40
-
41
- const [, yamlContent, body] = match;
42
- const frontmatter = parseYamlFrontmatter(yamlContent);
43
-
44
- return { frontmatter, body: body.trim() };
45
- }
46
-
47
- /**
48
- * Simple YAML frontmatter parser for subagent files
49
- */
50
- function parseYamlFrontmatter(yamlContent: string): SubagentFrontmatter {
51
- const frontmatter: SubagentFrontmatter = {};
52
-
53
- try {
54
- const lines = yamlContent.split("\n");
55
- for (const line of lines) {
56
- const trimmed = line.trim();
57
- if (!trimmed || trimmed.startsWith("#")) continue;
58
-
59
- const colonIndex = trimmed.indexOf(":");
60
- if (colonIndex === -1) continue;
61
-
62
- const key = trimmed.substring(0, colonIndex).trim();
63
- const value = trimmed
64
- .substring(colonIndex + 1)
65
- .trim()
66
- .replace(/^["']|["']$/g, "");
67
-
68
- if (key && value) {
69
- // Handle array values for tools
70
- if (key === "tools" && value) {
71
- let arrayValue = value;
72
- if (arrayValue.startsWith("[") && arrayValue.endsWith("]")) {
73
- arrayValue = arrayValue.slice(1, -1);
74
- }
75
- frontmatter[key] = arrayValue
76
- .split(",")
77
- .map((s) => s.trim())
78
- .filter(Boolean);
79
- } else {
80
- if (key === "name" || key === "description" || key === "model") {
81
- frontmatter[key] = value;
82
- }
83
- }
84
- }
85
- }
86
- } catch {
87
- // Return empty frontmatter on parse error - validation will catch missing fields
88
- }
89
-
90
- return frontmatter;
91
- }
92
-
93
- /**
94
- * Validate subagent configuration
95
- */
96
- function validateConfiguration(
97
- config: SubagentFrontmatter,
98
- filePath: string,
99
- ): void {
100
- if (!config.name) {
101
- throw new Error(`Missing required field 'name' in ${filePath}`);
102
- }
103
-
104
- if (!config.description) {
105
- throw new Error(`Missing required field 'description' in ${filePath}`);
106
- }
107
-
108
- // Validate name pattern - allow letters (upper/lowercase), numbers, and hyphens
109
- const namePattern = /^[a-zA-Z][a-zA-Z0-9-]*$/;
110
- if (!namePattern.test(config.name)) {
111
- throw new Error(
112
- `Invalid subagent name '${config.name}' in ${filePath}. Must start with a letter and contain only letters, numbers, and hyphens.`,
113
- );
114
- }
115
-
116
- // Validate model if specified - allow any non-empty string
117
- if (config.model && typeof config.model !== "string") {
118
- throw new Error(
119
- `Invalid model '${config.model}' in ${filePath}. Must be a string.`,
120
- );
121
- }
122
- }
123
-
124
- /**
125
- * Parse a single subagent markdown file with optional pluginRoot support
126
- */
127
- function parseSubagentFile(
128
- filePath: string,
129
- scope: "project" | "user" | "builtin" | "plugin",
130
- pluginRoot?: string,
131
- ): SubagentConfiguration {
132
- try {
133
- const content = readFileSync(filePath, "utf-8");
134
- const { frontmatter, body } = parseFrontmatter(content);
135
-
136
- // Use filename as default name if not specified in frontmatter
137
- if (!frontmatter.name) {
138
- frontmatter.name = basename(filePath, extname(filePath));
139
- }
140
-
141
- validateConfiguration(frontmatter, filePath);
142
-
143
- if (!body.trim()) {
144
- throw new Error(`Empty system prompt in ${filePath}`);
145
- }
146
-
147
- let priority = 1;
148
- if (scope === "user") priority = 2;
149
- if (scope === "builtin") priority = 3;
150
- if (scope === "plugin") priority = 2; // Same priority as user-level
151
-
152
- let systemPrompt = body;
153
-
154
- // Substitute ${WAVE_PLUGIN_ROOT} for plugin scope at parse time
155
- if (scope === "plugin" && pluginRoot) {
156
- systemPrompt = systemPrompt.replace(
157
- /\$\{WAVE_PLUGIN_ROOT\}/g,
158
- pluginRoot,
159
- );
160
- }
161
-
162
- return {
163
- name: frontmatter.name!,
164
- description: frontmatter.description!,
165
- tools: frontmatter.tools,
166
- model: frontmatter.model,
167
- systemPrompt,
168
- filePath,
169
- scope,
170
- priority,
171
- pluginRoot: scope === "plugin" ? pluginRoot : undefined,
172
- };
173
- } catch (error) {
174
- throw new Error(
175
- `Failed to parse subagent file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
176
- );
177
- }
178
- }
179
-
180
- /**
181
- * Parse a plugin agent markdown file.
182
- * Exposed as a public API for PluginLoader to use.
183
- */
184
- export function parseAgentFile(
185
- filePath: string,
186
- scope: "plugin",
187
- pluginRoot: string,
188
- ): SubagentConfiguration {
189
- return parseSubagentFile(filePath, scope, pluginRoot);
190
- }
191
-
192
- /**
193
- * Scan directory for subagent files
194
- */
195
- function scanSubagentDirectory(
196
- dirPath: string,
197
- scope: "project" | "user" | "builtin",
198
- ): SubagentConfiguration[] {
199
- const configurations: SubagentConfiguration[] = [];
200
-
201
- try {
202
- const entries = readdirSync(dirPath);
203
-
204
- for (const entry of entries) {
205
- const fullPath = join(dirPath, entry);
206
- const stat = statSync(fullPath);
207
-
208
- if (stat.isFile() && extname(entry) === ".md") {
209
- try {
210
- const config = parseSubagentFile(fullPath, scope);
211
- configurations.push(config);
212
- } catch (parseError) {
213
- // Log error but continue with other files
214
- logger.warn(
215
- `Warning: ${parseError instanceof Error ? parseError.message : String(parseError)}`,
216
- );
217
- }
218
- }
219
- }
220
- } catch {
221
- // Directory doesn't exist or can't be read - this is OK
222
- }
223
-
224
- return configurations;
225
- }
226
-
227
- /**
228
- * Load all subagent configurations from project and user directories, plus built-in subagents
229
- */
230
- export async function loadSubagentConfigurations(
231
- workdir: string,
232
- ): Promise<SubagentConfiguration[]> {
233
- const projectWaveDir = join(workdir, ".wave", "agents");
234
- const projectClaudeDir = join(workdir, ".claude", "agents");
235
- const userWaveDir = join(process.env.HOME || "~", ".wave", "agents");
236
- const userClaudeDir = join(process.env.HOME || "~", ".claude", "agents");
237
- const builtinDir = getBuiltinSubagentsDir();
238
-
239
- // Load configurations from all sources
240
- const builtinConfigs = scanSubagentDirectory(builtinDir, "builtin");
241
- const userClaudeConfigs = scanSubagentDirectory(userClaudeDir, "user");
242
- const userWaveConfigs = scanSubagentDirectory(userWaveDir, "user");
243
- const projectClaudeConfigs = scanSubagentDirectory(
244
- projectClaudeDir,
245
- "project",
246
- );
247
- const projectWaveConfigs = scanSubagentDirectory(projectWaveDir, "project");
248
-
249
- // Merge configurations, with .wave taking priority over .claude
250
- const configMap = new Map<string, SubagentConfiguration>();
251
-
252
- // Merge order: builtin → userClaude → userWave → projectClaude → projectWave
253
- // Later writes override earlier ones, so .wave takes priority over .claude
254
- for (const config of [
255
- ...builtinConfigs,
256
- ...userClaudeConfigs,
257
- ...userWaveConfigs,
258
- ...projectClaudeConfigs,
259
- ...projectWaveConfigs,
260
- ]) {
261
- configMap.set(config.name, config);
262
- }
263
-
264
- return Array.from(configMap.values()).sort((a, b) => {
265
- if (a.priority !== b.priority) return a.priority - b.priority;
266
- return a.name.localeCompare(b.name);
267
- });
268
- }
269
-
270
- /**
271
- * Find subagent by exact name match
272
- */
273
- export async function findSubagentByName(
274
- name: string,
275
- workdir: string,
276
- ): Promise<SubagentConfiguration | null> {
277
- const configurations = await loadSubagentConfigurations(workdir);
278
- return configurations.find((config) => config.name === name) || null;
279
- }
@@ -1,96 +0,0 @@
1
- import type { Message } from "../types/messaging.js";
2
- import type { Task } from "../types/tasks.js";
3
-
4
- export const TASK_REMINDER_CONFIG = {
5
- TURNS_SINCE_WRITE: 10,
6
- TURNS_BETWEEN_REMINDERS: 10,
7
- };
8
-
9
- const TASK_MANAGEMENT_TOOLS = new Set(["TaskCreate", "TaskUpdate"]);
10
- const TASK_REMINDER_MARKER = "<!-- task-reminder -->";
11
-
12
- function isQualifyingAssistantMessage(message: Message): boolean {
13
- if (message.role !== "assistant") return false;
14
- if (message.isMeta) return false;
15
- return message.blocks.some((block) => block.type !== "reasoning");
16
- }
17
-
18
- export function getTaskReminderTurnCounts(messages: Message[]): {
19
- turnsSinceLastTaskManagement: number;
20
- turnsSinceLastReminder: number;
21
- } {
22
- let assistantTurnCount = 0;
23
- let turnsSinceLastTaskManagement: number | undefined;
24
- let turnsSinceLastReminder: number | undefined;
25
-
26
- for (let i = messages.length - 1; i >= 0; i--) {
27
- const message = messages[i];
28
-
29
- // Check blocks for task management tools and reminder markers
30
- for (const block of message.blocks) {
31
- if (
32
- turnsSinceLastTaskManagement === undefined &&
33
- block.type === "tool" &&
34
- block.name &&
35
- TASK_MANAGEMENT_TOOLS.has(block.name)
36
- ) {
37
- turnsSinceLastTaskManagement = assistantTurnCount;
38
- }
39
- if (
40
- turnsSinceLastReminder === undefined &&
41
- block.type === "text" &&
42
- block.content.includes(TASK_REMINDER_MARKER)
43
- ) {
44
- turnsSinceLastReminder = assistantTurnCount;
45
- }
46
- }
47
-
48
- if (isQualifyingAssistantMessage(message)) {
49
- assistantTurnCount++;
50
- }
51
- }
52
-
53
- return {
54
- turnsSinceLastTaskManagement:
55
- turnsSinceLastTaskManagement ?? assistantTurnCount,
56
- turnsSinceLastReminder: turnsSinceLastReminder ?? assistantTurnCount,
57
- };
58
- }
59
-
60
- export function buildTaskReminderText(tasks: Task[]): string {
61
- let text = `${TASK_REMINDER_MARKER}\n`;
62
- text +=
63
- "The task tools haven't been used recently. If you're working on tasks that would benefit from tracking progress, consider using TaskCreate to add new tasks and TaskUpdate to update task status (set to in_progress when starting, completed when done). Also consider cleaning up the task list if it has become stale. Only use these if relevant to the current work. This is just a gentle reminder - ignore if not applicable. Make sure that you never mention this reminder to the user";
64
-
65
- if (tasks.length > 0) {
66
- text += "\n\nHere are the existing tasks:\n";
67
- for (const task of tasks) {
68
- text += `#${task.id} [${task.status}] ${task.subject}\n`;
69
- }
70
- }
71
-
72
- return text;
73
- }
74
-
75
- export function maybeInjectTaskReminder(
76
- turnCounts: {
77
- turnsSinceLastTaskManagement: number;
78
- turnsSinceLastReminder: number;
79
- },
80
- tasks: Task[],
81
- ): string | null {
82
- if (
83
- turnCounts.turnsSinceLastTaskManagement <
84
- TASK_REMINDER_CONFIG.TURNS_SINCE_WRITE
85
- ) {
86
- return null;
87
- }
88
- if (
89
- turnCounts.turnsSinceLastReminder <
90
- TASK_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS
91
- ) {
92
- return null;
93
- }
94
-
95
- return buildTaskReminderText(tasks);
96
- }
@@ -1,43 +0,0 @@
1
- import type { Usage } from "../types/index.js";
2
-
3
- /**
4
- * Calculate comprehensive total tokens including cache-related tokens
5
- *
6
- * This function computes the true total token cost by including:
7
- * - Base total_tokens (prompt + completion)
8
- * - Cache read tokens (cost savings indicator)
9
- * - Cache creation tokens (cache investment)
10
- *
11
- * For accurate cost tracking with Claude models that support cache control.
12
- *
13
- * @param usage - Usage statistics from AI operation
14
- * @returns Comprehensive total including all cache-related tokens
15
- */
16
- export function calculateComprehensiveTotalTokens(usage: Usage): number {
17
- const baseTokens = usage.total_tokens;
18
- const cacheReadTokens = usage.cache_read_input_tokens || 0;
19
- const cacheCreateTokens = usage.cache_creation_input_tokens || 0;
20
-
21
- return baseTokens + cacheReadTokens + cacheCreateTokens;
22
- }
23
-
24
- /**
25
- * Extract the latest total tokens from the last message with usage data
26
- * Uses comprehensive calculation that includes cache tokens for accurate tracking
27
- *
28
- * @param messages - Array of messages to search
29
- * @returns Comprehensive total tokens from the most recent usage data, or 0 if none found
30
- */
31
- export function extractLatestTotalTokens(
32
- messages: Array<{ usage?: Usage }>,
33
- ): number {
34
- // Find the last message with usage data (iterate backwards for efficiency)
35
- for (let i = messages.length - 1; i >= 0; i--) {
36
- const message = messages[i];
37
- if (message.usage) {
38
- return calculateComprehensiveTotalTokens(message.usage);
39
- }
40
- }
41
-
42
- return 0; // No usage data found
43
- }
@@ -1,34 +0,0 @@
1
- /**
2
- * CJK-aware token estimation without external dependencies.
3
- *
4
- * The naive `length / 4` heuristic under-estimates CJK text by ~4x because
5
- * each Chinese/Japanese/Korean character is typically 1-2 tokens, not 0.25.
6
- * This function separates CJK characters from other text and applies
7
- * different ratios:
8
- *
9
- * - CJK characters: 1 char ≈ 1 token
10
- * - Other characters: 4 chars ≈ 1 token (2 for JSON/JSONL/JSONC)
11
- *
12
- * The estimate intentionally leans high for CJK (safe direction for limit
13
- * checks — better to reject than to let oversized content through).
14
- */
15
-
16
- // CJK Unified Ideographs + Extension A + Hiragana + Katakana + Hangul Syllables
17
- const CJK_REGEX =
18
- /[\u4e00-\u9fff\u3400-\u4dbf\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
19
-
20
- /**
21
- * Estimate token count for a string, with CJK-awareness.
22
- *
23
- * @param content - The text content to estimate
24
- * @param ext - File extension (without dot), e.g. "ts", "json". JSON/JSONL/JSONC
25
- * files use a tighter ratio (2 chars/token) for non-CJK text.
26
- * @returns Estimated token count
27
- */
28
- export function estimateTokens(content: string, ext?: string): number {
29
- const cjkCount = (content.match(CJK_REGEX) || []).length;
30
- const otherCount = content.length - cjkCount;
31
- const bytesPerToken =
32
- ext === "json" || ext === "jsonl" || ext === "jsonc" ? 2 : 4;
33
- return Math.ceil(cjkCount + otherCount / bytesPerToken);
34
- }
@@ -1,117 +0,0 @@
1
- /**
2
- * Shared tool result persistence and truncation logic.
3
- *
4
- * When a tool result exceeds a size threshold, the full content is saved to a
5
- * file in /tmp/wave-tool-results/ and the model receives a <persisted-output>
6
- * preview with the file path so it can use the Read tool to access the full output.
7
- */
8
-
9
- import * as fs from "fs";
10
- import * as path from "path";
11
- import * as os from "os";
12
- import {
13
- DEFAULT_MAX_RESULT_SIZE_CHARS,
14
- PREVIEW_SIZE_BYTES,
15
- } from "../constants/toolLimits.js";
16
- import { logger } from "./globalLogger.js";
17
-
18
- const TOOL_RESULTS_DIR = path.join(os.tmpdir(), "wave-tool-results");
19
-
20
- /**
21
- * Get (and create if needed) the tool-results directory.
22
- * Uses /tmp/wave-tool-results/ for simplicity and automatic OS cleanup.
23
- */
24
- export function getToolResultsDir(): string {
25
- fs.mkdirSync(TOOL_RESULTS_DIR, { recursive: true });
26
- return TOOL_RESULTS_DIR;
27
- }
28
-
29
- /**
30
- * Persist full tool output to a file in the tool-results directory.
31
- * Returns the file path on success, or undefined on failure.
32
- */
33
- export function persistToolResult(
34
- content: string,
35
- prefix: string = "tool",
36
- ): string | undefined {
37
- try {
38
- const dir = getToolResultsDir();
39
- const id = `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
40
- const filePath = path.join(dir, `${id}.txt`);
41
- fs.writeFileSync(filePath, content, "utf8");
42
- return filePath;
43
- } catch (error) {
44
- logger?.error("Failed to persist tool result:", error);
45
- return undefined;
46
- }
47
- }
48
-
49
- /**
50
- * Generate a preview from content: first `previewSize` characters with ellipsis.
51
- */
52
- export function generatePreview(
53
- content: string,
54
- previewSize: number = PREVIEW_SIZE_BYTES,
55
- ): string {
56
- if (content.length <= previewSize) return content;
57
- return content.substring(0, previewSize) + "\n...";
58
- }
59
-
60
- /**
61
- * Build the <persisted-output> wrapper message that the model sees.
62
- *
63
- * Example output:
64
- * <persisted-output>
65
- * Output too large (150,000 characters). Full output saved to: /tmp/wave-tool-results/mcp_server_tool_12345.txt
66
- * Preview (first 2,048 characters):
67
- * {preview content}
68
- * ...
69
- * </persisted-output>
70
- */
71
- export function buildPersistedOutputMessage(
72
- totalChars: number,
73
- filePath: string,
74
- preview: string,
75
- ): string {
76
- return [
77
- "<persisted-output>",
78
- `Output too large (${totalChars.toLocaleString()} characters). Full output saved to: ${filePath}`,
79
- `Preview (first ${PREVIEW_SIZE_BYTES.toLocaleString()} characters):`,
80
- preview,
81
- "</persisted-output>",
82
- ].join("\n");
83
- }
84
-
85
- /**
86
- * Process tool result: if content exceeds maxChars, persist to file and return
87
- * truncated content with <persisted-output> wrapper. Otherwise return unchanged.
88
- *
89
- * This is the main entry point for both MCP and bash tools.
90
- *
91
- * @param content - The tool result content
92
- * @param maxChars - Maximum characters before persistence kicks in (defaults to DEFAULT_MAX_RESULT_SIZE_CHARS)
93
- * @param prefix - File name prefix for the persisted file (e.g. "bash", "mcp")
94
- * @returns The content to send to the model (either original or persisted-output wrapper)
95
- */
96
- export function processToolResult(
97
- content: string,
98
- maxChars: number = DEFAULT_MAX_RESULT_SIZE_CHARS,
99
- prefix: string = "tool",
100
- ): string {
101
- if (content.length <= maxChars) {
102
- return content;
103
- }
104
-
105
- const filePath = persistToolResult(content, prefix);
106
-
107
- if (filePath) {
108
- const preview = generatePreview(content);
109
- return buildPersistedOutputMessage(content.length, filePath, preview);
110
- }
111
-
112
- // Fallback: truncation only (persistence failed)
113
- return (
114
- content.substring(0, maxChars) +
115
- "\n\n... (output truncated, failed to persist full output)"
116
- );
117
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * Worktree session state tracking.
3
- *
4
- * The session state is stored per-agent in each session's DI container (see the
5
- * "WorktreeSession" container slot registered in containerSetup.ts and accessed via
6
- * AIManager.getWorktreeSession()/setWorktreeSession()). This keeps worktree state
7
- * isolated per session in stdio multi-agent mode — a process-level singleton would
8
- * leak state across concurrent sessions (see docs/specs/multi-agent/worktree.md FR-042).
9
- */
10
-
11
- export interface WorktreeSession {
12
- /** The working directory the session was in before EnterWorktree */
13
- originalCwd: string;
14
- /** Path to the worktree directory */
15
- worktreePath: string;
16
- /** Git branch name for the worktree */
17
- worktreeBranch: string;
18
- /** User-provided or auto-generated worktree name */
19
- worktreeName: string;
20
- /** Whether this worktree was newly created (vs resumed existing) */
21
- isNew: boolean;
22
- /** The canonical git repo root */
23
- repoRoot: string;
24
- /** The HEAD commit of the original branch at worktree creation time */
25
- originalHeadCommit?: string;
26
- }