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
2851 lines (2649 loc) · 118 KB
/
Copy pathlib.rs
File metadata and controls
2851 lines (2649 loc) · 118 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
// cc-query: The core agentic query loop.
//
// This crate implements the main conversation loop that:
// 1. Sends messages to the Anthropic API
// 2. Processes streaming responses
// 3. Detects tool-use requests and dispatches them
// 4. Feeds tool results back to the model
// 5. Handles auto-compact when the context window fills up
// 6. Manages stop conditions (end_turn, max_turns, cancellation)
pub mod agent_tool;
pub mod auto_dream;
pub mod away_summary;
pub mod command_queue;
pub mod compact;
pub mod context_analyzer;
pub mod coordinator;
pub mod cron_scheduler;
pub mod goal_loop;
pub mod managed_orchestrator;
pub mod session_memory;
pub mod skill_prefetch;
pub use agent_tool::{init_team_swarm_runner, AgentTool};
pub use command_queue::{drain_command_queue, CommandPriority, CommandQueue, QueuedCommand};
pub use compact::{
auto_compact_if_needed, calculate_messages_to_keep_index, calculate_token_warning_state,
compact_conversation, context_collapse, context_window_for_model, format_compact_summary,
get_compact_prompt, group_messages_for_compact, micro_compact_if_needed, reactive_compact,
should_auto_compact, should_compact, should_context_collapse, snip_compact, AutoCompactState,
CompactResult, CompactTrigger, MessageGroup, MicroCompactConfig, TokenWarningState,
};
pub use cron_scheduler::start_cron_scheduler;
pub use goal_loop::{check_and_continue_goal, mark_goal_complete, GoalContinuation, StopReason};
pub use session_memory::{
ExtractedMemory, MemoryCandidate, MemoryCandidateStatus, MemoryCandidateStore, MemoryCategory,
MemoryPersistenceOutcome, SessionMemoryExtractor, SessionMemoryState,
};
pub use skill_prefetch::{
format_skill_listing, prefetch_skills, SharedSkillIndex, SkillDefinition, SkillIndex,
};
use claurst_api::{
AnthropicStreamEvent, ApiMessage, ApiToolDefinition, CreateMessageRequest, StreamAccumulator,
StreamHandler, SystemPrompt, ThinkingConfig,
};
use claurst_core::config::Config;
use claurst_core::cost::CostTracker;
use claurst_core::error::ClaudeError;
use claurst_core::types::{ContentBlock, Message, ToolResultContent, UsageInfo};
use claurst_tools::{Tool, ToolContext, ToolResult};
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{debug, error, info, warn};
// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------
/// Outcome of a single query-loop run.
#[derive(Debug)]
pub enum QueryOutcome {
/// The model finished its turn (end_turn stop reason).
EndTurn { message: Message, usage: UsageInfo },
/// The model hit max_tokens.
MaxTokens {
partial_message: Message,
usage: UsageInfo,
},
/// The conversation was cancelled by the user.
Cancelled,
/// An unrecoverable error occurred.
Error(ClaudeError),
/// The configured USD budget was exceeded.
BudgetExceeded { cost_usd: f64, limit_usd: f64 },
}
/// Configuration for a single query-loop invocation.
#[derive(Clone)]
pub struct QueryConfig {
pub model: String,
pub max_tokens: u32,
pub max_turns: u32,
pub system_prompt: Option<String>,
pub append_system_prompt: Option<String>,
pub output_style: claurst_core::system_prompt::OutputStyle,
pub output_style_prompt: Option<String>,
pub working_directory: Option<String>,
pub thinking_budget: Option<u32>,
pub temperature: Option<f32>,
/// Maximum cumulative character count of all tool results in the message
/// history before older results are replaced with a truncation notice.
/// Mirrors the TS `applyToolResultBudget` mechanism. Default: 50_000.
pub tool_result_budget: usize,
/// Optional effort level. When set and `thinking_budget` is `None`,
/// the effort level's `thinking_budget_tokens()` is used as the
/// thinking budget. Also provides a temperature override when the
/// level specifies one.
pub effort_level: Option<claurst_core::effort::EffortLevel>,
/// T1-4: Optional shared command queue.
///
/// When set, the query loop drains this queue before each API call and
/// injects any resulting messages into the conversation. The queue is
/// shared (Arc-backed) so the TUI input thread can push commands while the
/// loop is waiting for a model response.
pub command_queue: Option<CommandQueue>,
/// T1-5: Optional shared skill index.
///
/// When set, `prefetch_skills` is spawned once before the loop begins and
/// the resulting index is used to inject a skill listing attachment into
/// the conversation context.
pub skill_index: Option<SharedSkillIndex>,
/// Optional USD spend cap. The query loop checks accumulated cost after
/// each turn and aborts with `QueryOutcome::BudgetExceeded` when exceeded.
pub max_budget_usd: Option<f64>,
/// Fallback model name. Used when the primary model returns overloaded /
/// rate-limit errors (mirrors TS `--fallback-model`).
pub fallback_model: Option<String>,
/// Optional ProviderRegistry for dispatching to non-Anthropic providers.
/// When `config.provider` is set to something other than "anthropic" and
/// this registry contains that provider, the registry's provider is used
/// instead of `AnthropicClient`.
pub provider_registry: Option<std::sync::Arc<claurst_api::ProviderRegistry>>,
/// Active agent name (e.g., "build", "plan", "explore", or None for default).
pub agent_name: Option<String>,
/// Resolved agent definition for the current session.
pub agent_definition: Option<claurst_core::AgentDefinition>,
/// Optional shared model registry for dynamic provider and model resolution.
/// When set, the query loop uses this instead of constructing a fresh registry.
pub model_registry: Option<std::sync::Arc<claurst_api::ModelRegistry>>,
/// Managed agent (manager-executor) configuration.
pub managed_agents: Option<claurst_core::ManagedAgentConfig>,
/// Preserve an explicit caller-selected model instead of allowing managed-agent
/// manager_model to replace it at query runtime.
pub preserve_selected_model: bool,
}
impl Default for QueryConfig {
fn default() -> Self {
Self {
model: claurst_core::constants::DEFAULT_MODEL.to_string(),
max_tokens: claurst_core::constants::DEFAULT_MAX_TOKENS,
max_turns: claurst_core::constants::MAX_TURNS_DEFAULT,
system_prompt: None,
append_system_prompt: None,
output_style: claurst_core::system_prompt::OutputStyle::Default,
output_style_prompt: None,
working_directory: None,
thinking_budget: None,
temperature: None,
tool_result_budget: 50_000,
effort_level: None,
command_queue: None,
skill_index: None,
max_budget_usd: None,
fallback_model: None,
provider_registry: None,
agent_name: None,
agent_definition: None,
model_registry: None,
managed_agents: None,
preserve_selected_model: false,
}
}
}
impl QueryConfig {
pub fn from_config(cfg: &Config) -> Self {
Self {
model: cfg.effective_model().to_string(),
max_tokens: cfg.effective_max_tokens(),
output_style: cfg.effective_output_style(),
output_style_prompt: cfg.resolve_output_style_prompt(),
working_directory: cfg.project_dir.as_ref().map(|p| p.display().to_string()),
managed_agents: cfg.managed_agents.clone(),
..Default::default()
}
}
/// Build a QueryConfig using dynamic model resolution from the model registry.
///
/// Prefers the best model for the configured provider (from models.dev data)
/// over the hardcoded defaults.
pub fn from_config_with_registry(cfg: &Config, registry: &claurst_api::ModelRegistry) -> Self {
// We can't move the Arc here, but we need a clone for the query loop.
// Callers typically wrap the registry in an Arc already.
Self {
model: claurst_api::effective_model_for_config(cfg, registry),
max_tokens: cfg.effective_max_tokens(),
output_style: cfg.effective_output_style(),
output_style_prompt: cfg.resolve_output_style_prompt(),
working_directory: cfg.project_dir.as_ref().map(|p| p.display().to_string()),
managed_agents: cfg.managed_agents.clone(),
..Default::default()
}
}
}
fn reasoning_effort_for_level(effort_level: claurst_core::effort::EffortLevel) -> &'static str {
match effort_level {
claurst_core::effort::EffortLevel::Low => "low",
claurst_core::effort::EffortLevel::Medium => "medium",
claurst_core::effort::EffortLevel::High | claurst_core::effort::EffortLevel::Max => "high",
}
}
fn google_thinking_level_for_effort(
effort_level: Option<claurst_core::effort::EffortLevel>,
) -> &'static str {
match effort_level.unwrap_or(claurst_core::effort::EffortLevel::High) {
claurst_core::effort::EffortLevel::Low => "low",
claurst_core::effort::EffortLevel::Medium => "medium",
claurst_core::effort::EffortLevel::High | claurst_core::effort::EffortLevel::Max => "high",
}
}
fn is_openai_reasoning_model(model_id: &str) -> bool {
let model_id = model_id.to_ascii_lowercase();
model_id.starts_with("gpt-5")
|| model_id.starts_with("o1")
|| model_id.starts_with("o3")
|| model_id.starts_with("o4")
}
fn is_openaiish_provider(provider_id: &str) -> bool {
matches!(
provider_id,
"openai"
| "azure"
| "groq"
| "mistral"
| "deepseek"
| "xai"
| "openrouter"
| "togetherai"
| "together-ai"
| "perplexity"
| "cerebras"
| "deepinfra"
| "venice"
| "huggingface"
| "nvidia"
| "siliconflow"
| "sambanova"
| "moonshot"
| "zhipu"
| "zai"
| "qwen"
| "nebius"
| "novita"
| "ovhcloud"
| "scaleway"
| "vultr"
| "vultr-ai"
| "baseten"
| "friendli"
| "upstage"
| "stepfun"
| "fireworks"
| "ollama"
| "codex"
| "openai-codex"
| "lmstudio"
| "lm-studio"
| "llamacpp"
| "llama-cpp"
)
}
fn build_provider_options(
provider_id: &str,
model_id: &str,
effort_level: Option<claurst_core::effort::EffortLevel>,
thinking_budget: Option<u32>,
) -> Value {
let mut options = serde_json::Map::new();
let model_id = model_id.to_ascii_lowercase();
if provider_id == "github-copilot" {
if model_id.contains("claude") {
options.insert(
"thinking_budget".to_string(),
serde_json::json!(thinking_budget.unwrap_or(4_000)),
);
} else if model_id.starts_with("gpt-5") && !model_id.contains("gpt-5-pro") {
let reasoning_effort = effort_level
.map(reasoning_effort_for_level)
.unwrap_or("medium");
options.insert(
"reasoningEffort".to_string(),
serde_json::json!(reasoning_effort),
);
options.insert("reasoningSummary".to_string(), serde_json::json!("auto"));
options.insert(
"include".to_string(),
serde_json::json!(["reasoning.encrypted_content"]),
);
if model_id.contains("gpt-5.")
&& !model_id.contains("codex")
&& !model_id.contains("-chat")
{
options.insert("textVerbosity".to_string(), serde_json::json!("low"));
}
}
}
if provider_id == "google" && model_id.contains("gemini") {
if model_id.contains("2.5") {
if let Some(budget) = thinking_budget {
options.insert(
"thinkingConfig".to_string(),
serde_json::json!({
"includeThoughts": true,
"thinkingBudget": budget,
}),
);
}
} else if model_id.contains("3.") || model_id.contains("gemini-3") {
options.insert(
"thinkingConfig".to_string(),
serde_json::json!({
"includeThoughts": true,
"thinkingLevel": google_thinking_level_for_effort(effort_level),
}),
);
}
}
if provider_id == "amazon-bedrock" {
if model_id.contains("anthropic") || model_id.contains("claude") {
if let Some(budget) = thinking_budget {
options.insert(
"reasoningConfig".to_string(),
serde_json::json!({
"type": "enabled",
"budgetTokens": budget.min(31_999),
}),
);
}
} else if let Some(level) = effort_level {
options.insert(
"reasoningConfig".to_string(),
serde_json::json!({
"type": "enabled",
"maxReasoningEffort": reasoning_effort_for_level(level),
}),
);
}
}
if is_openaiish_provider(provider_id) && is_openai_reasoning_model(&model_id) {
let reasoning_effort = effort_level
.map(reasoning_effort_for_level)
.unwrap_or("medium");
options.insert(
"reasoningEffort".to_string(),
serde_json::json!(reasoning_effort),
);
if model_id.starts_with("gpt-5")
&& model_id.contains("gpt-5.")
&& !model_id.contains("codex")
&& !model_id.contains("-chat")
&& provider_id != "azure"
{
options.insert("textVerbosity".to_string(), serde_json::json!("low"));
// DeepSeek V4 thinking mode: map effort level to thinking/reasoning_effort params.
// DeepSeek docs: thinking={"type":"enabled/disabled"}, reasoning_effort="high"|"max"
// low/medium are mapped to "high" by the API; xhigh mapped to "max".
if provider_id == "deepseek" {
match effort_level {
None
| Some(claurst_core::effort::EffortLevel::Medium)
| Some(claurst_core::effort::EffortLevel::High) => {
options.insert(
"thinking".to_string(),
serde_json::json!({"type": "enabled"}),
);
options.insert("reasoningEffort".to_string(), serde_json::json!("high"));
}
Some(claurst_core::effort::EffortLevel::Max) => {
options.insert(
"thinking".to_string(),
serde_json::json!({"type": "enabled"}),
);
options.insert("reasoningEffort".to_string(), serde_json::json!("max"));
}
Some(claurst_core::effort::EffortLevel::Low) => {
options.insert(
"thinking".to_string(),
serde_json::json!({"type": "disabled"}),
);
}
}
}
}
}
if provider_id == "openrouter" {
options.insert("usage".to_string(), serde_json::json!({ "include": true }));
if model_id.contains("gemini-3") {
options.insert(
"reasoning".to_string(),
serde_json::json!({ "effort": "high" }),
);
}
}
if provider_id == "qwen" && thinking_budget.is_some() && !model_id.contains("kimi-k2-thinking")
{
options.insert("enable_thinking".to_string(), serde_json::json!(true));
}
if (provider_id == "zhipu" || provider_id == "zai") && thinking_budget.is_some() {
options.insert(
"thinking".to_string(),
serde_json::json!({
"type": "enabled",
"clear_thinking": false,
}),
);
}
if options.is_empty() {
Value::Null
} else {
Value::Object(options)
}
}
/// Events emitted by the query loop for the TUI to render.
#[derive(Debug, Clone)]
pub enum QueryEvent {
/// A stream event from the API.
Stream(AnthropicStreamEvent),
/// A tool is about to be executed.
ToolStart {
tool_name: String,
tool_id: String,
input_json: String,
},
/// A tool has finished executing.
ToolEnd {
tool_name: String,
tool_id: String,
result: String,
is_error: bool,
},
/// The model finished a turn.
TurnComplete {
turn: u32,
stop_reason: String,
usage: Option<UsageInfo>,
},
/// An informational status message.
Status(String),
/// An error.
Error(String),
/// Token usage has crossed a warning threshold.
/// `state` is Warning (≥ 80 %) or Critical (≥ 95 %).
/// `pct_used` is the fraction of the context window consumed (0.0–1.0).
TokenWarning {
state: TokenWarningState,
pct_used: f64,
},
}
// ---------------------------------------------------------------------------
// T1-3: Post-sampling hooks
// ---------------------------------------------------------------------------
/// Result returned by `fire_post_sampling_hooks`.
#[derive(Debug, Default)]
pub struct PostSamplingHookResult {
/// Error messages produced by hooks with non-zero exit codes.
/// These are injected into the conversation as user messages before the
/// next model turn so the model can react to them.
pub blocking_errors: Vec<claurst_core::types::Message>,
/// When `true` the query loop must not continue and should surface the
/// error messages to the caller. Set when any hook exits with code > 1.
pub prevent_continuation: bool,
}
/// Execute all `PostModelTurn` hooks defined in `config.hooks`.
///
/// Each hook is run synchronously (blocking via `std::process::Command`).
/// On a non-zero exit code, the hook's stderr (falling back to stdout) is
/// wrapped in a user `Message` and appended to `blocking_errors`.
/// If the exit code is **strictly greater than 1** `prevent_continuation` is
/// set so the query loop can return early.
pub fn fire_post_sampling_hooks(
_turn_result: &claurst_core::types::Message,
config: &claurst_core::config::Config,
) -> PostSamplingHookResult {
use claurst_core::config::HookEvent;
use claurst_core::types::Message;
let mut result = PostSamplingHookResult::default();
let entries = match config.hooks.get(&HookEvent::PostModelTurn) {
Some(e) => e,
None => return result,
};
for entry in entries {
let sh = if cfg!(windows) { "cmd" } else { "sh" };
let flag = if cfg!(windows) { "/C" } else { "-c" };
let output = match std::process::Command::new(sh)
.args([flag, &entry.command])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
{
Ok(o) => o,
Err(e) => {
tracing::warn!(command = %entry.command, error = %e, "PostModelTurn hook spawn failed");
continue;
}
};
if output.status.success() {
continue;
}
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let body = if !stderr.trim().is_empty() {
stderr
} else {
stdout
};
tracing::warn!(
command = %entry.command,
exit_code = ?output.status.code(),
"PostModelTurn hook returned non-zero exit"
);
result.blocking_errors.push(Message::user(format!(
"[Hook '{}' error]:\n{}",
entry.command,
body.trim()
)));
// Exit code > 1 → hard veto of continuation.
if output.status.code().unwrap_or(1) > 1 {
result.prevent_continuation = true;
}
}
result
}
/// Spawn all `Stop` hooks in fire-and-forget background tasks.
///
/// Stop hooks are non-blocking by design: the caller does not wait for them.
/// Returns an empty `Vec` immediately; results (if any) are lost.
pub fn stop_hooks_with_full_behavior(
turn_result: &claurst_core::types::Message,
config: &claurst_core::config::Config,
working_dir: std::path::PathBuf,
) -> Vec<claurst_core::types::Message> {
use claurst_core::config::HookEvent;
let entries = match config.hooks.get(&HookEvent::Stop) {
Some(e) if !e.is_empty() => e.clone(),
_ => return Vec::new(),
};
let output_text = turn_result.get_all_text();
for entry in entries {
let cmd = entry.command.clone();
let dir = working_dir.clone();
let text = output_text.clone();
tokio::task::spawn_blocking(move || {
let sh = if cfg!(windows) { "cmd" } else { "sh" };
let flag = if cfg!(windows) { "/C" } else { "-c" };
let _ = std::process::Command::new(sh)
.args([flag, &cmd])
.current_dir(&dir)
.env("CLAUDE_HOOK_OUTPUT", &text)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
});
}
Vec::new()
}
// ---------------------------------------------------------------------------
// Tool-result budgeting
// ---------------------------------------------------------------------------
/// Return the combined character count of all tool-result content blocks found
/// in `messages`. Only user messages are examined (tool results always live
/// in user turns).
fn total_tool_result_chars(messages: &[Message]) -> usize {
messages
.iter()
.filter(|m| m.role == claurst_core::types::Role::User)
.flat_map(|m| match &m.content {
claurst_core::types::MessageContent::Blocks(blocks) => blocks.as_slice(),
_ => &[],
})
.filter_map(|b| {
if let ContentBlock::ToolResult { content, .. } = b {
Some(match content {
ToolResultContent::Text(t) => t.len(),
ToolResultContent::Blocks(blocks) => blocks
.iter()
.map(|b| {
if let ContentBlock::Text { text } = b {
text.len()
} else {
0
}
})
.sum(),
})
} else {
None
}
})
.sum()
}
/// When the cumulative tool-result content exceeds `budget` characters, walk
/// the message list from oldest to newest and replace individual
/// `ToolResult` content with a placeholder until the running total is back
/// under budget. Returns the (possibly modified) message list and the
/// number of results that were truncated.
///
/// Mirrors the spirit of the TypeScript `applyToolResultBudget` /
/// `enforceToolResultBudget` logic, simplified to a straightforward
/// oldest-first eviction without the session-persistence layer.
fn apply_tool_result_budget(messages: Vec<Message>, budget: usize) -> (Vec<Message>, usize) {
let total = total_tool_result_chars(&messages);
if total <= budget {
return (messages, 0);
}
let mut to_shed = total - budget;
let mut truncated = 0usize;
let mut result = messages;
'outer: for msg in result.iter_mut() {
if msg.role != claurst_core::types::Role::User {
continue;
}
let blocks = match &mut msg.content {
claurst_core::types::MessageContent::Blocks(b) => b,
_ => continue,
};
for block in blocks.iter_mut() {
if let ContentBlock::ToolResult { content, .. } = block {
let size = match &*content {
ToolResultContent::Text(t) => t.len(),
ToolResultContent::Blocks(inner) => inner
.iter()
.map(|b| {
if let ContentBlock::Text { text } = b {
text.len()
} else {
0
}
})
.sum(),
};
if size == 0 {
continue;
}
*content =
ToolResultContent::Text("[tool result truncated to save context]".to_string());
truncated += 1;
if size > to_shed {
break 'outer;
}
to_shed -= size;
}
}
}
(result, truncated)
}
// ---------------------------------------------------------------------------
// Query loop
// ---------------------------------------------------------------------------
/// Maximum number of max_tokens continuation attempts before surfacing the
/// partial response. Mirrors `MAX_OUTPUT_TOKENS_RECOVERY_LIMIT` in query.ts.
const MAX_TOKENS_RECOVERY_LIMIT: u32 = 3;
/// Message injected when the model hits its output-token limit.
/// Mirrors the TS recovery message in query.ts lines 1224-1228.
const MAX_TOKENS_RECOVERY_MSG: &str =
"Output token limit hit. Resume directly — no apology, no recap of what \
you were doing. Pick up mid-thought if that is where the cut happened. \
Break remaining work into smaller pieces.";
fn should_emit_turn_complete(stop: &str, max_tokens_recovery_count: u32) -> bool {
match stop {
"tool_use" => false,
"max_tokens" => max_tokens_recovery_count >= MAX_TOKENS_RECOVERY_LIMIT,
_ => true,
}
}
fn selected_model_for_query(config: &QueryConfig) -> String {
let selected_model = if let Some(ref agent) = config.agent_definition {
agent.model.clone().unwrap_or_else(|| config.model.clone())
} else {
config.model.clone()
};
if config.preserve_selected_model {
return selected_model;
}
if let Some(ref ma_config) = config.managed_agents {
if ma_config.enabled && !ma_config.manager_model.is_empty() {
return ma_config.manager_model.clone();
}
}
selected_model
}
fn is_fallback_worthy_api_error(err: &ClaudeError) -> bool {
match err {
ClaudeError::RateLimit => true,
ClaudeError::ApiStatus { status, message } => {
*status == 429 || *status == 529 || message.to_lowercase().contains("overloaded")
}
_ => {
let err_str = err.to_string().to_lowercase();
err_str.contains("overloaded")
|| err_str.contains("529")
|| err_str.contains("rate_limit")
|| err_str.contains("rate limit")
}
}
}
fn enrich_error_notice(
err: ClaudeError,
provider: &str,
model: &str,
account: Option<&str>,
) -> ClaudeError {
match err {
ClaudeError::RateLimit => ClaudeError::ApiStatus {
status: 429,
message: rate_limit_notice(provider, model, account, None),
},
ClaudeError::ApiStatus {
status: 429,
message,
} => ClaudeError::ApiStatus {
status: 429,
message: rate_limit_notice(provider, model, account, Some(&message)),
},
other => other,
}
}
fn rate_limit_notice(
provider: &str,
model: &str,
account: Option<&str>,
provider_message: Option<&str>,
) -> String {
let account_part = account
.filter(|value| !value.trim().is_empty())
.map(|value| format!(" on account `{}`", value.trim()))
.unwrap_or_default();
let mut message = format!(
"Claude rate limit for model `{model}`{account_part}.\n\n\
Anthropic/Claude Max limits are model-tier scoped: Sonnet/Opus can be limited while Haiku still works.\n\
Try switching to Haiku, switching Anthropic accounts, or waiting before retrying."
);
if account
.map(|value| value.to_lowercase().contains("claude-code"))
.unwrap_or(false)
{
message.push_str(
"\n\nThis is an imported Claude Code credential. Coven Code is using the imported token for direct Anthropic requests; it is not running the `claude` CLI for this turn.",
);
}
let provider_message = provider_message
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| !value.eq_ignore_ascii_case("error"));
if let Some(provider_message) = provider_message {
message.push_str(&format!("\n\nProvider message: {provider_message}"));
} else if provider != "anthropic" {
message.push_str(&format!("\n\nProvider: {provider}"));
}
message
}
fn active_account_notice(provider: &str) -> Option<String> {
let registry = claurst_core::accounts::AccountRegistry::load();
let profile = registry.active_profile(provider)?;
let display_name = profile.display_name();
let mut label = if display_name == profile.id {
profile.id.clone()
} else {
format!("{} ({})", profile.id, display_name)
};
if let Some(tier) = profile
.subscription_tier
.as_deref()
.map(str::trim)
.filter(|tier| !tier.is_empty())
{
label.push_str(&format!(" [{tier}]"));
}
Some(label)
}
// Spinner verbs are imported from claurst_core::spinner
/// Run the agentic query loop.
///
/// This sends the conversation to the API, handles tool calls in a loop, and
/// returns when the model issues an end_turn or an error/limit is hit.
///
/// `pending_messages` is an optional queue of user messages that were enqueued
/// during tool execution (e.g. by the UI or a command queue). Each string is
/// appended as a plain user message between turns. Callers that do not need
/// command queuing may pass `None` or an empty `Vec`.
//
// Allowed: the inputs here are intentionally separate domain values (HTTP
// client, mutable message log, immutable tool set, tool execution context,
// query knobs, cost accumulator, event channel, cancellation token, pending
// messages). Bundling them behind a single config struct would mostly move
// the parameter count from the signature into the struct without improving
// clarity — and several of these arguments need separate lifetimes that a
// struct can't easily express.
#[allow(clippy::too_many_arguments)]
pub async fn run_query_loop(
client: &claurst_api::AnthropicClient,
messages: &mut Vec<Message>,
tools: &[Box<dyn Tool>],
tool_ctx: &ToolContext,
config: &QueryConfig,
cost_tracker: Arc<CostTracker>,
event_tx: Option<mpsc::UnboundedSender<QueryEvent>>,
cancel_token: tokio_util::sync::CancellationToken,
mut pending_messages: Option<&mut Vec<String>>,
) -> QueryOutcome {
let mut turn = 0u32;
let mut compact_state = compact::AutoCompactState::default();
// Tracks how many consecutive max_tokens recoveries we've attempted so
// we don't loop forever on a model that can't finish within any budget.
let mut max_tokens_recovery_count: u32 = 0;
// Active model — may switch to fallback on overloaded errors.
// Agent model override takes priority over the session model when set.
let mut effective_model = selected_model_for_query(config);
let mut used_fallback = false;
// How many automatic retries remain when a stream stalls (no data for 45s).
let mut retries_left: u32 = 2;
// If an agent defines a max_turns override, respect it (agent wins over config).
let effective_max_turns = config
.agent_definition
.as_ref()
.and_then(|a| a.max_turns)
.unwrap_or(config.max_turns);
// Shadow-git snapshot: capture the worktree state before any tools run so we
// can produce a per-turn file-change patch when the turn ends.
let shadow_snap: Option<std::sync::Arc<claurst_core::snapshot::ShadowSnapshot>> =
if tool_ctx.config.auto_commits == Some(true) {
claurst_core::snapshot::get_or_create(&tool_ctx.working_dir)
} else {
None
};
// Pre-capture tree hash; refreshed at the start of each turn's tool phase.
let initial_snapshot: Option<String> = if let Some(ref s) = shadow_snap {
s.track().await
} else {
None
};
loop {
turn += 1;
tool_ctx
.current_turn
.store(turn as usize, std::sync::atomic::Ordering::Relaxed);
if turn > effective_max_turns {
info!(turns = turn, "Max turns reached");
if let Some(ref tx) = event_tx {
let _ = tx.send(QueryEvent::Status(format!(
"Reached maximum turn limit ({})",
effective_max_turns
)));
}
// Return the last assistant message if any
let last_msg = messages
.last()
.cloned()
.unwrap_or_else(|| Message::assistant("Max turns reached."));
return QueryOutcome::EndTurn {
message: last_msg,
usage: UsageInfo::default(),
};
}
// Check for cancellation
if cancel_token.is_cancelled() {
return QueryOutcome::Cancelled;
}
// Drain any pending user messages that were queued during the previous
// tool-execution phase (e.g. commands entered while tools ran).
// Mirrors the TS `messageQueueManager` drain between turns.
if let Some(queue) = pending_messages.as_deref_mut() {
for text in queue.drain(..) {
debug!("Injecting pending message: {}", &text);
messages.push(Message::user(text));
}
}
// T1-4: Drain the priority command queue (if wired up) and prepend any
// resulting messages to the conversation before the API call.
// Mirrors the TS `messageQueueManager` priority-queue drain.
if let Some(ref cq) = config.command_queue {
if !cq.is_empty() {
let injected = drain_command_queue(cq);
if !injected.is_empty() {
debug!(count = injected.len(), "Injecting command-queue messages");
// Prepend so that higher-priority commands appear first.
let tail = std::mem::take(messages);
messages.extend(injected);
messages.extend(tail);
}
}
}
// Apply tool-result budget: if the cumulative size of all tool results
// in the conversation exceeds the configured threshold, replace the
// oldest results with a placeholder until we're back under budget.
// This mirrors the TS `applyToolResultBudget` call in query.ts.
if config.tool_result_budget > 0 {
let (budgeted, truncated) =
apply_tool_result_budget(std::mem::take(messages), config.tool_result_budget);
*messages = budgeted;
if truncated > 0 {
info!(
truncated,
budget = config.tool_result_budget,
"Tool-result budget exceeded: truncated {} result(s)",
truncated
);
if let Some(ref tx) = event_tx {
let _ = tx.send(QueryEvent::Status(format!(
"[{} older tool result(s) truncated to save context]",
truncated
)));
}
}
}
// Build API request
let api_messages: Vec<ApiMessage> = messages.iter().map(ApiMessage::from).collect();
let api_tools: Vec<ApiToolDefinition> = tools
.iter()
.map(|t| ApiToolDefinition::from(&t.to_definition()))
.collect();
// Verification nudge: if there are incomplete todos for this session
// and the conversation has more than 2 turns, append a reminder.
let system = {
// Build a (possibly patched) config for system-prompt assembly.
// Agent prompt prefix and todo nudge are both applied here.
let mut patched = config.clone();
// Apply agent system-prompt prefix: prepend before the main system prompt.
if let Some(ref agent) = config.agent_definition {
if let Some(ref agent_prompt) = agent.prompt {
patched.system_prompt = Some(match &config.system_prompt {
Some(existing) => format!("{}\n\n{}", agent_prompt, existing),
None => agent_prompt.clone(),
});
}
}