Fix: Add proper error handling to context hook stdin processing

- Wrap stdin event handler in try/catch to catch async errors
- Output errors to stdout so Claude can see them
- Show input preview and stack trace for debugging
- Remove outer try/catch that wasn't catching async errors
This commit is contained in:
Alex Newman
2025-10-25 23:51:53 -04:00
parent f499810c7a
commit c06abbc6f2
2 changed files with 40 additions and 31 deletions
+24 -15
View File
@@ -7,28 +7,37 @@
import { contextHook } from '../../hooks/context.js';
import { stdin } from 'process';
try {
// Check for --index flag
const useIndexView = process.argv.includes('--index');
// Check for --index flag
const useIndexView = process.argv.includes('--index');
if (stdin.isTTY) {
// Running manually from terminal - print formatted output with colors
if (stdin.isTTY) {
// Running manually from terminal - print formatted output with colors
try {
const contextOutput = contextHook(undefined, true, useIndexView);
console.log(contextOutput);
process.exit(0);
} else {
// Running from hook - output plain text to stdout (for SessionStart hooks)
let input = '';
stdin.on('data', (chunk) => input += chunk);
stdin.on('end', () => {
} catch (error: any) {
console.error(`[claude-mem context-hook error: ${error.message}]`);
console.error(error.stack);
process.exit(1);
}
} else {
// Running from hook - output plain text to stdout (for SessionStart hooks)
let input = '';
stdin.on('data', (chunk) => input += chunk);
stdin.on('end', () => {
try {
const parsed = input.trim() ? JSON.parse(input) : undefined;
const contextOutput = contextHook(parsed, false, useIndexView);
// SessionStart hooks add stdout directly to context
console.log(contextOutput);
process.exit(0);
});
}
} catch (error: any) {
console.error(`[claude-mem context-hook error: ${error.message}]`);
process.exit(0);
} catch (error: any) {
// Output error to stdout so Claude sees it
console.log(`[claude-mem context-hook ERROR: ${error.message}]`);
console.log(`Input received: ${input.substring(0, 200)}...`);
console.log(error.stack);
process.exit(1);
}
});
}