From 5f63e9d7878f50c181695362d518cb89eff72f02 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 12:26:14 -0700 Subject: [PATCH 1/2] logging --- package-lock.json | 227 ++++++++++++++++++++++++++++++++- package.json | 1 + src/commands/chat.ts | 13 +- src/index.ts | 10 +- src/mcp.ts | 5 + src/session.ts | 7 +- src/streamChatResponse.ts | 10 +- src/tools/index.ts | 8 +- src/ui/hooks/useChat.ts | 5 + src/util/exponentialBackoff.ts | 3 + src/util/logger.ts | 59 +++++++++ 11 files changed, 325 insertions(+), 23 deletions(-) create mode 100644 src/util/logger.ts diff --git a/package-lock.json b/package-lock.json index 86460ec58..cd368c222 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "1.3.6", + "version": "1.4.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "1.3.6", + "version": "1.4.2", "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "^1.0.96", @@ -33,6 +33,7 @@ "turndown": "^7.2.0", "typescript": "^5.8.3", "uuid": "^9.0.1", + "winston": "^3.17.0", "yaml": "^2.8.0" }, "bin": { @@ -1468,6 +1469,16 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@dabh/diagnostics": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz", + "integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==", + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.6", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.6.tgz", @@ -4356,6 +4367,11 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/triple-beam": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", + "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" + }, "node_modules/@types/turndown": { "version": "5.0.5", "resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.5.tgz", @@ -4609,7 +4625,6 @@ "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "dev": true, "license": "MIT" }, "node_modules/asynckit": { @@ -5392,6 +5407,15 @@ "dev": true, "license": "MIT" }, + "node_modules/color": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz", + "integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==", + "dependencies": { + "color-convert": "^1.9.3", + "color-string": "^1.6.0" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -5410,6 +5434,37 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "license": "MIT" }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/color/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + }, + "node_modules/colorspace": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz", + "integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==", + "dependencies": { + "color": "^3.1.3", + "text-hex": "1.0.x" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -6096,6 +6151,11 @@ "dev": true, "license": "MIT" }, + "node_modules/enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -6648,6 +6708,11 @@ "bser": "2.1.1" } }, + "node_modules/fecha": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", + "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==" + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -6793,6 +6858,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, "node_modules/follow-redirects": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", @@ -8026,7 +8096,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -9491,6 +9560,11 @@ "node": ">=6" } }, + "node_modules/kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, "node_modules/leb": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/leb/-/leb-1.0.0.tgz", @@ -9623,6 +9697,30 @@ "dev": true, "license": "MIT" }, + "node_modules/logform": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz", + "integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==", + "dependencies": { + "@colors/colors": "1.6.0", + "@types/triple-beam": "^1.3.2", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "safe-stable-stringify": "^2.3.1", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/logform/node_modules/@colors/colors": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -12833,6 +12931,14 @@ "wrappy": "1" } }, + "node_modules/one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "dependencies": { + "fn.name": "1.x.x" + } + }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -13921,6 +14027,14 @@ ], "license": "MIT" }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -14517,6 +14631,19 @@ "node": ">=4" } }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, + "node_modules/simple-swizzle/node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, "node_modules/sisteransi": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", @@ -14668,6 +14795,14 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "engines": { + "node": "*" + } + }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -14704,7 +14839,6 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.1.0" @@ -14714,7 +14848,6 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, "license": "MIT" }, "node_modules/string-length": { @@ -14993,6 +15126,11 @@ "node": "*" } }, + "node_modules/text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", @@ -15091,6 +15229,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/triple-beam": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", + "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==", + "engines": { + "node": ">= 14.0.0" + } + }, "node_modules/ts-jest": { "version": "29.3.2", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.3.2.tgz", @@ -15435,7 +15581,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, "license": "MIT" }, "node_modules/uuid": { @@ -15615,6 +15760,74 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/winston": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz", + "integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==", + "dependencies": { + "@colors/colors": "^1.6.0", + "@dabh/diagnostics": "^2.0.2", + "async": "^3.2.3", + "is-stream": "^2.0.0", + "logform": "^2.7.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.9.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz", + "integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==", + "dependencies": { + "logform": "^2.7.0", + "readable-stream": "^3.6.2", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/winston/node_modules/@colors/colors": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", + "engines": { + "node": ">=0.1.90" + } + }, + "node_modules/winston/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", diff --git a/package.json b/package.json index 1183f4302..166898c99 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "turndown": "^7.2.0", "typescript": "^5.8.3", "uuid": "^9.0.1", + "winston": "^3.17.0", "yaml": "^2.8.0" }, "devDependencies": { diff --git a/src/commands/chat.ts b/src/commands/chat.ts index ee3c09be9..32a745738 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -10,6 +10,7 @@ import { streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { startTUIChat } from "../ui/index.js"; import { formatError } from "../util/formatError.js"; +import logger from "../util/logger.js"; export interface ChatOptions { headless?: boolean; @@ -74,9 +75,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { const savedHistory = loadSession(); if (savedHistory) { chatHistory = savedHistory; - console.log(chalk.yellow("Resuming previous session...")); + logger.info(chalk.yellow("Resuming previous session...")); } else { - console.log( + logger.info( chalk.yellow("No previous session found, starting fresh...") ); } @@ -125,22 +126,22 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // In headless mode, only print the final response if (options.headless && finalResponse.trim()) { - console.log(finalResponse); + logger.info(finalResponse); } // Save session after each successful response saveSession(chatHistory); } catch (e: any) { - console.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`); + logger.error(`\n${chalk.red(`Error: ${formatError(e)}`)}`); if (!options.headless) { - console.info( + logger.info( chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`) ); } } } } catch (error: any) { - console.error(chalk.red(`Fatal error: ${formatError(error)}`)); + logger.error(chalk.red(`Fatal error: ${formatError(error)}`)); process.exit(1); } } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index f5a7eec13..300fb8e34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,15 +5,16 @@ import { chat } from "./commands/chat.js"; import { login } from "./commands/login.js"; import { logout } from "./commands/logout.js"; import { getVersion } from "./version.js"; +import logger from "./util/logger.js"; // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { - console.error("Unhandled Rejection at:", promise, "reason:", reason); + logger.error("Unhandled Rejection at:", { promise, reason }); // Don't exit the process, just log the error }); process.on("uncaughtException", (error) => { - console.error("Uncaught Exception:", error); + logger.error("Uncaught Exception:", error); // Don't exit the process, just log the error }); @@ -34,6 +35,7 @@ program .option("--resume", "Resume from last session") .option("--readonly", "Only allow readonly tools") .option("--no-tools", "Disable all tools") + .option("-v, --verbose", "Enable verbose logging") .option( "--rule ", "Add a rule (can be a file path, hub slug, or string content). Can be specified multiple times.", @@ -45,6 +47,10 @@ program [] as string[] ) .action(async (prompt, options) => { + if (options.verbose) { + logger.setLevel('debug'); + logger.debug('Verbose logging enabled'); + } await chat(prompt, options); }); diff --git a/src/mcp.ts b/src/mcp.ts index ff033a903..10489d553 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -1,6 +1,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import logger from "./util/logger.js"; export class MCPService { private readonly connections: MCPConnection[] = []; @@ -20,11 +21,13 @@ export class MCPService { const service = new MCPService(assistant); if (assistant.mcpServers?.length) { + logger.debug('Creating MCP connections', { serverCount: assistant.mcpServers.length }); const connectionPromises = assistant.mcpServers.map((server) => MCPConnection.create(server) ); const connections = await Promise.all(connectionPromises); service.connections.push(...connections); + logger.debug('MCP connections established', { connectionCount: connections.length }); } // Store the instance and return it @@ -93,8 +96,10 @@ export class MCPConnection { // Connect and get all prompts and tools const connection = new MCPConnection(client); + logger.debug('Connecting to MCP server', { command: config.command }); await client.connect(transport); const capabilities = client.getServerCapabilities(); + logger.debug('MCP server capabilities', { hasPrompts: !!capabilities?.prompts, hasTools: !!capabilities?.tools }); if (capabilities?.prompts) { connection.prompts = (await client.listPrompts()).prompts; diff --git a/src/session.ts b/src/session.ts index e5cbbe87b..7f49408b0 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2,6 +2,7 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import fs from "fs"; import path from "path"; import os from "os"; +import logger from "./util/logger.js"; /** * Get a unique session identifier for the current terminal session @@ -60,7 +61,7 @@ export function saveSession(chatHistory: ChatCompletionMessageParam[]): void { fs.writeFileSync(sessionFilePath, JSON.stringify(sessionData, null, 2)); } catch (error) { - console.error('Error saving session:', error); + logger.error('Error saving session:', error); } } @@ -78,7 +79,7 @@ export function loadSession(): ChatCompletionMessageParam[] | null { const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, 'utf8')); return sessionData.chatHistory || null; } catch (error) { - console.error('Error loading session:', error); + logger.error('Error loading session:', error); return null; } } @@ -93,7 +94,7 @@ export function clearSession(): void { fs.unlinkSync(sessionFilePath); } } catch (error) { - console.error('Error clearing session:', error); + logger.error('Error clearing session:', error); } } diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index a2ded72a2..fb097076b 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -11,6 +11,7 @@ import { MCPService } from "./mcp.js"; import { executeToolCall } from "./tools.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js"; +import logger from "./util/logger.js"; dotenv.config(); @@ -86,8 +87,10 @@ export async function streamChatResponse( let shouldContinueConversation = true; while (shouldContinueConversation) { + logger.debug('Starting new conversation iteration', { hasToolCalls: currentToolCalls.length > 0 }); // Factory function to create the stream generator const streamFactory = async () => { + logger.debug('Creating chat completion stream', { model, messageCount: chatHistory.length, toolCount: toolsForRequest.length }); return await chatCompletionStreamWithBackoff( llmApi, { @@ -113,6 +116,7 @@ export async function streamChatResponse( ); for await (const chunk of streamWithBackoff) { + logger.debug('Received stream chunk', { hasContent: !!chunk.choices[0].delta.content, hasToolCalls: !!chunk.choices[0].delta.tool_calls }); // Check if we should abort if (abortController?.signal.aborted) { break; @@ -201,15 +205,15 @@ export async function streamChatResponse( return fullResponse; } // For other errors, re-throw them - console.error( + logger.error( chalk.red("Error in streamChatResponse:"), - chalk.red(error.message) + error ); throw error; } if (!callbacks?.onContent && !isHeadless) { - console.info(); // Add a newline after the response + logger.info(""); // Add a newline after the response } // Notify that content is complete if we have content and are about to process tool calls diff --git a/src/tools/index.ts b/src/tools/index.ts index 7a2c16bca..37b5bd2a5 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -9,6 +9,7 @@ import { searchCodeTool } from "./searchCode.js"; import { type Tool, type ToolParameters } from "./types.js"; import { viewDiffTool } from "./viewDiff.js"; import { writeFileTool } from "./writeFile.js"; +import logger from "../util/logger.js"; export type { Tool, ToolParameters }; @@ -87,7 +88,7 @@ export function extractToolCalls( }); } } catch (e) { - console.error("Failed to parse tool call:", match[1]); + logger.error("Failed to parse tool call:", { toolCall: match[1] }); } } @@ -164,7 +165,10 @@ export async function executeToolCall(toolCall: { } try { - return await tool.run(toolCall.arguments); + logger.debug('Executing tool', { toolName: toolCall.name, arguments: toolCall.arguments }); + const result = await tool.run(toolCall.arguments); + logger.debug('Tool execution completed', { toolName: toolCall.name, resultLength: result?.length || 0 }); + return result; } catch (error) { return `Error executing tool "${toolCall.name}": ${ error instanceof Error ? error.message : String(error) diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 29eed0787..03700dec5 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -13,6 +13,7 @@ import { import { constructSystemMessage } from "../../systemMessage.js"; import { getToolDisplayName } from "../../tools.js"; import { formatError } from "../../util/formatError.js"; +import logger from "../../util/logger.js"; import { DisplayMessage } from "../types.js"; @@ -185,6 +186,7 @@ export function useChat({ setAbortController(controller); setIsWaitingForResponse(true); setInputMode(false); + logger.debug('Starting chat response stream', { messageLength: message.length, historyLength: newHistory.length }); try { let currentStreamingMessage: DisplayMessage | null = null; @@ -310,9 +312,12 @@ export function useChat({ // Update the chat history with the complete conversation after streaming setChatHistory(finalHistory); + logger.debug('Chat history updated', { finalHistoryLength: finalHistory.length }); // Save the updated history to session + logger.debug('Saving session', { historyLength: finalHistory.length }); saveSession(finalHistory); + logger.debug('Session saved'); } catch (error: any) { const errorMessage = `Error: ${formatError(error)}`; setMessages((prev) => [ diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index 9a9fd3ded..8174c7f29 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -2,6 +2,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; import { error, warn } from "../logging.js"; import { formatError } from "./formatError.js"; +import logger from "./logger.js"; export interface ExponentialBackoffOptions { /** Maximum number of retry attempts */ @@ -198,6 +199,7 @@ export async function* withExponentialBackoff( } const delay = calculateDelay(attempt, opts); + logger.debug('Retry attempt', { attempt, delay, error: err.message }); // Only log retry attempts after the first opts.hiddenRetries attempts if (attempt >= opts.hiddenRetries) { @@ -209,6 +211,7 @@ export async function* withExponentialBackoff( } // Wait before retrying + logger.debug('Waiting before retry', { delayMs: delay }); await new Promise((resolve) => setTimeout(resolve, delay)); } } diff --git a/src/util/logger.ts b/src/util/logger.ts new file mode 100644 index 000000000..c30f71724 --- /dev/null +++ b/src/util/logger.ts @@ -0,0 +1,59 @@ +import winston from 'winston'; + +const { combine, timestamp, printf, colorize, errors } = winston.format; + +// Custom format for console output +const consoleFormat = printf(({ level, message, timestamp, stack, ...metadata }) => { + let msg = `${timestamp} [${level}]: ${message}`; + + // Add metadata if present + if (Object.keys(metadata).length > 0) { + msg += ` ${JSON.stringify(metadata)}`; + } + + // Add stack trace for errors + if (stack) { + msg += `\n${stack}`; + } + + return msg; +}); + +// Create the logger instance +const logger = winston.createLogger({ + level: 'info', // Default level + format: combine( + errors({ stack: true }), + timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), + ), + transports: [ + new winston.transports.Console({ + format: combine( + colorize(), + consoleFormat + ), + }), + ], +}); + +// Function to set log level +export function setLogLevel(level: string) { + logger.level = level; +} + +// Export logger methods +export default { + debug: (message: string, meta?: any) => logger.debug(message, meta), + info: (message: string, meta?: any) => logger.info(message, meta), + warn: (message: string, meta?: any) => logger.warn(message, meta), + error: (message: string, error?: Error | any, meta?: any) => { + if (error instanceof Error) { + logger.error(message, { ...meta, error: error.message, stack: error.stack }); + } else if (error) { + logger.error(message, { ...meta, error }); + } else { + logger.error(message, meta); + } + }, + setLevel: setLogLevel, +}; \ No newline at end of file From c7d2f25a59e957e6c9e51732e2e140a4bee193e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 12:43:08 -0700 Subject: [PATCH 2/2] log file --- src/index.ts | 5 +++++ src/util/logger.ts | 47 +++++++++++++++++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/src/index.ts b/src/index.ts index 300fb8e34..cd70384b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -49,6 +49,11 @@ program .action(async (prompt, options) => { if (options.verbose) { logger.setLevel('debug'); + const logPath = logger.getLogPath(); + const sessionId = logger.getSessionId(); + console.log(`Verbose logging enabled (session: ${sessionId})`); + console.log(`Logs: ${logPath}`); + console.log(`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`); logger.debug('Verbose logging enabled'); } await chat(prompt, options); diff --git a/src/util/logger.ts b/src/util/logger.ts index c30f71724..91326388e 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -1,10 +1,36 @@ import winston from 'winston'; +import path from 'path'; +import os from 'os'; +import fs from 'fs'; +import crypto from 'crypto'; -const { combine, timestamp, printf, colorize, errors } = winston.format; +const { combine, timestamp, printf, errors } = winston.format; -// Custom format for console output -const consoleFormat = printf(({ level, message, timestamp, stack, ...metadata }) => { - let msg = `${timestamp} [${level}]: ${message}`; +// Generate a unique session ID for this process +const SESSION_ID = crypto.randomBytes(4).toString('hex'); + +// Get log directory +function getLogDir(): string { + const homeDir = os.homedir(); + const logDir = path.join(homeDir, '.continue', 'logs'); + + // Create directory if it doesn't exist + if (!fs.existsSync(logDir)) { + fs.mkdirSync(logDir, { recursive: true }); + } + + return logDir; +} + +// Get current log file path +function getLogFilePath(): string { + const logDir = getLogDir(); + return path.join(logDir, 'cn.log'); +} + +// Custom format for log output +const logFormat = printf(({ level, message, timestamp, stack, ...metadata }) => { + let msg = `${timestamp} [${SESSION_ID}] [${level}]: ${message}`; // Add metadata if present if (Object.keys(metadata).length > 0) { @@ -25,13 +51,14 @@ const logger = winston.createLogger({ format: combine( errors({ stack: true }), timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), + logFormat ), transports: [ - new winston.transports.Console({ - format: combine( - colorize(), - consoleFormat - ), + // File transport for all logs + new winston.transports.File({ + filename: getLogFilePath(), + maxsize: 10 * 1024 * 1024, // 10MB + maxFiles: 5, }), ], }); @@ -56,4 +83,6 @@ export default { } }, setLevel: setLogLevel, + getLogPath: getLogFilePath, + getSessionId: () => SESSION_ID, }; \ No newline at end of file