@goodfoot/agent-hooks 1.0.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.
- package/README.md +137 -0
- package/dist/agents/antigravity/events.js +42 -0
- package/dist/agents/antigravity/hooks.js +59 -0
- package/dist/agents/antigravity/index.js +28 -0
- package/dist/agents/antigravity/outputs.js +81 -0
- package/dist/agents/antigravity/transport.js +84 -0
- package/dist/agents/antigravity/types.js +11 -0
- package/dist/agents/claude-code/env.js +27 -0
- package/dist/agents/claude-code/events.js +87 -0
- package/dist/agents/claude-code/hooks.js +1000 -0
- package/dist/agents/claude-code/index.js +57 -0
- package/dist/agents/claude-code/outputs.js +579 -0
- package/dist/agents/claude-code/tool-helpers.js +840 -0
- package/dist/agents/claude-code/transport.js +254 -0
- package/dist/agents/claude-code/types.js +11 -0
- package/dist/agents/codex/cli-support.js +318 -0
- package/dist/agents/codex/constants.js +29 -0
- package/dist/agents/codex/events.js +68 -0
- package/dist/agents/codex/hooks.js +93 -0
- package/dist/agents/codex/index.js +21 -0
- package/dist/agents/codex/outputs.js +189 -0
- package/dist/agents/codex/scaffold.js +273 -0
- package/dist/agents/codex/transport.js +139 -0
- package/dist/agents/codex/types.js +1 -0
- package/dist/cli.js +1357 -0
- package/dist/constants.js +39 -0
- package/dist/core/define-hook.js +61 -0
- package/dist/core/env.js +186 -0
- package/dist/core/logger.js +508 -0
- package/dist/core/stdin.js +38 -0
- package/dist/core/transport.js +231 -0
- package/dist/core/types.js +10 -0
- package/dist/index.js +17 -0
- package/dist/scaffold.js +512 -0
- package/package.json +61 -0
- package/types/agents/antigravity/events.d.ts +50 -0
- package/types/agents/antigravity/hooks.d.ts +76 -0
- package/types/agents/antigravity/index.d.ts +27 -0
- package/types/agents/antigravity/outputs.d.ts +107 -0
- package/types/agents/antigravity/transport.d.ts +47 -0
- package/types/agents/antigravity/types.d.ts +58 -0
- package/types/agents/claude-code/env.d.ts +27 -0
- package/types/agents/claude-code/events.d.ts +69 -0
- package/types/agents/claude-code/hooks.d.ts +1182 -0
- package/types/agents/claude-code/index.d.ts +23 -0
- package/types/agents/claude-code/outputs.d.ts +1160 -0
- package/types/agents/claude-code/tool-helpers.d.ts +807 -0
- package/types/agents/claude-code/transport.d.ts +119 -0
- package/types/agents/claude-code/types.d.ts +557 -0
- package/types/agents/codex/cli-support.d.ts +105 -0
- package/types/agents/codex/constants.d.ts +10 -0
- package/types/agents/codex/events.d.ts +63 -0
- package/types/agents/codex/hooks.d.ts +135 -0
- package/types/agents/codex/index.d.ts +19 -0
- package/types/agents/codex/outputs.d.ts +190 -0
- package/types/agents/codex/scaffold.d.ts +14 -0
- package/types/agents/codex/transport.d.ts +74 -0
- package/types/agents/codex/types.d.ts +131 -0
- package/types/cli.d.ts +315 -0
- package/types/constants.d.ts +9 -0
- package/types/core/define-hook.d.ts +39 -0
- package/types/core/env.d.ts +150 -0
- package/types/core/logger.d.ts +476 -0
- package/types/core/stdin.d.ts +21 -0
- package/types/core/transport.d.ts +131 -0
- package/types/core/types.d.ts +137 -0
- package/types/index.d.ts +18 -0
- package/types/scaffold.d.ts +46 -0
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logger system for agent hooks.
|
|
3
|
+
*
|
|
4
|
+
* Provides structured logging with event subscription and optional file output.
|
|
5
|
+
* The logger is **silent by default** to avoid interfering with hook protocol
|
|
6
|
+
* (stdout is reserved for JSON responses, stderr may conflict with the host
|
|
7
|
+
* CLI).
|
|
8
|
+
* @module
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { logger } from '@goodfoot/agent-hooks';
|
|
12
|
+
*
|
|
13
|
+
* // Subscribe to log events
|
|
14
|
+
* const unsubscribe = logger.on('error', (event) => {
|
|
15
|
+
* console.error(`Error in ${event.hookType}: ${event.message}`);
|
|
16
|
+
* });
|
|
17
|
+
*
|
|
18
|
+
* // Later, clean up
|
|
19
|
+
* unsubscribe();
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import { closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
23
|
+
import { dirname } from "node:path";
|
|
24
|
+
/**
|
|
25
|
+
* All log levels in order of severity (lowest to highest).
|
|
26
|
+
*/
|
|
27
|
+
export const LOG_LEVELS = ["debug", "info", "warn", "error"];
|
|
28
|
+
// ============================================================================
|
|
29
|
+
// Logger Class
|
|
30
|
+
// ============================================================================
|
|
31
|
+
/**
|
|
32
|
+
* Logger for agent hooks with event subscription and file output.
|
|
33
|
+
*
|
|
34
|
+
* ## Key Behaviors
|
|
35
|
+
*
|
|
36
|
+
* | Configuration | Behavior |
|
|
37
|
+
* |--------------|----------|
|
|
38
|
+
* | No config (default) | **Silent** - no output anywhere |
|
|
39
|
+
* | `AGENT_HOOKS_LOG_FILE` env var | Append JSON lines to file |
|
|
40
|
+
* | `.on(level, handler)` registered | Events delivered to handlers only |
|
|
41
|
+
* | Multiple destinations | All destinations receive events |
|
|
42
|
+
*
|
|
43
|
+
* ## Important Notes
|
|
44
|
+
*
|
|
45
|
+
* - **Never outputs to stdout** (reserved for JSON hook response)
|
|
46
|
+
* - **Never outputs to stderr** (may interfere with host CLI error handling)
|
|
47
|
+
* - File output uses JSON Lines format for easy parsing
|
|
48
|
+
* - `.on(level, handler)` returns an unsubscribe function
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* import { logger } from '@goodfoot/agent-hooks';
|
|
52
|
+
*
|
|
53
|
+
* // Subscribe to events at specific level
|
|
54
|
+
* logger.on('warn', (event) => {
|
|
55
|
+
* sendAlert(event.message);
|
|
56
|
+
* });
|
|
57
|
+
*
|
|
58
|
+
* // Log within a hook handler
|
|
59
|
+
* export default preToolUseHook({ matcher: 'Bash' }, async (input, { logger }) => {
|
|
60
|
+
* logger.warn('About to validate Bash command');
|
|
61
|
+
* return preToolUseOutput({ allow: true });
|
|
62
|
+
* });
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export class Logger {
|
|
66
|
+
/**
|
|
67
|
+
* Registered event handlers by log level.
|
|
68
|
+
*/
|
|
69
|
+
handlers = new Map();
|
|
70
|
+
/**
|
|
71
|
+
* File descriptor for log file output.
|
|
72
|
+
* Lazily initialized on first write.
|
|
73
|
+
*/
|
|
74
|
+
logFileFd = null;
|
|
75
|
+
/**
|
|
76
|
+
* Path to the log file, if configured.
|
|
77
|
+
*/
|
|
78
|
+
logFilePath = null;
|
|
79
|
+
/**
|
|
80
|
+
* Whether file initialization has been attempted.
|
|
81
|
+
*/
|
|
82
|
+
fileInitialized = false;
|
|
83
|
+
/**
|
|
84
|
+
* Current hook context for enriching log events.
|
|
85
|
+
*/
|
|
86
|
+
currentHookType;
|
|
87
|
+
/**
|
|
88
|
+
* Current hook input for enriching log events.
|
|
89
|
+
*/
|
|
90
|
+
currentInput;
|
|
91
|
+
/**
|
|
92
|
+
* Creates a new Logger instance.
|
|
93
|
+
*
|
|
94
|
+
* Typically you should use the exported `logger` singleton rather than
|
|
95
|
+
* creating new instances.
|
|
96
|
+
* @param config - Optional configuration
|
|
97
|
+
* @example
|
|
98
|
+
* ```typescript
|
|
99
|
+
* // Use singleton (recommended)
|
|
100
|
+
* import { logger } from '@goodfoot/agent-hooks';
|
|
101
|
+
*
|
|
102
|
+
* // Or create custom instance
|
|
103
|
+
* const customLogger = new Logger({ logFilePath: '/var/log/hooks.log' });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
constructor(config = {}) {
|
|
107
|
+
// Initialize handlers map for each level
|
|
108
|
+
for (const level of LOG_LEVELS) {
|
|
109
|
+
this.handlers.set(level, new Set());
|
|
110
|
+
}
|
|
111
|
+
// Set log file path from explicit config, or by reading the configured env var
|
|
112
|
+
this.logFilePath = config.logFilePath ?? (config.logEnvVar ? process.env[config.logEnvVar] : undefined) ?? null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Logs a debug message.
|
|
116
|
+
*
|
|
117
|
+
* Use for detailed debugging information that is typically only useful
|
|
118
|
+
* during development or troubleshooting.
|
|
119
|
+
* @param message - The debug message
|
|
120
|
+
* @param context - Optional additional context
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* logger.debug('Processing tool input', { toolName: 'Bash', inputSize: 256 });
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
debug(message, context) {
|
|
127
|
+
this.emit("debug", message, context);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Logs an info message.
|
|
131
|
+
*
|
|
132
|
+
* Use for general operational events like hook invocations, successful
|
|
133
|
+
* completions, or state changes.
|
|
134
|
+
* @param message - The info message
|
|
135
|
+
* @param context - Optional additional context
|
|
136
|
+
* @example
|
|
137
|
+
* ```typescript
|
|
138
|
+
* logger.info('Session started', { source: 'startup', sessionId: 'abc123' });
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
info(message, context) {
|
|
142
|
+
this.emit("info", message, context);
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Logs a warning message.
|
|
146
|
+
*
|
|
147
|
+
* Use for conditions that may indicate issues but don't prevent
|
|
148
|
+
* operation, such as deprecated patterns or performance concerns.
|
|
149
|
+
* @param message - The warning message
|
|
150
|
+
* @param context - Optional additional context
|
|
151
|
+
* @example
|
|
152
|
+
* ```typescript
|
|
153
|
+
* logger.warn('Deprecated hook pattern detected', { pattern: 'legacyMatcher' });
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
warn(message, context) {
|
|
157
|
+
this.emit("warn", message, context);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Logs an error message.
|
|
161
|
+
*
|
|
162
|
+
* Use for error conditions that require attention but were handled
|
|
163
|
+
* gracefully. For exceptions, prefer {@link logError}.
|
|
164
|
+
* @param message - The error message
|
|
165
|
+
* @param context - Optional additional context
|
|
166
|
+
* @example
|
|
167
|
+
* ```typescript
|
|
168
|
+
* logger.error('Failed to validate tool input', { toolName: 'Bash', reason: 'empty command' });
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
error(message, context) {
|
|
172
|
+
this.emit("error", message, context);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Logs a structured error with full error details.
|
|
176
|
+
*
|
|
177
|
+
* Use this method when logging caught exceptions to capture the full
|
|
178
|
+
* error context including name, message, stack trace, and cause chain.
|
|
179
|
+
* @param error - The error to log
|
|
180
|
+
* @param message - Human-readable description of what failed
|
|
181
|
+
* @param context - Optional additional context
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* try {
|
|
185
|
+
* await dangerousOperation();
|
|
186
|
+
* } catch (err) {
|
|
187
|
+
* logger.logError(err, 'Failed to execute dangerous operation', {
|
|
188
|
+
* operation: 'delete',
|
|
189
|
+
* target: '/important/file.txt'
|
|
190
|
+
* });
|
|
191
|
+
* }
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
logError(error, message, context) {
|
|
195
|
+
const errorInfo = this.extractErrorInfo(error);
|
|
196
|
+
const event = {
|
|
197
|
+
timestamp: new Date().toISOString(),
|
|
198
|
+
level: "error",
|
|
199
|
+
hookType: this.currentHookType,
|
|
200
|
+
message,
|
|
201
|
+
input: this.currentInput,
|
|
202
|
+
error: errorInfo,
|
|
203
|
+
context,
|
|
204
|
+
};
|
|
205
|
+
this.deliverEvent(event);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Subscribes a handler to log events at the specified level.
|
|
209
|
+
*
|
|
210
|
+
* The handler will be called for every log event at the specified level.
|
|
211
|
+
* Returns an unsubscribe function that should be called when the handler
|
|
212
|
+
* is no longer needed.
|
|
213
|
+
* @param level - The log level to subscribe to
|
|
214
|
+
* @param handler - The handler function to call for each event
|
|
215
|
+
* @returns A function to unsubscribe the handler
|
|
216
|
+
* @example
|
|
217
|
+
* ```typescript
|
|
218
|
+
* // Subscribe to error events
|
|
219
|
+
* const unsubscribe = logger.on('error', (event) => {
|
|
220
|
+
* console.error(`[${event.hookType}] ${event.message}`);
|
|
221
|
+
* if (event.error) {
|
|
222
|
+
* console.error(event.error.stack);
|
|
223
|
+
* }
|
|
224
|
+
* });
|
|
225
|
+
*
|
|
226
|
+
* // Later, clean up
|
|
227
|
+
* unsubscribe();
|
|
228
|
+
* ```
|
|
229
|
+
* @example
|
|
230
|
+
* ```typescript
|
|
231
|
+
* // Forward to external logging library
|
|
232
|
+
* import pino from 'pino';
|
|
233
|
+
* const pinoLogger = pino();
|
|
234
|
+
*
|
|
235
|
+
* logger.on('info', (event) => pinoLogger.info(event, event.message));
|
|
236
|
+
* logger.on('warn', (event) => pinoLogger.warn(event, event.message));
|
|
237
|
+
* logger.on('error', (event) => pinoLogger.error(event, event.message));
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
on(level, handler) {
|
|
241
|
+
const levelHandlers = this.handlers.get(level);
|
|
242
|
+
if (levelHandlers) {
|
|
243
|
+
levelHandlers.add(handler);
|
|
244
|
+
}
|
|
245
|
+
return () => {
|
|
246
|
+
levelHandlers?.delete(handler);
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Sets the current hook context for enriching log events.
|
|
251
|
+
*
|
|
252
|
+
* This is called internally by the runtime before invoking hook handlers.
|
|
253
|
+
* You typically don't need to call this directly.
|
|
254
|
+
* @param hookType - The agent event name being executed
|
|
255
|
+
* @param input - The hook input data
|
|
256
|
+
* @internal
|
|
257
|
+
*/
|
|
258
|
+
setContext(hookType, input) {
|
|
259
|
+
this.currentHookType = hookType;
|
|
260
|
+
this.currentInput = input;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Clears the current hook context.
|
|
264
|
+
*
|
|
265
|
+
* Called internally by the runtime after hook execution completes.
|
|
266
|
+
* @internal
|
|
267
|
+
*/
|
|
268
|
+
clearContext() {
|
|
269
|
+
this.currentHookType = undefined;
|
|
270
|
+
this.currentInput = undefined;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Configures the log file path at runtime.
|
|
274
|
+
*
|
|
275
|
+
* Call this to enable or change file logging. Setting to `null` disables
|
|
276
|
+
* file logging (but doesn't close existing file handle immediately).
|
|
277
|
+
* @param filePath - Path to the log file, or null to disable
|
|
278
|
+
* @example
|
|
279
|
+
* ```typescript
|
|
280
|
+
* // Enable file logging at runtime
|
|
281
|
+
* logger.setLogFile('/var/log/agent-hooks.log');
|
|
282
|
+
*
|
|
283
|
+
* // Disable file logging
|
|
284
|
+
* logger.setLogFile(null);
|
|
285
|
+
* ```
|
|
286
|
+
*/
|
|
287
|
+
setLogFile(filePath) {
|
|
288
|
+
// Close existing file if open
|
|
289
|
+
if (this.logFileFd !== null) {
|
|
290
|
+
try {
|
|
291
|
+
closeSync(this.logFileFd);
|
|
292
|
+
}
|
|
293
|
+
catch (closeError) {
|
|
294
|
+
process.stderr.write(`[agent-hooks] Failed to close log file: ${String(closeError)}\n`);
|
|
295
|
+
}
|
|
296
|
+
this.logFileFd = null;
|
|
297
|
+
}
|
|
298
|
+
this.logFilePath = filePath;
|
|
299
|
+
this.fileInitialized = false;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Closes all resources held by the logger.
|
|
303
|
+
*
|
|
304
|
+
* Call this during graceful shutdown to ensure all log data is flushed.
|
|
305
|
+
* @example
|
|
306
|
+
* ```typescript
|
|
307
|
+
* process.on('exit', () => {
|
|
308
|
+
* logger.close();
|
|
309
|
+
* });
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
312
|
+
close() {
|
|
313
|
+
if (this.logFileFd !== null) {
|
|
314
|
+
try {
|
|
315
|
+
closeSync(this.logFileFd);
|
|
316
|
+
}
|
|
317
|
+
catch (closeError) {
|
|
318
|
+
process.stderr.write(`[agent-hooks] Failed to close log file: ${String(closeError)}\n`);
|
|
319
|
+
}
|
|
320
|
+
this.logFileFd = null;
|
|
321
|
+
}
|
|
322
|
+
this.fileInitialized = false;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Checks if there are any active handlers or destinations.
|
|
326
|
+
*
|
|
327
|
+
* Returns true if any handlers are registered or file logging is enabled.
|
|
328
|
+
* @returns Whether the logger has any active output destinations
|
|
329
|
+
*/
|
|
330
|
+
hasDestinations() {
|
|
331
|
+
for (const handlers of this.handlers.values()) {
|
|
332
|
+
if (handlers.size > 0)
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
return this.logFilePath !== null;
|
|
336
|
+
}
|
|
337
|
+
// ============================================================================
|
|
338
|
+
// Private Methods
|
|
339
|
+
// ============================================================================
|
|
340
|
+
/**
|
|
341
|
+
* Emits a log event.
|
|
342
|
+
* @param level - The severity level of the event
|
|
343
|
+
* @param message - The log message
|
|
344
|
+
* @param context - Optional additional context data
|
|
345
|
+
*/
|
|
346
|
+
emit(level, message, context) {
|
|
347
|
+
const event = {
|
|
348
|
+
timestamp: new Date().toISOString(),
|
|
349
|
+
level,
|
|
350
|
+
hookType: this.currentHookType,
|
|
351
|
+
message,
|
|
352
|
+
input: this.currentInput,
|
|
353
|
+
context,
|
|
354
|
+
};
|
|
355
|
+
this.deliverEvent(event);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Delivers an event to all registered destinations.
|
|
359
|
+
* @param event - The log event to deliver
|
|
360
|
+
*/
|
|
361
|
+
deliverEvent(event) {
|
|
362
|
+
// Deliver to event handlers
|
|
363
|
+
const levelHandlers = this.handlers.get(event.level);
|
|
364
|
+
if (levelHandlers) {
|
|
365
|
+
for (const handler of levelHandlers) {
|
|
366
|
+
try {
|
|
367
|
+
handler(event);
|
|
368
|
+
}
|
|
369
|
+
catch (handlerError) {
|
|
370
|
+
process.stderr.write(`[agent-hooks] Log handler error: ${String(handlerError)}\n`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
// Write to file if configured
|
|
375
|
+
this.writeToFile(event);
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Writes an event to the log file.
|
|
379
|
+
* @param event - The log event to write
|
|
380
|
+
*/
|
|
381
|
+
writeToFile(event) {
|
|
382
|
+
if (!this.logFilePath)
|
|
383
|
+
return;
|
|
384
|
+
// Lazy initialization of file handle
|
|
385
|
+
if (!this.fileInitialized) {
|
|
386
|
+
this.initializeFile();
|
|
387
|
+
}
|
|
388
|
+
if (this.logFileFd === null)
|
|
389
|
+
return;
|
|
390
|
+
try {
|
|
391
|
+
const line = `${JSON.stringify(event)}\n`;
|
|
392
|
+
writeSync(this.logFileFd, line);
|
|
393
|
+
}
|
|
394
|
+
catch (writeError) {
|
|
395
|
+
// Disable file logging after a write failure to avoid repeated errors
|
|
396
|
+
this.logFileFd = null;
|
|
397
|
+
this.fileInitialized = false;
|
|
398
|
+
process.stderr.write(`[agent-hooks] Log file write failed: ${String(writeError)}\n`);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Initializes the log file for writing.
|
|
403
|
+
*/
|
|
404
|
+
initializeFile() {
|
|
405
|
+
this.fileInitialized = true;
|
|
406
|
+
if (!this.logFilePath)
|
|
407
|
+
return;
|
|
408
|
+
try {
|
|
409
|
+
// Ensure directory exists
|
|
410
|
+
const dir = dirname(this.logFilePath);
|
|
411
|
+
if (!existsSync(dir)) {
|
|
412
|
+
mkdirSync(dir, { recursive: true });
|
|
413
|
+
}
|
|
414
|
+
// Open file for appending
|
|
415
|
+
this.logFileFd = openSync(this.logFilePath, "a");
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
// Silently ignore file initialization errors
|
|
419
|
+
this.logFileFd = null;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Extracts structured error information from an unknown error.
|
|
424
|
+
* @param error - The error to extract information from
|
|
425
|
+
* @returns Structured error information
|
|
426
|
+
*/
|
|
427
|
+
extractErrorInfo(error) {
|
|
428
|
+
if (error instanceof Error) {
|
|
429
|
+
const info = {
|
|
430
|
+
name: error.name,
|
|
431
|
+
message: error.message,
|
|
432
|
+
stack: error.stack,
|
|
433
|
+
};
|
|
434
|
+
// Extract cause chain if present
|
|
435
|
+
if (error.cause !== undefined) {
|
|
436
|
+
info.cause = this.extractErrorInfo(error.cause);
|
|
437
|
+
}
|
|
438
|
+
return info;
|
|
439
|
+
}
|
|
440
|
+
// Handle non-Error values
|
|
441
|
+
return {
|
|
442
|
+
name: "UnknownError",
|
|
443
|
+
message: String(error),
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
// ============================================================================
|
|
448
|
+
// Singleton Export
|
|
449
|
+
// ============================================================================
|
|
450
|
+
/**
|
|
451
|
+
* Global logger instance for agent hooks.
|
|
452
|
+
*
|
|
453
|
+
* Use this singleton for all logging within hooks. The logger is configured
|
|
454
|
+
* via environment variables and supports event subscription for custom
|
|
455
|
+
* destinations.
|
|
456
|
+
*
|
|
457
|
+
* ## Configuration
|
|
458
|
+
*
|
|
459
|
+
* | Environment Variable | Description |
|
|
460
|
+
* |---------------------|-------------|
|
|
461
|
+
* | `AGENT_HOOKS_LOG_FILE` | Path to log file (JSON Lines format) |
|
|
462
|
+
*
|
|
463
|
+
* ## Usage in Hooks
|
|
464
|
+
*
|
|
465
|
+
* The logger is passed to hook handlers via context for convenience:
|
|
466
|
+
*
|
|
467
|
+
* ```typescript
|
|
468
|
+
* export default preToolUseHook({ matcher: 'Bash' }, async (input, { logger }) => {
|
|
469
|
+
* logger.warn('Validating Bash command');
|
|
470
|
+
* return preToolUseOutput({ allow: true });
|
|
471
|
+
* });
|
|
472
|
+
* ```
|
|
473
|
+
*
|
|
474
|
+
* ## External Integration
|
|
475
|
+
*
|
|
476
|
+
* Subscribe to events to forward logs to external systems:
|
|
477
|
+
*
|
|
478
|
+
* ```typescript
|
|
479
|
+
* import { logger } from '@goodfoot/agent-hooks';
|
|
480
|
+
* import pino from 'pino';
|
|
481
|
+
*
|
|
482
|
+
* const pinoLogger = pino({ level: 'debug' });
|
|
483
|
+
*
|
|
484
|
+
* logger.on('debug', (event) => pinoLogger.debug(event, event.message));
|
|
485
|
+
* logger.on('info', (event) => pinoLogger.info(event, event.message));
|
|
486
|
+
* logger.on('warn', (event) => pinoLogger.warn(event, event.message));
|
|
487
|
+
* logger.on('error', (event) => pinoLogger.error(event, event.message));
|
|
488
|
+
* ```
|
|
489
|
+
* @example
|
|
490
|
+
* ```typescript
|
|
491
|
+
* // Direct usage
|
|
492
|
+
* import { logger } from '@goodfoot/agent-hooks';
|
|
493
|
+
*
|
|
494
|
+
* logger.info('Starting operation');
|
|
495
|
+
* logger.warn('Resource limit approaching', { usage: 0.9 });
|
|
496
|
+
*
|
|
497
|
+
* try {
|
|
498
|
+
* await riskyOperation();
|
|
499
|
+
* } catch (err) {
|
|
500
|
+
* logger.logError(err, 'Risky operation failed');
|
|
501
|
+
* }
|
|
502
|
+
* ```
|
|
503
|
+
*/
|
|
504
|
+
// AGENT_HOOKS_LOG_ENV_VAR is set unconditionally by the --log-env-var banner
|
|
505
|
+
// before this module initialises. If absent, fall back to the default env var name.
|
|
506
|
+
export const logger = new Logger({
|
|
507
|
+
logEnvVar: process.env.AGENT_HOOKS_LOG_ENV_VAR ?? "AGENT_HOOKS_LOG_FILE",
|
|
508
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stdin acquisition and JSON parsing for agent hooks.
|
|
3
|
+
*
|
|
4
|
+
* Both source runtimes (`claude-code-hooks`, `codex-hooks`) read stdin and
|
|
5
|
+
* parse JSON identically; this module is that shared logic. Wire rules for
|
|
6
|
+
* what a parse failure *means* belong to each agent's transport — core only
|
|
7
|
+
* classifies the outcome.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Reads all data from stdin.
|
|
12
|
+
* @returns Promise resolving to the complete stdin content
|
|
13
|
+
*/
|
|
14
|
+
export async function readStdin() {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const chunks = [];
|
|
17
|
+
// Set encoding first to ensure data events receive strings
|
|
18
|
+
process.stdin.setEncoding("utf-8");
|
|
19
|
+
process.stdin.on("data", (chunk) => {
|
|
20
|
+
chunks.push(chunk);
|
|
21
|
+
});
|
|
22
|
+
process.stdin.on("end", () => {
|
|
23
|
+
resolve(chunks.join(""));
|
|
24
|
+
});
|
|
25
|
+
process.stdin.on("error", (error) => {
|
|
26
|
+
reject(error);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Parses stdin JSON input.
|
|
32
|
+
* @param stdinContent - Raw stdin content
|
|
33
|
+
* @returns Parsed input in the host CLI's wire format
|
|
34
|
+
* @throws SyntaxError if JSON is malformed
|
|
35
|
+
*/
|
|
36
|
+
export function parseStdinJson(stdinContent) {
|
|
37
|
+
return JSON.parse(stdinContent);
|
|
38
|
+
}
|