@everworker/oneringai 0.1.0

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.
@@ -0,0 +1,405 @@
1
+ // src/capabilities/agents/ExecutionContext.ts
2
+ var ExecutionContext = class {
3
+ // Execution metadata
4
+ executionId;
5
+ startTime;
6
+ iteration = 0;
7
+ // Tool tracking
8
+ toolCalls = /* @__PURE__ */ new Map();
9
+ toolResults = /* @__PURE__ */ new Map();
10
+ // Control state
11
+ paused = false;
12
+ pauseReason;
13
+ cancelled = false;
14
+ cancelReason;
15
+ // User data (for hooks to share state)
16
+ metadata = /* @__PURE__ */ new Map();
17
+ // History storage (memory-safe)
18
+ config;
19
+ iterations = [];
20
+ iterationSummaries = [];
21
+ // Metrics
22
+ metrics = {
23
+ totalDuration: 0,
24
+ llmDuration: 0,
25
+ toolDuration: 0,
26
+ hookDuration: 0,
27
+ iterationCount: 0,
28
+ toolCallCount: 0,
29
+ toolSuccessCount: 0,
30
+ toolFailureCount: 0,
31
+ toolTimeoutCount: 0,
32
+ inputTokens: 0,
33
+ outputTokens: 0,
34
+ totalTokens: 0,
35
+ errors: []
36
+ };
37
+ // Audit trail
38
+ auditTrail = [];
39
+ constructor(executionId, config = {}) {
40
+ this.executionId = executionId;
41
+ this.startTime = /* @__PURE__ */ new Date();
42
+ this.config = {
43
+ maxHistorySize: config.maxHistorySize || 10,
44
+ historyMode: config.historyMode || "summary",
45
+ maxAuditTrailSize: config.maxAuditTrailSize || 1e3
46
+ };
47
+ }
48
+ /**
49
+ * Add iteration to history (memory-safe)
50
+ */
51
+ addIteration(record) {
52
+ switch (this.config.historyMode) {
53
+ case "none":
54
+ break;
55
+ case "summary":
56
+ this.iterationSummaries.push({
57
+ iteration: record.iteration,
58
+ tokens: record.response.usage.total_tokens,
59
+ toolCount: record.toolCalls.length,
60
+ duration: record.endTime.getTime() - record.startTime.getTime(),
61
+ timestamp: record.startTime
62
+ });
63
+ if (this.iterationSummaries.length > this.config.maxHistorySize) {
64
+ this.iterationSummaries.shift();
65
+ }
66
+ break;
67
+ case "full":
68
+ this.iterations.push(record);
69
+ if (this.iterations.length > this.config.maxHistorySize) {
70
+ this.iterations.shift();
71
+ }
72
+ break;
73
+ }
74
+ }
75
+ /**
76
+ * Get iteration history
77
+ */
78
+ getHistory() {
79
+ return this.config.historyMode === "full" ? this.iterations : this.iterationSummaries;
80
+ }
81
+ /**
82
+ * Add audit entry
83
+ */
84
+ audit(type, details, hookName, toolName) {
85
+ this.auditTrail.push({
86
+ timestamp: /* @__PURE__ */ new Date(),
87
+ type,
88
+ hookName,
89
+ toolName,
90
+ details
91
+ });
92
+ if (this.auditTrail.length > this.config.maxAuditTrailSize) {
93
+ this.auditTrail.shift();
94
+ }
95
+ }
96
+ /**
97
+ * Get audit trail
98
+ */
99
+ getAuditTrail() {
100
+ return this.auditTrail;
101
+ }
102
+ /**
103
+ * Update metrics
104
+ */
105
+ updateMetrics(update) {
106
+ Object.assign(this.metrics, update);
107
+ }
108
+ /**
109
+ * Add tool call to tracking
110
+ */
111
+ addToolCall(toolCall) {
112
+ this.toolCalls.set(toolCall.id, toolCall);
113
+ this.metrics.toolCallCount++;
114
+ }
115
+ /**
116
+ * Add tool result to tracking
117
+ */
118
+ addToolResult(result) {
119
+ this.toolResults.set(result.tool_use_id, result);
120
+ if (result.state === "completed" /* COMPLETED */) {
121
+ this.metrics.toolSuccessCount++;
122
+ } else if (result.state === "failed" /* FAILED */) {
123
+ this.metrics.toolFailureCount++;
124
+ } else if (result.state === "timeout" /* TIMEOUT */) {
125
+ this.metrics.toolTimeoutCount++;
126
+ }
127
+ }
128
+ /**
129
+ * Check resource limits
130
+ */
131
+ checkLimits(limits) {
132
+ if (!limits) return;
133
+ if (limits.maxExecutionTime) {
134
+ const elapsed = Date.now() - this.startTime.getTime();
135
+ if (elapsed > limits.maxExecutionTime) {
136
+ throw new Error(
137
+ `Execution time limit exceeded: ${elapsed}ms > ${limits.maxExecutionTime}ms`
138
+ );
139
+ }
140
+ }
141
+ if (limits.maxToolCalls && this.toolCalls.size > limits.maxToolCalls) {
142
+ throw new Error(
143
+ `Tool call limit exceeded: ${this.toolCalls.size} > ${limits.maxToolCalls}`
144
+ );
145
+ }
146
+ if (limits.maxContextSize) {
147
+ const size = this.estimateSize();
148
+ if (size > limits.maxContextSize) {
149
+ throw new Error(
150
+ `Context size limit exceeded: ${size} bytes > ${limits.maxContextSize} bytes`
151
+ );
152
+ }
153
+ }
154
+ }
155
+ /**
156
+ * Estimate memory usage (rough approximation)
157
+ */
158
+ estimateSize() {
159
+ try {
160
+ const data = {
161
+ toolCalls: Array.from(this.toolCalls.values()),
162
+ toolResults: Array.from(this.toolResults.values()),
163
+ iterations: this.config.historyMode === "full" ? this.iterations : this.iterationSummaries,
164
+ auditTrail: this.auditTrail
165
+ };
166
+ return JSON.stringify(data).length;
167
+ } catch {
168
+ return 0;
169
+ }
170
+ }
171
+ /**
172
+ * Cleanup resources and release memory
173
+ * Clears all internal arrays and maps to allow garbage collection
174
+ */
175
+ cleanup() {
176
+ const summary = {
177
+ executionId: this.executionId,
178
+ totalIterations: this.iteration,
179
+ totalToolCalls: this.metrics.toolCallCount,
180
+ totalDuration: Date.now() - this.startTime.getTime(),
181
+ success: !this.cancelled && this.metrics.errors.length === 0
182
+ };
183
+ this.toolCalls.clear();
184
+ this.toolResults.clear();
185
+ this.metadata.clear();
186
+ this.iterations.length = 0;
187
+ this.iterationSummaries.length = 0;
188
+ this.auditTrail.length = 0;
189
+ this.metrics.errors.length = 0;
190
+ this.metadata.set("execution_summary", summary);
191
+ }
192
+ /**
193
+ * Get execution summary
194
+ */
195
+ getSummary() {
196
+ return {
197
+ executionId: this.executionId,
198
+ startTime: this.startTime,
199
+ currentIteration: this.iteration,
200
+ paused: this.paused,
201
+ cancelled: this.cancelled,
202
+ metrics: { ...this.metrics },
203
+ totalDuration: Date.now() - this.startTime.getTime()
204
+ };
205
+ }
206
+ };
207
+
208
+ // src/capabilities/agents/HookManager.ts
209
+ var HookManager = class {
210
+ hooks = /* @__PURE__ */ new Map();
211
+ timeout;
212
+ parallel;
213
+ // Per-hook error tracking: hookKey -> consecutive error count
214
+ hookErrorCounts = /* @__PURE__ */ new Map();
215
+ // Disabled hooks that exceeded error threshold
216
+ disabledHooks = /* @__PURE__ */ new Set();
217
+ maxConsecutiveErrors = 3;
218
+ emitter;
219
+ constructor(config = {}, emitter, errorHandling) {
220
+ this.timeout = config.hookTimeout || 5e3;
221
+ this.parallel = config.parallelHooks || false;
222
+ this.emitter = emitter;
223
+ this.maxConsecutiveErrors = errorHandling?.maxConsecutiveErrors || 3;
224
+ this.registerFromConfig(config);
225
+ }
226
+ /**
227
+ * Register hooks from configuration
228
+ */
229
+ registerFromConfig(config) {
230
+ const hookNames = [
231
+ "before:execution",
232
+ "after:execution",
233
+ "before:llm",
234
+ "after:llm",
235
+ "before:tool",
236
+ "after:tool",
237
+ "approve:tool",
238
+ "pause:check"
239
+ ];
240
+ for (const name of hookNames) {
241
+ const hook = config[name];
242
+ if (hook) {
243
+ this.register(name, hook);
244
+ }
245
+ }
246
+ }
247
+ /**
248
+ * Register a hook
249
+ */
250
+ register(name, hook) {
251
+ if (typeof hook !== "function") {
252
+ throw new Error(`Hook must be a function, got: ${typeof hook}`);
253
+ }
254
+ if (!this.hooks.has(name)) {
255
+ this.hooks.set(name, []);
256
+ }
257
+ const existing = this.hooks.get(name);
258
+ if (existing.length >= 10) {
259
+ throw new Error(`Too many hooks for ${name} (max: 10)`);
260
+ }
261
+ existing.push(hook);
262
+ }
263
+ /**
264
+ * Execute hooks for a given name
265
+ */
266
+ async executeHooks(name, context, defaultResult) {
267
+ const hooks = this.hooks.get(name);
268
+ if (!hooks || hooks.length === 0) {
269
+ return defaultResult;
270
+ }
271
+ if (this.parallel && hooks.length > 1) {
272
+ return this.executeHooksParallel(hooks, context, defaultResult);
273
+ }
274
+ return this.executeHooksSequential(hooks, context, defaultResult);
275
+ }
276
+ /**
277
+ * Execute hooks sequentially
278
+ */
279
+ async executeHooksSequential(hooks, context, defaultResult) {
280
+ let result = defaultResult;
281
+ for (let i = 0; i < hooks.length; i++) {
282
+ const hook = hooks[i];
283
+ const hookKey = this.getHookKey(hook, i);
284
+ const hookResult = await this.executeHookSafely(hook, context, hookKey);
285
+ if (hookResult === null) {
286
+ continue;
287
+ }
288
+ result = { ...result, ...hookResult };
289
+ if (hookResult.skip === true) {
290
+ break;
291
+ }
292
+ }
293
+ return result;
294
+ }
295
+ /**
296
+ * Execute hooks in parallel
297
+ */
298
+ async executeHooksParallel(hooks, context, defaultResult) {
299
+ const results = await Promise.all(
300
+ hooks.map((hook, i) => {
301
+ const hookKey = this.getHookKey(hook, i);
302
+ return this.executeHookSafely(hook, context, hookKey);
303
+ })
304
+ );
305
+ const validResults = results.filter((r) => r !== null);
306
+ return validResults.reduce(
307
+ (acc, hookResult) => ({ ...acc, ...hookResult }),
308
+ defaultResult
309
+ );
310
+ }
311
+ /**
312
+ * Generate unique key for a hook
313
+ */
314
+ getHookKey(hook, index) {
315
+ return `${hook.name || "anonymous"}_${index}`;
316
+ }
317
+ /**
318
+ * Execute single hook with error isolation and timeout (with per-hook error tracking)
319
+ */
320
+ async executeHookSafely(hook, context, hookKey) {
321
+ const key = hookKey || hook.name || "anonymous";
322
+ if (this.disabledHooks.has(key)) {
323
+ return null;
324
+ }
325
+ const startTime = Date.now();
326
+ try {
327
+ const result = await Promise.race([
328
+ hook(context),
329
+ new Promise(
330
+ (_, reject) => setTimeout(() => reject(new Error("Hook timeout")), this.timeout)
331
+ )
332
+ ]);
333
+ this.hookErrorCounts.delete(key);
334
+ const duration = Date.now() - startTime;
335
+ if (context.context?.updateMetrics) {
336
+ context.context.updateMetrics({
337
+ hookDuration: (context.context.metrics.hookDuration || 0) + duration
338
+ });
339
+ }
340
+ return result;
341
+ } catch (error) {
342
+ const errorCount = (this.hookErrorCounts.get(key) || 0) + 1;
343
+ this.hookErrorCounts.set(key, errorCount);
344
+ this.emitter.emit("hook:error", {
345
+ executionId: context.executionId,
346
+ hookName: hook.name || "anonymous",
347
+ error,
348
+ consecutiveErrors: errorCount,
349
+ timestamp: /* @__PURE__ */ new Date()
350
+ });
351
+ if (errorCount >= this.maxConsecutiveErrors) {
352
+ this.disabledHooks.add(key);
353
+ console.warn(
354
+ `Hook "${key}" disabled after ${errorCount} consecutive failures. Last error: ${error.message}`
355
+ );
356
+ } else {
357
+ console.warn(
358
+ `Hook execution failed (${key}): ${error.message} (${errorCount}/${this.maxConsecutiveErrors} errors)`
359
+ );
360
+ }
361
+ return null;
362
+ }
363
+ }
364
+ /**
365
+ * Check if there are any hooks registered
366
+ */
367
+ hasHooks(name) {
368
+ const hooks = this.hooks.get(name);
369
+ return !!hooks && hooks.length > 0;
370
+ }
371
+ /**
372
+ * Get hook count
373
+ */
374
+ getHookCount(name) {
375
+ if (name) {
376
+ return this.hooks.get(name)?.length || 0;
377
+ }
378
+ return Array.from(this.hooks.values()).reduce((sum, arr) => sum + arr.length, 0);
379
+ }
380
+ /**
381
+ * Clear all hooks and reset error tracking
382
+ */
383
+ clear() {
384
+ this.hooks.clear();
385
+ this.hookErrorCounts.clear();
386
+ this.disabledHooks.clear();
387
+ }
388
+ /**
389
+ * Re-enable a disabled hook
390
+ */
391
+ enableHook(hookKey) {
392
+ this.disabledHooks.delete(hookKey);
393
+ this.hookErrorCounts.delete(hookKey);
394
+ }
395
+ /**
396
+ * Get list of disabled hooks
397
+ */
398
+ getDisabledHooks() {
399
+ return Array.from(this.disabledHooks);
400
+ }
401
+ };
402
+
403
+ export { ExecutionContext, HookManager };
404
+ //# sourceMappingURL=index.js.map
405
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/capabilities/agents/ExecutionContext.ts","../../../src/capabilities/agents/HookManager.ts"],"names":[],"mappings":";AA2EO,IAAM,mBAAN,MAAuB;AAAA;AAAA,EAEnB,WAAA;AAAA,EACA,SAAA;AAAA,EACT,SAAA,GAAoB,CAAA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AC,CAAA;AAAA,EACjF;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,MAAM,KAAA,EAAM;AACjB,IAAA,IAAA,CAAK,gBAAgB,KAAA,EAAM;AAC3B,IAAA,IAAA,CAAK,cAAc,KAAA,EAAM;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,WAAW,OAAA,EAAuB;AAChC,IAAA,IAAA,CAAK,aAAA,CAAc,OAAO,OAAO,CAAA;AACjC,IAAA,IAAA,CAAK,eAAA,CAAgB,OAAO,OAAO,CAAA;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAA,GAA6B;AAC3B,IAAA,OAAO,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,aAAa,CAAA;AAAA,EACtC;AACF","file":"index.js","sourcesContent":["/**\n * Execution context - tracks state, metrics, and history for agent execution\n * Includes memory safety (circular buffers) and resource limits\n */\n\nimport { AgentResponse } from '../../domain/entities/Response.js';\nimport { TextGenerateOptions } from '../../domain/interfaces/ITextProvider.js';\nimport { ToolCall, ToolResult, ToolCallState } from '../../domain/entities/Tool.js';\n\nexport type HistoryMode = 'none' | 'summary' | 'full';\n\nexport interface ExecutionContextConfig {\n maxHistorySize?: number; // Max iterations to store (default: 10)\n historyMode?: HistoryMode; // What to store (default: 'summary')\n maxAuditTrailSize?: number; // Max audit entries (default: 1000)\n}\n\nexport interface IterationRecord {\n iteration: number;\n request: TextGenerateOptions;\n response: AgentResponse;\n toolCalls: ToolCall[];\n toolResults: ToolResult[];\n startTime: Date;\n endTime: Date;\n}\n\nexport interface IterationSummary {\n iteration: number;\n tokens: number;\n toolCount: number;\n duration: number;\n timestamp: Date;\n}\n\nexport interface ExecutionMetrics {\n // Timing\n totalDuration: number;\n llmDuration: number;\n toolDuration: number;\n hookDuration: number;\n\n // Counts\n iterationCount: number;\n toolCallCount: number;\n toolSuccessCount: number;\n toolFailureCount: number;\n toolTimeoutCount: number;\n\n // Tokens\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n\n // Errors\n errors: Array<{ type: string; message: string; timestamp: Date }>;\n}\n\nexport interface AuditEntry {\n timestamp: Date;\n type:\n | 'hook_executed'\n | 'tool_modified'\n | 'tool_skipped'\n | 'execution_paused'\n | 'execution_resumed'\n | 'tool_approved'\n | 'tool_rejected'\n | 'tool_blocked'\n | 'tool_permission_approved';\n hookName?: string;\n toolName?: string;\n details: any;\n}\n\nexport class ExecutionContext {\n // Execution metadata\n readonly executionId: string;\n readonly startTime: Date;\n iteration: number = 0;\n\n // Tool tracking\n readonly toolCalls: Map<string, ToolCall> = new Map();\n readonly toolResults: Map<string, ToolResult> = new Map();\n\n // Control state\n paused: boolean = false;\n pauseReason?: string;\n cancelled: boolean = false;\n cancelReason?: string;\n\n // User data (for hooks to share state)\n readonly metadata: Map<string, any> = new Map();\n\n // History storage (memory-safe)\n private readonly config: ExecutionContextConfig;\n private readonly iterations: IterationRecord[] = [];\n private readonly iterationSummaries: IterationSummary[] = [];\n\n // Metrics\n readonly metrics: ExecutionMetrics = {\n totalDuration: 0,\n llmDuration: 0,\n toolDuration: 0,\n hookDuration: 0,\n iterationCount: 0,\n toolCallCount: 0,\n toolSuccessCount: 0,\n toolFailureCount: 0,\n toolTimeoutCount: 0,\n inputTokens: 0,\n outputTokens: 0,\n totalTokens: 0,\n errors: [],\n };\n\n // Audit trail\n private readonly auditTrail: AuditEntry[] = [];\n\n constructor(\n executionId: string,\n config: ExecutionContextConfig = {}\n ) {\n this.executionId = executionId;\n this.startTime = new Date();\n this.config = {\n maxHistorySize: config.maxHistorySize || 10,\n historyMode: config.historyMode || 'summary',\n maxAuditTrailSize: config.maxAuditTrailSize || 1000,\n };\n }\n\n /**\n * Add iteration to history (memory-safe)\n */\n addIteration(record: IterationRecord): void {\n switch (this.config.historyMode) {\n case 'none':\n // Don't store anything\n break;\n\n case 'summary':\n // Store lightweight summary only\n this.iterationSummaries.push({\n iteration: record.iteration,\n tokens: record.response.usage.total_tokens,\n toolCount: record.toolCalls.length,\n duration: record.endTime.getTime() - record.startTime.getTime(),\n timestamp: record.startTime,\n });\n\n // Keep circular buffer\n if (this.iterationSummaries.length > this.config.maxHistorySize!) {\n this.iterationSummaries.shift();\n }\n break;\n\n case 'full':\n // Store full iteration data\n this.iterations.push(record);\n\n // Keep circular buffer\n if (this.iterations.length > this.config.maxHistorySize!) {\n this.iterations.shift();\n }\n break;\n }\n }\n\n /**\n * Get iteration history\n */\n getHistory(): IterationRecord[] | IterationSummary[] {\n return this.config.historyMode === 'full' ? this.iterations : this.iterationSummaries;\n }\n\n /**\n * Add audit entry\n */\n audit(type: AuditEntry['type'], details: any, hookName?: string, toolName?: string): void {\n this.auditTrail.push({\n timestamp: new Date(),\n type,\n hookName,\n toolName,\n details,\n });\n\n // Keep circular buffer\n if (this.auditTrail.length > this.config.maxAuditTrailSize!) {\n this.auditTrail.shift();\n }\n }\n\n /**\n * Get audit trail\n */\n getAuditTrail(): readonly AuditEntry[] {\n return this.auditTrail;\n }\n\n /**\n * Update metrics\n */\n updateMetrics(update: Partial<ExecutionMetrics>): void {\n Object.assign(this.metrics, update);\n }\n\n /**\n * Add tool call to tracking\n */\n addToolCall(toolCall: ToolCall): void {\n this.toolCalls.set(toolCall.id, toolCall);\n this.metrics.toolCallCount++;\n }\n\n /**\n * Add tool result to tracking\n */\n addToolResult(result: ToolResult): void {\n this.toolResults.set(result.tool_use_id, result);\n\n // Update metrics\n if (result.state === ToolCallState.COMPLETED) {\n this.metrics.toolSuccessCount++;\n } else if (result.state === ToolCallState.FAILED) {\n this.metrics.toolFailureCount++;\n } else if (result.state === ToolCallState.TIMEOUT) {\n this.metrics.toolTimeoutCount++;\n }\n }\n\n /**\n * Check resource limits\n */\n checkLimits(limits?: {\n maxExecutionTime?: number;\n maxToolCalls?: number;\n maxContextSize?: number;\n }): void {\n if (!limits) return;\n\n // Check execution time\n if (limits.maxExecutionTime) {\n const elapsed = Date.now() - this.startTime.getTime();\n if (elapsed > limits.maxExecutionTime) {\n throw new Error(\n `Execution time limit exceeded: ${elapsed}ms > ${limits.maxExecutionTime}ms`\n );\n }\n }\n\n // Check tool call count\n if (limits.maxToolCalls && this.toolCalls.size > limits.maxToolCalls) {\n throw new Error(\n `Tool call limit exceeded: ${this.toolCalls.size} > ${limits.maxToolCalls}`\n );\n }\n\n // Check context size\n if (limits.maxContextSize) {\n const size = this.estimateSize();\n if (size > limits.maxContextSize) {\n throw new Error(\n `Context size limit exceeded: ${size} bytes > ${limits.maxContextSize} bytes`\n );\n }\n }\n }\n\n /**\n * Estimate memory usage (rough approximation)\n */\n private estimateSize(): number {\n try {\n const data = {\n toolCalls: Array.from(this.toolCalls.values()),\n toolResults: Array.from(this.toolResults.values()),\n iterations: this.config.historyMode === 'full' ? this.iterations : this.iterationSummaries,\n auditTrail: this.auditTrail,\n };\n return JSON.stringify(data).length;\n } catch {\n return 0; // Error estimating, return 0\n }\n }\n\n /**\n * Cleanup resources and release memory\n * Clears all internal arrays and maps to allow garbage collection\n */\n cleanup(): void {\n // Store execution summary before clearing\n const summary = {\n executionId: this.executionId,\n totalIterations: this.iteration,\n totalToolCalls: this.metrics.toolCallCount,\n totalDuration: Date.now() - this.startTime.getTime(),\n success: !this.cancelled && this.metrics.errors.length === 0,\n };\n\n // Clear all maps\n this.toolCalls.clear();\n this.toolResults.clear();\n this.metadata.clear();\n\n // Clear all arrays (modify length to allow GC of items)\n this.iterations.length = 0;\n this.iterationSummaries.length = 0;\n this.auditTrail.length = 0;\n this.metrics.errors.length = 0;\n\n // Store summary after clearing (for final access if needed)\n this.metadata.set('execution_summary', summary);\n }\n\n /**\n * Get execution summary\n */\n getSummary() {\n return {\n executionId: this.executionId,\n startTime: this.startTime,\n currentIteration: this.iteration,\n paused: this.paused,\n cancelled: this.cancelled,\n metrics: { ...this.metrics },\n totalDuration: Date.now() - this.startTime.getTime(),\n };\n }\n}\n","/**\n * Hook manager - handles hook registration and execution\n * Includes error isolation, timeouts, and optional parallel execution\n */\n\nimport { EventEmitter } from 'eventemitter3';\nimport {\n Hook,\n HookConfig,\n HookName,\n HookSignatures,\n} from './types/HookTypes.js';\n\nexport class HookManager {\n private hooks: Map<HookName, Hook<any, any>[]> = new Map();\n private timeout: number;\n private parallel: boolean;\n // Per-hook error tracking: hookKey -> consecutive error count\n private hookErrorCounts: Map<string, number> = new Map();\n // Disabled hooks that exceeded error threshold\n private disabledHooks: Set<string> = new Set();\n private maxConsecutiveErrors: number = 3;\n private emitter: EventEmitter;\n\n constructor(\n config: HookConfig = {},\n emitter: EventEmitter,\n errorHandling?: { maxConsecutiveErrors?: number }\n ) {\n this.timeout = config.hookTimeout || 5000; // 5 second default\n this.parallel = config.parallelHooks || false;\n this.emitter = emitter;\n this.maxConsecutiveErrors = errorHandling?.maxConsecutiveErrors || 3;\n\n // Register hooks from config\n this.registerFromConfig(config);\n }\n\n /**\n * Register hooks from configuration\n */\n private registerFromConfig(config: HookConfig): void {\n const hookNames: HookName[] = [\n 'before:execution',\n 'after:execution',\n 'before:llm',\n 'after:llm',\n 'before:tool',\n 'after:tool',\n 'approve:tool',\n 'pause:check',\n ];\n\n for (const name of hookNames) {\n const hook = config[name];\n if (hook) {\n this.register(name, hook);\n }\n }\n }\n\n /**\n * Register a hook\n */\n register(name: HookName, hook: Hook<any, any>): void {\n // Validate hook is a function\n if (typeof hook !== 'function') {\n throw new Error(`Hook must be a function, got: ${typeof hook}`);\n }\n\n // Get or create hooks array\n if (!this.hooks.has(name)) {\n this.hooks.set(name, []);\n }\n\n const existing = this.hooks.get(name)!;\n\n // Limit number of hooks per name\n if (existing.length >= 10) {\n throw new Error(`Too many hooks for ${name} (max: 10)`);\n }\n\n existing.push(hook);\n }\n\n /**\n * Execute hooks for a given name\n */\n async executeHooks<K extends HookName>(\n name: K,\n context: HookSignatures[K]['context'],\n defaultResult: HookSignatures[K]['result']\n ): Promise<HookSignatures[K]['result']> {\n const hooks = this.hooks.get(name);\n\n if (!hooks || hooks.length === 0) {\n return defaultResult;\n }\n\n // Parallel execution (for independent hooks)\n if (this.parallel && hooks.length > 1) {\n return this.executeHooksParallel(hooks, context, defaultResult);\n }\n\n // Sequential execution (default)\n return this.executeHooksSequential(hooks, context, defaultResult);\n }\n\n /**\n * Execute hooks sequentially\n */\n private async executeHooksSequential<T>(\n hooks: Hook<any, any>[],\n context: any,\n defaultResult: T\n ): Promise<T> {\n let result = defaultResult;\n\n for (let i = 0; i < hooks.length; i++) {\n const hook = hooks[i]!;\n const hookKey = this.getHookKey(hook, i);\n const hookResult = await this.executeHookSafely(hook, context, hookKey);\n\n // Skip failed hooks\n if (hookResult === null) {\n continue;\n }\n\n // Merge hook result\n result = { ...result, ...hookResult };\n\n // Check for early exit\n if ((hookResult as any).skip === true) {\n break;\n }\n }\n\n return result;\n }\n\n /**\n * Execute hooks in parallel\n */\n private async executeHooksParallel<T>(\n hooks: Hook<any, any>[],\n context: any,\n defaultResult: T\n ): Promise<T> {\n // Execute all hooks concurrently with unique keys\n const results = await Promise.all(\n hooks.map((hook, i) => {\n const hookKey = this.getHookKey(hook, i);\n return this.executeHookSafely(hook, context, hookKey);\n })\n );\n\n // Filter out failures and merge results\n const validResults = results.filter((r) => r !== null);\n\n return validResults.reduce(\n (acc, hookResult) => ({ ...acc, ...hookResult }),\n defaultResult\n );\n }\n\n /**\n * Generate unique key for a hook\n */\n private getHookKey(hook: Hook<any, any>, index: number): string {\n return `${hook.name || 'anonymous'}_${index}`;\n }\n\n /**\n * Execute single hook with error isolation and timeout (with per-hook error tracking)\n */\n private async executeHookSafely<T>(\n hook: Hook<any, any>,\n context: any,\n hookKey?: string\n ): Promise<T | null> {\n const key = hookKey || hook.name || 'anonymous';\n\n // Skip disabled hooks\n if (this.disabledHooks.has(key)) {\n return null;\n }\n\n const startTime = Date.now();\n\n try {\n // Execute with timeout\n const result = await Promise.race([\n hook(context),\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new Error('Hook timeout')), this.timeout)\n ),\n ]);\n\n // Reset error counter for this hook on success\n this.hookErrorCounts.delete(key);\n\n // Track timing\n const duration = Date.now() - startTime;\n if (context.context?.updateMetrics) {\n context.context.updateMetrics({\n hookDuration: (context.context.metrics.hookDuration || 0) + duration,\n });\n }\n\n return result as T;\n } catch (error) {\n // Increment error counter for this specific hook\n const errorCount = (this.hookErrorCounts.get(key) || 0) + 1;\n this.hookErrorCounts.set(key, errorCount);\n\n // Emit error event\n this.emitter.emit('hook:error', {\n executionId: context.executionId,\n hookName: hook.name || 'anonymous',\n error: error as Error,\n consecutiveErrors: errorCount,\n timestamp: new Date(),\n });\n\n // Check consecutive error threshold for this hook\n if (errorCount >= this.maxConsecutiveErrors) {\n // Disable this specific hook, not all hooks\n this.disabledHooks.add(key);\n console.warn(\n `Hook \"${key}\" disabled after ${errorCount} consecutive failures. Last error: ${(error as Error).message}`\n );\n } else {\n // Log warning but continue (degraded mode)\n console.warn(\n `Hook execution failed (${key}): ${(error as Error).message} (${errorCount}/${this.maxConsecutiveErrors} errors)`\n );\n }\n\n return null; // Hook failed, skip its result\n }\n }\n\n /**\n * Check if there are any hooks registered\n */\n hasHooks(name: HookName): boolean {\n const hooks = this.hooks.get(name);\n return !!hooks && hooks.length > 0;\n }\n\n /**\n * Get hook count\n */\n getHookCount(name?: HookName): number {\n if (name) {\n return this.hooks.get(name)?.length || 0;\n }\n // Total across all hooks\n return Array.from(this.hooks.values()).reduce((sum, arr) => sum + arr.length, 0);\n }\n\n /**\n * Clear all hooks and reset error tracking\n */\n clear(): void {\n this.hooks.clear();\n this.hookErrorCounts.clear();\n this.disabledHooks.clear();\n }\n\n /**\n * Re-enable a disabled hook\n */\n enableHook(hookKey: string): void {\n this.disabledHooks.delete(hookKey);\n this.hookErrorCounts.delete(hookKey);\n }\n\n /**\n * Get list of disabled hooks\n */\n getDisabledHooks(): string[] {\n return Array.from(this.disabledHooks);\n }\n}\n"]}