-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Expand file tree
/
Copy pathmain.rs
More file actions
3502 lines (3242 loc) · 155 KB
/
main.rs
File metadata and controls
3502 lines (3242 loc) · 155 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 CLI entry point
//
// This is the main binary for Claurst. It:
// 1. Parses CLI arguments with clap (mirrors cli.tsx + main.tsx flags)
// 2. Loads configuration from settings.json + env vars
// 3. Builds system/user context (git status, AGENTS.md)
// 4. Runs in either:
// - Headless (--print / -p) mode: single query, output to stdout
// - Interactive REPL mode: full TUI with ratatui
mod oauth_flow;
mod codex_oauth_flow;
// ---------------------------------------------------------------------------
// Build-time metadata (embedded via build.rs)
// ---------------------------------------------------------------------------
/// Build timestamp in RFC 3339 format
pub const BUILD_TIME: &str = env!("BUILD_TIME");
/// Short git commit hash (or "unknown" if not a git repo)
pub const GIT_COMMIT: &str = env!("GIT_COMMIT");
/// Package/distribution identifier
pub const PACKAGE_URL: &str = env!("PACKAGE_URL");
/// Feedback/issue reporting channel
pub const FEEDBACK_CHANNEL: &str = env!("FEEDBACK_CHANNEL");
/// Explanation of issue routing in this build
pub const ISSUES_EXPLAINER: &str = env!("ISSUES_EXPLAINER");
use anyhow::Context;
use claurst_core::{
config::{Config, PermissionMode, Settings},
constants::APP_VERSION,
context::ContextBuilder,
cost::CostTracker,
permissions::{AutoPermissionHandler, InteractivePermissionHandler, PermissionManager},
};
use async_trait::async_trait;
use claurst_core::types::ToolDefinition;
use claurst_tools::{PermissionLevel, Tool, ToolContext, ToolResult};
use clap::{ArgAction, Parser, ValueEnum};
use parking_lot::Mutex as ParkingMutex;
use std::{path::PathBuf, sync::Arc};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;
// ---------------------------------------------------------------------------
// MCP tool wrapper: makes MCP server tools look like native cc-tools.
// ---------------------------------------------------------------------------
struct McpToolWrapper {
tool_def: ToolDefinition,
server_name: String,
manager: Arc<claurst_mcp::McpManager>,
}
#[async_trait]
impl Tool for McpToolWrapper {
fn name(&self) -> &str {
&self.tool_def.name
}
fn description(&self) -> &str {
&self.tool_def.description
}
fn permission_level(&self) -> PermissionLevel {
// MCP tools run external processes – treat as Execute.
PermissionLevel::Execute
}
fn input_schema(&self) -> serde_json::Value {
self.tool_def.input_schema.clone()
}
async fn execute(&self, input: serde_json::Value, ctx: &ToolContext) -> ToolResult {
let desc = format!("Run MCP tool {}", self.tool_def.name);
if let Err(e) = ctx.check_permission(self.name(), &desc, false) {
return ToolResult::error(e.to_string());
}
// Strip the server-name prefix to get the bare tool name.
let prefix = format!("{}_", self.server_name);
let bare_name = self
.tool_def
.name
.strip_prefix(&prefix)
.unwrap_or(&self.tool_def.name);
let args = if input.is_null() { None } else { Some(input) };
match self.manager.call_tool(&self.tool_def.name, args).await {
Ok(result) => {
let text = claurst_mcp::mcp_result_to_string(&result);
if result.is_error {
ToolResult::error(text)
} else {
ToolResult::success(text)
}
}
Err(e) => ToolResult::error(format!("MCP tool '{}' failed: {}", bare_name, e)),
}
}
}
// ---------------------------------------------------------------------------
// CLI argument definition (matches TypeScript main.tsx flags)
// ---------------------------------------------------------------------------
#[derive(Parser, Debug)]
#[command(
name = "claude",
version = APP_VERSION,
about = "Claurst - AI-powered coding assistant",
long_about = None,
)]
struct Cli {
/// Initial prompt to send (enables headless/print mode)
prompt: Option<String>,
/// Print mode: send prompt and exit (non-interactive)
#[arg(short = 'p', long = "print", action = ArgAction::SetTrue)]
print: bool,
/// Model to use
#[arg(short = 'm', long = "model")]
model: Option<String>,
/// Permission mode
#[arg(long = "permission-mode", value_enum, default_value_t = CliPermissionMode::Default)]
permission_mode: CliPermissionMode,
/// Resume a previous session by ID
#[arg(long = "resume")]
resume: Option<String>,
/// Maximum number of agentic turns
#[arg(long = "max-turns", default_value_t = 10)]
max_turns: u32,
/// Custom system prompt
#[arg(long = "system-prompt", short = 's')]
system_prompt: Option<String>,
/// Append to system prompt
#[arg(long = "append-system-prompt")]
append_system_prompt: Option<String>,
/// Disable AGENTS.md memory files
#[arg(long = "no-claude-md", action = ArgAction::SetTrue)]
no_claude_md: bool,
/// Output format
#[arg(long = "output-format", value_enum, default_value_t = CliOutputFormat::Text)]
output_format: CliOutputFormat,
/// Enable verbose logging
#[arg(long = "verbose", short = 'v', action = ArgAction::SetTrue)]
verbose: bool,
/// API key for the active provider (overrides provider-specific env vars)
#[arg(long = "api-key")]
api_key: Option<String>,
/// Maximum tokens per response
#[arg(long = "max-tokens")]
max_tokens: Option<u32>,
/// Working directory
#[arg(long = "cwd")]
cwd: Option<PathBuf>,
/// Bypass all permission checks (danger!)
#[arg(long = "dangerously-skip-permissions", action = ArgAction::SetTrue)]
dangerously_skip_permissions: bool,
/// Dump the system prompt to stdout and exit
#[arg(long = "dump-system-prompt", action = ArgAction::SetTrue, hide = true)]
dump_system_prompt: bool,
/// MCP config JSON string (inline server definitions)
#[arg(long = "mcp-config")]
mcp_config: Option<String>,
/// Disable auto-compaction
#[arg(long = "no-auto-compact", action = ArgAction::SetTrue)]
no_auto_compact: bool,
/// Grant Claurst access to an additional directory (can be repeated)
#[arg(long = "add-dir", value_name = "DIR", action = ArgAction::Append)]
add_dir: Vec<PathBuf>,
/// Input format for --print mode (text or stream-json)
#[arg(long = "input-format", value_enum, default_value_t = CliInputFormat::Text)]
input_format: CliInputFormat,
/// Session ID to tag this headless run (for tracking in logs/hooks)
#[arg(long = "session-id")]
session_id_flag: Option<String>,
/// Prefill the first assistant turn with this text
#[arg(long = "prefill")]
prefill: Option<String>,
/// Effort level for extended thinking (low, medium, high, max)
#[arg(long = "effort", value_name = "LEVEL")]
effort: Option<String>,
/// Extended thinking budget in tokens (enables extended thinking)
#[arg(long = "thinking", value_name = "TOKENS")]
thinking: Option<u32>,
/// Continue the most recent conversation
#[arg(short = 'c', long = "continue", action = ArgAction::SetTrue)]
continue_session: bool,
/// Override system prompt from a file
#[arg(long = "system-prompt-file")]
system_prompt_file: Option<PathBuf>,
/// Tools to allow (comma-separated, default: all)
#[arg(long = "allowed-tools", value_name = "TOOLS")]
allowed_tools: Option<String>,
/// Tools to disallow (comma-separated)
#[arg(long = "disallowed-tools", value_name = "TOOLS")]
disallowed_tools: Option<String>,
/// Extra beta feature headers to send (comma-separated)
#[arg(long = "betas", value_name = "HEADERS")]
betas: Option<String>,
/// Disable all slash commands
#[arg(long = "disable-slash-commands", action = ArgAction::SetTrue)]
disable_slash_commands: bool,
/// Run in bare mode (no hooks, no plugins, no AGENTS.md)
#[arg(long = "bare", action = ArgAction::SetTrue)]
bare: bool,
/// Billing workload tag
#[arg(long = "workload", value_name = "TAG")]
workload: Option<String>,
/// Maximum spend in USD before aborting the query loop
#[arg(long = "max-budget-usd", value_name = "USD")]
max_budget_usd: Option<f64>,
/// Fallback model to use if the primary model is overloaded or unavailable
#[arg(long = "fallback-model")]
fallback_model: Option<String>,
/// LLM provider to use (default: anthropic). Examples: openai, google, ollama
#[arg(long, env = "CLAURST_PROVIDER")]
provider: Option<String>,
/// Override the API base URL for the selected provider
#[arg(long, env = "CLAURST_API_BASE")]
api_base: Option<String>,
/// Named agent to use (e.g., build, plan, explore)
#[arg(long, short = 'A')]
agent: Option<String>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum CliPermissionMode {
Default,
AcceptEdits,
BypassPermissions,
Plan,
}
impl From<CliPermissionMode> for PermissionMode {
fn from(m: CliPermissionMode) -> Self {
match m {
CliPermissionMode::Default => PermissionMode::Default,
CliPermissionMode::AcceptEdits => PermissionMode::AcceptEdits,
CliPermissionMode::BypassPermissions => PermissionMode::BypassPermissions,
CliPermissionMode::Plan => PermissionMode::Plan,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum CliOutputFormat {
Text,
Json,
#[value(name = "stream-json")]
StreamJson,
}
impl From<CliOutputFormat> for claurst_core::config::OutputFormat {
fn from(f: CliOutputFormat) -> Self {
match f {
CliOutputFormat::Text => claurst_core::config::OutputFormat::Text,
CliOutputFormat::Json => claurst_core::config::OutputFormat::Json,
CliOutputFormat::StreamJson => claurst_core::config::OutputFormat::StreamJson,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum CliInputFormat {
/// Plain text prompt (default)
Text,
/// Newline-delimited JSON messages — each line is {"role":"user"|"assistant","content":"..."}
#[value(name = "stream-json")]
StreamJson,
}
fn resolve_bridge_config(
settings: &Settings,
auth_credential: &str,
use_bearer_auth: bool,
is_headless: bool,
) -> Option<claurst_bridge::BridgeConfig> {
if is_headless {
return None;
}
let mut bridge_config = claurst_bridge::BridgeConfig::from_env();
if settings.remote_control_at_startup {
bridge_config.enabled = true;
}
if bridge_config.session_token.is_none() && use_bearer_auth && !auth_credential.is_empty() {
bridge_config.session_token = Some(auth_credential.to_string());
}
bridge_config.is_active().then_some(bridge_config)
}
// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Fast-path: handle --version before parsing everything
let raw_args: Vec<String> = std::env::args().collect();
if raw_args.iter().any(|a| a == "--version" || a == "-V") {
println!("claude {}", APP_VERSION);
return Ok(());
}
// Fast-path: `claude auth <login|logout|status>` — mirrors TypeScript cli.tsx pattern
if raw_args.get(1).map(|s| s.as_str()) == Some("auth") {
return handle_auth_command(&raw_args[2..]).await;
}
// Fast-path: `claude acp` — start the Agent Client Protocol stdio server.
if raw_args.get(1).map(|s| s.as_str()) == Some("acp") {
return claurst_acp::run_acp_server().await;
}
// Fast-path: `claude models` — list all available providers and models.
if raw_args.get(1).map(|s| s.as_str()) == Some("models") {
let mut registry = claurst_api::ModelRegistry::new();
// Load cached models.dev data if available so the list is comprehensive.
registry.load_cache(&models_cache_path());
let mut entries = registry.list_all();
// Sort by provider then model id for stable output.
entries.sort_by(|a, b| {
(&*a.info.provider_id).cmp(&*b.info.provider_id)
.then_with(|| (&*a.info.id).cmp(&*b.info.id))
});
for entry in entries {
println!(
"{}/{} — {} (ctx: {}K, in: ${:.2}/M, out: ${:.2}/M)",
entry.info.provider_id,
entry.info.id,
entry.info.name,
entry.info.context_window / 1000,
entry.cost_input.unwrap_or(0.0),
entry.cost_output.unwrap_or(0.0),
);
}
return Ok(());
}
// Fast-path: named commands (`claude agents`, `claude ide`, `claude branch`, …)
// Check before Cli::parse() so these names don't conflict with positional prompt arg.
if let Some(cmd_name) = raw_args.get(1).map(|s| s.as_str()) {
// Only intercept if it looks like a subcommand (no leading `-` or `/`)
if !cmd_name.starts_with('-') && !cmd_name.starts_with('/') {
if let Some(named_cmd) = claurst_commands::named_commands::find_named_command(cmd_name) {
// Build a minimal CommandContext (named commands are pre-session)
let settings = Settings::load().await.unwrap_or_default();
let config = settings.effective_config();
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let cmd_ctx = claurst_commands::CommandContext {
config,
cost_tracker: CostTracker::new(),
messages: vec![],
working_dir: cwd,
session_id: "pre-session".to_string(),
session_title: None,
remote_session_url: None,
mcp_manager: None,
mcp_auth_runner: None,
};
// Collect remaining args after the command name
let rest: Vec<&str> = raw_args[2..].iter().map(|s| s.as_str()).collect();
let result = named_cmd.execute_named(&rest, &cmd_ctx);
match result {
claurst_commands::CommandResult::Message(msg)
| claurst_commands::CommandResult::UserMessage(msg) => {
println!("{}", msg);
std::process::exit(0);
}
claurst_commands::CommandResult::Error(e) => {
eprintln!("Error: {}", e);
eprintln!("Usage: {}", named_cmd.usage());
std::process::exit(1);
}
_ => {
// For any other result variant, fall through to normal startup
}
}
return Ok(());
}
}
}
let cli = Cli::parse();
// Setup logging
let log_level = if cli.verbose { "debug" } else { "warn" };
let base_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new(log_level));
let log_filter = base_filter
.add_directive("rmcp::service::client=error".parse().expect("valid rmcp directive"));
tracing_subscriber::fmt()
.with_env_filter(log_filter)
.with_target(false)
.without_time()
.init();
// Determine working directory
let cwd = cli
.cwd
.clone()
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
debug!(cwd = %cwd.display(), "Starting Claurst");
// Load settings from disk (hierarchical: global < project)
let settings = Settings::load_hierarchical(&cwd).await;
// Build effective config (CLI args override settings)
let mut config = settings.effective_config();
if let Some(ref key) = cli.api_key {
config.api_key = Some(key.clone());
}
if let Some(ref m) = cli.model {
config.model = Some(m.clone());
}
if let Some(mt) = cli.max_tokens {
config.max_tokens = Some(mt);
}
config.verbose = cli.verbose;
config.output_format = cli.output_format.into();
config.disable_claude_mds = cli.no_claude_md;
if let Some(sp) = cli.system_prompt.clone() {
config.custom_system_prompt = Some(sp);
}
if let Some(asp) = cli.append_system_prompt.clone() {
config.append_system_prompt = Some(asp);
}
if cli.dangerously_skip_permissions {
// Mirror TS setup.ts: block bypass mode when running as root/sudo.
#[cfg(unix)]
if nix::unistd::Uid::effective().is_root() {
anyhow::bail!(
"--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"
);
}
config.permission_mode = PermissionMode::BypassPermissions;
} else {
config.permission_mode = cli.permission_mode.into();
}
config.additional_dirs = cli.add_dir.clone();
if cli.no_auto_compact {
config.auto_compact = false;
}
config.project_dir = Some(cwd.clone());
if let Some(p) = &cli.provider {
config.provider = Some(p.clone());
}
if let Some(base) = &cli.api_base {
// Store in the provider's config entry
let provider_id = config.provider.clone().unwrap_or_else(|| "anthropic".to_string());
config
.provider_configs
.entry(provider_id)
.or_default()
.api_base = Some(base.clone());
}
// --dump-system-prompt fast path
if cli.dump_system_prompt {
let ctx = ContextBuilder::new(cwd.clone())
.disable_claude_mds(config.disable_claude_mds);
let sys = ctx.build_system_context().await;
let user = ctx.build_user_context().await;
println!("{}\n\n{}", sys, user);
return Ok(());
}
// Build context
let ctx_builder = ContextBuilder::new(cwd.clone())
.disable_claude_mds(config.disable_claude_mds);
let system_ctx = ctx_builder.build_system_context().await;
let user_ctx = ctx_builder.build_user_context().await;
// Build system prompt
let mut system_parts = vec![
include_str!("system_prompt.txt").to_string(),
system_ctx,
user_ctx,
];
if let Some(ref custom) = config.custom_system_prompt {
// replace base system prompt
system_parts[0] = custom.clone();
}
if let Some(ref append) = config.append_system_prompt {
system_parts.push(append.clone());
}
let system_prompt = system_parts.join("\n\n");
// Determine mode early (needed for auth error handling and permission handler selection).
let is_headless = cli.print || cli.prompt.is_some();
// Initialize API client.
// Try config/env first; fall back to saved OAuth tokens.
// If no Anthropic credentials are found, check whether any other provider is
// configured (OpenAI, Google, Ollama, Groq, etc.) — if so, proceed without
// requiring Anthropic auth. Only launch the OAuth flow when Anthropic is
// explicitly the intended provider and no key exists at all.
let active_provider = config.selected_provider_id();
let (api_key, use_bearer_auth) = if active_provider == "anthropic" {
match config.resolve_anthropic_auth_async().await {
Some(auth) => auth,
None => {
if is_headless {
anyhow::bail!(
"No API key found. Options:\n\
- Set ANTHROPIC_API_KEY for Anthropic\n\
- Set OPENAI_API_KEY for OpenAI\n\
- Set GOOGLE_API_KEY for Google Gemini\n\
- Set GROQ_API_KEY for Groq (fast, free tier available)\n\
- Run `claurst --provider ollama` for local models (no key needed)\n\
- Run `claurst auth login` for Anthropic OAuth"
);
} else {
(String::new(), false)
}
}
}
} else {
(String::new(), false)
};
let client_config = claurst_api::client::ClientConfig {
api_key: api_key.clone(),
api_base: config.resolve_anthropic_api_base(),
use_bearer_auth,
..Default::default()
};
let client = Arc::new(
claurst_api::AnthropicClient::new(client_config.clone())
.context("Failed to create API client")?,
);
// Build provider registry: auto-registers all env-configured providers
// AND providers with keys stored in ~/.claurst/auth.json (from /connect).
// Anthropic is always the default; additional providers (OpenAI, Google,
// Bedrock, Azure, Copilot, Cohere, local providers) are registered when
// their respective environment variables or auth store entries are found.
let provider_registry = claurst_api::ProviderRegistry::from_config(&config, client_config);
let bridge_config = resolve_bridge_config(&settings, &api_key, use_bearer_auth, is_headless);
if let Some(cfg) = bridge_config.as_ref() {
info!(
server_url = %cfg.server_url,
startup_enabled = settings.remote_control_at_startup,
"Remote control bridge configured for interactive startup"
);
}
let permission_manager = Arc::new(std::sync::Mutex::new(PermissionManager::new(
config.permission_mode.clone(),
&settings,
)));
let permission_handler: Arc<dyn claurst_core::PermissionHandler> = if is_headless {
Arc::new(AutoPermissionHandler::with_manager(permission_manager.clone()))
} else {
Arc::new(InteractivePermissionHandler::with_manager(permission_manager.clone()))
};
let cost_tracker = CostTracker::new();
// Use --session-id if provided, otherwise generate a fresh UUID.
let session_id = cli
.session_id_flag
.clone()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let file_history = Arc::new(ParkingMutex::new(
claurst_core::file_history::FileHistory::new(),
));
let current_turn = Arc::new(std::sync::atomic::AtomicUsize::new(0));
// Initialize MCP servers first (needed for ToolContext.mcp_manager).
let mcp_manager_arc = connect_mcp_manager_arc(&config).await;
let pending_permissions = Arc::new(ParkingMutex::new(claurst_tools::PendingPermissionStore::default()));
let tool_ctx = ToolContext {
working_dir: cwd.clone(),
permission_mode: config.permission_mode.clone(),
permission_handler: permission_handler.clone(),
cost_tracker: cost_tracker.clone(),
session_id: session_id.clone(),
file_history: file_history.clone(),
current_turn: current_turn.clone(),
non_interactive: cli.print || cli.prompt.is_some(),
mcp_manager: mcp_manager_arc.clone(),
config: config.clone(),
managed_agent_config: config.managed_agents.clone(),
completion_notifier: None,
pending_permissions: Some(pending_permissions.clone()),
permission_manager: Some(permission_manager.clone()),
};
// Register the cc-query-backed agent runner so TeamCreateTool can spawn real
// sub-agents. Must be called before any tool execution begins.
// The function is idempotent if already registered (panics only on double-call,
// but we guard with a std::sync::OnceLock internally).
{
static SWARM_INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
SWARM_INIT.get_or_init(|| claurst_query::init_team_swarm_runner());
}
// Build the full tool list: built-ins from cc-tools plus AgentTool from cc-query
// (AgentTool lives in cc-query to avoid a circular cc-tools ↔ cc-query dependency).
// Wrap in Arc so the list can be shared by the main loop AND the cron scheduler.
let tools = build_tools_with_mcp(mcp_manager_arc.clone());
// Load plugins and register any plugin-provided MCP servers into the
// in-memory config (does not modify the settings file on disk).
let plugin_registry = claurst_plugins::load_plugins(&cwd, &[]).await;
{
let plugin_cmd_count = plugin_registry.all_command_defs().len();
let plugin_hook_count = plugin_registry
.build_hook_registry()
.values()
.map(|v| v.len())
.sum::<usize>();
info!(
plugins = plugin_registry.enabled_count(),
commands = plugin_cmd_count,
hooks = plugin_hook_count,
"Plugins loaded"
);
// Register plugin MCP servers into the in-memory config so they are
// picked up by any subsequent MCP manager construction.
let existing_names: std::collections::HashSet<String> = config
.mcp_servers
.iter()
.map(|s| s.name.clone())
.collect();
for mcp_server in plugin_registry.all_mcp_servers() {
if !existing_names.contains(&mcp_server.name) {
config.mcp_servers.push(mcp_server);
}
}
}
// Build model registry for dynamic model/provider resolution.
// The registry is pre-populated with a hardcoded snapshot and enriched
// from the models.dev cache if available.
let model_registry = load_cached_model_registry();
// Build query config
let mut query_config = claurst_query::QueryConfig::from_config_with_registry(&config, &model_registry);
query_config.model_registry = Some(model_registry.clone());
query_config.max_turns = cli.max_turns;
query_config.system_prompt = Some(system_prompt);
query_config.append_system_prompt = None;
query_config.working_directory = Some(cwd.display().to_string());
if let Some(tokens) = cli.thinking {
query_config.thinking_budget = Some(tokens);
}
if let Some(ref level_str) = cli.effort {
if let Some(level) = claurst_core::effort::EffortLevel::from_str(level_str) {
query_config.effort_level = Some(level);
} else {
eprintln!("Warning: unknown effort level '{}' — expected low/medium/high/max", level_str);
}
}
if let Some(usd) = cli.max_budget_usd {
query_config.max_budget_usd = Some(usd);
}
if let Some(ref fb) = cli.fallback_model {
query_config.fallback_model = Some(fb.clone());
}
// Wire in the provider registry so non-Anthropic providers can be dispatched.
let provider_registry = std::sync::Arc::new(provider_registry);
query_config.provider_registry = Some(provider_registry.clone());
// Wire in the named agent (--agent flag).
// Merge built-in default agents with user-defined agents (user wins on collision).
let tools = if let Some(ref agent_name) = cli.agent {
query_config.agent_name = Some(agent_name.clone());
let mut all_agents = claurst_core::default_agents();
all_agents.extend(config.agents.clone());
if let Some(def) = all_agents.get(agent_name) {
let access = def.access.clone();
query_config.agent_definition = Some(def.clone());
// Override max_turns from agent definition when specified.
if let Some(turns) = def.max_turns {
query_config.max_turns = turns;
}
filter_tools_for_agent(tools, &access)
} else {
eprintln!("Warning: unknown agent '{}'. Run /agent to see available agents.", agent_name);
tools
}
} else {
tools
};
// Spawn the background cron scheduler (fires cron tasks at scheduled times).
// Cancelled automatically when the process exits since we use a shared token.
let cron_cancel = tokio_util::sync::CancellationToken::new();
claurst_query::start_cron_scheduler(
client.clone(),
tools.clone(),
tool_ctx.clone(),
query_config.clone(),
cron_cancel.clone(),
);
// --print mode (headless)
let result = if is_headless {
run_headless(
&cli,
client,
tools,
tool_ctx,
query_config,
cost_tracker,
)
.await
} else {
let auth_store = claurst_core::AuthStore::load();
let has_saved_credentials = !auth_store.credentials.is_empty()
|| claurst_core::oauth_config::get_codex_tokens().is_some();
let has_credentials = !api_key.is_empty()
|| has_saved_credentials
|| config.provider.as_deref().is_some_and(|p| p != "anthropic");
run_interactive(
config,
settings,
client,
tools,
tool_ctx,
query_config,
cost_tracker,
cli.resume,
bridge_config,
has_credentials,
model_registry,
)
.await
};
cron_cancel.cancel();
result
}
async fn connect_mcp_manager_arc(
config: &Config,
) -> Option<Arc<claurst_mcp::McpManager>> {
if config.mcp_servers.is_empty() {
return None;
}
info!(count = config.mcp_servers.len(), "Connecting to MCP servers");
let mcp_manager = Arc::new(claurst_mcp::McpManager::connect_all(&config.mcp_servers).await);
mcp_manager.clone().spawn_notification_poll_loop();
Some(mcp_manager)
}
fn build_tools_with_mcp(
mcp_manager: Option<Arc<claurst_mcp::McpManager>>,
) -> Arc<Vec<Box<dyn claurst_tools::Tool>>> {
let mut v: Vec<Box<dyn claurst_tools::Tool>> = claurst_tools::all_tools();
v.push(Box::new(claurst_query::AgentTool));
if let Some(ref manager_arc) = mcp_manager {
for (server_name, tool_def) in manager_arc.all_tool_definitions() {
let wrapper = McpToolWrapper {
tool_def,
server_name,
manager: manager_arc.clone(),
};
v.push(Box::new(wrapper));
}
debug!(total_tools = v.len(), "MCP tools registered");
}
Arc::new(v)
}
fn model_cache_dir() -> PathBuf {
dirs::cache_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("claurst")
}
fn models_cache_path() -> PathBuf {
model_cache_dir().join("models.json")
}
fn models_dev_cache_path() -> PathBuf {
model_cache_dir().join("models_dev.json")
}
fn load_cached_model_registry() -> Arc<claurst_api::ModelRegistry> {
let mut reg = claurst_api::ModelRegistry::new();
reg.load_cache(&models_cache_path());
Arc::new(reg)
}
fn spawn_models_cache_refresh() {
let cache_paths = vec![models_cache_path(), models_dev_cache_path()];
tokio::spawn(async move {
let client = match reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
{
Ok(c) => c,
Err(_) => return,
};
let url = std::env::var("MODELS_DEV_URL")
.unwrap_or_else(|_| "https://models.dev/api.json".to_string());
if let Ok(resp) = client
.get(&url)
.header("User-Agent", "Claurst/0.0.9")
.send()
.await
{
if resp.status().is_success() {
if let Ok(text) = resp.text().await {
if let Some(parent) = cache_paths[0].parent() {
let _ = std::fs::create_dir_all(parent);
}
for path in &cache_paths {
let _ = std::fs::write(path, &text);
}
tracing::info!("Models cache refreshed from models.dev");
}
}
}
});
}
async fn remove_file_if_exists(path: &std::path::Path) -> anyhow::Result<()> {
match tokio::fs::remove_file(path).await {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
struct RefreshedProviderRuntime {
config: Config,
client: Arc<claurst_api::AnthropicClient>,
provider_registry: Arc<claurst_api::ProviderRegistry>,
model_registry: Arc<claurst_api::ModelRegistry>,
auth_store: claurst_core::AuthStore,
}
async fn refresh_provider_runtime_state(
current_config: &Config,
) -> anyhow::Result<RefreshedProviderRuntime> {
remove_file_if_exists(&claurst_core::AuthStore::path())
.await
.context("Failed to clear auth store")?;
remove_file_if_exists(&claurst_core::oauth::OAuthTokens::token_file_path())
.await
.context("Failed to clear OAuth token cache")?;
remove_file_if_exists(&models_cache_path())
.await
.context("Failed to clear model cache")?;
remove_file_if_exists(&models_dev_cache_path())
.await
.context("Failed to clear legacy model cache")?;
let mut settings = Settings::load()
.await
.context("Failed to load settings for /refresh")?;
settings.provider = None;
settings.config.provider = None;
settings.config.model = None;
settings.config.api_key = None;
settings
.save()
.await
.context("Failed to save refreshed settings")?;
let mut config = current_config.clone();
config.api_key = None;
config.provider = None;
config.model = None;
let (api_key, use_bearer_auth) = config
.resolve_anthropic_auth_async()
.await
.unwrap_or((String::new(), false));
let client_config = claurst_api::client::ClientConfig {
api_key,
api_base: config.resolve_anthropic_api_base(),
use_bearer_auth,
..Default::default()
};
let client = Arc::new(
claurst_api::AnthropicClient::new(client_config.clone())
.context("Failed to rebuild Anthropic client")?,
);
let provider_registry =
Arc::new(claurst_api::ProviderRegistry::from_config(&config, client_config));
let model_registry = load_cached_model_registry();
spawn_models_cache_refresh();
Ok(RefreshedProviderRuntime {
config,
client,
provider_registry,
model_registry,
auth_store: claurst_core::AuthStore::default(),
})
}
fn normalize_provider_from_model(config: &mut Config) {
if let Some(model) = config.model.as_deref() {
if let Some((provider, _)) = model.split_once('/') {
config.provider = Some(provider.to_string());
}
}
}
/// Filter the tool list based on the agent's access level.
/// - "full" → all tools allowed (no filtering)
/// - "read-only" → only ReadOnly/None permission tools and AskUserQuestion
/// - "search-only" → only Grep, Glob, Read, WebSearch, WebFetch tools
fn filter_tools_for_agent(
tools: Arc<Vec<Box<dyn claurst_tools::Tool>>>,
access: &str,
) -> Arc<Vec<Box<dyn claurst_tools::Tool>>> {
use claurst_tools::PermissionLevel as PL;
match access {
"read-only" => {
// Collect names of tools that are read-only, then rebuild from all_tools
// (Box<dyn Tool> is not Clone so we can't directly filter-and-keep).
let allowed_names: Vec<String> = tools
.iter()
.filter(|t| {
matches!(t.permission_level(), PL::ReadOnly | PL::None)
|| t.name() == "AskUserQuestion"
})
.map(|t| t.name().to_string())
.collect();
let filtered: Vec<Box<dyn claurst_tools::Tool>> = claurst_tools::all_tools()
.into_iter()
.filter(|t| allowed_names.iter().any(|n| n == t.name()))
.collect();
Arc::new(filtered)
}
"search-only" => {
const SEARCH_TOOLS: &[&str] = &["Grep", "Glob", "Read", "WebSearch", "WebFetch"];
let filtered: Vec<Box<dyn claurst_tools::Tool>> = claurst_tools::all_tools()
.into_iter()
.filter(|t| SEARCH_TOOLS.contains(&t.name()))
.collect();
Arc::new(filtered)
}
_ => tools, // "full" — allow all tools unchanged
}
}
// ---------------------------------------------------------------------------
// Headless mode: read prompt from arg/stdin, run, print response