-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmod.rs
More file actions
2463 lines (2257 loc) · 112 KB
/
Copy pathmod.rs
File metadata and controls
2463 lines (2257 loc) · 112 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
//! Agent module for interactive AI-powered CLI assistance
//!
//! This module provides an agent layer using the Rig library that allows users
//! to interact with the CLI through natural language conversations.
//!
//! # Features
//!
//! - **Conversation History**: Maintains context across multiple turns
//! - **Automatic Compaction**: Compresses old history when token count exceeds threshold
//! - **Tool Tracking**: Records tool calls for better context preservation
//!
//! # Usage
//!
//! ```bash
//! # Interactive mode
//! sync-ctl chat
//!
//! # With specific provider
//! sync-ctl chat --provider openai --model gpt-5.2
//!
//! # Single query
//! sync-ctl chat --query "What security issues does this project have?"
//! ```
//!
//! # Interactive Commands
//!
//! - `/model` - Switch to a different AI model
//! - `/provider` - Switch provider (prompts for API key if needed)
//! - `/help` - Show available commands
//! - `/clear` - Clear conversation history
//! - `/exit` - Exit the chat
pub mod commands;
pub mod compact;
pub mod history;
pub mod ide;
pub mod persistence;
pub mod prompts;
pub mod session;
pub mod tools;
pub mod ui;
use colored::Colorize;
use commands::TokenUsage;
use history::{ConversationHistory, ToolCallRecord};
use ide::IdeClient;
use rig::{
client::{CompletionClient, ProviderClient},
completion::Prompt,
providers::{anthropic, openai},
};
use session::{ChatSession, PlanMode};
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex as TokioMutex;
use ui::{ResponseFormatter, ToolDisplayHook};
/// Provider type for the agent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProviderType {
#[default]
OpenAI,
Anthropic,
Bedrock,
}
impl std::fmt::Display for ProviderType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProviderType::OpenAI => write!(f, "openai"),
ProviderType::Anthropic => write!(f, "anthropic"),
ProviderType::Bedrock => write!(f, "bedrock"),
}
}
}
impl std::str::FromStr for ProviderType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"openai" => Ok(ProviderType::OpenAI),
"anthropic" => Ok(ProviderType::Anthropic),
"bedrock" | "aws" | "aws-bedrock" => Ok(ProviderType::Bedrock),
_ => Err(format!(
"Unknown provider: {}. Use: openai, anthropic, or bedrock",
s
)),
}
}
}
/// Error types for the agent
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
#[error("Missing API key. Set {0} environment variable.")]
MissingApiKey(String),
#[error("Provider error: {0}")]
ProviderError(String),
#[error("Tool error: {0}")]
ToolError(String),
}
pub type AgentResult<T> = Result<T, AgentError>;
/// Get the system prompt for the agent based on query type and plan mode
fn get_system_prompt(project_path: &Path, query: Option<&str>, plan_mode: PlanMode) -> String {
// In planning mode, use the read-only exploration prompt
if plan_mode.is_planning() {
return prompts::get_planning_prompt(project_path);
}
if let Some(q) = query {
// First check if it's a code development task (highest priority)
if prompts::is_code_development_query(q) {
return prompts::get_code_development_prompt(project_path);
}
// Then check if it's DevOps generation (Docker, Terraform, Helm)
if prompts::is_generation_query(q) {
return prompts::get_devops_prompt(project_path, Some(q));
}
}
// Default to analysis prompt
prompts::get_analysis_prompt(project_path)
}
/// Run the agent in interactive mode with custom REPL supporting /model and /provider commands
pub async fn run_interactive(
project_path: &Path,
provider: ProviderType,
model: Option<String>,
) -> AgentResult<()> {
use tools::*;
let mut session = ChatSession::new(project_path, provider, model);
// Shared background process manager for Prometheus port-forwards
let bg_manager = Arc::new(BackgroundProcessManager::new());
// Terminal layout for split screen is disabled for now - see notes below
// let terminal_layout = ui::TerminalLayout::new();
// let layout_state = terminal_layout.state();
// Initialize conversation history with compaction support
let mut conversation_history = ConversationHistory::new();
// Initialize IDE client for native diff viewing
let ide_client: Option<Arc<TokioMutex<IdeClient>>> = {
let mut client = IdeClient::new().await;
if client.is_ide_available() {
match client.connect().await {
Ok(()) => {
println!(
"{} Connected to {} IDE companion",
"✓".green(),
client.ide_name().unwrap_or("VS Code")
);
Some(Arc::new(TokioMutex::new(client)))
}
Err(e) => {
// IDE detected but companion not running or connection failed
println!("{} IDE companion not connected: {}", "!".yellow(), e);
None
}
}
} else {
println!(
"{} No IDE detected (TERM_PROGRAM={})",
"·".dimmed(),
std::env::var("TERM_PROGRAM").unwrap_or_default()
);
None
}
};
// Load API key from config file to env if not already set
ChatSession::load_api_key_to_env(session.provider);
// Check if API key is configured, prompt if not
if !ChatSession::has_api_key(session.provider) {
ChatSession::prompt_api_key(session.provider)?;
}
session.print_banner();
// Display platform context if a project is selected
if session.platform_session.is_project_selected() {
println!(
"{}",
format!("Platform context: {}", session.platform_session.display_context()).dimmed()
);
}
// NOTE: Terminal layout with ANSI scroll regions is disabled for now.
// The scroll region approach conflicts with the existing input/output flow.
// TODO: Implement proper scroll region support that integrates with the input handler.
// For now, we rely on the pause/resume mechanism in progress indicator.
//
// if let Err(e) = terminal_layout.init() {
// eprintln!(
// "{}",
// format!("Note: Terminal layout initialization failed: {}. Using fallback mode.", e)
// .dimmed()
// );
// }
// Raw Rig messages for multi-turn - preserves Reasoning blocks for thinking
// Our ConversationHistory only stores text summaries, but rig needs full Message structure
let mut raw_chat_history: Vec<rig::completion::Message> = Vec::new();
// Pending input for auto-continue after plan creation
let mut pending_input: Option<String> = None;
// Auto-accept mode for plan execution (skips write confirmations)
let mut auto_accept_writes = false;
// Initialize session recorder for conversation persistence
let mut session_recorder = persistence::SessionRecorder::new(project_path);
loop {
// Show conversation status if we have history
if !conversation_history.is_empty() {
println!(
"{}",
format!(" 💬 Context: {}", conversation_history.status()).dimmed()
);
}
// Check for pending input (from plan menu selection)
let input = if let Some(pending) = pending_input.take() {
// Show what we're executing
println!("{} {}", "→".cyan(), pending.dimmed());
pending
} else {
// New user turn - reset auto-accept mode from previous plan execution
auto_accept_writes = false;
// Read user input (returns InputResult)
let input_result = match session.read_input() {
Ok(result) => result,
Err(_) => break,
};
// Handle the input result
match input_result {
ui::InputResult::Submit(text) => ChatSession::process_submitted_text(&text),
ui::InputResult::Cancel | ui::InputResult::Exit => break,
ui::InputResult::TogglePlanMode => {
// Toggle planning mode - minimal feedback, no extra newlines
let new_mode = session.toggle_plan_mode();
if new_mode.is_planning() {
println!("{}", "★ plan mode".yellow());
} else {
println!("{}", "▶ standard mode".green());
}
continue;
}
}
};
if input.is_empty() {
continue;
}
// Check for commands
if ChatSession::is_command(&input) {
// Special handling for /clear to also clear conversation history
if input.trim().to_lowercase() == "/clear" || input.trim().to_lowercase() == "/c" {
conversation_history.clear();
raw_chat_history.clear();
}
match session.process_command(&input) {
Ok(true) => {
// Check if /resume loaded a session
if let Some(record) = session.pending_resume.take() {
// Display previous messages
println!();
println!("{}", "─── Previous Conversation ───".dimmed());
for msg in &record.messages {
match msg.role {
persistence::MessageRole::User => {
println!();
println!(
"{} {}",
"You:".cyan().bold(),
truncate_string(&msg.content, 500)
);
}
persistence::MessageRole::Assistant => {
println!();
// Show tool calls if any (same format as live display)
if let Some(ref tools) = msg.tool_calls {
for tc in tools {
// Match live tool display: green dot for completed, cyan bold name
if tc.args_summary.is_empty() {
println!(
"{} {}",
"●".green(),
tc.name.cyan().bold()
);
} else {
println!(
"{} {}({})",
"●".green(),
tc.name.cyan().bold(),
truncate_string(&tc.args_summary, 50).dimmed()
);
}
}
}
// Show response (same ResponseFormatter as live)
if !msg.content.is_empty() {
ResponseFormatter::print_response(&truncate_string(
&msg.content,
1000,
));
}
}
persistence::MessageRole::System => {
// Skip system messages in display
}
}
}
println!("{}", "─── End of History ───".dimmed());
println!();
// Try to restore from history_snapshot (new format with full context)
let restored_from_snapshot = if let Some(history_json) =
&record.history_snapshot
{
match ConversationHistory::from_json(history_json) {
Ok(restored) => {
conversation_history = restored;
// Rebuild raw_chat_history from restored conversation_history
raw_chat_history = conversation_history.to_messages();
println!(
"{}",
" ✓ Restored full conversation context (including compacted history)".green()
);
true
}
Err(e) => {
eprintln!(
"{}",
format!(
" Warning: Failed to restore history snapshot: {}",
e
)
.yellow()
);
false
}
}
} else {
false
};
// Fallback: Load from messages (old format or if snapshot failed)
if !restored_from_snapshot {
// Load messages into raw_chat_history for AI context
for msg in &record.messages {
match msg.role {
persistence::MessageRole::User => {
raw_chat_history.push(rig::completion::Message::User {
content: rig::one_or_many::OneOrMany::one(
rig::completion::message::UserContent::text(
&msg.content,
),
),
});
}
persistence::MessageRole::Assistant => {
raw_chat_history
.push(rig::completion::Message::Assistant {
id: Some(msg.id.clone()),
content: rig::one_or_many::OneOrMany::one(
rig::completion::message::AssistantContent::text(
&msg.content,
),
),
});
}
persistence::MessageRole::System => {}
}
}
// Load into conversation_history with tool calls from message records
for msg in &record.messages {
if msg.role == persistence::MessageRole::User {
// Find the next assistant message
let (response, tool_calls) = record
.messages
.iter()
.skip_while(|m| m.id != msg.id)
.skip(1)
.find(|m| m.role == persistence::MessageRole::Assistant)
.map(|m| {
let tcs = m.tool_calls.as_ref().map(|calls| {
calls
.iter()
.map(|tc| history::ToolCallRecord {
tool_name: tc.name.clone(),
args_summary: tc.args_summary.clone(),
result_summary: tc.result_summary.clone(),
tool_id: None,
droppable: false,
})
.collect::<Vec<_>>()
});
(m.content.clone(), tcs.unwrap_or_default())
})
.unwrap_or_default();
conversation_history.add_turn(
msg.content.clone(),
response,
tool_calls,
);
}
}
println!(
"{}",
format!(
" ✓ Loaded {} messages (legacy format).",
record.messages.len()
)
.green()
);
}
println!();
}
continue;
}
Ok(false) => break, // /exit
Err(e) => {
eprintln!("{}", format!("Error: {}", e).red());
continue;
}
}
}
// Check API key before making request (in case provider changed)
if !ChatSession::has_api_key(session.provider) {
eprintln!(
"{}",
"No API key configured. Use /provider to set one.".yellow()
);
continue;
}
// Check if compaction is needed before making the request
if conversation_history.needs_compaction() {
println!("{}", " 📦 Compacting conversation history...".dimmed());
if let Some(summary) = conversation_history.compact() {
println!(
"{}",
format!(" ✓ Compressed {} turns", summary.matches("Turn").count()).dimmed()
);
}
}
// Pre-request check: estimate if we're approaching context limit
// Check raw_chat_history (actual messages) not conversation_history
// because conversation_history may be out of sync
let estimated_input_tokens = estimate_raw_history_tokens(&raw_chat_history)
+ input.len() / 4 // New input
+ 5000; // System prompt overhead estimate
if estimated_input_tokens > 150_000 {
println!(
"{}",
" ⚠ Large context detected. Pre-truncating...".yellow()
);
let old_count = raw_chat_history.len();
// Keep last 20 messages when approaching limit
if raw_chat_history.len() > 20 {
let drain_count = raw_chat_history.len() - 20;
raw_chat_history.drain(0..drain_count);
// Ensure history starts with User message for OpenAI Responses API compatibility
ensure_history_starts_with_user(&mut raw_chat_history);
// Preserve compacted summary while clearing turns to stay in sync
conversation_history.clear_turns_preserve_context();
println!(
"{}",
format!(
" ✓ Truncated {} → {} messages",
old_count,
raw_chat_history.len()
)
.dimmed()
);
}
}
// Retry loop for automatic error recovery
// MAX_RETRIES is for failures without progress
// MAX_CONTINUATIONS is for truncations WITH progress (more generous)
// TOOL_CALL_CHECKPOINT is the interval at which we ask user to confirm
// MAX_TOOL_CALLS is the absolute maximum (300 = 6 checkpoints x 50)
const MAX_RETRIES: u32 = 3;
const MAX_CONTINUATIONS: u32 = 10;
const _TOOL_CALL_CHECKPOINT: usize = 50;
const MAX_TOOL_CALLS: usize = 300;
let mut retry_attempt = 0;
let mut continuation_count = 0;
let mut total_tool_calls: usize = 0;
let mut auto_continue_tools = false; // User can select "always" to skip future prompts
let mut current_input = input.clone();
let mut succeeded = false;
while retry_attempt < MAX_RETRIES && continuation_count < MAX_CONTINUATIONS && !succeeded {
// Log if this is a continuation attempt
if continuation_count > 0 {
eprintln!("{}", " 📡 Sending continuation request...".dimmed());
}
// Create hook for Claude Code style tool display
let hook = ToolDisplayHook::new();
// Create progress indicator for visual feedback during generation
let progress = ui::GenerationIndicator::new();
// Layout connection disabled - using inline progress mode
// progress.state().set_layout(layout_state.clone());
hook.set_progress_state(progress.state()).await;
let project_path_buf = session.project_path.clone();
// Select prompt based on query type (analysis vs generation) and plan mode
let preamble = get_system_prompt(
&session.project_path,
Some(¤t_input),
session.plan_mode,
);
let is_generation = prompts::is_generation_query(¤t_input);
let is_planning = session.plan_mode.is_planning();
// Note: using raw_chat_history directly which preserves Reasoning blocks
// This is needed for extended thinking to work with multi-turn conversations
// Get progress state for interrupt detection
let progress_state = progress.state();
// Use tokio::select! to race the API call against Ctrl+C
// This allows immediate cancellation, not just between tool calls
let mut user_interrupted = false;
// API call with Ctrl+C interrupt support
let response = tokio::select! {
biased; // Check ctrl_c first for faster response
_ = tokio::signal::ctrl_c() => {
user_interrupted = true;
Err::<String, String>("User cancelled".to_string())
}
result = async {
match session.provider {
ProviderType::OpenAI => {
// Use Responses API (default) for reasoning model support.
// rig-core 0.28+ handles Reasoning items properly in multi-turn.
let client = openai::Client::from_env();
let mut builder = client
.agent(&session.model)
.preamble(&preamble)
.max_tokens(4096)
.tool(AnalyzeTool::new(project_path_buf.clone()))
.tool(SecurityScanTool::new(project_path_buf.clone()))
.tool(VulnerabilitiesTool::new(project_path_buf.clone()))
.tool(HadolintTool::new(project_path_buf.clone()))
.tool(DclintTool::new(project_path_buf.clone()))
.tool(KubelintTool::new(project_path_buf.clone()))
.tool(K8sOptimizeTool::new(project_path_buf.clone()))
.tool(K8sCostsTool::new(project_path_buf.clone()))
.tool(K8sDriftTool::new(project_path_buf.clone()))
.tool(HelmlintTool::new(project_path_buf.clone()))
.tool(TerraformFmtTool::new(project_path_buf.clone()))
.tool(TerraformValidateTool::new(project_path_buf.clone()))
.tool(TerraformInstallTool::new())
.tool(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()))
.tool(WebFetchTool::new())
// Prometheus discovery and connection tools for live K8s analysis
.tool(PrometheusDiscoverTool::new())
.tool(PrometheusConnectTool::new(bg_manager.clone()))
// RAG retrieval tools for compressed tool outputs
.tool(RetrieveOutputTool::new())
.tool(ListOutputsTool::new())
// Platform tools for project management
.tool(ListOrganizationsTool::new())
.tool(ListProjectsTool::new())
.tool(SelectProjectTool::new())
.tool(CurrentContextTool::new())
.tool(OpenProviderSettingsTool::new())
.tool(CheckProviderConnectionTool::new())
.tool(ListDeploymentCapabilitiesTool::new())
// Deployment tools for service management
.tool(CreateDeploymentConfigTool::new())
.tool(DeployServiceTool::new(project_path_buf.clone()))
.tool(ListDeploymentConfigsTool::new())
.tool(TriggerDeploymentTool::new())
.tool(GetDeploymentStatusTool::new())
.tool(ListDeploymentsTool::new())
.tool(GetServiceLogsTool::new());
// Add tools based on mode
if is_planning {
// Plan mode: read-only shell + plan creation tools
builder = builder
.tool(ShellTool::new(project_path_buf.clone()).with_read_only(true))
.tool(PlanCreateTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()));
} else if is_generation {
// Standard mode + generation query: all tools including file writes and plan execution
let (mut write_file_tool, mut write_files_tool) =
if let Some(ref client) = ide_client {
(
WriteFileTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
WriteFilesTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
)
} else {
(
WriteFileTool::new(project_path_buf.clone()),
WriteFilesTool::new(project_path_buf.clone()),
)
};
// Disable confirmations if auto-accept mode is enabled (from plan menu)
if auto_accept_writes {
write_file_tool = write_file_tool.without_confirmation();
write_files_tool = write_files_tool.without_confirmation();
}
builder = builder
.tool(write_file_tool)
.tool(write_files_tool)
.tool(ShellTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()))
.tool(PlanNextTool::new(project_path_buf.clone()))
.tool(PlanUpdateTool::new(project_path_buf.clone()));
}
// Enable reasoning for OpenAI reasoning models (GPT-5.x, O1, O3, O4)
let model_lower = session.model.to_lowercase();
let is_reasoning_model = model_lower.starts_with("gpt-5")
|| model_lower.starts_with("gpt5")
|| model_lower.starts_with("o1")
|| model_lower.starts_with("o3")
|| model_lower.starts_with("o4");
let agent = if is_reasoning_model {
let reasoning_params = serde_json::json!({
"reasoning": {
"effort": "medium",
"summary": "detailed"
}
});
builder.additional_params(reasoning_params).build()
} else {
builder.build()
};
// Use multi_turn with Responses API
agent
.prompt(¤t_input)
.with_history(&mut raw_chat_history)
.with_hook(hook.clone())
.multi_turn(50)
.await
}
ProviderType::Anthropic => {
let client = anthropic::Client::from_env();
// TODO: Extended thinking for Claude is disabled because rig-bedrock/rig-anthropic
// don't properly handle thinking blocks in multi-turn conversations with tool use.
// When thinking is enabled, ALL assistant messages must start with thinking blocks
// BEFORE tool_use blocks, but rig doesn't preserve/replay these.
// See: forge/crates/forge_services/src/provider/bedrock/provider.rs for reference impl.
let mut builder = client
.agent(&session.model)
.preamble(&preamble)
.max_tokens(4096)
.tool(AnalyzeTool::new(project_path_buf.clone()))
.tool(SecurityScanTool::new(project_path_buf.clone()))
.tool(VulnerabilitiesTool::new(project_path_buf.clone()))
.tool(HadolintTool::new(project_path_buf.clone()))
.tool(DclintTool::new(project_path_buf.clone()))
.tool(KubelintTool::new(project_path_buf.clone()))
.tool(K8sOptimizeTool::new(project_path_buf.clone()))
.tool(K8sCostsTool::new(project_path_buf.clone()))
.tool(K8sDriftTool::new(project_path_buf.clone()))
.tool(HelmlintTool::new(project_path_buf.clone()))
.tool(TerraformFmtTool::new(project_path_buf.clone()))
.tool(TerraformValidateTool::new(project_path_buf.clone()))
.tool(TerraformInstallTool::new())
.tool(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()))
.tool(WebFetchTool::new())
// Prometheus discovery and connection tools for live K8s analysis
.tool(PrometheusDiscoverTool::new())
.tool(PrometheusConnectTool::new(bg_manager.clone()))
// RAG retrieval tools for compressed tool outputs
.tool(RetrieveOutputTool::new())
.tool(ListOutputsTool::new())
// Platform tools for project management
.tool(ListOrganizationsTool::new())
.tool(ListProjectsTool::new())
.tool(SelectProjectTool::new())
.tool(CurrentContextTool::new())
.tool(OpenProviderSettingsTool::new())
.tool(CheckProviderConnectionTool::new())
.tool(ListDeploymentCapabilitiesTool::new())
// Deployment tools for service management
.tool(CreateDeploymentConfigTool::new())
.tool(DeployServiceTool::new(project_path_buf.clone()))
.tool(ListDeploymentConfigsTool::new())
.tool(TriggerDeploymentTool::new())
.tool(GetDeploymentStatusTool::new())
.tool(ListDeploymentsTool::new())
.tool(GetServiceLogsTool::new());
// Add tools based on mode
if is_planning {
// Plan mode: read-only shell + plan creation tools
builder = builder
.tool(ShellTool::new(project_path_buf.clone()).with_read_only(true))
.tool(PlanCreateTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()));
} else if is_generation {
// Standard mode + generation query: all tools including file writes and plan execution
let (mut write_file_tool, mut write_files_tool) =
if let Some(ref client) = ide_client {
(
WriteFileTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
WriteFilesTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
)
} else {
(
WriteFileTool::new(project_path_buf.clone()),
WriteFilesTool::new(project_path_buf.clone()),
)
};
// Disable confirmations if auto-accept mode is enabled (from plan menu)
if auto_accept_writes {
write_file_tool = write_file_tool.without_confirmation();
write_files_tool = write_files_tool.without_confirmation();
}
builder = builder
.tool(write_file_tool)
.tool(write_files_tool)
.tool(ShellTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()))
.tool(PlanNextTool::new(project_path_buf.clone()))
.tool(PlanUpdateTool::new(project_path_buf.clone()));
}
let agent = builder.build();
// Allow up to 50 tool call turns for complex generation tasks
// Use hook to display tool calls as they happen
// Pass conversation history for context continuity
agent
.prompt(¤t_input)
.with_history(&mut raw_chat_history)
.with_hook(hook.clone())
.multi_turn(50)
.await
}
ProviderType::Bedrock => {
// Bedrock provider via rig-bedrock - same pattern as OpenAI/Anthropic
let client = crate::bedrock::client::Client::from_env();
// Extended thinking for Claude models via Bedrock
// This enables Claude to show its reasoning process before responding.
// Requires vendored rig-bedrock that preserves Reasoning blocks with tool calls.
// Extended thinking budget - reduced to help with rate limits
// 8000 is enough for most tasks, increase to 16000 for complex analysis
let thinking_params = serde_json::json!({
"thinking": {
"type": "enabled",
"budget_tokens": 8000
}
});
let mut builder = client
.agent(&session.model)
.preamble(&preamble)
.max_tokens(64000) // Max output tokens for Claude Sonnet on Bedrock
.tool(AnalyzeTool::new(project_path_buf.clone()))
.tool(SecurityScanTool::new(project_path_buf.clone()))
.tool(VulnerabilitiesTool::new(project_path_buf.clone()))
.tool(HadolintTool::new(project_path_buf.clone()))
.tool(DclintTool::new(project_path_buf.clone()))
.tool(KubelintTool::new(project_path_buf.clone()))
.tool(K8sOptimizeTool::new(project_path_buf.clone()))
.tool(K8sCostsTool::new(project_path_buf.clone()))
.tool(K8sDriftTool::new(project_path_buf.clone()))
.tool(HelmlintTool::new(project_path_buf.clone()))
.tool(TerraformFmtTool::new(project_path_buf.clone()))
.tool(TerraformValidateTool::new(project_path_buf.clone()))
.tool(TerraformInstallTool::new())
.tool(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()))
.tool(WebFetchTool::new())
// Prometheus discovery and connection tools for live K8s analysis
.tool(PrometheusDiscoverTool::new())
.tool(PrometheusConnectTool::new(bg_manager.clone()))
// RAG retrieval tools for compressed tool outputs
.tool(RetrieveOutputTool::new())
.tool(ListOutputsTool::new())
// Platform tools for project management
.tool(ListOrganizationsTool::new())
.tool(ListProjectsTool::new())
.tool(SelectProjectTool::new())
.tool(CurrentContextTool::new())
.tool(OpenProviderSettingsTool::new())
.tool(CheckProviderConnectionTool::new())
.tool(ListDeploymentCapabilitiesTool::new())
// Deployment tools for service management
.tool(CreateDeploymentConfigTool::new())
.tool(DeployServiceTool::new(project_path_buf.clone()))
.tool(ListDeploymentConfigsTool::new())
.tool(TriggerDeploymentTool::new())
.tool(GetDeploymentStatusTool::new())
.tool(ListDeploymentsTool::new())
.tool(GetServiceLogsTool::new());
// Add tools based on mode
if is_planning {
// Plan mode: read-only shell + plan creation tools
builder = builder
.tool(ShellTool::new(project_path_buf.clone()).with_read_only(true))
.tool(PlanCreateTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()));
} else if is_generation {
// Standard mode + generation query: all tools including file writes and plan execution
let (mut write_file_tool, mut write_files_tool) =
if let Some(ref client) = ide_client {
(
WriteFileTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
WriteFilesTool::new(project_path_buf.clone())
.with_ide_client(client.clone()),
)
} else {
(
WriteFileTool::new(project_path_buf.clone()),
WriteFilesTool::new(project_path_buf.clone()),
)
};
// Disable confirmations if auto-accept mode is enabled (from plan menu)
if auto_accept_writes {
write_file_tool = write_file_tool.without_confirmation();
write_files_tool = write_files_tool.without_confirmation();
}
builder = builder
.tool(write_file_tool)
.tool(write_files_tool)
.tool(ShellTool::new(project_path_buf.clone()))
.tool(PlanListTool::new(project_path_buf.clone()))
.tool(PlanNextTool::new(project_path_buf.clone()))
.tool(PlanUpdateTool::new(project_path_buf.clone()));
}
// Add thinking params for extended reasoning
builder = builder.additional_params(thinking_params);
let agent = builder.build();
// Use same multi-turn pattern as OpenAI/Anthropic
agent
.prompt(¤t_input)
.with_history(&mut raw_chat_history)
.with_hook(hook.clone())
.multi_turn(50)
.await
}
}.map_err(|e| e.to_string())
} => result
};
// Stop the progress indicator before handling the response
progress.stop().await;
// Suppress unused variable warnings
let _ = (&progress_state, user_interrupted);
match response {
Ok(text) => {
// Show final response
println!();
ResponseFormatter::print_response(&text);
// Track token usage - use actual from hook if available, else estimate
let hook_usage = hook.get_usage().await;
if hook_usage.has_data() {
// Use actual token counts from API response
session
.token_usage
.add_actual(hook_usage.input_tokens, hook_usage.output_tokens);
} else {
// Fall back to estimation when API doesn't provide usage
let prompt_tokens = TokenUsage::estimate_tokens(&input);
let completion_tokens = TokenUsage::estimate_tokens(&text);
session
.token_usage
.add_estimated(prompt_tokens, completion_tokens);
}
// Reset hook usage for next request batch
hook.reset_usage().await;
// Show context indicator like Forge: [model/~tokens]
let model_short = session
.model
.split('/')
.next_back()
.unwrap_or(&session.model)
.split(':')
.next()
.unwrap_or(&session.model);
println!();
println!(
" {}[{}/{}]{}",
ui::colors::ansi::DIM,
model_short,
session.token_usage.format_compact(),
ui::colors::ansi::RESET
);
// Extract tool calls from the hook state for history tracking
let tool_calls = extract_tool_calls_from_hook(&hook).await;
let batch_tool_count = tool_calls.len();
total_tool_calls += batch_tool_count;
// Show tool call summary if significant
if batch_tool_count > 10 {
println!(
"{}",
format!(
" ✓ Completed with {} tool calls ({} total this session)",
batch_tool_count, total_tool_calls
)
.dimmed()
);
}
// Add to conversation history with tool call records
conversation_history.add_turn(input.clone(), text.clone(), tool_calls.clone());
// Check if this heavy turn requires immediate compaction
// This helps prevent context overflow in subsequent requests
if conversation_history.needs_compaction() {
println!("{}", " 📦 Compacting conversation history...".dimmed());
if let Some(summary) = conversation_history.compact() {
println!(
"{}",
format!(" ✓ Compressed {} turns", summary.matches("Turn").count())
.dimmed()
);
}
}
// Simplify history for OpenAI Responses API reasoning models
// Keep only User text and Assistant text - strip reasoning, tool calls, tool results
// This prevents pairing errors like "rs_... without its required following item"
// and "fc_... without its required reasoning item"
if session.provider == ProviderType::OpenAI {
simplify_history_for_openai_reasoning(&mut raw_chat_history);
}
// Also update legacy session history for compatibility
session.history.push(("user".to_string(), input.clone()));
session
.history
.push(("assistant".to_string(), text.clone()));
// Record to persistent session storage (includes full history snapshot)
session_recorder.record_user_message(&input);
session_recorder.record_assistant_message(&text, Some(&tool_calls));
if let Err(e) = session_recorder.save_with_history(&conversation_history) {
eprintln!(
"{}",
format!(" Warning: Failed to save session: {}", e).dimmed()
);
}
// Check if plan_create was called - show interactive menu
if let Some(plan_info) = find_plan_create_call(&tool_calls) {
println!(); // Space before menu
// Show the plan action menu (don't switch modes yet - let user choose)
match ui::show_plan_action_menu(&plan_info.0, plan_info.1) {
ui::PlanActionResult::ExecuteAutoAccept => {
// Now switch to standard mode for execution
if session.plan_mode.is_planning() {
session.plan_mode = session.plan_mode.toggle();
}