File size: 10,395 Bytes
7a1ad33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { FunctionCallingConfigMode } from '@google/genai';
import {
DefaultHookOutput,
BeforeToolHookOutput,
BeforeModelHookOutput,
BeforeToolSelectionHookOutput,
AfterModelHookOutput,
AfterAgentHookOutput,
HookEventName,
type HookOutput,
type HookExecutionResult,
type BeforeToolSelectionOutput,
} from './types.js';
/**
* Aggregated hook result
*/
export interface AggregatedHookResult {
success: boolean;
finalOutput?: DefaultHookOutput;
allOutputs: HookOutput[];
errors: Error[];
totalDuration: number;
}
/**
* Hook aggregator that merges results from multiple hooks using event-specific strategies
*/
export class HookAggregator {
/**
* Aggregate results from multiple hook executions
*/
aggregateResults(
results: HookExecutionResult[],
eventName: HookEventName,
): AggregatedHookResult {
const allOutputs: HookOutput[] = [];
const errors: Error[] = [];
let totalDuration = 0;
// Collect all outputs and errors
for (const result of results) {
totalDuration += result.duration;
if (result.error) {
errors.push(result.error);
}
if (result.output) {
allOutputs.push(result.output);
}
}
// Merge outputs using event-specific strategy
const mergedOutput = this.mergeOutputs(allOutputs, eventName);
const finalOutput = mergedOutput
? this.createSpecificHookOutput(mergedOutput, eventName)
: undefined;
return {
success: errors.length === 0,
finalOutput,
allOutputs,
errors,
totalDuration,
};
}
/**
* Merge hook outputs using event-specific strategies
*
* Note: We always use the merge logic even for single hooks to ensure
* consistent default behaviors (e.g., default decision='allow' for OR logic)
*/
private mergeOutputs(
outputs: HookOutput[],
eventName: HookEventName,
): HookOutput | undefined {
if (outputs.length === 0) {
return undefined;
}
switch (eventName) {
case HookEventName.BeforeTool:
case HookEventName.AfterTool:
case HookEventName.BeforeAgent:
case HookEventName.AfterAgent:
case HookEventName.SessionStart:
return this.mergeWithOrDecision(outputs);
case HookEventName.BeforeModel:
case HookEventName.AfterModel:
return this.mergeWithFieldReplacement(outputs);
case HookEventName.BeforeToolSelection:
return this.mergeToolSelectionOutputs(
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
outputs as BeforeToolSelectionOutput[],
);
default:
// For other events, use simple merge
return this.mergeSimple(outputs);
}
}
/**
* Merge outputs with OR decision logic and message concatenation
*/
private mergeWithOrDecision(outputs: HookOutput[]): HookOutput {
const merged: HookOutput = {
continue: true,
suppressOutput: false,
};
const messages: string[] = [];
const reasons: string[] = [];
const systemMessages: string[] = [];
const additionalContexts: string[] = [];
let hasBlockDecision = false;
let hasAskDecision = false;
let hasContinueFalse = false;
for (const output of outputs) {
// Handle continue flag
if (output.continue === false) {
hasContinueFalse = true;
merged.continue = false;
if (output.stopReason) {
messages.push(output.stopReason);
}
}
// Handle decision (OR logic for blocking)
const tempOutput = new DefaultHookOutput(output);
if (tempOutput.isBlockingDecision()) {
hasBlockDecision = true;
merged.decision = output.decision;
} else if (tempOutput.isAskDecision()) {
hasAskDecision = true;
// Ask decision is only set if no blocking decision was found so far
if (!hasBlockDecision) {
merged.decision = output.decision;
}
}
// Collect messages
if (output.reason) {
reasons.push(output.reason);
}
if (output.systemMessage) {
systemMessages.push(output.systemMessage);
}
// Handle suppress output (any true wins)
if (output.suppressOutput) {
merged.suppressOutput = true;
}
// Handle clearContext (any true wins) - for AfterAgent hooks
if (output.hookSpecificOutput?.['clearContext'] === true) {
merged.hookSpecificOutput = {
...(merged.hookSpecificOutput || {}),
clearContext: true,
};
}
// Merge hookSpecificOutput (excluding clearContext which is handled above)
if (output.hookSpecificOutput) {
const { clearContext: _clearContext, ...restSpecificOutput } =
output.hookSpecificOutput;
merged.hookSpecificOutput = {
...(merged.hookSpecificOutput || {}),
...restSpecificOutput,
};
}
// Collect additional context from hook-specific outputs
this.extractAdditionalContext(output, additionalContexts);
}
// Set final decision if no blocking or ask decision was found
if (!hasBlockDecision && !hasAskDecision && !hasContinueFalse) {
merged.decision = 'allow';
}
// Merge messages
if (messages.length > 0) {
merged.stopReason = messages.join('\n');
}
if (reasons.length > 0) {
merged.reason = reasons.join('\n');
}
if (systemMessages.length > 0) {
merged.systemMessage = systemMessages.join('\n');
}
// Add merged additional context
if (additionalContexts.length > 0) {
merged.hookSpecificOutput = {
...(merged.hookSpecificOutput || {}),
additionalContext: additionalContexts.join('\n'),
};
}
return merged;
}
/**
* Merge outputs with later fields replacing earlier fields
*/
private mergeWithFieldReplacement(outputs: HookOutput[]): HookOutput {
let merged: HookOutput = {};
for (const output of outputs) {
// Later outputs override earlier ones
merged = {
...merged,
...output,
hookSpecificOutput: {
...merged.hookSpecificOutput,
...output.hookSpecificOutput,
},
};
}
return merged;
}
/**
* Merge tool selection outputs with specific logic for tool config
*
* Tool Selection Strategy:
* - The intent is to provide a UNION of tools from all hooks
* - If any hook specifies NONE mode, no tools are available (most restrictive wins)
* - If any hook specifies ANY mode (and no NONE), ANY mode is used
* - Otherwise AUTO mode is used
* - Function names are collected from all hooks and sorted for deterministic caching
*
* This means hooks can only add/enable tools, not filter them out individually.
* If one hook restricts and another re-enables, the union takes the re-enabled tool.
*/
private mergeToolSelectionOutputs(
outputs: BeforeToolSelectionOutput[],
): BeforeToolSelectionOutput {
const merged: BeforeToolSelectionOutput = {};
const allFunctionNames = new Set<string>();
let hasNoneMode = false;
let hasAnyMode = false;
for (const output of outputs) {
const toolConfig = output.hookSpecificOutput?.toolConfig;
if (!toolConfig) {
continue;
}
// Check mode (using simplified HookToolConfig format)
if (toolConfig.mode === 'NONE') {
hasNoneMode = true;
} else if (toolConfig.mode === 'ANY') {
hasAnyMode = true;
}
// Collect function names (union of all hooks)
if (toolConfig.allowedFunctionNames) {
for (const name of toolConfig.allowedFunctionNames) {
allFunctionNames.add(name);
}
}
}
// Determine final mode and function names
let finalMode: FunctionCallingConfigMode;
let finalFunctionNames: string[] = [];
if (hasNoneMode) {
// NONE mode wins - most restrictive
finalMode = FunctionCallingConfigMode.NONE;
finalFunctionNames = [];
} else if (hasAnyMode) {
// ANY mode if present (and no NONE)
finalMode = FunctionCallingConfigMode.ANY;
// Sort for deterministic output to ensure consistent caching
finalFunctionNames = Array.from(allFunctionNames).sort();
} else {
// Default to AUTO mode
finalMode = FunctionCallingConfigMode.AUTO;
// Sort for deterministic output to ensure consistent caching
finalFunctionNames = Array.from(allFunctionNames).sort();
}
merged.hookSpecificOutput = {
hookEventName: 'BeforeToolSelection',
toolConfig: {
mode: finalMode,
allowedFunctionNames: finalFunctionNames,
},
};
return merged;
}
/**
* Simple merge for events without special logic
*/
private mergeSimple(outputs: HookOutput[]): HookOutput {
let merged: HookOutput = {};
for (const output of outputs) {
merged = { ...merged, ...output };
}
return merged;
}
/**
* Create the appropriate specific hook output class based on event type
*/
private createSpecificHookOutput(
output: HookOutput,
eventName: HookEventName,
): DefaultHookOutput {
switch (eventName) {
case HookEventName.BeforeTool:
return new BeforeToolHookOutput(output);
case HookEventName.BeforeModel:
return new BeforeModelHookOutput(output);
case HookEventName.BeforeToolSelection:
return new BeforeToolSelectionHookOutput(output);
case HookEventName.AfterModel:
return new AfterModelHookOutput(output);
case HookEventName.AfterAgent:
return new AfterAgentHookOutput(output);
default:
return new DefaultHookOutput(output);
}
}
/**
* Extract additional context from hook-specific outputs
*/
private extractAdditionalContext(
output: HookOutput,
contexts: string[],
): void {
const specific = output.hookSpecificOutput;
if (!specific) {
return;
}
// Extract additionalContext from various hook types
if (
'additionalContext' in specific &&
// eslint-disable-next-line no-restricted-syntax
typeof specific['additionalContext'] === 'string'
) {
contexts.push(specific['additionalContext']);
}
}
}
|