Skip to main content

vtcode_core/cli/args/
mod.rs

1use clap::{ArgAction, ColorChoice, Parser, Subcommand, ValueHint};
2use colorchoice_clap::Color as ColorSelection;
3use std::env;
4use std::path::PathBuf;
5
6use crate::config::models::ModelId;
7
8mod acp;
9mod ask;
10mod background;
11mod bench;
12mod companion;
13mod config;
14mod debug;
15mod exec;
16mod models;
17mod plugins;
18mod pods;
19mod review;
20mod schedule;
21mod schema;
22mod secret;
23mod session_store;
24mod skills;
25mod version;
26mod webmcp;
27pub use version::long_version;
28
29pub use acp::AgentClientProtocolTarget;
30pub use ask::{AskCommandOptions, AskOutputFormat};
31pub use background::BackgroundSubagentArgs;
32pub use bench::BenchAllocatorArgs;
33pub use companion::{CompanionCommand, CompanionSetupArgs};
34pub use config::{
35    ConfigCommand, ConfigFile, ConfigResetArgs, ContextConfig, LoggingConfig, PerformanceConfig, SecurityConfig,
36    ToolConfig,
37};
38pub use debug::DebugCommand;
39pub use exec::{EvalOutputFormat, ExecEvalArgs, ExecResumeArgs, ExecSubcommand};
40pub use models::ModelCommands;
41pub use plugins::PluginsSubcommand;
42pub use pods::PodsCommands;
43pub use review::ReviewArgs;
44pub use schedule::{ScheduleCreateArgs, ScheduleSubcommand};
45pub use schema::{SchemaCommands, SchemaMode, SchemaOutputFormat};
46pub use secret::{MigrateArgs, SecretArgs, SecretProvider, SecretSubcommand};
47pub use session_store::SessionStoreCommand;
48pub use skills::{SkillsRefSubcommand, SkillsSubcommand};
49pub use webmcp::{WebmcpCommand, WebmcpPairArgs, WebmcpServeArgs};
50
51#[derive(Parser, Debug, Clone)]
52pub struct Cli {
53    /// Color output selection (auto, always, never)
54    #[command(flatten)]
55    pub color: ColorSelection,
56
57    /// Optional positional path to run vtcode against a different workspace
58    #[arg(
59        value_name = "WORKSPACE",
60        value_hint = ValueHint::DirPath,
61        value_parser = version::parse_workspace_directory,
62        global = true,
63        last = true
64    )]
65    pub workspace_path: Option<PathBuf>,
66
67    /// LLM Model ID (e.g., gpt-5, claude-sonnet-4-6, gemini-3-flash-preview)
68    #[arg(long, global = true)]
69    pub model: Option<String>,
70
71    /// LLM Provider (gemini, openai, anthropic, deepseek, meta, openrouter, merge-gateway, codex, zai, moonshot, minimax, ollama, lmstudio)
72    #[arg(long, global = true)]
73    pub provider: Option<String>,
74
75    /// API key environment variable (auto-detects GEMINI_API_KEY, OPENAI_API_KEY, etc.)
76    #[arg(long, global = true, default_value = crate::config::constants::defaults::DEFAULT_API_KEY_ENV)]
77    pub api_key_env: String,
78
79    /// Workspace root directory (default: current directory)
80    #[arg(
81        long,
82        global = true,
83        alias = "workspace-dir",
84        value_name = "PATH",
85        value_hint = ValueHint::DirPath,
86        value_parser = version::parse_workspace_directory
87    )]
88    pub workspace: Option<PathBuf>,
89
90    /// Enable research-preview features
91    #[arg(long, global = true)]
92    pub research_preview: bool,
93
94    /// Security level for tool execution (strict, moderate, permissive)
95    #[arg(long, global = true, default_value = "moderate")]
96    pub security_level: String,
97
98    /// Show diffs for file changes in chat interface
99    #[arg(long, global = true)]
100    pub show_file_diffs: bool,
101
102    /// Maximum concurrent async operations
103    #[arg(long, global = true, default_value_t = 5)]
104    pub max_concurrent_ops: usize,
105
106    /// Maximum API requests per minute
107    #[arg(long, global = true, default_value_t = 30)]
108    pub api_rate_limit: usize,
109
110    /// Maximum tool calls per session
111    #[arg(long, global = true, default_value_t = 10)]
112    pub max_tool_calls: usize,
113
114    /// Enable debug output for troubleshooting
115    #[arg(long, global = true)]
116    pub debug: bool,
117
118    /// Enable verbose logging
119    #[arg(long, global = true)]
120    pub verbose: bool,
121
122    /// Suppress all non-essential output (for scripting, CI/CD)
123    #[arg(short, long, global = true)]
124    pub quiet: bool,
125
126    /// Configuration overrides or file path (KEY=VALUE or PATH)
127    #[arg(
128        short = 'c',
129        long = "config",
130        value_name = "KEY=VALUE|PATH",
131        action = ArgAction::Append,
132        global = true
133    )]
134    pub config: Vec<String>,
135
136    /// Log level (error, warn, info, debug, trace)
137    #[arg(long, global = true, default_value = "info")]
138    pub log_level: String,
139
140    /// Disable color output (equivalent to `--color never`)
141    #[arg(long, global = true)]
142    pub no_color: bool,
143
144    /// Select UI theme (e.g., ciapre-dark, ciapre-blue)
145    #[arg(long, global = true, value_name = "THEME")]
146    pub theme: Option<String>,
147
148    /// App tick rate in milliseconds (default: 250)
149    #[arg(short = 't', long, default_value_t = 250)]
150    pub tick_rate: u64,
151
152    /// Frame rate in FPS (default: 60)
153    #[arg(short = 'f', long, default_value_t = 60)]
154    pub frame_rate: u64,
155
156    /// Enable skills system
157    #[arg(long, global = true)]
158    pub enable_skills: bool,
159
160    /// Enable Chrome browser integration for web automation
161    #[arg(long, global = true)]
162    pub chrome: bool,
163
164    /// Disable Chrome browser integration
165    #[arg(long = "no-chrome", global = true, conflicts_with = "chrome")]
166    pub no_chrome: bool,
167
168    /// Skip safety confirmations (use with caution)
169    #[arg(long, global = true)]
170    pub skip_confirmations: bool,
171
172    /// Enable experimental Codex app-server features for this run
173    #[arg(long = "codex-experimental", global = true, conflicts_with = "no_codex_experimental")]
174    pub codex_experimental: bool,
175
176    /// Disable experimental Codex app-server features for this run
177    #[arg(long = "no-codex-experimental", global = true, conflicts_with = "codex_experimental")]
178    pub no_codex_experimental: bool,
179
180    /// Print response without launching the interactive TUI
181    #[arg(
182        short = 'p',
183        long = "print",
184        value_name = "PROMPT",
185        value_hint = ValueHint::Other,
186        num_args = 0..=1,
187        default_missing_value = "",
188        global = true,
189        conflicts_with_all = ["full_auto"]
190    )]
191    pub print: Option<String>,
192
193    /// Run non-interactively with full-auto permission review
194    #[arg(
195        long = "full-auto",
196        global = true,
197        help = "Run non-interactively with full-auto permission review",
198        long_help = r#"Run non-interactively on top of the active primary agent.
199
200If no primary agent is explicitly selected or configured, VT Code selects the effective `auto` primary agent. Explicit choices, including `duck`, are honoured. Full-auto is an execution and permission layer, not a primary agent.
201
202Full-auto does not override explicit denies or grant tools outside `[automation.full_auto].allowed_tools`. Tools outside that allow-list are denied. Promptable actions inside the allow-list are routed through automatic permission review after deny and policy checks instead of asking. The run fails fast if it needs the defaulted `auto` primary agent and no effective `auto` exists."#,
203        value_name = "PROMPT",
204        num_args = 0..=1,
205        default_missing_value = "",
206        value_hint = ValueHint::Other
207    )]
208    pub full_auto: Option<String>,
209
210    /// Resume a previous conversation (use without ID for interactive picker)
211    #[arg(
212        short = 'r',
213        long = "resume",
214        global = true,
215        value_name = "SESSION_ID",
216        num_args = 0..=1,
217        default_missing_value = "__interactive__",
218        conflicts_with_all = ["continue_latest", "full_auto"]
219    )]
220    pub resume_session: Option<String>,
221
222    /// Continue the most recent conversation automatically
223    #[arg(
224        long = "continue",
225        visible_alias = "continue-session",
226        global = true,
227        conflicts_with_all = ["resume_session", "full_auto"]
228    )]
229    pub continue_latest: bool,
230
231    /// Fork an existing session with a new session ID
232    #[arg(
233        long = "fork-session",
234        global = true,
235        value_name = "SESSION_ID",
236        conflicts_with_all = ["resume_session", "continue_latest", "full_auto"]
237    )]
238    pub fork_session: Option<String>,
239
240    /// Show archived sessions from every workspace when resuming or forking
241    #[arg(long, global = true)]
242    pub all: bool,
243
244    /// Custom suffix for session identifier (alphanumeric, dash, underscore only, max 64 chars)
245    #[arg(long = "session-id", global = true, value_name = "CUSTOM_SUFFIX")]
246    pub session_id: Option<String>,
247
248    /// Use summarized history when forking a session
249    #[arg(long, global = true)]
250    pub summarize: bool,
251
252    /// Override the default agent model for this session
253    #[arg(long, global = true, value_name = "AGENT")]
254    pub agent: Option<String>,
255
256    /// Tools that execute without prompting (comma-separated, supports patterns like "Bash(git:*)")
257    #[arg(long = "allowed-tools", global = true, value_name = "TOOLS", action = ArgAction::Append)]
258    pub allowed_tools: Vec<String>,
259
260    /// Tools that cannot be used by the agent
261    #[arg(long = "disallowed-tools", global = true, value_name = "TOOLS", action = ArgAction::Append)]
262    pub disallowed_tools: Vec<String>,
263
264    /// Auto-approve promptable actions while respecting denies and policy blocks
265    #[arg(
266        long = "dangerously-skip-permissions",
267        global = true,
268        help = "Auto-approve promptable actions while respecting denies and policy blocks",
269        long_help = "Auto-approve promptable actions while still respecting explicit denies and policy blocks."
270    )]
271    pub dangerously_skip_permissions: bool,
272
273    /// Disable the process sandbox and automatically approve promptable actions for this session.
274    #[arg(long, global = true, conflicts_with_all = ["full_auto", "skip_confirmations", "dangerously_skip_permissions"])]
275    pub full_access: bool,
276
277    /// Explicitly connect to IDE on startup (auto-detects available IDEs)
278    #[arg(long, global = true)]
279    pub ide: bool,
280
281    #[command(subcommand)]
282    pub command: Option<Commands>,
283}
284
285#[derive(Subcommand, Debug, Clone)]
286pub enum Commands {
287    /// Configure the local VT Code Companion plugin.
288    #[command(name = "companion")]
289    Companion {
290        #[command(subcommand)]
291        command: CompanionCommand,
292    },
293
294    /// Start Agent Client Protocol bridge for IDE integrations
295    #[command(name = "acp")]
296    AgentClientProtocol {
297        /// Client to connect over ACP
298        #[arg(value_enum, default_value_t = AgentClientProtocolTarget::Zed)]
299        target: AgentClientProtocolTarget,
300    },
301
302    /// Unified per-session state store (single source of truth for state,
303    /// context, and history). Consolidates the legacy `checkpoints/`, `logs/`,
304    /// and `history/` stores.
305    #[command(name = "session-store")]
306    SessionStore {
307        #[command(subcommand)]
308        command: SessionStoreCommand,
309    },
310
311    /// Interactive AI coding assistant
312    Chat,
313
314    /// Resume the most recent conversation automatically
315    ///
316    /// Equivalent to `vtcode --continue`. Loads the latest archived session in
317    /// the current workspace (or across all workspaces with `--all`) and resumes
318    /// it without showing the interactive picker.
319    ///
320    /// Examples:
321    ///   vtcode continue
322    ///   vtcode continue --all
323    ///   vtcode continue --session-id my-fork   # fork latest into a new session
324    Continue,
325
326    /// Single prompt mode - prints model reply without tools
327    ///
328    /// Send a single prompt to the model and print the response. No tools are
329    /// invoked, no session is created, and the process exits after replying.
330    ///
331    /// Examples:
332    ///   vtcode ask "what is a monad?"
333    ///   echo "summarize this" | vtcode ask
334    ///   vtcode ask --output-format json "explain ownership in Rust"
335    Ask {
336        /// Prompt to ask. Use `-` to force reading from stdin.
337        #[arg(
338            value_name = "PROMPT",
339            long_help = "The prompt to send to the model.\n\nOmit to read from stdin (piped input).\nUse '-' to explicitly force reading from stdin."
340        )]
341        prompt: Option<String>,
342        /// Format the response using a structured representation.
343        #[arg(
344            long = "output-format",
345            value_enum,
346            value_name = "FORMAT",
347            long_help = "Output format for the response.\n\nCurrently supports:\n  json - Emit the response as a structured JSON document."
348        )]
349        output_format: Option<AskOutputFormat>,
350    },
351    /// Headless execution mode
352    ///
353    /// Run the agent in non-interactive mode. The agent executes the prompt,
354    /// runs tools, and exits when done. Ideal for CI/CD, scripting, and
355    /// agent-to-agent workflows.
356    ///
357    /// Examples:
358    ///   vtcode exec "explain this codebase"
359    ///   vtcode exec --json "fix the failing test"
360    ///   vtcode exec --dry-run "refactor auth module"
361    ///   cat file.rs | vtcode exec "review this code"
362    ///   vtcode exec resume --last
363    Exec {
364        /// Emit structured JSON events to stdout (one per line)
365        #[arg(
366            long,
367            long_help = "Stream newline-delimited JSON events to stdout.\nEach line is a JSON object representing an agent event (tool call, message, etc.).\nUseful for programmatic consumption and CI integration."
368        )]
369        json: bool,
370        /// Run a read-only dry-run execution (blocks mutating tool calls)
371        #[arg(
372            long,
373            long_help = "Simulate execution without making changes.\nThe agent plans tool calls but does not execute mutating operations (file writes, shell commands).\nUseful for previewing what the agent would do."
374        )]
375        dry_run: bool,
376        /// Optional path to write the JSONL transcript
377        #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath, long_help = "Write the full JSONL event transcript to this file.\nIncludes all agent events: tool calls, messages, errors, and metadata.")]
378        events: Option<PathBuf>,
379        /// Write the last agent message to this file
380        #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath, long_help = "Write only the final agent message to this file.\nUseful for piping the agent's response into other tools.")]
381        last_message_file: Option<PathBuf>,
382        /// Optional exec subcommand
383        #[command(subcommand)]
384        command: Option<ExecSubcommand>,
385        /// Prompt to execute. Use `-` to force reading from stdin.
386        #[arg(
387            value_name = "PROMPT",
388            long_help = "The prompt to execute.\n\nOmit to read from stdin (piped input).\nUse '-' to explicitly force reading from stdin.\nQuote multi-word prompts: vtcode exec \"fix the bug in auth.rs\""
389        )]
390        prompt: Option<String>,
391    },
392    /// Run an evaluation suite (shorthand for `vtcode exec eval`)
393    ///
394    /// Executes each task in the suite autonomously in an isolated worktree,
395    /// verifies the outcome with environment probes, and aggregates pass@k /
396    /// pass^k metrics into a markdown or JSON report.
397    ///
398    /// Examples:
399    ///   vtcode eval --suite suite.json
400    ///   vtcode eval --suite suite.json --format json --output report.json
401    Eval(ExecEvalArgs),
402    /// Manage durable scheduled tasks
403    ///
404    /// Create, list, and delete scheduled tasks that run on a recurring or
405    /// one-shot basis. Tasks are stored persistently and survive restarts
406    /// when paired with `vtcode schedule install-service`.
407    ///
408    /// Examples:
409    ///   vtcode schedule create --name "daily-review" --cron "0 9 * * 1-5" --prompt "review recent changes"
410    ///   vtcode schedule create --name "reminder" --reminder "standup in 10 minutes" --at "09:50"
411    ///   vtcode schedule list
412    ///   vtcode schedule delete `<task-id>`
413    Schedule {
414        #[command(subcommand)]
415        command: ScheduleSubcommand,
416    },
417
418    /// Internal VT Code background subagent runner
419    #[command(name = "background-subagent", hide = true)]
420    BackgroundSubagent(BackgroundSubagentArgs),
421
422    /// Headless code review for the current diff, selected files, or a custom git target
423    #[command(
424        long_about = "Run a non-interactive code review.\n\nExamples:\n  vtcode review\n  vtcode review \"Review the full diff for correctness and regressions\"\n  vtcode review --last-diff\n  vtcode review --target HEAD~1..HEAD\n  vtcode review --file src/main.rs --file crates/codegen/vtcode-core/src/lib.rs\n  vtcode review --style security \"Focus on auth bypass and injection\""
425    )]
426    Review(ReviewArgs),
427
428    /// Runtime schema introspection for built-in tools
429    Schema {
430        #[command(subcommand)]
431        command: SchemaCommands,
432    },
433
434    /// Verbose interactive chat with debug output
435    ChatVerbose,
436
437    /// Analyze workspace (structure, security, performance)
438    Analyze {
439        /// Type of analysis to perform
440        #[arg(value_name = "TYPE", default_value = "full")]
441        analysis_type: String,
442    },
443
444    /// Pretty-print trajectory logs
445    #[command(name = "trajectory")]
446    Trajectory {
447        /// Optional path to trajectory JSONL file
448        #[arg(long)]
449        file: Option<PathBuf>,
450        /// Number of top entries to show
451        #[arg(long, default_value_t = 10)]
452        top: usize,
453    },
454
455    /// Inspect or exercise the workspace's OS sandbox (no agent session)
456    #[command(name = "debug")]
457    Debug {
458        #[command(subcommand)]
459        command: DebugCommand,
460    },
461
462    /// Send a VT Code notification using the built-in notification system
463    Notify {
464        /// Optional notification title
465        #[arg(long, value_name = "TITLE")]
466        title: Option<String>,
467        /// Notification message
468        #[arg(value_name = "MESSAGE")]
469        message: String,
470    },
471
472    /// Benchmark against SWE-bench evaluation framework
473    Benchmark {
474        /// Path to a JSON benchmark specification
475        #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath)]
476        task_file: Option<PathBuf>,
477        /// Inline JSON specification for quick experiments
478        #[arg(long, value_name = "JSON")]
479        task: Option<String>,
480        /// Optional path to write the structured benchmark report
481        #[arg(long, value_name = "PATH", value_hint = ValueHint::FilePath)]
482        output: Option<PathBuf>,
483        /// Limit the number of tasks executed
484        #[arg(long, value_name = "COUNT")]
485        max_tasks: Option<usize>,
486    },
487
488    /// Measure allocator RSS behavior under a bursty/sparse Tokio workload
489    ///
490    /// Reproduces the mimalloc-vs-jemalloc analysis pattern: many short-lived
491    /// tasks allocated across Tokio worker threads, with idle gaps between
492    /// bursts. Reports the RSS trajectory so you can see whether the global
493    /// allocator returns memory to the OS (jemalloc) or pins it (mimalloc/glibc).
494    /// Build with `--features allocator-jemalloc` to compare allocators.
495    #[command(name = "bench-allocator")]
496    BenchAllocator(BenchAllocatorArgs),
497
498    /// Create complete Rust project
499    CreateProject {
500        name: String,
501        #[arg(long = "feature", value_name = "FEATURE", action = ArgAction::Append)]
502        features: Vec<String>,
503    },
504
505    /// Revert agent to a previous snapshot
506    Revert {
507        /// Turn number to revert to
508        #[arg(short, long)]
509        turn: usize,
510        /// Scope of revert operation: conversation, code, full
511        #[arg(long)]
512        partial: Option<String>,
513        /// Session that owns the checkpoint (required when several sessions recorded the same turn)
514        #[arg(long)]
515        session: Option<String>,
516    },
517
518    /// List all available snapshots
519    Snapshots,
520
521    /// Clean up old snapshots
522    ///
523    /// Features:
524    ///   • Remove snapshots beyond limit
525    ///   • Configurable retention policy
526    ///   • Safe deletion with confirmation
527    ///
528    /// Examples:
529    ///   vtcode cleanup-snapshots
530    ///   vtcode cleanup-snapshots --max 20
531    #[command(name = "cleanup-snapshots")]
532    CleanupSnapshots {
533        /// Maximum number of snapshots to keep
534        ///
535        /// Default: 50
536        /// Example: --max 20
537        #[arg(short, long, default_value_t = 50)]
538        max: usize,
539    },
540
541    /// Initialize project guidance and workspace scaffolding
542    ///
543    /// Bootstrap a workspace for use with VT Code. Creates vtcode.toml,
544    /// AGENTS.md, and other scaffolding. Run this once per project.
545    ///
546    /// Examples:
547    ///   vtcode init
548    ///   vtcode init --force
549    Init {
550        /// Overwrite an existing AGENTS.md without prompting
551        #[arg(
552            long,
553            short = 'f',
554            long_help = "Overwrite AGENTS.md without confirmation.\nUse this in CI/CD or scripts where interactive prompts are not possible."
555        )]
556        force: bool,
557    },
558
559    /// Initialize project in the user state directory's `projects/` path.
560    ///
561    /// Create a new project entry in the VT Code projects directory.
562    /// This is separate from `vtcode init` which bootstraps a workspace.
563    ///
564    /// Examples:
565    ///   vtcode init-project
566    ///   vtcode init-project --name my-project
567    ///   vtcode init-project --force --migrate
568    #[command(name = "init-project")]
569    InitProject {
570        /// Project name - defaults to current directory name
571        #[arg(
572            long,
573            long_help = "Name for the project.\nDefaults to the current directory name if not specified."
574        )]
575        name: Option<String>,
576        /// Force initialization - overwrite existing project structure
577        #[arg(long, long_help = "Overwrite existing project structure without confirmation.")]
578        force: bool,
579        /// Migrate existing files - move existing config/cache files to new structure
580        #[arg(
581            long,
582            long_help = "Move existing config and cache files into the new project structure."
583        )]
584        migrate: bool,
585    },
586
587    /// Generate or manage configuration files
588    ///
589    /// Create a vtcode.toml configuration file with default settings, or use
590    /// `reset` to clear one configuration layer.
591    /// Use --global to create in the canonical user config directory or specify an output path.
592    ///
593    /// Examples:
594    ///   vtcode config
595    ///   vtcode config --global
596    ///   vtcode config --output ./my-vtcode.toml
597    ///   vtcode config reset
598    ///   vtcode config reset --global
599    ///   vtcode config reset --project
600    Config {
601        #[command(subcommand)]
602        command: Option<ConfigCommand>,
603        /// Output file path
604        #[arg(
605            long,
606            long_help = "Write the configuration to this path.\nDefaults to ./vtcode.toml in the current directory."
607        )]
608        output: Option<PathBuf>,
609        /// Create in the canonical user config directory.
610        #[arg(
611            long,
612            long_help = "Write the configuration to the canonical user config directory.\nThis sets global defaults for all workspaces."
613        )]
614        global: bool,
615    },
616
617    /// Authenticate with a supported provider
618    ///
619    /// Start an OAuth or API-key login flow for the given provider.
620    /// Credentials are stored securely in the OS keychain.
621    ///
622    /// Examples:
623    ///   vtcode login openai
624    ///   vtcode login openai --from-codex
625    ///   vtcode login openrouter
626    ///   vtcode login codex
627    ///   vtcode login codex --device-code
628    Login {
629        /// Provider name (`openai`, `openrouter`, `copilot`, or `codex`)
630        #[arg(long_help = "The provider to authenticate with.\nSupported: openai, openrouter, copilot, codex")]
631        provider: String,
632        /// Use device-code login when the provider supports it (currently `codex` only)
633        #[arg(
634            long,
635            default_value_t = false,
636            long_help = "Use the device-code OAuth flow.\nCurrently supported only for the `codex` provider.\nOpens a browser URL and asks you to enter a code."
637        )]
638        device_code: bool,
639        /// Import ChatGPT credentials from Codex's `~/.codex/auth.json` instead
640        /// of running the browser OAuth flow (currently `openai` only)
641        #[arg(
642            long,
643            default_value_t = false,
644            long_help = "Import ChatGPT OAuth tokens from Codex's auth.json.\n\
645                         Requires that you have already run `codex login`.\n\
646                         Currently supported only for the `openai` provider."
647        )]
648        from_codex: bool,
649    },
650
651    /// Clear stored authentication credentials for a provider
652    ///
653    /// Remove stored OAuth tokens or API keys for the given provider.
654    ///
655    /// Examples:
656    ///   vtcode logout openai
657    ///   vtcode logout openrouter
658    Logout {
659        /// Provider name (`openai`, `openrouter`, `copilot`, or `codex`)
660        #[arg(long_help = "The provider to deauthenticate.\nSupported: openai, openrouter, copilot, codex")]
661        provider: String,
662    },
663
664    /// Show authentication status for one provider or all supported providers
665    ///
666    /// Display whether each provider is authenticated, which credential type
667    /// is in use, and token/session metadata when available.
668    ///
669    /// Examples:
670    ///   vtcode auth
671    ///   vtcode auth openai
672    ///   vtcode auth openrouter
673    Auth {
674        /// Optional provider name (`openai`, `openrouter`, `copilot`, or `codex`)
675        #[arg(long_help = "Show status for a single provider.\nOmit to show status for all supported providers.")]
676        provider: Option<String>,
677    },
678
679    /// Manage tool execution policies
680    #[command(name = "tool-policy")]
681    ToolPolicy {
682        #[command(subcommand)]
683        command: crate::cli::tool_policy_commands::ToolPolicyCommands,
684    },
685
686    /// Manage Model Context Protocol providers and inspect their resources
687    #[command(name = "mcp")]
688    Mcp {
689        #[command(subcommand)]
690        command: crate::mcp::cli::McpCommands,
691    },
692
693    /// Agent2Agent (A2A) Protocol
694    #[command(name = "a2a")]
695    A2a {
696        #[command(subcommand)]
697        command: super::super::a2a::cli::A2aCommands,
698    },
699
700    /// Authenticated browser editor bridge
701    #[command(name = "webmcp")]
702    Webmcp {
703        #[command(subcommand)]
704        command: WebmcpCommand,
705    },
706
707    /// Proxy to the official Codex app-server
708    #[command(name = "app-server")]
709    AppServer {
710        /// Transport listen target passed through to `codex app-server`
711        #[arg(long, default_value = "stdio://")]
712        listen: String,
713    },
714
715    /// Start the local VT Code desktop service over JSON-RPC stdio.
716    #[command(name = "desktop-server")]
717    DesktopServer,
718
719    /// Open the VT Code desktop app (macOS).
720    ///
721    /// Locates VT Code.app (explicit path, VTCODE_DESKTOP_APP, then
722    /// ~/Applications and /Applications) and opens a new instance.
723    /// Pass --install to download and install it from the release asset instead.
724    ///
725    ///   vtcode desktop --install
726    #[command(name = "desktop")]
727    Desktop {
728        /// Path to VT Code.app when it is outside the standard locations
729        #[arg(value_name = "APP_PATH")]
730        app_path: Option<PathBuf>,
731        /// Download and install the app from the prebuilt release asset instead of opening it
732        #[arg(
733            long,
734            conflicts_with = "app_path",
735            long_help = "Download and install the desktop app from the prebuilt release asset instead of opening it.\nUpdates install in place; fresh installs go to ~/Applications."
736        )]
737        install: bool,
738    },
739
740    /// Manage models and providers
741    Models {
742        #[command(subcommand)]
743        command: ModelCommands,
744    },
745
746    /// Manage GPU pod deployments
747    #[command(name = "pods")]
748    Pods {
749        #[command(subcommand)]
750        command: PodsCommands,
751    },
752
753    /// Generate or display man pages
754    Man {
755        /// Command name to generate man page for (optional)
756        command: Option<String>,
757        /// Generate the main page and every visible command page
758        #[arg(long, conflicts_with = "command", requires = "output")]
759        all_pages: bool,
760        /// Output file, or output directory when --all-pages is specified
761        #[arg(short, long)]
762        output: Option<PathBuf>,
763    },
764
765    /// Manage Agent Skills
766    ///
767    /// Skills are reusable instruction sets that extend the agent's capabilities.
768    /// Each skill is a directory containing a SKILL.md manifest and optional scripts.
769    ///
770    /// Examples:
771    ///   vtcode skills list
772    ///   vtcode skills create my-skill
773    ///   vtcode skills load my-skill
774    ///   vtcode skills info my-skill
775    ///   vtcode skills validate ./path/to/skill
776    #[command(subcommand)]
777    Skills(SkillsSubcommand),
778
779    /// Manage Agent Plugins
780    ///
781    /// Agent Plugins are portable packages that bundle Agent Skills and MCP servers
782    /// under a root plugin.json manifest, following the Agent Plugins spec.
783    ///
784    /// Examples:
785    ///   vtcode plugins list
786    ///   vtcode plugins info my-plugin
787    ///   vtcode plugins validate ./path/to/plugin
788    ///   vtcode plugins add <https://github.com/example/plugin>
789    ///   vtcode plugins remove my-plugin
790    #[command(subcommand)]
791    Plugins(PluginsSubcommand),
792
793    /// List available skills (alias for `vtcode skills list`)
794    #[command(name = "list-skills", hide = true)]
795    ListSkills {},
796
797    /// Manage API keys in secure storage (OS keyring or encrypted file)
798    ///
799    /// Store, inspect, and delete provider API keys without exposing them
800    /// in shell history or workspace files.
801    ///
802    /// Examples:
803    ///   vtcode secret
804    ///   vtcode secret list
805    ///   vtcode secret status openai
806    ///   vtcode secret add openai
807    ///   vtcode secret delete openai
808    Secret(SecretArgs),
809
810    /// Check for and install binary updates from GitHub Releases
811    ///
812    /// Manage VT Code binary updates. By default checks for a new version
813    /// and offers to install it. Use flags to customize behavior.
814    ///
815    /// Examples:
816    ///   vtcode update
817    ///   vtcode update --check
818    ///   vtcode update --force
819    ///   vtcode update --list
820    ///   vtcode update --pin 0.120.0
821    ///   vtcode update --unpin
822    ///   vtcode update --with-desktop
823    #[command(name = "update")]
824    Update {
825        /// Check for updates without installing
826        #[arg(
827            long,
828            long_help = "Check whether a newer version is available without installing it."
829        )]
830        check: bool,
831        /// Force update even if on latest version
832        #[arg(
833            long,
834            long_help = "Reinstall or downgrade even if the current version is already the latest."
835        )]
836        force: bool,
837        /// List available versions
838        #[arg(long, long_help = "Print available release versions from GitHub and exit.")]
839        list: bool,
840        /// Number of versions to list (default: 10)
841        #[arg(
842            long,
843            default_value = "10",
844            long_help = "Maximum number of versions to display with --list."
845        )]
846        limit: usize,
847        /// Pin to a specific version
848        #[arg(
849            long,
850            value_name = "VERSION",
851            long_help = "Pin the binary to a specific version.\nAuto-updates are disabled until --unpin is used."
852        )]
853        pin: Option<String>,
854        /// Unpin version
855        #[arg(long, long_help = "Remove a previously set version pin and resume auto-updates.")]
856        unpin: bool,
857        /// Set release channel (stable, beta, nightly)
858        #[arg(
859            long,
860            value_name = "CHANNEL",
861            long_help = "Switch the release channel.\nAccepted values: stable, beta, nightly."
862        )]
863        channel: Option<String>,
864        /// Show current update configuration
865        #[arg(
866            long,
867            long_help = "Display the current update configuration (channel, pin, intervals) and exit."
868        )]
869        show_config: bool,
870        /// Install or update the macOS desktop app without prompting
871        #[arg(
872            long,
873            conflicts_with = "without_desktop",
874            long_help = "Install or update the macOS desktop app from the prebuilt release asset without prompting.\nFails on non-macOS platforms."
875        )]
876        with_desktop: bool,
877        /// Skip the macOS desktop app without prompting
878        #[arg(
879            long,
880            conflicts_with = "with_desktop",
881            long_help = "Skip the macOS desktop app install/update step without prompting."
882        )]
883        without_desktop: bool,
884    },
885
886    /// Start Anthropic API compatibility server
887    #[command(name = "anthropic-api")]
888    AnthropicApi {
889        /// Port to run the server on
890        #[arg(long, default_value = "11434")]
891        port: u16,
892        /// Host address to bind to
893        #[arg(long, default_value = "127.0.0.1")]
894        host: String,
895    },
896}
897
898impl Default for Cli {
899    fn default() -> Self {
900        Self {
901            color: ColorSelection { color: ColorChoice::Auto },
902            workspace_path: None,
903            model: Some(ModelId::default().to_string()),
904            provider: Some("gemini".to_owned()),
905            api_key_env: "GEMINI_API_KEY".to_owned(),
906            workspace: None,
907            research_preview: false,
908            security_level: "moderate".to_owned(),
909            show_file_diffs: false,
910            max_concurrent_ops: 5,
911            api_rate_limit: 30,
912            max_tool_calls: 10,
913            verbose: false,
914            quiet: false,
915            config: Vec::new(),
916            log_level: "info".to_owned(),
917            no_color: false,
918            theme: None,
919            skip_confirmations: false,
920            codex_experimental: false,
921            no_codex_experimental: false,
922            print: None,
923            full_auto: None,
924            resume_session: None,
925            continue_latest: false,
926            fork_session: None,
927            all: false,
928            session_id: None,
929            summarize: false,
930            debug: false,
931            enable_skills: false,
932            tick_rate: 250,
933            frame_rate: 60,
934            agent: None,
935            allowed_tools: Vec::new(),
936            disallowed_tools: Vec::new(),
937            dangerously_skip_permissions: false,
938            full_access: false,
939            ide: false,
940            chrome: false,
941            no_chrome: false,
942            command: Some(Commands::Chat),
943        }
944    }
945}
946
947impl Cli {
948    /// Get the effective API key environment variable
949    ///
950    /// Automatically infers the API key environment variable based on the provider
951    /// when the current value matches the default or is not explicitly set.
952    pub fn get_api_key_env(&self) -> String {
953        crate::config::api_keys::resolve_api_key_env(
954            self.provider
955                .as_deref()
956                .unwrap_or(crate::config::constants::defaults::DEFAULT_PROVIDER),
957            &self.api_key_env,
958        )
959    }
960
961    pub fn codex_experimental_override(&self) -> Option<bool> {
962        if self.codex_experimental {
963            Some(true)
964        } else if self.no_codex_experimental {
965            Some(false)
966        } else {
967            None
968        }
969    }
970}
971
972#[cfg(test)]
973mod tests;