"use strict";
/**
 * Claude Launcher — Concern H
 *
 * Handles final argument assembly, trace context injection, Windows shell
 * escaping, spawning the Claude CLI process, starting the runtime quota
 * monitor, and wiring up cleanup handlers.
 */
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.launchClaude = void 0;
const child_process_1 = require("child_process");
const os = __importStar(require("os"));
const shell_executor_1 = require("../../utils/shell-executor");
const config_generator_1 = require("../config/config-generator");
const websearch_manager_1 = require("../../utils/websearch-manager");
const image_analysis_1 = require("../../utils/image-analysis");
const browser_1 = require("../../utils/browser");
const account_manager_1 = require("../accounts/account-manager");
const session_bridge_1 = require("./session-bridge");
const account_resolution_1 = require("./account-resolution");
const claude_subcommand_detector_1 = require("../../utils/claude-subcommand-detector");
/**
 * Assemble final Claude CLI arguments, inject trace context, spawn the process,
 * start the runtime quota monitor, and wire cleanup handlers.
 *
 * @returns The spawned ChildProcess for the Claude CLI.
 */
async function launchClaude(context) {
    const { claudeCli, claudeArgs, env, cfg, provider, compositeProviders, skipLocalAuth, sessionId, imageAnalysisMcpReady, browserRuntimeEnv, inheritedClaudeConfigDir, codexReasoningProxy, toolSanitizationProxy, httpsTunnel, verbose, } = context;
    const isWindows = process.platform === 'win32';
    const needsShell = isWindows && /\.(cmd|bat|ps1)$/i.test(claudeCli);
    const settingsPath = cfg.customSettingsPath
        ? cfg.customSettingsPath.replace(/^~/, os.homedir())
        : (0, config_generator_1.getProviderSettingsPath)(provider);
    // Claude subcommands (agents, doctor, mcp, ...) don't accept `--settings` —
    // its presence flips `agents` into list mode instead of opening the
    // interactive agent view. Provider routing still flows via env vars.
    // Issue #1218.
    const isSubcommand = (0, claude_subcommand_detector_1.isClaudeSubcommandInvocation)(claudeArgs);
    const claudeSessionArgs = isSubcommand
        ? (0, claude_subcommand_detector_1.stripClaudeSubcommandSessionArgs)(claudeArgs)
        : claudeArgs;
    // Assemble final args: image analysis tools → browser tools → web search tools → settings
    const imageAnalysisArgs = imageAnalysisMcpReady
        ? (0, image_analysis_1.appendThirdPartyImageAnalysisToolArgs)(claudeSessionArgs)
        : claudeSessionArgs;
    const browserArgs = browserRuntimeEnv
        ? (0, browser_1.appendBrowserToolArgs)(imageAnalysisArgs)
        : imageAnalysisArgs;
    const launchArgs = isSubcommand
        ? (0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(browserArgs)
        : ['--settings', settingsPath, ...(0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(browserArgs)];
    // Inject web search trace context into env
    const traceEnv = (0, websearch_manager_1.createWebSearchTraceContext)({
        launcher: 'cliproxy.executor',
        args: launchArgs,
        profile: cfg.profileName || provider,
        profileType: 'cliproxy',
        settingsPath,
        claudeConfigDir: inheritedClaudeConfigDir,
    });
    const baseTracedEnv = (0, claude_subcommand_detector_1.stripClaudeCodeFeatureBlockingEnv)({ ...env, ...traceEnv });
    // Strip telemetry-disable env vars for subcommands; otherwise Claude's
    // `agents`/`mcp`/... TUIs silently fall back to non-interactive list mode.
    // Issue #1218.
    const tracedEnv = isSubcommand ? (0, claude_subcommand_detector_1.stripSubcommandBlockingEnv)(baseTracedEnv) : baseTracedEnv;
    // Spawn: Windows .cmd/.bat/.ps1 need shell escaping; all others spawn directly
    let claude;
    if (needsShell) {
        const cmdString = [claudeCli, ...launchArgs].map(shell_executor_1.escapeShellArg).join(' ');
        claude = (0, child_process_1.spawn)(cmdString, {
            stdio: 'inherit',
            windowsHide: true,
            shell: (0, shell_executor_1.getWindowsEscapedCommandShell)(),
            env: tracedEnv,
        });
    }
    else {
        claude = (0, child_process_1.spawn)(claudeCli, launchArgs, {
            stdio: 'inherit',
            windowsHide: true,
            env: tracedEnv,
        });
    }
    // Start runtime quota monitor (adaptive polling during session)
    if (!skipLocalAuth) {
        const { startQuotaMonitor } = await Promise.resolve().then(() => __importStar(require('../quota/quota-manager')));
        for (const monitorProvider of (0, account_resolution_1.resolveRuntimeQuotaMonitorProviders)(provider, compositeProviders)) {
            const monitorAccount = (0, account_manager_1.getDefaultAccount)(monitorProvider);
            if (monitorAccount) {
                startQuotaMonitor(monitorProvider, monitorAccount.id);
            }
        }
    }
    // Wire cleanup handlers (process exit, SIGINT, SIGTERM, proxy teardown)
    (0, session_bridge_1.setupCleanupHandlers)(claude, sessionId, cfg.port, codexReasoningProxy, toolSanitizationProxy, httpsTunnel, verbose);
    return claude;
}
exports.launchClaude = launchClaude;
//# sourceMappingURL=claude-launcher.js.map