#!/usr/bin/env node import { Command } from 'commander'; import { authorizeHeadless, isDaemonRunning, getConfig, explainPolicy, pauseNode9, resumeNode9, checkPause, } from './core'; import { setupClaude, setupGemini, setupAntigravity, setupCopilot, setupCursor, setupCodex, setupWindsurf, setupVSCode, setupHud, setupHermes, } from './setup'; import { AGENT_TEARDOWNS, resolveAgentTeardown, agentTeardownTargets } from './agent-teardowns'; import { clearHookBaseline } from './daemon/hook-baseline'; import { getAgentWiring } from './agent-wiring'; import { writeCredentialsAndConfig } from './credentials'; import { stopDaemon } from './daemon/index'; import chalk from 'chalk'; import fs from 'fs'; import path from 'path'; import os from 'os'; import { confirm } from '@inquirer/prompts'; import { parseDuration } from './utils/duration'; import { runProxy } from './proxy'; import { autoStartDaemonAndWait } from './cli/daemon-starter'; import { onboardMachine, renderOnboardOutcome } from './onboarding'; import { loginViaBrowser } from './auth/browser-login'; import { registerLogoutCommand, revokeSelf } from './cli/commands/logout'; import { openBrowser } from './utils/open-browser'; import { buildExplainJson, buildExplainJsonError, displaySafe, inputPreview, toSafeJson, } from './cli/render/explain-display'; import type { ExplainResult } from './policy'; import { registerCheckCommand } from './cli/commands/check'; import { registerLogCommand } from './cli/commands/log'; import { registerShieldCommand } from './cli/commands/shield'; import { registerAppsCommand } from './cli/commands/apps'; import { registerConfigCommand } from './cli/commands/config-cmd'; import { autoMigrateLocalConfig } from './config/migrate'; import { registerDoctorCommand } from './cli/commands/doctor'; import { registerAuditCommand } from './cli/commands/audit'; import { registerReportCommand } from './cli/commands/report'; import { registerDaemonCommand } from './cli/commands/daemon-cmd'; import { registerStatusCommand } from './cli/commands/status'; import { registerInitCommand } from './cli/commands/init'; import { registerHealCommand } from './cli/commands/heal'; import { registerConnectCommand } from './cli/commands/connect'; import { registerUndoCommand } from './cli/commands/undo'; import { registerMcpGatewayCommand } from './cli/commands/mcp-gateway'; import { registerMcpServerCommand } from './cli/commands/mcp-server'; import { registerTrustCommand } from './cli/commands/trust'; import { registerMcpPinCommand } from './cli/commands/mcp-pin'; import { registerSyncCommand } from './cli/commands/sync'; import { registerAgentsCommand } from './cli/commands/agents'; import { registerScanCommand } from './cli/commands/scan'; import { registerForecastCasesCommand } from './cli/commands/forecast-cases'; import { registerPostureCommand } from './cli/commands/posture'; import { registerScanRepoCommand } from './cli/commands/scan-repo'; import { registerEgressCommand } from './cli/commands/egress'; import { registerChecksCommand } from './cli/commands/checks'; import { registerJailCommand } from './cli/commands/jail'; import { registerCanaryCommand } from './cli/commands/canary'; import { removeKind } from './canary/plant'; import { ALL_KINDS } from './canary/sites'; import { uninstallDaemonService } from './daemon/index'; import { registerSandboxCommand } from './cli/commands/sandbox'; import { registerSessionsCommand } from './cli/commands/sessions'; import { registerSessionTaintCommand } from './cli/commands/session-taint'; import { registerSessionExposureCommand } from './cli/commands/session-exposure'; import { registerPackageIndexCommand } from './cli/commands/package-index'; import { registerSkillPinCommand } from './cli/commands/skill-pin'; import { registerDecisionsCommand } from './cli/commands/decisions'; import { registerDlpCommand } from './cli/commands/dlp'; import { registerMaskCommand } from './cli/commands/mask'; import { registerBlastCommand } from './cli/commands/blast'; import { undoLeftoverPaths } from './utils/undo-leftovers'; import { safeMessage } from './utils/safe-text'; const { version } = JSON.parse( fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8') ) as { version: string }; const program = new Command(); program.name('node9').description('The Sudo Command for AI Agents').version(version); // 1. LOGIN — with no argument, the browser device-auth flow (login-v2 B1): // auth + workspace choice happen in the browser and the machine key is // delivered over the wire, never through a human. With a raw key argument, // the legacy/service path. program .command('login') .argument('[apiKey]', 'Service/legacy key. Omit to log in via your browser.') .option( '--local', 'Keep policy decisions local — the cloud never overrides them (cost data still syncs)' ) .option('--profile ', 'Save as a named profile (default: "default")') .option('--no-browser', "Don't auto-open the browser — just print the link") .option('--force', 'Allow interactive login even when CI is detected') .option('--api-url ', 'Override the device-auth endpoint (self-host / dev)') .action( async ( apiKey: string | undefined, options: { local?: boolean; profile?: string; browser?: boolean; force?: boolean; apiUrl?: string; } ) => { if (!apiKey) { // CI runners must not device-login: no browser, no human, and an // ephemeral "machine". They get service keys via NODE9_API_KEY. if ( (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') && !options.force ) { console.error(chalk.red('✗ CI environment detected.')); console.error( chalk.gray( ' Interactive login is for human machines. In CI, create a service key in\n' + ' the dashboard and set it as the NODE9_API_KEY secret. (Override: --force)' ) ); process.exitCode = 1; return; } if (options.local) { console.error(chalk.red('✗ --local needs a key: node9 login --local')); process.exitCode = 1; return; } const result = await loginViaBrowser({ apiUrl: options.apiUrl, noBrowser: options.browser === false, cliVersion: version, }); if (result.kind === 'failed' || result.kind === 'cancelled') { console.error(chalk.red(`✗ ${safeMessage(result.reason)}`)); process.exitCode = 1; } else { console.log( renderOnboardOutcome(result.outcome, { workspaceName: result.workspaceName }) ); if (result.kind === 'partial') process.exitCode = 1; } return; } await runKeyLogin(apiKey, options); } ); async function runKeyLogin(apiKey: string, options: { local?: boolean; profile?: string }) { // Named profile / --local keep their narrow legacy behavior: write the key, // say what happened, no cloud onboarding. Profiles are on a deprecation // path (login-v2 §6). `--local` sets approvers.cloud=false, so it keeps POLICY // AUTHORITY local and turns the audit shipper off — it is NOT a no-egress // switch: costSync gates on neither localOnly nor approvers.cloud, so cost // rows (which carry `workingDir`) still ship. Do not call it "privacy mode". if (options.profile && options.profile !== 'default') { const { profileName } = writeCredentialsAndConfig(apiKey, { profileName: options.profile, isLocal: options.local, }); console.log(chalk.green(`✅ Profile "${profileName}" saved`)); console.log(chalk.gray(` Switch to it per-session: NODE9_PROFILE=${profileName} claude`)); return; } if (options.local) { writeCredentialsAndConfig(apiKey, { isLocal: true }); console.log(chalk.green(`✅ Key saved. Local control mode.`)); console.log( chalk.gray(` Policy decisions stay on this machine; the cloud cannot override them.`) ); console.log(chalk.gray(` Audit shipping is off. Cost and usage data still sync to node9,`)); console.log(chalk.gray(` including the project directory each session ran in.`)); return; } // Default profile, cloud mode: run THE shared onboarding routine // (onboarding.ts) — same steps and same scorecard as `node9 connect`, so a // manually-entered key ends with a machine the dashboard can actually see. const outcome = await onboardMachine(apiKey); console.log(renderOnboardOutcome(outcome)); if (!outcome.ok) process.exitCode = 1; } // 1b. SIGNUP — open the node9 dashboard signup/login in the browser (Phase-1 capture). program .command('signup') .description('Create your node9 account / open the dashboard in your browser') .option('--login', 'Open the login page instead of signup') .action((options: { login?: boolean }) => { const route = options.login ? 'auth/login' : 'auth/signup'; const url = `https://node9.ai/${route}?ref=cli_cmd`; console.log(''); console.log(' ' + chalk.dim('Opening ') + chalk.cyan.underline(url)); // Best-effort open — on headless/SSH/VM the printed URL is the fallback. openBrowser(url); console.log(''); }); // 2. ADDTO program .command('addto', { hidden: true }) .description('Integrate Node9 with an AI agent') .addHelpText( 'after', '\n Supported targets: claude antigravity copilot gemini cursor codex windsurf vscode hud' ) .argument( '', 'The agent to protect: claude | antigravity | copilot | gemini | cursor | codex | windsurf | vscode | hud' ) .action(async (target: string) => { if (target === 'gemini') return await setupGemini(); if (target === 'antigravity' || target === 'agy') return await setupAntigravity(); if (target === 'copilot') return await setupCopilot(); if (target === 'claude') return await setupClaude(); if (target === 'cursor') return await setupCursor(); if (target === 'codex') return await setupCodex(); if (target === 'windsurf') return await setupWindsurf(); if (target === 'vscode') return await setupVSCode(); if (target === 'hermes') return setupHermes(); if (target === 'hud') return setupHud(); console.error( chalk.red( `Unknown target: "${target}". Supported: claude, antigravity, copilot, gemini, cursor, codex, windsurf, vscode, hermes, hud` ) ); process.exit(1); }); // 2b. SETUP (alias for addto) program .command('setup') .description('Set up dashboard or local protection; optionally configure a specific agent') .addHelpText( 'after', '\n Supported targets: claude antigravity copilot gemini cursor codex windsurf vscode hud' ) .argument( '[target]', 'The agent to protect: claude | antigravity | copilot | gemini | cursor | codex | windsurf | vscode | hud' ) .action(async (target?: string) => { if (!target) { const { runSetupWizard } = await import('./cli/first-run.js'); await runSetupWizard({ version }); return; } const t = target.toLowerCase(); if (t === 'gemini') return await setupGemini(); if (t === 'antigravity' || t === 'agy') return await setupAntigravity(); if (t === 'copilot') return await setupCopilot(); if (t === 'claude') return await setupClaude(); if (t === 'cursor') return await setupCursor(); if (t === 'codex') return await setupCodex(); if (t === 'windsurf') return await setupWindsurf(); if (t === 'vscode') return await setupVSCode(); if (t === 'hermes') return setupHermes(); if (t === 'hud') return setupHud(); console.error( chalk.red( `Unknown target: "${target}". Supported: claude, antigravity, copilot, gemini, cursor, codex, windsurf, vscode, hermes, hud` ) ); process.exit(1); }); // 2c. REMOVEFROM program .command('removefrom', { hidden: true }) .description('Remove Node9 hooks from an AI agent configuration') .addHelpText('after', `\n Supported targets: ${agentTeardownTargets().join(' ')}`) .argument('', `The agent to remove from: ${agentTeardownTargets().join(' | ')}`) .action((target: string) => { // Validate before logging so the target string is never interpolated // into output before it has been confirmed to be a known value. Resolved // off the single AGENT_TEARDOWNS source of truth (ids + aliases). const agent = resolveAgentTeardown(target); if (!agent) { console.error( chalk.red(`Unknown target: "${target}". Supported: ${agentTeardownTargets().join(', ')}`) ); process.exit(1); return; } console.log(chalk.cyan(`\n🛡️ Node9: removing hooks from ${agent.label}...\n`)); try { agent.fn(); } catch (err) { console.error(chalk.red(` ⚠️ Failed: ${err instanceof Error ? err.message : String(err)}`)); process.exit(1); } console.log(chalk.gray('\n Restart the agent for changes to take effect.')); }); // The last thing a user removing node9 ever sees from us. `preuninstall` runs // `node9 uninstall` WITHOUT --purge, so without this the message says "config // and audit log" while up to hundreds of gigabytes of shadow git repos stay // behind under a path we just described as holding a config file. function undoLeftoverNote(): string { if (undoLeftoverPaths().length === 0) return ''; return ( '\n Snapshots from the removed undo feature also remain.' + '\n Remove them with: node9 undo --purge' ); } // 2d. UNINSTALL program .command('uninstall') .description('Remove all Node9 hooks and optionally delete config files') .option('--purge', 'Also delete ~/.node9/ directory (config, audit log, credentials)') .action(async (options: { purge?: boolean }) => { console.log(chalk.cyan('\n🛡️ Node9 Uninstall\n')); // 0. Cloud disconnect — FIRST, while the key still exists locally // (--purge deletes credentials below; a machine that uninstalls without // this stays listed in the dashboard forever). Best-effort: an offline // uninstall proceeds, but says what remains. try { const credRaw = fs.readFileSync( path.join(os.homedir(), '.node9', 'credentials.json'), 'utf-8' ); const prof = (JSON.parse(credRaw) as Record)[ process.env.NODE9_PROFILE || 'default' ]; if (prof?.apiKey) { console.log(chalk.bold('Disconnecting from the cloud...')); const r = await revokeSelf({ apiKey: prof.apiKey, apiUrl: prof.apiUrl }); if (r.outcome === 'revoked') { console.log(chalk.green(' ✅ Machine disconnected — its key is revoked')); } else if (r.outcome === 'already') { console.log(chalk.blue(' ℹ️ Machine was already disconnected')); } else { console.log( chalk.yellow( ' ⚠️ Could not reach the cloud — the machine is still listed in the dashboard.' ) ); console.log(chalk.gray(' Disconnect it there: Enforcement › Devices › Disconnect.')); } } } catch { /* no credentials — nothing to disconnect */ } // 1. Stop the daemon console.log(chalk.bold('Stopping daemon...')); try { stopDaemon(); console.log(chalk.green(' ✅ Daemon stopped')); } catch { console.log(chalk.blue(' ℹ️ Daemon was not running')); } // 1b. Remove the auto-start service. stopDaemon above kills the RUNNING // process; the launchd plist / systemd unit is what starts it again at // next login, and it was never on the teardown list. On macOS that // leaves launchd trying to run a binary the user may have just // npm-uninstalled. uninstallDaemonService is a no-op when nothing is // installed. try { uninstallDaemonService(); console.log(chalk.green(' ✅ Auto-start service removed')); } catch (err) { console.error( chalk.yellow( ` ⚠️ Could not remove the auto-start service: ${err instanceof Error ? err.message : String(err)}` ) ); } // 2. Remove hooks/shims from EVERY supported agent (each wrapped // independently so a partial failure does not silently skip the rest). // Driven off the single AGENT_TEARDOWNS source of truth so a newly // supported agent can't be silently left behind (issue #186: Opencode + // Pi plugin shims used to be missed). Teardowns are no-op-safe when the // agent isn't installed. console.log(chalk.bold('\nRemoving hooks...')); let teardownFailed = false; for (const { label, fn } of AGENT_TEARDOWNS) { try { fn(); } catch (err) { teardownFailed = true; console.error( chalk.red( ` ⚠️ Failed to remove ${label} hooks: ${err instanceof Error ? err.message : String(err)}` ) ); } } // Forget node9's intended-governance record so the daemon's hook-heal pass // never nudges to re-`init` an agent the user just deliberately uninstalled. clearHookBaseline(); // 2b. Leftover scan — re-read the agent-wiring registry and report any agent // still wired. Scoped wording on purpose: the registry covers node9's // hook + plugin-shim agents (the Opencode/Pi shims from #186 included), // but NOT the MCP-config / statusline edits for Windsurf, VSCode, HUD, // ClaudeDesktop — those teardowns ran above but aren't re-verified here // (verifying them = expanding the registry; tracked separately). So the // message claims only what it actually checked. try { const residual = getAgentWiring().filter((a) => a.wireState === 'wired'); if (residual.length === 0) { console.log(chalk.green(' ✅ Verified — no node9 hooks or plugin shims remain')); } else { teardownFailed = true; console.error(chalk.red(' ⚠️ Still wired after teardown:')); for (const a of residual) { console.error(chalk.red(` • ${a.label} — ${a.settingsPath}`)); } } } catch { // A scan failure must not block uninstall; the teardown loop above is // the actual removal. Skip the verification line silently. } // 2c. Remove the decoy credential files node9 planted, BEFORE any purge. // Order is the whole point: --purge deletes ~/.node9 including // canaries.json, which is the ONLY record that those files are fake. // Deleting the map while keeping the treasure leaves three files every // secret scanner flags as a critical leak, and no way for a tool or a // human to tell them from real credentials — node9 itself then reports // them as `absent`. // // Removed on EVERY uninstall, with or without --purge: these are files // node9 created in the user's home, which is a different question from // whether to delete node9's own directory. let decoysLeft: string[] = []; try { const results = ALL_KINDS.map((k) => removeKind(k)); const removed = results.filter((r) => r.action === 'removed' || r.action === 'already-gone'); const refused = results.filter((r) => r.action === 'refused'); if (removed.length > 0 || refused.length > 0) { console.log(chalk.bold('\nRemoving decoy credentials...')); for (const r of removed) { if (r.path) console.log(chalk.green(` ✅ ${r.path.replace(os.homedir(), '~')}`)); } // A refusal must not fail the uninstall, and must not be silent: the // user has to know exactly what is still on disk and why. for (const r of refused) { decoysLeft.push(r.path ?? '(unknown path)'); console.error(chalk.yellow(` ⚠️ Left in place: ${r.path}`)); if (r.reason) console.error(chalk.gray(` ${r.reason}`)); } } } catch (err) { console.error( chalk.yellow( ` ⚠️ Could not remove decoy credentials: ${err instanceof Error ? err.message : String(err)}` ) ); decoysLeft = ['(the decoy registry could not be read)']; } // 3. Optionally purge ~/.node9/ — requires explicit confirmation because the // directory may contain credentials and cannot be recovered after deletion. if (options.purge) { const node9Dir = path.join(os.homedir(), '.node9'); if (fs.existsSync(node9Dir)) { // The prompt must name everything it removes. Snapshots from the removed // undo feature also live here and can run to hundreds of gigabytes of // copies of the user's own source — someone agreeing to drop "config, // audit log, credentials" is not agreeing to that. const alsoSnapshots = undoLeftoverPaths().length > 0 ? ', old undo snapshots' : ''; // Never orphan a decoy: the registry is the only record that those // files are fake, so deleting it while one is still on disk makes it // permanently indistinguishable from a real credential. if (decoysLeft.length > 0) { console.error(chalk.red('\n ⚠️ Decoy credential files are still on disk:')); for (const d of decoysLeft) console.error(chalk.red(` • ${d}`)); console.error( chalk.yellow( ' Deleting ~/.node9/ now would remove the only record that these are fake.\n' + ' Delete them yourself first, or keep ~/.node9/ so `node9 canary status` can still identify them.' ) ); } const confirmed = await confirm({ message: `Permanently delete ${node9Dir} (config, audit log, credentials${alsoSnapshots})?`, default: false, }); if (confirmed) { fs.rmSync(node9Dir, { recursive: true }); // Verify deletion succeeded — force:true would swallow errors and // print a false success if a file was locked or permission-denied. if (fs.existsSync(node9Dir)) { console.error( chalk.red('\n ⚠️ ~/.node9/ could not be fully deleted — remove it manually.') ); } else { console.log( chalk.green( `\n ✅ Deleted ~/.node9/ (config, audit log, credentials${alsoSnapshots})` ) ); } } else { // Declining is the one case where the leftover note is actionable: // node9 is going away, so this is the last chance to mention it. console.log( chalk.yellow(`\n Skipped — ~/.node9/ was not deleted.${undoLeftoverNote()}`) ); } } else { console.log(chalk.blue('\n ℹ️ ~/.node9/ not found — nothing to delete')); } } else { console.log( chalk.gray( `\n ~/.node9/ kept — run with --purge to delete config and audit log${undoLeftoverNote()}` ) ); } if (teardownFailed) { console.error(chalk.red('\n ⚠️ Some hooks could not be removed — see errors above.')); process.exit(1); } console.log(chalk.green.bold('\n🛡️ Node9 removed. Run: npm uninstall -g node9-ai')); console.log(chalk.gray(' Restart any open AI agent sessions for changes to take effect.\n')); }); // 2e. DOCTOR registerDoctorCommand(program, version); // 2d. EXPLAIN program .command('explain') .description( 'Show exactly how Node9 evaluates a tool call — waterfall + step-by-step policy trace' ) .argument('', 'Tool name (e.g. bash, str_replace_based_edit_tool, execute_query)') .argument('[args]', 'Tool arguments as JSON, or a plain command string for shell tools') .option( '--json', 'Machine-readable output (one JSON document; no "decision" field means failure)' ) .action(async (tool: string, argsRaw: string | undefined, opts: { json?: boolean }) => { // Every user-derived string goes through displaySafe() (redacted, one // visible line) before it is printed, so the input cannot forge a // Decision line or leak a secret into a log of this output. const failJson = (message: string): never => { console.log(toSafeJson(buildExplainJsonError(message))); process.exit(1); }; let args: unknown = {}; if (argsRaw) { const trimmed = argsRaw.trim(); if (trimmed.startsWith('{') || trimmed.startsWith('[')) { try { args = JSON.parse(trimmed); } catch { if (opts.json) failJson('Invalid JSON in [args]'); console.error(chalk.red(`\n❌ Invalid JSON: ${displaySafe(trimmed)}\n`)); process.exit(1); } } else { // Plain string — treat as a shell command for convenience args = { command: trimmed }; } } let result: ExplainResult; try { result = await explainPolicy(tool, args); } catch (err) { if (opts.json) failJson(`explain failed: ${displaySafe(String(err))}`); throw err; } if (opts.json) { console.log(toSafeJson(buildExplainJson(result, argsRaw))); return; } console.log(''); console.log(chalk.cyan.bold('🛡️ Node9 Explain')); console.log(''); console.log(` ${chalk.bold('Tool:')} ${chalk.white(displaySafe(result.tool))}`); if (argsRaw) { console.log(` ${chalk.bold('Input:')} ${chalk.gray(inputPreview(argsRaw))}`); } // ── Waterfall ──────────────────────────────────────────────────────────── console.log(''); console.log(chalk.bold('Config Sources (Waterfall):')); for (const tier of result.waterfall) { const num = chalk.gray(` ${tier.tier}.`); // path comes from the cwd and note can carry NODE9_MODE: both are // outside input, sanitized like the rest of the trace. const label = displaySafe(tier.label).padEnd(16); const tierNote = tier.note === undefined ? undefined : displaySafe(tier.note); let statusStr: string; if (tier.tier === 1) { statusStr = chalk.gray(tierNote ?? ''); } else if (tier.status === 'active') { const loc = tier.path ? chalk.gray(displaySafe(tier.path)) : ''; const note = tierNote ? chalk.gray(`(${tierNote})`) : ''; statusStr = chalk.green('✓ active') + (loc ? ' ' + loc : '') + (note ? ' ' + note : ''); } else { statusStr = chalk.gray('○ ' + (tierNote ?? 'not found')); } console.log(`${num} ${chalk.white(label)} ${statusStr}`); } // ── Policy steps ───────────────────────────────────────────────────────── console.log(''); console.log(chalk.bold('Policy Evaluation:')); for (const step of result.steps) { const isFinal = step.isFinal; let icon: string; if (step.outcome === 'allow') icon = chalk.green(' ✅'); else if (step.outcome === 'block') icon = chalk.red(' 🛑'); else if (step.outcome === 'review') icon = chalk.red(' 🔴'); else if (step.outcome === 'skip') icon = chalk.gray(' ─ '); else icon = chalk.gray(' ○ '); const name = displaySafe(step.name).padEnd(18); const nameStr = isFinal ? chalk.white.bold(name) : chalk.white(name); const safeDetail = displaySafe(step.detail); const detail = isFinal ? chalk.white(safeDetail) : chalk.gray(safeDetail); const arrow = isFinal ? chalk.yellow(' ← STOP') : ''; console.log(`${icon} ${nameStr} ${detail}${arrow}`); } // ── Final verdict ───────────────────────────────────────────────────────── console.log(''); if (result.decision === 'allow') { console.log(chalk.green.bold(' Decision: ✅ ALLOW') + chalk.gray(' — no approval needed')); } else if (result.decision === 'block') { console.log( chalk.red.bold(' Decision: 🛑 BLOCK') + chalk.gray(' — this action is blocked') ); if (result.blockedByLabel) { console.log(chalk.gray(` Reason: ${displaySafe(result.blockedByLabel)}`)); } } else { console.log( chalk.red.bold(' Decision: 🔴 REVIEW') + chalk.gray(' — human approval required') ); if (result.blockedByLabel) { console.log(chalk.gray(` Reason: ${displaySafe(result.blockedByLabel)}`)); } } console.log(''); }); // 3. INIT registerInitCommand(program); registerHealCommand(program); registerConnectCommand(program); registerLogoutCommand(program); // 4. AUDIT registerAuditCommand(program); registerReportCommand(program); // 5. STATUS registerStatusCommand(program); // 5. DAEMON registerDaemonCommand(program); // 6. TAIL program .command('tail') .description('Stream live agent activity to the terminal') .option('--history', 'Replay recent history then continue live', false) .option('--clear', 'Clear the history buffer and exit (does not stream)', false) .action(async (options: { history?: boolean; clear?: boolean }) => { const { startTail } = await import('./tui/tail.js'); try { await startTail(options); } catch (err) { console.error(chalk.red(`❌ ${err instanceof Error ? err.message : String(err)}`)); process.exit(1); } }); // node9 monitor — Ink-based unified live dashboard. // Renders four panels: live SSE stream, high-level summary, report // breakdown, DLP/loop/risk. Reversible: delete src/tui/dashboard/ + // this block. // // Implementation note: ink@7 + react@19 are ESM with top-level await, // so they cannot be require()'d from this CJS bundle. The dashboard // is built as a separate ESM bundle (dist/dashboard.mjs by tsup's // second config) and loaded here via runtime dynamic import. The // `new Function('id', 'return import(id)')` indirection bypasses // tsup's static-import-to-require transform, which would otherwise // rewrite a literal `import()` to require() in this CJS file. program .command('monitor') .description('Live interactive dashboard — activity feed, approvals, security signals') .action(async () => { try { const dashboardPath = path.join(__dirname, 'dashboard.mjs'); const dynamicImport = new Function('id', 'return import(id)') as (id: string) => Promise<{ startMonitor: () => Promise; }>; const mod = await dynamicImport(`file://${dashboardPath}`); await mod.startMonitor(); } catch (err) { console.error(chalk.red(`❌ ${err instanceof Error ? err.message : String(err)}`)); process.exit(1); } }); // node9 mcp-gateway + mcp pin registerMcpGatewayCommand(program); registerMcpServerCommand(program); registerMcpPinCommand(program); registerSkillPinCommand(program); registerDecisionsCommand(program); // 7. CHECK (PreToolUse hook) + LOG (PostToolUse hook) registerCheckCommand(program); registerLogCommand(program); // HUD — statusLine subprocess for Claude Code program .command('hud', { hidden: true }) .description('Render node9 security statusline (spawned by Claude Code statusLine)') .addHelpText( 'after', ` Outputs up to 3 lines to stdout, then exits: Line 1 — Security state (always shown): 🛡 node9 | [shields] | ✅ allowed 🛑 blocked 🚨 dlp ~$cost Shows "offline" if the node9 daemon is not running. Line 2 — Claude context & rate limits (shown when available): │ ctx ██████░░░░ 61% │ 5h ████░░░░░░ 40% (2h 10m left) Only appears when Claude Code passes context_window / rate_limits data via stdin. Line 3 — Environment counts (shown when non-zero): 2 CLAUDE.md | 5 rules | 4 MCPs | 3 hooks Counts CLAUDE.md files, rules/, MCP servers, and hook entries across user + project scope. Disable with: { "settings": { "hud": { "showEnvironmentCounts": false } } } in node9.config.json Claude Code spawns this command every ~300ms and writes a JSON payload to stdin. Run "node9 addto claude" to register it as the statusLine.` ) .argument('[subcommand]', 'Optional: "debug on" / "debug off" to toggle stdin logging') .argument('[state]', 'on|off — used with "debug" subcommand') .action(async (subcommand?: string, state?: string) => { if (subcommand === 'debug') { const flagFile = path.join(os.homedir(), '.node9', 'hud-debug'); if (state === 'on') { fs.mkdirSync(path.dirname(flagFile), { recursive: true }); fs.writeFileSync(flagFile, ''); console.log('HUD debug logging enabled → ~/.node9/hud-debug.log'); console.log('Tail it with: tail -f ~/.node9/hud-debug.log'); } else if (state === 'off') { if (fs.existsSync(flagFile)) fs.unlinkSync(flagFile); console.log('HUD debug logging disabled.'); } else { console.error('Usage: node9 hud debug on|off'); process.exit(1); } return; } const { main } = await import('./cli/hud.js'); await main(); }); // 8. PAUSE program .command('pause') .description('Temporarily disable Node9 protection for a set duration') .option('-d, --duration ', 'How long to pause (e.g. 15m, 1h, 30s)', '15m') .action((options: { duration: string }) => { const ms = parseDuration(options.duration); if (ms === null) { console.error( chalk.red(`\n❌ Invalid duration: "${options.duration}". Use format like 15m, 1h, 30s.\n`) ); process.exit(1); } pauseNode9(ms, options.duration); const expiresAt = new Date(Date.now() + ms).toLocaleTimeString(); console.log(chalk.yellow(`\n⏸ Node9 paused until ${expiresAt}`)); console.log(chalk.gray(` All tool calls will be allowed without review.`)); console.log(chalk.gray(` Run "node9 resume" to re-enable early.\n`)); }); // 9. RESUME program .command('resume') .description('Re-enable Node9 protection immediately') .action(() => { const { paused } = checkPause(); if (!paused) { console.log(chalk.gray('\nNode9 is already active — nothing to resume.\n')); return; } resumeNode9(); console.log(chalk.green('\n▶ Node9 resumed — protection is active.\n')); }); // 10. SMART RUNNER const HOOK_BASED_AGENTS: Record = { claude: 'claude', gemini: 'gemini', antigravity: 'antigravity', agy: 'antigravity', copilot: 'copilot', cursor: 'cursor', }; program .argument('[command...]', 'The agent command to run (e.g., gemini)') .action(async (commandArgs) => { if (commandArgs && commandArgs.length > 0) { const firstArg = commandArgs[0].toLowerCase(); if (HOOK_BASED_AGENTS[firstArg] !== undefined) { const target = HOOK_BASED_AGENTS[firstArg]; console.error( chalk.yellow(`\n⚠️ Node9 proxy mode does not support "${target}" directly.`) ); console.error(chalk.white(`\n "${target}" uses its own hook system. Use:`)); console.error( chalk.green(` node9 addto ${target} `) + chalk.gray('# one-time setup') ); console.error(chalk.green(` ${target} `) + chalk.gray('# run normally')); process.exit(1); } // Allow "node9 shell " as an alias for "node9 " const runArgs = firstArg === 'shell' ? commandArgs.slice(1) : commandArgs; if (runArgs.length === 0) { program.help(); return; } const fullCommand = runArgs.join(' '); let result = await authorizeHeadless( 'shell', { command: fullCommand }, { agent: 'Terminal', } ); if ( result.noApprovalMechanism && !isDaemonRunning() && !process.env.NODE9_NO_AUTO_DAEMON && getConfig().settings.autoStartDaemon ) { console.error(chalk.cyan('\n🛡️ Node9: Starting approval daemon automatically...')); const daemonReady = await autoStartDaemonAndWait(); if (daemonReady) result = await authorizeHeadless('shell', { command: fullCommand }); } // Fallback: inline Y/N prompt when no approval channel is available if (result.noApprovalMechanism && process.stdout.isTTY) { const approved = await confirm({ message: `🛡️ Node9: Allow "${fullCommand}"?`, default: false, }); result = { approved, reason: approved ? undefined : 'Denied by user at terminal.' }; } if (!result.approved) { console.error( chalk.red(`\n❌ Node9 Blocked: ${result.reason || 'Dangerous command detected.'}`) ); process.exit(1); } console.error(chalk.green('\n✅ Approved — running command...\n')); await runProxy(fullCommand); } else { const { readFirstRunEnv, shouldOfferFirstRun, runSetupWizard, unwiredAgentHint } = await import('./cli/first-run.js'); if (process.argv.length === 2 && shouldOfferFirstRun(readFirstRunEnv())) { await runSetupWizard({ version }); } else { program.outputHelp(); if (process.stdin.isTTY && process.stdout.isTTY) console.log(unwiredAgentHint()); } } }); // UNDO registerUndoCommand(program); // Shield management + config show registerShieldCommand(program); registerAppsCommand(program); registerConfigCommand(program); // Trusted-host allowlist registerTrustCommand(program); // Cloud policy sync registerSyncCommand(program); // Agent management registerAgentsCommand(program); // Retrospective scan registerScanCommand(program); registerForecastCasesCommand(program); // Security posture scorecard registerPostureCommand(program); // Repo agent-security scan (the CI-gate front door) registerScanRepoCommand(program); // Egress control (the posture remediation on-ramp) registerEgressCommand(program); registerChecksCommand(program); // Credential jail — user-extensible protected paths registerJailCommand(program); // Decoy credentials (canary) registerCanaryCommand(program); registerSandboxCommand(program, version); // Session history registerSessionsCommand(program); registerSessionTaintCommand(program); registerSessionExposureCommand(program); registerPackageIndexCommand(program); // Response DLP findings registerDlpCommand(program); registerMaskCommand(program); registerBlastCommand(program); // Daemon registers its own keep-alive unhandledRejection handler in startDaemon(). // Skip registration here entirely for daemon mode to avoid any ordering dependency // between this handler and the daemon's handler. // Note: process.argv[2] is evaluated at module load time — this is intentional, // cli.ts is always the process entry point, never imported as a library. if (process.argv[2] !== 'daemon') { process.on('unhandledRejection', (reason) => { const isCheckHook = process.argv[2] === 'check'; if (isCheckHook) { if (process.env.NODE9_DEBUG === '1' || getConfig().settings.enableHookLogDebug) { const logPath = path.join(os.homedir(), '.node9', 'hook-debug.log'); const msg = reason instanceof Error ? reason.message : String(reason); fs.appendFileSync(logPath, `[${new Date().toISOString()}] UNHANDLED: ${msg}\n`); } process.exit(0); } else { console.error('[Node9] Unhandled error:', reason); process.exit(1); } }); } // If the first argument is not a known node9 subcommand and doesn't start with // '-', we are in proxy mode (e.g. `node9 npx -y @pkg`). Inject '--' before the // command so Commander stops parsing options and passes everything — including // flags like -y, --config, --nexus-url — through to the action handler intact. // Without this, Commander errors on unknown flags before the handler ever runs. // // Derived from registered commands at runtime so it stays in sync automatically // when new subcommands are added — no hand-maintained allowlist to forget to update. // Note: c.name() returns the primary name; aliases (c.aliases()) are not included. // No subcommands currently use aliases, so this is safe. If aliases are added later, // extend this set with: program.commands.flatMap(c => [c.name(), ...c.aliases()]) const knownSubcommands = new Set(program.commands.map((c) => c.name())); const firstArg = process.argv[2]; if (firstArg && firstArg !== '--' && !firstArg.startsWith('-') && !knownSubcommands.has(firstArg)) { process.argv.splice(2, 0, '--'); } // The one-time move of ~/.node9/config.json to the v2 shape runs before any // command except the hooks: `check` and `log` run on every tool call, in // parallel, and must never write the config. The daemon runs it at start. program.hook('preAction', (_thisCommand, actionCommand) => { const name = actionCommand.name(); if (name === 'check' || name === 'log') return; autoMigrateLocalConfig(); }); (async () => { await program.parseAsync(); })();