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.
- package/dist/agent.d.ts +23 -1
- package/dist/agent.js +34 -4
- package/dist/managers/aiManager.d.ts +36 -0
- package/dist/managers/aiManager.js +240 -8
- package/dist/managers/messageManager.d.ts +1 -3
- package/dist/managers/messageManager.js +19 -9
- package/dist/managers/slashCommandManager.js +28 -0
- package/dist/managers/subagentManager.d.ts +0 -2
- package/dist/services/session.js +2 -9
- package/dist/telemetry/instrumentation.d.ts +1 -1
- package/dist/telemetry/instrumentation.js +57 -28
- package/dist/tools/bashTool.js +16 -6
- package/dist/tools/grepTool.js +11 -3
- package/dist/types/index.d.ts +3 -0
- package/dist/types/messaging.d.ts +2 -0
- package/dist/utils/containerSetup.js +0 -3
- package/dist/utils/messageOperations.d.ts +10 -1
- package/dist/utils/messageOperations.js +19 -1
- package/dist/utils/notificationXml.js +5 -0
- package/dist/utils/ripgrep.d.ts +4 -4
- package/dist/utils/ripgrep.js +4 -27
- package/package.json +20 -8
- package/bin/rg +0 -79
- package/dist/managers/forkedAgentManager.d.ts +0 -50
- package/dist/managers/forkedAgentManager.js +0 -130
- package/scripts/install_ripgrep.js +0 -111
- package/scripts/postinstall.js +0 -38
- package/src/agent.ts +0 -1271
- package/src/constants/subagents.ts +0 -4
- package/src/constants/toolLimits.ts +0 -15
- package/src/constants/tools.ts +0 -24
- package/src/core/plugin.ts +0 -237
- package/src/core/session.ts +0 -9
- package/src/index.ts +0 -38
- package/src/managers/MemoryRuleManager.ts +0 -198
- package/src/managers/aiManager.ts +0 -2429
- package/src/managers/backgroundTaskManager.ts +0 -480
- package/src/managers/bangManager.ts +0 -119
- package/src/managers/cronManager.ts +0 -401
- package/src/managers/foregroundTaskManager.ts +0 -30
- package/src/managers/forkedAgentManager.ts +0 -216
- package/src/managers/hookManager.ts +0 -1089
- package/src/managers/liveConfigManager.ts +0 -445
- package/src/managers/lspManager.ts +0 -470
- package/src/managers/mcpManager.ts +0 -1010
- package/src/managers/messageManager.ts +0 -1180
- package/src/managers/messageQueue.ts +0 -157
- package/src/managers/permissionManager.ts +0 -1140
- package/src/managers/planManager.ts +0 -112
- package/src/managers/pluginManager.ts +0 -330
- package/src/managers/pluginScopeManager.ts +0 -124
- package/src/managers/reversionManager.ts +0 -178
- package/src/managers/skillManager.ts +0 -578
- package/src/managers/slashCommandManager.ts +0 -564
- package/src/managers/subagentManager.ts +0 -915
- package/src/managers/toolManager.ts +0 -489
- package/src/managers/workflowManager.ts +0 -493
- package/src/prompts/autoMemory.ts +0 -33
- package/src/prompts/autoMemoryExtraction.ts +0 -146
- package/src/prompts/index.ts +0 -506
- package/src/prompts/planModeReminders.ts +0 -126
- package/src/services/GitService.ts +0 -131
- package/src/services/MarketplaceService.ts +0 -1052
- package/src/services/MemoryRuleService.ts +0 -71
- package/src/services/aiService.ts +0 -919
- package/src/services/authService.ts +0 -565
- package/src/services/autoMemoryService.ts +0 -280
- package/src/services/configurationService.ts +0 -1520
- package/src/services/fileWatcher.ts +0 -319
- package/src/services/hook.ts +0 -348
- package/src/services/initializationService.ts +0 -357
- package/src/services/interactionService.ts +0 -229
- package/src/services/jsonlHandler.ts +0 -295
- package/src/services/memory.ts +0 -234
- package/src/services/pluginLoader.ts +0 -252
- package/src/services/remoteSettingsService.ts +0 -366
- package/src/services/reversionService.ts +0 -122
- package/src/services/session.ts +0 -922
- package/src/services/taskManager.ts +0 -321
- package/src/telemetry/events.ts +0 -65
- package/src/telemetry/instrumentation.ts +0 -499
- package/src/telemetry/sessionTracing.ts +0 -348
- package/src/tools/agentTool.ts +0 -322
- package/src/tools/askUserQuestion.ts +0 -160
- package/src/tools/bashTool.ts +0 -621
- package/src/tools/buildTool.ts +0 -61
- package/src/tools/cronCreateTool.ts +0 -161
- package/src/tools/cronDeleteTool.ts +0 -51
- package/src/tools/cronListTool.ts +0 -47
- package/src/tools/editTool.ts +0 -313
- package/src/tools/enterPlanMode.ts +0 -124
- package/src/tools/enterWorktreeTool.ts +0 -190
- package/src/tools/exitPlanMode.ts +0 -139
- package/src/tools/exitWorktreeTool.ts +0 -236
- package/src/tools/globTool.ts +0 -167
- package/src/tools/grepTool.ts +0 -399
- package/src/tools/lspTool.ts +0 -883
- package/src/tools/readTool.ts +0 -426
- package/src/tools/skillTool.ts +0 -248
- package/src/tools/taskManagementTools.ts +0 -574
- package/src/tools/taskStopTool.ts +0 -78
- package/src/tools/types.ts +0 -137
- package/src/tools/webFetchTool.ts +0 -373
- package/src/tools/workflowTool.ts +0 -205
- package/src/tools/writeTool.ts +0 -267
- package/src/types/agent.ts +0 -128
- package/src/types/auth.ts +0 -19
- package/src/types/commands.ts +0 -30
- package/src/types/config.ts +0 -43
- package/src/types/configuration.ts +0 -168
- package/src/types/core.ts +0 -105
- package/src/types/cron.ts +0 -13
- package/src/types/environment.ts +0 -106
- package/src/types/fileSearch.ts +0 -4
- package/src/types/history.ts +0 -7
- package/src/types/hooks.ts +0 -256
- package/src/types/index.ts +0 -41
- package/src/types/lsp.ts +0 -98
- package/src/types/marketplace.ts +0 -71
- package/src/types/mcp.ts +0 -43
- package/src/types/memoryRule.ts +0 -31
- package/src/types/messaging.ts +0 -114
- package/src/types/permissions.ts +0 -80
- package/src/types/plugins.ts +0 -39
- package/src/types/processes.ts +0 -99
- package/src/types/reversion.ts +0 -29
- package/src/types/session.ts +0 -12
- package/src/types/skills.ts +0 -108
- package/src/types/tasks.ts +0 -13
- package/src/types/telemetry.ts +0 -98
- package/src/types/tools.ts +0 -44
- package/src/types/workflow.ts +0 -6
- package/src/utils/abortUtils.ts +0 -118
- package/src/utils/atomicWrite.ts +0 -61
- package/src/utils/bashParser.ts +0 -899
- package/src/utils/cacheControlUtils.ts +0 -426
- package/src/utils/commandArgumentParser.ts +0 -161
- package/src/utils/commandPathResolver.ts +0 -88
- package/src/utils/configPaths.ts +0 -220
- package/src/utils/configValidator.ts +0 -100
- package/src/utils/constants.ts +0 -39
- package/src/utils/container.ts +0 -92
- package/src/utils/containerSetup.ts +0 -371
- package/src/utils/convertMessagesForAPI.ts +0 -326
- package/src/utils/cronTasks.ts +0 -128
- package/src/utils/cronTasksLock.ts +0 -182
- package/src/utils/cronToHuman.ts +0 -99
- package/src/utils/customCommands.ts +0 -95
- package/src/utils/editUtils.ts +0 -20
- package/src/utils/fileFormat.ts +0 -40
- package/src/utils/fileSearch.ts +0 -151
- package/src/utils/fileUtils.ts +0 -223
- package/src/utils/gitUtils.ts +0 -315
- package/src/utils/globalLogger.ts +0 -128
- package/src/utils/groupMessagesByApiRound.ts +0 -121
- package/src/utils/hookMatcher.ts +0 -176
- package/src/utils/markdownParser.ts +0 -317
- package/src/utils/mcpUtils.ts +0 -138
- package/src/utils/messageOperations.ts +0 -641
- package/src/utils/modelCapabilities.ts +0 -30
- package/src/utils/nameGenerator.ts +0 -99
- package/src/utils/notificationXml.ts +0 -57
- package/src/utils/openaiClient.ts +0 -251
- package/src/utils/parseCronExpression.ts +0 -78
- package/src/utils/path.ts +0 -72
- package/src/utils/pathEncoder.ts +0 -400
- package/src/utils/pathSafety.ts +0 -40
- package/src/utils/promptHistory.ts +0 -168
- package/src/utils/ripgrep.ts +0 -35
- package/src/utils/shellResolver.ts +0 -190
- package/src/utils/skillParser.ts +0 -246
- package/src/utils/stringUtils.ts +0 -156
- package/src/utils/subagentParser.ts +0 -279
- package/src/utils/taskReminder.ts +0 -96
- package/src/utils/tokenCalculation.ts +0 -43
- package/src/utils/tokenEstimate.ts +0 -34
- package/src/utils/toolResultStorage.ts +0 -117
- package/src/utils/worktreeSession.ts +0 -26
- package/src/utils/worktreeUtils.ts +0 -786
- package/src/workflow/budgetTracker.ts +0 -34
- package/src/workflow/concurrencyLimiter.ts +0 -47
- package/src/workflow/journal.ts +0 -95
- package/src/workflow/progressReporter.ts +0 -141
- package/src/workflow/runState.ts +0 -65
- package/src/workflow/scriptRuntime.ts +0 -274
- package/src/workflow/structuredOutput.ts +0 -123
- package/src/workflow/types.ts +0 -101
- package/src/workflow/workflowApis.ts +0 -410
- package/vendor/ripgrep/linux-aarch64/rg +0 -0
- package/vendor/ripgrep/linux-x86_64/rg +0 -0
- package/vendor/ripgrep/macos-aarch64/rg +0 -0
- package/vendor/ripgrep/macos-x86_64/rg +0 -0
- package/vendor/ripgrep/windows-aarch64/rg.exe +0 -0
- 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
|
-
}
|