-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmod.rs
More file actions
842 lines (745 loc) · 36.9 KB
/
Copy pathmod.rs
File metadata and controls
842 lines (745 loc) · 36.9 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
//! 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 history;
pub mod ide;
pub mod prompts;
pub mod session;
pub mod tools;
pub mod ui;
use colored::Colorize;
use history::{ConversationHistory, ToolCallRecord};
use ide::IdeClient;
use rig::{
client::{CompletionClient, ProviderClient},
completion::Prompt,
providers::{anthropic, openai},
};
use session::ChatSession;
use commands::TokenUsage;
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,
}
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"),
}
}
}
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),
_ => Err(format!("Unknown provider: {}", 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
fn get_system_prompt(project_path: &Path, query: Option<&str>) -> String {
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);
}
}
// 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);
// 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();
loop {
// Show conversation status if we have history
if !conversation_history.is_empty() {
println!("{}", format!(" 💬 Context: {}", conversation_history.status()).dimmed());
}
// Read user input
let input = match session.read_input() {
Ok(input) => input,
Err(_) => break,
};
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();
}
match session.process_command(&input) {
Ok(true) => 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());
}
}
// 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!("{}", format!(" 📡 Sending continuation request...").dimmed());
}
// Create hook for Claude Code style tool display
let hook = ToolDisplayHook::new();
let project_path_buf = session.project_path.clone();
// Select prompt based on query type (analysis vs generation)
let preamble = get_system_prompt(&session.project_path, Some(¤t_input));
let is_generation = prompts::is_generation_query(¤t_input);
// Convert conversation history to Rig Message format
let mut chat_history = conversation_history.to_messages();
let response = match session.provider {
ProviderType::OpenAI => {
let client = openai::Client::from_env();
// For GPT-5.x reasoning models, enable reasoning with summary output
// so we can see the model's thinking process
let reasoning_params = if session.model.starts_with("gpt-5") || session.model.starts_with("o1") {
Some(serde_json::json!({
"reasoning": {
"effort": "medium",
"summary": "detailed"
}
}))
} else {
None
};
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(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()));
// Add generation tools if this is a generation query
if is_generation {
// Create file tools with IDE client if connected
let (write_file_tool, 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()),
)
};
builder = builder
.tool(write_file_tool)
.tool(write_files_tool)
.tool(ShellTool::new(project_path_buf.clone()));
}
if let Some(params) = reasoning_params {
builder = builder.additional_params(params);
}
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 chat_history)
.with_hook(hook.clone())
.multi_turn(50)
.await
}
ProviderType::Anthropic => {
let client = anthropic::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(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()));
// Add generation tools if this is a generation query
if is_generation {
// Create file tools with IDE client if connected
let (write_file_tool, 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()),
)
};
builder = builder
.tool(write_file_tool)
.tool(write_files_tool)
.tool(ShellTool::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 chat_history)
.with_hook(hook.clone())
.multi_turn(50)
.await
}
};
match response {
Ok(text) => {
// Show final response
println!();
ResponseFormatter::print_response(&text);
// Track token usage (estimate since Rig doesn't expose exact counts)
let prompt_tokens = TokenUsage::estimate_tokens(&input);
let completion_tokens = TokenUsage::estimate_tokens(&text);
session.token_usage.add_request(prompt_tokens, completion_tokens);
// 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);
// 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());
}
}
// Also update legacy session history for compatibility
session.history.push(("user".to_string(), input.clone()));
session.history.push(("assistant".to_string(), text));
succeeded = true;
}
Err(e) => {
let err_str = e.to_string();
println!();
// Check if this is a max depth error - handle as checkpoint
if err_str.contains("MaxDepth") || err_str.contains("max_depth") || err_str.contains("reached limit") {
// Extract what was done before hitting the limit
let completed_tools = extract_tool_calls_from_hook(&hook).await;
let agent_thinking = extract_agent_messages_from_hook(&hook).await;
let batch_tool_count = completed_tools.len();
total_tool_calls += batch_tool_count;
eprintln!("{}", format!(
"⚠ Reached {} tool calls this batch ({} total). Maximum allowed: {}",
batch_tool_count, total_tool_calls, MAX_TOOL_CALLS
).yellow());
// Check if we've hit the absolute maximum
if total_tool_calls >= MAX_TOOL_CALLS {
eprintln!("{}", format!("Maximum tool call limit ({}) reached.", MAX_TOOL_CALLS).red());
eprintln!("{}", "The task is too complex. Try breaking it into smaller parts.".dimmed());
break;
}
// Ask user if they want to continue (unless auto-continue is enabled)
let should_continue = if auto_continue_tools {
eprintln!("{}", " Auto-continuing (you selected 'always')...".dimmed());
true
} else {
eprintln!("{}", "Excessive tool calls used. Want to continue?".yellow());
eprintln!("{}", " [y] Yes, continue [n] No, stop [a] Always continue".dimmed());
print!(" > ");
let _ = std::io::Write::flush(&mut std::io::stdout());
// Read user input
let mut response = String::new();
match std::io::stdin().read_line(&mut response) {
Ok(_) => {
let resp = response.trim().to_lowercase();
if resp == "a" || resp == "always" {
auto_continue_tools = true;
true
} else {
resp == "y" || resp == "yes" || resp.is_empty()
}
}
Err(_) => false,
}
};
if !should_continue {
eprintln!("{}", "Stopped by user. Type 'continue' to resume later.".dimmed());
// Add partial progress to history
if !completed_tools.is_empty() {
conversation_history.add_turn(
current_input.clone(),
format!("[Stopped at checkpoint - {} tools completed]", batch_tool_count),
vec![]
);
}
break;
}
// Continue from checkpoint
eprintln!("{}", format!(
" → Continuing... {} remaining tool calls available",
MAX_TOOL_CALLS - total_tool_calls
).dimmed());
// Add partial progress to history (without duplicating tool calls)
conversation_history.add_turn(
current_input.clone(),
format!("[Checkpoint - {} tools completed, continuing...]", batch_tool_count),
vec![]
);
// Build continuation prompt
current_input = build_continuation_prompt(&input, &completed_tools, &agent_thinking);
// Brief delay before continuation
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
continue; // Continue the loop without incrementing retry_attempt
} else if err_str.contains("rate") || err_str.contains("Rate") || err_str.contains("429") {
eprintln!("{}", "⚠ Rate limited by API provider.".yellow());
// Wait before retry for rate limits
retry_attempt += 1;
eprintln!("{}", format!(" Waiting 5 seconds before retry ({}/{})...", retry_attempt, MAX_RETRIES).dimmed());
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
} else if is_truncation_error(&err_str) {
// Truncation error - try intelligent continuation
let completed_tools = extract_tool_calls_from_hook(&hook).await;
let agent_thinking = extract_agent_messages_from_hook(&hook).await;
// Count actually completed tools (not in-progress)
let completed_count = completed_tools.iter()
.filter(|t| !t.result_summary.contains("IN PROGRESS"))
.count();
let in_progress_count = completed_tools.len() - completed_count;
if !completed_tools.is_empty() && continuation_count < MAX_CONTINUATIONS {
// We have partial progress - continue from where we left off
continuation_count += 1;
let status_msg = if in_progress_count > 0 {
format!(
"⚠ Response truncated. {} completed, {} in-progress. Auto-continuing ({}/{})...",
completed_count, in_progress_count, continuation_count, MAX_CONTINUATIONS
)
} else {
format!(
"⚠ Response truncated. {} tool calls completed. Auto-continuing ({}/{})...",
completed_count, continuation_count, MAX_CONTINUATIONS
)
};
eprintln!("{}", status_msg.yellow());
// Add partial progress to conversation history
// NOTE: We intentionally pass empty tool_calls here because the
// continuation prompt already contains the detailed file list.
// Including them in history would duplicate the context and waste tokens.
conversation_history.add_turn(
current_input.clone(),
format!("[Partial response - {} tools completed, {} in-progress before truncation. See continuation prompt for details.]",
completed_count, in_progress_count),
vec![] // Don't duplicate - continuation prompt has the details
);
// Check if we need compaction after adding this heavy turn
// This is important for long multi-turn sessions with many tool calls
if conversation_history.needs_compaction() {
eprintln!("{}", " 📦 Compacting history before continuation...".dimmed());
if let Some(summary) = conversation_history.compact() {
eprintln!("{}", format!(" ✓ Compressed {} turns", summary.matches("Turn").count()).dimmed());
}
}
// Build continuation prompt with context
current_input = build_continuation_prompt(&input, &completed_tools, &agent_thinking);
// Log continuation details for debugging
eprintln!("{}", format!(
" → Continuing with {} files read, {} written, {} other actions tracked",
completed_tools.iter().filter(|t| t.tool_name == "read_file").count(),
completed_tools.iter().filter(|t| t.tool_name == "write_file" || t.tool_name == "write_files").count(),
completed_tools.iter().filter(|t| t.tool_name != "read_file" && t.tool_name != "write_file" && t.tool_name != "write_files" && t.tool_name != "list_directory").count()
).dimmed());
// Brief delay before continuation
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
// Don't increment retry_attempt - this is progress via continuation
} else if retry_attempt < MAX_RETRIES {
// No tool calls completed - simple retry
retry_attempt += 1;
eprintln!("{}", format!("⚠ Response error (attempt {}/{}). Retrying...", retry_attempt, MAX_RETRIES).yellow());
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
} else {
// Max retries/continuations reached
eprintln!("{}", format!("Error: {}", e).red());
if continuation_count >= MAX_CONTINUATIONS {
eprintln!("{}", format!("Max continuations ({}) reached. The task is too complex for one request.", MAX_CONTINUATIONS).dimmed());
} else {
eprintln!("{}", "Max retries reached. The response may be too complex.".dimmed());
}
eprintln!("{}", "Try breaking your request into smaller parts.".dimmed());
break;
}
} else if err_str.contains("timeout") || err_str.contains("Timeout") {
// Timeout - simple retry
retry_attempt += 1;
if retry_attempt < MAX_RETRIES {
eprintln!("{}", format!("⚠ Request timed out (attempt {}/{}). Retrying...", retry_attempt, MAX_RETRIES).yellow());
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
} else {
eprintln!("{}", "Request timed out. Please try again.".red());
break;
}
} else {
// Unknown error - show details and break
eprintln!("{}", format!("Error: {}", e).red());
if continuation_count > 0 {
eprintln!("{}", format!(" (occurred during continuation attempt {})", continuation_count).dimmed());
}
eprintln!("{}", "Error details for debugging:".dimmed());
eprintln!("{}", format!(" - retry_attempt: {}/{}", retry_attempt, MAX_RETRIES).dimmed());
eprintln!("{}", format!(" - continuation_count: {}/{}", continuation_count, MAX_CONTINUATIONS).dimmed());
break;
}
}
}
}
println!();
}
Ok(())
}
/// Extract tool call records from the hook state for history tracking
async fn extract_tool_calls_from_hook(hook: &ToolDisplayHook) -> Vec<ToolCallRecord> {
let state = hook.state();
let guard = state.lock().await;
guard.tool_calls.iter().enumerate().map(|(i, tc)| {
let result = if tc.is_running {
// Tool was in progress when error occurred
"[IN PROGRESS - may need to be re-run]".to_string()
} else if let Some(output) = &tc.output {
truncate_string(output, 200)
} else {
"completed".to_string()
};
ToolCallRecord {
tool_name: tc.name.clone(),
args_summary: truncate_string(&tc.args, 100),
result_summary: result,
// Generate a unique tool ID for proper message pairing
tool_id: Some(format!("tool_{}_{}", tc.name, i)),
}
}).collect()
}
/// Extract any agent thinking/messages from the hook for context
async fn extract_agent_messages_from_hook(hook: &ToolDisplayHook) -> Vec<String> {
let state = hook.state();
let guard = state.lock().await;
guard.agent_messages.clone()
}
/// Helper to truncate strings for summaries
fn truncate_string(s: &str, max_len: usize) -> String {
if s.len() <= max_len {
s.to_string()
} else {
format!("{}...", &s[..max_len.saturating_sub(3)])
}
}
/// Check if an error is a truncation/JSON parsing error that can be recovered via continuation
fn is_truncation_error(err_str: &str) -> bool {
err_str.contains("JsonError")
|| err_str.contains("EOF while parsing")
|| err_str.contains("JSON")
|| err_str.contains("unexpected end")
}
/// Build a continuation prompt that tells the AI what work was completed
/// and asks it to continue from where it left off
fn build_continuation_prompt(
original_task: &str,
completed_tools: &[ToolCallRecord],
agent_thinking: &[String],
) -> String {
use std::collections::HashSet;
// Group tools by type and extract unique files read
let mut files_read: HashSet<String> = HashSet::new();
let mut files_written: HashSet<String> = HashSet::new();
let mut dirs_listed: HashSet<String> = HashSet::new();
let mut other_tools: Vec<String> = Vec::new();
let mut in_progress: Vec<String> = Vec::new();
for tool in completed_tools {
let is_in_progress = tool.result_summary.contains("IN PROGRESS");
if is_in_progress {
in_progress.push(format!("{}({})", tool.tool_name, tool.args_summary));
continue;
}
match tool.tool_name.as_str() {
"read_file" => {
// Extract path from args
files_read.insert(tool.args_summary.clone());
}
"write_file" | "write_files" => {
files_written.insert(tool.args_summary.clone());
}
"list_directory" => {
dirs_listed.insert(tool.args_summary.clone());
}
_ => {
other_tools.push(format!("{}({})", tool.tool_name, truncate_string(&tool.args_summary, 40)));
}
}
}
let mut prompt = format!(
"[CONTINUE] Your previous response was interrupted. DO NOT repeat completed work.\n\n\
Original task: {}\n",
truncate_string(original_task, 500)
);
// Show files already read - CRITICAL for preventing re-reads
if !files_read.is_empty() {
prompt.push_str("\n== FILES ALREADY READ (do NOT read again) ==\n");
for file in &files_read {
prompt.push_str(&format!(" - {}\n", file));
}
}
if !dirs_listed.is_empty() {
prompt.push_str("\n== DIRECTORIES ALREADY LISTED ==\n");
for dir in &dirs_listed {
prompt.push_str(&format!(" - {}\n", dir));
}
}
if !files_written.is_empty() {
prompt.push_str("\n== FILES ALREADY WRITTEN ==\n");
for file in &files_written {
prompt.push_str(&format!(" - {}\n", file));
}
}
if !other_tools.is_empty() {
prompt.push_str("\n== OTHER COMPLETED ACTIONS ==\n");
for tool in other_tools.iter().take(20) {
prompt.push_str(&format!(" - {}\n", tool));
}
if other_tools.len() > 20 {
prompt.push_str(&format!(" ... and {} more\n", other_tools.len() - 20));
}
}
if !in_progress.is_empty() {
prompt.push_str("\n== INTERRUPTED (may need re-run) ==\n");
for tool in &in_progress {
prompt.push_str(&format!(" ⚠ {}\n", tool));
}
}
// Include last thinking context if available
if !agent_thinking.is_empty() {
if let Some(last_thought) = agent_thinking.last() {
prompt.push_str(&format!(
"\n== YOUR LAST THOUGHTS ==\n\"{}\"\n",
truncate_string(last_thought, 300)
));
}
}
prompt.push_str("\n== INSTRUCTIONS ==\n");
prompt.push_str("IMPORTANT: Your previous response was too long and got cut off.\n");
prompt.push_str("1. Do NOT re-read files listed above - they are already in context.\n");
prompt.push_str("2. If writing a document, write it in SECTIONS - complete one section now, then continue.\n");
prompt.push_str("3. Keep your response SHORT and focused. Better to complete small chunks than fail on large ones.\n");
prompt.push_str("4. If the task involves writing a file, START WRITING NOW - don't explain what you'll do.\n");
prompt
}
/// Run a single query and return the response
pub async fn run_query(
project_path: &Path,
query: &str,
provider: ProviderType,
model: Option<String>,
) -> AgentResult<String> {
use tools::*;
let project_path_buf = project_path.to_path_buf();
// Select prompt based on query type (analysis vs generation)
let preamble = get_system_prompt(project_path, Some(query));
let is_generation = prompts::is_generation_query(query);
match provider {
ProviderType::OpenAI => {
let client = openai::Client::from_env();
let model_name = model.as_deref().unwrap_or("gpt-5.2");
// For GPT-5.x reasoning models, enable reasoning with summary output
let reasoning_params = if model_name.starts_with("gpt-5") || model_name.starts_with("o1") {
Some(serde_json::json!({
"reasoning": {
"effort": "medium",
"summary": "detailed"
}
}))
} else {
None
};
let mut builder = client
.agent(model_name)
.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(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()));
// Add generation tools if this is a generation query
if is_generation {
builder = builder
.tool(WriteFileTool::new(project_path_buf.clone()))
.tool(WriteFilesTool::new(project_path_buf.clone()))
.tool(ShellTool::new(project_path_buf.clone()));
}
if let Some(params) = reasoning_params {
builder = builder.additional_params(params);
}
let agent = builder.build();
agent
.prompt(query)
.multi_turn(50)
.await
.map_err(|e| AgentError::ProviderError(e.to_string()))
}
ProviderType::Anthropic => {
let client = anthropic::Client::from_env();
let model_name = model.as_deref().unwrap_or("claude-sonnet-4-20250514");
let mut builder = client
.agent(model_name)
.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(ReadFileTool::new(project_path_buf.clone()))
.tool(ListDirectoryTool::new(project_path_buf.clone()));
// Add generation tools if this is a generation query
if is_generation {
builder = builder
.tool(WriteFileTool::new(project_path_buf.clone()))
.tool(WriteFilesTool::new(project_path_buf.clone()))
.tool(ShellTool::new(project_path_buf.clone()));
}
let agent = builder.build();
agent
.prompt(query)
.multi_turn(50)
.await
.map_err(|e| AgentError::ProviderError(e.to_string()))
}
}
}