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,1089 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Hook Manager
|
|
3
|
-
*
|
|
4
|
-
* Central orchestrator for the hooks system. Handles configuration loading,
|
|
5
|
-
* validation, and hook execution across all supported events.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import {
|
|
9
|
-
type HookEvent,
|
|
10
|
-
type HookEventConfig,
|
|
11
|
-
type HookExecutionContext,
|
|
12
|
-
type ExtendedHookExecutionContext,
|
|
13
|
-
type HookExecutionResult,
|
|
14
|
-
type HookValidationResult,
|
|
15
|
-
type SessionEndSource,
|
|
16
|
-
type SessionStartSource,
|
|
17
|
-
HookConfigurationError,
|
|
18
|
-
isValidHookEvent,
|
|
19
|
-
isValidHookEventConfig,
|
|
20
|
-
} from "../types/hooks.js";
|
|
21
|
-
import type {
|
|
22
|
-
WaveConfiguration,
|
|
23
|
-
PartialHookConfiguration,
|
|
24
|
-
} from "../types/configuration.js";
|
|
25
|
-
import { HookMatcher } from "../utils/hookMatcher.js";
|
|
26
|
-
import { executeCommand, isCommandSafe } from "../services/hook.js";
|
|
27
|
-
import { MessageSource } from "../types/index.js";
|
|
28
|
-
import type { MessageManager } from "./messageManager.js";
|
|
29
|
-
import { Container } from "../utils/container.js";
|
|
30
|
-
import type { ConfigurationService } from "../services/configurationService.js";
|
|
31
|
-
|
|
32
|
-
import { logger } from "../utils/globalLogger.js";
|
|
33
|
-
|
|
34
|
-
export class HookManager {
|
|
35
|
-
private configuration: PartialHookConfiguration | undefined;
|
|
36
|
-
private programmaticHooks: PartialHookConfiguration = {};
|
|
37
|
-
private pluginHooks: PartialHookConfiguration = {};
|
|
38
|
-
private waveConfigHooks: PartialHookConfiguration = {};
|
|
39
|
-
private readonly matcher: HookMatcher;
|
|
40
|
-
private readonly workdir: string;
|
|
41
|
-
|
|
42
|
-
constructor(
|
|
43
|
-
private container: Container,
|
|
44
|
-
workdir: string,
|
|
45
|
-
matcher: HookMatcher = new HookMatcher(),
|
|
46
|
-
) {
|
|
47
|
-
this.workdir = workdir;
|
|
48
|
-
this.matcher = matcher;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* Merged env for this session (OS env overlaid with the per-session settings
|
|
53
|
-
* snapshot). Hook subprocesses spawn with this env so settings.json `env`
|
|
54
|
-
* vars reach hooks without polluting other sessions in one stdio process.
|
|
55
|
-
*/
|
|
56
|
-
private get sessionEnv(): Record<string, string> {
|
|
57
|
-
return (
|
|
58
|
-
this.container
|
|
59
|
-
.get<ConfigurationService>("ConfigurationService")
|
|
60
|
-
?.getMergedEnv?.() ?? (process.env as Record<string, string>)
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Load hook configuration from programmatic source (AgentOptions.hooks)
|
|
66
|
-
*/
|
|
67
|
-
loadConfiguration(hooks?: PartialHookConfiguration): void {
|
|
68
|
-
this.programmaticHooks = {};
|
|
69
|
-
|
|
70
|
-
if (hooks) {
|
|
71
|
-
this.mergeHooksConfiguration(this.programmaticHooks, hooks);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// Validate merged configuration
|
|
75
|
-
const validation = this.validatePartialConfiguration(
|
|
76
|
-
this.programmaticHooks,
|
|
77
|
-
);
|
|
78
|
-
if (!validation.valid) {
|
|
79
|
-
throw new HookConfigurationError(
|
|
80
|
-
"merged configuration",
|
|
81
|
-
validation.errors,
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
this.rebuildConfiguration();
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Load hooks configuration from a pre-loaded WaveConfiguration
|
|
90
|
-
* Configuration loading is now handled by ConfigurationService
|
|
91
|
-
*/
|
|
92
|
-
loadConfigurationFromWaveConfig(waveConfig: WaveConfiguration | null): void {
|
|
93
|
-
try {
|
|
94
|
-
// Replace (not append) wave config hooks to avoid duplicates on reload
|
|
95
|
-
this.waveConfigHooks = {};
|
|
96
|
-
|
|
97
|
-
if (waveConfig?.hooks) {
|
|
98
|
-
const validation = this.validatePartialConfiguration(waveConfig.hooks);
|
|
99
|
-
if (!validation.valid) {
|
|
100
|
-
throw new HookConfigurationError(
|
|
101
|
-
"provided configuration",
|
|
102
|
-
validation.errors,
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
this.waveConfigHooks = { ...waveConfig.hooks };
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
this.rebuildConfiguration();
|
|
109
|
-
} catch (error) {
|
|
110
|
-
// Re-throw configuration errors, but handle other errors gracefully
|
|
111
|
-
if (error instanceof HookConfigurationError) {
|
|
112
|
-
throw error;
|
|
113
|
-
} else {
|
|
114
|
-
logger?.warn(
|
|
115
|
-
`[HookManager] Failed to load configuration, continuing with existing hooks: ${(error as Error).message}`,
|
|
116
|
-
);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/**
|
|
122
|
-
* Rebuild the full configuration from all sources:
|
|
123
|
-
* programmatic (AgentOptions.hooks) + plugin + wave config (settings.json)
|
|
124
|
-
* Order determines precedence on conflict (later sources append).
|
|
125
|
-
*/
|
|
126
|
-
private rebuildConfiguration(): void {
|
|
127
|
-
const rebuilt: PartialHookConfiguration = {};
|
|
128
|
-
this.mergeHooksConfiguration(rebuilt, this.programmaticHooks);
|
|
129
|
-
this.mergeHooksConfiguration(rebuilt, this.pluginHooks);
|
|
130
|
-
this.mergeHooksConfiguration(rebuilt, this.waveConfigHooks);
|
|
131
|
-
this.configuration = Object.keys(rebuilt).length > 0 ? rebuilt : undefined;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Execute hooks for a specific event
|
|
136
|
-
*/
|
|
137
|
-
async executeHooks(
|
|
138
|
-
event: HookEvent,
|
|
139
|
-
context: HookExecutionContext | ExtendedHookExecutionContext,
|
|
140
|
-
): Promise<HookExecutionResult[]> {
|
|
141
|
-
// Validate execution context
|
|
142
|
-
const contextValidation = this.validateExecutionContext(event, context);
|
|
143
|
-
if (!contextValidation.valid) {
|
|
144
|
-
logger?.error(
|
|
145
|
-
`[HookManager] Invalid execution context for ${event}: ${contextValidation.errors.join(", ")}`,
|
|
146
|
-
);
|
|
147
|
-
return [
|
|
148
|
-
{
|
|
149
|
-
success: false,
|
|
150
|
-
stderr: `Invalid execution context: ${contextValidation.errors.join(", ")}`,
|
|
151
|
-
duration: 0,
|
|
152
|
-
timedOut: false,
|
|
153
|
-
},
|
|
154
|
-
];
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
if (!this.configuration) {
|
|
158
|
-
return [];
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const eventConfigs = this.configuration[event];
|
|
162
|
-
if (!eventConfigs || eventConfigs.length === 0) {
|
|
163
|
-
return [];
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
const results: HookExecutionResult[] = [];
|
|
167
|
-
|
|
168
|
-
for (
|
|
169
|
-
let configIndex = 0;
|
|
170
|
-
configIndex < eventConfigs.length;
|
|
171
|
-
configIndex++
|
|
172
|
-
) {
|
|
173
|
-
const config = eventConfigs[configIndex];
|
|
174
|
-
|
|
175
|
-
// Check if this config applies to the current context
|
|
176
|
-
if (!this.configApplies(config, event, context.toolName)) {
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// Execute all commands for this configuration
|
|
181
|
-
for (
|
|
182
|
-
let commandIndex = 0;
|
|
183
|
-
commandIndex < config.hooks.length;
|
|
184
|
-
commandIndex++
|
|
185
|
-
) {
|
|
186
|
-
const hookCommand = config.hooks[commandIndex];
|
|
187
|
-
|
|
188
|
-
try {
|
|
189
|
-
const options = hookCommand.timeout
|
|
190
|
-
? { timeout: hookCommand.timeout * 1000 }
|
|
191
|
-
: undefined;
|
|
192
|
-
|
|
193
|
-
// Build execution context with WAVE_PLUGIN_ROOT if this is a plugin hook
|
|
194
|
-
let command = hookCommand.command;
|
|
195
|
-
const execContext: typeof context = hookCommand.pluginRoot
|
|
196
|
-
? {
|
|
197
|
-
...context,
|
|
198
|
-
env: {
|
|
199
|
-
...("env" in context ? (context.env ?? {}) : {}),
|
|
200
|
-
WAVE_PLUGIN_ROOT: hookCommand.pluginRoot,
|
|
201
|
-
CLAUDE_PLUGIN_ROOT: hookCommand.pluginRoot,
|
|
202
|
-
},
|
|
203
|
-
}
|
|
204
|
-
: context;
|
|
205
|
-
|
|
206
|
-
// Substitute ${WAVE_PLUGIN_ROOT} and ${CLAUDE_PLUGIN_ROOT} in the command string
|
|
207
|
-
if (hookCommand.pluginRoot) {
|
|
208
|
-
command = command.replace(
|
|
209
|
-
/\$\{WAVE_PLUGIN_ROOT\}/g,
|
|
210
|
-
hookCommand.pluginRoot,
|
|
211
|
-
);
|
|
212
|
-
command = command.replace(
|
|
213
|
-
/\$\{CLAUDE_PLUGIN_ROOT\}/g,
|
|
214
|
-
hookCommand.pluginRoot,
|
|
215
|
-
);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
if (hookCommand.async) {
|
|
219
|
-
// Execute async command without awaiting
|
|
220
|
-
executeCommand(command, execContext, options).catch((error) => {
|
|
221
|
-
const errorMessage =
|
|
222
|
-
error instanceof Error
|
|
223
|
-
? error.message
|
|
224
|
-
: "Unknown execution error";
|
|
225
|
-
logger?.error(
|
|
226
|
-
`[HookManager] Async hook command ${commandIndex + 1} failed: ${errorMessage}`,
|
|
227
|
-
);
|
|
228
|
-
});
|
|
229
|
-
// Async hooks are not included in results to prevent blocking
|
|
230
|
-
continue;
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const result = await executeCommand(command, execContext, options);
|
|
234
|
-
results.push(result);
|
|
235
|
-
|
|
236
|
-
// Continue with next command even if this one fails
|
|
237
|
-
// This allows for non-critical hooks to fail without stopping the workflow
|
|
238
|
-
} catch (error) {
|
|
239
|
-
// This should be rare as executor handles most errors
|
|
240
|
-
const errorMessage =
|
|
241
|
-
error instanceof Error ? error.message : "Unknown execution error";
|
|
242
|
-
logger?.error(
|
|
243
|
-
`[HookManager] Unexpected error in command ${commandIndex + 1}: ${errorMessage}`,
|
|
244
|
-
);
|
|
245
|
-
|
|
246
|
-
results.push({
|
|
247
|
-
success: false,
|
|
248
|
-
stderr: errorMessage,
|
|
249
|
-
duration: 0,
|
|
250
|
-
timedOut: false,
|
|
251
|
-
});
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
return results;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/**
|
|
260
|
-
* Process hook execution results and determine appropriate actions
|
|
261
|
-
* based on exit codes and hook event type
|
|
262
|
-
*/
|
|
263
|
-
processHookResults(
|
|
264
|
-
event: HookEvent,
|
|
265
|
-
results: HookExecutionResult[],
|
|
266
|
-
messageManager?: MessageManager,
|
|
267
|
-
toolId?: string,
|
|
268
|
-
toolParameters?: string,
|
|
269
|
-
): {
|
|
270
|
-
shouldBlock: boolean;
|
|
271
|
-
errorMessage?: string;
|
|
272
|
-
} {
|
|
273
|
-
if (!messageManager || results.length === 0) {
|
|
274
|
-
return { shouldBlock: false };
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// First pass: Check for any blocking errors (exit code 2)
|
|
278
|
-
// Blocking errors take precedence and stop all processing
|
|
279
|
-
for (const result of results) {
|
|
280
|
-
if (result.exitCode === 2) {
|
|
281
|
-
// Handle blocking error immediately and return
|
|
282
|
-
const blockingResult = this.handleBlockingError(
|
|
283
|
-
event,
|
|
284
|
-
result,
|
|
285
|
-
messageManager,
|
|
286
|
-
toolId,
|
|
287
|
-
toolParameters,
|
|
288
|
-
);
|
|
289
|
-
return {
|
|
290
|
-
shouldBlock: blockingResult.shouldBlock,
|
|
291
|
-
errorMessage: blockingResult.errorMessage,
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// Second pass: Process all non-blocking results
|
|
297
|
-
for (const result of results) {
|
|
298
|
-
if (result.exitCode === undefined) {
|
|
299
|
-
continue; // Skip results without exit codes
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
// Handle exit code interpretation
|
|
303
|
-
if (result.exitCode === 0) {
|
|
304
|
-
// Success case - handle stdout based on hook type
|
|
305
|
-
this.handleHookSuccess(event, result, messageManager);
|
|
306
|
-
} else {
|
|
307
|
-
// Non-blocking error case (any exit code except 0 and 2)
|
|
308
|
-
this.handleNonBlockingError(result, messageManager);
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
return { shouldBlock: false };
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
/**
|
|
316
|
-
* Handle successful hook execution (exit code 0)
|
|
317
|
-
*/
|
|
318
|
-
private handleHookSuccess(
|
|
319
|
-
event: HookEvent,
|
|
320
|
-
result: HookExecutionResult,
|
|
321
|
-
messageManager: MessageManager,
|
|
322
|
-
): void {
|
|
323
|
-
if (event === "UserPromptSubmit" && result.stdout?.trim()) {
|
|
324
|
-
// Inject stdout as user message context for UserPromptSubmit
|
|
325
|
-
messageManager.addUserMessage({
|
|
326
|
-
content: result.stdout.trim(),
|
|
327
|
-
source: MessageSource.HOOK,
|
|
328
|
-
});
|
|
329
|
-
}
|
|
330
|
-
// For SessionStart, stdout is processed separately in executeSessionStartHooks
|
|
331
|
-
// For SessionEnd, stdout is ignored (fire-and-forget cleanup)
|
|
332
|
-
// For other hook types (PreToolUse, PostToolUse, Stop, PermissionRequest), ignore stdout
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* Handle blocking error (exit code 2) - behavior varies by hook type
|
|
337
|
-
*/
|
|
338
|
-
private handleBlockingError(
|
|
339
|
-
event: HookEvent,
|
|
340
|
-
result: HookExecutionResult,
|
|
341
|
-
messageManager: MessageManager,
|
|
342
|
-
toolId?: string,
|
|
343
|
-
toolParameters?: string,
|
|
344
|
-
): {
|
|
345
|
-
shouldBlock: boolean;
|
|
346
|
-
errorMessage?: string;
|
|
347
|
-
} {
|
|
348
|
-
const errorMessage = result.stderr?.trim() || "Hook execution failed";
|
|
349
|
-
|
|
350
|
-
switch (event) {
|
|
351
|
-
case "UserPromptSubmit":
|
|
352
|
-
// Block prompt processing, show error to user, erase prompt
|
|
353
|
-
messageManager.addErrorBlock(errorMessage);
|
|
354
|
-
messageManager.removeLastUserMessage();
|
|
355
|
-
return {
|
|
356
|
-
shouldBlock: true,
|
|
357
|
-
errorMessage,
|
|
358
|
-
};
|
|
359
|
-
|
|
360
|
-
case "PreToolUse":
|
|
361
|
-
// Block tool execution and show error to Wave Agent via tool block
|
|
362
|
-
if (toolId) {
|
|
363
|
-
messageManager.updateToolBlock({
|
|
364
|
-
id: toolId,
|
|
365
|
-
parameters: toolParameters || "",
|
|
366
|
-
result: errorMessage,
|
|
367
|
-
success: false,
|
|
368
|
-
error: "Hook blocked tool execution",
|
|
369
|
-
stage: "end", // Hook blocking results in end stage with error
|
|
370
|
-
});
|
|
371
|
-
}
|
|
372
|
-
return { shouldBlock: true };
|
|
373
|
-
|
|
374
|
-
case "PostToolUse":
|
|
375
|
-
// Show error to Wave Agent via user message and allow AI to continue
|
|
376
|
-
messageManager.addUserMessage({
|
|
377
|
-
content: errorMessage,
|
|
378
|
-
source: MessageSource.HOOK,
|
|
379
|
-
});
|
|
380
|
-
return { shouldBlock: false };
|
|
381
|
-
|
|
382
|
-
case "Stop":
|
|
383
|
-
// Show error to Wave Agent via user message and block stopping to continue conversation
|
|
384
|
-
messageManager.addUserMessage({
|
|
385
|
-
content: errorMessage,
|
|
386
|
-
source: MessageSource.HOOK,
|
|
387
|
-
});
|
|
388
|
-
return { shouldBlock: true, errorMessage };
|
|
389
|
-
|
|
390
|
-
case "PermissionRequest":
|
|
391
|
-
// For permission request hooks with exit code 2, show stderr in error block and block (deny) permission
|
|
392
|
-
messageManager.addErrorBlock(errorMessage);
|
|
393
|
-
return { shouldBlock: true, errorMessage };
|
|
394
|
-
|
|
395
|
-
case "SubagentStop":
|
|
396
|
-
// Similar to Stop, show error and allow blocking
|
|
397
|
-
messageManager.addUserMessage({
|
|
398
|
-
content: errorMessage,
|
|
399
|
-
source: MessageSource.HOOK,
|
|
400
|
-
});
|
|
401
|
-
return { shouldBlock: true, errorMessage };
|
|
402
|
-
|
|
403
|
-
case "WorktreeCreate":
|
|
404
|
-
// Non-blocking for now, just show error in error block
|
|
405
|
-
messageManager.addErrorBlock(errorMessage);
|
|
406
|
-
return { shouldBlock: false };
|
|
407
|
-
|
|
408
|
-
case "WorktreeRemove":
|
|
409
|
-
// Non-blocking for cleanup, log error but don't block
|
|
410
|
-
messageManager.addErrorBlock(errorMessage);
|
|
411
|
-
return { shouldBlock: false };
|
|
412
|
-
|
|
413
|
-
case "SessionStart":
|
|
414
|
-
// Non-blocking for startup, show error in error block
|
|
415
|
-
messageManager.addErrorBlock(errorMessage);
|
|
416
|
-
return { shouldBlock: false };
|
|
417
|
-
|
|
418
|
-
case "SessionEnd":
|
|
419
|
-
// Blocking error (exit code 2): show in error block, don't block shutdown
|
|
420
|
-
messageManager.addErrorBlock(errorMessage);
|
|
421
|
-
return { shouldBlock: false };
|
|
422
|
-
|
|
423
|
-
case "PreCompact":
|
|
424
|
-
// Non-blocking for compaction, show error in error block
|
|
425
|
-
messageManager.addErrorBlock(errorMessage);
|
|
426
|
-
return { shouldBlock: false };
|
|
427
|
-
|
|
428
|
-
case "PostCompact":
|
|
429
|
-
// Non-blocking for compaction, show error in error block
|
|
430
|
-
messageManager.addErrorBlock(errorMessage);
|
|
431
|
-
return { shouldBlock: false };
|
|
432
|
-
|
|
433
|
-
default:
|
|
434
|
-
return { shouldBlock: false };
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
/**
|
|
439
|
-
* Handle non-blocking error (other exit codes)
|
|
440
|
-
*/
|
|
441
|
-
private handleNonBlockingError(
|
|
442
|
-
result: HookExecutionResult,
|
|
443
|
-
messageManager: MessageManager,
|
|
444
|
-
): void {
|
|
445
|
-
const errorMessage = result.stderr?.trim() || "Hook execution failed";
|
|
446
|
-
messageManager.addErrorBlock(errorMessage);
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
* Check if hooks are configured for an event/tool combination
|
|
451
|
-
*/
|
|
452
|
-
hasHooks(event: HookEvent, toolName?: string): boolean {
|
|
453
|
-
if (!this.configuration) return false;
|
|
454
|
-
|
|
455
|
-
const eventConfigs = this.configuration[event];
|
|
456
|
-
if (!eventConfigs || eventConfigs.length === 0) return false;
|
|
457
|
-
|
|
458
|
-
return eventConfigs.some((config) =>
|
|
459
|
-
this.configApplies(config, event, toolName),
|
|
460
|
-
);
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
/**
|
|
464
|
-
* Validate Wave configuration structure and content
|
|
465
|
-
*/
|
|
466
|
-
validateConfiguration(config: WaveConfiguration): HookValidationResult {
|
|
467
|
-
const errors: string[] = [];
|
|
468
|
-
|
|
469
|
-
if (!config || typeof config !== "object") {
|
|
470
|
-
return { valid: false, errors: ["Configuration must be an object"] };
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// Validate hooks if present
|
|
474
|
-
if (config.hooks) {
|
|
475
|
-
if (typeof config.hooks !== "object") {
|
|
476
|
-
errors.push("hooks property must be an object");
|
|
477
|
-
} else {
|
|
478
|
-
// Validate each hook event
|
|
479
|
-
for (const [eventName, eventConfigs] of Object.entries(config.hooks)) {
|
|
480
|
-
// Validate event name
|
|
481
|
-
if (!isValidHookEvent(eventName)) {
|
|
482
|
-
errors.push(`Invalid hook event: ${eventName}`);
|
|
483
|
-
continue;
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
// Validate event configurations
|
|
487
|
-
if (!Array.isArray(eventConfigs)) {
|
|
488
|
-
errors.push(
|
|
489
|
-
`Hook event ${eventName} must be an array of configurations`,
|
|
490
|
-
);
|
|
491
|
-
continue;
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
eventConfigs.forEach((eventConfig, index) => {
|
|
495
|
-
const configErrors = this.validateEventConfig(
|
|
496
|
-
eventName as HookEvent,
|
|
497
|
-
eventConfig,
|
|
498
|
-
index,
|
|
499
|
-
);
|
|
500
|
-
errors.push(...configErrors);
|
|
501
|
-
});
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// Validate environment variables if present
|
|
507
|
-
if (config.env) {
|
|
508
|
-
if (typeof config.env !== "object" || Array.isArray(config.env)) {
|
|
509
|
-
errors.push("env property must be an object");
|
|
510
|
-
} else {
|
|
511
|
-
for (const [key, value] of Object.entries(config.env)) {
|
|
512
|
-
if (typeof key !== "string" || key.trim() === "") {
|
|
513
|
-
errors.push(`Invalid environment variable key: ${key}`);
|
|
514
|
-
}
|
|
515
|
-
if (typeof value !== "string") {
|
|
516
|
-
errors.push(`Environment variable ${key} must have a string value`);
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
return {
|
|
523
|
-
valid: errors.length === 0,
|
|
524
|
-
errors,
|
|
525
|
-
};
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
/**
|
|
529
|
-
* Validate partial hook configuration structure and content
|
|
530
|
-
*/
|
|
531
|
-
private validatePartialConfiguration(
|
|
532
|
-
config: PartialHookConfiguration,
|
|
533
|
-
): HookValidationResult {
|
|
534
|
-
const errors: string[] = [];
|
|
535
|
-
|
|
536
|
-
if (!config || typeof config !== "object") {
|
|
537
|
-
return { valid: false, errors: ["Configuration must be an object"] };
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// Validate each hook event that is present
|
|
541
|
-
for (const [eventName, eventConfigs] of Object.entries(config)) {
|
|
542
|
-
// Validate event name
|
|
543
|
-
if (!isValidHookEvent(eventName)) {
|
|
544
|
-
errors.push(`Invalid hook event: ${eventName}`);
|
|
545
|
-
continue;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
// Validate event configurations
|
|
549
|
-
if (!Array.isArray(eventConfigs)) {
|
|
550
|
-
errors.push(
|
|
551
|
-
`Hook event ${eventName} must be an array of configurations`,
|
|
552
|
-
);
|
|
553
|
-
continue;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
eventConfigs.forEach((eventConfig, index) => {
|
|
557
|
-
const configErrors = this.validateEventConfig(
|
|
558
|
-
eventName as HookEvent,
|
|
559
|
-
eventConfig,
|
|
560
|
-
index,
|
|
561
|
-
);
|
|
562
|
-
errors.push(...configErrors);
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
return {
|
|
567
|
-
valid: errors.length === 0,
|
|
568
|
-
errors,
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Get current configuration
|
|
574
|
-
*/
|
|
575
|
-
getConfiguration(): PartialHookConfiguration | undefined {
|
|
576
|
-
if (!this.configuration) return undefined;
|
|
577
|
-
|
|
578
|
-
// Deep clone to prevent external modification
|
|
579
|
-
return JSON.parse(JSON.stringify(this.configuration));
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
/**
|
|
583
|
-
* Clear current configuration
|
|
584
|
-
*/
|
|
585
|
-
clearConfiguration(): void {
|
|
586
|
-
this.configuration = undefined;
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
/**
|
|
590
|
-
* Validate execution context for a specific event
|
|
591
|
-
*/
|
|
592
|
-
private validateExecutionContext(
|
|
593
|
-
event: HookEvent,
|
|
594
|
-
context: HookExecutionContext,
|
|
595
|
-
): HookValidationResult {
|
|
596
|
-
const errors: string[] = [];
|
|
597
|
-
|
|
598
|
-
// Validate basic context structure
|
|
599
|
-
if (!context || typeof context !== "object") {
|
|
600
|
-
return { valid: false, errors: ["Context must be an object"] };
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
// Warn about event mismatch but don't fail validation
|
|
604
|
-
if (context.event !== event) {
|
|
605
|
-
logger?.warn(
|
|
606
|
-
`[HookManager] Context event '${context.event}' does not match requested event '${event}'`,
|
|
607
|
-
);
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
// Validate project directory
|
|
611
|
-
if (!context.projectDir || typeof context.projectDir !== "string") {
|
|
612
|
-
errors.push("Context must have a valid projectDir string");
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
// Validate timestamp
|
|
616
|
-
if (!context.timestamp || !(context.timestamp instanceof Date)) {
|
|
617
|
-
errors.push("Context must have a valid timestamp Date object");
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// Validate tool-specific requirements
|
|
621
|
-
if (
|
|
622
|
-
event === "PreToolUse" ||
|
|
623
|
-
event === "PostToolUse" ||
|
|
624
|
-
event === "PermissionRequest"
|
|
625
|
-
) {
|
|
626
|
-
if (!context.toolName || typeof context.toolName !== "string") {
|
|
627
|
-
errors.push(`${event} event requires a valid toolName in context`);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
// Validate non-tool events don't have unexpected tool names
|
|
632
|
-
if (
|
|
633
|
-
(event === "UserPromptSubmit" ||
|
|
634
|
-
event === "Stop" ||
|
|
635
|
-
event === "SubagentStop" ||
|
|
636
|
-
event === "WorktreeCreate" ||
|
|
637
|
-
event === "WorktreeRemove" ||
|
|
638
|
-
event === "SessionStart" ||
|
|
639
|
-
event === "SessionEnd" ||
|
|
640
|
-
event === "PreCompact" ||
|
|
641
|
-
event === "PostCompact") &&
|
|
642
|
-
context.toolName !== undefined
|
|
643
|
-
) {
|
|
644
|
-
logger?.warn(
|
|
645
|
-
`[HookManager] ${event} event has unexpected toolName in context: ${context.toolName}`,
|
|
646
|
-
);
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
return {
|
|
650
|
-
valid: errors.length === 0,
|
|
651
|
-
errors,
|
|
652
|
-
};
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
/**
|
|
656
|
-
* Generate a summary of hook execution results
|
|
657
|
-
*/
|
|
658
|
-
private generateExecutionSummary(
|
|
659
|
-
event: HookEvent,
|
|
660
|
-
results: HookExecutionResult[],
|
|
661
|
-
totalDuration: number,
|
|
662
|
-
): string {
|
|
663
|
-
if (results.length === 0) {
|
|
664
|
-
return `No hooks executed for ${event}`;
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
const successful = results.filter((r) => r.success).length;
|
|
668
|
-
const failed = results.length - successful;
|
|
669
|
-
const timedOut = results.filter((r) => r.timedOut).length;
|
|
670
|
-
const avgDuration =
|
|
671
|
-
results.reduce((sum, r) => sum + r.duration, 0) / results.length;
|
|
672
|
-
|
|
673
|
-
let summary = `${successful}/${results.length} commands successful`;
|
|
674
|
-
|
|
675
|
-
if (failed > 0) {
|
|
676
|
-
summary += `, ${failed} failed`;
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
if (timedOut > 0) {
|
|
680
|
-
summary += `, ${timedOut} timed out`;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
summary += ` (avg: ${Math.round(avgDuration)}ms, total: ${totalDuration}ms)`;
|
|
684
|
-
|
|
685
|
-
return summary;
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
/**
|
|
689
|
-
* Merge hook configurations, with the second taking precedence
|
|
690
|
-
*/
|
|
691
|
-
private mergeHooksConfiguration(
|
|
692
|
-
target: PartialHookConfiguration,
|
|
693
|
-
source: PartialHookConfiguration,
|
|
694
|
-
): void {
|
|
695
|
-
for (const [event, configs] of Object.entries(source)) {
|
|
696
|
-
if (isValidHookEvent(event)) {
|
|
697
|
-
// Concatenate hook configs so multiple sources (programmatic, file-based, plugins) coexist
|
|
698
|
-
if (!target[event]) {
|
|
699
|
-
target[event] = [...configs];
|
|
700
|
-
} else {
|
|
701
|
-
target[event] = [...target[event], ...configs];
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
|
|
707
|
-
/**
|
|
708
|
-
* Check if a hook configuration applies to the current context
|
|
709
|
-
*/
|
|
710
|
-
private configApplies(
|
|
711
|
-
config: HookEventConfig,
|
|
712
|
-
event: HookEvent,
|
|
713
|
-
toolName?: string,
|
|
714
|
-
): boolean {
|
|
715
|
-
// For events that don't use matchers, config always applies
|
|
716
|
-
if (
|
|
717
|
-
event === "UserPromptSubmit" ||
|
|
718
|
-
event === "Stop" ||
|
|
719
|
-
event === "SubagentStop" ||
|
|
720
|
-
event === "WorktreeCreate" ||
|
|
721
|
-
event === "WorktreeRemove" ||
|
|
722
|
-
event === "CwdChanged" ||
|
|
723
|
-
event === "SessionStart" ||
|
|
724
|
-
event === "SessionEnd" ||
|
|
725
|
-
event === "PreCompact" ||
|
|
726
|
-
event === "PostCompact"
|
|
727
|
-
) {
|
|
728
|
-
return true;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
// For tool-based events, check matcher if present
|
|
732
|
-
if (
|
|
733
|
-
event === "PreToolUse" ||
|
|
734
|
-
event === "PostToolUse" ||
|
|
735
|
-
event === "PermissionRequest"
|
|
736
|
-
) {
|
|
737
|
-
if (!config.matcher) {
|
|
738
|
-
// No matcher means applies to all tools
|
|
739
|
-
return true;
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
if (!toolName) {
|
|
743
|
-
// No tool name provided, cannot match
|
|
744
|
-
return false;
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
return this.matcher.matches(config.matcher, toolName);
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
return false;
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
/**
|
|
754
|
-
* Validate a single event configuration
|
|
755
|
-
*/
|
|
756
|
-
private validateEventConfig(
|
|
757
|
-
event: HookEvent,
|
|
758
|
-
config: unknown,
|
|
759
|
-
index: number,
|
|
760
|
-
): string[] {
|
|
761
|
-
const errors: string[] = [];
|
|
762
|
-
const prefix = `Hook event ${event}[${index}]`;
|
|
763
|
-
|
|
764
|
-
if (!isValidHookEventConfig(config)) {
|
|
765
|
-
errors.push(`${prefix}: Invalid hook event configuration structure`);
|
|
766
|
-
return errors;
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
// Validate matcher requirements
|
|
770
|
-
if (
|
|
771
|
-
(event === "PreToolUse" ||
|
|
772
|
-
event === "PostToolUse" ||
|
|
773
|
-
event === "PermissionRequest") &&
|
|
774
|
-
config.matcher
|
|
775
|
-
) {
|
|
776
|
-
if (!this.matcher.isValidPattern(config.matcher)) {
|
|
777
|
-
errors.push(`${prefix}: Invalid matcher pattern: ${config.matcher}`);
|
|
778
|
-
}
|
|
779
|
-
}
|
|
780
|
-
|
|
781
|
-
// Validate that non-tool events don't have matchers
|
|
782
|
-
if (
|
|
783
|
-
(event === "UserPromptSubmit" ||
|
|
784
|
-
event === "Stop" ||
|
|
785
|
-
event === "SubagentStop" ||
|
|
786
|
-
event === "WorktreeCreate" ||
|
|
787
|
-
event === "WorktreeRemove" ||
|
|
788
|
-
event === "SessionStart" ||
|
|
789
|
-
event === "SessionEnd" ||
|
|
790
|
-
event === "PreCompact" ||
|
|
791
|
-
event === "PostCompact") &&
|
|
792
|
-
config.matcher
|
|
793
|
-
) {
|
|
794
|
-
errors.push(`${prefix}: Event ${event} should not have a matcher`);
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
// Validate commands
|
|
798
|
-
config.hooks.forEach((hookCommand, cmdIndex) => {
|
|
799
|
-
if (!isCommandSafe(hookCommand.command)) {
|
|
800
|
-
errors.push(
|
|
801
|
-
`${prefix}.hooks[${cmdIndex}]: Command may be unsafe: ${hookCommand.command}`,
|
|
802
|
-
);
|
|
803
|
-
}
|
|
804
|
-
});
|
|
805
|
-
|
|
806
|
-
return errors;
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
/**
|
|
810
|
-
* Get statistics about current configuration
|
|
811
|
-
*/
|
|
812
|
-
getConfigurationStats(): {
|
|
813
|
-
totalEvents: number;
|
|
814
|
-
totalConfigs: number;
|
|
815
|
-
totalCommands: number;
|
|
816
|
-
eventBreakdown: Record<HookEvent, number>;
|
|
817
|
-
} {
|
|
818
|
-
if (!this.configuration) {
|
|
819
|
-
return {
|
|
820
|
-
totalEvents: 0,
|
|
821
|
-
totalConfigs: 0,
|
|
822
|
-
totalCommands: 0,
|
|
823
|
-
eventBreakdown: {
|
|
824
|
-
PreToolUse: 0,
|
|
825
|
-
PostToolUse: 0,
|
|
826
|
-
UserPromptSubmit: 0,
|
|
827
|
-
Stop: 0,
|
|
828
|
-
SubagentStop: 0,
|
|
829
|
-
PermissionRequest: 0,
|
|
830
|
-
WorktreeCreate: 0,
|
|
831
|
-
WorktreeRemove: 0,
|
|
832
|
-
CwdChanged: 0,
|
|
833
|
-
SessionStart: 0,
|
|
834
|
-
SessionEnd: 0,
|
|
835
|
-
PreCompact: 0,
|
|
836
|
-
PostCompact: 0,
|
|
837
|
-
},
|
|
838
|
-
};
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
const eventBreakdown: Record<HookEvent, number> = {
|
|
842
|
-
PreToolUse: 0,
|
|
843
|
-
PostToolUse: 0,
|
|
844
|
-
UserPromptSubmit: 0,
|
|
845
|
-
Stop: 0,
|
|
846
|
-
SubagentStop: 0,
|
|
847
|
-
PermissionRequest: 0,
|
|
848
|
-
WorktreeCreate: 0,
|
|
849
|
-
WorktreeRemove: 0,
|
|
850
|
-
CwdChanged: 0,
|
|
851
|
-
SessionStart: 0,
|
|
852
|
-
SessionEnd: 0,
|
|
853
|
-
PreCompact: 0,
|
|
854
|
-
PostCompact: 0,
|
|
855
|
-
};
|
|
856
|
-
|
|
857
|
-
let totalConfigs = 0;
|
|
858
|
-
let totalCommands = 0;
|
|
859
|
-
|
|
860
|
-
Object.entries(this.configuration).forEach(([event, configs]) => {
|
|
861
|
-
if (isValidHookEvent(event)) {
|
|
862
|
-
eventBreakdown[event] = configs.length;
|
|
863
|
-
totalConfigs += configs.length;
|
|
864
|
-
totalCommands += configs.reduce(
|
|
865
|
-
(sum, config) => sum + config.hooks.length,
|
|
866
|
-
0,
|
|
867
|
-
);
|
|
868
|
-
}
|
|
869
|
-
});
|
|
870
|
-
|
|
871
|
-
return {
|
|
872
|
-
totalEvents: Object.keys(this.configuration).length,
|
|
873
|
-
totalConfigs,
|
|
874
|
-
totalCommands,
|
|
875
|
-
eventBreakdown,
|
|
876
|
-
};
|
|
877
|
-
}
|
|
878
|
-
|
|
879
|
-
/**
|
|
880
|
-
* Execute CwdChanged hooks.
|
|
881
|
-
*/
|
|
882
|
-
async executeCwdChangedHooks(
|
|
883
|
-
oldCwd: string,
|
|
884
|
-
newCwd: string,
|
|
885
|
-
sessionId: string,
|
|
886
|
-
transcriptPath: string,
|
|
887
|
-
env: Record<string, string>,
|
|
888
|
-
): Promise<HookExecutionResult[]> {
|
|
889
|
-
const context: ExtendedHookExecutionContext = {
|
|
890
|
-
event: "CwdChanged",
|
|
891
|
-
projectDir: this.workdir,
|
|
892
|
-
timestamp: new Date(),
|
|
893
|
-
sessionId,
|
|
894
|
-
transcriptPath,
|
|
895
|
-
cwd: newCwd,
|
|
896
|
-
oldCwd,
|
|
897
|
-
newCwd,
|
|
898
|
-
env,
|
|
899
|
-
};
|
|
900
|
-
const results = await this.executeHooks("CwdChanged", context);
|
|
901
|
-
if (results.length > 0) {
|
|
902
|
-
// For CwdChanged hooks, we don't block, just log errors
|
|
903
|
-
this.processHookResults("CwdChanged", results);
|
|
904
|
-
}
|
|
905
|
-
return results;
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
/**
|
|
909
|
-
* Register hooks provided by a plugin
|
|
910
|
-
*/
|
|
911
|
-
registerPluginHooks(
|
|
912
|
-
pluginRoot: string,
|
|
913
|
-
hooks: PartialHookConfiguration,
|
|
914
|
-
): void {
|
|
915
|
-
// Stamp pluginRoot on each hook command
|
|
916
|
-
const stampedHooks: PartialHookConfiguration = {};
|
|
917
|
-
for (const [event, configs] of Object.entries(hooks)) {
|
|
918
|
-
if (!isValidHookEvent(event)) continue;
|
|
919
|
-
stampedHooks[event] = configs.map((config) => ({
|
|
920
|
-
...config,
|
|
921
|
-
hooks: config.hooks.map((cmd) => ({ ...cmd, pluginRoot })),
|
|
922
|
-
}));
|
|
923
|
-
}
|
|
924
|
-
|
|
925
|
-
this.mergeHooksConfiguration(this.pluginHooks, stampedHooks);
|
|
926
|
-
this.rebuildConfiguration();
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
/**
|
|
930
|
-
* Execute SessionStart hooks during initialization.
|
|
931
|
-
* Collects additionalContext and initialUserMessage from hook stdout.
|
|
932
|
-
*/
|
|
933
|
-
async executeSessionStartHooks(
|
|
934
|
-
source: SessionStartSource,
|
|
935
|
-
sessionId: string,
|
|
936
|
-
transcriptPath: string,
|
|
937
|
-
agentType?: string,
|
|
938
|
-
): Promise<{
|
|
939
|
-
results: HookExecutionResult[];
|
|
940
|
-
additionalContext?: string;
|
|
941
|
-
initialUserMessage?: string;
|
|
942
|
-
}> {
|
|
943
|
-
const context: ExtendedHookExecutionContext = {
|
|
944
|
-
event: "SessionStart",
|
|
945
|
-
projectDir: this.workdir,
|
|
946
|
-
timestamp: new Date(),
|
|
947
|
-
sessionId,
|
|
948
|
-
transcriptPath,
|
|
949
|
-
cwd: this.workdir,
|
|
950
|
-
source,
|
|
951
|
-
agentType,
|
|
952
|
-
env: Object.fromEntries(
|
|
953
|
-
Object.entries(this.sessionEnv).filter((e) => e[1] !== undefined),
|
|
954
|
-
) as Record<string, string>,
|
|
955
|
-
};
|
|
956
|
-
|
|
957
|
-
const results = await this.executeHooks("SessionStart", context);
|
|
958
|
-
|
|
959
|
-
let additionalContext: string | undefined;
|
|
960
|
-
let initialUserMessage: string | undefined;
|
|
961
|
-
|
|
962
|
-
// Process stdout from successful hooks
|
|
963
|
-
for (const result of results) {
|
|
964
|
-
if (result.success && result.stdout?.trim()) {
|
|
965
|
-
const trimmed = result.stdout.trim();
|
|
966
|
-
// Try to parse as JSON for structured output
|
|
967
|
-
try {
|
|
968
|
-
const parsed = JSON.parse(trimmed);
|
|
969
|
-
if (parsed.hookSpecificOutput?.additionalContext) {
|
|
970
|
-
additionalContext =
|
|
971
|
-
(additionalContext ? additionalContext + "\n" : "") +
|
|
972
|
-
parsed.hookSpecificOutput.additionalContext;
|
|
973
|
-
}
|
|
974
|
-
if (parsed.initialUserMessage) {
|
|
975
|
-
initialUserMessage = parsed.initialUserMessage;
|
|
976
|
-
}
|
|
977
|
-
} catch {
|
|
978
|
-
// Not JSON, treat as additional context
|
|
979
|
-
additionalContext =
|
|
980
|
-
(additionalContext ? additionalContext + "\n" : "") + trimmed;
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
|
|
985
|
-
return { results, additionalContext, initialUserMessage };
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
/**
|
|
989
|
-
* Execute SessionEnd hooks during agent destruction.
|
|
990
|
-
* Non-blocking: always continues shutdown even if hooks fail.
|
|
991
|
-
* No stdout processing needed (SessionEnd hooks are fire-and-forget cleanup).
|
|
992
|
-
*/
|
|
993
|
-
async executeSessionEndHooks(
|
|
994
|
-
source: SessionEndSource,
|
|
995
|
-
sessionId: string,
|
|
996
|
-
transcriptPath: string,
|
|
997
|
-
): Promise<HookExecutionResult[]> {
|
|
998
|
-
const context: ExtendedHookExecutionContext = {
|
|
999
|
-
event: "SessionEnd",
|
|
1000
|
-
projectDir: this.workdir,
|
|
1001
|
-
timestamp: new Date(),
|
|
1002
|
-
sessionId,
|
|
1003
|
-
transcriptPath,
|
|
1004
|
-
cwd: this.workdir,
|
|
1005
|
-
endSource: source,
|
|
1006
|
-
env: Object.fromEntries(
|
|
1007
|
-
Object.entries(this.sessionEnv).filter((e) => e[1] !== undefined),
|
|
1008
|
-
) as Record<string, string>,
|
|
1009
|
-
};
|
|
1010
|
-
|
|
1011
|
-
const results = await this.executeHooks("SessionEnd", context);
|
|
1012
|
-
|
|
1013
|
-
// Process results but never block shutdown
|
|
1014
|
-
if (results.length > 0) {
|
|
1015
|
-
this.processHookResults("SessionEnd", results);
|
|
1016
|
-
}
|
|
1017
|
-
|
|
1018
|
-
return results;
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
/**
|
|
1022
|
-
* Execute PreCompact hooks before compaction.
|
|
1023
|
-
* Returns custom instructions from hook stdout.
|
|
1024
|
-
*/
|
|
1025
|
-
async executePreCompactHooks(
|
|
1026
|
-
sessionId: string,
|
|
1027
|
-
transcriptPath: string,
|
|
1028
|
-
customInstructions?: string,
|
|
1029
|
-
): Promise<{
|
|
1030
|
-
results: HookExecutionResult[];
|
|
1031
|
-
additionalInstructions?: string;
|
|
1032
|
-
}> {
|
|
1033
|
-
const context: ExtendedHookExecutionContext = {
|
|
1034
|
-
event: "PreCompact",
|
|
1035
|
-
projectDir: this.workdir,
|
|
1036
|
-
timestamp: new Date(),
|
|
1037
|
-
sessionId,
|
|
1038
|
-
transcriptPath,
|
|
1039
|
-
cwd: this.workdir,
|
|
1040
|
-
compactInstructions: customInstructions,
|
|
1041
|
-
env: Object.fromEntries(
|
|
1042
|
-
Object.entries(this.sessionEnv).filter((e) => e[1] !== undefined),
|
|
1043
|
-
) as Record<string, string>,
|
|
1044
|
-
};
|
|
1045
|
-
|
|
1046
|
-
const results = await this.executeHooks("PreCompact", context);
|
|
1047
|
-
|
|
1048
|
-
let additionalInstructions: string | undefined;
|
|
1049
|
-
for (const result of results) {
|
|
1050
|
-
if (result.success && result.stdout?.trim()) {
|
|
1051
|
-
const trimmed = result.stdout.trim();
|
|
1052
|
-
additionalInstructions = additionalInstructions
|
|
1053
|
-
? additionalInstructions + "\n" + trimmed
|
|
1054
|
-
: trimmed;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
|
|
1058
|
-
return { results, additionalInstructions };
|
|
1059
|
-
}
|
|
1060
|
-
|
|
1061
|
-
/**
|
|
1062
|
-
* Execute PostCompact hooks after compaction.
|
|
1063
|
-
* Receives the compact summary text.
|
|
1064
|
-
*/
|
|
1065
|
-
async executePostCompactHooks(
|
|
1066
|
-
sessionId: string,
|
|
1067
|
-
transcriptPath: string,
|
|
1068
|
-
compactSummary: string,
|
|
1069
|
-
): Promise<HookExecutionResult[]> {
|
|
1070
|
-
const context: ExtendedHookExecutionContext = {
|
|
1071
|
-
event: "PostCompact",
|
|
1072
|
-
projectDir: this.workdir,
|
|
1073
|
-
timestamp: new Date(),
|
|
1074
|
-
sessionId,
|
|
1075
|
-
transcriptPath,
|
|
1076
|
-
cwd: this.workdir,
|
|
1077
|
-
compactSummary,
|
|
1078
|
-
env: Object.fromEntries(
|
|
1079
|
-
Object.entries(this.sessionEnv).filter((e) => e[1] !== undefined),
|
|
1080
|
-
) as Record<string, string>,
|
|
1081
|
-
};
|
|
1082
|
-
|
|
1083
|
-
const results = await this.executeHooks("PostCompact", context);
|
|
1084
|
-
if (results.length > 0) {
|
|
1085
|
-
this.processHookResults("PostCompact", results);
|
|
1086
|
-
}
|
|
1087
|
-
return results;
|
|
1088
|
-
}
|
|
1089
|
-
}
|