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