From 662891f5d9e7d3bc67798cbb4e0222a3c8aaac01 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 1 Aug 2025 16:16:58 -0700 Subject: [PATCH] improv: error handling --- src/commands/chat.ts | 7 ++----- src/index.ts | 1 + src/util/logger.ts | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 3327ac300..3169b8efb 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -123,11 +123,8 @@ async function processMessage( // Save session after each successful response saveSession(chatHistory); } catch (e: any) { - // In headless mode, ensure errors are visible on stderr - if (isHeadless) { - console.error(chalk.red(`Error: ${formatError(e)}`)); - } else { - logger.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`); + logger.error(`Error: ${formatError(e)}`, e); + if (!isHeadless) { logger.info( chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) ); diff --git a/src/index.ts b/src/index.ts index 5cdf34db5..50d348664 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,6 +47,7 @@ addCommonOptions(program) // Configure console overrides FIRST, before any other logging const isHeadless = options.print; configureConsoleForHeadless(isHeadless); + logger.configureHeadlessMode(isHeadless); // Validate --format flag only works with -p/--print if (options.format && !options.print) { diff --git a/src/util/logger.ts b/src/util/logger.ts index 91326388e..7bf06ffbb 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -3,6 +3,7 @@ import path from 'path'; import os from 'os'; import fs from 'fs'; import crypto from 'crypto'; +import chalk from 'chalk'; const { combine, timestamp, printf, errors } = winston.format; @@ -45,6 +46,9 @@ const logFormat = printf(({ level, message, timestamp, stack, ...metadata }) => return msg; }); +// Track headless mode +let isHeadlessMode = false; + // Create the logger instance const logger = winston.createLogger({ level: 'info', // Default level @@ -68,6 +72,11 @@ export function setLogLevel(level: string) { logger.level = level; } +// Function to configure headless mode +export function configureHeadlessMode(headless: boolean) { + isHeadlessMode = headless; +} + // Export logger methods export default { debug: (message: string, meta?: any) => logger.debug(message, meta), @@ -81,8 +90,20 @@ export default { } else { logger.error(message, meta); } + + // In headless mode, also output to stderr + if (isHeadlessMode) { + if (error instanceof Error) { + console.error(chalk.red(`${message}: ${error.message}`)); + } else if (error) { + console.error(chalk.red(`${message}: ${error}`)); + } else { + console.error(chalk.red(message)); + } + } }, setLevel: setLogLevel, + configureHeadlessMode, getLogPath: getLogFilePath, getSessionId: () => SESSION_ID, }; \ No newline at end of file