declare const __CLI_VERSION__: string; import { existsSync } from 'node:fs'; import { Command, Option } from 'commander'; import chalk from 'chalk'; import { BLOCKS_EXAMPLES, DUMP_EXAMPLES, EXTRACT_EXAMPLES, IMPORT_EXAMPLES, USAGE_REPORT_EXAMPLES, HISTORY_EXAMPLES, MAP_EXAMPLES, QUOTA_EXAMPLES, ROOT_EXAMPLES, STATUSLINE_HELP, } from './help'; import { argsAfterCommand, firstCommandToken } from './argvScan'; import { isOfflineRun, needsFullStartup, runStartupSideEffects } from './startup'; import { shouldRunUpdateNotice, startUpdateNotice, type UpdateNoticeHandle } from './updateCheck'; import { contextFidelityOption, dumpFormatOption, mapFormatOption, mapLabelsOption, mapMotionOption, mapThemeOption, noteImportanceOption, noteStatusOption, noteTypeOption, quotaHistoryProviderOption, quotaProviderOption, reportThemeOption, rootProviderOption, sessionProviderChoice, sessionProviderOption, tasksStatusOption, } from './options'; import { detectProvider } from 'sidekick-shared'; import type { ProviderId, SessionProviderBase } from 'sidekick-shared'; import { AntigravityProvider, ClaudeCodeProvider, CodexProvider, GeminiProvider, OpenCodeProvider, } from 'sidekick-shared'; import { formatCliError } from './cliError'; import { installClosedPipeHandler } from './closedPipe'; import { leaveActiveAltScreen } from './dashboard/altScreen'; import { registerAccountsCommand } from './commands/accounts'; import { helpWhenRunAlone, rejectUnknownSubcommands, showGlobalOptionsEverywhere, } from './subcommandHelp'; // chalk 5 reads --no-color and FORCE_COLOR but not NO_COLOR (no-color.org). // Set the level here, the main bundle's entry (the SEA build starts here // too), so one-shot output and the Ink dashboard, which share this chalk, // both honour it. FORCE_COLOR still wins, and nothing leaks to child processes. if (process.env.NO_COLOR && !process.env.FORCE_COLOR) chalk.level = 0; const commandToken = firstCommandToken(process.argv.slice(2)); // `sidekick stats | head` closes the pipe early: end quietly instead of // printing an EPIPE stack trace. The status line keeps running after the // reader is gone so it can still write state.json and persist the quota. installClosedPipeHandler({ exit: commandToken !== 'statusline', beforeExit: leaveActiveAltScreen }); const program = new Command(); program .name('sidekick') .description('Query Sidekick project intelligence from the command line') .version(__CLI_VERSION__) .option('--json', 'Output as JSON') .option('--project ', 'Override project path (default: cwd)') // Chalk honors --no-color and a non-TTY stdout on its own (NO_COLOR is // applied above); declaring it here only stops Commander rejecting the flag. .option('--no-color', 'Disable colored output (also honors NO_COLOR)') .option( '--offline', 'Price from the cached catalog only; never refresh it over the network (also SIDEKICK_OFFLINE=1)', ) .option('--output-file ', 'Write everything the command prints to stdout into this file') .addOption(rootProviderOption()) .addHelpText('after', ROOT_EXAMPLES); let updateNotice: UpdateNoticeHandle | null = null; // preAction fires for real action handlers and not for --help, --version, or a // bare invocation, so the network fetch and account bootstrap stay off those // paths entirely. program.hook('preAction', async (_program, actionCommand) => { // Started first so the npm registry check overlaps startup and the command; // postAction collects it. Cache-only commands and offline runs read the // cached answer but never fetch. const noticeContext = { commandToken, json: Boolean(program.opts().json), env: process.env, stdoutIsTTY: Boolean(process.stdout.isTTY), stderrIsTTY: Boolean(process.stderr.isTTY), }; if (shouldRunUpdateNotice(noticeContext)) { updateNotice = startUpdateNotice({ allowFetch: needsFullStartup(commandToken) && !isOfflineRun(), }); } // A mistyped --project still "works" (an empty project), so say so once. const project = program.opts().project as string | undefined; if (project && !existsSync(project)) { process.stderr.write(`Warning: --project ${project} does not exist.\n`); } const outputFile = program.opts().outputFile as string | undefined; if (outputFile) { const { installOutputRedirect, isRedirectUnsupported } = await import('./outputRedirect'); if (commandToken && isRedirectUnsupported(commandToken, process.argv.slice(2))) { process.stderr.write(`--output-file is ignored for '${commandToken}'.\n`); } else { installOutputRedirect(outputFile); } } const accountDoctor = actionCommand.name() === 'doctor' && ['accounts', 'account'].includes(actionCommand.parent?.name() ?? ''); return runStartupSideEffects(commandToken, { accountDoctor }); }); // After the command's own output, on stderr so stdout stays clean. A command // that throws skips this, which is fine: the notice can wait for the next run. program.hook('postAction', async () => { const notice = await updateNotice?.finish().catch(() => null); if (notice) process.stderr.write(notice); }); export function resolveProviderId( opts: { provider?: string }, defaultProvider: ProviderId | 'auto' = 'auto', ): ProviderId { const choice = sessionProviderChoice(opts.provider || undefined); if (choice && choice !== 'auto') { return choice; } if (defaultProvider !== 'auto') { return defaultProvider; } return detectProvider(); } export function resolveProvider(opts: { provider?: string }): SessionProviderBase { const id = resolveProviderId(opts); switch (id) { case 'opencode': return new OpenCodeProvider(); case 'codex': // Codex compresses older rollouts (`.jsonl.zst`); read them too. return new CodexProvider({ includeCompressedRollouts: true }); case 'gemini': return new GeminiProvider(); case 'antigravity': return new AntigravityProvider(); case 'claude-code': default: return new ClaudeCodeProvider(); } } // Dashboard command uses dynamic imports — lazy-load to avoid import at parse time const dashCmd = new Command('dashboard') .description('Full-screen TUI dashboard with live session metrics') .option('--session ', 'Follow a specific session (default: most recent)') .option('--replay', 'Replay existing events before streaming new ones') .option('--no-mouse', 'Disable mouse capture so terminal text selection works (toggle with M)') .action(async (_opts: Record, cmd: Command) => { const { dashboardAction } = await import('./commands/dashboard'); return dashboardAction(_opts, cmd); }); program.addCommand(dashCmd); // Dump command — static session dump in text, JSON, or markdown format const dumpCmd = new Command('dump') .description( 'Dump session data as text timeline, JSON metrics, or markdown report; --prompts dumps prompts by session', ) .option('--list', 'List available session IDs for the current project') .option('--csv', 'With --list, print the session table as CSV') .option( '--limit ', 'Maximum sessions listed with --list (default: 50), or dumped with --prompts', ) .option('--session ', 'Target a specific session (default: most recent)') .option('--width ', 'Terminal width for text output (default: auto-detect)') .option('--expand', 'Show all events including noise') .addOption(dumpFormatOption()) .option('--prompts', 'Dump every human prompt grouped by session (Claude Code and Codex)') .option('--all', 'With --prompts, every session of this project and its worktrees') .option( '--since