-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathargs.rs
More file actions
2058 lines (1781 loc) · 65.7 KB
/
args.rs
File metadata and controls
2058 lines (1781 loc) · 65.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! CLI argument structures and parsing.
//!
//! Defines all command-line argument structures using clap.
use clap::{Args, Parser, Subcommand};
use std::path::PathBuf;
use super::styles::{AFTER_HELP, BEFORE_HELP, HELP_TEMPLATE, categories, get_styles};
use crate::acp_cmd::AcpCli;
use crate::agent_cmd::AgentCli;
use crate::alias_cmd::AliasCli;
use crate::cache_cmd::CacheCli;
use crate::compact_cmd::CompactCli;
use crate::dag_cmd::DagCli;
use crate::debug_cmd::DebugCli;
use crate::exec_cmd::ExecCli;
use crate::export_cmd::ExportCommand;
use crate::feedback_cmd::FeedbackCli;
use crate::github_cmd::GitHubCli;
use crate::import_cmd::ImportCommand;
use crate::lock_cmd::LockCli;
use crate::logs_cmd::LogsCli;
use crate::mcp_cmd::McpCli;
use crate::models_cmd::ModelsCli;
use crate::plugin_cmd::PluginCli;
use crate::pr_cmd::PrCli;
use crate::run_cmd::RunCli;
use crate::scrape_cmd::ScrapeCommand;
use crate::shell_cmd::ShellCli;
use crate::stats_cmd::StatsCli;
use crate::uninstall_cmd::UninstallCli;
use crate::upgrade_cmd::UpgradeCli;
use crate::workspace_cmd::WorkspaceCli;
use crate::{LandlockCommand, SeatbeltCommand, WindowsCommand};
use cortex_common::CliConfigOverrides;
/// Build-time version string with commit hash and build date.
pub fn get_long_version() -> &'static str {
const VERSION: &str = env!("CARGO_PKG_VERSION");
const GIT_HASH: &str = match option_env!("CORTEX_GIT_HASH") {
Some(v) => v,
None => "unknown",
};
const BUILD_DATE: &str = match option_env!("CORTEX_BUILD_DATE") {
Some(v) => v,
None => "unknown",
};
static LONG_VERSION: std::sync::OnceLock<String> = std::sync::OnceLock::new();
LONG_VERSION.get_or_init(|| format!("{} ({} {})", VERSION, GIT_HASH, BUILD_DATE))
}
/// Log verbosity level for CLI output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum LogLevel {
/// Only show errors
Error,
/// Show warnings and errors
Warn,
/// Show informational messages, warnings, and errors (default)
#[default]
Info,
/// Show debug messages and above
Debug,
/// Show all messages including trace-level details
Trace,
}
impl LogLevel {
/// Convert to tracing filter string.
pub fn as_filter_str(&self) -> &'static str {
match self {
LogLevel::Error => "error",
LogLevel::Warn => "warn",
LogLevel::Info => "info",
LogLevel::Debug => "debug",
LogLevel::Trace => "trace",
}
}
/// Parse from string (case-insensitive).
pub fn from_str_loose(s: &str) -> Option<LogLevel> {
match s.to_lowercase().as_str() {
"error" => Some(LogLevel::Error),
"warn" | "warning" => Some(LogLevel::Warn),
"info" => Some(LogLevel::Info),
"debug" => Some(LogLevel::Debug),
"trace" => Some(LogLevel::Trace),
_ => None,
}
}
}
/// Color output mode for CLI.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum ColorMode {
/// Automatically detect if output is a terminal
#[default]
Auto,
/// Always output with colors
Always,
/// Never output with colors
Never,
}
/// Cortex CLI - AI Coding Agent
///
/// If no subcommand is specified, starts the interactive TUI.
#[derive(Parser)]
#[command(name = "cortex")]
#[command(author, version, long_version = get_long_version())]
#[command(about = "Cortex - AI Coding Agent", long_about = None)]
#[command(
styles = get_styles(),
subcommand_negates_reqs = true,
override_usage = "cortex [OPTIONS] [PROMPT]\n cortex [OPTIONS] <COMMAND> [ARGS]",
before_help = BEFORE_HELP,
after_help = AFTER_HELP,
help_template = HELP_TEMPLATE
)]
pub struct Cli {
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
/// Enable verbose output (same as --log-level debug)
#[arg(long = "verbose", short = 'v', global = true)]
pub verbose: bool,
/// Enable trace-level logging for debugging
#[arg(long = "trace", global = true)]
pub trace: bool,
/// Control color output: auto (default), always, or never
#[arg(long = "color", global = true, value_enum, default_value_t = ColorMode::Auto)]
pub color: ColorMode,
#[clap(flatten)]
pub interactive: InteractiveArgs,
#[command(subcommand)]
pub command: Option<Commands>,
}
/// Arguments for interactive mode.
#[derive(Args, Debug, Default)]
pub struct InteractiveArgs {
/// Model to use (e.g., claude-sonnet-4-20250514, gpt-4o, gemini-2.0-flash)
#[arg(short, long, help_heading = "Model Configuration")]
pub model: Option<String>,
/// Use open-source/local LLM providers instead of cloud APIs.
#[arg(
long = "oss",
default_value_t = false,
help_heading = "Model Configuration"
)]
pub oss: bool,
/// Configuration profile from config.toml
#[arg(long = "profile", short = 'p', help_heading = "Model Configuration")]
pub config_profile: Option<String>,
/// Select the sandbox policy for shell commands
#[arg(long = "sandbox", short = 's', help_heading = "Security")]
pub sandbox_mode: Option<String>,
/// Set the approval policy for tool executions.
#[arg(
long = "ask-for-approval",
short = 'a',
value_name = "POLICY",
help_heading = "Security"
)]
pub approval_policy: Option<String>,
/// Enable fully automatic mode with sandboxed execution.
#[arg(long = "full-auto", default_value_t = false, help_heading = "Security")]
pub full_auto: bool,
/// Skip all confirmation prompts and execute commands without sandboxing. DANGEROUS!
#[arg(
long = "dangerously-bypass-approvals-and-sandbox",
alias = "yolo",
default_value_t = false,
conflicts_with_all = ["approval_policy", "full_auto"],
help_heading = "Security"
)]
pub dangerously_bypass_approvals_and_sandbox: bool,
/// Tell the agent to use the specified directory as its working root
#[arg(
long = "cd",
short = 'C',
value_name = "DIR",
help_heading = "Workspace"
)]
pub cwd: Option<PathBuf>,
/// Additional directories that should be writable
#[arg(long = "add-dir", value_name = "DIR", help_heading = "Workspace")]
pub add_dir: Vec<PathBuf>,
/// Image files to attach to the initial prompt
#[arg(long = "image", short = 'i', value_delimiter = ',', num_args = 1.., help_heading = "Workspace")]
pub images: Vec<PathBuf>,
/// Enable web search capability for the agent.
#[arg(long = "search", default_value_t = false, help_heading = "Features")]
pub web_search: bool,
/// Maximum number of concurrent agent threads
#[arg(
long = "max-agent-threads",
value_name = "N",
help_heading = "Execution"
)]
pub max_agent_threads: Option<usize>,
/// Maximum number of concurrent tool executions
#[arg(
long = "max-tool-threads",
value_name = "N",
help_heading = "Execution"
)]
pub max_tool_threads: Option<usize>,
/// Timeout for shell commands in seconds
#[arg(
long = "command-timeout",
value_name = "SECONDS",
help_heading = "Execution"
)]
pub command_timeout: Option<u64>,
/// Timeout for HTTP requests in seconds
#[arg(
long = "http-timeout",
value_name = "SECONDS",
help_heading = "Execution"
)]
pub http_timeout: Option<u64>,
/// Disable streaming responses
#[arg(
long = "no-streaming",
default_value_t = false,
help_heading = "Execution"
)]
pub no_streaming: bool,
/// Set log verbosity level (error, warn, info, debug, trace)
#[arg(
long = "log-level",
short = 'L',
value_enum,
default_value = "info",
help_heading = "Debugging"
)]
pub log_level: LogLevel,
/// Enable debug mode: writes ALL trace-level logs to ./debug.txt
#[arg(long = "debug", help_heading = "Debugging")]
pub debug: bool,
/// Initial prompt (if no subcommand).
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
pub prompt: Vec<String>,
}
/// CLI subcommands.
#[derive(Subcommand)]
pub enum Commands {
// ========================================================================
// 🚀 Execution (order 1-9)
// ========================================================================
/// Run Cortex non-interactively with advanced options
#[command(visible_alias = "r", display_order = 1)]
#[command(next_help_heading = categories::EXECUTION)]
Run(RunCli),
/// Execute in headless mode (for CI/CD, scripts, automation)
#[command(visible_alias = "e", display_order = 2)]
#[command(next_help_heading = categories::EXECUTION)]
Exec(ExecCli),
// ========================================================================
// 📋 Session Management (order 10-19)
// ========================================================================
/// Resume a previous interactive session
#[command(display_order = 10)]
#[command(next_help_heading = categories::SESSION)]
Resume(ResumeCommand),
/// List previous sessions
#[command(display_order = 11)]
#[command(next_help_heading = categories::SESSION)]
Sessions(SessionsCommand),
/// Export a session to JSON format
#[command(display_order = 12)]
#[command(next_help_heading = categories::SESSION)]
Export(ExportCommand),
/// Import a session from JSON file or URL
#[command(display_order = 13)]
#[command(next_help_heading = categories::SESSION)]
Import(ImportCommand),
/// Delete a session
#[command(display_order = 14)]
#[command(next_help_heading = categories::SESSION)]
Delete(DeleteCommand),
// ========================================================================
// 🔐 Authentication (order 20-29)
// ========================================================================
/// Authenticate with Cortex API
#[command(display_order = 20)]
#[command(next_help_heading = categories::AUTH)]
Login(LoginCommand),
/// Remove stored authentication credentials
#[command(display_order = 21)]
#[command(next_help_heading = categories::AUTH)]
Logout(LogoutCommand),
/// Show currently authenticated user
#[command(display_order = 22)]
#[command(next_help_heading = categories::AUTH)]
Whoami,
// ========================================================================
// 🔌 Extensibility (order 30-39)
// ========================================================================
/// Manage agents (list, create, show)
#[command(display_order = 30)]
#[command(next_help_heading = categories::EXTENSION)]
Agent(AgentCli),
/// Manage MCP (Model Context Protocol) servers
#[command(display_order = 31)]
#[command(next_help_heading = categories::EXTENSION)]
Mcp(McpCli),
/// Run the MCP server (stdio transport)
#[command(display_order = 32, hide = true)]
#[command(next_help_heading = categories::EXTENSION)]
McpServer,
/// Start ACP server for IDE integration (e.g., Zed)
#[command(display_order = 33)]
#[command(next_help_heading = categories::EXTENSION)]
Acp(AcpCli),
// ========================================================================
// ⚙️ Configuration (order 40-49)
// ========================================================================
/// Show or edit configuration
#[command(display_order = 40)]
#[command(next_help_heading = categories::CONFIG)]
Config(ConfigCommand),
/// List available models
#[command(display_order = 41)]
#[command(next_help_heading = categories::CONFIG)]
Models(ModelsCli),
/// Inspect feature flags
#[command(display_order = 42)]
#[command(next_help_heading = categories::CONFIG)]
Features(FeaturesCommand),
/// Initialize AGENTS.md in the current directory
#[command(display_order = 43)]
#[command(next_help_heading = categories::CONFIG)]
Init(InitCommand),
// ========================================================================
// 🛠️ Utilities (order 50-59)
// ========================================================================
/// GitHub integration (actions, workflows)
#[command(visible_alias = "gh", display_order = 50)]
#[command(next_help_heading = categories::UTILITIES)]
Github(GitHubCli),
/// Checkout a pull request
#[command(display_order = 51)]
#[command(next_help_heading = categories::UTILITIES)]
Pr(PrCli),
/// Scrape web content to markdown/text/html
#[command(display_order = 52)]
#[command(next_help_heading = categories::UTILITIES)]
Scrape(ScrapeCommand),
/// Show usage statistics
#[command(display_order = 53)]
#[command(next_help_heading = categories::UTILITIES)]
Stats(StatsCli),
/// Generate shell completion scripts
#[command(display_order = 54)]
#[command(next_help_heading = categories::UTILITIES)]
Completion(CompletionCommand),
// ========================================================================
// 🔧 Maintenance (order 60-69)
// ========================================================================
/// Check for and install updates
#[command(display_order = 60)]
#[command(next_help_heading = categories::MAINTENANCE)]
Upgrade(UpgradeCli),
/// Uninstall Cortex CLI
#[command(display_order = 61)]
#[command(next_help_heading = categories::MAINTENANCE)]
Uninstall(UninstallCli),
/// Data compaction and cleanup (logs, sessions, history)
#[command(visible_aliases = ["gc", "cleanup"], display_order = 62)]
#[command(next_help_heading = categories::MAINTENANCE)]
Compact(CompactCli),
/// Manage cache
#[command(display_order = 63)]
#[command(next_help_heading = categories::MAINTENANCE)]
Cache(CacheCli),
/// View application logs
#[command(display_order = 64)]
#[command(next_help_heading = categories::MAINTENANCE)]
Logs(LogsCli),
/// Submit feedback and bug reports
#[command(visible_alias = "report", display_order = 65)]
#[command(next_help_heading = categories::MAINTENANCE)]
Feedback(FeedbackCli),
/// Lock/protect sessions from deletion
#[command(visible_alias = "protect", display_order = 66)]
#[command(next_help_heading = categories::MAINTENANCE)]
Lock(LockCli),
/// Manage command aliases
#[command(visible_alias = "aliases", display_order = 67)]
#[command(next_help_heading = categories::MAINTENANCE)]
Alias(AliasCli),
/// Manage plugins
#[command(visible_alias = "plugins", display_order = 68)]
#[command(next_help_heading = categories::MAINTENANCE)]
Plugin(PluginCli),
// ========================================================================
// Hidden commands (internal/debug/advanced)
// ========================================================================
/// Debug and diagnostic commands
#[command(display_order = 99, hide = true)]
Debug(DebugCli),
/// Start interactive shell/REPL mode
#[command(visible_aliases = ["interactive", "repl"], hide = true)]
Shell(ShellCli),
/// Execute and manage task DAGs (dependency graphs)
#[command(visible_alias = "tasks", hide = true)]
Dag(DagCli),
/// Discover Cortex servers on the local network
#[command(hide = true)]
Servers(ServersCommand),
/// View prompt history from past sessions
#[command(hide = true)]
History(HistoryCommand),
/// Manage workspace/project settings
#[command(visible_alias = "project", hide = true)]
Workspace(WorkspaceCli),
/// Run commands within a Cortex-provided sandbox
#[command(visible_alias = "sb", hide = true)]
Sandbox(SandboxArgs),
/// Run the HTTP API server (for desktop/web integration)
#[command(hide = true)]
Serve(ServeCommand),
}
// ============================================================================
// Subcommand argument structures
// ============================================================================
/// Login command.
#[derive(Args)]
pub struct LoginCommand {
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Read the API key from stdin
#[arg(long = "with-api-key")]
pub with_api_key: bool,
/// Provide API token directly (for CI/CD automation).
#[arg(long = "token", value_name = "TOKEN", conflicts_with = "with_api_key")]
pub token: Option<String>,
/// Use device code authentication flow
#[arg(long = "device-auth")]
pub use_device_code: bool,
/// Use enterprise SSO authentication.
#[arg(long = "sso")]
pub use_sso: bool,
/// Override the OAuth issuer base URL (advanced)
#[arg(long = "experimental_issuer", value_name = "URL", hide = true)]
pub issuer_base_url: Option<String>,
/// Override the OAuth client ID (advanced)
#[arg(long = "experimental_client-id", value_name = "CLIENT_ID", hide = true)]
pub client_id: Option<String>,
#[command(subcommand)]
pub action: Option<LoginSubcommand>,
}
/// Login subcommands.
#[derive(Subcommand)]
pub enum LoginSubcommand {
/// Show login status
Status,
}
/// Logout command.
#[derive(Args)]
pub struct LogoutCommand {
#[clap(skip)]
pub config_overrides: CliConfigOverrides,
/// Skip confirmation prompt and log out immediately.
#[arg(short = 'y', long = "yes")]
pub yes: bool,
/// Log out from all logged in accounts.
#[arg(long = "all")]
pub all: bool,
}
/// Completion command.
#[derive(Args)]
pub struct CompletionCommand {
/// Shell to generate completions for.
#[arg(value_enum)]
pub shell: Option<clap_complete::Shell>,
/// Install completions to your shell configuration file.
#[arg(long = "install")]
pub install: bool,
}
/// Init command - initialize AGENTS.md.
#[derive(Args)]
pub struct InitCommand {
/// Force overwrite if AGENTS.md already exists.
#[arg(short = 'f', long = "force")]
pub force: bool,
/// Accept defaults without prompting (non-interactive mode).
#[arg(short = 'y', long = "yes")]
pub yes: bool,
}
/// Resume command.
#[derive(Args)]
pub struct ResumeCommand {
/// Session ID to resume (or "last" for most recent)
#[arg(value_name = "SESSION_ID")]
pub session_id: Option<String>,
/// Continue the most recent session without showing the picker
#[arg(long = "last", default_value_t = false, conflicts_with = "session_id")]
pub last: bool,
/// Show interactive picker to select from recent sessions
#[arg(long = "pick", default_value_t = false, conflicts_with_all = ["session_id", "last"])]
pub pick: bool,
/// Show all sessions (disables cwd filtering)
#[arg(long = "all", default_value_t = false)]
pub all: bool,
/// Do not persist session changes (incompatible with resume, will error).
#[arg(long = "no-session", default_value_t = false)]
pub no_session: bool,
#[clap(flatten)]
pub config_overrides: CliConfigOverrides,
}
/// Sessions command.
#[derive(Args)]
pub struct SessionsCommand {
/// Show all sessions including from other directories
#[arg(long)]
pub all: bool,
/// Show sessions from the last N days
#[arg(long)]
pub days: Option<u32>,
/// Show sessions since this date (YYYY-MM-DD)
#[arg(long)]
pub since: Option<String>,
/// Show sessions until this date (YYYY-MM-DD)
#[arg(long)]
pub until: Option<String>,
/// Show only favorite sessions
#[arg(long)]
pub favorites: bool,
/// Search sessions by title or ID
#[arg(long, short)]
pub search: Option<String>,
/// Maximum number of sessions to show
#[arg(long, short)]
pub limit: Option<usize>,
/// Output in JSON format
#[arg(long)]
pub json: bool,
}
/// Delete command - delete a session.
#[derive(Args)]
pub struct DeleteCommand {
/// Session ID to delete (full UUID or 8-character prefix)
#[arg(required = true)]
pub session_id: String,
/// Skip confirmation prompt
#[arg(long, short = 'y')]
pub yes: bool,
/// Force deletion even if session is locked
#[arg(long, short = 'f')]
pub force: bool,
}
/// Config command.
#[derive(Args)]
pub struct ConfigCommand {
/// Show configuration in JSON format
#[arg(long)]
pub json: bool,
/// Edit configuration interactively
#[arg(long)]
pub edit: bool,
#[command(subcommand)]
pub action: Option<ConfigSubcommand>,
}
/// Config subcommands.
#[derive(Subcommand)]
pub enum ConfigSubcommand {
/// Get a configuration value
Get(ConfigGetArgs),
/// Set a configuration value
Set(ConfigSetArgs),
/// Unset (remove) a configuration value
Unset(ConfigUnsetArgs),
}
/// Arguments for config get.
#[derive(Args)]
pub struct ConfigGetArgs {
/// Configuration key to get (e.g., model, provider)
pub key: String,
}
/// Arguments for config set.
#[derive(Args)]
pub struct ConfigSetArgs {
/// Configuration key (e.g., model, provider)
pub key: String,
/// Value to set
pub value: String,
}
/// Arguments for config unset.
#[derive(Args)]
pub struct ConfigUnsetArgs {
/// Configuration key to remove
pub key: String,
}
/// Sandbox debug commands.
#[derive(Args)]
pub struct SandboxArgs {
#[command(subcommand)]
pub cmd: SandboxCommand,
}
/// Sandbox subcommands.
#[derive(Subcommand)]
pub enum SandboxCommand {
/// Run a command under Seatbelt (macOS only)
#[command(visible_alias = "seatbelt")]
Macos(SeatbeltCommand),
/// Run a command under Landlock+seccomp (Linux only)
#[command(visible_alias = "landlock")]
Linux(LandlockCommand),
/// Run a command under Windows restricted token (Windows only)
Windows(WindowsCommand),
}
/// Features command.
#[derive(Args)]
pub struct FeaturesCommand {
#[command(subcommand)]
pub sub: FeaturesSubcommand,
}
/// Features subcommands.
#[derive(Subcommand)]
pub enum FeaturesSubcommand {
/// List known features with their stage and effective state
List,
}
/// Serve command - runs HTTP API server.
#[derive(Args)]
pub struct ServeCommand {
/// Port to listen on
#[arg(short, long, default_value = "3000")]
pub port: u16,
/// Host address to bind the server to.
#[arg(long, default_value = "127.0.0.1")]
pub host: String,
/// Authentication token for API access.
#[arg(long = "auth-token")]
pub auth_token: Option<String>,
/// Enable CORS (Cross-Origin Resource Sharing) for all origins.
#[arg(long)]
pub cors: bool,
/// Allowed CORS origin(s). Can be specified multiple times.
#[arg(long = "cors-origin", value_name = "ORIGIN")]
pub cors_origins: Vec<String>,
/// Enable mDNS service discovery (advertise on local network)
#[arg(long = "mdns", default_value_t = false)]
pub mdns: bool,
/// Disable mDNS service discovery
#[arg(long = "no-mdns", default_value_t = false, conflicts_with = "mdns")]
pub no_mdns: bool,
/// Custom service name for mDNS advertising
#[arg(long = "mdns-name")]
pub mdns_name: Option<String>,
}
/// Servers command - discover Cortex servers on the network.
#[derive(Args)]
pub struct ServersCommand {
#[command(subcommand)]
pub action: Option<ServersSubcommand>,
/// Timeout for discovery in seconds
#[arg(short, long, default_value = "3")]
pub timeout: u64,
/// Output in JSON format
#[arg(long)]
pub json: bool,
}
/// Servers subcommands.
#[derive(Subcommand)]
pub enum ServersSubcommand {
/// Re-scan the network for mDNS servers (forces a fresh discovery)
Refresh(ServersRefreshArgs),
}
/// Arguments for servers refresh command.
#[derive(Args)]
pub struct ServersRefreshArgs {
/// Timeout for discovery in seconds
#[arg(short, long, default_value = "5")]
pub timeout: u64,
/// Output in JSON format
#[arg(long)]
pub json: bool,
}
/// History command - view past prompts and sessions.
#[derive(Args)]
#[command(
after_help = "With no subcommand, list recent prompts. Use search to filter history or clear to delete it."
)]
pub struct HistoryCommand {
#[command(subcommand)]
pub action: Option<HistorySubcommand>,
/// Maximum number of entries to show
#[arg(short = 'n', long, default_value = "20")]
pub limit: usize,
/// Show history from all directories
#[arg(long)]
pub all: bool,
/// Output in JSON format
#[arg(long)]
pub json: bool,
}
/// History subcommands.
#[derive(Subcommand)]
pub enum HistorySubcommand {
/// Search history for a pattern
Search(HistorySearchArgs),
/// Clear history (requires confirmation)
Clear(HistoryClearArgs),
}
/// Arguments for history search command.
#[derive(Args)]
pub struct HistorySearchArgs {
/// Pattern to search for in prompts
pub pattern: String,
/// Maximum number of results
#[arg(short = 'n', long, default_value = "20")]
pub limit: usize,
/// Output in JSON format
#[arg(long)]
pub json: bool,
}
/// Arguments for history clear command.
#[derive(Args)]
pub struct HistoryClearArgs {
/// Skip confirmation prompt
#[arg(short = 'y', long)]
pub yes: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use clap::{CommandFactory, Parser};
// ==========================================================================
// LogLevel tests
// ==========================================================================
#[test]
fn test_log_level_default() {
let default = LogLevel::default();
assert_eq!(default, LogLevel::Info);
}
#[test]
fn test_log_level_as_filter_str() {
assert_eq!(LogLevel::Error.as_filter_str(), "error");
assert_eq!(LogLevel::Warn.as_filter_str(), "warn");
assert_eq!(LogLevel::Info.as_filter_str(), "info");
assert_eq!(LogLevel::Debug.as_filter_str(), "debug");
assert_eq!(LogLevel::Trace.as_filter_str(), "trace");
}
#[test]
fn test_log_level_from_str_loose_valid() {
assert_eq!(LogLevel::from_str_loose("error"), Some(LogLevel::Error));
assert_eq!(LogLevel::from_str_loose("warn"), Some(LogLevel::Warn));
assert_eq!(LogLevel::from_str_loose("warning"), Some(LogLevel::Warn));
assert_eq!(LogLevel::from_str_loose("info"), Some(LogLevel::Info));
assert_eq!(LogLevel::from_str_loose("debug"), Some(LogLevel::Debug));
assert_eq!(LogLevel::from_str_loose("trace"), Some(LogLevel::Trace));
}
#[test]
fn test_log_level_from_str_loose_case_insensitive() {
assert_eq!(LogLevel::from_str_loose("ERROR"), Some(LogLevel::Error));
assert_eq!(LogLevel::from_str_loose("WARN"), Some(LogLevel::Warn));
assert_eq!(LogLevel::from_str_loose("WARNING"), Some(LogLevel::Warn));
assert_eq!(LogLevel::from_str_loose("INFO"), Some(LogLevel::Info));
assert_eq!(LogLevel::from_str_loose("Debug"), Some(LogLevel::Debug));
assert_eq!(LogLevel::from_str_loose("TrAcE"), Some(LogLevel::Trace));
}
#[test]
fn test_log_level_from_str_loose_invalid() {
assert_eq!(LogLevel::from_str_loose("invalid"), None);
assert_eq!(LogLevel::from_str_loose(""), None);
assert_eq!(LogLevel::from_str_loose("err"), None);
assert_eq!(LogLevel::from_str_loose("verbose"), None);
}
#[test]
fn test_log_level_equality() {
assert_eq!(LogLevel::Error, LogLevel::Error);
assert_ne!(LogLevel::Error, LogLevel::Warn);
assert_ne!(LogLevel::Info, LogLevel::Debug);
}
#[test]
fn test_log_level_clone() {
let level = LogLevel::Debug;
let cloned = level;
assert_eq!(level, cloned);
}
// ==========================================================================
// ColorMode tests
// ==========================================================================
#[test]
fn test_color_mode_default() {
let default = ColorMode::default();
assert_eq!(default, ColorMode::Auto);
}
#[test]
fn test_color_mode_equality() {
assert_eq!(ColorMode::Auto, ColorMode::Auto);
assert_eq!(ColorMode::Always, ColorMode::Always);
assert_eq!(ColorMode::Never, ColorMode::Never);
assert_ne!(ColorMode::Auto, ColorMode::Always);
assert_ne!(ColorMode::Always, ColorMode::Never);
}
#[test]
fn test_color_mode_clone() {
let mode = ColorMode::Always;
let cloned = mode;
assert_eq!(mode, cloned);
}
// ==========================================================================
// InteractiveArgs tests
// ==========================================================================
#[test]
fn test_interactive_args_default() {
let args = InteractiveArgs::default();
assert!(args.model.is_none());
assert!(!args.oss);
assert!(args.config_profile.is_none());
assert!(args.sandbox_mode.is_none());
assert!(args.approval_policy.is_none());
assert!(!args.full_auto);
assert!(!args.dangerously_bypass_approvals_and_sandbox);
assert!(args.cwd.is_none());
assert!(args.add_dir.is_empty());
assert!(args.images.is_empty());
assert!(!args.web_search);
assert_eq!(args.log_level, LogLevel::Info);
assert!(!args.debug);
assert!(args.prompt.is_empty());
}
// ==========================================================================
// Cli parsing tests
// ==========================================================================
#[test]
fn test_cli_no_args() {
let cli = Cli::try_parse_from(["cortex"]).expect("should parse with no args");
assert!(cli.command.is_none());
assert!(!cli.verbose);
assert!(!cli.trace);
assert_eq!(cli.color, ColorMode::Auto);
}
#[test]
fn test_cli_verbose_flag() {
let cli = Cli::try_parse_from(["cortex", "--verbose"]).expect("should parse --verbose");
assert!(cli.verbose);
}
#[test]
fn test_cli_verbose_short_flag() {
let cli = Cli::try_parse_from(["cortex", "-v"]).expect("should parse -v");
assert!(cli.verbose);
}
#[test]