"use strict";
/**
 * MCP server stderr tee — writes console.error output to both stderr
 * (for Claude Code) and a dated log file (for logs-read.sh retrieval).
 *
 * Claude Code spawns MCP servers as child processes and consumes their
 * stderr internally. The platform cannot intercept at the spawn level.
 * Each server must tee its own stderr to the account's log directory.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.initStderrTee = initStderrTee;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
/**
 * Patch process.stderr.write to tee output to a dated log file.
 *
 * Reads LOG_DIR from environment. When absent (dev mode, tool discovery),
 * does nothing — stderr continues to work as before.
 *
 * Log file: {LOG_DIR}/mcp-{serverName}-stderr-YYYY-MM-DD.log (append mode)
 */
function initStderrTee(serverName) {
    const logDir = process.env.LOG_DIR;
    if (!logDir)
        return; // Dev mode or tool discovery — stderr only
    let logStream;
    try {
        (0, node_fs_1.mkdirSync)(logDir, { recursive: true });
        const date = new Date().toISOString().slice(0, 10);
        logStream = (0, node_fs_1.createWriteStream)((0, node_path_1.resolve)(logDir, `mcp-${serverName}-stderr-${date}.log`), { flags: "a" });
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        process.stderr.write(`[${serverName}] WARNING: log file tee failed (${msg}), stderr only\n`);
        return;
    }
    const originalWrite = process.stderr.write.bind(process.stderr);
    process.stderr.write = (chunk, ...args) => {
        if (!logStream.destroyed) {
            logStream.write(chunk);
        }
        return originalWrite(chunk, ...args);
    };
}
//# sourceMappingURL=index.js.map