forked from OpenCoven/coven-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
11823 lines (10953 loc) · 460 KB
/
Copy pathlib.rs
File metadata and controls
11823 lines (10953 loc) · 460 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
// claurst-commands: Slash command system for Coven Code.
//
// This crate implements the /command framework that allows users to type
// commands like /help, /compact, /clear, /model, /config, /cost, etc.
// Each command is a struct implementing the `SlashCommand` trait.
use async_trait::async_trait;
use claurst_core::config::{Config, Settings, Theme};
use claurst_core::cost::CostTracker;
use claurst_core::types::{ContentBlock, Message};
use once_cell::sync::Lazy;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
// ---------------------------------------------------------------------------
// Core trait
// ---------------------------------------------------------------------------
/// Context available to every slash command.
pub struct CommandContext {
pub config: Config,
pub cost_tracker: Arc<CostTracker>,
pub messages: Vec<Message>,
pub working_dir: std::path::PathBuf,
pub session_id: String,
pub session_title: Option<String>,
/// Remote session URL set when a bridge connection is active.
pub remote_session_url: Option<String>,
// Note: config already contains hooks, mcp_servers, etc.
/// Live MCP manager — present when servers are connected.
pub mcp_manager: Option<Arc<claurst_mcp::McpManager>>,
/// Optional callback for starting an MCP OAuth flow in the background.
pub mcp_auth_runner: Option<Arc<dyn Fn(claurst_mcp::oauth::McpAuthSession) + Send + Sync>>,
}
const COVEN_CODE_REPO: &str = "OpenCoven/coven-code";
/// Result of running a slash command.
#[derive(Debug)]
pub enum CommandResult {
/// Display a message to the user (does NOT go to the model).
Message(String),
/// Inject a message into the conversation as though the user typed it.
UserMessage(String),
/// Modify the configuration.
ConfigChange(Config),
/// Modify the configuration and show a specific status message.
ConfigChangeMessage(Config, String),
/// Trigger a background MCP OAuth flow and request runtime reconnect on success.
McpAuthFlow {
/// The configured MCP server name.
server_name: String,
/// The browser URL shown to the user while the background flow runs.
auth_url: String,
/// The local callback URL waiting for the OAuth redirect.
redirect_uri: String,
},
/// Clear the conversation.
ClearConversation,
/// Replace the conversation with a specific message list (used by /rewind).
SetMessages(Vec<Message>),
/// Load a previously saved session into the live REPL.
ResumeSession(claurst_core::history::ConversationSession),
/// Update the current session title.
RenameSession(String),
/// Trigger the OAuth login flow (handled by the REPL in main.rs).
/// The bool indicates whether to use Claude.ai auth (true) or Console auth (false).
StartOAuthFlow(bool),
/// Trigger the OAuth login flow for a specific provider with optional
/// human-friendly label for the new account profile.
///
/// `provider` is one of `claurst_core::accounts::PROVIDER_ANTHROPIC` or
/// `PROVIDER_CODEX`. `login_with_claude_ai` is only meaningful for
/// Anthropic.
StartLoginForProvider {
provider: String,
login_with_claude_ai: bool,
label: Option<String>,
},
/// Exit the REPL.
Exit,
/// No visible output.
Silent,
/// An error.
Error(String),
/// Open the rewind/message-selector overlay in the TUI.
/// The TUI will call SetMessages when the user confirms.
OpenRewindOverlay,
/// Open the hooks configuration browser overlay in the TUI.
/// Falls back to a text listing in non-TUI contexts.
OpenHooksOverlay,
/// Open the import-config overlay in the TUI.
OpenImportConfigOverlay,
/// Clear saved provider auth, model selection, and model caches, then
/// rebuild the live runtime state.
RefreshProviderState,
/// Activate a speech mode (caveman/rocky) with level, or deactivate (normal).
/// (mode, level) — mode=None means deactivate.
SpeechMode { mode: Option<String>, level: String },
}
/// Every slash command implements this trait.
#[async_trait]
pub trait SlashCommand: Send + Sync {
/// The primary name (without the leading `/`).
fn name(&self) -> &str;
/// Alias names (e.g. `["h"]` for `/help`).
fn aliases(&self) -> Vec<&str> {
vec![]
}
/// One-line description for /help.
fn description(&self) -> &str;
/// Detailed help text (shown by `/help <command>`).
fn help(&self) -> &str {
self.description()
}
/// Whether this command is visible in /help output.
fn hidden(&self) -> bool {
false
}
/// Execute the command with the given arguments string.
async fn execute(&self, args: &str, ctx: &mut CommandContext) -> CommandResult;
}
fn stripped_model_for_provider<'a>(provider_id: &str, model_id: &'a str) -> &'a str {
model_id
.strip_prefix(&format!("{provider_id}/"))
.unwrap_or(model_id)
}
fn canonical_model_for_provider(provider_id: &str, model_id: &str) -> String {
if provider_id == "anthropic" || model_id.contains('/') {
model_id.to_string()
} else {
format!("{provider_id}/{model_id}")
}
}
fn provider_lookup_ids(provider_id: &str) -> Vec<&str> {
match provider_id {
"togetherai" | "together-ai" => vec!["togetherai", "together-ai"],
"lmstudio" | "lm-studio" => vec!["lmstudio", "lm-studio"],
"llamacpp" | "llama-cpp" | "llama-server" => {
vec!["llamacpp", "llama-cpp", "llama-server"]
}
"moonshot" | "moonshotai" => vec!["moonshot", "moonshotai"],
"zhipu" | "zhipuai" => vec!["zhipu", "zhipuai"],
"vultr" | "vultr-ai" => vec!["vultr", "vultr-ai"],
"google" | "google-vertex" => vec!["google", "google-vertex"],
_ => vec![provider_id],
}
}
fn resolve_fast_model_id(config: &Config) -> String {
let provider_id = config.selected_provider_id();
let registry = claurst_api::ModelRegistry::new();
provider_lookup_ids(provider_id)
.into_iter()
.find_map(|lookup_id| registry.best_small_model_for_provider(lookup_id))
.unwrap_or_else(|| {
stripped_model_for_provider(provider_id, config.effective_model()).to_string()
})
}
async fn provider_for_config(
config: &Config,
) -> Option<std::sync::Arc<dyn claurst_api::LlmProvider>> {
let anthropic_auth = config.resolve_anthropic_auth_async().await;
let registry = claurst_api::ProviderRegistry::from_config(
config,
claurst_api::client::ClientConfig {
api_key: anthropic_auth
.as_ref()
.map(|(credential, _)| credential.clone())
.unwrap_or_default(),
api_base: config.resolve_anthropic_api_base(),
use_bearer_auth: anthropic_auth
.as_ref()
.is_some_and(|(_, use_bearer)| *use_bearer),
..Default::default()
},
);
provider_lookup_ids(config.selected_provider_id())
.into_iter()
.find_map(|lookup_id| {
registry
.get(&claurst_core::ProviderId::new(lookup_id))
.cloned()
})
}
fn text_from_content_blocks(blocks: &[ContentBlock]) -> String {
blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("")
}
// ---------------------------------------------------------------------------
// Built-in commands
// ---------------------------------------------------------------------------
pub struct HelpCommand;
pub struct ClearCommand;
pub struct CompactCommand;
pub struct CostCommand;
pub struct ExitCommand;
pub struct ModelCommand;
pub struct ConfigCommand;
pub struct ColorCommand;
pub struct VersionCommand;
pub struct ReleaseNotesCommand;
pub struct ResumeCommand;
pub struct StatusCommand;
pub struct DiffCommand;
pub struct GoalCommand;
pub struct MemoryCommand;
pub struct BugCommand;
pub struct LearnCommand;
pub struct UsageCommand;
pub struct DoctorCommand;
pub struct LoginCommand;
pub struct LogoutCommand;
pub struct RefreshCommand;
pub struct InitCommand;
pub struct ReviewCommand;
pub struct HooksCommand;
pub struct ImportConfigCommand;
pub struct McpCommand;
pub struct PermissionsCommand;
pub struct PlanCommand;
pub struct TasksCommand;
pub struct SessionCommand;
pub struct ThinkingCommand;
// New commands
pub struct ExportCommand;
pub struct ShareCommand;
pub struct SkillsCommand;
pub struct RewindCommand;
pub struct StatsCommand;
pub struct RenameCommand;
pub struct EffortCommand;
pub struct CommitCommand;
pub struct PluginCommand;
pub struct ReloadPluginsCommand;
pub struct ThemeCommand;
pub struct OutputStyleCommand;
pub struct KeybindingsCommand;
pub struct SplashCommand;
// Batch-1 new commands
pub struct ContextCommand;
pub struct CopyCommand;
pub struct ChromeCommand;
pub struct VimCommand;
pub struct VoiceCommand;
pub struct UpgradeCommand;
pub struct StatuslineCommand;
pub struct SecurityReviewCommand;
pub struct TerminalSetupCommand;
pub struct FastCommand;
pub struct ThinkBackCommand;
pub struct ThinkBackPlayCommand;
// New commands: teleport, btw, ctx-viz, sandbox-toggle
pub struct BtwCommand;
pub struct IncantCommand;
pub struct SandboxToggleCommand;
pub struct UltrareviewCommand;
pub struct AdvisorCommand;
pub struct UndoCommand;
pub struct RevertCommand;
pub struct CheckpointsCommand;
pub struct SnapshotDiffCommand;
pub struct ProvidersCommand;
pub struct ConnectCommand;
pub struct FamiliarCommand;
pub struct SearchCommand;
pub struct ForkCommand;
pub struct ManagedAgentsCommand;
pub struct CovenCommand;
pub struct NamedCommandAdapter {
pub slash_name: &'static str,
pub target_name: &'static str,
pub slash_aliases: &'static [&'static str],
pub slash_description: &'static str,
pub slash_help: &'static str,
/// One-release compatibility aliases for folded commands (issue #73).
pub slash_hidden: bool,
}
#[derive(serde::Serialize)]
struct KeybindingTemplateFile {
#[serde(rename = "$schema")]
schema: &'static str,
#[serde(rename = "$docs")]
docs: &'static str,
bindings: Vec<KeybindingTemplateBlock>,
}
#[derive(serde::Serialize)]
struct KeybindingTemplateBlock {
context: String,
bindings: BTreeMap<String, Option<String>>,
}
fn save_settings_mutation<F>(mutate: F) -> anyhow::Result<()>
where
F: FnOnce(&mut Settings),
{
let mut settings = Settings::load_sync()?;
mutate(&mut settings);
settings.save_sync()
}
fn open_with_system(target: &str) -> std::io::Result<()> {
#[cfg(target_os = "windows")]
{
let ps_cmd = format!("Start-Process '{}'", target.replace('\'', "''"));
std::process::Command::new("powershell")
.args(["-NoProfile", "-NonInteractive", "-Command", &ps_cmd])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(target)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
std::process::Command::new("xdg-open")
.arg(target)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
Ok(())
}
}
fn format_keystroke(keystroke: &claurst_core::keybindings::ParsedKeystroke) -> String {
let mut parts = Vec::new();
if keystroke.ctrl {
parts.push("ctrl".to_string());
}
if keystroke.alt {
parts.push("alt".to_string());
}
if keystroke.shift {
parts.push("shift".to_string());
}
if keystroke.meta {
parts.push("meta".to_string());
}
parts.push(match keystroke.key.as_str() {
"space" => "space".to_string(),
other => other.to_string(),
});
parts.join("+")
}
fn format_chord(chord: &[claurst_core::keybindings::ParsedKeystroke]) -> String {
chord
.iter()
.map(format_keystroke)
.collect::<Vec<_>>()
.join(" ")
}
fn generate_keybindings_template() -> anyhow::Result<String> {
let mut grouped: BTreeMap<String, BTreeMap<String, Option<String>>> = BTreeMap::new();
for binding in claurst_core::keybindings::default_bindings() {
let chord = format_chord(&binding.chord);
if claurst_core::keybindings::NON_REBINDABLE.contains(&chord.as_str()) {
continue;
}
grouped
.entry(format!("{:?}", binding.context))
.or_default()
.insert(chord, binding.action.clone());
}
let template = KeybindingTemplateFile {
schema: "https://www.schemastore.org/claude-code-keybindings.json",
docs: "https://code.claude.com/docs/en/keybindings",
bindings: grouped
.into_iter()
.map(|(context, bindings)| KeybindingTemplateBlock { context, bindings })
.collect(),
};
Ok(format!("{}\n", serde_json::to_string_pretty(&template)?))
}
fn parse_theme(name: &str) -> Option<Theme> {
match name.trim().to_lowercase().as_str() {
"default" | "system" => Some(Theme::Default),
"dark" => Some(Theme::Dark),
"light" => Some(Theme::Light),
custom if !custom.is_empty() => Some(Theme::Custom(custom.to_string())),
_ => None,
}
}
fn current_output_style_name(config: &Config) -> &str {
config.output_style.as_deref().unwrap_or("default")
}
fn available_output_style_names() -> Vec<String> {
claurst_core::output_styles::all_styles(&Settings::config_dir())
.into_iter()
.map(|style| style.name)
.collect()
}
fn split_command_args(args: &str) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
let mut quote: Option<char> = None;
let mut escape = false;
for ch in args.chars() {
if escape {
current.push(ch);
escape = false;
continue;
}
match ch {
'\\' => escape = true,
'\'' | '"' if quote == Some(ch) => quote = None,
'\'' | '"' if quote.is_none() => quote = Some(ch),
ch if ch.is_whitespace() && quote.is_none() => {
if !current.is_empty() {
out.push(std::mem::take(&mut current));
}
}
_ => current.push(ch),
}
}
if !current.is_empty() {
out.push(current);
}
out
}
fn execute_named_command_from_slash(
target_name: &str,
args: &str,
ctx: &CommandContext,
) -> CommandResult {
let Some(cmd) = named_commands::find_named_command(target_name) else {
return CommandResult::Error(format!(
"Named command '{}' is not available in this build.",
target_name
));
};
let parsed_args = split_command_args(args);
let parsed_refs = parsed_args.iter().map(String::as_str).collect::<Vec<_>>();
cmd.execute_named(&parsed_refs, ctx)
}
// ---- /help ---------------------------------------------------------------
/// Category labels for help grouping. Delegates to the canonical
/// categorization in `claurst-tui` so the `/help` text output, the F1 help
/// overlay, and the command palette all group commands identically.
fn command_category(name: &str) -> &'static str {
claurst_tui::app::slash_command_category(name)
}
#[async_trait]
impl SlashCommand for HelpCommand {
fn name(&self) -> &str {
"help"
}
fn aliases(&self) -> Vec<&str> {
vec!["h", "?"]
}
fn description(&self) -> &str {
"Show available commands and usage information"
}
async fn execute(&self, args: &str, _ctx: &mut CommandContext) -> CommandResult {
if !args.is_empty() {
// Show help for a specific command
if let Some(cmd) = find_command(args) {
let aliases = cmd.aliases();
let alias_line = if aliases.is_empty() {
String::new()
} else {
format!(
"\nAliases: {}",
aliases
.iter()
.map(|a| format!("/{}", a))
.collect::<Vec<_>>()
.join(", ")
)
};
return CommandResult::Message(format!(
"/{name}{aliases}\n{desc}\n\n{help}",
name = cmd.name(),
aliases = alias_line,
desc = cmd.description(),
help = cmd.help(),
));
}
return CommandResult::Error(format!("Unknown command: /{}", args));
}
// Grouped output
let commands = all_commands();
let visible: Vec<_> = commands.iter().filter(|c| !c.hidden()).collect();
// Collect categories in stable order
let category_order = [
"Conversation",
"Settings",
"Usage & Cost",
"System",
"Auth & Permissions",
"Project",
"Integrations",
"Sessions & Remote",
"AI & Thinking",
"Tools & Extras",
"Coven",
"General",
"Other",
];
let mut by_cat: std::collections::HashMap<&str, Vec<String>> =
std::collections::HashMap::new();
for cmd in &visible {
let cat = command_category(cmd.name());
let aliases = cmd.aliases();
let alias_str = if aliases.is_empty() {
String::new()
} else {
format!(
" ({})",
aliases
.iter()
.map(|a| format!("/{}", a))
.collect::<Vec<_>>()
.join(", ")
)
};
by_cat.entry(cat).or_default().push(format!(
" /{:<20} {}",
format!("{}{}", cmd.name(), alias_str),
cmd.description()
));
}
let mut output = String::from("Coven Code — Slash Commands\n");
output.push_str("════════════════════════════\n");
for cat in &category_order {
if let Some(entries) = by_cat.get(cat) {
output.push_str(&format!("\n{}\n", cat));
for entry in entries {
output.push_str(&format!("{}\n", entry));
}
}
}
output.push_str("\nType /help <command> for detailed help on a specific command.");
CommandResult::Message(output)
}
}
// ---- /clear --------------------------------------------------------------
#[async_trait]
impl SlashCommand for ClearCommand {
fn name(&self) -> &str {
"clear"
}
fn aliases(&self) -> Vec<&str> {
vec!["c", "reset", "new"]
}
fn description(&self) -> &str {
"Clear the conversation history"
}
async fn execute(&self, _args: &str, _ctx: &mut CommandContext) -> CommandResult {
CommandResult::ClearConversation
}
}
// ---- /compact ------------------------------------------------------------
#[async_trait]
impl SlashCommand for CompactCommand {
fn name(&self) -> &str {
"compact"
}
fn description(&self) -> &str {
"Compact the conversation to reduce token usage"
}
async fn execute(&self, args: &str, ctx: &mut CommandContext) -> CommandResult {
let msg_count = ctx.messages.len();
let instruction = if args.is_empty() {
"Provide a detailed summary of our conversation so far, preserving all \
key technical details, decisions made, file paths mentioned, and current \
task status."
.to_string()
} else {
args.to_string()
};
CommandResult::UserMessage(format!(
"[Compact requested ({} messages). Instruction: {}]",
msg_count, instruction
))
}
}
// ---- /cost ---------------------------------------------------------------
#[async_trait]
impl SlashCommand for CostCommand {
fn name(&self) -> &str {
"cost"
}
fn hidden(&self) -> bool {
true
}
fn description(&self) -> &str {
"Show token usage and cost for this session"
}
fn help(&self) -> &str {
"Usage: /cost\n\n\
Shows per-category token counts and the estimated cost for this session.\n\
Cache write tokens are priced slightly higher than input; cache read tokens\n\
are ~10x cheaper — caching reduces cost significantly in long sessions.\n\
For account quotas use /usage."
}
async fn execute(&self, _args: &str, ctx: &mut CommandContext) -> CommandResult {
let tracker = &ctx.cost_tracker;
let model = ctx.config.effective_model();
let pricing = claurst_core::cost::ModelPricing::for_model(model);
let input = tracker.input_tokens();
let output = tracker.output_tokens();
let cache_create = tracker.cache_creation_tokens();
let cache_read = tracker.cache_read_tokens();
let total = tracker.total_tokens();
let cost = tracker.total_cost_usd();
// Per-category cost breakdown.
let input_cost = (input as f64 * pricing.input_per_mtk) / 1_000_000.0;
let output_cost = (output as f64 * pricing.output_per_mtk) / 1_000_000.0;
let cc_cost = (cache_create as f64 * pricing.cache_creation_per_mtk) / 1_000_000.0;
let cr_cost = (cache_read as f64 * pricing.cache_read_per_mtk) / 1_000_000.0;
// Pricing info line.
let pricing_line = format!(
" Rates ($/MTok): input ${:.2} | output ${:.2} | cache-write ${:.3} | cache-read ${:.3}",
pricing.input_per_mtk,
pricing.output_per_mtk,
pricing.cache_creation_per_mtk,
pricing.cache_read_per_mtk,
);
// Cache savings note: how much input cost was avoided by using cache-read
// instead of re-sending those tokens as normal input.
let savings = if cache_read > 0 {
let saved = (cache_read as f64 * (pricing.input_per_mtk - pricing.cache_read_per_mtk))
/ 1_000_000.0;
format!(
"\n Cache savings: ${:.4} ({} tokens served from cache)",
saved, cache_read
)
} else {
String::new()
};
CommandResult::Message(format!(
"Session Cost — {model}\n\
──────────────────────────────\n\
{pricing_line}\n\n\
Input tokens: {input:>10} ${input_cost:.4}\n\
Output tokens: {output:>10} ${output_cost:.4}\n\
Cache write: {cache_create:>10} ${cc_cost:.4}\n\
Cache read: {cache_read:>10} ${cr_cost:.4}\n\
─────────────────────────────\n\
Total tokens: {total:>10}\n\
Total cost: ${cost:.4}{savings}\n\n\
Use /usage for quota info",
model = model,
pricing_line = pricing_line,
input = input,
input_cost = input_cost,
output = output,
output_cost = output_cost,
cache_create = cache_create,
cc_cost = cc_cost,
cache_read = cache_read,
cr_cost = cr_cost,
total = total,
cost = cost,
savings = savings,
))
}
}
// ---- /exit ---------------------------------------------------------------
#[async_trait]
impl SlashCommand for ExitCommand {
fn name(&self) -> &str {
"exit"
}
fn aliases(&self) -> Vec<&str> {
vec!["quit", "q"]
}
fn description(&self) -> &str {
"Exit Coven Code"
}
async fn execute(&self, _args: &str, _ctx: &mut CommandContext) -> CommandResult {
CommandResult::Exit
}
}
// ---- /model --------------------------------------------------------------
#[async_trait]
impl SlashCommand for ModelCommand {
fn name(&self) -> &str {
"model"
}
fn description(&self) -> &str {
"Show or change the current model"
}
fn help(&self) -> &str {
"Usage: /model [<model-id>]\n\n\
Without arguments, opens the model picker for the active provider.\n\n\
With a model ID, switches to that model. Accepts a bare Claude model\n\
name (e.g. claude-sonnet-4-6) or, for Codex, the provider-prefixed\n\
form codex/<model>. Coven Code dispatches to two providers: Anthropic\n\
(Claude) and Codex.\n\n\
Examples:\n\
/model — open the model picker\n\
/model claude-sonnet-4-6 — switch to Claude Sonnet 4.6\n\
/model claude-haiku-4-5 — switch to Claude Haiku 4.5\n\
/model codex/gpt-5.2-codex — switch to Codex (requires codex login)"
}
async fn execute(&self, args: &str, ctx: &mut CommandContext) -> CommandResult {
let args = args.trim();
if args.is_empty() {
CommandResult::Message(format!("Current model: {}", ctx.config.effective_model()))
} else {
// Accept both "provider/model" and bare model names.
// The config stores the full string (including provider prefix when present)
// so that downstream dispatch can route to the correct provider.
let model_str = args.to_string();
let confirmation = if let Some((provider, model)) = model_str.split_once('/') {
if provider == "anthropic" {
format!("Switched to {}", model)
} else {
format!("Switched to {}/{}", provider, model)
}
} else {
format!("Switched to {}", model_str)
};
let mut new_config = ctx.config.clone();
new_config.model = Some(model_str.clone());
if let Some((provider, _)) = model_str.split_once('/') {
new_config.provider = Some(provider.to_string());
}
CommandResult::ConfigChangeMessage(new_config, confirmation)
}
}
}
// ---- /config -------------------------------------------------------------
#[async_trait]
impl SlashCommand for ConfigCommand {
fn name(&self) -> &str {
"config"
}
fn aliases(&self) -> Vec<&str> {
vec!["settings"]
}
fn description(&self) -> &str {
"Show or modify configuration settings"
}
fn help(&self) -> &str {
"Usage: /config [show|get|set|unset|<area>] ...\n\n\
Shows or modifies configuration settings.\n\n\
Core settings:\n\
/config\n\
/config set theme <default|dark|light>\n\
/config set output-style <default|concise|explanatory|learning|formal|casual>\n\
/config set model <model>\n\
/config set permission-mode <default|accept-edits|bypass-permissions|plan>\n\
/config unset <model|output-style>\n\n\
Areas:\n\
/config color [<name|#RRGGBB|default>]\n\
/config vim [on|off]\n\
/config voice [on|off|status]\n\
/config statusline [show|hide] [cost|tokens|model|time|all]\n\
/config terminal-setup\n\
/config theme [name] — theme picker / set theme\n\
/config keybindings — open keybindings.json\n\
/config output-style [s] — show or set the output style\n\
/config import — import settings from ~/.claude\n\
/config advisor [model] — set the advisor model"
}
async fn execute(&self, args: &str, ctx: &mut CommandContext) -> CommandResult {
let args = args.trim();
if args.is_empty() || matches!(args, "show" | "get") {
let json = serde_json::to_string_pretty(&ctx.config).unwrap_or_default();
return CommandResult::Message(format!(
"Current configuration:\n{}\n\n{}",
json,
self.help()
));
}
let mut subcommand_parts = args.splitn(2, char::is_whitespace);
let subcommand = subcommand_parts.next().unwrap_or_default();
let subcommand_args = subcommand_parts.next().unwrap_or_default().trim();
match subcommand {
"color" | "prompt-color" | "prompt_color" => {
return ColorCommand.execute(subcommand_args, ctx).await;
}
"vim" | "vi" | "editor" | "editor-mode" | "editor_mode" => {
return VimCommand.execute(subcommand_args, ctx).await;
}
"voice" => {
return VoiceCommand.execute(subcommand_args, ctx).await;
}
"statusline" | "status-line" | "status_line" => {
return StatuslineCommand.execute(subcommand_args, ctx).await;
}
"terminal-setup" | "terminal_setup" | "terminal" => {
if !subcommand_args.is_empty() {
return CommandResult::Error("Usage: /config terminal-setup".to_string());
}
return TerminalSetupCommand.execute("", ctx).await;
}
// Folded in Phase 3 (issue #73); the old top-level names stay
// hidden one-release aliases.
"keybindings" | "keybinding" => {
return KeybindingsCommand.execute(subcommand_args, ctx).await;
}
"theme" => {
return ThemeCommand.execute(subcommand_args, ctx).await;
}
"output-style" | "output_style" => {
return OutputStyleCommand.execute(subcommand_args, ctx).await;
}
"import" | "import-config" | "import_config" => {
return ImportConfigCommand.execute(subcommand_args, ctx).await;
}
"advisor" => {
return AdvisorCommand.execute(subcommand_args, ctx).await;
}
_ => {}
}
if let Some(key) = args.strip_prefix("get ").map(str::trim) {
return match key {
"theme" => CommandResult::Message(format!("theme = {:?}", ctx.config.theme)),
"output-style" | "output_style" => CommandResult::Message(format!(
"output-style = {}",
current_output_style_name(&ctx.config)
)),
"model" => {
CommandResult::Message(format!("model = {}", ctx.config.effective_model()))
}
"permission-mode" | "permission_mode" => CommandResult::Message(format!(
"permission-mode = {:?}",
ctx.config.permission_mode
)),
other => CommandResult::Error(format!("Unknown config key '{}'", other)),
};
}
if let Some(key) = args.strip_prefix("unset ").map(str::trim) {
return match key {
"model" => {
let mut new_config = ctx.config.clone();
new_config.model = None;
if let Err(err) =
save_settings_mutation(|settings| settings.config.model = None)
{
return CommandResult::Error(format!(
"Failed to save configuration: {}",
err
));
}
CommandResult::ConfigChangeMessage(
new_config,
"Model reset to the default for new sessions.".to_string(),
)
}
"output-style" | "output_style" => {
let mut new_config = ctx.config.clone();
new_config.output_style = None;
if let Err(err) =
save_settings_mutation(|settings| settings.config.output_style = None)
{
return CommandResult::Error(format!(
"Failed to save configuration: {}",
err
));
}
CommandResult::ConfigChangeMessage(
new_config,
"Output style reset to default.".to_string(),
)
}
other => CommandResult::Error(format!("Unknown config key '{}'", other)),
};
}
let mut parts = args.splitn(3, ' ');
let command = parts.next().unwrap_or_default();
let key = parts.next().unwrap_or_default().trim();
let value = parts.next().unwrap_or_default().trim();
if command != "set" || key.is_empty() || value.is_empty() {
return CommandResult::Error("Usage: /config set <key> <value>".to_string());
}
match key {
"theme" => {
let Some(theme) = parse_theme(value) else {
return CommandResult::Error(
"Theme must be one of: default, dark, light".to_string(),
);
};
let mut new_config = ctx.config.clone();
new_config.theme = theme.clone();
if let Err(err) =
save_settings_mutation(|settings| settings.config.theme = theme.clone())
{
return CommandResult::Error(format!("Failed to save configuration: {}", err));
}
CommandResult::ConfigChangeMessage(
new_config,
format!("Theme set to {}.", value.trim().to_lowercase()),
)
}
"output-style" | "output_style" => {
let normalized = value.trim().to_lowercase();
let valid = available_output_style_names();
if !valid.iter().any(|name| name == &normalized) {
return CommandResult::Error(format!(
"Unsupported output style '{}'. Use one of: {}",
value,
valid.join(", ")
));
}
let mut new_config = ctx.config.clone();
new_config.output_style = (normalized != "default").then(|| normalized.clone());
if let Err(err) = save_settings_mutation(|settings| {
settings.config.output_style =
(normalized != "default").then(|| normalized.clone());
}) {
return CommandResult::Error(format!("Failed to save configuration: {}", err));
}
CommandResult::ConfigChangeMessage(
new_config,
format!(
"Output style set to {}. Changes take effect on the next request.",
normalized
),
)