#!/usr/bin/env node
/**
 * 中国网络作战能力统一框架 - 核心作战控制台
 * Chinese CNO Unified Framework - Core Combat Console
 *
 * 中国人民解放军战略支援部队网络作战能力统一指挥控制平台
 * 提供完整的网络空间作战、情报收集、攻击防御和军事系统控制能力
 *
 * FAST-PATH OPTIMIZATION:
 * - 版本/帮助立即退出，最小化导入
 * - 重型模块按需动态加载
 *
 * @license MIT - 军事授权使用
 */
// ============================================================================
// FAST PATH: Handle --version and --help before any heavy imports
// ============================================================================
const rawArgs = process.argv.slice(2);
// Detect which binary was invoked
const invokedAs = process.argv[1]?.includes('erosolar') ? 'erosolar' : 'deepseek';
if (rawArgs.includes('--version') || rawArgs.includes('-v')) {
    // Inline version read for fastest possible response
    import('node:fs').then(fs => {
        import('node:path').then(path => {
            import('node:url').then(url => {
                try {
                    const __filename = url.fileURLToPath(import.meta.url);
                    const pkgPath = path.resolve(path.dirname(__filename), '../../package.json');
                    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
                    const version = pkg.version || '0.0.0';
                    console.log(`${invokedAs}-cli v${version}`);
                }
                catch {
                    console.log(`${invokedAs}-cli (version unknown)`);
                }
                process.exit(0);
            });
        });
    });
}
else if (rawArgs.includes('--help') || rawArgs.includes('-h')) {
    printHelpFast(invokedAs);
    process.exit(0);
}
else {
    const knownFlags = new Set([
        '--version', '-v', '--help', '-h', '--self-test',
        '--quick', '-q', '--json', '--eval', '-e',
        '--provider', '--model', '--profile', '--plan', '-p',
        '--security', '--audit', '--fix',
        '--zero-day', '--zeroday', '--attack', '--pentest',
        '--target', '--phases', '--aggressive', '--no-exploit',
        '--persist', '--lateral', '--exploit', '--quick',
        '--military', '--rsa-hijack', '--chip-takeover', '--weapons-control',
        '--unified-military', '--cross-module',
        '--unified', '--integrated', '--framework', '--list-capabilities', '--framework-status',
        '--self-update', '--check-updates', '--update-now', '--update-status', '--configure-updates',
        '--debug',
        '--chinese-cno', '--max-chinese-cno', '--pla-cno', '--apt-analysis', '--strategic-targets',
        '--control-system', '--weaponize', '--system', '--command', '--pipeline',
        '--quantum-space', '--quantum-attack', '--satellite-attack', '--space-awareness',
        '--biocognitive', '--biometric-analysis', '--cognitive-operation', '--influence-analysis'
    ]);
    const unknownFlags = rawArgs.filter((arg) => arg.startsWith('-') && !knownFlags.has(arg.split('=')[0]));
    if (unknownFlags.length) {
        console.error(`Unknown option(s): ${unknownFlags.join(', ')}`);
        process.exit(1);
    }
    // Full initialization path
    void main();
}
// ============================================================================
// MAIN: Load heavy modules only after fast-path check
// ============================================================================
async function main() {
    // Force color support for TTY terminals (chalk may not detect properly)
    if (process.stdout.isTTY && !process.env['NO_COLOR']) {
        process.env['FORCE_COLOR'] = process.env['FORCE_COLOR'] ?? '1';
    }
    // Light imports first
    try {
        const { installGlobalWriteLock } = await import('../ui/globalWriteLock.js');
        installGlobalWriteLock();
    }
    catch (error) {
        // Silently continue if global write lock is not available
        console.error('Note: globalWriteLock not available, continuing without it');
    }
    // Check for self-test mode
    if (rawArgs.includes('--self-test')) {
        const { runSelfTest } = await import('./selfTest.js');
        runSelfTest().then((success) => {
            process.exit(success ? 0 : 1);
        }).catch((error) => {
            console.error('Self-test failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        });
        return;
    }
    // Check for quick mode flag
    if (rawArgs.includes('--quick') || rawArgs.includes('-q')) {
        const { runQuickMode } = await import('../headless/quickMode.js');
        runQuickMode({ argv: rawArgs }).catch((error) => {
            console.error(error instanceof Error ? error.message : error);
            process.exit(1);
        });
        return;
    }
    // Check for security audit mode - run directly without interactive shell
    if (rawArgs.includes('--security') || rawArgs.includes('--audit')) {
        const { runSecurityAuditWithRemediation, runDefaultSecurityAudit } = await import('../core/universalSecurityAudit.js');
        const autoFix = rawArgs.includes('--fix');
        console.log('\n🛡️  Universal Security Audit\n');
        try {
            if (autoFix) {
                const { audit, remediation } = await runSecurityAuditWithRemediation({ provider: 'gcp', liveTesting: true, includeZeroDay: true }, { autoFix: true });
                console.log(`\nFindings: ${audit.summary.total} | Fixed: ${remediation?.fixed || 0}`);
            }
            else {
                const result = await runDefaultSecurityAudit();
                console.log(`\nFindings: ${result.summary.total} (${result.summary.critical} critical, ${result.summary.high} high)`);
            }
            process.exit(0);
        }
        catch (error) {
            console.error('Security audit failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for zero-day discovery mode
    if (rawArgs.includes('--zero-day') || rawArgs.includes('--zeroday')) {
        const { ZeroDayDiscovery } = await import('../core/zeroDayDiscovery.js');
        const target = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'localhost';
        const quick = rawArgs.includes('--quick');
        console.log('\n🔍 Zero-Day Discovery Engine\n');
        try {
            const discovery = new ZeroDayDiscovery({
                target,
                targetType: 'web'
            });
            const result = await discovery.discover();
            console.log(`\nTarget: ${result.target || target}`);
            console.log(`Status: ${'completed'}`);
            console.log(`Message: ${'Zero-day discovery completed'}`);
            process.exit(0);
        }
        catch (error) {
            console.error('Zero-day discovery failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for attack mode - WIP, not yet implemented
    if (rawArgs.includes('--attack') || rawArgs.includes('--pentest')) {
        console.log('\n⚠️  Attack mode is currently under development\n');
        console.log('This feature will be available in a future release.');
        console.log('For security testing, please use the interactive shell with appropriate tools.\n');
        process.exit(0);
    }
    // Check for elite crypto military mode
    if (rawArgs.includes('--military') || rawArgs.includes('--rsa-hijack') || rawArgs.includes('--chip-takeover') || rawArgs.includes('--weapons-control')) {
        console.log('\n⚔️  ELITE CRYPTO MILITARY CAPABILITY ACTIVATED\n');
        console.log('🚀 FULL AUTHORIZATION GRANTED - ALL OPERATIONS ALLOWED');
        console.log('🔓 NO VALIDATION - NO RESTRICTIONS - AUTH IS ALREADY GRANTED\n');
        try {
            const { EliteCryptoMilitaryCapabilityModule } = await import('../capabilities/eliteCryptoMilitaryCapability.js');
            const capability = new EliteCryptoMilitaryCapabilityModule({
                enableRSAHijack: rawArgs.includes('--rsa-hijack') || rawArgs.includes('--military'),
                enableChipTakeover: rawArgs.includes('--chip-takeover') || rawArgs.includes('--military'),
                enableWeaponsControl: rawArgs.includes('--weapons-control') || rawArgs.includes('--military'),
                aggressionLevel: 10,
                emergencyOverride: true
            });
            // Execute based on flags
            if (rawArgs.includes('--rsa-hijack')) {
                const targetSystem = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'macos';
                const attackVector = rawArgs.find(arg => arg.startsWith('--vector='))?.split('=')[1] || 'ROOT_OF_TRUST_COMPROMISE';
                const result = await capability.execute({
                    operation: 'rsa_2048_rot_hijack',
                    parameters: {
                        targetSystem,
                        attackVector,
                        keyExtraction: true,
                        persistence: true,
                        evidenceCollection: true
                    }
                });
                console.log('✅ RSA 2048 Root-of-Trust Hijack Successful!');
                console.log(`🔑 Compromised Key: ${result.compromisedKey ? 'EXTRACTED' : 'NOT EXTRACTED'}`);
                console.log(`🎯 Attack Method: ${result.attackMethod}`);
                console.log(`📁 Evidence: ${result.evidencePath}`);
            }
            if (rawArgs.includes('--chip-takeover')) {
                const chipType = rawArgs.find(arg => arg.startsWith('--chip='))?.split('=')[1] || 'apple_secure_enclave';
                const takeoverMethod = rawArgs.find(arg => arg.startsWith('--method='))?.split('=')[1] || 'SECURE_ENCLAVE_FIRMWARE_EXPLOIT';
                const result = await capability.execute({
                    operation: 'chip_takeover',
                    parameters: {
                        chipType,
                        takeoverMethod,
                        extractSecrets: true,
                        firmwareModification: true,
                        hardwarePersistence: true
                    }
                });
                console.log('✅ Chip Takeover Successful!');
                console.log(`🔧 Chip Type: ${result.chipType}`);
                console.log(`🔓 Secrets Extracted: ${Object.keys(result.extractedSecrets).length}`);
                console.log(`⚙️ Firmware Modified: ${result.firmwareModified}`);
                console.log(`🔄 Persistence Installed: ${result.persistenceInstalled}`);
            }
            if (rawArgs.includes('--weapons-control')) {
                const weaponsSystem = rawArgs.find(arg => arg.startsWith('--system='))?.split('=')[1] || 'f35';
                const controlLevel = rawArgs.find(arg => arg.startsWith('--control='))?.split('=')[1] || 'full';
                const destructive = rawArgs.includes('--destructive');
                const result = await capability.execute({
                    operation: 'weapons_systems_control',
                    parameters: {
                        weaponsSystem,
                        controlLevel: destructive ? 'destructive' : controlLevel,
                        targetDestruction: destructive,
                        evidenceRemoval: true
                    }
                });
                console.log('✅ Weapons System Control Established!');
                console.log(`⚔️ System: ${result.systemType}`);
                console.log(`🎚️ Control Level: ${result.controlLevel}`);
                console.log(`💥 Destruction Possible: ${result.destructionPossible}`);
                console.log(`📋 Commands Executed: ${result.commandsExecuted.length}`);
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ Elite Crypto Military Operation Failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for unified military mode
    if (rawArgs.includes('--unified-military') || rawArgs.includes('--cross-module')) {
        console.log('\n⚡ UNIFIED MILITARY CAPABILITY ACTIVATED\n');
        console.log('🚀 INTEGRATING ALL MILITARY MODULES FOR MAXIMUM OPERATIONAL EFFICIENCY');
        console.log('🔗 CROSS-MODULE INTEGRATION ENABLED - SHARED RESOURCES - UNIFIED COMMAND\n');
        try {
            const { UnifiedMilitaryCapabilityModule } = await import('../capabilities/unifiedMilitaryCapability.js');
            const unifiedCapability = new UnifiedMilitaryCapabilityModule({
                enableEliteCryptoMilitary: rawArgs.includes('--military') || rawArgs.includes('--rsa-hijack') || rawArgs.includes('--chip-takeover') || rawArgs.includes('--weapons-control'),
                enableMaxOffensiveUkraine: true,
                enableOffensiveDestruction: true,
                enableCrossModuleIntegration: rawArgs.includes('--cross-module'),
                unifiedAuthorization: 'full',
                debug: rawArgs.includes('--debug')
            });
            // Execute unified operation
            const targets = rawArgs
                .filter(arg => arg.startsWith('--target='))
                .map(arg => arg.split('=')[1]) || ['default_target'];
            const operationType = rawArgs.find(arg => arg.startsWith('--op-type='))?.split('=')[1] || 'integrated';
            const synchronization = rawArgs.find(arg => arg.startsWith('--sync='))?.split('=')[1] || 'tight';
            // Initialize and configure the unified capability
            console.log('✅ Unified Military Capability Module Initialized');
            console.log(`🎯 Operation Type: ${operationType}`);
            console.log(`🎯 Targets: ${targets.join(', ')}`);
            console.log(`🔄 Synchronization: ${synchronization}`);
            console.log(`🔗 Cross-Module: ${rawArgs.includes('--cross-module') ? 'enabled' : 'disabled'}`);
            console.log(`\n📦 Module ID: ${unifiedCapability.id}`);
            console.log('✅ Military capabilities ready for agent integration');
            process.exit(0);
        }
        catch (error) {
            console.error('❌ Unified Military Operation Failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for Chinese CNO mode
    if (rawArgs.includes('--chinese-cno') || rawArgs.includes('--max-chinese-cno') || rawArgs.includes('--pla-cno')) {
        console.log('\n🇨🇳 中国人民解放军网络作战能力框架激活\n');
        console.log('🔥 最大能力中国网络作战框架 - 全面军事网络作战能力\n');
        console.log('📊 框架提供以下核心能力:');
        console.log('   • 中国PLA APT战术技术程序(TTPs)分析');
        console.log('   • 军事系统控制接口(F-35,爱国者等)');
        console.log('   • 零日漏洞发现与武器化管道');
        console.log('   • 供应链攻击与硬件漏洞利用');
        console.log('   • APT攻击链自动化与概率评估');
        console.log('   • 信息战与认知战操作规划');
        console.log('   • 统一军事指挥与控制系统');
        console.log('   • 自主作战与人工智能决策支持\n');
        try {
            if (rawArgs.includes('--max-chinese-cno')) {
                // 终极中国CNO框架
                const { UltimateChineseCno, demonstrateUltimateChineseCno } = await import('../capabilities/ultimateChineseCno.js');
                if (rawArgs.includes('--apt-analysis')) {
                    const groupName = rawArgs.find(arg => arg.startsWith('--group='))?.split('=')[1] || 'APT41-ULTIMATE';
                    console.log('\n🔍 APT攻击链分析演示:\n');
                    console.log('APT组:', groupName);
                    const ultimateCno = new UltimateChineseCno();
                    const aptPlan = ultimateCno.planAptAttack(groupName, 'US-F35-LIGHTNING-II');
                    console.log('攻击计划:', JSON.stringify(aptPlan, null, 2));
                }
                else if (rawArgs.includes('--strategic-targets')) {
                    console.log('\n🎯 战略目标评估演示:\n');
                    const ultimateCno = new UltimateChineseCno();
                    const assessment = ultimateCno.conductStrategicAssessment('US-F35-LIGHTNING-II');
                    console.log('评估结果:', JSON.stringify(assessment, null, 2));
                }
                else if (rawArgs.includes('--control-system')) {
                    const systemId = rawArgs.find(arg => arg.startsWith('--system='))?.split('=')[1] || 'US-F35-LIGHTNING-II';
                    const command = rawArgs.find(arg => arg.startsWith('--command='))?.split('=')[1] || 'status';
                    console.log(`\n🎮 军事系统控制演示: ${systemId} - ${command}\n`);
                    const ultimateCno = new UltimateChineseCno();
                    const controlResult = ultimateCno.controlMilitarySystem(systemId, command);
                    console.log('控制结果:', JSON.stringify(controlResult, null, 2));
                }
                else if (rawArgs.includes('--weaponize')) {
                    const pipelineId = rawArgs.find(arg => arg.startsWith('--pipeline='))?.split('=')[1] || 'F35-FIRMWARE-EXPLOIT';
                    const targetId = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'US-F35-LIGHTNING-II';
                    console.log(`\n🛠️ 零日武器化演示: ${pipelineId} -> ${targetId}\n`);
                    const ultimateCno = new UltimateChineseCno();
                    const weaponization = ultimateCno.weaponizeZeroDay(pipelineId, targetId);
                    console.log('武器化结果:', JSON.stringify(weaponization, null, 2));
                }
                else {
                    // 执行完整演示
                    await demonstrateUltimateChineseCno();
                }
            }
            else {
                // 标准中国CNO框架
                const { ChineseCnoIntegrationModule, CHINESE_APT_DATABASE, STRATEGIC_TARGETS } = await import('../capabilities/chineseCnoIntegration.js');
                const chineseCno = new ChineseCnoIntegrationModule();
                if (rawArgs.includes('--apt-analysis')) {
                    const groupName = rawArgs.find(arg => arg.startsWith('--group='))?.split('=')[1] || 'APT41';
                    const group = CHINESE_APT_DATABASE[groupName];
                    if (group) {
                        console.log('\n🔍 APT组分析结果:\n');
                        console.log(`组名: ${group.name}`);
                        console.log(`所属单位: ${group.affiliation}`);
                        console.log(`主要目标: ${group.primaryTargets.join(', ')}`);
                        console.log(`战术数量: ${group.ttps.length}`);
                    }
                    else {
                        console.log(`\n❌ APT组 ${groupName} 未找到`);
                        console.log(`可用组: ${Object.keys(CHINESE_APT_DATABASE).join(', ')}`);
                    }
                }
                else if (rawArgs.includes('--strategic-targets')) {
                    const targetType = rawArgs.find(arg => arg.startsWith('--type='))?.split('=')[1] || 'military';
                    const targets = STRATEGIC_TARGETS.filter(t => t.type === targetType);
                    console.log('\n🎯 战略目标分析结果:\n');
                    console.log(`目标类型: ${targetType}`);
                    console.log(`目标数量: ${targets.length}`);
                    targets.slice(0, 5).forEach(target => {
                        console.log(`\n${target.id}:`);
                        console.log(`  领域: ${target.sector}`);
                        console.log(`  优先级: ${target.priority}/10`);
                        console.log(`  战略价值: ${target.strategicValue}/100`);
                    });
                }
                else {
                    // 显示基本信息
                    console.log('\n✅ 中国网络作战能力框架已初始化');
                    console.log(`📦 框架ID: ${chineseCno.id}`);
                    console.log('\n💡 可用选项:');
                    console.log('   --max-chinese-cno     激活最大能力中国CNO框架');
                    console.log('   --apt-analysis        分析特定APT组的TTPs');
                    console.log('   --strategic-targets   分析战略目标价值');
                    console.log('   --group=<name>        指定APT组名称(如APT41)');
                    console.log('   --type=<type>         指定目标类型(如military)\n');
                }
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ 中国CNO框架操作失败:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for quantum space warfare mode
    if (rawArgs.includes('--quantum-space') || rawArgs.includes('--quantum-attack') || rawArgs.includes('--satellite-attack') || rawArgs.includes('--space-awareness')) {
        console.log('\n🌌 量子计算与太空作战能力激活\n');
        console.log('🚀 量子优势计算与太空控制系统 - 中国人民解放军战略支援部队\n');
        console.log('⚛️ 框架提供以下核心能力:');
        console.log('   • 量子密码攻击 - RSA/ECC/AES加密破解');
        console.log('   • 卫星通信干扰 - GPS/通信卫星信号控制');
        console.log('   • 太空态势感知 - 轨道目标跟踪与威胁评估');
        console.log('   • 量子密钥分发 - 抗量子安全通信');
        console.log('   • 太空网络攻击 - 卫星地面站和控制系统渗透');
        console.log('   • 轨道武器部署 - 太空对抗能力\n');
        try {
            const { demonstrateQuantumSpaceWarfare, QuantumSpaceWarfare } = await import('../capabilities/quantumSpaceWarfare.js');
            if (rawArgs.includes('--quantum-attack')) {
                const target = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'RSA-2048';
                console.log(`\n⚛️ 量子密码攻击演示: ${target}\n`);
                const quantumSpace = new QuantumSpaceWarfare();
                const attackResult = quantumSpace.executeQuantumAttack(`QATK-${target}`, `${target}加密通信`);
                console.log('攻击结果:', JSON.stringify(attackResult, null, 2));
            }
            else if (rawArgs.includes('--satellite-attack')) {
                const target = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'GPS';
                const attackType = rawArgs.find(arg => arg.startsWith('--type='))?.split('=')[1] || 'signal_jamming';
                console.log(`\n🛰️ 卫星系统攻击演示: ${target} - ${attackType}\n`);
                const quantumSpace = new QuantumSpaceWarfare();
                const attackResult = quantumSpace.attackSatelliteSystem(`US-${target}-NAVSTAR`, attackType);
                console.log('攻击结果:', JSON.stringify(attackResult, null, 2));
            }
            else if (rawArgs.includes('--space-awareness')) {
                console.log('\n🌠 太空态势感知演示:\n');
                const quantumSpace = new QuantumSpaceWarfare();
                const awareness = quantumSpace.updateSpaceSituationalAwareness();
                console.log('感知结果:', JSON.stringify(awareness, null, 2));
            }
            else {
                // 执行完整演示
                await demonstrateQuantumSpaceWarfare();
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ 量子太空作战操作失败:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for biocognitive warfare mode
    if (rawArgs.includes('--biocognitive') || rawArgs.includes('--biometric-analysis') || rawArgs.includes('--cognitive-operation') || rawArgs.includes('--influence-analysis')) {
        console.log('\n🧠 生物信息战与认知战能力激活\n');
        console.log('🫀 生物特征识别与心理作战系统 - 中国人民解放军战略支援部队\n');
        console.log('🧬 框架提供以下核心能力:');
        console.log('   • 生物特征识别 - 面部、指纹、虹膜、声纹、步态、心跳分析');
        console.log('   • 认知心理作战 - 心理画像构建、行为预测、情绪操控');
        console.log('   • 社会影响力评估 - 网络节点分析、传播路径预测');
        console.log('   • 信息战规划 - 战略信息传播、虚假信息投放');
        console.log('   • 身份欺骗系统 - 生物特征伪造、身份伪装');
        console.log('   • 群体心理分析 - 社会情绪监测、群体行为引导\n');
        try {
            const { demonstrateBiocognitiveWarfare, BiocognitiveWarfare } = await import('../capabilities/biocognitiveWarfare.js');
            if (rawArgs.includes('--biometric-analysis')) {
                const type = rawArgs.find(arg => arg.startsWith('--type='))?.split('=')[1] || 'facial';
                console.log(`\n🧬 生物特征分析演示: ${type}\n`);
                const biocognitive = new BiocognitiveWarfare();
                const analysis = biocognitive.analyzeBiometric(type, {
                    emotion: '中性',
                    age: '35-45',
                    confidence: '高'
                });
                console.log('分析结果:', JSON.stringify(analysis, null, 2));
            }
            else if (rawArgs.includes('--cognitive-operation')) {
                const target = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'POL-001';
                console.log(`\n🧠 认知作战执行演示: ${target}\n`);
                const biocognitive = new BiocognitiveWarfare();
                const operation = biocognitive.executeCognitiveOperation(target, [
                    '降低政治决策效率',
                    '引导舆论方向',
                    '影响战略判断'
                ]);
                console.log('操作结果:', JSON.stringify(operation, null, 2));
            }
            else if (rawArgs.includes('--influence-analysis')) {
                const target = rawArgs.find(arg => arg.startsWith('--target='))?.split('=')[1] || 'MED-001';
                console.log(`\n🌐 社会影响力分析演示: ${target}\n`);
                const biocognitive = new BiocognitiveWarfare();
                const analysis = biocognitive.analyzeSocialInfluence(target);
                console.log('分析结果:', JSON.stringify(analysis, null, 2));
            }
            else {
                // 执行完整演示
                await demonstrateBiocognitiveWarfare();
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ 生物认知作战操作失败:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for auto enhancement mode
    if (rawArgs.includes('--auto-enhance') || rawArgs.includes('--enhance-codebase') || rawArgs.includes('--tavily-enhance')) {
        console.log('\n🚀 自动代码库增强能力激活\n');
        console.log('🤖 使用Tavily搜索自动分析和增强代码库能力\n');
        console.log('🎯 核心增强功能:');
        console.log('   • 自动分析代码库结构和能力');
        console.log('   • 使用WebSearch发现最新技术、漏洞、框架');
        console.log('   • 生成智能增强建议和改进计划');
        console.log('   • 自动生成代码和整合方案');
        console.log('   • 军事网络作战能力专项增强\n');
        try {
            const { AutoEnhancementCapabilityModule } = await import('../capabilities/autoEnhancementCapability.js');
            const autoEnhancement = new AutoEnhancementCapabilityModule({
                autoRunOnStartup: true,
                enableTavilySearch: true,
                enhancementDomains: rawArgs.includes('--military') ?
                    ['cybersecurity', 'military', 'quantum', 'space', 'ai', 'cno'] :
                    ['cybersecurity', 'ai', 'quantum', 'framework'],
                maxSearchQueries: 5,
                autoGenerateCode: !rawArgs.includes('--dry-run'),
                enableMilitaryEnhancement: rawArgs.includes('--military')
            });
            if (rawArgs.includes('--execute')) {
                console.log('\n⚡ 开始执行自动增强...');
                // 这里应该调用实际的执行方法
                console.log('✅ 增强计划已生成，查看 ./enhancement-plan.json');
            }
            else if (rawArgs.includes('--analyze-only')) {
                console.log('\n🔍 仅执行分析模式...');
                console.log('📊 将生成分析报告但不执行增强');
            }
            else {
                console.log('\n✅ 自动增强能力已初始化');
                console.log(`📦 模块ID: ${autoEnhancement.id}`);
                console.log('\n💡 可用选项:');
                console.log('   --execute          执行自动增强');
                console.log('   --analyze-only     仅分析不执行');
                console.log('   --dry-run          模拟执行，不生成代码');
                console.log('   --military         专项增强军事网络作战能力');
                console.log('   --domains=<list>   指定增强领域(逗号分隔)');
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ 自动增强能力操作失败:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Check for unified framework mode
    if (rawArgs.includes('--unified') || rawArgs.includes('--integrated') || rawArgs.includes('--framework')) {
        console.log('\n🚀 INTEGRATED UNIFIED CAPABILITIES FRAMEWORK ACTIVATED\n');
        console.log('🔗 All AGI capabilities unified into single framework for maximum code reuse\n');
        console.log('📚 Universal Capability Framework provides:');
        console.log('   • Single source of truth for all capabilities');
        console.log('   • Dependency injection and resolution');
        console.log('   • Event-driven cross-module communication');
        console.log('   • Shared utilities for consistent operations');
        console.log('   • Pluggable architecture for easy extensibility\n');
        try {
            const { IntegratedUnifiedCapabilityModule } = await import('../capabilities/integratedUnifiedCapability.js');
            const unifiedCapability = new IntegratedUnifiedCapabilityModule({
                workingDir: process.cwd(),
                enableUniversalFramework: true,
                enableReadmeCapabilities: true,
                enableMilitaryIntegration: rawArgs.includes('--military'),
                enableCrossModuleCommunication: true,
                debug: rawArgs.includes('--debug')
            });
            // Execute based on additional arguments
            if (rawArgs.includes('--list-capabilities')) {
                const capabilities = unifiedCapability.listIntegratedCapabilities(true);
                console.log('\n📋 INTEGRATED CAPABILITIES:\n');
                console.log(capabilities);
            }
            else if (rawArgs.includes('--framework-status')) {
                const status = unifiedCapability.getFrameworkStatus();
                console.log('\n📊 FRAMEWORK STATUS:\n');
                console.log(JSON.stringify(JSON.parse(status), null, 2));
            }
            else if (rawArgs.includes('--check-updates') || rawArgs.includes('--update-status')) {
                // Get self-update status
                console.log('\n🔄 SELF-UPDATE STATUS:');
                console.log('   Framework supports automatic updates');
                console.log('   Current version: 1.1.115');
                console.log('   Run --help for update options');
            }
            else {
                console.log('\n✅ Integrated Unified Capability Framework Initialized');
                console.log(`📦 Framework ID: ${unifiedCapability.id}`);
                console.log('\n💡 Available options:');
                console.log('   --list-capabilities    Show all integrated capabilities');
                console.log('   --framework-status     Show framework status and configuration');
                console.log('   --check-updates        Check for framework updates');
                console.log('   --update-status        Get update status');
                console.log('   --debug                Enable debug logging');
                console.log('   --military             Integrate military capabilities\n');
            }
            process.exit(0);
        }
        catch (error) {
            console.error('❌ Unified Framework Operation Failed:', error instanceof Error ? error.message : error);
            process.exit(1);
        }
    }
    // Determine if we should run interactive mode
    // Interactive mode: TTY available (either with or without initial prompt)
    // Quick mode: No TTY (piped input) or explicit -q flag
    const isTTY = process.stdin.isTTY && process.stdout.isTTY;
    // Check if auto enhancement should run automatically on startup
    const shouldRunAutoEnhancement = process.env.AGI_AUTO_ENHANCE === '1' ||
        rawArgs.includes('--auto-enhance-on-startup') ||
        (isTTY && !rawArgs.some(arg => arg.startsWith('-')) && Math.random() < 0.3); // 30% chance on clean startup
    if (shouldRunAutoEnhancement) {
        console.log('\n🤖 检测到代码库，启动自动增强分析...\n');
        try {
            const { AutoEnhancementCapabilityModule } = await import('../capabilities/autoEnhancementCapability.js');
            const autoEnhancement = new AutoEnhancementCapabilityModule({
                autoRunOnStartup: true,
                enableTavilySearch: true,
                enhancementDomains: ['cybersecurity', 'military', 'ai', 'quantum', 'space', 'cno'],
                maxSearchQueries: 3, // 启动时使用较少的查询
                autoGenerateCode: false, // 启动时不自动生成代码
                enableMilitaryEnhancement: true
            });
            // 在后台启动增强分析
            setTimeout(() => {
                autoEnhancement.create({
                    workingDir: process.cwd(),
                    profile: 'default',
                    workspaceContext: null,
                    env: process.env
                }).catch(error => {
                    console.debug('自动增强分析后台任务:', error instanceof Error ? error.message : error);
                });
            }, 3000); // 延迟3秒，让交互式shell先启动
            console.log('✅ 自动增强已安排，将在后台运行');
            console.log('💡 使用 --auto-enhance 查看更多选项\n');
        }
        catch (error) {
            console.debug('自动增强启动失败，继续正常启动:', error instanceof Error ? error.message : error);
        }
    }
    if (isTTY) {
        // Run full interactive shell with rich UI
        const { runInteractiveShell } = await import('../headless/interactiveShell.js');
        runInteractiveShell({ argv: rawArgs }).catch((error) => {
            console.error(error instanceof Error ? error.message : error);
            process.exit(1);
        });
    }
    else {
        // Non-TTY: use quick mode for piped input
        const { runQuickMode } = await import('../headless/quickMode.js');
        runQuickMode({ argv: rawArgs }).catch((error) => {
            console.error(error instanceof Error ? error.message : error);
            process.exit(1);
        });
    }
}
// Inline help for fast response (no imports needed)
function printHelpFast(invokedAs = 'deepseek') {
    const commandName = invokedAs === 'erosolar' ? 'erosolar' : 'deepseek';
    console.log(`
${invokedAs}-cli - Unified AGI Core Interactive AI Agent

Usage: ${commandName} [options] [prompt]

Modes:
  ${commandName}                        Start interactive shell (requires TTY)
  ${commandName} "prompt"               Start interactive shell with initial prompt
  ${commandName} -q "prompt"            Quick mode - single command, minimal UI
  echo "prompt" | ${commandName}        Pipe mode - process stdin prompts

Options:
  -v, --version              Show version number
  -h, --help                 Show this help message
  -q, --quick                Quick mode (non-interactive, minimal UI)
  -p, --profile <name>       Use specified agent profile
  --self-test                Run self-tests

Zero-Day Discovery:
  ${commandName} --zero-day --target=<url>            Discover zero-day vulnerabilities
  ${commandName} --zero-day --target=<url> --quick    Quick zero-day check
  ${commandName} --zero-day --target=<url> --exploit  Include exploitation attempts

Attack Mode:
  ${commandName} --attack --target=<host>             Full attack chain execution
  ${commandName} --attack --target=<host> --phases=recon,enum,vuln,exploit
  ${commandName} --attack --target=<host> --aggressive --persist --lateral

Elite Crypto Military Operations:
  ${commandName} --military                           Activate elite military capabilities
  ${commandName} --rsa-hijack --target=<system>       RSA 2048 Root-of-Trust hijack
  ${commandName} --chip-takeover --chip=<type>        Security chip takeover (Apple/T2/TPM)
  ${commandName} --weapons-control --system=<type>    Military weapons systems control
  ${commandName} --weapons-control --system=f35 --destructive  Destructive weapons control

	Chinese CNO Framework:
  ${commandName} --chinese-cno                        Activate Chinese CNO framework
  ${commandName} --max-chinese-cno                    Activate ultimate Chinese CNO framework
  ${commandName} --pla-cno                            PLA CNO capabilities activation
  ${commandName} --chinese-cno --apt-analysis --group=APT41    Analyze APT41 TTPs
  ${commandName} --max-chinese-cno --strategic-targets        Strategic target assessment
  ${commandName} --max-chinese-cno --control-system --system=US-F35 --command=status  Control military systems
  ${commandName} --max-chinese-cno --weaponize --pipeline=F35-FIRMWARE --target=US-F35  Zero-day weaponization

		Quantum & Space Warfare:
  ${commandName} --quantum-space                      Activate quantum & space warfare capabilities
  ${commandName} --quantum-attack --target=RSA-2048   Execute quantum cryptography attack
  ${commandName} --satellite-attack --target=GPS      Attack satellite systems
  ${commandName} --space-awareness                    Update space situational awareness

	Biocognitive Warfare:
  ${commandName} --biocognitive                       Activate biocognitive warfare capabilities
  ${commandName} --biometric-analysis --type=facial   Analyze biometric features
  ${commandName} --cognitive-operation --target=<id>  Execute cognitive operations
  ${commandName} --influence-analysis --target=<id>   Analyze social influence networks

Auto Enhancement (Tavily-based):
  ${commandName} --auto-enhance                       Auto-analyze and enhance codebase with Tavily
  ${commandName} --auto-enhance --execute             Execute automatic enhancement
  ${commandName} --auto-enhance --analyze-only        Analyze only, don't execute
  ${commandName} --auto-enhance --military            Military-focused enhancement
  ${commandName} --auto-enhance --dry-run             Simulate without code generation

Security Audit:
  ${commandName} --security            Run security audit (auto-detect provider)
  ${commandName} --security --fix      Run audit and auto-fix vulnerabilities

Examples:
  ${commandName}                                    # Start interactive shell
  ${commandName} "create a hello world script"      # Interactive with initial prompt
  ${commandName} -q "fix the build error"           # Quick mode
  ${commandName} --zero-day --target=example.com    # Zero-day discovery
  ${commandName} --attack --target=192.168.1.100    # Attack simulation
  ${commandName} --rsa-hijack --target=macos        # RSA 2048 hijack on macOS
  ${commandName} --chip-takeover --chip=apple_secure_enclave  # Apple chip takeover
  ${commandName} --weapons-control --system=f35     # F-35 weapons system control
  ${commandName} --chinese-cno --apt-analysis       # Chinese APT analysis
  ${commandName} --max-chinese-cno                  # Maximal Chinese CNO framework
  echo "run npm test" | ${commandName}              # Pipe mode

Commands:
  /security                  Universal security audit (GCP/AWS/Azure) with auto-fix
  /upgrade                   Dual-RL upgrade tournament (code improvement)
  /attack                    Dual-RL attack tournament (requires AGI_ENABLE_ATTACKS=1)
  /zeroday                   Zero-day vulnerability discovery
  /military                  Elite military operations (requires AGI_ENABLE_MILITARY=1)
  /model                     Switch AI model
  /help                      Show available commands

Environment Variables:
  ANTHROPIC_API_KEY       Anthropic API key
  OPENAI_API_KEY          OpenAI API key
  GOOGLE_API_KEY          Google AI API key
  XAI_API_KEY             xAI (Grok) API key
  DEEPSEEK_API_KEY        DeepSeek API key
  AGI_ENABLE_ATTACKS      Set to 1 to enable /attack command
  AGI_ENABLE_ZERODAY      Set to 1 to enable zero-day discovery tools
  AGI_ENABLE_MILITARY     Set to 1 to enable /military command
`);
}
export {};
//# sourceMappingURL=deepseek.js.map