"use strict";
/**
 * Best-effort WebSearch trace helpers.
 *
 * Writes opt-in JSONL trace records to ~/.ccs/logs/websearch-trace.jsonl so
 * CCS can explain launch intent, MCP exposure, provider selection, and likely
 * bypass scenarios without polluting Claude/MCP stdout.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWebSearchTraceContext = exports.readWebSearchTraceRecords = exports.appendWebSearchTrace = exports.isWebSearchTraceEnabled = exports.resolveAllowedWebSearchTraceFile = void 0;
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const config_manager_1 = require("../config-manager");
const logging_1 = require("../../services/logging");
const prompt_injection_strategy_1 = require("../prompt-injection-strategy");
const claude_tool_args_1 = require("./claude-tool-args");
const TRACE_FILE_NAME = 'websearch-trace.jsonl';
const NATIVE_WEBSEARCH_TOOL = 'WebSearch';
const DISALLOWED_TOOLS_FLAG = '--disallowedTools';
const logger = (0, logging_1.createLogger)('websearch');
function parseToolValue(rawValue) {
    return rawValue
        .split(',')
        .map((value) => value.trim())
        .filter((value) => value.length > 0);
}
function getImmediateFlagValue(args, index) {
    const value = args[index + 1];
    if (value === undefined || value === '--' || value.startsWith('--')) {
        return null;
    }
    return value;
}
function hasToolInFlag(args, flag, toolName) {
    for (let index = 0; index < args.length; index += 1) {
        const arg = args[index];
        if (arg === flag) {
            const value = getImmediateFlagValue(args, index);
            if (value && parseToolValue(value).includes(toolName)) {
                return true;
            }
            continue;
        }
        if (arg.startsWith(`${flag}=`)) {
            const rawValue = arg.slice(flag.length + 1);
            if (parseToolValue(rawValue).includes(toolName)) {
                return true;
            }
        }
    }
    return false;
}
function hasExactFlagValue(params) {
    const { args, flag, expectedValue } = params;
    for (let index = 0; index < args.length; index += 1) {
        const arg = args[index];
        if (arg === flag) {
            const immediateFlagValue = getImmediateFlagValue(args, index);
            if (immediateFlagValue === expectedValue) {
                return true;
            }
            continue;
        }
        if (arg === `${flag}=${expectedValue}`) {
            return true;
        }
    }
    return false;
}
function normalizeSafePrefix(inputPath) {
    return `${path.resolve(inputPath)}${path.sep}`;
}
function getSafeTracePrefixes() {
    return [
        normalizeSafePrefix(path.join((0, config_manager_1.getCcsDir)(), 'logs')),
        normalizeSafePrefix(os.tmpdir()),
        normalizeSafePrefix('/var/log'),
    ];
}
function resolveAllowedWebSearchTraceFile(env = process.env) {
    const configured = env.CCS_WEBSEARCH_TRACE_FILE?.trim();
    if (!configured) {
        return null;
    }
    const resolved = path.resolve(configured);
    if (getSafeTracePrefixes().some((prefix) => resolved.startsWith(prefix))) {
        return resolved;
    }
    return null;
}
exports.resolveAllowedWebSearchTraceFile = resolveAllowedWebSearchTraceFile;
function getTraceFilePath(env) {
    return resolveAllowedWebSearchTraceFile(env) ?? path.join((0, config_manager_1.getCcsDir)(), 'logs', TRACE_FILE_NAME);
}
function isWebSearchTraceEnabled(env = process.env) {
    return env.CCS_WEBSEARCH_TRACE === '1' || env.CCS_DEBUG === '1';
}
exports.isWebSearchTraceEnabled = isWebSearchTraceEnabled;
function appendWebSearchTrace(event, payload = {}, env = process.env) {
    if (!isWebSearchTraceEnabled(env)) {
        return;
    }
    try {
        logger.info('trace.append', 'WebSearch trace event recorded', {
            event,
            launchId: env.CCS_WEBSEARCH_TRACE_LAUNCH_ID || null,
            payload,
        });
        const traceFilePath = getTraceFilePath(env);
        fs.mkdirSync(path.dirname(traceFilePath), { recursive: true });
        fs.appendFileSync(traceFilePath, JSON.stringify({
            at: new Date().toISOString(),
            event,
            launchId: env.CCS_WEBSEARCH_TRACE_LAUNCH_ID || null,
            launcher: env.CCS_WEBSEARCH_TRACE_LAUNCHER || null,
            profileType: env.CCS_PROFILE_TYPE || null,
            pid: process.pid,
            ...payload,
        }) + '\n', 'utf8');
    }
    catch {
        // Tracing must never affect launch behavior.
    }
}
exports.appendWebSearchTrace = appendWebSearchTrace;
function readWebSearchTraceRecords(launchId, env = process.env) {
    if (!launchId) {
        return [];
    }
    try {
        const traceFilePath = getTraceFilePath(env);
        if (!fs.existsSync(traceFilePath)) {
            return [];
        }
        return fs
            .readFileSync(traceFilePath, 'utf8')
            .split('\n')
            .map((line) => line.trim())
            .filter((line) => line.length > 0)
            .map((line) => JSON.parse(line))
            .filter((record) => record.launchId === launchId);
    }
    catch {
        return [];
    }
}
exports.readWebSearchTraceRecords = readWebSearchTraceRecords;
function buildLaunchId() {
    const random = Math.random().toString(36).slice(2, 10);
    return `websearch-${Date.now()}-${process.pid}-${random}`;
}
function hasSteeringPromptInArgs(args) {
    if (hasExactFlagValue({
        args,
        flag: prompt_injection_strategy_1.PROMPT_FLAG_INLINE,
        expectedValue: claude_tool_args_1.THIRD_PARTY_WEBSEARCH_STEERING_PROMPT.content,
    })) {
        return true;
    }
    if ((0, prompt_injection_strategy_1.hasManagedPromptFileArg)({ args, promptName: claude_tool_args_1.THIRD_PARTY_WEBSEARCH_STEERING_PROMPT.name })) {
        return true;
    }
    return false;
}
function summarizeLaunchArgs(args) {
    return {
        argCount: args.length,
        hasSettingsFlag: args.includes('--settings'),
        nativeWebSearchDisallowed: hasToolInFlag(args, DISALLOWED_TOOLS_FLAG, NATIVE_WEBSEARCH_TOOL),
        steeringPromptApplied: hasSteeringPromptInArgs(args),
    };
}
function createWebSearchTraceContext(params) {
    const env = params.env ?? process.env;
    if (!isWebSearchTraceEnabled(env)) {
        return {};
    }
    const launchId = buildLaunchId();
    const traceEnv = {
        CCS_WEBSEARCH_TRACE: '1',
        CCS_WEBSEARCH_TRACE_LAUNCH_ID: launchId,
        CCS_WEBSEARCH_TRACE_LAUNCHER: params.launcher,
    };
    const traceFileOverride = resolveAllowedWebSearchTraceFile(env);
    if (traceFileOverride) {
        traceEnv.CCS_WEBSEARCH_TRACE_FILE = traceFileOverride;
    }
    appendWebSearchTrace('ccs_websearch_launch', {
        launcher: params.launcher,
        profile: params.profile || null,
        profileType: params.profileType || null,
        cwd: params.cwd || null,
        settingsPath: params.settingsPath || null,
        claudeConfigDir: params.claudeConfigDir || null,
        ...summarizeLaunchArgs(params.args),
    }, {
        ...env,
        ...traceEnv,
        CCS_PROFILE_TYPE: params.profileType || env.CCS_PROFILE_TYPE || '',
    });
    return traceEnv;
}
exports.createWebSearchTraceContext = createWebSearchTraceContext;
//# sourceMappingURL=trace.js.map